{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \n\t\n}\n\neverything.each do | it |\n\t# everyone needs a place to stay\n\tes = /(\\w*\\/?\\w*\\/?\\w*\\/?)\\w+/\n\tputs it\n\ta_home = it.match(es)\n\tFileUtils.mkdir_p 'docs/'+remember+'/'+a_home.to_s#tay\n\n\tfond = File.open(it)\n\tform = fond.read\n\trest = Kramdown::Document.new(form).to_html\n\tfinally = ERB.new(fashion).result(binding)\n\ttil = it.sub! '.md', '.html'\n\ttil = remember + '/' + til\n\tFile.write('docs/'+til, finally)\n\tfond.close\nend\n\n# i need to find all the years\n# and then all the months\n# and then all the\nall = Hash.new\ntraces = []\nexpress = /(\\d+)-(\\d+)-(\\d+)-(\\d+)\\/(.*\\.html)/\n\nfiles = Dir.glob(\"docs/**/**\").sort_by { |f| File.mtime(f) }\nchaos = files.reverse\n\nchaos.each do | bit |\n\tdeconstruct = bit.match(express)\n\n\tif deconstruct\n\t\tyear = deconstruct[1]\n\t\tif !all.has_key? year\n\t\t\tall[year] = Hash.new # we create a new array to store all the months, only if that doesn't exist already\n\t\tend\n\n\t\tmonth = deconstruct[2]\n\t\tif !all[year].has_key? month\n\t\t\tall[year][month] = Hash.new\n\t\tend\n\n\t\tday = deconstruct[3]\n\t\tif !all[year][month].has_key? day\n\t\t\tall[year][month][day] = Hash.new\n\t\tend\n\n\t\ttime = deconstruct[4]\n\t\tif !all[year][month][day].has_key? time\n\t\t\tall[year][month][day][time] = Array.new\n\t\tend\n\n\t\tall[year][month][day][time] << deconstruct[5]\n\tend\nend\n\nputs \"they need to be together\"\nspace = %{\n\t\n\t\n\t\t\n\t\t\t\n\t\t\tthe role of aesthetics in source code understandings\n\t\t\n\t\t\n\t\t\t\n\t\t\t
\n\t\t\t\t

the role of aesthetics in the understandings of source code

\n\t\t\t\t

what you see here is the automatic rendering of all the notes taken during my phd thesis. since it is a thesis on source code, might as well show its own source code.

\n\t\t\t\t

the main question i'm asking is: how do aesthetics enable understanding in source code, what kind of understanding(s) might derive from their presence, or absence, and how does this highlight code as textual matter? this touches upon issues of style, clarity, epistemology, psychology, programming and literature.

\n\t\t\t\t

this doctoral work is being done at the university of sorbonne nouvelle, under the joint direction of alexandre gefen (Paris-3, CNRS) and nick montfort (MIT Comparative Media Studies).

\n

you can start with the most recent summary, the current state of the final manuscript or the whole github repository.

\n\t\t\t\t
\n\t\t\t\t<% all.each_key do | year | %>\n\t\t\t\t\t<% all[year].each_key do | month | %>\n\t\t\t\t\t\t<% all[year][month].each_key do | day | %>\n\t\t\t\t\t\t\t

<%= year %> - <%= month %> - <%= day %>

\n\t\t\t\t\t\t\t<% all[year][month][day].each_key do | time | %>\n\t\t\t\t\t\t\t\t

<%= time %>

\n\t\t\t\t\t\t\t\t<% all[year][month][day][time].each do | trace | %>\n\t\t\t\t\t\t\t\t\t
  • \"><%= trace %>
  • \n\t\t\t\t\t\t\t\t<% end %>\n\t\t\t\t\t\t\t<% end %>\n\t\t\t\t\t\t<% end %>\n\t\t\t\t\t<% end %>\n\t\t\t\t<% end %>\n\t\t\t
    \n\t\t\n\t\n}\n\npublic = ERB.new(space).result(binding)\nFile.write(\"docs/index.html\", public)\n\nputs \"then\"\nputs \"it's done, for now\"\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2973958,"cells":{"blob_id":{"kind":"string","value":"f852cd437f7b59240838a8ce91e97d8fc5a1e791"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"jjuarez/jabber_notifier"},"path":{"kind":"string","value":"/lib/jabber_notifier/cli.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":416,"string":"416"},"score":{"kind":"number","value":2.53125,"string":"2.53125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"require 'yaml'\nrequire 'jabber_notifier/options_parser'\nrequire 'jabber_notifier/connection'\n\n\nmodule JabberNotifier\n\n class Cli\n\n def self.run(options)\n\n config = YAML.load_file(options[:config])\n connection = Connection.new(:username =>config[\"username\"], :password =>config[\"password\"], :delay =>options[:delay].to_f)\n\n connection.notify(options[:to], options[:message])\n end\n end\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2973959,"cells":{"blob_id":{"kind":"string","value":"7ad402efc4cbc26cdaddb36171d21e1b3f83bfbe"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"BlueMeadow/L3"},"path":{"kind":"string","value":"/S6/PROJET/Hanjie-master/Generation/Picture.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2259,"string":"2,259"},"score":{"kind":"number","value":3.359375,"string":"3.359375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"require 'rmagick'\ninclude Magick\n\nclass Magick::Pixel\n\tdef isBlack?()\n\t\t(self.green + self.red + self.blue) / 3 < (QuantumRange / 2)\n\tend\nend\n\nclass Picture\n\n\t@origine\t\t\t# Contient l'image original\n\t@indicesH \t\t\t# Groupe d'indices de colonne (array[array])\n\t@indicesV \t\t\t# Groupe d'indices de ligne (array[array])\n\t@precision \t\t\t# Precision souhaité (variation de couleur)\n\t@dimension \t\t\t# Dimension souhaité (5x5, 10x10, 15x15)\n\n\tprivate_class_method :new\n\tattr_reader :precision\n\n\tdef Picture.creer(imageName,dimension)\n\t\tnew(imageName,dimension)\n\tend\n\n\tdef initialize(imageName,dimension)\n\t\t@origine = Image.read(imageName).first.resize_to_fill(dimension,dimension)\n\t\t@indicesH = []\n\t\t@indicesV = []\n\t\t@precision = 1\n\t\t@dimension = dimension\n\tend\n\n\tdef getIndicesH(i)\n\t\treturn @indicesH[i]\n\tend\n\n\tdef getIndicesV(i)\n\t\treturn @indicesV[i]\n\tend\n\n\tdef toBoolean\n\t\t# image --> [true,true,false,true]\t\t\t\t\ttrue = blanc\n\t\t#\t\t\t[false,true,false,false]\t\t\t\tfalse = noir\n\t\t# \t\t\t[true,true,true,true]\n\n\t\tgrid = []\n\t\timage = toGrey(@precision)\n\t\timage.each_pixel{|pixel| grid << !pixel.isBlack?}\n\t\tgrid.each_slice(image.columns).to_a\n\tend\n\n\tdef calcIndice\n\t\t# [true,true,false,true]\t\t\t\t[2,1]\n\t\t# [false,true,false,false]\t\t--> \t[1]\n\t\t# [true,true,true,false,true]\t\t\t[3,1]\n\n\t\tgrid = self.toBoolean\n\t\t@indicesH = groupeIndicesGrid(grid)\n\t\t@indicesV = groupeIndicesGrid(grid.transpose)\n\t\treturn grid\n\tend\n\n\tdef to_s\n\t\ttoBoolean.map{|ligne| ligne.map{|pix| pix ? \"+\":\" \"}.join}.join(\"\\n\")\n\tend\n\n\tdef printIndice\n\t\tafficherIndices(@indicesH)\n\t\tprint \"\\n\\n\"\n\t\tafficherIndices(@indicesV)\n\tend\n\n\t# PRIVATE CLASS\n\n\tprivate\n\tdef toGrey(precision)\n\t\t@origine.quantize(256,GRAYColorspace).edge(precision)\n\tend\n\n\tdef groupeIndicesLigne(ligne)\n\t\tindices = []\n\t\ti = 0\n\t\tligne.each_with_index{|etat,index|\n\t\t\tif etat then\n\t\t\t\ti += 1\n\t\t\tend\n\n\t\t\tif (index == ligne.length-1 || !etat) && (i !=0) then\n\t\t\t\tindices << i\n\t\t\t\ti = 0\n\t\t\tend\n\t\t}\n\t\treturn indices\n\tend\n\n\tdef groupeIndicesGrid(grid)\n\t\tindices = []\n\t\tgrid.each{|ligne| indices << groupeIndicesLigne(ligne)}\n\t\treturn indices\n\tend\n\n\tdef afficherIndices(grid)\n\t\ti = 1\n\t\tgrid.each{|g|\n\t\t\tprint i,\" : \", g, \"\\n\"\n\t\t\ti += 1\n\t\t}\n\tend\n\nend\n\n# i = Picture.creer(\"apple.bmp\",10);\n# puts i\n# i.calcIndice\n# i.printIndice\n#p i.getIndicesV(0)\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2973960,"cells":{"blob_id":{"kind":"string","value":"b486346a10cd4ec53db5f1f40c885e8e9c962aa6"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"b-dalton/04_ruby_tutorial"},"path":{"kind":"string","value":"/strings_arrays_time/time.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":462,"string":"462"},"score":{"kind":"number","value":3.34375,"string":"3.34375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"require 'date'\n# s = String.new(\"A man, a plan, a canal—Panama!\")\n\n# t = s.split(\", \")\n# p t\n\n# a = Array.new\n# a << 3 << 4\n# puts a\n\n# now = Time.now\n# puts now\n\nmoon_landing = Time.new(1969, 7, 20, 20, 17, 40)\n# puts moon_landing.day\n\n# puts now - moon_landing\n\n# DAYNAMES = Date::DAYNAMES\n# DAYNAMES = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"]\n# puts DAYNAMES[moon_landing.wday]\n# puts DAYNAMES[Time.now.wday]\n\nputs now\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2973961,"cells":{"blob_id":{"kind":"string","value":"6e64453d405288e6a5863bca64506cb5cf9d5a20"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"JimMcL/sampleIt"},"path":{"kind":"string","value":"/lib/view_angle.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":4169,"string":"4,169"},"score":{"kind":"number","value":3.40625,"string":"3.40625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"# Class for working with view angles of photos of specimens.\n# The angle is specified by latitude (phi) and longitude (lambda). Photos\n# are assumed to be directed towards the centre of the specimen, with\n# the top of the specimen facing up or else the front of the specimen\n# facing towards the left. Longitude (lamba) is 0 at the middle of the\n# face. Units are (integral) degrees.\n\n# Hence, an anterior (frontal) view is (0, 0), a lateral view (taken from the\n# specimen's left side) is (0, 90), and a dorsal view is (90, 0).\n#\n# See also http://insects.oeb.harvard.edu/etypes/specificimages.htm\nclass ViewAngle\n include Comparable\n attr_accessor :phi, :lambda\n\n NAMED_ANGLES = {lateral: [0, 90],\n dorsal: [90, 0],\n ventral: [-90, 0],\n anterior: [0, 0],\n posterior: [0, 180],\n lateral_right_side: [0, -90]\n }\n SYNONYMS = {frontal: [0, 0],\n face: [0, 0],\n underside: [-90, 0]}\n\n # Returns the list of named angles\n def self.angle_names\n NAMED_ANGLES.keys\n end\n\n # If params contains a parameter such as {view_angle: 'lateral'}, removes it and\n # adds {view_phi: 0, view_lambda: 90}\n def self.expand_query_params(params)\n if params.key?(:view_angle) && (va = ViewAngle.new(params[:view_angle])) && va.valid?\n params = params.merge(view_phi: va.phi, view_lambda: va.lambda)\n end\n params.except(:view_angle)\n end\n\n # Creates a ViewAngle.\n # Takes either a view name (a symbol or string), phi and lambda, or a name and relative phi and lambda.\n # \n # Examples:\n # ViewAngle.new(:lateral) # Taken from left side\n # ViewAngle.new(0, 90) # Same as :lateral\n # ViewAngle.new('0, 90') # Same as :lateral\n # ViewAngle(:dorsal) # Taken from above, head towards the left (by convention)\n # ViewAngle(:dorsal, -5, 90) # Taken from above by 5 degrees towards dorsal\n def initialize(phi_or_name, lambda_or_relative_phi = 0, relative_lambda = 0)\n if phi_or_name.is_a?(Numeric) && lambda_or_relative_phi.is_a?(Numeric)\n @phi = phi_or_name\n @lambda = lambda_or_relative_phi\n elsif !phi_or_name.blank?\n # Check for 2 angles in a string\n phi_or_name = phi_or_name.to_s\n if (m = phi_or_name.scan(/[+-]?\\d+/)) && m.length == 2\n @phi = m[0].to_i\n @lambda = m[1].to_i\n else\n # Check for name of an angle\n key = phi_or_name.parameterize(separator: '_').intern\n na = NAMED_ANGLES[key]\n na = SYNONYMS[key] if na.blank?\n raise ArgumentError, \"Invalid named view angle '#{phi_or_name}', require one of [#{NAMED_ANGLES.keys.join(', ')}]\" if na.blank?\n @phi = na[0]\n @lambda = na[1]\n\n # Add relative angle if specified\n if lambda_or_relative_phi.is_a?(Numeric) && relative_lambda.is_a?(Numeric)\n @phi += lambda_or_relative_phi\n @lambda += relative_lambda\n end\n end\n end\n end\n\n def valid?\n !@phi.nil? && !@lambda.nil? && @phi >= -90 && @phi <= 90 && @lambda >= -180 && @lambda <= 180\n end\n\n def to_s\n valid? ? (name && name.humanize || \"#{@phi}, #{@lambda}\") : ''\n end\n\n def inspect\n \"ViewAngle(phi: #{@phi}, lambda: #{@lambda}, name: #{name})\"\n end\n\n def description\n valid? ? \"#{to_s.humanize} view\" : ''\n end\n \n def name\n nm = false\n NAMED_ANGLES.each do |key, value|\n nm = key.to_s if value[0] == @phi && value[1] == @lambda\n end\n nm\n end\n\n def hash\n [phi, lambda].hash\n end\n\n def eql?(other)\n self == other || (other.is_a?(ViewAngle) && phi == other.phi && lambda == other.lambda)\n end \n\n # Define a somewhat arbitrary ordering, based on how photos should appear\n def <=>(other)\n if other.is_a? ViewAngle\n nm1 = name\n nm2 = other.name\n # Named angles come first\n return -1 if nm1 && !nm2\n return 1 if !nm1 && nm2\n # String comparison if neither is named\n return to_s <=> other.to_s if !nm1\n # Named angles use the order defined in NAMED_ANGLES\n idx1 = NAMED_ANGLES.keys.index(nm1.to_sym)\n idx2 = NAMED_ANGLES.keys.index(nm2.to_sym)\n idx1 <=> idx2\n end\n end\n \nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2973962,"cells":{"blob_id":{"kind":"string","value":"76e73f4aa830046a84748d275fcbeb31df7e4855"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"johnantoni/plugin.tweakify"},"path":{"kind":"string","value":"/lib/common/active_record.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":339,"string":"339"},"score":{"kind":"number","value":2.578125,"string":"2.578125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"class ActiveRecord::Base\n def self.to_a_simplify\n # takes table object and breaks it down into a simple array\n return self.to_enum.map {|e| e::id }\n end\n\n def self.simply_paginate(id)\n # converts table into array, then finds prev/next/current & returns as hash\n return self.to_a_simplify.simply_paginate_array(id)\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2973963,"cells":{"blob_id":{"kind":"string","value":"5ba3b8edfc283490351aad1e5899ca4d7b61cc85"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"JEG2/ender"},"path":{"kind":"string","value":"/test/tc_config.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":864,"string":"864"},"score":{"kind":"number","value":2.71875,"string":"2.71875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"#!/usr/bin/env ruby -wKU\n\nrequire \"test/unit\"\nrequire \"tempfile\"\n\nrequire \"config\"\n\nclass TestConfig < Test::Unit::TestCase\n def test_config_returns_a_customized_ostruct\n assert_instance_of(OpenStruct, config)\n end\n \n def test_config_object_is_passed_into_the_file_and_used_to_set_options\n c = config(<<-END_SETTINGS)\n config.string_setting = \"just a String\"\n config.integer_setting = 41\n END_SETTINGS\n assert_equal(\"just a String\", c.string_setting)\n assert_equal(41, c.integer_setting)\n end\n \n def test_exceptions_bubble_up_to_the_caller\n assert_raise(RuntimeError) do\n config(<<-END_ERROR)\n raise \"Oops!\"\n END_ERROR\n end\n end\n \n private\n \n def config(content = String.new)\n cf = Tempfile.new(\"ender_config_test\")\n cf << content\n cf.flush\n Config.load_config_file(cf.path)\n end\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2973964,"cells":{"blob_id":{"kind":"string","value":"094afe2138299494f6f6b683d8471a870e21360b"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"rayleyva/ArangoDB"},"path":{"kind":"string","value":"/3rdParty/mruby/mrblib/struct.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":854,"string":"854"},"score":{"kind":"number","value":3.46875,"string":"3.46875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["Apache-2.0","MIT"],"string":"[\n \"Apache-2.0\",\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"##\n# Struct\n#\n# ISO 15.2.18\nclass Struct\n\n ##\n # Calls the given block for each element of +self+\n # and pass the respective element.\n #\n # ISO 15.2.18.4.4\n def each(&block)\n self.class.members.each{|field|\n block.call(self[field])\n }\n self\n end\n\n ##\n # Calls the given block for each element of +self+\n # and pass the name and value of the respectiev\n # element.\n #\n # ISO 15.2.18.4.5\n def each_pair(&block)\n self.class.members.each{|field|\n block.call(field.to_sym, self[field])\n }\n self\n end\n\n ##\n # Calls the given block for each element of +self+\n # and returns an array with all elements of which\n # block is not false.\n #\n # ISO 15.2.18.4.7\n def select(&block)\n ary = []\n self.class.members.each{|field|\n val = self[field]\n ary.push(val) if block.call(val)\n }\n ary\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2973965,"cells":{"blob_id":{"kind":"string","value":"c249e8b59fccbe7b0efd0be155e1daef95a11585"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"jparbros/leaderboard"},"path":{"kind":"string","value":"/app/models/concerns/input_filters.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2821,"string":"2,821"},"score":{"kind":"number","value":2.53125,"string":"2.53125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"module InputFilters\n\n def self.included(base)\n base.extend(ClassMethods)\n end\n\n module ClassMethods\n def search(params)\n inputs = self.includes(:user, :departament)\n inputs = inputs.by_user(params[:user_id]) if params[:user_id]\n inputs = inputs.by_today if params[:period] == 'today'\n inputs = inputs.by_week if params[:period] == 'week'\n inputs = inputs.by_month if params[:period] == 'month'\n inputs = inputs.by_quarter if params[:period] == 'quarter'\n inputs = inputs.by_year if params[:period] == 'year'\n inputs = inputs.by_departament(params[:departament_id]) if params[:departament_id]\n inputs = inputs.group_by_user if params[:group_by_user]\n inputs = inputs.paginate(page: params[:page], per_page: 20) if params[:page]\n inputs = inputs.get_ordered(params) if params[:order]\n inputs\n end\n\n def by_today\n where(date: Date.today)\n end\n\n def by_week\n where('date >= ? and date <= ?', Date.today.at_beginning_of_week, Date.today.at_end_of_week)\n end\n\n def by_month\n where('date >= ? and date <= ?', Date.today.beginning_of_month, Date.today.end_of_month)\n end\n\n def by_quarter\n where('date >= ? and date <= ?', Date.today.beginning_of_quarter, Date.today.end_of_quarter)\n end\n\n def by_year\n where('date >= ? and date <= ?', Date.today.beginning_of_year, Date.today.end_of_year)\n end\n\n def by_user user_id\n where(user_id: user_id)\n end\n\n def by_departament(departament_id)\n if departament_id == 'all_teams'\n joins(:departament)\n else\n joins(:departament).where(departaments: {id: departament_id})\n end\n end\n\n def group_by_user\n all.group_by {|input| input.user_id}.values.map do |values|\n user = values.first.user\n {realized: values.map(&:value).inject(0, &:+).round(2), username: user.name, picture: user.avatar.url(:medium), target: user.target}\n end.sort {|x,y| y[:realized] <=> x[:realized]}.take(5)\n end\n\n def get_leader\n all.max\n end\n\n def get_ordered(params)\n inputs = order_by_name(params[:order_direction]) if params[:order] == 'name'\n inputs = order_by_date(params[:order_direction]) if params[:order] == 'date'\n inputs = order_by_value(params[:order_direction]) if params[:order] == 'value'\n inputs = order_by_team(params[:order_direction]) if params[:order] == 'team'\n inputs\n end\n\n def order_by_name(direction = 'DESC')\n order(\"users.name #{direction}\")\n end\n\n def order_by_date(direction = 'DESC')\n order(\"inputs.date #{direction}\")\n end\n\n def order_by_value(direction = 'DESC')\n order(\"inputs.value #{direction}\")\n end\n\n def order_by_team(direction = 'DESC')\n order(\"departaments.name #{direction}\")\n end\n\n end\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2973966,"cells":{"blob_id":{"kind":"string","value":"5c18ab4b04705437902dc4b522af2e90632ba8fb"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"szib/oo-relationships-practice-london-web-career-040119"},"path":{"kind":"string","value":"/app/models/IMDB/Movie.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":132,"string":"132"},"score":{"kind":"number","value":2.5625,"string":"2.5625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"require_relative './VisualProduct'\n\nclass Movie < VisualProduct\n def self.most_actors\n all.max_by(&:number_of_actors)\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2973967,"cells":{"blob_id":{"kind":"string","value":"145fddeecb88889417783957828b40222f2bd4d3"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"itsolutionscorp/AutoStyle-Clustering"},"path":{"kind":"string","value":"/all_data/exercism_data/ruby/bob/2ea7d59f423b4a75b8d2db7c8b796d70.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":774,"string":"774"},"score":{"kind":"number","value":3.953125,"string":"3.953125"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"#!/usr/bin/env ruby\n\nclass Bob\n\n @@responses = { \n question: \"Sure.\",\n silence: \"Fine. Be that way!\",\n yelling: \"Woah, chill out!\",\n default: \"Whatever.\"\n }\n\n def hey(phrase)\n result = :default\n case\n when silence?(phrase)\n result = :silence\n when yelling?(phrase)\n result = :yelling\n when question?(phrase)\n result = :question\n end\n @@responses[result]\n end\n\n private\n\n def yelling?(phrase)\n if phrase.strip.empty?\n False\n else\n phrase.eql? phrase.upcase\n end\n end\n\n def question?(phrase)\n phrase.end_with? \"?\"\n end\n\n def silence?(phrase)\n phrase.strip.empty?\n end\n\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2973968,"cells":{"blob_id":{"kind":"string","value":"bd2c4e21ed88d79a8d95472c1c85de159e66813b"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"vgelinski/home_sinatra"},"path":{"kind":"string","value":"/src/model/user.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":687,"string":"687"},"score":{"kind":"number","value":2.796875,"string":"2.796875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"require 'data_mapper'\nrequire 'digest/sha1'\n\nclass User\n\n include DataMapper::Resource\n\n property :id, Serial\n property :name, String\n property :password, String\n property :salt, String\n\n def User.create(params)\n params[:salt] = (0..8).map{(33 + rand(92)).chr}.join\n plain_pass = params[:password]\n params[:password] = Digest::SHA1.hexdigest plain_pass + params[:salt]\n super(params)\n end\n\n def initialize(params)\n attribute_set :name, params[:name]\n attribute_set :password, params[:password]\n attribute_set :salt, params[:salt]\n end\n\n def check(m_name, m_password)\n name == m_name && (Digest::SHA1.hexdigest(m_password + salt) == password)\n end\n\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2973969,"cells":{"blob_id":{"kind":"string","value":"41b829cd54c3e872096b4dd560351c1f6d9b1032"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"Jylia/xyz"},"path":{"kind":"string","value":"/xyz.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":255,"string":"255"},"score":{"kind":"number","value":3.484375,"string":"3.484375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"def mult(x,y,z)\r\n if (x < y) ? \r\n if ((y < z) || (x < z)) ? \r\n a = [y, z] : a = [y, x]\r\n end \r\n :\r\n if ((x < z) || (y < z))?\r\n a = [x, z] : a = [y, x]\r\n end\r\n end\r\n return a[0]*a[0] + a[1]*a[1] \r\nend\r\n\r\nputs mult(-10, -9 ,-22)\r\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2973970,"cells":{"blob_id":{"kind":"string","value":"66f979f8c23ed9f71e0bf491762f564ea05f67e1"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"alansparrow/learningruby"},"path":{"kind":"string","value":"/benchmarkexample2.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":236,"string":"236"},"score":{"kind":"number","value":2.8125,"string":"2.8125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"require 'benchmark'\niterations = 1000000\n\nBenchmark.bmbm do |bmbm|\n bmbm.report(\"for:\") do\n for i in 1..iterations do\n x = i\n end\n end\n \n bmbm.report(\"times:\") do\n iterations.times do |i|\n x = i\n end\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2973971,"cells":{"blob_id":{"kind":"string","value":"71a162184d00779ea2e21462ef19492c3a7aa618"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"npatel007/Computer-Science-Notes"},"path":{"kind":"string","value":"/Ruby/RubyLect9.progs/RubyLect9.14.progs/closure.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2534,"string":"2,534"},"score":{"kind":"number","value":2.78125,"string":"2.78125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"#!/opt/local/bin/ruby2.0 -w\n# CLOSURE\n# Copyright Mark Keane, All Rights Reserved, 2011\n\narr1 = [\"john\", \"jim\",\"mary\", \"james\"]\narr2 = [\"A\", \"B\",\"C\", \"D\"]\n\ndef assign_marks(people, marks, time1 = 0, procs = [])\n\tpeople.each do |person|\n\t\ttime2 = 0\n\t\tmarks.each do |mark|\n\t\tfn = lambda {p [person, mark, time1, time2]}\n\t\tprocs << fn\n\t\tfn.call; time1 += 1; time2 += 1\n\t\tif (time1 == 10 || time2 == 4)\n\t\tthen puts \"Encountered an error at 10/4 seconds, going back to start\" \n\t\t\t procs.first.call end\n\t end\n\tend\n procs\nend\n\nfns = assign_marks(arr1, arr2)\np fns\nfns.each {|clos| clos.call}\n\n\n=begin\ndhcp-892b3c12:RubyWeek8.progs mkeane$ !!\nruby closure.rb\n[\"john\", \"A\", 0, 0]\n[\"john\", \"B\", 1, 1]\n[\"john\", \"C\", 2, 2]\n[\"john\", \"D\", 3, 3]\nEncountered an error at 10/4 seconds, going back to start\n[\"john\", \"A\", 4, 4]\n[\"jim\", \"A\", 4, 0]\n[\"jim\", \"B\", 5, 1]\n[\"jim\", \"C\", 6, 2]\n[\"jim\", \"D\", 7, 3]\nEncountered an error at 10/4 seconds, going back to start\n[\"john\", \"A\", 8, 4]\n[\"mary\", \"A\", 8, 0]\n[\"mary\", \"B\", 9, 1]\nEncountered an error at 10/4 seconds, going back to start\n[\"john\", \"A\", 10, 4]\n[\"mary\", \"C\", 10, 2]\n[\"mary\", \"D\", 11, 3]\nEncountered an error at 10/4 seconds, going back to start\n[\"john\", \"A\", 12, 4]\n[\"james\", \"A\", 12, 0]\n[\"james\", \"B\", 13, 1]\n[\"james\", \"C\", 14, 2]\n[\"james\", \"D\", 15, 3]\nEncountered an error at 10/4 seconds, going back to start\n[\"john\", \"A\", 16, 4]\n[#, #, #, #, #, #, #, #, #, #, #, #, #, #, #, #]\n[\"john\", \"A\", 16, 4]\n[\"john\", \"B\", 16, 4]\n[\"john\", \"C\", 16, 4]\n[\"john\", \"D\", 16, 4]\n[\"jim\", \"A\", 16, 4]\n[\"jim\", \"B\", 16, 4]\n[\"jim\", \"C\", 16, 4]\n[\"jim\", \"D\", 16, 4]\n[\"mary\", \"A\", 16, 4]\n[\"mary\", \"B\", 16, 4]\n[\"mary\", \"C\", 16, 4]\n[\"mary\", \"D\", 16, 4]\n[\"james\", \"A\", 16, 4]\n[\"james\", \"B\", 16, 4]\n[\"james\", \"C\", 16, 4]\n[\"james\", \"D\", 16, 4]\ndhcp-892b3c12:RubyWeek8.progs mkeane$ \n=end"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2973972,"cells":{"blob_id":{"kind":"string","value":"f11a357e083cf04a3f6889b5e77568d3aa3325f5"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"parrot-studio/rdgc-dm"},"path":{"kind":"string","value":"/lib/rdgc/maker/divide_temp_block.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":7099,"string":"7,099"},"score":{"kind":"number","value":2.609375,"string":"2.609375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT","LicenseRef-scancode-unknown-license-reference"],"string":"[\n \"MIT\",\n \"LicenseRef-scancode-unknown-license-reference\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"# coding: UTF-8\r\nmodule RDGC\r\n module Maker\r\n class DivideTempBlock < TempBlock\r\n\r\n attr_accessor :divide_direction\r\n attr_writer :depth, :min_size\r\n\r\n def depth\r\n @depth ||= 0\r\n @depth\r\n end\r\n\r\n def min_size\r\n @min_size = Util::Config.min_block_size if @min_size.to_i < Util::Config.min_block_size\r\n @min_size\r\n end\r\n\r\n def min_divide_size\r\n min_size * 2\r\n end\r\n\r\n def opposite_direction\r\n case self.divide_direction\r\n when :horizontal\r\n :vertical\r\n when :vertical\r\n :horizontal\r\n else\r\n nil\r\n end\r\n end\r\n\r\n def dividable_size?\r\n case self.divide_direction\r\n when :horizontal\r\n height >= min_divide_size ? true : false\r\n when :vertical\r\n width >= min_divide_size ? true : false\r\n else\r\n false\r\n end\r\n end\r\n\r\n def dividable(f = true)\r\n @dividable = f\r\n end\r\n\r\n def dividable?\r\n @dividable\r\n end\r\n\r\n def set_dividable\r\n return unless dividable_size?\r\n dividable\r\n end\r\n\r\n def divide_point(val)\r\n range_rand(min_size, val - min_divide_size)\r\n end\r\n\r\n def divide\r\n self.divide_direction ||= select_rand({:horizontal => 1, :vertical => 1})\r\n return unless dividable_size?\r\n\r\n case self.divide_direction\r\n when :horizontal\r\n divide_horizontal\r\n when :vertical\r\n divide_vertical\r\n end\r\n end\r\n\r\n def divide_horizontal\r\n return unless dividable_size?\r\n\r\n # 分割幅決定\r\n point = divide_point(height)\r\n\r\n upper = DivideTempBlock.create(top, top + point - 1, left, right)\r\n lower = DivideTempBlock.create(top + point, bottom, left, right)\r\n\r\n set_next_value(upper, lower)\r\n [upper, lower].shuffle\r\n end\r\n\r\n def divide_vertical\r\n return unless dividable_size?\r\n\r\n # 分割点決定\r\n point = divide_point(width)\r\n\r\n lefter = DivideTempBlock.create(top, bottom, left, left + point - 1)\r\n righter = DivideTempBlock.create(top, bottom, left + point, right)\r\n\r\n set_next_value(lefter, righter)\r\n [lefter, righter].shuffle\r\n end\r\n\r\n def set_next_value(b1, b2)\r\n [b1, b2].each do |b|\r\n b.depth = self.depth + 1\r\n b.divide_direction = opposite_direction\r\n b.min_size = min_size\r\n end\r\n\r\n if bool_rand\r\n b1.set_dividable\r\n b2.set_dividable if bool_rand\r\n else\r\n b2.set_dividable\r\n b1.set_dividable if bool_rand\r\n end\r\n end\r\n\r\n # for road ----------------------------------------------------\r\n\r\n def road_created(f = true)\r\n @road_created = f\r\n self\r\n end\r\n\r\n def road_created?\r\n @road_created\r\n end\r\n\r\n def set_road_point(direction, point)\r\n @road_point ||= {}\r\n @road_point[direction] = point\r\n end\r\n\r\n def road_point\r\n @road_point ||= {}\r\n @road_point\r\n end\r\n\r\n def remain_cling_blocks\r\n @remain_cling_blocks ||= []\r\n @remain_cling_blocks\r\n end\r\n\r\n def add_remain_cling_blocks(b)\r\n return if b.has_room?\r\n remain_cling_blocks << b\r\n end\r\n\r\n def has_remain_cling_blocks?\r\n remain_cling_blocks.empty? ? false : true\r\n end\r\n\r\n def dead_end?\r\n return false if has_room?\r\n return false unless has_cross_point?\r\n road_point.keys.size == 1 ? true : false\r\n end\r\n\r\n def remain_direction\r\n [:top, :bottom, :left, :right] - road_point.keys\r\n end\r\n\r\n def create_road_to(b)\r\n return unless (has_room? || has_cross_point?)\r\n return unless (b.has_room? || b.has_cross_point?)\r\n\r\n # 相手とどこで接しているか調べる\r\n # 接線に向かって道を伸ばす\r\n # 左か上に位置する部屋に接続線を引く\r\n case cling_direction_to(b)\r\n when :top\r\n my_x = create_road_for_direction(:top)\r\n b_x = b.create_road_for_direction(:bottom)\r\n b.create_road_for_adjoin_x(my_x, b_x)\r\n when :bottom\r\n my_x = create_road_for_direction(:bottom)\r\n b_x = b.create_road_for_direction(:top)\r\n create_road_for_adjoin_x(my_x, b_x)\r\n when :left\r\n my_y = create_road_for_direction(:left)\r\n b_y = b.create_road_for_direction(:right)\r\n b.create_road_for_adjoin_y(my_y, b_y)\r\n when :right\r\n my_y = create_road_for_direction(:right)\r\n b_y = b.create_road_for_direction(:left)\r\n create_road_for_adjoin_y(my_y, b_y)\r\n end\r\n end\r\n\r\n def create_road_for_direction(d)\r\n # 道を描くポイントを持っている(すでに道がある)ならそれを返す\r\n val = road_point[d]\r\n return val if val\r\n\r\n # 新しい道を描く\r\n case\r\n when has_room?\r\n val = create_road_from_room(d)\r\n when has_cross_point?\r\n val = create_road_from_point(d)\r\n end\r\n\r\n val\r\n end\r\n\r\n def create_road_from_room(d)\r\n return unless has_room?\r\n return if road_point[d]\r\n\r\n case d\r\n when :top\r\n x = range_rand(room.left, room.right)\r\n set_road_point(:top, x)\r\n add_road(Map::Road.create(top, room.top-1, x, x))\r\n x\r\n when :bottom\r\n x = range_rand(room.left, room.right)\r\n set_road_point(:bottom, x)\r\n add_road(Map::Road.create(room.bottom+1, bottom, x, x))\r\n x\r\n when :left\r\n y = range_rand(room.top, room.bottom)\r\n set_road_point(:left, y)\r\n add_road(Map::Road.create(y, y, left, room.left-1))\r\n y\r\n when :right\r\n y = range_rand(room.top, room.bottom)\r\n set_road_point(:right, y)\r\n add_road(Map::Road.create(y, y, room.right+1, right))\r\n y\r\n end\r\n end\r\n\r\n def create_road_from_point(d)\r\n return unless has_cross_point?\r\n return if road_point[d]\r\n\r\n x, y = cross_point\r\n case d\r\n when :top\r\n set_road_point(:top, x)\r\n add_road(Map::Road.create(top, y, x, x))\r\n x\r\n when :bottom\r\n set_road_point(:bottom, x)\r\n add_road(Map::Road.create(y, bottom, x, x))\r\n x\r\n when :left\r\n set_road_point(:left, y)\r\n add_road(Map::Road.create(y, y, left, x))\r\n y\r\n when :right\r\n set_road_point(:right, y)\r\n add_road(Map::Road.create(y, y, x, right))\r\n y\r\n end\r\n end\r\n\r\n def create_road_for_adjoin_x(x1, x2)\r\n p_s, p_e = [x1, x2].sort\r\n add_road(Map::Road.create(bottom, bottom, p_s, p_e))\r\n end\r\n\r\n def create_road_for_adjoin_y(y1, y2)\r\n p_s, p_e = [y1, y2].sort\r\n add_road(Map::Road.create(p_s, p_e, right, right))\r\n end\r\n\r\n end\r\n end\r\nend\r\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2973973,"cells":{"blob_id":{"kind":"string","value":"803967a84198386138106048acacbd1a99502042"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"SuhaylTFaris/XASJS"},"path":{"kind":"string","value":"/XAS Tool HUD 0.1.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":23885,"string":"23,885"},"score":{"kind":"number","value":2.6875,"string":"2.6875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"#==============================================================================\r\n# ■ +++ MOG - XAS TOOL HUD (v1.0) +++\r\n#==============================================================================\r\n# By Moghunter\r\n# http://www.atelier-rgss.com\r\n#==============================================================================\r\n# Apresenta as huds usadas pelas ferramentas usadas no XAS , mais a hud da\r\n# quantidade de ouro.\r\n#===============================================================================\r\nmodule XAS_TOOL_HUD\r\n #Ativar a Hud de habilidades.\r\n ENABLE_SKILL_HUD = true\r\n #Ativar a Hud de Item.\r\n ENABLE_ITEM_HUD = true\r\n #Ativar a Hud de Armas.\r\n ENABLE_WEAPON_HUD = true\r\n #Ativar a Hud de Escudo.\r\n ENABLE_SHIELD_HUD = true\r\n #Ativar a Hud de Dinheiro(Gold).\r\n ENABLE_GOLD_HUD = true\r\n #Posição geral da hud de Item.\r\n ITEM_HUD = [220,365]\r\n #Posição geral da hud de Habilidades\r\n SKILL_HUD = [264,365]\r\n #Posição geral da hud de armas.\r\n WEAPON_HUD = [308,365]\r\n #Posição geral da hud de escudo.\r\n SHIELD_HUD = [352,365]\r\n #Posição geral da hud de dinheiro(Gold).\r\n GOLD_HUD = [430,395]\r\n #Posição do numero de dinheiro(Gold).\r\n GOLD_NUMBER = [40,1]\r\n #Posição do Layout.\r\n LAYOUT = [0,0]\r\n #Posição do Ícone.\r\n ICON = [5, 12]\r\n #Posição do numero.\r\n NUMBER = [18, 35]\r\n #Ajuste de espaço entre os numeros.\r\n NUMBER_SPACE = 0\r\nend\r\n\r\n#==============================================================================\r\n# ■ Tool Hud\r\n#==============================================================================\r\nclass Tool_Hud\r\n include XAS_TOOL_HUD\r\n \r\n #--------------------------------------------------------------------------\r\n # ● Initialize\r\n #-------------------------------------------------------------------------- \r\n def initialize\r\n @actor = $game_party.members[0]\r\n return if @actor == nil\r\n @icon_image = Cache.system(\"Iconset\")\r\n @number_image = Cache.system(\"XAS_Tool_Number\")\r\n @number_cw = @number_image.width / 10\r\n @number_ch = @number_image.height / 3 \r\n @number_sc = @number_cw + NUMBER_SPACE\r\n create_skill if ENABLE_SKILL_HUD\r\n create_item if ENABLE_ITEM_HUD\r\n create_weapon if ENABLE_WEAPON_HUD\r\n create_shield if ENABLE_SHIELD_HUD\r\n create_gold if ENABLE_GOLD_HUD\r\n end \r\n\r\n #--------------------------------------------------------------------------\r\n # ● Refresh\r\n #-------------------------------------------------------------------------- \r\n def refresh\r\n dispose \r\n initialize\r\n end \r\n \r\n #--------------------------------------------------------------------------\r\n # ● Create Gold\r\n #-------------------------------------------------------------------------- \r\n def create_gold\r\n @gold = $game_party.gold\r\n @gold_old = @gold\r\n @gold_ref = @gold_old\r\n @gold_refresh = false \r\n # Layout -------------------------------------------------------------------\r\n @gold_layout_sprite = Sprite.new\r\n @gold_layout_sprite.bitmap = Cache.system(\"XAS_Tool_Gold\")\r\n @gold_layout_sprite.z = 151\r\n @gold_layout_sprite.x = GOLD_HUD[0]\r\n @gold_layout_sprite.y = GOLD_HUD[1]\r\n # Gold ---------------------------------------------------------------------\r\n @gold_number_sprite = Sprite.new\r\n @gold_number_sprite.bitmap = Bitmap.new(@number_image.width, @number_image.height / 3)\r\n @gold_number_sprite.z = 152\r\n @gold_number_sprite.x = GOLD_HUD[0] + GOLD_NUMBER[0] \r\n @gold_number_sprite.y = GOLD_HUD[1] + GOLD_NUMBER[1] \r\n gold_number_update \r\n end\r\n \r\n #--------------------------------------------------------------------------\r\n # ● Create Shield\r\n #-------------------------------------------------------------------------- \r\n def create_shield\r\n #LAYOUT ------------------------------------------------------------\r\n @shield_layout_sprite = Sprite.new\r\n @shield_layout_sprite.bitmap = Cache.system(\"XAS_Tool_Shield\")\r\n @shield_layout_sprite.z = 150\r\n @shield_layout_sprite.x = SHIELD_HUD[0] + LAYOUT[0]\r\n @shield_layout_sprite.y = SHIELD_HUD[1] + LAYOUT[1] \r\n @shield = @actor.equips[1]\r\n @old_shield = @shield\r\n if @shield != nil\r\n icon_index = @shield.icon_index\r\n else \r\n icon_index = 0\r\n end \r\n @shield_icon_sprite = Sprite.new\r\n @shield_icon_sprite.bitmap = Bitmap.new(24,24)\r\n bitmap_shield_rect = Rect.new(icon_index % 16 * 24, icon_index / 16 * 24, 24, 24)\r\n @shield_icon_sprite.bitmap.blt(0, 0, @icon_image, bitmap_shield_rect)\r\n @shield_icon_sprite.z = 151\r\n @shield_icon_sprite.x = SHIELD_HUD[0] + ICON[0]\r\n @shield_icon_sprite.y = SHIELD_HUD[1] + ICON[1] \r\n #NUMBER ------------------------------------------------------------\r\n @shield_number_sprite = Sprite.new\r\n @shield_number_sprite.bitmap = Bitmap.new(@number_image.width, @number_image.height / 3)\r\n @shield_number_sprite.z = 152\r\n refresh_shield_number\r\n end \r\n \r\n #--------------------------------------------------------------------------\r\n # ● Refresh Shield Number\r\n #-------------------------------------------------------------------------- \r\n def refresh_shield_number\r\n @shield_number = 0\r\n @s_item = 0\r\n @shield_number_sprite.bitmap.clear\r\n return if @shield == nil\r\n if @shield.note =~ //\r\n action_id = $1.to_i \r\n skill = $data_skills[action_id]\r\n if skill != nil\r\n if skill.note =~ //\r\n item_id = $1.to_i \r\n if item_id != nil\r\n @s_item = $data_items[item_id]\r\n @shield_number = $game_party.item_number(@s_item) \r\n end\r\n end\r\n end \r\n end \r\n return if @s_item == 0\r\n cost_split = @shield_number.to_s.split(//)\r\n for r in 0..cost_split.size - 1 \r\n number_abs = cost_split[r].to_i \r\n src_rect = Rect.new(@number_cw * number_abs, 0, @number_cw, @number_ch)\r\n @shield_number_sprite.bitmap.blt(@number_sc * r, 0, @number_image, src_rect) \r\n end \r\n xf = ((cost_split.size * @number_sc) / 2)\r\n @shield_number_sprite.x = SHIELD_HUD[0] + NUMBER[0] - xf\r\n @shield_number_sprite.y = SHIELD_HUD[1] + NUMBER[1] \r\n end \r\n \r\n #--------------------------------------------------------------------------\r\n # ● Create Weapon\r\n #-------------------------------------------------------------------------- \r\n def create_weapon\r\n #LAYOUT ------------------------------------------------------------\r\n @weapon_layout_sprite = Sprite.new\r\n @weapon_layout_sprite.bitmap = Cache.system(\"XAS_Tool_Weapon\")\r\n @weapon_layout_sprite.z = 150\r\n @weapon_layout_sprite.x = WEAPON_HUD[0] + LAYOUT[0]\r\n @weapon_layout_sprite.y = WEAPON_HUD[1] + LAYOUT[1] \r\n #ICON\r\n @weapon = @actor.equips[0]\r\n @old_weapon = @weapon\r\n if @weapon != nil\r\n icon_index = @weapon.icon_index\r\n else \r\n icon_index = 0\r\n end \r\n @weapon_icon_sprite = Sprite.new\r\n @weapon_icon_sprite.bitmap = Bitmap.new(24,24)\r\n bitmap_weapon_rect = Rect.new(icon_index % 16 * 24, icon_index / 16 * 24, 24, 24)\r\n @weapon_icon_sprite.bitmap.blt(0, 0, @icon_image, bitmap_weapon_rect)\r\n @weapon_icon_sprite.z = 151\r\n @weapon_icon_sprite.x = WEAPON_HUD[0] + ICON[0]\r\n @weapon_icon_sprite.y = WEAPON_HUD[1] + ICON[1] \r\n #NUMBER ------------------------------------------------------------\r\n @weapon_number_sprite = Sprite.new\r\n @weapon_number_sprite.bitmap = Bitmap.new(@number_image.width, @number_image.height / 3)\r\n @weapon_number_sprite.z = 152\r\n refresh_weapon_number\r\n end\r\n\r\n #--------------------------------------------------------------------------\r\n # ● Refresh Weapon Number\r\n #-------------------------------------------------------------------------- \r\n def refresh_weapon_number\r\n @weapon_number = 0\r\n @w_item = 0\r\n @weapon_number_sprite.bitmap.clear\r\n return if @weapon == nil\r\n if @weapon.note =~ //\r\n action_id = $1.to_i \r\n skill = $data_skills[action_id]\r\n if skill != nil\r\n if skill.note =~ //\r\n item_id = $1.to_i \r\n if item_id != nil\r\n @w_item = $data_items[item_id]\r\n @weapon_number = $game_party.item_number(@w_item) \r\n end\r\n end\r\n end \r\n end \r\n return if @w_item == 0\r\n cost_split = @weapon_number.to_s.split(//)\r\n for r in 0..cost_split.size - 1 \r\n number_abs = cost_split[r].to_i \r\n src_rect = Rect.new(@number_cw * number_abs, 0, @number_cw, @number_ch)\r\n @weapon_number_sprite.bitmap.blt(@number_sc * r, 0, @number_image, src_rect) \r\n end \r\n xf = ((cost_split.size * @number_sc) / 2)\r\n @weapon_number_sprite.x = WEAPON_HUD[0] + NUMBER[0] - xf\r\n @weapon_number_sprite.y = WEAPON_HUD[1] + NUMBER[1] \r\n end \r\n \r\n #--------------------------------------------------------------------------\r\n # ● Create Skill\r\n #-------------------------------------------------------------------------- \r\n def create_skill\r\n #LAYOUT ------------------------------------------------------------\r\n @skill_layout_sprite = Sprite.new\r\n @skill_layout_sprite.bitmap = Cache.system(\"XAS_Tool_Skill\")\r\n @skill_layout_sprite.z = 150\r\n @skill_layout_sprite.x = SKILL_HUD[0] + LAYOUT[0]\r\n @skill_layout_sprite.y = SKILL_HUD[1] + LAYOUT[1]\r\n #ICON ------------------------------------------------------------\r\n @old_skill = @actor.skill_id\r\n @skill = $data_skills[@actor.skill_id]\r\n if @skill != nil\r\n icon_index = @skill.icon_index\r\n @skill_mp_cost = @skill.mp_cost\r\n else \r\n icon_index = 0\r\n @skill_mp_cost = 0\r\n end \r\n @skill_icon_sprite = Sprite.new\r\n @skill_icon_sprite.bitmap = Bitmap.new(24,24)\r\n bitmap_skill_rect = Rect.new(icon_index % 16 * 24, icon_index / 16 * 24, 24, 24)\r\n @skill_icon_sprite.bitmap.blt(0, 0, @icon_image, bitmap_skill_rect)\r\n @skill_icon_sprite.z = 151\r\n @skill_icon_sprite.x = SKILL_HUD[0] + ICON[0]\r\n @skill_icon_sprite.y = SKILL_HUD[1] + ICON[1] \r\n #NUMBER ------------------------------------------------------------\r\n skill_number_bitmap = Bitmap.new(@number_image.width, @number_image.height / 3)\r\n @skill_number_sprite = Sprite.new\r\n @skill_number_sprite.bitmap = skill_number_bitmap\r\n cost_split = @skill_mp_cost.to_s.split(//)\r\n for r in 0..cost_split.size - 1 \r\n number_abs = cost_split[r].to_i \r\n src_rect = Rect.new(@number_cw * number_abs, @number_ch, @number_cw, @number_ch)\r\n skill_number_bitmap.blt(@number_sc * r, 0, @number_image, src_rect) \r\n end \r\n @skill_number_sprite.z = 152\r\n xf = ((cost_split.size * @number_sc) / 2)\r\n @skill_number_sprite.x = SKILL_HUD[0] + NUMBER[0] - xf\r\n @skill_number_sprite.y = SKILL_HUD[1] + NUMBER[1] \r\n end\r\n \r\n #--------------------------------------------------------------------------\r\n # ● Create Item\r\n #-------------------------------------------------------------------------- \r\n def create_item\r\n #LAYOUT ------------------------------------------------------------\r\n @item_layout_sprite = Sprite.new\r\n @item_layout_sprite.bitmap = Cache.system(\"XAS_Tool_Item\")\r\n @item_layout_sprite.z = 150\r\n @item_layout_sprite.x = ITEM_HUD[0] + LAYOUT[0]\r\n @item_layout_sprite.y = ITEM_HUD[1] + LAYOUT[1]\r\n #ICON ------------------------------------------------------------\r\n @old_item = @actor.item_id\r\n @item = $data_items[@actor.item_id]\r\n if @item != nil\r\n icon_index = @item.icon_index\r\n @item_number = $game_party.item_number(@item)\r\n else \r\n icon_index = 0\r\n @item_number = 0\r\n end \r\n @item_icon_sprite = Sprite.new\r\n @item_icon_sprite.bitmap = Bitmap.new(24,24)\r\n bitmap_item_rect = Rect.new(icon_index % 16 * 24, icon_index / 16 * 24, 24, 24)\r\n @item_icon_sprite.bitmap.blt(0, 0, @icon_image, bitmap_item_rect)\r\n @item_icon_sprite.z = 160\r\n @item_icon_sprite.x = ITEM_HUD[0] + ICON[0]\r\n @item_icon_sprite.y = ITEM_HUD[1] + ICON[1] \r\n #NUMBER ------------------------------------------------------------\r\n item_number_bitmap = Bitmap.new(@number_image.width, @number_image.height / 3)\r\n @item_number_sprite = Sprite.new\r\n @item_number_sprite.bitmap = item_number_bitmap\r\n cost_split = @item_number.to_s.split(//)\r\n for r in 0..cost_split.size - 1 \r\n number_abs = cost_split[r].to_i \r\n src_rect = Rect.new(@number_cw * number_abs, 0, @number_cw, @number_ch)\r\n @item_number_sprite.bitmap.blt(@number_sc * r, 0, @number_image, src_rect) \r\n end \r\n @item_number_sprite.z = 152\r\n xf = ((cost_split.size * @number_sc) / 2)\r\n @item_number_sprite.x = ITEM_HUD[0] + NUMBER[0] - xf\r\n @item_number_sprite.y = ITEM_HUD[1] + NUMBER[1] \r\n end\r\n \r\n #--------------------------------------------------------------------------\r\n # ● Dispose\r\n #-------------------------------------------------------------------------- \r\n def dispose\r\n return if @actor == nil \r\n dispose_skill if ENABLE_SKILL_HUD\r\n dispose_item if ENABLE_ITEM_HUD\r\n dispose_weapon if ENABLE_WEAPON_HUD\r\n dispose_shield if ENABLE_SHIELD_HUD\r\n dispose_gold if ENABLE_GOLD_HUD\r\n @icon_image.dispose\r\n @number_image.dispose \r\n end\r\n \r\n #--------------------------------------------------------------------------\r\n # ● Dispose Skill\r\n #-------------------------------------------------------------------------- \r\n def dispose_skill\r\n @skill_layout_sprite.bitmap.dispose\r\n @skill_layout_sprite.dispose\r\n @skill_icon_sprite.bitmap.dispose\r\n @skill_icon_sprite.dispose\r\n @skill_number_sprite.bitmap.dispose\r\n @skill_number_sprite.dispose\r\n end\r\n \r\n #--------------------------------------------------------------------------\r\n # ● Dispose Gold\r\n #-------------------------------------------------------------------------- \r\n def dispose_gold\r\n @gold_layout_sprite.bitmap.dispose\r\n @gold_layout_sprite.dispose\r\n @gold_number_sprite.bitmap.dispose\r\n @gold_number_sprite.dispose\r\n end\r\n \r\n #--------------------------------------------------------------------------\r\n # ● Dispose Item\r\n #-------------------------------------------------------------------------- \r\n def dispose_item\r\n @item_layout_sprite.bitmap.dispose\r\n @item_layout_sprite.dispose \r\n @item_icon_sprite.bitmap.dispose\r\n @item_icon_sprite.dispose \r\n @item_number_sprite.bitmap.dispose\r\n @item_number_sprite.dispose \r\n end \r\n \r\n #--------------------------------------------------------------------------\r\n # ● Dispose Weapon\r\n #-------------------------------------------------------------------------- \r\n def dispose_weapon\r\n @weapon_layout_sprite.bitmap.dispose\r\n @weapon_layout_sprite.dispose\r\n @weapon_icon_sprite.bitmap.dispose\r\n @weapon_icon_sprite.dispose\r\n @weapon_number_sprite.bitmap.dispose\r\n @weapon_number_sprite.dispose \r\n end \r\n \r\n #--------------------------------------------------------------------------\r\n # ● Dispose shield\r\n #-------------------------------------------------------------------------- \r\n def dispose_shield\r\n @shield_layout_sprite.bitmap.dispose\r\n @shield_layout_sprite.dispose\r\n @shield_icon_sprite.bitmap.dispose\r\n @shield_icon_sprite.dispose\r\n @shield_number_sprite.bitmap.dispose\r\n @shield_number_sprite.dispose \r\n end \r\n \r\n #--------------------------------------------------------------------------\r\n # ● Update\r\n #-------------------------------------------------------------------------- \r\n def update\r\n return if @actor == nil \r\n update_visible\r\n refresh if can_refresh_hud?\r\n refresh_item if ENABLE_ITEM_HUD and can_refresh_item_number?\r\n refresh_weapon_number if ENABLE_WEAPON_HUD and can_refreh_weapon_number?\r\n refresh_shield_number if ENABLE_SHIELD_HUD and can_refreh_shield_number?\r\n update_gold if ENABLE_GOLD_HUD\r\n end\r\n \r\n #--------------------------------------------------------------------------\r\n # ● Update Gold\r\n #-------------------------------------------------------------------------- \r\n def update_gold \r\n gold_number_down if @gold > $game_party.gold \r\n gold_number_up if @gold < $game_party.gold \r\n gold_number_update if @gold_refresh \r\n end \r\n \r\n #--------------------------------------------------------------------------\r\n # ● Can Refresh Weapon Number\r\n #-------------------------------------------------------------------------- \r\n def can_refreh_weapon_number?\r\n return true if @weapon_number != $game_party.item_number(@w_item) \r\n return false\r\n end \r\n\r\n #--------------------------------------------------------------------------\r\n # ● Can Refresh Shield Number\r\n #-------------------------------------------------------------------------- \r\n def can_refreh_shield_number?\r\n return true if @shield_number != $game_party.item_number(@s_item) \r\n return false\r\n end \r\n \r\n #--------------------------------------------------------------------------\r\n # ● Update Visible\r\n #-------------------------------------------------------------------------- \r\n def update_visible\r\n vis = $game_system.enable_hud\r\n if ENABLE_SKILL_HUD\r\n @skill_layout_sprite.visible = vis\r\n @skill_icon_sprite.visible = vis\r\n @skill_number_sprite.visible = vis\r\n end\r\n if ENABLE_ITEM_HUD\r\n @item_layout_sprite.visible = vis\r\n @item_icon_sprite.visible = vis\r\n @item_number_sprite.visible = vis\r\n end\r\n if ENABLE_WEAPON_HUD \r\n @weapon_layout_sprite.visible = vis\r\n @weapon_icon_sprite.visible = vis\r\n @weapon_number_sprite.visible = vis\r\n end\r\n if ENABLE_SHIELD_HUD \r\n @shield_layout_sprite.visible = vis\r\n @shield_icon_sprite.visible = vis\r\n @shield_number_sprite.visible = vis \r\n end \r\n if ENABLE_GOLD_HUD \r\n @gold_layout_sprite.visible = vis\r\n @gold_number_sprite.visible = vis \r\n end \r\n end\r\n \r\n #--------------------------------------------------------------------------\r\n # ● Can Refresh Hud\r\n #-------------------------------------------------------------------------- \r\n def can_refresh_hud? \r\n if @actor != nil\r\n if ENABLE_SKILL_HUD\r\n return true if @old_skill != @actor.skill_id\r\n end\r\n if ENABLE_ITEM_HUD\r\n return true if @old_item != @actor.item_id\r\n end\r\n if ENABLE_WEAPON_HUD\r\n return true if @old_weapon != @actor.equips[0]\r\n end\r\n if ENABLE_SHIELD_HUD\r\n return true if @old_shield != @actor.equips[1]\r\n end \r\n end\r\n return false\r\n end \r\n \r\n #--------------------------------------------------------------------------\r\n # ● Can Refresh Item Number\r\n #-------------------------------------------------------------------------- \r\n def can_refresh_item_number?\r\n return true if @item_number != $game_party.item_number(@item) \r\n return false\r\n end \r\n \r\n #--------------------------------------------------------------------------\r\n # ● Create Item\r\n #-------------------------------------------------------------------------- \r\n def refresh_item\r\n @item_number = $game_party.item_number(@item) \r\n #Item Number ------------------------------------------------------------\r\n @item_number_sprite.bitmap.clear\r\n cost_split = @item_number.to_s.split(//)\r\n for r in 0..cost_split.size - 1 \r\n number_abs = cost_split[r].to_i \r\n src_rect = Rect.new(@number_cw * number_abs, 0, @number_cw, @number_ch)\r\n @item_number_sprite.bitmap.blt(@number_sc * r, 0, @number_image, src_rect) \r\n end \r\n xf = ((cost_split.size * @number_sc) / 2)\r\n @item_number_sprite.x = ITEM_HUD[0] + NUMBER[0] - xf\r\n end \r\n\r\n #--------------------------------------------------------------------------\r\n # ● gold_number_up\r\n #--------------------------------------------------------------------------\r\n def gold_number_up\r\n @gold_refresh = true\r\n @gold_ref = 20 * (@gold - @gold_old) / 100\r\n @gold_ref = 1 if @gold_ref < 1\r\n @gold += @gold_ref \r\n if @gold >= $game_party.gold\r\n @gold_old = $game_party.gold\r\n @gold = $game_party.gold\r\n @gold_ref = 0\r\n end \r\n end \r\n\r\n #--------------------------------------------------------------------------\r\n # ● gold_number_down\r\n #--------------------------------------------------------------------------\r\n def gold_number_down\r\n @gold_refresh = true\r\n @gold_ref = 10 * (@gold_old - @gold) / 100\r\n @gold_ref = 1 if @gold_ref < 1\r\n @gold -= @gold_ref \r\n if @gold <= $game_party.gold\r\n @gold_old = $game_party.gold\r\n @gold = $game_party.gold\r\n @gold_ref = 0\r\n end \r\n end\r\n \r\n #--------------------------------------------------------------------------\r\n # ● gold_number_update\r\n #--------------------------------------------------------------------------\r\n def gold_number_update \r\n @gold_number_sprite.bitmap.clear\r\n @gold_number_text = @gold.abs.to_s.split(//)\r\n for r in 0..@gold_number_text.size - 1\r\n @gold_number_abs = @gold_number_text[r].to_i \r\n gold_src_rect = Rect.new(@number_cw * @gold_number_abs, @number_ch * 2, @number_cw, @number_ch)\r\n @gold_number_sprite.bitmap.blt(@number_cw * r, 0, @number_image, gold_src_rect) \r\n end \r\n @gold_refresh = false if @gold == $game_party.gold \r\n end \r\n \r\nend\r\n\r\n#==============================================================================\r\n# ■ Spriteset_Map\r\n#==============================================================================\r\nclass Spriteset_Map\r\n \r\n #--------------------------------------------------------------------------\r\n # ● initialize \r\n #--------------------------------------------------------------------------\r\n alias mog_tool_hud_initialize initialize \r\n def initialize \r\n @toolhud = Tool_Hud.new\r\n mog_tool_hud_initialize\r\n end\r\n \r\n #--------------------------------------------------------------------------\r\n # ● Dispose\r\n #--------------------------------------------------------------------------\r\n alias mog_tool_hud_dispose dispose\r\n def dispose \r\n @toolhud.dispose\r\n mog_tool_hud_dispose\r\n end\r\n \r\n #--------------------------------------------------------------------------\r\n # ● update \r\n #--------------------------------------------------------------------------\r\n alias mog_tool_hud_update update\r\n def update \r\n @toolhud.update\r\n mog_tool_hud_update\r\n end\r\n\r\n #--------------------------------------------------------------------------\r\n # ● Refresh Hud\r\n #-------------------------------------------------------------------------- \r\n alias mog_tool_hud_refresh_hud refresh_hud\r\n def refresh_hud\r\n mog_tool_hud_refresh_hud\r\n @toolhud.refresh\r\n end \r\n \r\nend \r\n\r\n$mog_rgss3_xas_tool_hud = true"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2973974,"cells":{"blob_id":{"kind":"string","value":"f4b5535ff352b373fab7bd6135e6899b11a5f696"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"yumidev/memory"},"path":{"kind":"string","value":"/game.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":572,"string":"572"},"score":{"kind":"number","value":3.453125,"string":"3.453125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"require_relative 'board'\n\nclass Game\n def initialize\n @board = Board.new\n @previous_guess\n end\n\n def play\n @board.populate\n while !@board.won?\n @board.render\n guessed_pos = gets.chomp.to_i\n @board.reveal(guessed_pos)\n make_guess(guessed_pos)\n end\n end\n\n def make_guess(pos)\n if @previous_guess\n unless @board.same_card?(@previous_guess, pos)\n @board.hide(pos)\n @board.hide(@previous_guess)\n end\n @previous_guess = nil\n else\n @previous_guess = pos\n end\n end\nend\n\ngame = Game.new\ngame.play\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2973975,"cells":{"blob_id":{"kind":"string","value":"70b9d8386b8cfb199ab330fec129246d54e0d353"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"jesusmaldonado/primes"},"path":{"kind":"string","value":"/lib/primes/prime_parser.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":359,"string":"359"},"score":{"kind":"number","value":2.53125,"string":"2.53125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"require_relative 'prime_table'\nrequire_relative 'prime_generator'\n\nmodule Primes\n class PrimeParser\n def initialize(opts = {})\n @prime_generator = Primes::PrimeGenerator.new(opts)\n @prime_table = Primes::PrimeTable.new()\n end\n\n def print\n @prime_table.primes = @prime_generator.primes\n @prime_table.print_table\n end\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2973976,"cells":{"blob_id":{"kind":"string","value":"b72bf55a7f445da02360fe482b6e204d707d78c2"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"nonsensery/ar_validation_sample"},"path":{"kind":"string","value":"/test/models/post_test.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1938,"string":"1,938"},"score":{"kind":"number","value":2.875,"string":"2.875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"require 'test_helper'\n\nclass PostTest < ActiveSupport::TestCase\n test 'duplicate tag is detected when added to new post' do\n tag = Tag.first\n\n # Create a new post:\n post = Post.new\n\n # Add a tag:\n post.post_tags.new tag: tag\n\n # Post should be valid\n assert post.valid?\n\n # Add a duplicate tag:\n post.post_tags.new tag: tag\n\n # Check validity:\n assert (post.valid? == false), 'Post is valid dispite duplicate tags'\n end\n\n test 'duplicate tag prevents saving' do\n tag = Tag.first\n\n # Create a new post:\n post = Post.new\n\n # Add a tag:\n post.post_tags.new tag: tag\n\n # Add a duplicate tag:\n post.post_tags.new tag: tag\n\n # Check savability:\n assert (post.save == false), 'Saved post dispite duplicate tags'\n end\n\n test 'saving the post should save all post-tags, or the save should fail' do\n tag = Tag.first\n\n # Create a new post:\n post = Post.new\n\n # Add a tag:\n post.post_tags.new tag: tag\n\n # Add a duplicate tag:\n post.post_tags.new tag: tag\n\n # Save the post:\n post.save!\n\n # Check whether the first post-tag was saved:\n assert (post.post_tags.first.id != nil), 'Saved post, but not first duplicate post-tag'\n\n # Check whether the second post-tag was saved:\n assert (post.post_tags.second.id != nil), 'Saved post, but not second duplicate post-tag'\n end\n\n test 'saving the post should not change the detection of duplicate tags' do\n tag = Tag.first\n\n # Create a new post:\n post = Post.new\n\n # Add a tag:\n post.post_tags.new tag: tag\n\n # Add a duplicate tag:\n post.post_tags.new tag: tag\n\n # Record the validity before saving\n was_valid = post.valid?\n\n # Save the post:\n post.save!\n\n # Check the validity after saving\n is_valid = post.valid?\n\n # Validity should not change!\n assert (was_valid == is_valid), \"Saving post changed its validity from #{was_valid} to #{is_valid}\"\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2973977,"cells":{"blob_id":{"kind":"string","value":"c069811d01e1b47eaed9320fe07c84bf342d4c6c"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"DavidMcKenzie218/Week_1_Homework"},"path":{"kind":"string","value":"/Day_2/functions_practice_lab/ruby_functions_practice.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1879,"string":"1,879"},"score":{"kind":"number","value":3.5625,"string":"3.5625"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"def return_10()\n return 10\nend\n\ndef add(number1, number2)\n result = number1 + number2\n return result\nend\n\ndef subtract(number1, number2)\n result = number1 - number2\n return result\nend\n\ndef multiply(number1, number2)\n result = number1 * number2\n return result\nend\n\ndef divide(number1, number2)\n result = number1/number2\n return result\nend\n\ndef length_of_string(string)\n result = string.length\n return result\nend\n\ndef join_string(string1, string2)\n result = string1 + string2\n return result\nend\n\ndef add_string_as_number(string1, string2)\n result = string1.to_i + string2.to_i\n return result\nend\n\ndef number_to_full_month_name(number)\n case number\n when 1\n return \"January\"\n when 2\n return \"Febuary\"\n when 3\n return \"March\"\n when 4\n return \"April\"\n when 5\n return \"May\"\n when 6\n return \"June\"\n when 7\n return \"July\"\n when 8\n return \"August\"\n when 9\n return \"September\"\n when 10\n return \"October\"\n when 11\n return \"November\"\n when 12\n return \"December\"\n end\nend\n\ndef number_to_short_month_name(number)\n case number\n when 1\n return \"Jan\"\n when 2\n return \"Feb\"\n when 3\n return \"Mar\"\n when 4\n return \"Apr\"\n when 5\n return \"May\"\n when 6\n return \"Jun\"\n when 7\n return \"Jul\"\n when 8\n return \"Aug\"\n when 9\n return \"Sep\"\n when 10\n return \"Oct\"\n when 11\n return \"Nov\"\n when 12\n return \"Dec\"\n end\nend\n\ndef volume_of_a_cube(side_length)\n volume = side_length**3\n return volume\nend\n\ndef volume_of_a_sphere(radius)\n pi = Math::PI\n volume = (4.0/3) * pi * (radius**3)\n return volume.round(2)\nend\n\ndef fahrenheit_to_celcius(fahrenheit)\n celcius = (fahrenheit.to_f - 32) * 5 / 9\n return celcius.round(1)\nend\n\ndef password_generator(name, number)\n new_name = name.swapcase\n new_number = number*2\n new_password = \"#{new_name}\"+new_number.to_s\n return new_password\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2973978,"cells":{"blob_id":{"kind":"string","value":"fc00a59c5bce5b15c32aaa1dbe92fc331bebb4ad"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"nkirkus/testing"},"path":{"kind":"string","value":"/Game/testloop.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":99,"string":"99"},"score":{"kind":"number","value":3,"string":"3"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"i = -99\nputs \"Before : \" + i.to_s\n(1..10).each{|i| print 1; puts \" haha\"}\nputs \"After : \" + i.to_s\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2973979,"cells":{"blob_id":{"kind":"string","value":"551367efc3da1488541449746a16d92ee11ba24b"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"mezbahalam/script_quote_city"},"path":{"kind":"string","value":"/run.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1312,"string":"1,312"},"score":{"kind":"number","value":2.640625,"string":"2.640625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"### Health Leads Lead Type — > 114 input fields https://leads.usacoverage.com/pingPostSpec.php?TYPE=6\n# require 'nokogiri'\n# file = File.open('ping.html')\n# html = Nokogiri::HTML(file)\n# data = html.css(\"a+ .hilite .left:nth-child(3)\")\n# #xpath(\"//a+//*[contains(concat( ' ', @class, ' ' ), concat( ' ', 'hilite', ' ' ))]//*[contains(concat( ' ', @class, ' ' ), concat( ' ', 'left', ' ' )) and (((count(preceding-sibling::*) + 1) = 3) and parent::*)]\")\n# output = File.new('generator_command.txt', 'w+')\n# data.each do |data|\n# field = data.text\n# File.open('generator_command.txt', 'a') { |f| f.write(field + \" \") }\n# end\n\n\n\n\n## Medicare Leads Lead Type — > 48 input fields https://leads.usacoverage.com/pingPostSpec.php?TYPE=7\nrequire 'nokogiri'\nrequire 'open-uri'\nhtml = Nokogiri::HTML(open('https://leads.usacoverage.com/pingPostSpec.php?TYPE=7'))\ndata = html.css(\"a+ .hilite .left:nth-child(3)\")\n#xpath(\"//a+//*[contains(concat( ' ', @class, ' ' ), concat( ' ', 'hilite', ' ' ))]//*[contains(concat( ' ', @class, ' ' ), concat( ' ', 'left', ' ' )) and (((count(preceding-sibling::*) + 1) = 3) and parent::*)]\")\noutput = File.new('medicare_generator_command.txt', 'w+')\ndata.each do |data|\n field = data.text\n File.open('medicare_generator_command.txt', 'a') { |f| f.write(field + \" \") }\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2973980,"cells":{"blob_id":{"kind":"string","value":"0be33067f6434e405c634ecfea3125a89fc6f56b"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"salomekbg/prime-ruby-001-prework-web"},"path":{"kind":"string","value":"/prime.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":286,"string":"286"},"score":{"kind":"number","value":3.734375,"string":"3.734375"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":["LicenseRef-scancode-unknown-license-reference","LicenseRef-scancode-public-domain"],"string":"[\n \"LicenseRef-scancode-unknown-license-reference\",\n \"LicenseRef-scancode-public-domain\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"def prime?(num)\n numbers = (2...num).to_a\n check = false\n numbers.each do |item|\n if num < 2\n check = false\n elsif num == 2\n check = true\n elsif num % item != 0\n check = true\n elsif num % item == 0\n check = false\n break\n end\n end\n check\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2973981,"cells":{"blob_id":{"kind":"string","value":"8def2db9abea87b94b693b9dcb90bf26c0865b8e"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"kennym/saas-class"},"path":{"kind":"string","value":"/hw1/cartesian_product.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":229,"string":"229"},"score":{"kind":"number","value":3.515625,"string":"3.515625"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"class CartesianProduct\n include Enumerable\n\n attr_accessor :xs, :ys\n\n def initialize(lhs, rhs)\n @xs, @ys = lhs, rhs\n end\n\n def each\n @xs.each do |x|\n @ys.each do |y|\n yield x, y\n end\n end\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2973982,"cells":{"blob_id":{"kind":"string","value":"5559f9c6a99d2a2963b74267697b08f00a8dcb12"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"ShinyVerse/anagram-app"},"path":{"kind":"string","value":"/spec/feature/app_spec.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1037,"string":"1,037"},"score":{"kind":"number","value":2.796875,"string":"2.796875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"require 'app'\nrequire 'anagram'\n\ndescribe 'Feature' do\n let(:app) { App.new(Anagram.new) }\n before(:each) do\n app.parse_user_input(\"era cat rat are pear ear\")\n end\n context 'found anagrams' do\n it 'prints expected positive output' do\n allow(STDIN).to receive(:gets).and_return(\"tac\\n\", \"exit\\n\")\n expect { app.start_app }.to output(\"Enter a word and receive anagrams from the list of your word\\n\"\\\n \"Write 'exit' to finish\\n\"\\\n \"Please enter your word to check\\n\"\\\n \"The anagrams found are: \\n\"\\\n \"cat\\n\"\\\n \"Please enter your word to check\\n\").to_stdout\n end\n end\n context 'no anagram matches' do\n it 'prints expected negative output' do\n allow(STDIN).to receive(:gets).and_return(\"wrong\\n\", \"exit\\n\")\n expect { app.start_app }.to output(\"Enter a word and receive anagrams from the list of your word\\n\"\\\n \"Write 'exit' to finish\\n\"\\\n \"Please enter your word to check\\n\"\\\n \"No matches\\n\"\\\n \"Please enter your word to check\\n\").to_stdout\n end\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2973983,"cells":{"blob_id":{"kind":"string","value":"63a4e6ebc06ad3c7637b29f90c161244cdb122cf"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"mcwaller422/Intro_to_Ruby"},"path":{"kind":"string","value":"/Arrays/Mutate.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":180,"string":"180"},"score":{"kind":"number","value":3.75,"string":"3.75"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"a = [1,2,3,4,5,6]\n\ndef mutate(arr)\n arr.pop\nend\n\ndef not_mutate(arr)\n arr.select{|i| i >3}\nend\n\na = [1,2,3,4,5,6]\n\nmutate(a)\nputs a \n\na = [1,2,3,4,5,6]\nnot_mutate(a)\nputs a\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2973984,"cells":{"blob_id":{"kind":"string","value":"ae72def25a8499bb36f655c78c42ecb8881853c3"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"robopro/2019-06-14-Cookbook-day-1"},"path":{"kind":"string","value":"/controller.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":825,"string":"825"},"score":{"kind":"number","value":3.078125,"string":"3.078125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"require_relative 'view'\n\nclass Controller\n def initialize(cookbook)\n @cookbook = cookbook\n @view = View.new\n end\n\n def list\n # first get all recipes from cookbook\n recipes = @cookbook.all\n # send data to view\n @view.display(recipes)\n end\n\n def create\n # add a new recipe:\n # ask user for name\n name = @view.ask_for(:name)\n # ask user for description\n description = @view.ask_for(:description)\n # create recipe from name and description\n recipe = Recipe.new(name, description)\n # pass recipe to cookbook\n @cookbook.add_recipe(recipe)\n end\n\n def destroy\n # display all the recipes\n list\n # ask the user for which recipe\n index = @view.ask_for_index\n # delete recipe from cookbook\n @cookbook.remove_recipe(index)\n # show the new recipe\n list\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2973985,"cells":{"blob_id":{"kind":"string","value":"7dcdfc4cbfe1f04524604c3f6474c938cc004deb"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"rimuhosting/fog"},"path":{"kind":"string","value":"/lib/fog/model.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1971,"string":"1,971"},"score":{"kind":"number","value":2.75,"string":"2.75"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"module Fog\n class Model\n\n def self.attribute(name, other_names = [])\n class_eval <<-EOS, __FILE__, __LINE__\n attr_accessor :#{name}\n EOS\n @attributes ||= []\n @attributes |= [name]\n for other_name in [*other_names]\n aliases[other_name] = name\n end\n end\n\n def self.identity(name, other_names = [])\n @identity = name\n self.attribute(name, other_names)\n end\n\n def self.aliases\n @aliases ||= {}\n end\n\n def self.attributes\n @attributes ||= []\n end\n\n def attributes\n attributes = {}\n for attribute in self.class.attributes\n attributes[attribute] = send(\"#{attribute}\")\n end\n attributes\n end\n\n def collection\n @collection\n end\n\n def identity\n send(self.class.instance_variable_get('@identity'))\n end\n\n def initialize(new_attributes = {})\n merge_attributes(new_attributes)\n end\n\n def inspect\n data = \"#<#{self.class.name}\"\n for attribute in self.class.attributes\n data << \" #{attribute}=#{send(attribute).inspect}\"\n end\n data << \">\"\n end\n\n def merge_attributes(new_attributes = {})\n for key, value in new_attributes\n if aliased_key = self.class.aliases[key]\n send(\"#{aliased_key}=\", value)\n else\n send(\"#{key}=\", value)\n end\n end\n self\n end\n\n def new_record?\n !identity\n end\n\n def reload\n new_attributes = collection.get(identity).attributes\n merge_attributes(new_attributes)\n end\n\n private\n\n def collection=(new_collection)\n @collection = new_collection\n end\n\n def connection=(new_connection)\n @connection = new_connection\n end\n\n def connection\n @connection\n end\n\n def remap_attributes(attributes, mapping)\n for key, value in mapping\n if attributes.key?(key)\n attributes[value] = attributes.delete(key)\n end\n end\n end\n\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2973986,"cells":{"blob_id":{"kind":"string","value":"22a205d2e20118269cad67337cfc3832f979697d"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"cesartalves/ruby_metaprogramming_as_spec"},"path":{"kind":"string","value":"/spec/callables/blocks_spec.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1392,"string":"1,392"},"score":{"kind":"number","value":3.359375,"string":"3.359375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"require 'spec_helper'\n\ndescribe \"Ruby Blocks\" do\n\n def method_using_block_implicitly\n yield\n end\n\n def method_using_block_explicity(&block)\n block.call\n end\n\n it \"they will run the code which is passed to the method\" do\n expect(method_using_block_implicitly { 5 }).to eq 5\n end\n\n it \"they can be multilined, like a foreach\" do\n expect(\n method_using_block_implicitly do\n 4 \n end).to eq 4\n end\n\n it \"they can receive block explicitly\" do\n expect(method_using_block_explicity {5} ).to eq 5\n end\n\n it \"they can raise erros if no blocks are passed\" do\n expect { method_using_block_implicitly }.to raise_error LocalJumpError\n end\n\n it \"are a Proc/Closures\" do\n \n end\n\n it \"Self yield\" do\n class String\n def yield_self\n yield self.class\n end\n end\n\n expect do \n \"This is a string\".yield_self { |x| print x }\n end.to output('String').to_stdout\n end\n\n it \"Symbol.to_proc\" do\n expect([1, 2, 3].map(&:to_s)).to include(\"1\", \"2\", \"3\")\n\n # this is how ruby implements it, sort of\n\n class Symbol\n def to_proc\n Proc.new { |x| x.send self }\n\n end\n end\n\n expect([1, 2, 3].map(&:to_s)).to include(\"1\", \"2\", \"3\")\n end\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2973987,"cells":{"blob_id":{"kind":"string","value":"7e3c8b4fd45faabb5021633ee46caa44c3a50580"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"adambeynon/opal"},"path":{"kind":"string","value":"/lib/opal/nodes/if.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1619,"string":"1,619"},"score":{"kind":"number","value":2.515625,"string":"2.515625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"require 'opal/nodes/base'\n\nmodule Opal\n module Nodes\n class IfNode < Base\n handle :if\n\n children :test, :true_body, :false_body\n\n RUBY_ENGINE_CHECK = [:call, [:const, :RUBY_ENGINE],\n :==, [:arglist, [:str, \"opal\"]]]\n\n RUBY_PLATFORM_CHECK = [:call, [:const, :RUBY_PLATFORM],\n :==, [:arglist, [:str, \"opal\"]]]\n\n def compile\n truthy, falsy = self.truthy, self.falsy\n\n if skip_check_present?\n falsy = nil\n end\n\n push \"if (\", js_truthy(test), \") {\"\n\n # skip if-body if no truthy sexp\n indent { line stmt(truthy) } if truthy\n\n if falsy\n if falsy.type == :if\n line \"} else \", stmt(falsy)\n else\n indent do\n line \"} else {\"\n line stmt(falsy)\n end\n\n line \"}\"\n end\n else\n push \"}\"\n end\n\n wrap \"(function() {\", \"; return nil; })()\" if needs_wrapper?\n end\n\n # pre-processing only effects falsy blocks. If engine is\n # opal, then falsy block gets generated as normal. Unless\n # engine is opal then that code gets generated as the\n # falsy block\n def skip_check_present?\n test == RUBY_ENGINE_CHECK or test == RUBY_PLATFORM_CHECK\n end\n\n def truthy\n needs_wrapper? ? compiler.returns(true_body || s(:nil)) : true_body\n end\n\n def falsy\n needs_wrapper? ? compiler.returns(false_body || s(:nil)) : false_body\n end\n\n def needs_wrapper?\n expr? or recv?\n end\n end\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2973988,"cells":{"blob_id":{"kind":"string","value":"7c504d0ae57cc77fa63d4b1d70373c7a87e9c3f3"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"Tim-Feng/learn-to-program"},"path":{"kind":"string","value":"/ch12-2.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":177,"string":"177"},"score":{"kind":"number","value":3.25,"string":"3.25"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"puts \"Please enter the year you born:\"\nborn_y = gets.chomp\nputs \"Please enter the month you born:\"\nborn_m = gets.chomp\nputs \"Please enter the date you born:\"\nborn_y = gets.chomp"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2973989,"cells":{"blob_id":{"kind":"string","value":"bf00e71275725e61820bbf02d6ffb4dc65ba0a66"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"hawthornehaus/astronom-web"},"path":{"kind":"string","value":"/app/models/nutrient_loss.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2298,"string":"2,298"},"score":{"kind":"number","value":2.53125,"string":"2.53125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"class NutrientLoss\n include Enumerable\n\n delegate :[], :each,\n :to => :loss_table\n\n attr_reader :from, :to, :gender, :duration_in_seconds, :significance\n\n def initialize(from: , to: , gender: , significance: 6)\n @gender = gender # currently unused\n @from = from.to_time\n @to = to.to_time\n @duration_in_seconds = ((@to - @from) / 1.seconds).round\n @significance = significance\n end\n\n\n def loss_table\n @loss_table ||= calculate_losses\n end\n\n alias_method :all, :loss_table\n\n\n def calculate_losses\n LOSSES_PER_DAY.each.with_object({}) do |(nutrient, loss_per_day), acc|\n acc[nutrient] = (loss_per_day * (duration_in_seconds / SECONDS_IN_DAY)).round(significance)\n end\n end\n\n SECONDS_IN_DAY = 86400.0\n\n LOSSES_PER_DAY = {\n 'water' => 3000.0,\n 'energy' => 3200.0,\n 'protein' => 202.0,\n 'total_lipid' => 54.0,\n # 'ash' =>\n 'carbohydrates' => 486.0,\n 'fiber_td' => 43.0,\n 'total_sugar' => 38.0,\n 'calcium' => 1000.0,\n 'iron' => 8.0,\n 'magnesium' => 420.0,\n 'phosphorus' => 700.0,\n 'potassium' => 3000.0,\n 'sodium' => 3000.0,\n 'zinc' => 11.0,\n 'copper' => 900.0,\n 'maganese' => 9.0,\n 'selenium' => 55.0,\n 'vitamin_c' => 90.0,\n 'thiamin' => 1.2,\n 'riboflavin' => 1.3,\n 'niacin' => 16.0,\n 'panto_acid' => 5.0,\n 'vitamin_b6' => 1.3,\n 'total_folate' => 400.0,\n # 'folic_acid' =>\n # 'food_folate' =>\n # 'folate_dfe' =>\n 'total_choline' => 550.0,\n 'vitamin_b12' => 2.4,\n 'vitamin_a' => 900.0,\n 'retinol' => 900.0,\n 'alpha_carotene' => 4.71,\n 'vitamin_e' => 15.0,\n 'vitamin_d' => 5.0,\n 'vitamin_k' => 120.0,\n 'fat_saturated' => 9.0,\n 'fat_monounsaturated' => 25.0,\n 'fat_polyunsaturated' => 20.0,\n 'cholesterol' => 300.0,\n # 'beta_carotene' =>\n # 'beta_cryptoxanthin' =>\n # 'lycopene' =>\n # 'lutein_and_zeaxanthin' =>\n }\n\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2973990,"cells":{"blob_id":{"kind":"string","value":"7e833c69b16cc89afe8f1795e77dac67d4365856"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"zauzaj/prime_number_list"},"path":{"kind":"string","value":"/lib/concern/prime_number_generator.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":451,"string":"451"},"score":{"kind":"number","value":3.390625,"string":"3.390625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"require 'pry-rails'\nmodule PrimeNumberGenerator\n\t\n\tdef generate starting_value, ending_value\n\t\tprimes_list = []\n\t\tinput_order_changing(starting_value, ending_value).to_a.each do |value|\n\t\t\tprimes_list << value if isPrime(value)\n\t\tend\n\t\tprimes_list\n\tend\n\n\n\tdef isPrime argument\n\t\t(2..(argument/2)).to_a.all? {|div| argument%div > 0}\n\tend\n\n\tdef input_order_changing num1, num2\n\t\tnum1 if num1 == num2\n\t\tnum1 > num2 ? (num2..num1) : (num1..num2) \n\tend\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2973991,"cells":{"blob_id":{"kind":"string","value":"ce3568e273896e8872369bb4a204231114444382"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"chiensiTB/OpenStudio-server-orig"},"path":{"kind":"string","value":"/gems/gems/dencity-0.1.0/lib/dencity/client/structure.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":4497,"string":"4,497"},"score":{"kind":"number","value":2.71875,"string":"2.71875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["BSD-2-Clause"],"string":"[\n \"BSD-2-Clause\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"module Dencity\n # Structure methods\n class Structure\n include Request\n\n attr_accessor :analysis_id\n attr_accessor :user_defined_id\n attr_accessor :structure\n attr_accessor :measure_instances\n\n # initialize\n def initialize(analysis_id = nil, user_defined_id = nil, path = nil, connection)\n @analysis_id = analysis_id\n @user_defined_id = user_defined_id\n @structure = Hashie::Mash.new\n @measure_instances = Hashie::Mash.new\n\n @connection = connection\n\n # initialize with json file\n unless path.nil?\n load_from_file(path)\n end\n\n @upload_retries = nil\n end\n\n def push\n begin\n @upload_retries ||= 0\n\n response = post('api/structure', format_structure)\n @structure.id = response['id'] if response['id']\n return response if response\n rescue StandardError => se\n # Decide if we should fail based on number of retries\n if @upload_retries < 3\n\n raise 'could not upload'\n else\n # or here: @upload_retries = nil\n return se\n end\n end\n rescue => e\n @upload_retries += 1\n sleep 2\n retry\n ensure\n # always do this\n # verify that this is only called if the retry is not triggered\n @upload_retries = nil\n end\n\n # load structure from json file into a mash\n def load_from_file(path)\n return unless File.exist?(path)\n json_data = File.read(path)\n load_raw_json(json_data)\n end\n\n # load structure from raw json\n def load_raw_json(json_data)\n temp = Hashie::Mash.new(MultiJson.load(json_data))\n @structure = temp.structure ? temp.structure : Hashie::Mash.new\n @measure_instances = temp.measure_instances ? temp.measure_instances : Hashie::Mash.new\n # these could be set in the file\n @analysis_id = temp.structure.analysis_id if temp.structure.analysis_id\n @user_defined_id = temp.structure.user_defined_id if temp.structure.user_defined_id\n\n return true\n end\n\n # upload file\n def upload_file(path, file_name = nil)\n fail 'No Structure ID defined for structure. Can\\'t upload file' if @structure.id.nil?\n\n file = File.open(path, 'rb')\n the_file = Base64.strict_encode64(file.read)\n file.close\n\n # file_data param\n file_data = {}\n file_data['file_name'] = file_name.nil? ? File.basename(path) : file_name\n file_data['file'] = the_file\n\n data = Hashie::Mash.new\n data.structure_id = @structure.id\n data.file_data = file_data\n\n push_file('api/related_file', MultiJson.dump(data))\n end\n\n # delete an uploaded file\n # if structure_id is nil, will use @structure.id\n def delete_file(file_name)\n fail 'No Structure ID defined for structure. Can\\'t delete file' if @structure.id.nil?\n\n data = Hashie::Mash.new\n data.structure_id = @structure.id\n data.file_name = file_name\n\n push_file('api/remove_file', MultiJson.dump(data))\n end\n\n # push file w/ retry\n def push_file(path, data)\n begin\n @upload_retries ||= 0\n response = post(path, data)\n return response if response\n rescue StandardError => se\n # Decide if we should fail based on number of retries\n if @upload_retries < 3\n if path.include? 'remove'\n raise 'could not delete file'\n else\n raise 'could not upload file'\n end\n else\n return se\n end\n end\n rescue => e\n @upload_retries += 1\n sleep 2\n retry\n ensure\n # verify that this is only called if the retry is not triggered\n @upload_retries = nil\n end\n\n private\n\n # formats structure parameters for posting\n def format_structure\n # generate name/value pairs for structure metadata\n formatted_meta = []\n @structure.each do |k, v|\n formatted_meta << { name: k, value: v } unless %w(id user_defined_id analysis_id).include?(k)\n end\n new_struct = Hashie::Mash.new\n new_struct.metadata = formatted_meta\n\n # TODO: what if it's already in the structure hash?\n # add user_defined_id to structure\n new_struct.user_defined_id = @user_defined_id\n new_struct.analysis_id = @analysis_id\n\n data_hash = Hashie::Mash.new\n data_hash.structure = new_struct\n data_hash.measure_instances = @measure_instances ? @measure_instances : []\n\n # convert to json\n MultiJson.dump(data_hash)\n end\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2973992,"cells":{"blob_id":{"kind":"string","value":"e5bddb0675f89233850d478eb4e152d095de422f"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"ak061295/Radlibs"},"path":{"kind":"string","value":"/mad_libs.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":488,"string":"488"},"score":{"kind":"number","value":2.53125,"string":"2.53125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"require 'sinatra'\n\nget '/' do\n erb :form\nend\n\nget '/upload' do\n erb :upload\nend\n\nget '/story' do\n erb :story\nend\n\npost '/' do\n @name = \"#{params[:post][:first_name]} #{params[:post][:last_name]}\"\n @fname = \"#{params[:post][:first_name]}\"\n @lname = \"#{params[:post][:last_name]}\"\n if @name == \"Brennan Kinney\"\n erb \"Buckets\"\n elsif @name == \"Anthony Kennedy\"\n erb \"Nooo!!! Jimmy!!!\"\n else \n erb \"Hello, #{@name}. Welcome to my submarine. It's long and hard and full of seamen.\"\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2973993,"cells":{"blob_id":{"kind":"string","value":"81d57a9e7ea135b60ab5cb48984c6f4c380b1804"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"h11z/ruby-oo-relationships-practice-blood-oath-exercise-chi01-seng-ft-080320"},"path":{"kind":"string","value":"/app/models/Followers.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":841,"string":"841"},"score":{"kind":"number","value":3.140625,"string":"3.140625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["LicenseRef-scancode-unknown-license-reference","LicenseRef-scancode-public-domain"],"string":"[\n \"LicenseRef-scancode-unknown-license-reference\",\n \"LicenseRef-scancode-public-domain\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"class Follower\n attr_accessor\n attr_reader :name, :age, :life_motto\n\n @@all = []\n\n def self.all\n @@all\n end\n\n def initialize(name,age,life_motto)\n @name = name\n @age = age\n @life_motto = life_motto\n\n @@all << self\n end\n\n def cults\n cults_im_in = BloodOath.all.filter do |cult_lister|\n cult_lister.name.name == self.name\n end\n just_cults = cults_im_in.map do |cult_map|\n cult_map.cult\n end\n just_cults\n end\n\n def join_cult(cult)\n BloodOath.new(self,cult,\"2020-02-25\")\n end\n\n def self.of_a_certain_age(num)\n follower_map = Follower.all.map do |finder|\n if finder.age >= num\n finder\n end\n end\n follower_map.compact\n end\n\n\nend #end of follower class"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2973994,"cells":{"blob_id":{"kind":"string","value":"b856ed8910a721ee6cea960c5bf55657908a348d"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"realgam3/ysoserial.rb"},"path":{"kind":"string","value":"/lib/ysoserial/gadgets.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":637,"string":"637"},"score":{"kind":"number","value":2.578125,"string":"2.578125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["Apache-2.0"],"string":"[\n \"Apache-2.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"require 'pathname'\r\n\r\nmodule YSoSerial\r\n module Gadgets\r\n def self.load\r\n pattern = File.join(Pathname(__FILE__).dirname, \"gadgets\", \"*.rb\")\r\n Dir.glob(pattern).each do |path|\r\n Kernel.load(path)\r\n end\r\n end\r\n\r\n def self.table\r\n gadgets = {}\r\n self.load\r\n YSoSerial::Gadgets.constants.select do |const_symbol|\r\n const = YSoSerial::Gadgets.const_get(const_symbol) rescue nil\r\n if not const.nil? and const.is_a? Class\r\n class_name = const.name.split(\"::\")[-1].to_sym\r\n gadgets[class_name] = const\r\n end\r\n end\r\n gadgets\r\n end\r\n end\r\nend\r\n\r\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2973995,"cells":{"blob_id":{"kind":"string","value":"7ac9e5ac4bc5ac300000ad92e631310e8fce7800"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"ministryofjustice/offender-management-allocation-manager"},"path":{"kind":"string","value":"/lib/working_day_calculator.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":369,"string":"369"},"score":{"kind":"number","value":2.984375,"string":"2.984375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"require 'bank_holidays'\nrequire 'business_time'\n\nclass WorkingDayCalculator\n def initialize(holidays = BankHolidays.dates)\n BusinessTime::Config.holidays = Set.new(holidays)\n end\n\n def working_days_between(date1, date2)\n date1.business_days_until(date2)\n end\n\n def self.working_days_between(date1, date2)\n new.working_days_between(date1, date2)\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2973996,"cells":{"blob_id":{"kind":"string","value":"5c092562fb4b50d6fdd4415bbb5ed6257b8d2069"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"danielevans/gutenberg_text_search_compiler"},"path":{"kind":"string","value":"/parse.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":7245,"string":"7,245"},"score":{"kind":"number","value":2.515625,"string":"2.515625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"require 'rubygems'\nrequire 'stemmify'\nrequire 'fileutils'\nrequire 'shellwords'\nrequire 'json'\nrequire 'benchmark'\nrequire 'pp'\nrequire 'pry'\nrequire 'optionparser'\nrequire 'set'\nrequire 'progressbar'\n\nSTOP_WORDS = [ # ripped off from https://github.com/brez/stopwords/blob/master/lib/stopwords.rb\n 'a','cannot','into','our','thus','about','co','is','ours','to','above',\n 'could','it','ourselves','together','across','down','its','out','too',\n 'after','during','itself','over','toward','afterwards','each','last','own',\n 'towards','again','eg','latter','per','under','against','either','latterly',\n 'perhaps','until','all','else','least','rather','up','almost','elsewhere',\n 'less','same','upon','alone','enough','ltd','seem','us','along','etc',\n 'many','seemed','very','already','even','may','seeming','via','also','ever',\n 'me','seems','was','although','every','meanwhile','several','we','always',\n 'everyone','might','she','well','among','everything','more','should','were',\n 'amongst','everywhere','moreover','since','what','an','except','most','so',\n 'whatever','and','few','mostly','some','when','another','first','much',\n 'somehow','whence','any','for','must','someone','whenever','anyhow',\n 'former','my','something','where','anyone','formerly','myself','sometime',\n 'whereafter','anything','from','namely','sometimes','whereas','anywhere',\n 'further','neither','somewhere','whereby','are','had','never','still',\n 'wherein','around','has','nevertheless','such','whereupon','as','have',\n 'next','than','wherever','at','he','no','that','whether','be','hence',\n 'nobody','the','whither','became','her','none','their','which','because',\n 'here','noone','them','while','become','hereafter','nor','themselves','who',\n 'becomes','hereby','not','then','whoever','becoming','herein','nothing',\n 'thence','whole','been','hereupon','now','there','whom','before','hers',\n 'nowhere','thereafter','whose','beforehand','herself','of','thereby','why',\n 'behind','him','off','therefore','will','being','himself','often','therein',\n 'with','below','his','on','thereupon','within','beside','how','once',\n 'these','without','besides','however','one','they','would','between','i',\n 'only','this','yet','beyond','ie','onto','those','you','both','if','or',\n 'though','your','but','in','other','through','yours','by','inc','others',\n 'throughout','yourself','can','indeed','otherwise','thru','yourselves'\n].map(&:stem)\n\nBLANK_LINE_REGEXP = /^$/\nSTART_REGEXP = /^\\*+\\s*START[^$]*PROJECT GUTENBERG[^\\*]*\\*{3,}\\s*$/im\nINITIAL_CHOMP_REGEXP = /\\*{3,}[^*]*\\*{3,}\\s*/\nEND_REGEXP = /^\\*+\\s*END[^$]*PROJECT GUTENBERG/im\nPUNCTUATION_REGEXP = /\\p{Punct}+$/\nMINIMUM_WORDS = 2\n\nclass Parser\n attr_accessor :minimum_words\n attr_accessor :directories\n attr_accessor :verbose\n attr_accessor :progressbar\n\n def initialize dirs=\"gutenberg_data\", min_words=MINIMUM_WORDS\n self.directories = Array(dirs)\n self.minimum_words = min_words\n end\n\n def whitelisted_word? word\n @whitelist ||= begin\n words = if File.exist? \"whitelist.txt\"\n File.read(\"whitelist.txt\").split\n else\n generate_whitelist\n end\n Set.new words\n end\n\n @whitelist.include? word\n end\n\n def generate_whitelist\n words = (File.readlines(\"/usr/share/dict/words\").map { |word| word.chomp.downcase.stem } - STOP_WORDS).uniq\n File.open(\"whitelist.txt\", \"wb\") do |f|\n f.write @whitelist.join(\"\\n\")\n end\n words\n end\n\n def unzip f\n %x{unzip #{Shellwords.shellescape(f)}}\n end\n\n def cleanup\n Dir.glob(\"*.txt\").each do |f|\n FileUtils.rm f\n end\n\n Dir.glob(\"*\").each do |f|\n FileUtils.rm_r f if File.directory? f\n end\n end\n\n def paragraphs text\n aggregator_hash = Hash.new { |h, k| h[k] = 0 }\n\n text.split(BLANK_LINE_REGEXP).map do |paragraph|\n words = paragraph.gsub(/[\\s]+/, ' ').split.each_with_object(aggregator_hash.dup) do |word, memo|\n sanitary_word = word.gsub(PUNCTUATION_REGEXP, '').downcase.stem\n memo[sanitary_word] += 1 if whitelisted_word?(sanitary_word)\n end\n if words.length >= self.minimum_words\n { text: paragraph.gsub(\"\\n\", \" \").gsub(/\\s+/, ' ').gsub(/^\\s+/, '').gsub(/\\s$/, ''), words: words }\n end\n end.compact\n end\n\n def write_result dir, results_dir, result\n destination_dir = File.join(results_dir, dir)\n FileUtils.mkdir_p destination_dir\n id = File.split(dir).last\n json = JSON.pretty_generate({ id: id, paragraphs: result })\n File.open(File.join(destination_dir, \"#{id}.json\"), \"wb\") do |f|\n f.write(json)\n end\n end\n\n def get_textfile dir\n file = Dir.glob(\"*.zip\").sort.first\n return nil if !file\n unzip file\n Dir.glob(\"**/*.txt\").first\n end\n\n def process_directory dir\n puts \"Processing: #{dir}\" if verbose\n rt = Benchmark.realtime do\n results_dir = File.expand_path('./results')\n Dir.chdir dir do\n textfile = get_textfile dir\n\n if !textfile\n $stderr.puts \"Error getting textfile for #{dir}\"\n return false\n end\n\n file_data = nil\n\n File.open(textfile, 'rb') do |f|\n file_data = f.read\n end\n\n start_index = file_data.index START_REGEXP\n end_index = file_data.index END_REGEXP\n\n if start_index.nil? || end_index.nil?\n $stderr.puts \"#{File.join(dir, textfile)} did not match expected regular expressions (s:#{start_index} e:#{end_index})\"\n return false\n end\n\n file_data = file_data[start_index..end_index]\n .encode('UTF-8', invalid: :replace, undef: :replace, replace: '?')\n .gsub(\"\\r\", '')\n .gsub(INITIAL_CHOMP_REGEXP, '')\n .gsub(/^\\s*$/,'')\n if file_data.length > 0\n write_result dir, results_dir, paragraphs(file_data)\n else\n $stderr.puts \"#{File.join(dir, textfile)} contains no data\"\n end\n ensure\n cleanup\n end\n end\n puts \"Complete: #{dir} #{rt}s\" if verbose\n end\n\n def parse!\n count = 1\n rt = Benchmark.realtime do\n whitelisted_word? \"foo\" # generates the whitelist in the right place\n\n all_files = directories.map do |dir|\n Dir.glob(File.join(dir, \"**/*.zip\"))\n end.flatten.uniq\n\n files_by_dir = all_files.group_by { |f| f.gsub(/(.*)\\/[^\\/]*/, \"\\\\1\") }\n count = files_by_dir.length\n puts \"#{count} directories detected\"\n progressbar.total = count if progressbar\n files_by_dir.each_key.sort.each do |dir|\n process_directory dir\n progressbar.increment if progressbar\n end\n end\n\n puts \"Complete in #{rt}s\"\n end\nend\n\nparser = Parser.new\nOptionParser.new do |opts|\n opts.banner = \"Usage: parse.rb [options]\"\n\n opts.on(\"-v\", \"--[no-]verbose\", \"Run verbosely\") do |v|\n options[:verbose] = v\n end\n\n opts.on(\"-d=dir\", \"--directory=dir,dir,dir\", Array, \"directory to parse\") do |v|\n parser.directories = v\n end\n\n opts.on(\"-p\", \"show progress\") do\n parser.progressbar = ProgressBar.create title: \"Directories\", format: \"%t (%c/%C): %w\"\n end\n\nend.parse!\n\n\nparser.parse!\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2973997,"cells":{"blob_id":{"kind":"string","value":"be653cd5e01d9bf7faeae459adedf0f05a71e694"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"Steimel/Thomas"},"path":{"kind":"string","value":"/lib/thomas/canvas.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":910,"string":"910"},"score":{"kind":"number","value":3.0625,"string":"3.0625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"module Thomas\n class Canvas\n attr_reader :width, :height, :things\n\n def initialize(width, height)\n @width = width\n @height = height\n @things = []\n end\n\n def drawable_things\n @things.select{|thing| thing.drawable}\n end\n\n def place_thing(thing, r, c)\n thing.set_position(r,c)\n thing.canvas = self\n @things.push(thing)\n end\n\n def draw(border=false)\n self.to_s(border)\n end\n\n def to_s(border=false)\n output = Util.build_empty_string_box(@width, @height)\n drawable_things.each do |thing|\n output = thing.draw(output, @width, @height)\n end\n if border\n top_bottom_bar = ('-' * (@width + 2))\n return top_bottom_bar + \"\\n\\r\" + output.map{|row| '|' + row.join('') + '|'}.join(\"\\n\\r\") + \"\\n\\r\" + top_bottom_bar\n else\n return output.map{|row| row.join('')}.join(\"\\n\\r\")\n end\n end\n\n end\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2973998,"cells":{"blob_id":{"kind":"string","value":"7191bae7995ed1457716218e7d945de263d3e8c2"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"soutaro/querly"},"path":{"kind":"string","value":"/lib/querly/pattern/kind.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1603,"string":"1,603"},"score":{"kind":"number","value":2.734375,"string":"2.734375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"module Querly\n module Pattern\n module Kind\n class Base\n attr_reader :expr\n\n def initialize(expr:)\n @expr = expr\n end\n end\n\n module Negatable\n attr_reader :negated\n\n def initialize(expr:, negated:)\n @negated = negated\n super(expr: expr)\n end\n end\n\n class Any < Base\n def test_kind(pair)\n true\n end\n end\n\n class Conditional < Base\n include Negatable\n\n def test_kind(pair)\n !negated == !!conditional?(pair)\n end\n\n def conditional?(pair)\n node = pair.node\n parent = pair.parent&.node\n\n case parent&.type\n when :if\n node.equal? parent.children.first\n when :while\n node.equal? parent.children.first\n when :and\n node.equal? parent.children.first\n when :or\n node.equal? parent.children.first\n when :csend\n node.equal? parent.children.first\n else\n false\n end\n end\n end\n\n class Discarded < Base\n include Negatable\n\n def test_kind(pair)\n !negated == !!discarded?(pair)\n end\n\n def discarded?(pair)\n node = pair.node\n parent = pair.parent&.node\n\n case parent&.type\n when :begin\n if node.equal? parent.children.last\n discarded? pair.parent\n else\n true\n end\n else\n false\n end\n end\n end\n end\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2973999,"cells":{"blob_id":{"kind":"string","value":"75136031563b97cec3cbbc1ec40018eee9b8ca04"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"splashinn/Warmups"},"path":{"kind":"string","value":"/main.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1268,"string":"1,268"},"score":{"kind":"number","value":3.84375,"string":"3.84375"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"# Load in all the shakespeare and remove newline characters\ndef load_shakespeare\n File.read(File.dirname(__FILE__) + '/Shakespeare.txt').delete(\"\\n\")\nend\n\nshakespeare = load_shakespeare()\n\n# ********************\n\n# REGEX DRILLS\n# Use regular expressions to answer the following questions:\n\n# How many words does Shakespeare use?\nshakespeare.split(/\\w+/).count\n\n# How many different words does Shakespeare use?\nshakespeare.scan(/\\w+/).uniq.count\n\n# How many times does Shakespeare use the word 'the'?\nshakespeare.scan.(/the/i).count\n\n# How many times does Shakespeare write \"guildenstern\" or \"Guildenstern\"\nshakespeare.scan.(/guildenstern/i).count\n\n# Find the entire \"To be, or not to be- that is the question:\" with as few regex characters as possible\nshakespeare.scan(/To be, or[-: \\w+]/)\n\n# ********************\n\n# Write a method that accepts a word and returns all the words in Shakespeare.txt that follow that word.\n# In other words, words_after('to') will return an array of words which include 'be'... since Shakespeare writes \"to be\"\ndef words_after(word)\n shakespeare = File.read(File.dirname(__FILE__) + '/Shakespeare.txt')\n shakespeare.scan(Regexp.new(word + ' (\\w+)')).uniq.flatten\nend\n\n#This should be true:\n# words_after('to').include?('be')\n\t#=> true\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":29739,"numItemsPerPage":100,"numTotalItems":2976874,"offset":2973900,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1Nzc0OTk3NSwic3ViIjoiL2RhdGFzZXRzL2hvbmdsaXU5OTAzL3N0YWNrX2VkdV9ydWJ5IiwiZXhwIjoxNzU3NzUzNTc1LCJpc3MiOiJodHRwczovL2h1Z2dpbmdmYWNlLmNvIn0.w2AwuRL-okteEbVDkYrd5h4WdCLh7MqIMmNKhw03DczrHW6vcFzQnKMkq3gS3-iumLwEdhEDa2XJJmIxNkCoDA","displayUrls":true},"discussionsStats":{"closed":0,"open":0,"total":0},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}">
    blob_id
    stringlengths
    40
    40
    language
    stringclasses
    1 value
    repo_name
    stringlengths
    4
    137
    path
    stringlengths
    2
    355
    src_encoding
    stringclasses
    31 values
    length_bytes
    int64
    11
    3.9M
    score
    float64
    2.52
    5.47
    int_score
    int64
    3
    5
    detected_licenses
    listlengths
    0
    49
    license_type
    stringclasses
    2 values
    text
    stringlengths
    11
    3.93M
    download_success
    bool
    1 class
    c63e99789402ca7ccb151f1856aebac47165e99a
    Ruby
    yuuyas222/class_inherit
    /dvd.rb
    UTF-8
    452
    3.546875
    4
    []
    no_license
    class DVD < Product # attr_reader :running_time # def initialize(name, price, running_time) # super(name, price) # @running_time = running_time # end # def to_s # "name: #{name}" #スーパークラスのprivateメソッド # end private def name "An nice product" end end # dvd = DVD.new('great movie', 1000, 120) # dvd.name # "greate movie" # dvd.price #1000 # dvd.running_time #120
    true
    2aaa11745269084a41e8545d3e7266c737c499ad
    Ruby
    snikch/suitebar.co.nz
    /app/models/diary.rb
    UTF-8
    290
    3.609375
    4
    []
    no_license
    class Diary def self.day_valid? date # Sun, thur, fri, sat date.sunday? || date.thursday? || date.friday? || date.saturday? end def self.hour_valid? date date.hour >= 18 && date.hour <= 22 end def self.minutes_valid? date [0, 30].include? date.minute end end
    true
    64174e62bcf75aeed82caab31d30253152ec44d3
    Ruby
    glooer/dip
    /module/Widgets/PoPaginator.rb
    UTF-8
    2,980
    2.65625
    3
    []
    no_license
    class PoPaginator < Qt::Widget slots "_update_index(QString)", "pages_prev()", "pages_next()", "pages_stat()", "test(int)" signals "currentPageChanged(int)" def initialize parent = 0, pages_size_select = [30, 50, 100, 500, 1000] super parent @layout = Qt::HBoxLayout.new self self.setLayout @layout @layout.setContentsMargins(0, 0, 0, 0) @pages_selecter = Qt::ComboBox.new self @pages_navig_left = Qt::ToolButton.new self do self.text = "<" end @pages_navig_right = Qt::ToolButton.new self do self.text = ">" end @pages_size_selecter = Qt::ComboBox.new self do self.insertItems(0, pages_size_select.map(&:to_s)) end @layout.addWidget @pages_navig_left @layout.addWidget @pages_selecter @layout.addWidget @pages_navig_right @layout.addItem Qt::SpacerItem.new(40, 20, Qt::SizePolicy::Expanding, Qt::SizePolicy::Minimum) @layout.addWidget @pages_size_selecter update(0) #@old_size = currentSize connect(@pages_size_selecter, SIGNAL("currentIndexChanged(QString)"), SLOT("_update_index(QString)")) connect(@pages_selecter, SIGNAL("currentIndexChanged(int)"), SLOT("pages_stat()")) connect(@pages_navig_left, SIGNAL("clicked()"), SLOT("pages_prev()")) connect(@pages_navig_right, SIGNAL("clicked()"), SLOT("pages_next()")) connect(self, SIGNAL("currentPageChanged(int)"), SLOT("test(int)")) end def test i p "test - #{i}" end def currentIndexPagesSizeSelecter @pages_size_selecter.currentIndex end def setIndexPagesSizeSelecter i @pages_size_selecter.setCurrentIndex i end def pages_stat @pages_navig_left.enabled = @pages_selecter.currentIndex < 1 ? false : true @pages_navig_right.enabled = @pages_selecter.currentIndex + 1 == countPages ? false : true emit currentPageChanged currentOffset if @pages_selecter.currentIndex > -1 end def pages_prev @pages_selecter.setCurrentIndex @pages_selecter.currentIndex - 1 end def pages_next @pages_selecter.setCurrentIndex @pages_selecter.currentIndex + 1 end def _update_index str update 0 end def pagesEnabled state @pages_navig_left.enabled = state @pages_selecter.enabled = state @pages_navig_right.enabled = state end def currentSize @pages_size_selecter.currentText.to_i end def update num, size = currentSize if num <= size @pages_selecter.clear pagesEnabled false else setPagesSelecter -(-num / size) end end def currentPage @pages_selecter.currentText.to_i - 1 end def currentOffset currentPage * currentSize end def countPages @pages_selecter.count end def setPagesSelecter count @pages_selecter.clear @pages_selecter.blockSignals true @pages_selecter.insertItems(0, Array.new(count){ |i| i.next.to_s }) @pages_selecter.blockSignals false pagesEnabled true end end
    true
    3cf5d49e92c0bfd1bea46159a52d5f171b1438f4
    Ruby
    UsmanJ/codewars
    /simple_string_validation.rb
    UTF-8
    845
    4.09375
    4
    []
    no_license
    # This method accepts a single argument, a string to be validated. # The string can be of any length and have any contents. But to be considered valid, it must have zero or more blanks followed by zero to eight numeric digits followed by, again, zero or more blanks. # If it is valid, the number within the string + 1 is returned. Otherwise, the string 'invalid' is returned. A completely blank string is considered valid, equal to zero. # ' 7 ' returns 8 # ' 2 8 ' returns 'invalid' (there mustn't be any spaces (or any other characters) between digits # ' a 8 ' returns 'invalid' # ' ' returns 1 # 'abc1' returns 'invalid' def validation string if string.empty? == true return 0 elsif string.map { |s| s =~ /\A\[ \t]+/[0-9]/[ \t]+/ } return string.to_i +1 else return "invalid" end end
    true
    61db90bb636c0b28dba67019c1d2049c1ca2a657
    Ruby
    Arcath/Markabb
    /lib/markabb/classes/tag.rb
    UTF-8
    2,560
    3.296875
    3
    []
    no_license
    module Markabb # The hash which markabb stores all the avaliable tags in Tags = {} # Inserts a tag into Markabb::Tags # # Takes 3 inputs: # name - a symbol which is used as its key # tag - a Markabb::Tag object # group - a way to group similar tags so they can all be disabled # # register_tag(:foo, Markabb::Tag, :bar) # # would produce a tags hash of # # {:bar => {:foo => Markabb::Tag}} def self.register_tag(name, tag, group = nil) tag.name = name if group tag.group = group Tags[group] ||= {} Tags[group][name] = tag else Tags[name] = tag end end # Removes a tag from Markabb::Tags # takes the symbol for the key to delete def self.remove_tag(name) Tags.delete(name) end # Used for all tags (passed to register_tag) # Takes a REGEX matcher and a string to replace it with class Tag attr_reader :matcher, :replace attr_accessor :name, :group # Creates the Markabb::Tag object def initialize(matcher, replace) if matcher.is_a? String @matcher = generate_matcher(matcher) elsif matcher.is_a? Regexp @matcher = matcher else raise 'matcher is not valid' end if replace.is_a? String @replace = replace elsif replace.is_a? Markabb::Callback @replace = false @callback = replace else raise 'Replace is not valid' end end # Runs the tag on the input string # # Takes the target string and a Markabb::Config object def run(s, config) if @replace return s.gsub(@matcher, generate_replacement(@replace, config)) elsif @callback return run_callback(s) end end private def run_callback(s) s.gsub(@matcher) { |match| @callback.run(match.scan(@matcher).first) } end def generate_replacement(replace, config) if replace.scan(/config\[:(.*?)\]/) != [] then return replace.gsub(/config\[(.*?)\]/, config[$1.to_sym]) else return replace end end def generate_matcher(tag) /\[#{tag}\](.*?)\[\/#{tag}\]/ end end end
    true
    85ed68b331797afd13e8bf3cf97ef71f9e12e17a
    Ruby
    tjlee/OpenGenesis
    /test-automation/cucumber/lib/genesis_client.rb
    UTF-8
    2,580
    2.765625
    3
    []
    no_license
    require 'httparty' require 'yaml' class GenesisClient include HTTParty attr_accessor :auth def initialize() config = YAML::load(File.open(File.dirname(__FILE__) + "/../config.yml")) @host = config["genesis"]["host"] @port = config["genesis"]["port"] @auth = {:username => config["genesis"]["user"], :password => config["genesis"]["password"] } end def ping self.class.get(genesis_path + "/") end def whoami get("/whoami") end def project_id(name) response = get('/projects') resp = JSON.parse(response.body) found = resp.select { |r| r["name"] == name } if found.size > 0 found[0]["id"] else nil end end def create_project(name, manager, description = nil) project = {:name => name, :projectManager => manager, :description => description} post('/projects', :body=>project.to_json) end def delete_project(id) delete("/projects/#{id}") end def get_template(project, template, version) get("/projects/#{project}/templates/#{template}/v#{version}") end def env_id(project, name) response = get("/projects/#{project}/envs") found = JSON.parse(response.body).select { |e| e["name"] == name } if found.size > 0 found[0]["id"] end end def create_env(id, name, template, version, variables = {}) env = {:envName => name, :templateName => template, :templateVersion => version, :variables => variables } post("/projects/#{id}/envs", :body=> env.to_json) end def delete_projects resp = get('/projects') JSON.parse(resp.body).map { |p| delete_project(p["id"]) } end def rename_env(id, env_id, newname) resp = {:environment => {:name => newname}} put("/projects/#{id}/envs/#{env_id}", :body => resp.to_json) end private def genesis_path "http://#{@host}:#{@port}" end def get(p, options = {}) options.merge!({:basic_auth => auth}) unless auth.nil? self.class.get(path(p), options) end def post(p, options = {}) options.merge!({:basic_auth => auth, :headers => {'Content-Type' => 'application/json'}}) unless auth.nil? self.class.post(path(p), options) end def put(p, options = {}) options.merge!({:basic_auth => auth, :headers => {'Content-Type' => 'application/json'}}) unless auth.nil? self.class.put(path(p), options) end def delete(p, options = {}) options.merge!({:basic_auth => auth}) if auth self.class.delete(path(p), options) end def path(p) genesis_path + '/rest/' + p end end
    true
    d17ae5896788acf195956c3be1ad152dc7a47215
    Ruby
    chaganiu/playwright-ruby-client
    /lib/playwright/route_handler_entry.rb
    UTF-8
    633
    2.890625
    3
    [ "MIT" ]
    permissive
    module Playwright class RouteHandlerEntry # @param url [String] # @param base_url [String|nil] # @param handler [Proc] def initialize(url, base_url, handler) @url_value = url @url_matcher = UrlMatcher.new(url, base_url: base_url) @handler = handler end def handle(route, request) if @url_matcher.match?(request.url) @handler.call(route, request) true else false end end def same_value?(url:, handler: nil) if handler @url_value == url && @handler == handler else @url_value == url end end end end
    true
    a2b1644da9e4e037f2e7ce838d8d8dc1f2ec9779
    Ruby
    destinf/t5008_converter
    /lib/t5008_converter.rb
    UTF-8
    1,903
    2.875
    3
    []
    no_license
    require "t5008_converter/version" require "t5008_converter/row_data" require "t5008_converter/exchange_rate/exchange_rate_api" require "csv" module T5008Converter class Error < StandardError; end REQUIRED_INPUT_COLUMNS = [ "quantity", "closing date", "currency (original)", "proceeds of disposition (original)", "adjusted cost base (original)", "outlays and expenses (original)", "currency (converted)" ] COLUMNS = REQUIRED_INPUT_COLUMNS + [ "name of fund", "gain (or loss) (original)", "proceeds of disposition (converted)", "adjusted cost base (converted)", "outlays and expenses (converted)", "gain (or loss) (converted)", "exchange rate used"] def self.generate_template(output_template_file_name) CSV.open(output_template_file_name, "wb", write_headers: true, headers: COLUMNS) do |output_csv| end end def self.fill_csv(input_file_name, output_file_name, exchange_rate_service) CSV.open(output_file_name, "wb", write_headers: true, headers: COLUMNS) do |output_csv| CSV.foreach(input_file_name, headers: true) do |row| row_data = RowData.new(row, exchange_rate_service) row_data.fill_missing_values! output_csv << convert_row_data_to_row(row_data) end end end private def self.convert_row_data_to_row(row_data) [ row_data.quantity, row_data.closing_date, row_data.original_currency, row_data.original_proceeds, row_data.original_cost, row_data.original_expenses, row_data.converted_currency, row_data.name, row_data.original_gain_loss, row_data.converted_proceeds, row_data.converted_cost, row_data.converted_expenses, row_data.converted_gain_loss, row_data.exchange_rate ] end end
    true
    5a6cc30dbc6a25649ce3249f7ee5bd560a3bc799
    Ruby
    toasterbob/review
    /challenges/ruby/hackerrank/implementation/birthday_choc.rb
    UTF-8
    320
    3.375
    3
    []
    no_license
    #!/bin/ruby def getWays(squares, d, m) total = 0 squares.each_cons(m) do |block| total += 1 if block.reduce(:+) == d end return total end n = gets.strip.to_i s = gets.strip s = s.split(' ').map(&:to_i) d,m = gets.strip.split(' ') d = d.to_i m = m.to_i result = getWays(s, d, m) print(result)
    true
    3b1cff3c4b92b323d7255fbbf2d832292076fbfa
    Ruby
    cpjolicoeur/rails
    /activesupport/lib/active_support/core_ext/object/try.rb
    UTF-8
    2,335
    3.4375
    3
    [ "Ruby", "MIT" ]
    permissive
    class Object # Invokes the public method whose name goes as first argument just like # +public_send+ does, except that if the receiver does not respond to it the # call returns +nil+ rather than raising an exception. # # This method is defined to be able to write # # @person.do_or_do_not(:name) # # instead of # # @person ? @person.name : nil # # +do_or_do_not+ returns +nil+ when called on +nil+ regardless of whether it responds # to the method: # # nil.do_or_do_not(:to_i) # => nil, rather than 0 # # Arguments and blocks are forwarded to the method if invoked: # # @posts.do_or_do_not(:each_slice, 2) do |a, b| # ... # end # # The number of arguments in the signature must match. If the object responds # to the method the call is attempted and +ArgumentError+ is still raised # otherwise. # # If +do_or_do_not+ is called without arguments it yields the receiver to a given # block unless it is +nil+: # # @person.do_or_do_not do |p| # ... # end # # Please also note that +do_or_do_not+ is defined on +Object+, therefore it won't work # with instances of classes that do not have +Object+ among their ancestors, # like direct subclasses of +BasicObject+. For example, using +do_or_do_not+ with # +SimpleDelegator+ will delegate +do_or_do_not+ to the target instead of calling it on # delegator itself. def do_or_do_not(*a, &b) if a.empty? && block_given? yield self else public_send(*a, &b) if respond_to?(a.first) end end # Same as #do_or_do_not, but will raise a NoMethodError exception if the receiving is not nil and # does not implement the tried method. def do_or_do_not!(*a, &b) if a.empty? && block_given? yield self else public_send(*a, &b) end end end class NilClass # Calling +do_or_do_not+ on +nil+ always returns +nil+. # It becomes specially helpful when navigating through associations that may return +nil+. # # nil.do_or_do_not(:name) # => nil # # Without +do_or_do_not+ # @person && [email protected]? && @person.children.first.name # # With +do_or_do_not+ # @person.do_or_do_not(:children).do_or_do_not(:first).do_or_do_not(:name) def do_or_do_not(*args) nil end def do_or_do_not!(*args) nil end end
    true
    589ba41f92d11ae37cf472086d7799380c2726b2
    Ruby
    sekoudosso82/ruby-oo-relationships-practice-blood-oath-exercise-nyc-web-012720
    /app/models/flower.rb
    UTF-8
    932
    3.609375
    4
    [ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
    permissive
    class Flower attr_accessor :name, :age, :life_motto @@all = [] def initialize(name, age, life_motto) @name = name @age = age @life_motto = life_motto @@all << self end def cults # returns an Array of this follower's cults BloodOath.all.select do |bloodOath| bloodOath.cult = self end end def join_cult(cult) # takes in an argument of a Cult instance and adds this follower to the cult's list of followers list = BloodOath.all.select do |bloodOath| bloodOath.flower == self end list << cult end def self.all @@all end def self.of_a_certain_age(age) # takes an Integer argument that is an age and returns an Array of followers who are the given age or older @@all.select do |flower| flower.age >= age end end end
    true
    f2d747f87a414c939d314cddd226fcb5e5cae5bc
    Ruby
    MaxSechz/appacademy-exercises
    /poker/spec/card_spec.rb
    UTF-8
    1,605
    3.203125
    3
    []
    no_license
    require 'rspec' require 'card.rb' describe Card do subject(:card) { Card.new(:king, :club) } it "initializes with a suit" do expect(card.suit).to eq(:club) end it "initializes with a face" do expect(card.face).to eq(:king) end describe "#>" do let(:larger_card) { Card.new(:ace, :heart) } let(:smaller_card) { Card.new(:ten, :diamond) } let(:better_suit) { Card.new(:king, :diamond)} let(:worse_suit) { Card.new(:king, :heart)} it "returns true if left card greater than right card" do expect(card > smaller_card).to eq(true) end it "returns false if left card smaller than right card" do expect(card > larger_card).to eq(false) end it "returns true if faces are equal but left card has better suit" do expect(card > worse_suit).to eq(true) end it "returns false if faces equal but left card has worse suit" do expect(card > better_suit).to eq(false) end end describe "#==" do let(:equal) { Card.new(:king, :club)} let(:different_suit) { Card.new(:king, :heart)} let(:different_face) {Card.new(:queen, :club)} let(:different) {Card.new(:ace, :diamond)} it "returns true if both face and suit are the same" do expect(card==equal).to eq(true) end it "returns false if the suits differ" do expect(card==different_suit).to eq(false) end it "returns false if the faces differ" do expect(card==different_face).to eq(false) end it "returns false if both face and suit differ" do expect(card==different).to eq(false) end end end
    true
    8507bbf30ad9b76ed6cc09564a4004f74b079280
    Ruby
    stringham/contests
    /2012-mebipenny/contest/biological-entropy/solution.rb
    UTF-8
    1,613
    3.359375
    3
    [ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
    permissive
    KEEP_RESULT = false def formatter(significant, next_code) # format with the right number of hex digits for our size result = format("%0#{significant}x", next_code) [result, next_code + 1] end def compress(line, size) # initialize dictionary = {} sequence = "" result = "" length = 0 next_code = 0 significant = size / 4 %w(A G C T).map do |dna| dictionary[dna], next_code = formatter(significant, next_code) end # for each character line.each_char do |char| next_sequence = "#{sequence}#{char}" # if the sequence with the new char is in the dict, continue if dictionary.has_key?(next_sequence) sequence = next_sequence # otherwise else # make a new code, if possible if next_code < (2 ** size) dictionary[next_sequence], next_code = formatter(significant, next_code) end # add the code to the result result += dictionary[sequence] if KEEP_RESULT length += dictionary[sequence].length # and continue with the new char sequence = char end end # finish up any loose ends result += dictionary[sequence] if KEEP_RESULT length += dictionary[sequence].length length end while line = gets line = line.strip options = [ # length of 2 bit encoding is just length of string * 2 [line.length * 2, "2"], # all the rest we are keeping track of in hex, so multiply by 4 for bits [compress(line, 4) * 4, "4"], [compress(line, 8) * 4, "8"], [compress(line, 16) * 4, "16"], [compress(line, 32) * 4, "32"], ] puts options.sort_by{|opt| opt.first}.first[1] end
    true
    6f976ba226a474143c28e667fc33e341bf020e1f
    Ruby
    codesicario/ls-intro-ruby
    /exercise_string.dir/string2.rb
    UTF-8
    310
    3.296875
    3
    []
    no_license
    words = 'car human elephant airplane' plural_words = words.split plural_words.each { |x| puts x + "s"} #another option words.split(' ').each do |word| puts word + 's' end colors = 'blue boredom pink yellow orange' puts colors.include?("yellow") puts colors.include?("purple") puts colors.include?("red")
    true
    2bbc9a103fea6bbe16f95a103839129dc9a5dce2
    Ruby
    AnaTeresaDona/Ruby-Ejercicios2-2020
    /calculo_notas2.rb
    UTF-8
    409
    3.46875
    3
    []
    no_license
    data1 = open("notas.data").readlines data = data1.map{|elemento| elemento.split(",")} def notas_mas_alta (array) n_arreglo = [] array.each do |arreglo_interno| nombres = arreglo_interno[0] notas = (arreglo_interno[1..arreglo_interno.count].map{|nota| nota.to_i}).max nombres_y_nota = [nombres,notas] n_arreglo.push(nombres_y_nota) end print n_arreglo end print notas_mas_alta(data)
    true
    fdf4c32826fa47a2c576587798adf745e0b2ce70
    Ruby
    realestate-com-au/blobby
    /lib/blobby/key_constraint.rb
    UTF-8
    723
    2.734375
    3
    []
    no_license
    # frozen_string_literal: true require "uri" module Blobby # Defines the keys we allow for use in BLOB-store implementations. # # Basically, we allow anything that would be a valid URI "path" component. # module KeyConstraint BAD_PATTERNS = [ %r{\A\Z}, # blank %r{\A/}, # leading slash %r{/\Z}, # trailing slash %r{//+}, # multiple slashes %r{:} # colon ].freeze module_function def allows?(key) BAD_PATTERNS.none? { |pattern| pattern =~ key } && URI.parse(key).path == key rescue URI::InvalidURIError false end def must_allow!(key) fail ArgumentError, "invalid key: #{key.inspect}" unless allows?(key) end end end
    true
    83e5d374d7e793ecf7639568c03437493a56ebaa
    Ruby
    sbfaulkner/byebug
    /test/commands/catch_test.rb
    UTF-8
    1,235
    2.6875
    3
    [ "BSD-2-Clause" ]
    permissive
    # frozen_string_literal: true require "test_helper" module Byebug # # Tests exception catching # class CatchTest < TestCase def test_catch_adds_catchpoints enter "catch NoMethodError" debug_code(minimal_program) assert_equal 1, Byebug.catchpoints.size end def test_catch_removes_specific_catchpoint enter "catch NoMethodError", "catch NoMethodError off" debug_code(minimal_program) assert_empty Byebug.catchpoints end def test_catch_off_removes_all_catchpoints_after_confirmation enter "catch NoMethodError", "catch off", "y" debug_code(minimal_program) assert_empty Byebug.catchpoints end def test_catch_without_arguments_and_no_exceptions_caught enter "catch" debug_code(minimal_program) check_output_includes "No exceptions set to be caught." end def test_catch_without_arguments_and_exceptions_caught enter "catch NoMethodError", "catch" debug_code(minimal_program) check_output_includes "NoMethodError: false" end def test_catch_help enter "help catch" debug_code(minimal_program) check_output_includes "cat[ch][ (off|<exception>[ off])]" end end end
    true
    cff4f887984c26146f7e80107adbf0084d48eb66
    Ruby
    myoan/sudoku
    /spec/sudoku/data_validator_spec.rb
    UTF-8
    1,227
    2.625
    3
    [ "MIT" ]
    permissive
    require "rspec" RSpec.describe Sudoku::DataValidator do describe ".validate_format!" do subject { Sudoku::DataValidator.validate_format!(data) } context "when line size less than 81" do let(:data) { Array.new(80) { "1" }.join } it { expect { subject }.to raise_error Exception } end context "when line size eq 9" do let(:data) { Array.new(81) { "1" }.join } it { expect { subject }.not_to raise_error } end context "when line size greater than 9" do let(:data) { Array.new(82) { "1" }.join } it { expect { subject }.to raise_error Exception } end end describe ".validate_data!" do subject { Sudoku::DataValidator.validate_data!(data) } context "exist whitespace" do let(:data) { [" "] } it { expect { subject }.not_to raise_error } end context "exist number (not zero)" do let(:data) { ["123456789"] } it { expect { subject }.not_to raise_error } end context "exist zero" do let(:data) { ["0"] } it { expect { subject }.to raise_error Exception } end context "exist charactor" do let(:data) { ["a"] } it { expect { subject }.to raise_error Exception } end end end
    true
    b26934d04be386827823da452889444b49051722
    Ruby
    saintaze/Hotel-Checkin
    /hotel.rb
    UTF-8
    1,078
    3.59375
    4
    []
    no_license
    class Hotel attr_reader :rooms def initialize(name = "Transalvania Inn") @name = name @rooms = { "lovelace" => Room.new(2), "hopper" => Room.new(2), "turing" => Room.new(1) } end def room_exists?(name) @rooms.has_key?(name) end def check_in(room, guest) @rooms[room].add_occupant(guest) end def has_vacanacy @rooms.all? {|k, v| v.available_space? > 0} end def list_rooms puts "------ ".brown + "Rooms and Remaining Spaces".brown + " ------".brown @rooms.each do |k, v| puts k.capitalize.cyan + " : " + v.available_space?.to_s.brown end puts ("=" * 40).brown end def list_rooms_with_names puts "---------- ".brown + "Rooms and Occupants".brown + " ---------".brown @rooms.each do |k, v| print k.capitalize.cyan + " : "; puts v.occupants.to_s.brown end puts ("=" * 40).brown end def validate_room_name(room_name) until @rooms.has_key?(room_name) print "Enter a valid room name!" room_name = gets.chomp.downcase end room_name end end
    true
    621368d5984ae879a4cb7530c7a799f61d6b9160
    Ruby
    Hansen-Nick/RB101
    /101-109_practice_problems/easy_2/greeting.rb
    UTF-8
    188
    3.640625
    4
    []
    no_license
    print "What is your name? " name = gets.chomp! if name.split('').include?("!") name.gsub!("!", '') puts "HELLO #{name.upcase}. WHY ARE WE SCREAMING?" else puts "Hello #{name}." end
    true
    c466072bee36789bfb2ca23a6de4ca9545c2fc86
    Ruby
    BWStearns/Chess
    /Chess_piece.rb
    UTF-8
    3,467
    3.375
    3
    []
    no_license
    # Assumptions # => White is on the bottom of the board (high indexes) # => White moves first # # require 'debugger' class Piece attr_accessor :board, :pos, :color BOARD_RANGE = (0..7).to_a CARDINAL_DELTA = [[0,1], [1,0], [-1,0], [0,-1]] DIAG_DELTA = [[1,1], [-1,-1], [1,-1], [-1,1]] COMP_DELTA = CARDINAL_DELTA + DIAG_DELTA def initialize(board = nil, pos, color)# color = :b/:w @board, @pos, @color = board, pos, color board[pos] = self end private def on_board?(move) move.all? { |coord| BOARD_RANGE.include?(coord) } end end class SlidingPiece < Piece private def possible_slides(deltas) #NEED to refactor moves = [] deltas.each do |delta| potential_move = pos.add_delta(delta) next unless on_board?(potential_move) target = board[potential_move] while on_board?(potential_move) && (target.nil? || target.color != self.color) moves << potential_move.dup break if (target != nil && target.color != self.color) potential_move.add_delta!(delta) target = board[potential_move] if on_board?(potential_move) end end moves end end class Castle < SlidingPiece def possible_moves possible_slides(CARDINAL_DELTA) end end class Bishop < SlidingPiece def possible_moves possible_slides(DIAG_DELTA) end end class Queen < SlidingPiece def possible_moves possible_slides(COMP_DELTA) end end class Pawn < Piece attr_accessor :moved KILLDELTA = [[0,-1],[0,1]] def initialize(board, pos, color) super(board, pos, color) @moved = false # move to main class if castling end def possible_moves regular_move + double_move + kill_move end private def regular_move color == :w ? [[(pos[0] - 1),(pos[1])]] : [[(pos[0] + 1),(pos[1])]] end def double_move #prevent if blocked return [] if moved moved = true color == :w ? [[(pos[0] - 2),(pos[1])]] : [[(pos[0] + 2),(pos[1])]] end def kill_move #need to specify that a enemy is in kill pos # if color == :w # [[(pos[0]-1),(pos[1]+1)],[(pos[0]-1),(pos[1]-1)]].keep_if do |target| # (board[target].class != nil) && (board[target].color == :b) # end #white pawn # else # [[(pos[0]+1),(pos[1]+1)],[(pos[0]+1),(pos[1]-1)]].keep_if do |target| # (board[target].class != nil) && (board[target].color == :w) # end #black pawn # end [] end def kill_move kill_targets = color == :w ? [[-1,1],[-1,-1]] : [[1,1],[1,-1]] kill_targets.map!.with_index {|target| target.add_delta(pos)} kill_targets.keep_if do |square| (board[square] != nil) && (board[square].color != color) end end end class SteppingPiece < Piece private def in_range_moves(deltas) #possibly move to main class if needed deltas.map { |x, y| [self.pos[0]+x, self.pos[1]+y] }.keep_if do |move| on_board?(move) end end end class Knight < SteppingPiece KNIGHT_DELTA = [1,2,-1,-2].permutation(2).to_a.keep_if {|x,y| x != -y } def possible_moves in_range_moves(KNIGHT_DELTA)#narrow to moves that are legal end end class King < SteppingPiece def possible_moves in_range_moves(COMP_DELTA) end end class Array def add_delta(delta, &prc) self.dup.add_delta!(delta, &prc) end def add_delta!(delta, &prc) prc = Proc.new{ |x,y| x + y } unless prc self.each_with_index { |item,index| self[index] = prc.call(item,delta[index]) } end end
    true
    8c1910a4db0c99a73162b66670eb090203b5cadc
    Ruby
    omahacodeschool/event-attendance
    /services/meetup.rb
    UTF-8
    3,815
    3.484375
    3
    []
    no_license
    # Wrapper for the information about one Meetup event, from the Meetup API. # This class is the bridge between an event from Meetup and an event in our # database--handling transformation of data as needed. class Meetup # event_info - api result converted to json hash # # itializing a meetup event will automatically add the event to the event table, # and delete the original entry if it already existed def initialize(event_info) @event_info = event_info @id = @event_info["id"] overwriteEntry save_to_events end # this is called by the controller, ultimately runs all functions in this class # # main purpose of this function is to loop through each meetup group # will access the api for each group and get the events # ultimately loads all events into the event table in the database def Meetup.groups meetups = $database.all("meetups") meetups.each do |group| events(group["url"]) end end # Accesses the meetup API and makes a Meetup object for each event # # group - the slug for the group meetup url # # def Meetup.events(group) response_as_array = JSON.parse(Meetup.response(group)) if response_as_array != [] response_as_array.map do |e| Meetup.new(e) end end end # Get events for a group from the Meetup api # # group - the slug for the group meetup url # # returns the api response as a String def Meetup.response(group) uri = URI('https://api.meetup.com/' + group + '/events') Net::HTTP.get(uri) end # Checks if an event is already in the database and delete it if so # # Returns nothing, this is necessary to be able to update event info def overwriteEntry if $database.checkExistenceOf("events", "id" , @id) $database.deleteRow("events", "id = '#{@id}'") end end # adds event to the event table of the database def save_to_events Event.create({ :id => @id, :title => title, :group_name => group_name, :time => time, :address => address, :location => location, :link => link, :date => date, :description => description }) end # removes ' from names since they are difficult to insert in sql # # returns group name def group_name name = @event_info["group"]["name"] name.gsub(/'/, "") end # returns event title def title @event_info["name"] end # returns event date as yyyy-mm-dd def date d = Time.at(@event_info["time"]/1000) date = d.strftime('%F') end # returns event time as hh:mm pm/am def time d = Time.at(@event_info["time"]/1000) time = d.strftime('%I:%M %p') end # returns event location or tbd if none provided def location if @event_info["venue"] return @event_info["venue"]["name"] else return "TBD" end end # returns event address or empty string if none provided def address if @event_info["venue"] return @event_info["venue"]["address_1"] else return "" end end # returns full link url to event def link @event_info["link"] end # returns the first 2 sentences of the description def description cleanedDescription = cleanDescription return shorten(cleanedDescription) end private def cleanDescription if @event_info['description'] # Removes all html tags clean = @event_info["description"].gsub(/<(.*?)>/, "") # Removes unicode cleaner = clean.gsub(/\\u\d{4}/, "") # Removes ' cleanest = cleaner.gsub("'","") else @event_info["description"] = "No description" end end def shorten(cleanedDescription) # Gets the first two sentences return cleanedDescription.slice!(/\A[^.||!||?]+[.||!||?][^.||!||?]+[.||!||?]/) end end
    true
    3ac334e3ce127642560a173f31f71595290052e7
    Ruby
    SupahNickie/WorkingPortfolio
    /test/features/project_test.rb
    UTF-8
    2,626
    2.609375
    3
    []
    no_license
    require "test_helper" # SAD PATH FOR VISITORS feature "a project cannot be created by a non-user" do scenario "a site visitor doesn't see the controls to make a new post" do # Given that some malicious user goes to my site # When they try to change anything to my projects listing visit projects_path # Then they can't find the controls page.wont_have_content "Edit" page.wont_have_content "Destroy" page.wont_have_content "New Project" end scenario "a site visitor gets rejected by Pundit if they try to hack around" do # Given that that malicious douchebag tries to hack to the proper URL # When they try to do anything, then Pundit doesn't let them visit edit_project_path(projects(:project1)) page.must_have_content "You are not authorized to perform this action." visit new_project_path page.must_have_content "You are not authorized to perform this action." end end # HAPPY PATH FOR THE ADMIN feature "a project can be CRUD'd by the site admin" do scenario "the admin can post a new project" do # Given the admin is signed in sign_in_user # When he visits the proper URL to create a new project and fills out valid data visit new_project_path fill_in "Title", with: "Test project name" fill_in "Technologies used", with: "Tech" fill_in "Body", with: "Test body" click_on "Create Project" # The new project should be listed page.must_have_content "Test project name" page.must_have_content "Tech" page.must_have_content "Test body" end scenario "the admin can edit an existing project" do # Given the admin is signed in sign_in_user # When he tries to edit an existing project visit edit_project_path(projects(:project1)) fill_in "Title", with: "Changed title" fill_in "Technologies used", with: "Changed tech" fill_in "Body", with: "Changed body" click_on "Update Project" # Then the page should reflect that change page.must_have_content "Changed title" page.must_have_content "Changed tech" page.must_have_content "Changed body" end scenario "the admin can destroy an existing project" do # Given the admin is signed in sign_in_user # When he tries to delete an existing project visit projects_path page.find("tr#project_#{projects(:project1).id}").click_on "Destroy" # Then the project is deleted page.wont_have_content "Test project" page.wont_have_content "Tech stuff" page.wont_have_content "Test body" end end
    true
    53bd66f613418e5353a1061578bbfba53a70b667
    Ruby
    Alex-Linhares/bongard_problem_generator
    /spec/grid_spec.rb
    UTF-8
    15,865
    2.765625
    3
    []
    no_license
    # Author:: Max Craigie (@MaxCraigie) # Copyright:: Copyright (c) 2017 Max Craigie # License:: Attribution-NonCommercial 3.0 Australia (CC BY-NC 3.0 AU) require_relative '../grid.rb' describe Bongard::Grid do describe '#initialize' do it 'fails if the cell data does not match the size' do cells = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] expect { Bongard::Grid.new(cells, 4) }.to raise_error CellDataShapeError end it 'fails if the cell data is incomplete' do cells = [[1, 2, 3], [4, 5, 6], [7, 8]] expect { Bongard::Grid.new(cells, 3) }.to raise_error CellDataShapeError end it 'fails if the cell data is incomplete' do cells = [[1, 2], [4, 5], [7, 8]] expect { Bongard::Grid.new(cells, 3) }.to raise_error CellDataShapeError end it 'fails if the cell data is incomplete' do cells = [[1, 2, 3], [4, 5, 6]] expect { Bongard::Grid.new(cells, 3) }.to raise_error CellDataShapeError end it 'fails if the cell data contains nil' do cells = [[1, 2, 3], [4, nil, 6], [7, 8, 9]] expect { Bongard::Grid.new(cells, 3) }.to raise_error CellDataNilError end it 'fails if the cell data contains nil' do cells = [[1, 2, 3], [4, 5, 6], [7, 8, 9], nil] expect { Bongard::Grid.new(cells, 3) }.to raise_error CellDataNilError end it 'fails if the cell data contains nil' do cells = [nil, [4, 5, 6], [7, 8, 9]] expect { Bongard::Grid.new(cells, 3) }.to raise_error CellDataNilError end it 'fails if the size is less than 3' do cells = [[1, 2], [3, 4]] expect { Bongard::Grid.new(cells, 2) }.to raise_error BelowMinimumSizeError end it 'fails if the size is less than 3' do cells = [[1]] expect { Bongard::Grid.new(cells, 1) }.to raise_error BelowMinimumSizeError end end describe '#each' do it 'visits all cells once' do cells = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] grid = Bongard::Grid.new(cells, 3) tally = Hash.new(0) grid.each do |cell| tally[cell.value] += 1 end expect(tally).to eq({ 1 => 1, 2 => 1, 3 => 1, 4 => 1, 5 => 1, 6 => 1, 7 => 1, 8 => 1, 9 => 1, }) end end describe '#size' do it 'returns the size' do cells = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] grid = Bongard::Grid.new(cells, 3) expect(grid.size).to eq(3) end it 'returns the size' do cells = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] grid = Bongard::Grid.new(cells, 4) expect(grid.size).to eq(4) end end describe '#any?' do before(:all) do cells = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] @grid = Bongard::Grid.new(cells, 3) end it 'returns true if any cell matches the block' do expect(@grid.any? { |c| c.value == 5 }).to be true end it 'returns false if no cell matches the block' do expect(@grid.any? { |c| c.value == 0 }).to be false end end describe '#all?' do before(:all) do cells = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] @grid = Bongard::Grid.new(cells, 3) end it 'returns true if all cells match the block' do expect(@grid.all? { |c| c.value > 0 }).to be true end it 'returns false if any cell does not match the block' do expect(@grid.all? { |c| c.value != 2 }).to be false end end describe '#find' do it 'returns an array of cells that meet the block criteria' do cells = [[1, 2, 3], [5, 5, 5], [7, 8, 9]] grid = Bongard::Grid.new(cells, 3) find_all_results = grid.find_all { |c| c.value == 5 }.map { |c| c.value } expect(find_all_results).to eq([5, 5, 5]) end it 'returns an array of cells that meet the block criteria' do cells = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] grid = Bongard::Grid.new(cells, 3) find_all_results = grid.find_all { |c| c.value == 0 }.map { |c| c.value } expect(find_all_results).to be_empty end end describe '#count' do it 'returns the number of cells that meet the block criteria' do cells = [[1, 2, 3], [5, 5, 5], [7, 8, 9]] grid = Bongard::Grid.new(cells, 3) expect(grid.count { |c| c.value == 5 }).to eq(3) end it 'returns the number of cells that meet the block criteria' do cells = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] grid = Bongard::Grid.new(cells, 3) expect(grid.count { |c| c.value == 5 }).to eq(1) end end describe '#cell_at' do before(:all) do cells = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] @grid = Bongard::Grid.new(cells, 3) end it 'gets the cell at the specified position' do expect(@grid.cell_at(1, 1).value).to eq(1) end it 'gets the cell at the specified position' do expect(@grid.cell_at(3, 3).value).to eq(9) end it 'returns nil if you specify a cell that does not exist' do expect(@grid.cell_at(0, 0)).to be_nil end it 'returns nil if you specify a cell that does not exist' do expect(@grid.cell_at(0, 1)).to be_nil end it 'returns nil if you specify a cell that does not exist' do expect(@grid.cell_at(4, 0)).to be_nil end it 'returns nil if you specify a cell that does not exist' do expect(@grid.cell_at(4, 4)).to be_nil end end describe '#cells_in_row' do before(:all) do cells = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] @grid = Bongard::Grid.new(cells, 3) end it 'returns an array containing all the cells in the specified row' do results = @grid.cells_in_row(1).map { |c| c.value } expect(results).to eq([1, 2, 3]) end it 'returns an array containing all the cells in the specified row' do results = @grid.cells_in_row(3).map { |c| c.value } expect(results).to eq([7, 8, 9]) end it 'returns nil if you specify a row that does not exist' do expect(@grid.cells_in_row(0)).to be_nil end it 'returns nil if you specify a row that does not exist' do expect(@grid.cells_in_row(4)).to be_nil end end describe '#cells_in_col' do before(:all) do cells = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] @grid = Bongard::Grid.new(cells, 3) end it 'returns an array containing all the cells in the specified col' do results = @grid.cells_in_col(1).map { |c| c.value } expect(results).to eq([1, 4, 7]) end it 'returns an array containing all the cells in the specified col' do results = @grid.cells_in_col(3).map { |c| c.value } expect(results).to eq([3, 6, 9]) end it 'returns nil if you specify a col that does not exist' do expect(@grid.cells_in_col(0)).to be_nil end it 'returns nil if you specify a col that does not exist' do expect(@grid.cells_in_col(4)).to be_nil end end describe '#edge_cells' do it 'returns an array containing all the cells at the edge' do cells = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] grid = Bongard::Grid.new(cells, 3) results = grid.edge_cells.map { |c| c.value }.sort expect(results).to eq([1, 2, 3, 4, 6, 7, 8, 9]) end it 'returns an array containing all the cells at the edge' do cells = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] grid = Bongard::Grid.new(cells, 4) results = grid.edge_cells.map { |c| c.value }.sort expect(results).to eq([1, 2, 3, 4, 5, 8, 9, 12, 13, 14, 15, 16]) end end describe '#corner_cells' do it 'returns an array containing all corner cells' do cells = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] grid = Bongard::Grid.new(cells, 3) results = grid.corner_cells.map { |c| c.value }.sort expect(results).to eq([1, 3, 7, 9]) end it 'returns an array containing all corner cells' do cells = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] grid = Bongard::Grid.new(cells, 4) results = grid.corner_cells.map { |c| c.value }.sort expect(results).to eq([1, 4, 13, 16]) end end describe '#center_cell' do it 'returns the center cell if the grid size is odd' do cells = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] grid = Bongard::Grid.new(cells, 3) expect(grid.center_cell.value).to eq(5) end it 'returns nil if the grid size is even' do cells = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] grid = Bongard::Grid.new(cells, 4) expect(grid.center_cell).to be_nil end end describe '#walk_dir (#walk_horizontal #walk_vertical)' do before(:all) do cells = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] @grid = Bongard::Grid.new(cells, 4) end it 'walks left 1' do starting_cell = @grid.cell_at(2, 1) destination = @grid.walk_horizontal(starting_cell, -1) expect(destination.value).to eq(1) end it 'walks right 1' do starting_cell = @grid.cell_at(1, 1) destination = @grid.walk_horizontal(starting_cell, 1) expect(destination.value).to eq(2) end it 'walks up 1' do starting_cell = @grid.cell_at(2, 2) destination = @grid.walk_vertical(starting_cell, -1) expect(destination.value).to eq(2) end it 'walks down 1' do starting_cell = @grid.cell_at(3, 3) destination = @grid.walk_vertical(starting_cell, 1) expect(destination.value).to eq(15) end it 'walks left 3' do starting_cell = @grid.cell_at(4, 1) destination = @grid.walk_horizontal(starting_cell, -3) expect(destination.value).to eq(1) end it 'walks right 3' do starting_cell = @grid.cell_at(1, 1) destination = @grid.walk_horizontal(starting_cell, 3) expect(destination.value).to eq(4) end it 'walks up 3' do starting_cell = @grid.cell_at(3, 4) destination = @grid.walk_vertical(starting_cell, -3) expect(destination.value).to eq(3) end it 'walks down 3' do starting_cell = @grid.cell_at(1, 1) destination = @grid.walk_vertical(starting_cell, 3) expect(destination.value).to eq(13) end it 'walks off-grid on the left by 1' do starting_cell = @grid.cell_at(1, 1) destination = @grid.walk_horizontal(starting_cell, -1) expect(destination).to be_nil end it 'walks off-grid on the right by 1' do starting_cell = @grid.cell_at(4, 2) destination = @grid.walk_horizontal(starting_cell, 1) expect(destination).to be_nil end it 'walks off-grid from the top by 1' do starting_cell = @grid.cell_at(2, 1) destination = @grid.walk_vertical(starting_cell, -1) expect(destination).to be_nil end it 'walks off-grid from the bottom by 1' do starting_cell = @grid.cell_at(2, 4) destination = @grid.walk_vertical(starting_cell, 1) expect(destination).to be_nil end it 'walks off-grid on the left by 2' do starting_cell = @grid.cell_at(1, 1) destination = @grid.walk_horizontal(starting_cell, -2) expect(destination).to be_nil end it 'walks off-grid on the right by 2' do starting_cell = @grid.cell_at(4, 1) destination = @grid.walk_horizontal(starting_cell, 2) expect(destination).to be_nil end it 'walks off-grid from the top by 2' do starting_cell = @grid.cell_at(3, 1) destination = @grid.walk_vertical(starting_cell, -2) expect(destination).to be_nil end it 'walks off-grid from the bottom by 2' do starting_cell = @grid.cell_at(4, 4) destination = @grid.walk_vertical(starting_cell, 2) expect(destination).to be_nil end end describe '#match?' do before(:all) do cells = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] @grid = Bongard::Grid.new(cells, 4) end it 'returns true if the pattern exists' do expect(@grid.match?('(?1)>(R2,?3)>(D1,?7)>(L1,?6)')).to be true end it 'returns false if the pattern does not exist' do expect(@grid.match?('(?1)>(R2,?1)')).to be false end it 'returns true if the pattern exists' do expect(@grid.match?('(?2)>(R2,?4)')).to be true end it 'returns false if the pattern does not exist' do expect(@grid.match?('(?2)>(R2,?0)')).to be false end it 'returns true if the pattern exists' do expect(@grid.match?('(?2)>(D1,?6)')).to be true end end describe '#==' do before(:all) do @cells1 = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] @grid1 = Bongard::Grid.new(@cells1, 4) end it 'is true if the grids have the same values for all cells' do same_grid = Bongard::Grid.new(@cells1, 4) expect(@grid1).to eq(same_grid) end it 'is false if the grids do not have the same values for all cells' do cells2 = [[1, 5, 9, 13], [2, 6, 10, 14], [3, 7, 11, 15], [4, 8, 12, 16]] different_grid = Bongard::Grid.new(cells2, 4) expect(@grid1).not_to eq(different_grid) end end # describe '#to_json' do # it 'converts the grid object to JSON' do # cells = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] # grid = Bongard::Grid.new(cells, 4) # grid_as_json = '[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]' # expect(grid.to_json).to eq(grid_as_json) # end # end describe '#rotate' do before(:all) do cells1 = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] @starting_grid = Bongard::Grid.new(cells1, 4) cells2 = [[13, 9, 5, 1], [14, 10, 6, 2], [15, 11, 7, 3], [16, 12, 8, 4]] @rotated_right_1 = Bongard::Grid.new(cells2, 4) cells3 = [[16, 15, 14, 13], [12, 11, 10, 9], [8, 7, 6, 5], [4, 3, 2, 1]] @rotated_right_2 = Bongard::Grid.new(cells3, 4) cells4 = [[4, 8, 12, 16], [3, 7, 11, 15], [2, 6, 10, 14], [1, 5, 9, 13]] @rotated_right_3 = Bongard::Grid.new(cells4, 4) end it 'returns a copy of the grid rotated once clockwise' do expect(@starting_grid.rotate(:clockwise, 1)).to eq(@rotated_right_1) end it 'returns a copy of the grid rotated twice clockwise' do expect(@starting_grid.rotate(:clockwise, 2)).to eq(@rotated_right_2) end it 'returns a copy of the grid rotated once anticlockwise' do expect(@starting_grid.rotate(:anticlockwise, 1)).to eq(@rotated_right_3) end it 'returns a copy of the grid rotated twice anticlockwise' do expect(@starting_grid.rotate(:anticlockwise, 2)).to eq(@rotated_right_2) end end describe '#mirror' do before(:all) do cells_1a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] @grid_1a = Bongard::Grid.new(cells_1a, 3) cells_1b = [[7, 8, 9], [4, 5, 6], [1, 2, 3]] @grid_1b = Bongard::Grid.new(cells_1b, 3) cells_1c = [[3, 2, 1], [6, 5, 4], [9, 8, 7]] @grid_1c = Bongard::Grid.new(cells_1c, 3) cells_2a = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] @grid_2a = Bongard::Grid.new(cells_2a, 4) cells_2b = [[13, 14, 15, 16], [9, 10, 11, 12], [5, 6, 7, 8], [1, 2, 3, 4]] @grid_2b = Bongard::Grid.new(cells_2b, 4) cells_2c = [[4, 3, 2, 1], [8, 7, 6, 5], [12, 11, 10, 9], [16, 15, 14, 13]] @grid_2c = Bongard::Grid.new(cells_2c, 4) end it 'returns a copy of the grid mirrored vertically' do expect(@grid_1a.mirror(:vertical)).to eq(@grid_1b) end it 'returns a copy of the grid mirrored horizontaly' do expect(@grid_1a.mirror(:horizontal)).to eq(@grid_1c) end it 'returns a copy of the grid mirrored vertically' do expect(@grid_2a.mirror(:vertical)).to eq(@grid_2b) end it 'returns a copy of the grid mirrored horizontaly' do expect(@grid_2a.mirror(:horizontal)).to eq(@grid_2c) end end end
    true
    13a23bd73a18970e82ea681dc80c67fc7b5610fd
    Ruby
    Odin94/RubyCollision
    /Rectangle.rb
    UTF-8
    1,659
    3.296875
    3
    []
    no_license
    class Rectangle def initialize(x, y, w, h) @x = x @y = y @w = w @h = h end attr_accessor :x, :y, :w, :h def handle_collisions(collidingRectangles) for rect in collidingRectangles resolve_x_collision(rect) resolve_y_collision(rect) resolve_xy_collosion(rect) # for diagonal movement it's possible to enter another rect by one pixel without this end end def resolve_x_collision(rect) while rectv_rectv_collide?(@x + @vel_x, @y, @w, @h, rect.x, rect.y, rect.w, rect.h) if @vel_x == 0 break end if @vel_x.abs < 1.1 @vel_x = abs_decrease_by(@vel_x, 0.5) # prevents leaving 1 pixel space between a rect and this else @vel_x = abs_decrease(@vel_x) end end end def resolve_y_collision(rect) while rectv_rectv_collide?(@x, @y + @vel_y, @w, @h, rect.x, rect.y, rect.w, rect.h) if @vel_y == 0 break end if @vel_y.abs < 1.1 then @vel_y = abs_decrease_by(@vel_y, 0.5) # prevents leaving 1 pixel space between a rect and this else @vel_y = abs_decrease(@vel_y) end end end def resolve_xy_collosion(rect) while rectv_rectv_collide?(@x + @vel_x, @y + @vel_y, @w, @h, rect.x, rect.y, rect.w, rect.h) if @vel_y == 0 and @vel_x == 0 break end @vel_y = abs_decrease(@vel_y) @vel_x = abs_decrease(@vel_x) end end end
    true
    1850a0a4e1d9b7c3a8786ee1acf233b591b6a2d4
    Ruby
    bluefish733/learn-and-share
    /hello.rb
    UTF-8
    155
    2.640625
    3
    []
    no_license
    #! /usr/bin/env ruby def hello puts 'hello world!' puts 'test rebase' puts 'zjl - 1' puts 'zjll - 2' puts 'zjl -3' puts 'zjl -4' end hello()
    true
    7866be20a1fb2a55ba8e1597411537077d5fa03b
    Ruby
    inDuberitably/WrightCSHelpRoom
    /bots/Email/EmailRequestForm.rb
    UTF-8
    308
    2.546875
    3
    []
    no_license
    class EmailRequestForm class << self attr_accessor :sender, :email_id, :original_msg, :hours, :completed, :total_hours def to_s return "Sender:#{self.sender}\nEmail_id:#{self.email_id}\nOriginal_msg:#{self.original_msg}\nHours:#{self.hours}\nCompleted?:#{self.completed}\n" end end end
    true
    eb7173e65f441849bfa2f7ad5260eecec745010b
    Ruby
    chendry/LSY201
    /test.rb
    UTF-8
    438
    2.859375
    3
    []
    no_license
    #!/usr/bin/env ruby require 'serialport' serial = SerialPort.new("/dev/tty.usbmodem3a21", 38400) buffer = [] while true buffer << serial.readbyte buffer = buffer.last(2) if buffer == [ 0xFF, 0xD8 ] while buffer.last(2) != [ 0xFF, 0xD9 ] buffer << serial.readbyte end File.open("test.jpg", "w") do |f| f.write buffer.pack("C*") end puts "wrote #{buffer.length} bytes" buffer = [] end end
    true
    d54e758b41a503b75f3ceff23d7e4c9968470512
    Ruby
    bantic/first-word-api
    /app/models/poll_item.rb
    UTF-8
    1,075
    2.671875
    3
    []
    no_license
    class PollItem < ActiveRecord::Base extend FriendlyId friendly_id :title, use: :slugged belongs_to :poll has_one :photo, dependent: :destroy def self.normalize_word(word) word.split(' ')[0].downcase.gsub(/[^a-z]+/, '') end def add_word word normalized_word = self.class.normalize_word(word) increment_list_item(normalized_word) increment_total_word_count end # Total count for all words for this poll_item def word_count (redis.get(word_count_key) || 0).to_i end # Array of tuples in desc order i.e. [ ["good", 3], ["great", 2] ] def sorted_words start = 0 stop = -1 # all options = {with_scores: true} redis.zrevrange(word_list_key, start, stop, options) end private def increment_total_word_count redis.incr(word_count_key) end def increment_list_item(list_item) amount = 1 redis.zincrby(word_list_key, amount, list_item) end def word_list_key "#{friendly_id}-word-list" end def word_count_key "#{friendly_id}-word-count" end def redis $redis end end
    true
    ba5f41d4f6fb7fd9618e24dbdac4aa52c296f818
    Ruby
    Altovate/bearded-octo-adventure
    /app/helpers/search_conditions.rb
    UTF-8
    1,537
    2.65625
    3
    []
    no_license
    # This class is used to generate search paramaters for offers class SearchConditions def initialize() @wheres = [] @values = [] end # Parse Key Value pairs and add them to the array def parse_param_string(params) # overriden in subclass end # Add where/value clauses to the array def add(where, value = nil) @wheres << where if value.instance_of?(Array) value.collect {|v| @values << v } else @values << value unless value.nil? end end # Return an array of values def conditions unless @wheres.nil? or @values.nil? [@wheres.join(" AND ")] + @values else [] end end def joins ["inner join crm_cases on crm_cases.connection_id = crm_connections.id inner join contact_infos on contact_infos.id=crm_connections.contact_info_id inner join email_addresses on email_addresses.contact_info_id=contact_infos.id inner join addresses on addresses.contact_info_id=contact_infos.id inner join phones on phones.contact_info_id=contact_infos.id inner join quoting_results on quoting_results.id=crm_cases.approved_details_id or quoting_results.id=crm_cases.quoted_details_id or quoting_results.id=crm_cases.submitted_details_id inner join carriers on carriers.id=quoting_results.carrier_id inner join crm_policy_types on crm_policy_types.id=quoting_results.policy_type_id inner join states on states.id=contact_infos.state_id inner join crm_statuses on crm_statuses.id=crm_cases.status_id"] end end
    true
    251cf4cc62ce2b9c27f61c223c074f3df6ee21ff
    Ruby
    arkency/md_pp_string_calculator
    /string_calculator_spec.rb
    UTF-8
    879
    3.09375
    3
    []
    no_license
    require 'rspec' require './string_calculator' describe StringCalculator do let(:calculator) { StringCalculator.new } specify { expect(calculator). to respond_to(:add) } specify { expect(calculator.add("")). to eql(0) } specify { expect(calculator.add("1")). to eql(1) } specify { expect(calculator.add("1,2")).to eql(3) } specify { expect(calculator.add("1,2,3,4")).to eql(10) } specify { expect(calculator.add("1\n2,3")).to eql(6) } custom_delimiters = ((33..46).to_a + (58..63).to_a).map(&:chr) custom_delimiters.map do |delimiter| specify { expect(calculator.add("//#{delimiter}\n3#{delimiter}5")).to eql(8) } end specify { expect{calculator.add("-1,-2")}.to raise_error(NegativesNotAllowed, "-1, -2")} specify { expect(calculator.add("2,1001")).to eql(2) } end
    true
    cc68a6ef735160f13db435603084c47528e57ff3
    Ruby
    birdcarrie/CacheExercise
    /MyHashMap/lib/p02_hashing.rb
    UTF-8
    567
    3.375
    3
    []
    no_license
    class Fixnum # Fixnum#hash already implemented for you end class Array def hash hash_key = self.length * 5717 hash_key = hash_key * self[-1] if self[-1].is_a?(Fixnum) hash_key = hash_key * self[0].ord if self[0].is_a?(String) hash_key end end class String def hash hash_key = self.length * 1741 hash_key = hash_key * self[-1].ord ** 2 if self[0].ord.even? hash_key = hash_key * self[0].ord ** 2 if self[0].ord.odd? hash_key = hash_key * self[self.length/2].ord hash_key end end # class Hash # def hash # end # end
    true
    767e87dd39fd883cde3865ad49db3496ff864890
    Ruby
    oliverpdahl/ttt-8-turn-online-web-sp-000
    /lib/turn.rb
    UTF-8
    1,122
    4.09375
    4
    [ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
    permissive
    def turn(board) puts "Please enter 1-9:" input = gets.strip index = input_to_index(input) if valid_move?(board, index) display_board(move(board,index)) else puts "Please enter a valid input" turn(board) end end def input_to_index(input) input = input.to_i return input - 1 end def display_board(boardIn) if boardIn == nil puts "That was an unacceptable input" else puts " #{boardIn[0]} | #{boardIn[1]} | #{boardIn[2]} " puts "-----------" puts " #{boardIn[3]} | #{boardIn[4]} | #{boardIn[5]} " puts "-----------" puts " #{boardIn[6]} | #{boardIn[7]} | #{boardIn[8]} " end end def move(boardIn, input_index, character = "X") boardIn[input_index] = character return boardIn end # code your #valid_move? method here def valid_move?(board, index) return index.between?(0,8) && !(position_taken?(board, index)) end # re-define your #position_taken? method here, so that you can use it in the #valid_move? method above. def position_taken?(board, index) spot = board[index] if spot == " " || spot == "" || spot == nil false else true end end
    true
    c9d77b1c5662673f09ea63c5dbf47ae88285f412
    Ruby
    ifad/eaco
    /lib/eaco/acl.rb
    UTF-8
    5,242
    3.078125
    3
    [ "MIT" ]
    permissive
    module Eaco ## # An ACL is an Hash whose keys are Designator string representations and # values are the role symbols defined in the Resource permissions # configuration. # # Example: # # authorize Document do # roles :reader, :editor # end # # @see Actor # @see Resource # class ACL < Hash ## # Builds a new ACL object from the given Hash representation with strings # as keys and values. # # @param definition [Hash] the ACL hash # # @return [ACL] this ACL # def initialize(definition = {}) (definition || {}).each do |designator, role| self[designator] = role.intern end end ## # Gives the given Designator access as the given +role+. # # @param role [Symbol] the role to grant # @param designator [Variadic] (see {#identify}) # # @return [ACL] this ACL # def add(role, *designator) identify(*designator).each do |key| self[key] = role end self end ## # Removes access from the given Designator. # # @param designator [Variadic] (see {#identify}) # # @return [ACL] this ACL # # @see Designator # def del(*designator) identify(*designator).each do |key| self.delete(key.to_s) end self end ## # @param name [Symbol] The role name # # @return [Set] A set of Designators having the given +role+. # # @see Designator # @see Resource # def find_by_role(name) self.inject(Set.new) do |ret, (designator, role)| ret.tap { ret.add Designator.parse(designator) if role == name } end end ## # @return [Set] all Designators in the ACL, regardless of their role. # def all self.inject(Set.new) do |ret, (designator,_)| ret.add Designator.parse(designator) end end ## # Gets a map of Actors in the ACL having the given +role+. # # This is a useful starting point for an Enterprise summary page of who is # granted to access a resource. Given that actor resolution is dynamic and # handled by the application's Designators implementation, you can rely on # your internal organigram APIs to resolve actual people out of positions, # groups, department of assignment, etc. # # @param name [Symbol] The role name # # @return [Hash] keyed by designator with Set of Actors as values # # @see Actor # @see Resource # def designators_map_for_role(name) find_by_role(name).inject({}) do |ret, designator| actors = designator.resolve ret.tap do ret[designator] ||= Set.new ret[designator].merge Array.new(actors) end end end ## # @param name [Symbol] the role name # # @return [Set] Actors having the given +role+. # # @see Actor # @see Resource # def actors_by_role(name) find_by_role(name).inject(Set.new) do |set, designator| set |= Array.new(designator.resolve) end.to_a end ## # Pretty prints this ACL in your console. # def inspect "#<#{self.class.name}: #{super}>" end alias pretty_print_inspect inspect ## # Pretty print for +pry+. # def pretty_inspect "#{self.class.name}\n#{super}" end protected ## # There are three ways of specifying designators: # # * Passing an +Designator+ instance obtained from somewhere else: # # >> designator # => #<Designator(User) value:42> # # >> resource.acl.add :reader, designator # => #<Resource::ACL {"user:42"=>:reader}> # # * Passing a designator type and an unique ID valid in the designator's # namespace: # # >> resource.acl.add :reader, :user, 42 # => #<Resource::ACL {"user:42"=>:reader}> # # * Passing a designator type and an Actor instance, will add all # designators of the given type owned by the Actor. # # >> actor # => #<User id:42 name:"Ethan Siegel"> # # >> actor.designators # => #<Set:{ # | #<Designator(User) value:42>, # | #<Designator(Group) value:"astrophysicists">, # | #<Designator(Group) value:"medium bloggers"> # | }> # # >> resource.acl.add :editor, :group, actor # => #<Resource::ACL { # | "group:astrophysicists"=>:editor, # | "group:medium bloggers"=>:editor # | } # # @param designator [Designator] the designator to grant # @param actor_or_id [Actor] or [String] the actor # def identify(designator, actor_or_id = nil) if designator.is_a?(Eaco::Designator) [designator] elsif designator && actor_or_id.respond_to?(:designators) designator = designator.to_sym actor_or_id.designators.select {|d| d.type == designator} elsif designator.is_a?(Symbol) [Eaco::Designator.make(designator, actor_or_id)] else raise Error, <<-EOF Cannot infer designator from #{designator.inspect} and #{actor_or_id.inspect} EOF end end end end
    true
    8d0350b8b920b50471366ff83f7b9c19abbbb841
    Ruby
    robhurring/bingo
    /app/models/move.rb
    UTF-8
    255
    3.03125
    3
    []
    no_license
    class Move def initialize(name, word, found = true) @name, @word, @found = name, word, found @hash = Digest::MD5.hexdigest(word) end def to_h { name: @name, found: @found, word: @word, hash: @hash } end end
    true
    f3e1398163af1a4877f7e6e4d4e0cac1776b19b9
    Ruby
    Harmonickey/EnHabit
    /Core/Accounts/update_account.rb
    UTF-8
    3,519
    2.515625
    3
    []
    no_license
    #!/usr/local/bin/ruby absPath = Dir.pwd base = absPath.split("/").index("public_html") deploymentBase = absPath.split("/")[0..(base + 1)].join("/") #this will reference whatever deployment we're in $: << "#{deploymentBase}/Libraries" require 'json' require 'moped' require 'bson' require 'PasswordHash' require 'tools' def UpdateUser(isAdmin, key, userId, isLandlord, isVerified, isActive, isAdminData, username, firstName, lastName, email, phoneNumber, newPassword) mongoSession = Moped::Session.new(['127.0.0.1:27017']) # our mongo database is local mongoSession.use("enhabit") # this is our current database usrObj = Hash.new usrObj["Username"] = username usrObj["FirstName"] = firstName usrObj["LastName"] = lastName usrObj["Email"] = email usrObj["PhoneNumber"] = phoneNumber usrObj["Password"] = PasswordHash.createHash(newPassword) unless newPassword.nil? usrObj["IsAdmin"] = (isAdminData.nil? ? false : isAdminData) usrObj["IsActive"] = (isActive.nil? ? true : isActive) usrObj["IsVerified"] = (isVerified.nil? ? true : isVerified) usrObj["IsLandlord"] = (isLandlord.nil? ? false : isLandlord) queryObj = Hash.new queryObj["Username"] = username if isAdmin queryObj[key] = userId unless isAdmin retMsg = "" #Username has a unique constraint attached, so we want to catch the raised error just in case begin mongoSession.with(safe: true) do |session| account = session[:accounts].find(queryObj).to_a # this is a safe query because it is assumed UpdateListing.rb is called # on an existing account if (account[0]["LandlordId"].nil? and isLandlord) usrObj["LandlordId"] = SecureRandom.uuid landlordObj = Hash.new landlordObj["Landlord"] = usrObj["Username"] session[:listings].find(landlordObj).update_all('$set' => {"LandlordId" => usrObj["LandlordId"]}) end session[:accounts].find(queryObj).update('$set' => usrObj) end retMsg = "Okay" rescue Moped::Errors::OperationFailure => e if e.message.include? "enhabit.accounts.$Email_1" retMsg = "That email is already registered with another user!" end end mongoSession.disconnect return retMsg end begin data = JSON.parse(ARGV[0].delete('\\')) unless ARGV[0].empty? #we are checking this because it's an optional thing on the UI newPassword = data["Password"] if not data["Password"].nil? and not data["Password"].empty? isLandlord = data["IsLandlord"].to_b if not data["IsLandlord"].nil? and not data["IsLandlord"].empty? isVerified = data["IsVerified"].to_b if not data["IsVerified"].nil? and not data["IsVerified"].empty? isActive = data["IsActive"].to_b if not data["IsActive"].nil? and not data["IsActive"].empty? isAdminData = data["IsAdmin"].to_b if not data["IsAdmin"].nil? and not data["IsAdmin"].empty? id = ARGV[1].split(",")[0] unless ARGV[1].empty? key = ARGV[2] unless ARGV[2].empty? isAdmin = ARGV[3].to_b unless ARGV[3].empty? puts UpdateUser(isAdmin, key, id, isLandlord, isVerified, isActive, isAdminData, data["Username"], data["FirstName"], data["LastName"], data["Email"], data["PhoneNumber"], newPassword) rescue Exception => e puts e.inspect end
    true
    83c59dac15464b893bb71af50c3e29d45071386e
    Ruby
    ErickLedesma/E7CP2A1
    /ejercicio1.rb
    UTF-8
    1,259
    4.5625
    5
    []
    no_license
    # Dado el array: # a = [1, 2, 3, 9, 1, 4, 5, 2, 3, 6, 6] # 1. Utilizando map aumentar el valor de cada elemento del array en 1. # 2. Utilizando map convertir todos los valores a float. # 3. Utilizando map convertir todos los valores a string. # 4. Utilizando reject descartar todos los elementos menores a 5 en el array. # 5. Utilizando select descartar todos los elementos mayores a 5 en el array. # 6. Utilizando inject obtener la suma de todos los elementos del array. # 7. Utilizando group_by agrupar todos los números por paridad (si son pares, es un # grupos, si son impares es otro grupo). # 8. Utilizando group_by agrupar todos los números mayores y menores que 6. a = [1, 2, 3, 9, 1, 4, 5, 2, 3, 6, 6] # 1 a.map! { |item| item += 1 } print a puts '' # 2 a_float = a.map { |item| item.to_f } print a_float puts '' # 3 a_string = a.map { |item| item.to_s} print a_string puts '' # 4 a_mayores = a.reject { |item| item < 5} print a_mayores puts '' # 5 a_menores = a.select { |item| item <= 5 } print a_menores puts '' # 6 a_suma = a.inject { |suma, item| suma += item} puts a_suma # 7 a_group = a.group_by { |item| item.even? } print a_group puts '' # 8 a_group = a.group_by { |item| item > 6 } print a_group puts ''
    true
    20267b98f992bde57845cbf116e4dc6bfd19ecf7
    Ruby
    pcapr-local/pcapr-local
    /lib/mu/pcap/sctp/chunk/data.rb
    UTF-8
    3,206
    2.78125
    3
    [ "MIT" ]
    permissive
    # http://www.mudynamics.com # http://labs.mudynamics.com # http://www.pcapr.net module Mu class Pcap class SCTP class Chunk class Data < Chunk FLAG_LAST_SEG = 0x01 FLAG_FIRST_SEG = 0x02 FLAG_UNORDERED = 0x04 attr_accessor :tsn, :sid, :ssn, :ppid def initialize super @type = CHUNK_DATA @tsn = 0 @sid = 0 @ssn = 0 @ppid = 0 end def self.from_bytes flags, size, bytes # Basic validation Pcap.assert(bytes.length >= 12, "Truncated data chunk header: 12 > #{bytes.length}") # Read init chunk header tsn, sid, ssn, ppid = bytes.unpack('NnnN') # Create data chunk data = Data.new data.flags = flags data.size = size data.tsn = tsn data.sid = sid data.ssn = ssn data.ppid = ppid # Save the payload data.payload_raw = data.payload = bytes[12..size - 5] # Return the result return data end def write io, ip chunk_header = [@type, @flags, @size].pack('CCn') data_header = [@tsn, @sid, @ssn, @ppid].pack('NnnN') # Write Chunk header followed by the Data chunk header and payload io.write(chunk_header) io.write(data_header) io.write(@payload_raw) # Write padding, if necessary if size < padded_size (padded_size - size).times do io.write("\x00") end end end def ordered? if 0 == @flags[2] return true else return false end end def first_segment? if 1 == @flags[1] and 0 == @flags[0] return true else return false end end def last_segment? if 0 == @flags[1] and 1 == @flags[0] return true else return false end end def complete_segment? if 1 == @flags[1] and 1 == @flags[0] return true else return false end end def to_s flags_s = '[' if ordered? flags_s += 'ordered, ' else flags_s += 'unordered, ' end if complete_segment? flags_s += 'complete segment' elsif first_segment? flags_s += 'first segment' elsif last_segment? flags_s += 'last segment' else flags_s += 'middle segment' end flags_s += ']' return "data(%s, %d, %d, %d, %d, %d, %s)" % [flags_s, @size, @tsn, @sid, @ssn, @ppid, @payload.inspect] end end # class Data end # class Chunk end # class SCTP end # class Pcap end # module Mu
    true
    02000bd715467436926036988e5f5792d9128b49
    Ruby
    ncoe/rosetta
    /Faulhabers_formula/Ruby/faulhaber.rb
    UTF-8
    1,674
    3.546875
    4
    [ "MIT" ]
    permissive
    def binomial(n,k) if n < 0 or k < 0 or n < k then return -1 end if n == 0 or k == 0 then return 1 end num = 1 for i in k+1 .. n do num = num * i end denom = 1 for i in 2 .. n-k do denom = denom * i end return num / denom end def bernoulli(n) if n < 0 then raise "n cannot be less than zero" end a = Array.new(16) for m in 0 .. n do a[m] = Rational(1, m + 1) for j in m.downto(1) do a[j-1] = (a[j-1] - a[j]) * Rational(j) end end if n != 1 then return a[0] end return -a[0] end def faulhaber(p) print("%d : " % [p]) q = Rational(1, p + 1) sign = -1 for j in 0 .. p do sign = -1 * sign coeff = q * Rational(sign) * Rational(binomial(p+1, j)) * bernoulli(j) if coeff == 0 then next end if j == 0 then if coeff != 1 then if coeff == -1 then print "-" else print coeff end end else if coeff == 1 then print " + " elsif coeff == -1 then print " - " elsif 0 < coeff then print " + " print coeff else print " - " print -coeff end end pwr = p + 1 - j if pwr > 1 then print "n^%d" % [pwr] else print "n" end end print "\n" end def main for i in 0 .. 9 do faulhaber(i) end end main()
    true
    ef3c86ef48544692906f94cfb786e655d6b98364
    Ruby
    JuliaFong/OpenApp
    /Ruby/Enumerables/enumerable.rb
    UTF-8
    7,668
    4.84375
    5
    []
    no_license
    #Enumerable Methods # In Ruby, an object enumerable is when it describes a set of # items and a method to loop over each of them # provides collection classes with several traversal and searching methods # you can mix into your classes # Enumerable module provides you with methods for # searching, traversal, and sorting colletions # you can mix in the enumerable module # array # .each # .each_with_index # string # .each_char # .each_char.with_index months = ["Jan", "Feb", "Mar", "Apr"] months.each_with_index do |ele, idx| puts ele puts idx puts "-----" end # months.each { |months| puts months} # i = 0 # while i < months.length # month = months[i] # puts month # i += 1 # end sentence = "hello world" sentence.each_char.with_index do |char, idx| puts char puts idx puts "----" end # range enumerable # (start..end).each, iterate from start to end (inclusive) # (start...end).each, iterate from start to end(excluding end) arr = ["a", "b", "c"] arr.each { |ele| puts ele } arr1 = [1, 2, 3, 4, 5] arr1.each { |ele| puts ele} [6, 7, 8, 9, 10].each { |num| puts num } puts "------" (0..11).each { |num| puts num } puts "-----------" (4...11).each { |num| puts num} puts "------" def fizzBuzz(max) arr = [] (1...max).each do |num| if num % 3 == 0 && num % 5 != 0 arr << num end if num % 3 != 0 && num % 5 == 0 arr << num end end return arr end print fizzBuzz(20) print fizzBuzz(9) puts"-------" (0..4).each { puts "hi"} 3.times { puts "hiiiii"} # Enumerable Methods people = ["Candace", "Jon", "Jose"] # iterate over elements of an array using each people.each { |person| puts person } # prints # Candace # Jon # Jose # iterate over elements of an array with index using each_with_index people.each_with_index do |person, i| puts person puts i puts "-----" end # prints # Candace # 0 # ----- # Jon # 1 # ----- # Jose # 2 # ----- # String Enumerable methods greeting = "hello" # iterate over characters of a string using each_char greeting.each_char { |char| puts char } #prints # h # e # l # l # o # iterate over characters of a string with index using each_char.with_index greeting.each_char.with_index do |char, i| puts char puts i puts "-----" end # prints # h # 0 # --- # e # 1 # --- # l # 2 # --- # l # 3 # --- # o # 4 # --- # OTHER # repeat a block using times 3.times do puts "hiiiii" end # hi # hi # hi # specify a range of numbers using (start..end) or (start...end) # including end (2..6).each {|n| puts n} puts "-----" # prints # 2 # 3 # 4 # 5 # 6 # excluding end (2...6).each {|n| puts n} # prints # 2 # 3 # 4 # 5 # Write a method to_initials that takes in a person's name # string and returns a string representing their initials. def to_initials(name) parts = name.split(" ") initials = "" parts.each { |part| initials += part[0] } return initials end puts to_initials("Kelvin Bridges") # => "KB" puts to_initials("Michaela Yamamoto") # => "MY" puts to_initials("Mary La Grange") # => "MLG" puts "-----" # Write a method first_in_array that takes in an array # and two elements, the method should return the element # that appears earlier in the array. def first_in_array(arr, el1, el2) if arr.index(el1) < arr.index(el2) return el1 else return el2 end end puts first_in_array(["a", "b", "c", "d"], "d", "b"); # => "b" puts first_in_array(["cat", "bird" ,"dog", "mouse" ], "dog", "mouse"); # => "dog" puts "-------" # Write a method abbreviate_sentence that takes in a # sentence string and returns a new sentence where # every word longer than 4 characters has all of it's # vowels removed. def abbreviate_sentence(sent) words = sent.split(" ") new_words = [] words.each do |word| if word.length > 4 new_word = abbreviate_word(word) new_words << new_word else new_words << word end end new_sent = new_words.join(" ") end def abbreviate_word(word) vowels = "aeiouy" no_vowels = "" word.each_char do |char| if !vowels.include?(char) no_vowels += char end end return no_vowels end puts abbreviate_sentence("follow the yellow brick road") puts abbreviate_sentence("what a wonderful life") puts "------" # Write a method format_name that takes in a name string # and returns the name properly capitalized. def format_name(str) parts = str.split(" ") new_parts = [] parts.each do |part| new_parts << part[0].upcase + part[1..-1].downcase end new_name = new_parts.join(" ") return new_name end puts format_name("chase WILSON") # => "Chase Wilson" puts format_name("brian CrAwFoRd scoTT") # => "Brian Crawford Scott" puts "-----------------" # Write a method is_valid_name that takes in a string and # returns a boolean indicating whether or not it is a valid name. def is_valid_name(str) parts = str.split(" ") if parts.length < 2 return false end parts.each do |part| if !is_capitalized(part) return false end end return true end def is_capitalized(word) if word[0] == word[0].upcase && word[1..-1] == word[1..-1].downcase return true else return false end end # puts is_capitalized("Bootcamp")# true # puts is_capitalized("BootCaMp")# false puts is_valid_name("Kush Patel") # => true puts is_valid_name("Daniel") # => false puts is_valid_name("Robert Downey Jr") # => true puts is_valid_name("ROBERT DOWNEY JR") # => false puts "--------" # Write a method is_valid_email that takes in a string # and returns a boolean indicating whether or not it is # a valid email address. def is_valid_email(str) parts = str.split("@") if parts.length != 2 return false end left = parts[0] right = parts[1] alpha = "abcdefghijklmnopqrstuvwxyz" left.each_char do |char| if !alpha.include?(char) return false end end if right.split(".").length == 2 return true else return false end end puts is_valid_email("[email protected]") # => true puts is_valid_email("[email protected]") # => true puts is_valid_email("jdoe@[email protected]") # => false puts is_valid_email("[email protected]") # => false puts is_valid_email("jdoegmail.com") # => false puts is_valid_email("az@email") # => false puts "-------" # Write a method reverse_words that takes in a sentence # string and returns the sentence with the order of # the characters in each word reversed. # Note that we need to reverse the order of characters in # the words, do not reverse the order of words in the sentence. def reverse_words(sent) words = sent.split(" ") new_words = [] words.each { |word| new_words << word.reverse } new_sent = new_words.join(" ") return new_sent end puts reverse_words('keep coding') # => 'peek gnidoc' puts reverse_words('simplicity is prerequisite for reliability') # => 'yticilpmis si etisiuqererp rof ytilibailer' puts "---------" # Write a method rotate_array that takes in an array and a # number. The method should return the array after # rotating the elements the specified number of times. A # single rotation takes the last element of the array and moves it to the front. def rotate_array(arr,num) num.times do ele = arr.pop arr.unshift(ele) end return arr end print rotate_array([ "Matt", "Danny", "Mashu", "Matthias" ], 1) # => [ "Matthias", "Matt", "Danny", "Mashu" ] puts print rotate_array([ "a", "b", "c", "d" ], 2) # => [ "c", "d", "a", "b" ] puts
    true
    f37b33a7c13025470ca491c1b5b3b07610af8d42
    Ruby
    GIL-GALILEO/alma-user-integration-legacy-converter
    /lib/classes/user_group.rb
    UTF-8
    2,698
    2.859375
    3
    []
    no_license
    require './lib/errors/no_group_mapping_error' # functionality for patron user_group including support for weighting class UserGroup attr_accessor :type, :alma_name, :banner_name, :weight, :institution, :exp_days def initialize(institution, campus, banner_name = nil, fs_codes = nil, class_code = nil) self.institution = institution create_group_data banner_name, fs_codes, campus, class_code copy_config_values end def heavier_than?(user_group) user_group.weight < weight end def to_s alma_name end def facstaff? type == 'facstaff' end def student? type == 'student' end private def copy_config_values if @data && @data['alma_name'] && @data['weight'] self.alma_name = @data['alma_name'] self.weight = @data['weight'].to_i self.type = @data['type'] self.exp_days = @data['exp_days'] else fail NoGroupMappingError, 'Insufficient data to properly map group, using default.' end end def create_group_data(banner_name, fs_codes, campus, class_code) @data = nil if banner_name && banner_name != '' create_from_banner banner_name, campus elsif fs_codes fail( NotImplementedError, 'FS Codes cannot be translated to User Groups if a Campus has been provided.' ) if campus create_from_fs_codes fs_codes, class_code end end def create_from_banner(banner_name, campus = nil) groups_settings = if campus campus.groups_settings else institution.groups_settings end self.banner_name = banner_name @data = groups_settings[banner_name] end def create_from_fs_codes(fs_codes, class_code) # ug students who are staff should be set as ug students if (fs_codes.include?('00') || fs_codes.include?('65')) && fs_codes.include?('02') && class_code == 'U' @data = institution.groups_settings[institution.groups_data['00']] elsif (fs_codes.include?('00') || fs_codes.include?('65')) && fs_codes.include?('02') && class_code == 'G' @data = institution.groups_settings[institution.groups_data['ZZ']] else fs_codes.each do |fs_code| next unless institution.groups_data.key? fs_code alma_name = institution.groups_data[fs_code] group_settings = institution.groups_settings[alma_name] if fs_code == '00' && (class_code == 'G' || class_code == 'P') group_settings = institution.groups_settings[institution.groups_data['ZZ']] end if !@data || group_settings['weight'] > @data['weight'] @data = group_settings end end end end end
    true
    ac14d7a48f57bb451ce14f18a445ab158247bf3e
    Ruby
    johnw188/me405
    /binary_hex_converter.rb
    UTF-8
    472
    2.71875
    3
    []
    no_license
    filename = ARGV[0] file = File.open(filename){|file| file.readlines} re='([01]{8})' binRegex = Regexp.new(re,Regexp::IGNORECASE); fullRegex = Regexp.new('(0b[01]{8})') file.each{|line| if binRegex.match(line) number = binRegex.match(line)[1].to_i(2).to_s(16) if number.length == 1 number = "0" + number end line.sub!(/0b[01]{8}/, "0x#{number}") puts line end } File.open(ARGV[0] + ".out", "wb"){|newfile| newfile.puts file }
    true
    76127d18eb7953f655995ec2eb2c375af0763dc7
    Ruby
    Malaber/AdventOfCode2020
    /code/14.rb
    UTF-8
    784
    3.140625
    3
    []
    no_license
    require_relative '../input' require_relative 'handheld/Instruction' require_relative 'handheld/Computer' lines = get_lines $PROGRAM_NAME @bitmask = "" mem = {} def apply_bitmask(value) new_value = value.dup @bitmask.split("").each_with_index do |char, index| next if char == "X" new_value[index] = char end new_value.gsub("X", "0") end lines.each do |line| if line.match(/mask/) @bitmask = line.gsub("mask = ", "").strip next end address_string, value = line.strip.split(" = ") address = address_string.gsub!("mem[", "").gsub!("]", "").to_i value_bin = value.to_i.to_s(2) until value_bin.size == @bitmask.size value_bin = "X#{value_bin}" end mem[address] = apply_bitmask(value_bin).to_i(2) end p mem.values.inject(0){|sum,x| sum + x }
    true
    d2f499bbbdd9d2aebb03fcb5da81ef082dec621d
    Ruby
    haruharuharuby/iiita
    /app/models/article_tagging.rb
    UTF-8
    759
    2.515625
    3
    []
    no_license
    class ArticleTagging def initialize(article) @article = article end def register ActiveRecord::Base.transaction do @article.save! update_tags end end def update(article_params) ActiveRecord::Base.transaction do @article.update(article_params) update_tags end end private def update_tags new_tag_names = @article.tag_list.split(",") @article.tags.each do |tag| rel = @article.article_tag_relations.find_by(tag: tag) unless new_tag_names.include?(tag.name) rel.destroy! if rel end new_tag_names.each do |tag_name| tag = Tag.find_or_create_by(name: tag_name) @article.article_tag_relations.find_or_create_by(tag: tag) end end end
    true
    2771f73ed28055119b298b1ea958b169523f5786
    Ruby
    marcolee1107/su-ruby-practice
    /examples/ex_203.rb
    UTF-8
    637
    2.890625
    3
    []
    no_license
    # 當SketchUp遇見Ruby - 邁向程式化建模之路(碁峯出版) # http://books.gotop.com.tw/v_AEC009100 # ex_203.rb - 分別用不同的方法繪出多邊形 mod = Sketchup.active_model # Open model ent = mod.entities # All entities in model normal = [0, 0, 1] radius = 2 # 用add_ngon方法指定6個邊線 ent.add_ngon [0, 0, 0], normal, radius, 6 # 用add_circle方法指定6個線段 ent.add_circle [5, 0, 0], normal, radius, 6 # 用add_ngon方法指定24個邊線 ent.add_ngon [10, 0, 0], normal, radius, 24 # 用add_circle方法指定24個線段(線段數量可省略) ent.add_circle [15, 0, 0], normal, radius
    true
    862cac4060ef0ad3ee0cbc1150ad1b2eea26bc44
    Ruby
    jss530/playlister-sinatra-v-000
    /app/models/song.rb
    UTF-8
    353
    2.6875
    3
    [ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
    permissive
    class Song < ActiveRecord::Base belongs_to :artist has_many :song_genres #going to access these through the join table has_many :genres, through: :song_genres #can access genres through song_genres table def slug name.downcase.gsub(" ","-") end def self.find_by_slug(slug) # binding.pry Song.all.find{|song| song.slug == slug} end end
    true
    3163843fa9b1309540a53f7f773ddd3357ad3e9d
    Ruby
    00s/depot
    /depot/db/seeds.rb
    UTF-8
    4,446
    2.9375
    3
    []
    no_license
    # encoding: utf-8 Product.delete_all Product.create!(title: 'Antologia Front-End', description: %{<p> Esse livro quer ser uma pequena celebração desse sucesso. Um grupo de 11 autores de renome nacional na comunidade se juntou para escrever artigos que julgamos relevantes para a Web. Os capítulos são independentes, cada um com seu autor. A única regra era: escrever algo memorável, que fizesse a diferença na Web brasileira. </p>}, image_url: 'Antologia-ebook_capa.png', price: 36.00) # . . . Product.create!(title: 'DevOps 3 na Pratica', description: %{<p> DevOps é um movimento cultural e profissional que está tentando quebrar essas barreiras. Com o foco em automação, colaboração, compartilhamento de ferramentas e de conhecimento, DevOps está mostrando que desenvolvedores e engenheiros de sistema têm muito o que aprender uns com os outros. </p>}, image_url: 'DevOps-3_capa.png', price: 49.95) # . . . Product.create!(title: 'Rails Test-Driven Development', description: %{<p> Rails Test-Driven Development Prescriptions Neste livro, você aprenderá sobre TDD, uma das práticas ágeis de desenvolvimento de software mais populares. TDD faz o desenvolvedor escrever o teste antes mesmo de implementar o código. Essa simples inversão na maneira de se trabalhar faz com o que o desenvolvedor escreva código mais testado, com menos bugs, e inclusive com mais qualidade. Seja profissional, teste seu software! </p>}, image_url: 'tdd-ruby-ebook_capa.png', price: 34.95) Product.create!(title: 'Google Android', description: %{<p> Faça as melhores aplicações Android, com as melhores práticas da área. Aprenda como publicar a aplicação e tê-la no ar em 1 dia. Saiba como utilizar o máximo dos aparelhos e crie aplicações extremamente ricas para celulares e tablets! </p>}, image_url: 'Android-280_capa.png', price: 34.95) Product.create!(title: 'O Programador Apaixonado', description: %{<p> Para ter sucesso no mercado de TI atual, é preciso ver sua carreira como se fosse um negócio. Nesse livro você vai aprender a empreender com a sua carreira e levá-la para o caminho que você escolheu. O do sucesso. Chad Fowler, famoso desenvolvedor de software e autor de diversos livros, ensina a construir sua carreira na área de desenvolvimento, passo a passo, seguindo o mesmo caminho de que se você estivesse criando e vendendo um produto. Afinal de contas, suas habilidades são um produto. </p>}, image_url: 'Passionate-Programmer-ebook_capa.png', price: 34.95) Product.create!(title: 'Java 8 Prático', description: %{<p> Quase 20 anos após sua primeira versão, um novo Java surge com novidades importantes. Entre os principais recursos, a linguagem recebe default methods, method references e lambdas. São conceitos simples mas que trazem importantes possibilidades. Durante o livro exploraremos esses e outros avanços. Sempre com exemplos práticos e apresentando onde utilizá-los, migrando o código legado do dia a dia para o novo paradigma funcional do Java 8. Com esse tripé de conceitos, a API conseguiu evoluir de uma maneira interessante. Os pacotes java.util.stream e java.util.function serão explorados com profundidade, apresentando formas sucintas para trabalhar com coleções e outros tipos de dados. Streams e Collectors farão parte da sua rotina e serão tão essenciais nas suas aplicações quanto já são as Collections e o java.io. </p>}, image_url: 'Java8-ebook_capa.png', price: 34.95) Product.create!(title: 'Play Framework', description: %{<p> Nesse livro, Fernando Boaglio ensina como criar uma aplicação do começo ao fim utilizando o Play Framework na versão Java, passando por situações comuns do dia a dia, indo desde o tradicional cadastro, até funcionalidades mais avançadas como habilitação de HTTPS, login integrado com redes sociais e integração com serviços REST. Você vai aprender como o Play Framework pode te tornar extremamente produtivo. </p>}, image_url: 'Play-ebooks_capa.png', price: 34.95)
    true
    3672dad1328f0d50ae3ee7c2f248813cfd6a1b51
    Ruby
    DarkWater666/rubywarrior
    /rubywarrior.rb
    UTF-8
    2,019
    3.015625
    3
    []
    no_license
    class Player attr_accessor :warrior def initialize() @max_hp=nil @current_hp=nil @prev_hp=nil @hp_history=[] @vision=[] @direction=:forward @directions=[:forward, :backward] @reverse_dir=[:backward, :forward] end def play_turn(warrior) @max_hp=warrior.health self.warrior=warrior update return warrior.rescue! @direction if warrior.feel(@direction).captive? return warrior.attack! @direction if enemy? return warrior.rest! if hurt? && !range_shot? && !warrior.look(@direction).any?{|elem| elem.enemy?} action = if (critical? && range_shot?) look_reverse elsif !warrior.look(:forward).any?{|elem| elem.captive?} && warrior.look(:forward).any?{|elem| elem.enemy?} && !warrior.look(:backward).any?{|elem| elem.enemy?} && !warrior.feel.enemy? warrior.shoot! elsif reverse==true warrior.pivot! else look end end def hurt? warrior.health<20 end def critical? warrior.health<10 end def enemy? warrior.feel(@direction).enemy? end def empty? warrior.feel(@direction).empty? end def reverse @directions.each do |dir| if warrior.feel(dir).wall? return true else return false end end false end def need_rest? warrior.health<@max_hp end def range_shot? warrior.health<@prev_hp end def update @prev_hp=@current_hp @current_hp=warrior.health @hp_history<<@current_hp end def look @directions.each do |dir| if (warrior.feel(dir).stairs?) || (warrior.feel(dir).empty?) warrior.walk!(dir) return true end end false end def look_reverse @reverse_dir.each do |dir| if (warrior.feel(dir).stairs?) || (warrior.feel(dir).empty?) warrior.walk!(dir) return true end end false end def turn @direction = (@direction == :forward) ? :backward : :forward end end
    true
    f2765b4f3ba1a26ddb4618174a95b462f3ac4be8
    Ruby
    projectblacklight/spotlight
    /lib/migration/iiif.rb
    UTF-8
    3,728
    2.65625
    3
    [ "Apache-2.0" ]
    permissive
    # frozen_string_literal: true module Migration # This migrates FeaturedImages with crop coordinates into IIIF urls which # are stored in the `iiif_url' field. class IIIF def self.run(hostname) new(hostname).run end def initialize(hostname) @hostname = hostname end def run migrate_featured_images migrate_contact_avatars migrate_upload_images end attr_reader :hostname private def migrate_featured_images Spotlight::FeaturedImage.all.each do |image| update_iiif_url(image) copy_exhibit_thumbnail_from_featured_image(image) end end def migrate_contact_avatars Spotlight::Contact.all.each do |contact| avatar = copy_contact_image_to_avatar(contact) contact.update(avatar: avatar) if avatar end end def migrate_upload_images Spotlight::Resources::Upload.all.each do |upload| copy_upload_to_featured_image(upload) end end # Checks if the image was associated as a thumbnail. # If so, this will update the STI type column of the FeaturedImage as well # as copy the file over to the correct directory given the new class name def copy_exhibit_thumbnail_from_featured_image(image) return unless Spotlight::Exhibit.where(thumbnail_id: image.id).any? filename = image.read_attribute_before_type_cast('image') filepath = "public/#{image.image.store_dir}/#{filename}" image.becomes!(Spotlight::ExhibitThumbnail) image.save return unless filename.present? && File.exist?(filepath) old_file = File.new(filepath) # AR + STI seems to require that we re-query for this # otherwise we get an association miss-match reloaded_image = Spotlight::ExhibitThumbnail.find(image.id) reloaded_image.image.store!(old_file) end # Looks for a file at the old uploader location and copies it to a FeaturedImage def copy_contact_image_to_avatar(contact) filename = contact.read_attribute_before_type_cast('avatar') filepath = "public/uploads/spotlight/contact/avatar/#{contact.id}/#{filename}" return unless filename.present? && File.exist?(filepath) old_file = File.new(filepath) image = contact.create_avatar { |i| i.image.store!(old_file) } iiif_tilesource = Spotlight::Engine.config.iiif_service.info_url(image) image.update(iiif_tilesource: iiif_tilesource, iiif_region: avatar_coordinates(contact)) image end def copy_upload_to_featured_image(upload) return unless upload.exhibit # We need exhibit context to re-index, and you can't find an item not in an exhibit filename = upload.read_attribute_before_type_cast('url') filepath = "public/uploads/spotlight/resources/upload/url/#{upload.id}/#{filename}" return unless filename.present? && File.exist?(filepath) old_file = File.new(filepath) image = upload.create_upload { |i| i.image.store!(old_file) } iiif_tilesource = Spotlight::Engine.config.iiif_service.info_url(image) image.update(iiif_tilesource: iiif_tilesource) upload.upload_id = image.id upload.save_and_index end def update_iiif_url(image) image.update( iiif_tilesource: Spotlight::Engine.config.iiif_service.info_url(image), iiif_region: coordinates(image) ) end def coordinates(image) return if image.image_crop_x.blank? [image.image_crop_x, image.image_crop_y, image.image_crop_w, image.image_crop_h].join(',') end def avatar_coordinates(contact) [contact.avatar_crop_x, contact.avatar_crop_y, contact.avatar_crop_w, contact.avatar_crop_h].join(',') end end end
    true
    3aac0a8448a19d744a6062cf19d00900307bb769
    Ruby
    nmgokhale/Ruby-Programming
    /src/Introduction to Programming/Array Methods & Enumerables/two_dim_arrays.rb
    UTF-8
    312
    4.125
    4
    []
    no_license
    # Two dimensional arrays arr = [ ["a", "b", "c"], ["d", "e"], ["f", "g", "h"] ] print arr #[["a", "b", "c"], ["d", "e"], ["f", "g", "h"]] puts puts arr[1][1] # e puts arr[2][0] # f puts "----------------" arr.each do |subArr| print subArr puts subArr.each do |element| puts element end end
    true
    a2a3086b386ca7a23ac981a26c7c8b1d59688f2b
    Ruby
    johnktravers/project_euler
    /problem_10/prime_summation_test.rb
    UTF-8
    601
    3.359375
    3
    []
    no_license
    require 'minitest/autorun' require 'minitest/pride' class PrimeSummationTest < Minitest::Test def prime_summation(max) max = max - 1 if max.even? sum = max >= 2 ? 2 : 0 (3..max).step(2) do |num| prime = true (2..(num ** 0.5 + 1)).each do |n| break prime = false if num % n == 0 end sum += num if prime end sum end #----------------- Tests -----------------# def test_prime_summation assert_equal 17, prime_summation(10) assert_equal 76127, prime_summation(1000) assert_equal 142913828922, prime_summation(2000000) end end
    true
    58181ea17adf2045f399fa5127b4076833b7d877
    Ruby
    mwagner19446/wdi_work
    /w01/d05/INSTRUCTOR/objects.rb
    UTF-8
    1,435
    4.21875
    4
    []
    no_license
    # Song # - title # - artist # - genre # - play ("Tommy by The Who is playing.") # Instantiate a few songs to test your class. class Song def title=(title) @title = title end def title() return @title end # def title() # return "Hamburgers" # end def artist=(artist) @artist = artist end def artist() return @artist end def genre=(genre) @genre = genre end def genre return @genre end def play # title = "Shmee" # artist = "Garbage" return "#{self.title()} by #{self.artist()} is playing." end end hips_dont_lie = Song.new hips_dont_lie.title=("Hips Don't Lie") hips_dont_lie.artist=("Shakira") hips_dont_lie.genre=("Puhp") puts hips_dont_lie.title() puts hips_dont_lie.artist() puts hips_dont_lie.genre() puts hips_dont_lie.play() # Playlist # - songs # - start (a random song starts) # - skip (another random song is played) # - add songs # - remove songs # - currently playing song class Playlist def initialize() @songs = [] end def add_song(song) self.songs().push(song) end def remove_song(song) self.songs().delete(song) end def start @current_song = self.songs().sample puts @current_song.play() end def skip self.start() end def current_song return @current_song end def songs return @songs end end playlist = Playlist.new playlist.add_song(hips_dont_lie) playlist.start()
    true
    989e99c1b38499e6a585f2b27d58a1665c5c97cd
    Ruby
    d3chapma/daily_bible
    /app/models/reference.rb
    UTF-8
    419
    3.203125
    3
    []
    no_license
    class Reference def initialize(book_name, chapter, verse) @book = Book.new(book_name) @chapter = @book.chapters[chapter.to_i-1] @verse = verse.to_i end def self.parse(ref) _, book_name, chapter, verse = ref.match(/(.+)\+(\d+):(\d+)/).to_a new(book_name, chapter, verse) end def to_s "#{@book}+#{@chapter}:#{@verse}" end def chunk @chapter.chunk_containing(@verse) end end
    true
    eead04a1cf5e21fddb6383a75f4a9ade9a474846
    Ruby
    itsolutionscorp/AutoStyle-Clustering
    /all_data/exercism_data/ruby/house/b5cbdd46e0b14c2a894b6753f56bbed4.rb
    UTF-8
    1,046
    3.578125
    4
    []
    no_license
    class House def self.recite new.recite end def recite result = "" (1..12).each { |i| phrase = "" count = 1 while count <= i phrase = "#{what_it_is(count)}" + phrase count += 1 end phrase = "This is " + phrase result += phrase } result.chomp end def what_it_is(n) case(n) when 1 "the house that Jack built.\n\n" when 2 "the malt\nthat lay in " when 3 "the rat\nthat ate " when 4 "the cat\nthat killed " when 5 "the dog\nthat worried " when 6 "the cow with the crumpled horn\nthat tossed " when 7 "the maiden all forlorn\nthat milked " when 8 "the man all tattered and torn\nthat kissed " when 9 "the priest all shaven and shorn\nthat married " when 10 "the rooster that crowed in the morn\nthat woke " when 11 "the farmer sowing his corn\nthat kept " when 12 "the horse and the hound and the horn\nthat belonged to " end end end
    true
    b9077c4f79676cb92a0245d5a166088bcd765041
    Ruby
    jfernapa/sinatra_roman_numerals
    /roman_numerals.rb
    UTF-8
    953
    3.640625
    4
    []
    no_license
    class RomanNumerals ONE_ROMAN = "I" def convert(number) begin roman_number = ONE_ROMAN * Integer(number) equivalences = {'M' => 1000, 'D' => 500, 'C' => 100, 'L' => 50, 'X' => 10, 'V' => 5} equivalences.each do |letter, number| roman_number = roman_number.gsub(ONE_ROMAN * number, letter) end exceptions = { 'DCCCC' => 'CM', 'CCCC' => 'CD', 'LXXXX' => 'XC', 'XXXX' => 'XL', 'VIIII' => 'IX', 'IIII' => 'IV' } exceptions.each do |wrong, correct| roman_number = roman_number.gsub(wrong, correct) end if roman_number.empty? "#{number} can not convert to roman numerals" else "#{number} is #{roman_number} in roman numerals" end rescue ArgumentError return "'#{number}' can not convert to roman numerals" end end end
    true
    d35c0f5ff25b341288c4e714dfc5b633c594aed8
    Ruby
    28221122/mobileautomatization
    /features/screens/autorized_whishlist.rb
    UTF-8
    1,001
    2.65625
    3
    []
    no_license
    class AutorizedWhiwlist def initialize @first_item_homescreen = Elements.new(:xpath,'//*[@resource-id="com.view9.foreveryng:id/banner"]') @items_to_be_liked = Elements.new(:xpath,'//*[@resource-id="com.view9.foreveryng:id/tbLove"]') @wishlist_check_for_brand = Elements.new(:xpath,'//*[@resource-id="com.view9.foreveryng:id/cardview_category_detail"]') @all_wishlist_buttons = Elements.new(:id , 'cardview_category_detail') end def click_first_item_homescreen @first_item_homescreen.click end def click_all_wishlist_items @items_to_be_liked.click_every_element_in_the_list end def check_wishlist_for_one_brand(expected) all_elements = @wishlist_check_for_brand.get_multiple_elements all_elements.each_index do |index| actual = all_elements[index].text raise "User name is not the same: Expected #{expected} , Actual: #{name}" unless actual == expected end end def click_first_brand_button @first_brand_button.click end end
    true
    aada2440b6535dd1595ba2b35336032dcc694712
    Ruby
    annacarey/oo-relationships-practice-nyc-web-111819
    /app/models/Location.rb
    UTF-8
    634
    3.265625
    3
    []
    no_license
    class Location attr_reader :name @@all = [] def initialize(name) @name = name self.class.all << self end def self.all @@all end def sessions Session.all.select do |session| session.location == self end end def trainers sessions.map do |session| session.trainer end end def clients sessions.map do |session| session.client end end def self.least_clients self.all.min_by do |location| location.clients.length end end end
    true
    3cc17904dda0fb30a6929a08badc2e2ceb511044
    Ruby
    periode/thesis
    /code/render.rb
    UTF-8
    4,424
    2.84375
    3
    [ "MIT" ]
    permissive
    #!/usr/bin/ruby require 'kramdown' require 'erb' require 'fileutils' attention = `git diff --name-only --cached` attention = attention.split("\n") unless attention.length puts "nevermind" exit end puts "time to publicize" the_only = Time.now # to remember = "#{the_only.year}-#{the_only.month}-#{the_only.day}-#{the_only.hour}#{the_only.min}" FileUtils.mkdir_p 'docs/' + remember puts "to set everything up" everything = [] attention.each do | for_this_fragment | there_is_a = /^(?!admin)(.*md)$/ if there_is_a.match for_this_fragment everything << for_this_fragment puts for_this_fragment puts "and" end end fashion = %{ <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>works in public</title> <link rel="stylesheet" href="/style.css"/> </head> <body> <div class="way"> <a href="/index.html">cover</a> </div> <div class="holding tight"> <%= rest %> </div> </body> </html> } everything.each do | it | # everyone needs a place to stay es = /(\w*\/?\w*\/?\w*\/?)\w+/ puts it a_home = it.match(es) FileUtils.mkdir_p 'docs/'+remember+'/'+a_home.to_s#tay fond = File.open(it) form = fond.read rest = Kramdown::Document.new(form).to_html finally = ERB.new(fashion).result(binding) til = it.sub! '.md', '.html' til = remember + '/' + til File.write('docs/'+til, finally) fond.close end # i need to find all the years # and then all the months # and then all the all = Hash.new traces = [] express = /(\d+)-(\d+)-(\d+)-(\d+)\/(.*\.html)/ files = Dir.glob("docs/**/**").sort_by { |f| File.mtime(f) } chaos = files.reverse chaos.each do | bit | deconstruct = bit.match(express) if deconstruct year = deconstruct[1] if !all.has_key? year all[year] = Hash.new # we create a new array to store all the months, only if that doesn't exist already end month = deconstruct[2] if !all[year].has_key? month all[year][month] = Hash.new end day = deconstruct[3] if !all[year][month].has_key? day all[year][month][day] = Hash.new end time = deconstruct[4] if !all[year][month][day].has_key? time all[year][month][day][time] = Array.new end all[year][month][day][time] << deconstruct[5] end end puts "they need to be together" space = %{ <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>the role of aesthetics in source code understandings</title> </head> <body> <style> @import url('https://rsms.me/inter/inter.css'); body { background-color: white; font-family: 'Inter', sans-serif; } .holding{ margin: auto; } .tight{ width: 70%; } </style> <div class="holding tight"> <h1>the role of aesthetics in the understandings of source code</h1> <p>what you see here is the automatic rendering of all the notes taken during <a href="https://pierredepaz.net">my</a> phd thesis. since it is a thesis on source code, might as well show its own source code.</p> <p>the main question i'm asking is: <i>how do aesthetics enable understanding in source code, what kind of understanding(s) might derive from their presence, or absence, and how does this highlight code as textual matter?</i> this touches upon issues of style, clarity, epistemology, psychology, programming and literature.</p> <p>this doctoral work is being done at the university of sorbonne nouvelle, under the joint direction of alexandre gefen (Paris-3, CNRS) and nick montfort (MIT Comparative Media Studies).</p> <p>you can start with the <a href="latest.pdf" target="_blank">most recent summary</a>, the current state of the <a href="thesis.pdf" target="_blank">final manuscript</a> or the whole <a href="https://github.com/periode/thesis">github repository</a>.</p> <hr/> <% all.each_key do | year | %> <% all[year].each_key do | month | %> <% all[year][month].each_key do | day | %> <h2> <%= year %> - <%= month %> - <%= day %> </h2> <% all[year][month][day].each_key do | time | %> <h3> <%= time %> </h3> <% all[year][month][day][time].each do | trace | %> <li><a href="<%= year+"-"+month+"-"+day+"-"+time+"/"+trace %>"><%= trace %></a></li> <% end %> <% end %> <% end %> <% end %> <% end %> </div> </body> </html> } public = ERB.new(space).result(binding) File.write("docs/index.html", public) puts "then" puts "it's done, for now"
    true
    f852cd437f7b59240838a8ce91e97d8fc5a1e791
    Ruby
    jjuarez/jabber_notifier
    /lib/jabber_notifier/cli.rb
    UTF-8
    416
    2.53125
    3
    [ "MIT" ]
    permissive
    require 'yaml' require 'jabber_notifier/options_parser' require 'jabber_notifier/connection' module JabberNotifier class Cli def self.run(options) config = YAML.load_file(options[:config]) connection = Connection.new(:username =>config["username"], :password =>config["password"], :delay =>options[:delay].to_f) connection.notify(options[:to], options[:message]) end end end
    true
    7ad402efc4cbc26cdaddb36171d21e1b3f83bfbe
    Ruby
    BlueMeadow/L3
    /S6/PROJET/Hanjie-master/Generation/Picture.rb
    UTF-8
    2,259
    3.359375
    3
    []
    no_license
    require 'rmagick' include Magick class Magick::Pixel def isBlack?() (self.green + self.red + self.blue) / 3 < (QuantumRange / 2) end end class Picture @origine # Contient l'image original @indicesH # Groupe d'indices de colonne (array[array]) @indicesV # Groupe d'indices de ligne (array[array]) @precision # Precision souhaité (variation de couleur) @dimension # Dimension souhaité (5x5, 10x10, 15x15) private_class_method :new attr_reader :precision def Picture.creer(imageName,dimension) new(imageName,dimension) end def initialize(imageName,dimension) @origine = Image.read(imageName).first.resize_to_fill(dimension,dimension) @indicesH = [] @indicesV = [] @precision = 1 @dimension = dimension end def getIndicesH(i) return @indicesH[i] end def getIndicesV(i) return @indicesV[i] end def toBoolean # image --> [true,true,false,true] true = blanc # [false,true,false,false] false = noir # [true,true,true,true] grid = [] image = toGrey(@precision) image.each_pixel{|pixel| grid << !pixel.isBlack?} grid.each_slice(image.columns).to_a end def calcIndice # [true,true,false,true] [2,1] # [false,true,false,false] --> [1] # [true,true,true,false,true] [3,1] grid = self.toBoolean @indicesH = groupeIndicesGrid(grid) @indicesV = groupeIndicesGrid(grid.transpose) return grid end def to_s toBoolean.map{|ligne| ligne.map{|pix| pix ? "+":" "}.join}.join("\n") end def printIndice afficherIndices(@indicesH) print "\n\n" afficherIndices(@indicesV) end # PRIVATE CLASS private def toGrey(precision) @origine.quantize(256,GRAYColorspace).edge(precision) end def groupeIndicesLigne(ligne) indices = [] i = 0 ligne.each_with_index{|etat,index| if etat then i += 1 end if (index == ligne.length-1 || !etat) && (i !=0) then indices << i i = 0 end } return indices end def groupeIndicesGrid(grid) indices = [] grid.each{|ligne| indices << groupeIndicesLigne(ligne)} return indices end def afficherIndices(grid) i = 1 grid.each{|g| print i," : ", g, "\n" i += 1 } end end # i = Picture.creer("apple.bmp",10); # puts i # i.calcIndice # i.printIndice #p i.getIndicesV(0)
    true
    b486346a10cd4ec53db5f1f40c885e8e9c962aa6
    Ruby
    b-dalton/04_ruby_tutorial
    /strings_arrays_time/time.rb
    UTF-8
    462
    3.34375
    3
    []
    no_license
    require 'date' # s = String.new("A man, a plan, a canal—Panama!") # t = s.split(", ") # p t # a = Array.new # a << 3 << 4 # puts a # now = Time.now # puts now moon_landing = Time.new(1969, 7, 20, 20, 17, 40) # puts moon_landing.day # puts now - moon_landing # DAYNAMES = Date::DAYNAMES # DAYNAMES = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] # puts DAYNAMES[moon_landing.wday] # puts DAYNAMES[Time.now.wday] puts now
    true
    6e64453d405288e6a5863bca64506cb5cf9d5a20
    Ruby
    JimMcL/sampleIt
    /lib/view_angle.rb
    UTF-8
    4,169
    3.40625
    3
    [ "MIT" ]
    permissive
    # Class for working with view angles of photos of specimens. # The angle is specified by latitude (phi) and longitude (lambda). Photos # are assumed to be directed towards the centre of the specimen, with # the top of the specimen facing up or else the front of the specimen # facing towards the left. Longitude (lamba) is 0 at the middle of the # face. Units are (integral) degrees. # Hence, an anterior (frontal) view is (0, 0), a lateral view (taken from the # specimen's left side) is (0, 90), and a dorsal view is (90, 0). # # See also http://insects.oeb.harvard.edu/etypes/specificimages.htm class ViewAngle include Comparable attr_accessor :phi, :lambda NAMED_ANGLES = {lateral: [0, 90], dorsal: [90, 0], ventral: [-90, 0], anterior: [0, 0], posterior: [0, 180], lateral_right_side: [0, -90] } SYNONYMS = {frontal: [0, 0], face: [0, 0], underside: [-90, 0]} # Returns the list of named angles def self.angle_names NAMED_ANGLES.keys end # If params contains a parameter such as {view_angle: 'lateral'}, removes it and # adds {view_phi: 0, view_lambda: 90} def self.expand_query_params(params) if params.key?(:view_angle) && (va = ViewAngle.new(params[:view_angle])) && va.valid? params = params.merge(view_phi: va.phi, view_lambda: va.lambda) end params.except(:view_angle) end # Creates a ViewAngle. # Takes either a view name (a symbol or string), phi and lambda, or a name and relative phi and lambda. # # Examples: # ViewAngle.new(:lateral) # Taken from left side # ViewAngle.new(0, 90) # Same as :lateral # ViewAngle.new('0, 90') # Same as :lateral # ViewAngle(:dorsal) # Taken from above, head towards the left (by convention) # ViewAngle(:dorsal, -5, 90) # Taken from above by 5 degrees towards dorsal def initialize(phi_or_name, lambda_or_relative_phi = 0, relative_lambda = 0) if phi_or_name.is_a?(Numeric) && lambda_or_relative_phi.is_a?(Numeric) @phi = phi_or_name @lambda = lambda_or_relative_phi elsif !phi_or_name.blank? # Check for 2 angles in a string phi_or_name = phi_or_name.to_s if (m = phi_or_name.scan(/[+-]?\d+/)) && m.length == 2 @phi = m[0].to_i @lambda = m[1].to_i else # Check for name of an angle key = phi_or_name.parameterize(separator: '_').intern na = NAMED_ANGLES[key] na = SYNONYMS[key] if na.blank? raise ArgumentError, "Invalid named view angle '#{phi_or_name}', require one of [#{NAMED_ANGLES.keys.join(', ')}]" if na.blank? @phi = na[0] @lambda = na[1] # Add relative angle if specified if lambda_or_relative_phi.is_a?(Numeric) && relative_lambda.is_a?(Numeric) @phi += lambda_or_relative_phi @lambda += relative_lambda end end end end def valid? [email protected]? && [email protected]? && @phi >= -90 && @phi <= 90 && @lambda >= -180 && @lambda <= 180 end def to_s valid? ? (name && name.humanize || "#{@phi}, #{@lambda}") : '' end def inspect "ViewAngle(phi: #{@phi}, lambda: #{@lambda}, name: #{name})" end def description valid? ? "#{to_s.humanize} view" : '' end def name nm = false NAMED_ANGLES.each do |key, value| nm = key.to_s if value[0] == @phi && value[1] == @lambda end nm end def hash [phi, lambda].hash end def eql?(other) self == other || (other.is_a?(ViewAngle) && phi == other.phi && lambda == other.lambda) end # Define a somewhat arbitrary ordering, based on how photos should appear def <=>(other) if other.is_a? ViewAngle nm1 = name nm2 = other.name # Named angles come first return -1 if nm1 && !nm2 return 1 if !nm1 && nm2 # String comparison if neither is named return to_s <=> other.to_s if !nm1 # Named angles use the order defined in NAMED_ANGLES idx1 = NAMED_ANGLES.keys.index(nm1.to_sym) idx2 = NAMED_ANGLES.keys.index(nm2.to_sym) idx1 <=> idx2 end end end
    true
    76e73f4aa830046a84748d275fcbeb31df7e4855
    Ruby
    johnantoni/plugin.tweakify
    /lib/common/active_record.rb
    UTF-8
    339
    2.578125
    3
    [ "MIT" ]
    permissive
    class ActiveRecord::Base def self.to_a_simplify # takes table object and breaks it down into a simple array return self.to_enum.map {|e| e::id } end def self.simply_paginate(id) # converts table into array, then finds prev/next/current & returns as hash return self.to_a_simplify.simply_paginate_array(id) end end
    true
    5ba3b8edfc283490351aad1e5899ca4d7b61cc85
    Ruby
    JEG2/ender
    /test/tc_config.rb
    UTF-8
    864
    2.71875
    3
    [ "MIT" ]
    permissive
    #!/usr/bin/env ruby -wKU require "test/unit" require "tempfile" require "config" class TestConfig < Test::Unit::TestCase def test_config_returns_a_customized_ostruct assert_instance_of(OpenStruct, config) end def test_config_object_is_passed_into_the_file_and_used_to_set_options c = config(<<-END_SETTINGS) config.string_setting = "just a String" config.integer_setting = 41 END_SETTINGS assert_equal("just a String", c.string_setting) assert_equal(41, c.integer_setting) end def test_exceptions_bubble_up_to_the_caller assert_raise(RuntimeError) do config(<<-END_ERROR) raise "Oops!" END_ERROR end end private def config(content = String.new) cf = Tempfile.new("ender_config_test") cf << content cf.flush Config.load_config_file(cf.path) end end
    true
    094afe2138299494f6f6b683d8471a870e21360b
    Ruby
    rayleyva/ArangoDB
    /3rdParty/mruby/mrblib/struct.rb
    UTF-8
    854
    3.46875
    3
    [ "Apache-2.0", "MIT" ]
    permissive
    ## # Struct # # ISO 15.2.18 class Struct ## # Calls the given block for each element of +self+ # and pass the respective element. # # ISO 15.2.18.4.4 def each(&block) self.class.members.each{|field| block.call(self[field]) } self end ## # Calls the given block for each element of +self+ # and pass the name and value of the respectiev # element. # # ISO 15.2.18.4.5 def each_pair(&block) self.class.members.each{|field| block.call(field.to_sym, self[field]) } self end ## # Calls the given block for each element of +self+ # and returns an array with all elements of which # block is not false. # # ISO 15.2.18.4.7 def select(&block) ary = [] self.class.members.each{|field| val = self[field] ary.push(val) if block.call(val) } ary end end
    true
    c249e8b59fccbe7b0efd0be155e1daef95a11585
    Ruby
    jparbros/leaderboard
    /app/models/concerns/input_filters.rb
    UTF-8
    2,821
    2.53125
    3
    []
    no_license
    module InputFilters def self.included(base) base.extend(ClassMethods) end module ClassMethods def search(params) inputs = self.includes(:user, :departament) inputs = inputs.by_user(params[:user_id]) if params[:user_id] inputs = inputs.by_today if params[:period] == 'today' inputs = inputs.by_week if params[:period] == 'week' inputs = inputs.by_month if params[:period] == 'month' inputs = inputs.by_quarter if params[:period] == 'quarter' inputs = inputs.by_year if params[:period] == 'year' inputs = inputs.by_departament(params[:departament_id]) if params[:departament_id] inputs = inputs.group_by_user if params[:group_by_user] inputs = inputs.paginate(page: params[:page], per_page: 20) if params[:page] inputs = inputs.get_ordered(params) if params[:order] inputs end def by_today where(date: Date.today) end def by_week where('date >= ? and date <= ?', Date.today.at_beginning_of_week, Date.today.at_end_of_week) end def by_month where('date >= ? and date <= ?', Date.today.beginning_of_month, Date.today.end_of_month) end def by_quarter where('date >= ? and date <= ?', Date.today.beginning_of_quarter, Date.today.end_of_quarter) end def by_year where('date >= ? and date <= ?', Date.today.beginning_of_year, Date.today.end_of_year) end def by_user user_id where(user_id: user_id) end def by_departament(departament_id) if departament_id == 'all_teams' joins(:departament) else joins(:departament).where(departaments: {id: departament_id}) end end def group_by_user all.group_by {|input| input.user_id}.values.map do |values| user = values.first.user {realized: values.map(&:value).inject(0, &:+).round(2), username: user.name, picture: user.avatar.url(:medium), target: user.target} end.sort {|x,y| y[:realized] <=> x[:realized]}.take(5) end def get_leader all.max end def get_ordered(params) inputs = order_by_name(params[:order_direction]) if params[:order] == 'name' inputs = order_by_date(params[:order_direction]) if params[:order] == 'date' inputs = order_by_value(params[:order_direction]) if params[:order] == 'value' inputs = order_by_team(params[:order_direction]) if params[:order] == 'team' inputs end def order_by_name(direction = 'DESC') order("users.name #{direction}") end def order_by_date(direction = 'DESC') order("inputs.date #{direction}") end def order_by_value(direction = 'DESC') order("inputs.value #{direction}") end def order_by_team(direction = 'DESC') order("departaments.name #{direction}") end end end
    true
    5c18ab4b04705437902dc4b522af2e90632ba8fb
    Ruby
    szib/oo-relationships-practice-london-web-career-040119
    /app/models/IMDB/Movie.rb
    UTF-8
    132
    2.5625
    3
    []
    no_license
    require_relative './VisualProduct' class Movie < VisualProduct def self.most_actors all.max_by(&:number_of_actors) end end
    true
    145fddeecb88889417783957828b40222f2bd4d3
    Ruby
    itsolutionscorp/AutoStyle-Clustering
    /all_data/exercism_data/ruby/bob/2ea7d59f423b4a75b8d2db7c8b796d70.rb
    UTF-8
    774
    3.953125
    4
    []
    no_license
    #!/usr/bin/env ruby class Bob @@responses = { question: "Sure.", silence: "Fine. Be that way!", yelling: "Woah, chill out!", default: "Whatever." } def hey(phrase) result = :default case when silence?(phrase) result = :silence when yelling?(phrase) result = :yelling when question?(phrase) result = :question end @@responses[result] end private def yelling?(phrase) if phrase.strip.empty? False else phrase.eql? phrase.upcase end end def question?(phrase) phrase.end_with? "?" end def silence?(phrase) phrase.strip.empty? end end
    true
    bd2c4e21ed88d79a8d95472c1c85de159e66813b
    Ruby
    vgelinski/home_sinatra
    /src/model/user.rb
    UTF-8
    687
    2.796875
    3
    []
    no_license
    require 'data_mapper' require 'digest/sha1' class User include DataMapper::Resource property :id, Serial property :name, String property :password, String property :salt, String def User.create(params) params[:salt] = (0..8).map{(33 + rand(92)).chr}.join plain_pass = params[:password] params[:password] = Digest::SHA1.hexdigest plain_pass + params[:salt] super(params) end def initialize(params) attribute_set :name, params[:name] attribute_set :password, params[:password] attribute_set :salt, params[:salt] end def check(m_name, m_password) name == m_name && (Digest::SHA1.hexdigest(m_password + salt) == password) end end
    true
    41b829cd54c3e872096b4dd560351c1f6d9b1032
    Ruby
    Jylia/xyz
    /xyz.rb
    UTF-8
    255
    3.484375
    3
    []
    no_license
    def mult(x,y,z) if (x < y) ? if ((y < z) || (x < z)) ? a = [y, z] : a = [y, x] end : if ((x < z) || (y < z))? a = [x, z] : a = [y, x] end end return a[0]*a[0] + a[1]*a[1] end puts mult(-10, -9 ,-22)
    true
    66f979f8c23ed9f71e0bf491762f564ea05f67e1
    Ruby
    alansparrow/learningruby
    /benchmarkexample2.rb
    UTF-8
    236
    2.8125
    3
    []
    no_license
    require 'benchmark' iterations = 1000000 Benchmark.bmbm do |bmbm| bmbm.report("for:") do for i in 1..iterations do x = i end end bmbm.report("times:") do iterations.times do |i| x = i end end end
    true
    71a162184d00779ea2e21462ef19492c3a7aa618
    Ruby
    npatel007/Computer-Science-Notes
    /Ruby/RubyLect9.progs/RubyLect9.14.progs/closure.rb
    UTF-8
    2,534
    2.78125
    3
    []
    no_license
    #!/opt/local/bin/ruby2.0 -w # CLOSURE # Copyright Mark Keane, All Rights Reserved, 2011 arr1 = ["john", "jim","mary", "james"] arr2 = ["A", "B","C", "D"] def assign_marks(people, marks, time1 = 0, procs = []) people.each do |person| time2 = 0 marks.each do |mark| fn = lambda {p [person, mark, time1, time2]} procs << fn fn.call; time1 += 1; time2 += 1 if (time1 == 10 || time2 == 4) then puts "Encountered an error at 10/4 seconds, going back to start" procs.first.call end end end procs end fns = assign_marks(arr1, arr2) p fns fns.each {|clos| clos.call} =begin dhcp-892b3c12:RubyWeek8.progs mkeane$ !! ruby closure.rb ["john", "A", 0, 0] ["john", "B", 1, 1] ["john", "C", 2, 2] ["john", "D", 3, 3] Encountered an error at 10/4 seconds, going back to start ["john", "A", 4, 4] ["jim", "A", 4, 0] ["jim", "B", 5, 1] ["jim", "C", 6, 2] ["jim", "D", 7, 3] Encountered an error at 10/4 seconds, going back to start ["john", "A", 8, 4] ["mary", "A", 8, 0] ["mary", "B", 9, 1] Encountered an error at 10/4 seconds, going back to start ["john", "A", 10, 4] ["mary", "C", 10, 2] ["mary", "D", 11, 3] Encountered an error at 10/4 seconds, going back to start ["john", "A", 12, 4] ["james", "A", 12, 0] ["james", "B", 13, 1] ["james", "C", 14, 2] ["james", "D", 15, 3] Encountered an error at 10/4 seconds, going back to start ["john", "A", 16, 4] [#<Proc:[email protected]:12 (lambda)>, #<Proc:[email protected]:12 (lambda)>, #<Proc:[email protected]:12 (lambda)>, #<Proc:[email protected]:12 (lambda)>, #<Proc:[email protected]:12 (lambda)>, #<Proc:[email protected]:12 (lambda)>, #<Proc:[email protected]:12 (lambda)>, #<Proc:[email protected]:12 (lambda)>, #<Proc:[email protected]:12 (lambda)>, #<Proc:[email protected]:12 (lambda)>, #<Proc:[email protected]:12 (lambda)>, #<Proc:[email protected]:12 (lambda)>, #<Proc:[email protected]:12 (lambda)>, #<Proc:[email protected]:12 (lambda)>, #<Proc:[email protected]:12 (lambda)>, #<Proc:[email protected]:12 (lambda)>] ["john", "A", 16, 4] ["john", "B", 16, 4] ["john", "C", 16, 4] ["john", "D", 16, 4] ["jim", "A", 16, 4] ["jim", "B", 16, 4] ["jim", "C", 16, 4] ["jim", "D", 16, 4] ["mary", "A", 16, 4] ["mary", "B", 16, 4] ["mary", "C", 16, 4] ["mary", "D", 16, 4] ["james", "A", 16, 4] ["james", "B", 16, 4] ["james", "C", 16, 4] ["james", "D", 16, 4] dhcp-892b3c12:RubyWeek8.progs mkeane$ =end
    true
    f11a357e083cf04a3f6889b5e77568d3aa3325f5
    Ruby
    parrot-studio/rdgc-dm
    /lib/rdgc/maker/divide_temp_block.rb
    UTF-8
    7,099
    2.609375
    3
    [ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
    permissive
    # coding: UTF-8 module RDGC module Maker class DivideTempBlock < TempBlock attr_accessor :divide_direction attr_writer :depth, :min_size def depth @depth ||= 0 @depth end def min_size @min_size = Util::Config.min_block_size if @min_size.to_i < Util::Config.min_block_size @min_size end def min_divide_size min_size * 2 end def opposite_direction case self.divide_direction when :horizontal :vertical when :vertical :horizontal else nil end end def dividable_size? case self.divide_direction when :horizontal height >= min_divide_size ? true : false when :vertical width >= min_divide_size ? true : false else false end end def dividable(f = true) @dividable = f end def dividable? @dividable end def set_dividable return unless dividable_size? dividable end def divide_point(val) range_rand(min_size, val - min_divide_size) end def divide self.divide_direction ||= select_rand({:horizontal => 1, :vertical => 1}) return unless dividable_size? case self.divide_direction when :horizontal divide_horizontal when :vertical divide_vertical end end def divide_horizontal return unless dividable_size? # 分割幅決定 point = divide_point(height) upper = DivideTempBlock.create(top, top + point - 1, left, right) lower = DivideTempBlock.create(top + point, bottom, left, right) set_next_value(upper, lower) [upper, lower].shuffle end def divide_vertical return unless dividable_size? # 分割点決定 point = divide_point(width) lefter = DivideTempBlock.create(top, bottom, left, left + point - 1) righter = DivideTempBlock.create(top, bottom, left + point, right) set_next_value(lefter, righter) [lefter, righter].shuffle end def set_next_value(b1, b2) [b1, b2].each do |b| b.depth = self.depth + 1 b.divide_direction = opposite_direction b.min_size = min_size end if bool_rand b1.set_dividable b2.set_dividable if bool_rand else b2.set_dividable b1.set_dividable if bool_rand end end # for road ---------------------------------------------------- def road_created(f = true) @road_created = f self end def road_created? @road_created end def set_road_point(direction, point) @road_point ||= {} @road_point[direction] = point end def road_point @road_point ||= {} @road_point end def remain_cling_blocks @remain_cling_blocks ||= [] @remain_cling_blocks end def add_remain_cling_blocks(b) return if b.has_room? remain_cling_blocks << b end def has_remain_cling_blocks? remain_cling_blocks.empty? ? false : true end def dead_end? return false if has_room? return false unless has_cross_point? road_point.keys.size == 1 ? true : false end def remain_direction [:top, :bottom, :left, :right] - road_point.keys end def create_road_to(b) return unless (has_room? || has_cross_point?) return unless (b.has_room? || b.has_cross_point?) # 相手とどこで接しているか調べる # 接線に向かって道を伸ばす # 左か上に位置する部屋に接続線を引く case cling_direction_to(b) when :top my_x = create_road_for_direction(:top) b_x = b.create_road_for_direction(:bottom) b.create_road_for_adjoin_x(my_x, b_x) when :bottom my_x = create_road_for_direction(:bottom) b_x = b.create_road_for_direction(:top) create_road_for_adjoin_x(my_x, b_x) when :left my_y = create_road_for_direction(:left) b_y = b.create_road_for_direction(:right) b.create_road_for_adjoin_y(my_y, b_y) when :right my_y = create_road_for_direction(:right) b_y = b.create_road_for_direction(:left) create_road_for_adjoin_y(my_y, b_y) end end def create_road_for_direction(d) # 道を描くポイントを持っている(すでに道がある)ならそれを返す val = road_point[d] return val if val # 新しい道を描く case when has_room? val = create_road_from_room(d) when has_cross_point? val = create_road_from_point(d) end val end def create_road_from_room(d) return unless has_room? return if road_point[d] case d when :top x = range_rand(room.left, room.right) set_road_point(:top, x) add_road(Map::Road.create(top, room.top-1, x, x)) x when :bottom x = range_rand(room.left, room.right) set_road_point(:bottom, x) add_road(Map::Road.create(room.bottom+1, bottom, x, x)) x when :left y = range_rand(room.top, room.bottom) set_road_point(:left, y) add_road(Map::Road.create(y, y, left, room.left-1)) y when :right y = range_rand(room.top, room.bottom) set_road_point(:right, y) add_road(Map::Road.create(y, y, room.right+1, right)) y end end def create_road_from_point(d) return unless has_cross_point? return if road_point[d] x, y = cross_point case d when :top set_road_point(:top, x) add_road(Map::Road.create(top, y, x, x)) x when :bottom set_road_point(:bottom, x) add_road(Map::Road.create(y, bottom, x, x)) x when :left set_road_point(:left, y) add_road(Map::Road.create(y, y, left, x)) y when :right set_road_point(:right, y) add_road(Map::Road.create(y, y, x, right)) y end end def create_road_for_adjoin_x(x1, x2) p_s, p_e = [x1, x2].sort add_road(Map::Road.create(bottom, bottom, p_s, p_e)) end def create_road_for_adjoin_y(y1, y2) p_s, p_e = [y1, y2].sort add_road(Map::Road.create(p_s, p_e, right, right)) end end end end
    true
    803967a84198386138106048acacbd1a99502042
    Ruby
    SuhaylTFaris/XASJS
    /XAS Tool HUD 0.1.rb
    UTF-8
    23,885
    2.6875
    3
    []
    no_license
    #============================================================================== # ■ +++ MOG - XAS TOOL HUD (v1.0) +++ #============================================================================== # By Moghunter # http://www.atelier-rgss.com #============================================================================== # Apresenta as huds usadas pelas ferramentas usadas no XAS , mais a hud da # quantidade de ouro. #=============================================================================== module XAS_TOOL_HUD #Ativar a Hud de habilidades. ENABLE_SKILL_HUD = true #Ativar a Hud de Item. ENABLE_ITEM_HUD = true #Ativar a Hud de Armas. ENABLE_WEAPON_HUD = true #Ativar a Hud de Escudo. ENABLE_SHIELD_HUD = true #Ativar a Hud de Dinheiro(Gold). ENABLE_GOLD_HUD = true #Posição geral da hud de Item. ITEM_HUD = [220,365] #Posição geral da hud de Habilidades SKILL_HUD = [264,365] #Posição geral da hud de armas. WEAPON_HUD = [308,365] #Posição geral da hud de escudo. SHIELD_HUD = [352,365] #Posição geral da hud de dinheiro(Gold). GOLD_HUD = [430,395] #Posição do numero de dinheiro(Gold). GOLD_NUMBER = [40,1] #Posição do Layout. LAYOUT = [0,0] #Posição do Ícone. ICON = [5, 12] #Posição do numero. NUMBER = [18, 35] #Ajuste de espaço entre os numeros. NUMBER_SPACE = 0 end #============================================================================== # ■ Tool Hud #============================================================================== class Tool_Hud include XAS_TOOL_HUD #-------------------------------------------------------------------------- # ● Initialize #-------------------------------------------------------------------------- def initialize @actor = $game_party.members[0] return if @actor == nil @icon_image = Cache.system("Iconset") @number_image = Cache.system("XAS_Tool_Number") @number_cw = @number_image.width / 10 @number_ch = @number_image.height / 3 @number_sc = @number_cw + NUMBER_SPACE create_skill if ENABLE_SKILL_HUD create_item if ENABLE_ITEM_HUD create_weapon if ENABLE_WEAPON_HUD create_shield if ENABLE_SHIELD_HUD create_gold if ENABLE_GOLD_HUD end #-------------------------------------------------------------------------- # ● Refresh #-------------------------------------------------------------------------- def refresh dispose initialize end #-------------------------------------------------------------------------- # ● Create Gold #-------------------------------------------------------------------------- def create_gold @gold = $game_party.gold @gold_old = @gold @gold_ref = @gold_old @gold_refresh = false # Layout ------------------------------------------------------------------- @gold_layout_sprite = Sprite.new @gold_layout_sprite.bitmap = Cache.system("XAS_Tool_Gold") @gold_layout_sprite.z = 151 @gold_layout_sprite.x = GOLD_HUD[0] @gold_layout_sprite.y = GOLD_HUD[1] # Gold --------------------------------------------------------------------- @gold_number_sprite = Sprite.new @gold_number_sprite.bitmap = Bitmap.new(@number_image.width, @number_image.height / 3) @gold_number_sprite.z = 152 @gold_number_sprite.x = GOLD_HUD[0] + GOLD_NUMBER[0] @gold_number_sprite.y = GOLD_HUD[1] + GOLD_NUMBER[1] gold_number_update end #-------------------------------------------------------------------------- # ● Create Shield #-------------------------------------------------------------------------- def create_shield #LAYOUT ------------------------------------------------------------ @shield_layout_sprite = Sprite.new @shield_layout_sprite.bitmap = Cache.system("XAS_Tool_Shield") @shield_layout_sprite.z = 150 @shield_layout_sprite.x = SHIELD_HUD[0] + LAYOUT[0] @shield_layout_sprite.y = SHIELD_HUD[1] + LAYOUT[1] @shield = @actor.equips[1] @old_shield = @shield if @shield != nil icon_index = @shield.icon_index else icon_index = 0 end @shield_icon_sprite = Sprite.new @shield_icon_sprite.bitmap = Bitmap.new(24,24) bitmap_shield_rect = Rect.new(icon_index % 16 * 24, icon_index / 16 * 24, 24, 24) @shield_icon_sprite.bitmap.blt(0, 0, @icon_image, bitmap_shield_rect) @shield_icon_sprite.z = 151 @shield_icon_sprite.x = SHIELD_HUD[0] + ICON[0] @shield_icon_sprite.y = SHIELD_HUD[1] + ICON[1] #NUMBER ------------------------------------------------------------ @shield_number_sprite = Sprite.new @shield_number_sprite.bitmap = Bitmap.new(@number_image.width, @number_image.height / 3) @shield_number_sprite.z = 152 refresh_shield_number end #-------------------------------------------------------------------------- # ● Refresh Shield Number #-------------------------------------------------------------------------- def refresh_shield_number @shield_number = 0 @s_item = 0 @shield_number_sprite.bitmap.clear return if @shield == nil if @shield.note =~ /<Action ID = (\d+)>/ action_id = $1.to_i skill = $data_skills[action_id] if skill != nil if skill.note =~ /<Item Cost = (\d+)>/ item_id = $1.to_i if item_id != nil @s_item = $data_items[item_id] @shield_number = $game_party.item_number(@s_item) end end end end return if @s_item == 0 cost_split = @shield_number.to_s.split(//) for r in 0..cost_split.size - 1 number_abs = cost_split[r].to_i src_rect = Rect.new(@number_cw * number_abs, 0, @number_cw, @number_ch) @shield_number_sprite.bitmap.blt(@number_sc * r, 0, @number_image, src_rect) end xf = ((cost_split.size * @number_sc) / 2) @shield_number_sprite.x = SHIELD_HUD[0] + NUMBER[0] - xf @shield_number_sprite.y = SHIELD_HUD[1] + NUMBER[1] end #-------------------------------------------------------------------------- # ● Create Weapon #-------------------------------------------------------------------------- def create_weapon #LAYOUT ------------------------------------------------------------ @weapon_layout_sprite = Sprite.new @weapon_layout_sprite.bitmap = Cache.system("XAS_Tool_Weapon") @weapon_layout_sprite.z = 150 @weapon_layout_sprite.x = WEAPON_HUD[0] + LAYOUT[0] @weapon_layout_sprite.y = WEAPON_HUD[1] + LAYOUT[1] #ICON @weapon = @actor.equips[0] @old_weapon = @weapon if @weapon != nil icon_index = @weapon.icon_index else icon_index = 0 end @weapon_icon_sprite = Sprite.new @weapon_icon_sprite.bitmap = Bitmap.new(24,24) bitmap_weapon_rect = Rect.new(icon_index % 16 * 24, icon_index / 16 * 24, 24, 24) @weapon_icon_sprite.bitmap.blt(0, 0, @icon_image, bitmap_weapon_rect) @weapon_icon_sprite.z = 151 @weapon_icon_sprite.x = WEAPON_HUD[0] + ICON[0] @weapon_icon_sprite.y = WEAPON_HUD[1] + ICON[1] #NUMBER ------------------------------------------------------------ @weapon_number_sprite = Sprite.new @weapon_number_sprite.bitmap = Bitmap.new(@number_image.width, @number_image.height / 3) @weapon_number_sprite.z = 152 refresh_weapon_number end #-------------------------------------------------------------------------- # ● Refresh Weapon Number #-------------------------------------------------------------------------- def refresh_weapon_number @weapon_number = 0 @w_item = 0 @weapon_number_sprite.bitmap.clear return if @weapon == nil if @weapon.note =~ /<Action ID = (\d+)>/ action_id = $1.to_i skill = $data_skills[action_id] if skill != nil if skill.note =~ /<Item Cost = (\d+)>/ item_id = $1.to_i if item_id != nil @w_item = $data_items[item_id] @weapon_number = $game_party.item_number(@w_item) end end end end return if @w_item == 0 cost_split = @weapon_number.to_s.split(//) for r in 0..cost_split.size - 1 number_abs = cost_split[r].to_i src_rect = Rect.new(@number_cw * number_abs, 0, @number_cw, @number_ch) @weapon_number_sprite.bitmap.blt(@number_sc * r, 0, @number_image, src_rect) end xf = ((cost_split.size * @number_sc) / 2) @weapon_number_sprite.x = WEAPON_HUD[0] + NUMBER[0] - xf @weapon_number_sprite.y = WEAPON_HUD[1] + NUMBER[1] end #-------------------------------------------------------------------------- # ● Create Skill #-------------------------------------------------------------------------- def create_skill #LAYOUT ------------------------------------------------------------ @skill_layout_sprite = Sprite.new @skill_layout_sprite.bitmap = Cache.system("XAS_Tool_Skill") @skill_layout_sprite.z = 150 @skill_layout_sprite.x = SKILL_HUD[0] + LAYOUT[0] @skill_layout_sprite.y = SKILL_HUD[1] + LAYOUT[1] #ICON ------------------------------------------------------------ @old_skill = @actor.skill_id @skill = $data_skills[@actor.skill_id] if @skill != nil icon_index = @skill.icon_index @skill_mp_cost = @skill.mp_cost else icon_index = 0 @skill_mp_cost = 0 end @skill_icon_sprite = Sprite.new @skill_icon_sprite.bitmap = Bitmap.new(24,24) bitmap_skill_rect = Rect.new(icon_index % 16 * 24, icon_index / 16 * 24, 24, 24) @skill_icon_sprite.bitmap.blt(0, 0, @icon_image, bitmap_skill_rect) @skill_icon_sprite.z = 151 @skill_icon_sprite.x = SKILL_HUD[0] + ICON[0] @skill_icon_sprite.y = SKILL_HUD[1] + ICON[1] #NUMBER ------------------------------------------------------------ skill_number_bitmap = Bitmap.new(@number_image.width, @number_image.height / 3) @skill_number_sprite = Sprite.new @skill_number_sprite.bitmap = skill_number_bitmap cost_split = @skill_mp_cost.to_s.split(//) for r in 0..cost_split.size - 1 number_abs = cost_split[r].to_i src_rect = Rect.new(@number_cw * number_abs, @number_ch, @number_cw, @number_ch) skill_number_bitmap.blt(@number_sc * r, 0, @number_image, src_rect) end @skill_number_sprite.z = 152 xf = ((cost_split.size * @number_sc) / 2) @skill_number_sprite.x = SKILL_HUD[0] + NUMBER[0] - xf @skill_number_sprite.y = SKILL_HUD[1] + NUMBER[1] end #-------------------------------------------------------------------------- # ● Create Item #-------------------------------------------------------------------------- def create_item #LAYOUT ------------------------------------------------------------ @item_layout_sprite = Sprite.new @item_layout_sprite.bitmap = Cache.system("XAS_Tool_Item") @item_layout_sprite.z = 150 @item_layout_sprite.x = ITEM_HUD[0] + LAYOUT[0] @item_layout_sprite.y = ITEM_HUD[1] + LAYOUT[1] #ICON ------------------------------------------------------------ @old_item = @actor.item_id @item = $data_items[@actor.item_id] if @item != nil icon_index = @item.icon_index @item_number = $game_party.item_number(@item) else icon_index = 0 @item_number = 0 end @item_icon_sprite = Sprite.new @item_icon_sprite.bitmap = Bitmap.new(24,24) bitmap_item_rect = Rect.new(icon_index % 16 * 24, icon_index / 16 * 24, 24, 24) @item_icon_sprite.bitmap.blt(0, 0, @icon_image, bitmap_item_rect) @item_icon_sprite.z = 160 @item_icon_sprite.x = ITEM_HUD[0] + ICON[0] @item_icon_sprite.y = ITEM_HUD[1] + ICON[1] #NUMBER ------------------------------------------------------------ item_number_bitmap = Bitmap.new(@number_image.width, @number_image.height / 3) @item_number_sprite = Sprite.new @item_number_sprite.bitmap = item_number_bitmap cost_split = @item_number.to_s.split(//) for r in 0..cost_split.size - 1 number_abs = cost_split[r].to_i src_rect = Rect.new(@number_cw * number_abs, 0, @number_cw, @number_ch) @item_number_sprite.bitmap.blt(@number_sc * r, 0, @number_image, src_rect) end @item_number_sprite.z = 152 xf = ((cost_split.size * @number_sc) / 2) @item_number_sprite.x = ITEM_HUD[0] + NUMBER[0] - xf @item_number_sprite.y = ITEM_HUD[1] + NUMBER[1] end #-------------------------------------------------------------------------- # ● Dispose #-------------------------------------------------------------------------- def dispose return if @actor == nil dispose_skill if ENABLE_SKILL_HUD dispose_item if ENABLE_ITEM_HUD dispose_weapon if ENABLE_WEAPON_HUD dispose_shield if ENABLE_SHIELD_HUD dispose_gold if ENABLE_GOLD_HUD @icon_image.dispose @number_image.dispose end #-------------------------------------------------------------------------- # ● Dispose Skill #-------------------------------------------------------------------------- def dispose_skill @skill_layout_sprite.bitmap.dispose @skill_layout_sprite.dispose @skill_icon_sprite.bitmap.dispose @skill_icon_sprite.dispose @skill_number_sprite.bitmap.dispose @skill_number_sprite.dispose end #-------------------------------------------------------------------------- # ● Dispose Gold #-------------------------------------------------------------------------- def dispose_gold @gold_layout_sprite.bitmap.dispose @gold_layout_sprite.dispose @gold_number_sprite.bitmap.dispose @gold_number_sprite.dispose end #-------------------------------------------------------------------------- # ● Dispose Item #-------------------------------------------------------------------------- def dispose_item @item_layout_sprite.bitmap.dispose @item_layout_sprite.dispose @item_icon_sprite.bitmap.dispose @item_icon_sprite.dispose @item_number_sprite.bitmap.dispose @item_number_sprite.dispose end #-------------------------------------------------------------------------- # ● Dispose Weapon #-------------------------------------------------------------------------- def dispose_weapon @weapon_layout_sprite.bitmap.dispose @weapon_layout_sprite.dispose @weapon_icon_sprite.bitmap.dispose @weapon_icon_sprite.dispose @weapon_number_sprite.bitmap.dispose @weapon_number_sprite.dispose end #-------------------------------------------------------------------------- # ● Dispose shield #-------------------------------------------------------------------------- def dispose_shield @shield_layout_sprite.bitmap.dispose @shield_layout_sprite.dispose @shield_icon_sprite.bitmap.dispose @shield_icon_sprite.dispose @shield_number_sprite.bitmap.dispose @shield_number_sprite.dispose end #-------------------------------------------------------------------------- # ● Update #-------------------------------------------------------------------------- def update return if @actor == nil update_visible refresh if can_refresh_hud? refresh_item if ENABLE_ITEM_HUD and can_refresh_item_number? refresh_weapon_number if ENABLE_WEAPON_HUD and can_refreh_weapon_number? refresh_shield_number if ENABLE_SHIELD_HUD and can_refreh_shield_number? update_gold if ENABLE_GOLD_HUD end #-------------------------------------------------------------------------- # ● Update Gold #-------------------------------------------------------------------------- def update_gold gold_number_down if @gold > $game_party.gold gold_number_up if @gold < $game_party.gold gold_number_update if @gold_refresh end #-------------------------------------------------------------------------- # ● Can Refresh Weapon Number #-------------------------------------------------------------------------- def can_refreh_weapon_number? return true if @weapon_number != $game_party.item_number(@w_item) return false end #-------------------------------------------------------------------------- # ● Can Refresh Shield Number #-------------------------------------------------------------------------- def can_refreh_shield_number? return true if @shield_number != $game_party.item_number(@s_item) return false end #-------------------------------------------------------------------------- # ● Update Visible #-------------------------------------------------------------------------- def update_visible vis = $game_system.enable_hud if ENABLE_SKILL_HUD @skill_layout_sprite.visible = vis @skill_icon_sprite.visible = vis @skill_number_sprite.visible = vis end if ENABLE_ITEM_HUD @item_layout_sprite.visible = vis @item_icon_sprite.visible = vis @item_number_sprite.visible = vis end if ENABLE_WEAPON_HUD @weapon_layout_sprite.visible = vis @weapon_icon_sprite.visible = vis @weapon_number_sprite.visible = vis end if ENABLE_SHIELD_HUD @shield_layout_sprite.visible = vis @shield_icon_sprite.visible = vis @shield_number_sprite.visible = vis end if ENABLE_GOLD_HUD @gold_layout_sprite.visible = vis @gold_number_sprite.visible = vis end end #-------------------------------------------------------------------------- # ● Can Refresh Hud #-------------------------------------------------------------------------- def can_refresh_hud? if @actor != nil if ENABLE_SKILL_HUD return true if @old_skill != @actor.skill_id end if ENABLE_ITEM_HUD return true if @old_item != @actor.item_id end if ENABLE_WEAPON_HUD return true if @old_weapon != @actor.equips[0] end if ENABLE_SHIELD_HUD return true if @old_shield != @actor.equips[1] end end return false end #-------------------------------------------------------------------------- # ● Can Refresh Item Number #-------------------------------------------------------------------------- def can_refresh_item_number? return true if @item_number != $game_party.item_number(@item) return false end #-------------------------------------------------------------------------- # ● Create Item #-------------------------------------------------------------------------- def refresh_item @item_number = $game_party.item_number(@item) #Item Number ------------------------------------------------------------ @item_number_sprite.bitmap.clear cost_split = @item_number.to_s.split(//) for r in 0..cost_split.size - 1 number_abs = cost_split[r].to_i src_rect = Rect.new(@number_cw * number_abs, 0, @number_cw, @number_ch) @item_number_sprite.bitmap.blt(@number_sc * r, 0, @number_image, src_rect) end xf = ((cost_split.size * @number_sc) / 2) @item_number_sprite.x = ITEM_HUD[0] + NUMBER[0] - xf end #-------------------------------------------------------------------------- # ● gold_number_up #-------------------------------------------------------------------------- def gold_number_up @gold_refresh = true @gold_ref = 20 * (@gold - @gold_old) / 100 @gold_ref = 1 if @gold_ref < 1 @gold += @gold_ref if @gold >= $game_party.gold @gold_old = $game_party.gold @gold = $game_party.gold @gold_ref = 0 end end #-------------------------------------------------------------------------- # ● gold_number_down #-------------------------------------------------------------------------- def gold_number_down @gold_refresh = true @gold_ref = 10 * (@gold_old - @gold) / 100 @gold_ref = 1 if @gold_ref < 1 @gold -= @gold_ref if @gold <= $game_party.gold @gold_old = $game_party.gold @gold = $game_party.gold @gold_ref = 0 end end #-------------------------------------------------------------------------- # ● gold_number_update #-------------------------------------------------------------------------- def gold_number_update @gold_number_sprite.bitmap.clear @gold_number_text = @gold.abs.to_s.split(//) for r in 0..@gold_number_text.size - 1 @gold_number_abs = @gold_number_text[r].to_i gold_src_rect = Rect.new(@number_cw * @gold_number_abs, @number_ch * 2, @number_cw, @number_ch) @gold_number_sprite.bitmap.blt(@number_cw * r, 0, @number_image, gold_src_rect) end @gold_refresh = false if @gold == $game_party.gold end end #============================================================================== # ■ Spriteset_Map #============================================================================== class Spriteset_Map #-------------------------------------------------------------------------- # ● initialize #-------------------------------------------------------------------------- alias mog_tool_hud_initialize initialize def initialize @toolhud = Tool_Hud.new mog_tool_hud_initialize end #-------------------------------------------------------------------------- # ● Dispose #-------------------------------------------------------------------------- alias mog_tool_hud_dispose dispose def dispose @toolhud.dispose mog_tool_hud_dispose end #-------------------------------------------------------------------------- # ● update #-------------------------------------------------------------------------- alias mog_tool_hud_update update def update @toolhud.update mog_tool_hud_update end #-------------------------------------------------------------------------- # ● Refresh Hud #-------------------------------------------------------------------------- alias mog_tool_hud_refresh_hud refresh_hud def refresh_hud mog_tool_hud_refresh_hud @toolhud.refresh end end $mog_rgss3_xas_tool_hud = true
    true
    f4b5535ff352b373fab7bd6135e6899b11a5f696
    Ruby
    yumidev/memory
    /game.rb
    UTF-8
    572
    3.453125
    3
    []
    no_license
    require_relative 'board' class Game def initialize @board = Board.new @previous_guess end def play @board.populate while [email protected]? @board.render guessed_pos = gets.chomp.to_i @board.reveal(guessed_pos) make_guess(guessed_pos) end end def make_guess(pos) if @previous_guess unless @board.same_card?(@previous_guess, pos) @board.hide(pos) @board.hide(@previous_guess) end @previous_guess = nil else @previous_guess = pos end end end game = Game.new game.play
    true
    70b9d8386b8cfb199ab330fec129246d54e0d353
    Ruby
    jesusmaldonado/primes
    /lib/primes/prime_parser.rb
    UTF-8
    359
    2.53125
    3
    [ "MIT" ]
    permissive
    require_relative 'prime_table' require_relative 'prime_generator' module Primes class PrimeParser def initialize(opts = {}) @prime_generator = Primes::PrimeGenerator.new(opts) @prime_table = Primes::PrimeTable.new() end def print @prime_table.primes = @prime_generator.primes @prime_table.print_table end end end
    true
    b72bf55a7f445da02360fe482b6e204d707d78c2
    Ruby
    nonsensery/ar_validation_sample
    /test/models/post_test.rb
    UTF-8
    1,938
    2.875
    3
    []
    no_license
    require 'test_helper' class PostTest < ActiveSupport::TestCase test 'duplicate tag is detected when added to new post' do tag = Tag.first # Create a new post: post = Post.new # Add a tag: post.post_tags.new tag: tag # Post should be valid assert post.valid? # Add a duplicate tag: post.post_tags.new tag: tag # Check validity: assert (post.valid? == false), 'Post is valid dispite duplicate tags' end test 'duplicate tag prevents saving' do tag = Tag.first # Create a new post: post = Post.new # Add a tag: post.post_tags.new tag: tag # Add a duplicate tag: post.post_tags.new tag: tag # Check savability: assert (post.save == false), 'Saved post dispite duplicate tags' end test 'saving the post should save all post-tags, or the save should fail' do tag = Tag.first # Create a new post: post = Post.new # Add a tag: post.post_tags.new tag: tag # Add a duplicate tag: post.post_tags.new tag: tag # Save the post: post.save! # Check whether the first post-tag was saved: assert (post.post_tags.first.id != nil), 'Saved post, but not first duplicate post-tag' # Check whether the second post-tag was saved: assert (post.post_tags.second.id != nil), 'Saved post, but not second duplicate post-tag' end test 'saving the post should not change the detection of duplicate tags' do tag = Tag.first # Create a new post: post = Post.new # Add a tag: post.post_tags.new tag: tag # Add a duplicate tag: post.post_tags.new tag: tag # Record the validity before saving was_valid = post.valid? # Save the post: post.save! # Check the validity after saving is_valid = post.valid? # Validity should not change! assert (was_valid == is_valid), "Saving post changed its validity from #{was_valid} to #{is_valid}" end end
    true
    c069811d01e1b47eaed9320fe07c84bf342d4c6c
    Ruby
    DavidMcKenzie218/Week_1_Homework
    /Day_2/functions_practice_lab/ruby_functions_practice.rb
    UTF-8
    1,879
    3.5625
    4
    []
    no_license
    def return_10() return 10 end def add(number1, number2) result = number1 + number2 return result end def subtract(number1, number2) result = number1 - number2 return result end def multiply(number1, number2) result = number1 * number2 return result end def divide(number1, number2) result = number1/number2 return result end def length_of_string(string) result = string.length return result end def join_string(string1, string2) result = string1 + string2 return result end def add_string_as_number(string1, string2) result = string1.to_i + string2.to_i return result end def number_to_full_month_name(number) case number when 1 return "January" when 2 return "Febuary" when 3 return "March" when 4 return "April" when 5 return "May" when 6 return "June" when 7 return "July" when 8 return "August" when 9 return "September" when 10 return "October" when 11 return "November" when 12 return "December" end end def number_to_short_month_name(number) case number when 1 return "Jan" when 2 return "Feb" when 3 return "Mar" when 4 return "Apr" when 5 return "May" when 6 return "Jun" when 7 return "Jul" when 8 return "Aug" when 9 return "Sep" when 10 return "Oct" when 11 return "Nov" when 12 return "Dec" end end def volume_of_a_cube(side_length) volume = side_length**3 return volume end def volume_of_a_sphere(radius) pi = Math::PI volume = (4.0/3) * pi * (radius**3) return volume.round(2) end def fahrenheit_to_celcius(fahrenheit) celcius = (fahrenheit.to_f - 32) * 5 / 9 return celcius.round(1) end def password_generator(name, number) new_name = name.swapcase new_number = number*2 new_password = "#{new_name}"+new_number.to_s return new_password end
    true
    fc00a59c5bce5b15c32aaa1dbe92fc331bebb4ad
    Ruby
    nkirkus/testing
    /Game/testloop.rb
    UTF-8
    99
    3
    3
    []
    no_license
    i = -99 puts "Before : " + i.to_s (1..10).each{|i| print 1; puts " haha"} puts "After : " + i.to_s
    true
    551367efc3da1488541449746a16d92ee11ba24b
    Ruby
    mezbahalam/script_quote_city
    /run.rb
    UTF-8
    1,312
    2.640625
    3
    []
    no_license
    ### Health Leads Lead Type — > 114 input fields https://leads.usacoverage.com/pingPostSpec.php?TYPE=6 # require 'nokogiri' # file = File.open('ping.html') # html = Nokogiri::HTML(file) # data = html.css("a+ .hilite .left:nth-child(3)") # #xpath("//a+//*[contains(concat( ' ', @class, ' ' ), concat( ' ', 'hilite', ' ' ))]//*[contains(concat( ' ', @class, ' ' ), concat( ' ', 'left', ' ' )) and (((count(preceding-sibling::*) + 1) = 3) and parent::*)]") # output = File.new('generator_command.txt', 'w+') # data.each do |data| # field = data.text # File.open('generator_command.txt', 'a') { |f| f.write(field + " ") } # end ## Medicare Leads Lead Type — > 48 input fields https://leads.usacoverage.com/pingPostSpec.php?TYPE=7 require 'nokogiri' require 'open-uri' html = Nokogiri::HTML(open('https://leads.usacoverage.com/pingPostSpec.php?TYPE=7')) data = html.css("a+ .hilite .left:nth-child(3)") #xpath("//a+//*[contains(concat( ' ', @class, ' ' ), concat( ' ', 'hilite', ' ' ))]//*[contains(concat( ' ', @class, ' ' ), concat( ' ', 'left', ' ' )) and (((count(preceding-sibling::*) + 1) = 3) and parent::*)]") output = File.new('medicare_generator_command.txt', 'w+') data.each do |data| field = data.text File.open('medicare_generator_command.txt', 'a') { |f| f.write(field + " ") } end
    true
    0be33067f6434e405c634ecfea3125a89fc6f56b
    Ruby
    salomekbg/prime-ruby-001-prework-web
    /prime.rb
    UTF-8
    286
    3.734375
    4
    [ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
    permissive
    def prime?(num) numbers = (2...num).to_a check = false numbers.each do |item| if num < 2 check = false elsif num == 2 check = true elsif num % item != 0 check = true elsif num % item == 0 check = false break end end check end
    true
    8def2db9abea87b94b693b9dcb90bf26c0865b8e
    Ruby
    kennym/saas-class
    /hw1/cartesian_product.rb
    UTF-8
    229
    3.515625
    4
    []
    no_license
    class CartesianProduct include Enumerable attr_accessor :xs, :ys def initialize(lhs, rhs) @xs, @ys = lhs, rhs end def each @xs.each do |x| @ys.each do |y| yield x, y end end end end
    true
    5559f9c6a99d2a2963b74267697b08f00a8dcb12
    Ruby
    ShinyVerse/anagram-app
    /spec/feature/app_spec.rb
    UTF-8
    1,037
    2.796875
    3
    []
    no_license
    require 'app' require 'anagram' describe 'Feature' do let(:app) { App.new(Anagram.new) } before(:each) do app.parse_user_input("era cat rat are pear ear") end context 'found anagrams' do it 'prints expected positive output' do allow(STDIN).to receive(:gets).and_return("tac\n", "exit\n") expect { app.start_app }.to output("Enter a word and receive anagrams from the list of your word\n"\ "Write 'exit' to finish\n"\ "Please enter your word to check\n"\ "The anagrams found are: \n"\ "cat\n"\ "Please enter your word to check\n").to_stdout end end context 'no anagram matches' do it 'prints expected negative output' do allow(STDIN).to receive(:gets).and_return("wrong\n", "exit\n") expect { app.start_app }.to output("Enter a word and receive anagrams from the list of your word\n"\ "Write 'exit' to finish\n"\ "Please enter your word to check\n"\ "No matches\n"\ "Please enter your word to check\n").to_stdout end end end
    true
    63a4e6ebc06ad3c7637b29f90c161244cdb122cf
    Ruby
    mcwaller422/Intro_to_Ruby
    /Arrays/Mutate.rb
    UTF-8
    180
    3.75
    4
    []
    no_license
    a = [1,2,3,4,5,6] def mutate(arr) arr.pop end def not_mutate(arr) arr.select{|i| i >3} end a = [1,2,3,4,5,6] mutate(a) puts a a = [1,2,3,4,5,6] not_mutate(a) puts a
    true
    ae72def25a8499bb36f655c78c42ecb8881853c3
    Ruby
    robopro/2019-06-14-Cookbook-day-1
    /controller.rb
    UTF-8
    825
    3.078125
    3
    []
    no_license
    require_relative 'view' class Controller def initialize(cookbook) @cookbook = cookbook @view = View.new end def list # first get all recipes from cookbook recipes = @cookbook.all # send data to view @view.display(recipes) end def create # add a new recipe: # ask user for name name = @view.ask_for(:name) # ask user for description description = @view.ask_for(:description) # create recipe from name and description recipe = Recipe.new(name, description) # pass recipe to cookbook @cookbook.add_recipe(recipe) end def destroy # display all the recipes list # ask the user for which recipe index = @view.ask_for_index # delete recipe from cookbook @cookbook.remove_recipe(index) # show the new recipe list end end
    true
    7dcdfc4cbfe1f04524604c3f6474c938cc004deb
    Ruby
    rimuhosting/fog
    /lib/fog/model.rb
    UTF-8
    1,971
    2.75
    3
    [ "MIT" ]
    permissive
    module Fog class Model def self.attribute(name, other_names = []) class_eval <<-EOS, __FILE__, __LINE__ attr_accessor :#{name} EOS @attributes ||= [] @attributes |= [name] for other_name in [*other_names] aliases[other_name] = name end end def self.identity(name, other_names = []) @identity = name self.attribute(name, other_names) end def self.aliases @aliases ||= {} end def self.attributes @attributes ||= [] end def attributes attributes = {} for attribute in self.class.attributes attributes[attribute] = send("#{attribute}") end attributes end def collection @collection end def identity send(self.class.instance_variable_get('@identity')) end def initialize(new_attributes = {}) merge_attributes(new_attributes) end def inspect data = "#<#{self.class.name}" for attribute in self.class.attributes data << " #{attribute}=#{send(attribute).inspect}" end data << ">" end def merge_attributes(new_attributes = {}) for key, value in new_attributes if aliased_key = self.class.aliases[key] send("#{aliased_key}=", value) else send("#{key}=", value) end end self end def new_record? !identity end def reload new_attributes = collection.get(identity).attributes merge_attributes(new_attributes) end private def collection=(new_collection) @collection = new_collection end def connection=(new_connection) @connection = new_connection end def connection @connection end def remap_attributes(attributes, mapping) for key, value in mapping if attributes.key?(key) attributes[value] = attributes.delete(key) end end end end end
    true
    22a205d2e20118269cad67337cfc3832f979697d
    Ruby
    cesartalves/ruby_metaprogramming_as_spec
    /spec/callables/blocks_spec.rb
    UTF-8
    1,392
    3.359375
    3
    []
    no_license
    require 'spec_helper' describe "Ruby Blocks" do def method_using_block_implicitly yield end def method_using_block_explicity(&block) block.call end it "they will run the code which is passed to the method" do expect(method_using_block_implicitly { 5 }).to eq 5 end it "they can be multilined, like a foreach" do expect( method_using_block_implicitly do 4 end).to eq 4 end it "they can receive block explicitly" do expect(method_using_block_explicity {5} ).to eq 5 end it "they can raise erros if no blocks are passed" do expect { method_using_block_implicitly }.to raise_error LocalJumpError end it "are a Proc/Closures" do end it "Self yield" do class String def yield_self yield self.class end end expect do "This is a string".yield_self { |x| print x } end.to output('String').to_stdout end it "Symbol.to_proc" do expect([1, 2, 3].map(&:to_s)).to include("1", "2", "3") # this is how ruby implements it, sort of class Symbol def to_proc Proc.new { |x| x.send self } end end expect([1, 2, 3].map(&:to_s)).to include("1", "2", "3") end end
    true
    7e3c8b4fd45faabb5021633ee46caa44c3a50580
    Ruby
    adambeynon/opal
    /lib/opal/nodes/if.rb
    UTF-8
    1,619
    2.515625
    3
    [ "MIT" ]
    permissive
    require 'opal/nodes/base' module Opal module Nodes class IfNode < Base handle :if children :test, :true_body, :false_body RUBY_ENGINE_CHECK = [:call, [:const, :RUBY_ENGINE], :==, [:arglist, [:str, "opal"]]] RUBY_PLATFORM_CHECK = [:call, [:const, :RUBY_PLATFORM], :==, [:arglist, [:str, "opal"]]] def compile truthy, falsy = self.truthy, self.falsy if skip_check_present? falsy = nil end push "if (", js_truthy(test), ") {" # skip if-body if no truthy sexp indent { line stmt(truthy) } if truthy if falsy if falsy.type == :if line "} else ", stmt(falsy) else indent do line "} else {" line stmt(falsy) end line "}" end else push "}" end wrap "(function() {", "; return nil; })()" if needs_wrapper? end # pre-processing only effects falsy blocks. If engine is # opal, then falsy block gets generated as normal. Unless # engine is opal then that code gets generated as the # falsy block def skip_check_present? test == RUBY_ENGINE_CHECK or test == RUBY_PLATFORM_CHECK end def truthy needs_wrapper? ? compiler.returns(true_body || s(:nil)) : true_body end def falsy needs_wrapper? ? compiler.returns(false_body || s(:nil)) : false_body end def needs_wrapper? expr? or recv? end end end end
    true
    7c504d0ae57cc77fa63d4b1d70373c7a87e9c3f3
    Ruby
    Tim-Feng/learn-to-program
    /ch12-2.rb
    UTF-8
    177
    3.25
    3
    []
    no_license
    puts "Please enter the year you born:" born_y = gets.chomp puts "Please enter the month you born:" born_m = gets.chomp puts "Please enter the date you born:" born_y = gets.chomp
    true
    bf00e71275725e61820bbf02d6ffb4dc65ba0a66
    Ruby
    hawthornehaus/astronom-web
    /app/models/nutrient_loss.rb
    UTF-8
    2,298
    2.53125
    3
    [ "MIT" ]
    permissive
    class NutrientLoss include Enumerable delegate :[], :each, :to => :loss_table attr_reader :from, :to, :gender, :duration_in_seconds, :significance def initialize(from: , to: , gender: , significance: 6) @gender = gender # currently unused @from = from.to_time @to = to.to_time @duration_in_seconds = ((@to - @from) / 1.seconds).round @significance = significance end def loss_table @loss_table ||= calculate_losses end alias_method :all, :loss_table def calculate_losses LOSSES_PER_DAY.each.with_object({}) do |(nutrient, loss_per_day), acc| acc[nutrient] = (loss_per_day * (duration_in_seconds / SECONDS_IN_DAY)).round(significance) end end SECONDS_IN_DAY = 86400.0 LOSSES_PER_DAY = { 'water' => 3000.0, 'energy' => 3200.0, 'protein' => 202.0, 'total_lipid' => 54.0, # 'ash' => 'carbohydrates' => 486.0, 'fiber_td' => 43.0, 'total_sugar' => 38.0, 'calcium' => 1000.0, 'iron' => 8.0, 'magnesium' => 420.0, 'phosphorus' => 700.0, 'potassium' => 3000.0, 'sodium' => 3000.0, 'zinc' => 11.0, 'copper' => 900.0, 'maganese' => 9.0, 'selenium' => 55.0, 'vitamin_c' => 90.0, 'thiamin' => 1.2, 'riboflavin' => 1.3, 'niacin' => 16.0, 'panto_acid' => 5.0, 'vitamin_b6' => 1.3, 'total_folate' => 400.0, # 'folic_acid' => # 'food_folate' => # 'folate_dfe' => 'total_choline' => 550.0, 'vitamin_b12' => 2.4, 'vitamin_a' => 900.0, 'retinol' => 900.0, 'alpha_carotene' => 4.71, 'vitamin_e' => 15.0, 'vitamin_d' => 5.0, 'vitamin_k' => 120.0, 'fat_saturated' => 9.0, 'fat_monounsaturated' => 25.0, 'fat_polyunsaturated' => 20.0, 'cholesterol' => 300.0, # 'beta_carotene' => # 'beta_cryptoxanthin' => # 'lycopene' => # 'lutein_and_zeaxanthin' => } end
    true
    7e833c69b16cc89afe8f1795e77dac67d4365856
    Ruby
    zauzaj/prime_number_list
    /lib/concern/prime_number_generator.rb
    UTF-8
    451
    3.390625
    3
    []
    no_license
    require 'pry-rails' module PrimeNumberGenerator def generate starting_value, ending_value primes_list = [] input_order_changing(starting_value, ending_value).to_a.each do |value| primes_list << value if isPrime(value) end primes_list end def isPrime argument (2..(argument/2)).to_a.all? {|div| argument%div > 0} end def input_order_changing num1, num2 num1 if num1 == num2 num1 > num2 ? (num2..num1) : (num1..num2) end end
    true
    ce3568e273896e8872369bb4a204231114444382
    Ruby
    chiensiTB/OpenStudio-server-orig
    /gems/gems/dencity-0.1.0/lib/dencity/client/structure.rb
    UTF-8
    4,497
    2.71875
    3
    [ "BSD-2-Clause" ]
    permissive
    module Dencity # Structure methods class Structure include Request attr_accessor :analysis_id attr_accessor :user_defined_id attr_accessor :structure attr_accessor :measure_instances # initialize def initialize(analysis_id = nil, user_defined_id = nil, path = nil, connection) @analysis_id = analysis_id @user_defined_id = user_defined_id @structure = Hashie::Mash.new @measure_instances = Hashie::Mash.new @connection = connection # initialize with json file unless path.nil? load_from_file(path) end @upload_retries = nil end def push begin @upload_retries ||= 0 response = post('api/structure', format_structure) @structure.id = response['id'] if response['id'] return response if response rescue StandardError => se # Decide if we should fail based on number of retries if @upload_retries < 3 raise 'could not upload' else # or here: @upload_retries = nil return se end end rescue => e @upload_retries += 1 sleep 2 retry ensure # always do this # verify that this is only called if the retry is not triggered @upload_retries = nil end # load structure from json file into a mash def load_from_file(path) return unless File.exist?(path) json_data = File.read(path) load_raw_json(json_data) end # load structure from raw json def load_raw_json(json_data) temp = Hashie::Mash.new(MultiJson.load(json_data)) @structure = temp.structure ? temp.structure : Hashie::Mash.new @measure_instances = temp.measure_instances ? temp.measure_instances : Hashie::Mash.new # these could be set in the file @analysis_id = temp.structure.analysis_id if temp.structure.analysis_id @user_defined_id = temp.structure.user_defined_id if temp.structure.user_defined_id return true end # upload file def upload_file(path, file_name = nil) fail 'No Structure ID defined for structure. Can\'t upload file' if @structure.id.nil? file = File.open(path, 'rb') the_file = Base64.strict_encode64(file.read) file.close # file_data param file_data = {} file_data['file_name'] = file_name.nil? ? File.basename(path) : file_name file_data['file'] = the_file data = Hashie::Mash.new data.structure_id = @structure.id data.file_data = file_data push_file('api/related_file', MultiJson.dump(data)) end # delete an uploaded file # if structure_id is nil, will use @structure.id def delete_file(file_name) fail 'No Structure ID defined for structure. Can\'t delete file' if @structure.id.nil? data = Hashie::Mash.new data.structure_id = @structure.id data.file_name = file_name push_file('api/remove_file', MultiJson.dump(data)) end # push file w/ retry def push_file(path, data) begin @upload_retries ||= 0 response = post(path, data) return response if response rescue StandardError => se # Decide if we should fail based on number of retries if @upload_retries < 3 if path.include? 'remove' raise 'could not delete file' else raise 'could not upload file' end else return se end end rescue => e @upload_retries += 1 sleep 2 retry ensure # verify that this is only called if the retry is not triggered @upload_retries = nil end private # formats structure parameters for posting def format_structure # generate name/value pairs for structure metadata formatted_meta = [] @structure.each do |k, v| formatted_meta << { name: k, value: v } unless %w(id user_defined_id analysis_id).include?(k) end new_struct = Hashie::Mash.new new_struct.metadata = formatted_meta # TODO: what if it's already in the structure hash? # add user_defined_id to structure new_struct.user_defined_id = @user_defined_id new_struct.analysis_id = @analysis_id data_hash = Hashie::Mash.new data_hash.structure = new_struct data_hash.measure_instances = @measure_instances ? @measure_instances : [] # convert to json MultiJson.dump(data_hash) end end end
    true
    e5bddb0675f89233850d478eb4e152d095de422f
    Ruby
    ak061295/Radlibs
    /mad_libs.rb
    UTF-8
    488
    2.53125
    3
    []
    no_license
    require 'sinatra' get '/' do erb :form end get '/upload' do erb :upload end get '/story' do erb :story end post '/' do @name = "#{params[:post][:first_name]} #{params[:post][:last_name]}" @fname = "#{params[:post][:first_name]}" @lname = "#{params[:post][:last_name]}" if @name == "Brennan Kinney" erb "Buckets" elsif @name == "Anthony Kennedy" erb "Nooo!!! Jimmy!!!" else erb "Hello, #{@name}. Welcome to my submarine. It's long and hard and full of seamen." end end
    true
    81d57a9e7ea135b60ab5cb48984c6f4c380b1804
    Ruby
    h11z/ruby-oo-relationships-practice-blood-oath-exercise-chi01-seng-ft-080320
    /app/models/Followers.rb
    UTF-8
    841
    3.140625
    3
    [ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
    permissive
    class Follower attr_accessor attr_reader :name, :age, :life_motto @@all = [] def self.all @@all end def initialize(name,age,life_motto) @name = name @age = age @life_motto = life_motto @@all << self end def cults cults_im_in = BloodOath.all.filter do |cult_lister| cult_lister.name.name == self.name end just_cults = cults_im_in.map do |cult_map| cult_map.cult end just_cults end def join_cult(cult) BloodOath.new(self,cult,"2020-02-25") end def self.of_a_certain_age(num) follower_map = Follower.all.map do |finder| if finder.age >= num finder end end follower_map.compact end end #end of follower class
    true
    b856ed8910a721ee6cea960c5bf55657908a348d
    Ruby
    realgam3/ysoserial.rb
    /lib/ysoserial/gadgets.rb
    UTF-8
    637
    2.578125
    3
    [ "Apache-2.0" ]
    permissive
    require 'pathname' module YSoSerial module Gadgets def self.load pattern = File.join(Pathname(__FILE__).dirname, "gadgets", "*.rb") Dir.glob(pattern).each do |path| Kernel.load(path) end end def self.table gadgets = {} self.load YSoSerial::Gadgets.constants.select do |const_symbol| const = YSoSerial::Gadgets.const_get(const_symbol) rescue nil if not const.nil? and const.is_a? Class class_name = const.name.split("::")[-1].to_sym gadgets[class_name] = const end end gadgets end end end
    true
    7ac9e5ac4bc5ac300000ad92e631310e8fce7800
    Ruby
    ministryofjustice/offender-management-allocation-manager
    /lib/working_day_calculator.rb
    UTF-8
    369
    2.984375
    3
    [ "MIT" ]
    permissive
    require 'bank_holidays' require 'business_time' class WorkingDayCalculator def initialize(holidays = BankHolidays.dates) BusinessTime::Config.holidays = Set.new(holidays) end def working_days_between(date1, date2) date1.business_days_until(date2) end def self.working_days_between(date1, date2) new.working_days_between(date1, date2) end end
    true
    5c092562fb4b50d6fdd4415bbb5ed6257b8d2069
    Ruby
    danielevans/gutenberg_text_search_compiler
    /parse.rb
    UTF-8
    7,245
    2.515625
    3
    []
    no_license
    require 'rubygems' require 'stemmify' require 'fileutils' require 'shellwords' require 'json' require 'benchmark' require 'pp' require 'pry' require 'optionparser' require 'set' require 'progressbar' STOP_WORDS = [ # ripped off from https://github.com/brez/stopwords/blob/master/lib/stopwords.rb 'a','cannot','into','our','thus','about','co','is','ours','to','above', 'could','it','ourselves','together','across','down','its','out','too', 'after','during','itself','over','toward','afterwards','each','last','own', 'towards','again','eg','latter','per','under','against','either','latterly', 'perhaps','until','all','else','least','rather','up','almost','elsewhere', 'less','same','upon','alone','enough','ltd','seem','us','along','etc', 'many','seemed','very','already','even','may','seeming','via','also','ever', 'me','seems','was','although','every','meanwhile','several','we','always', 'everyone','might','she','well','among','everything','more','should','were', 'amongst','everywhere','moreover','since','what','an','except','most','so', 'whatever','and','few','mostly','some','when','another','first','much', 'somehow','whence','any','for','must','someone','whenever','anyhow', 'former','my','something','where','anyone','formerly','myself','sometime', 'whereafter','anything','from','namely','sometimes','whereas','anywhere', 'further','neither','somewhere','whereby','are','had','never','still', 'wherein','around','has','nevertheless','such','whereupon','as','have', 'next','than','wherever','at','he','no','that','whether','be','hence', 'nobody','the','whither','became','her','none','their','which','because', 'here','noone','them','while','become','hereafter','nor','themselves','who', 'becomes','hereby','not','then','whoever','becoming','herein','nothing', 'thence','whole','been','hereupon','now','there','whom','before','hers', 'nowhere','thereafter','whose','beforehand','herself','of','thereby','why', 'behind','him','off','therefore','will','being','himself','often','therein', 'with','below','his','on','thereupon','within','beside','how','once', 'these','without','besides','however','one','they','would','between','i', 'only','this','yet','beyond','ie','onto','those','you','both','if','or', 'though','your','but','in','other','through','yours','by','inc','others', 'throughout','yourself','can','indeed','otherwise','thru','yourselves' ].map(&:stem) BLANK_LINE_REGEXP = /^$/ START_REGEXP = /^\*+\s*START[^$]*PROJECT GUTENBERG[^\*]*\*{3,}\s*$/im INITIAL_CHOMP_REGEXP = /\*{3,}[^*]*\*{3,}\s*/ END_REGEXP = /^\*+\s*END[^$]*PROJECT GUTENBERG/im PUNCTUATION_REGEXP = /\p{Punct}+$/ MINIMUM_WORDS = 2 class Parser attr_accessor :minimum_words attr_accessor :directories attr_accessor :verbose attr_accessor :progressbar def initialize dirs="gutenberg_data", min_words=MINIMUM_WORDS self.directories = Array(dirs) self.minimum_words = min_words end def whitelisted_word? word @whitelist ||= begin words = if File.exist? "whitelist.txt" File.read("whitelist.txt").split else generate_whitelist end Set.new words end @whitelist.include? word end def generate_whitelist words = (File.readlines("/usr/share/dict/words").map { |word| word.chomp.downcase.stem } - STOP_WORDS).uniq File.open("whitelist.txt", "wb") do |f| f.write @whitelist.join("\n") end words end def unzip f %x{unzip #{Shellwords.shellescape(f)}} end def cleanup Dir.glob("*.txt").each do |f| FileUtils.rm f end Dir.glob("*").each do |f| FileUtils.rm_r f if File.directory? f end end def paragraphs text aggregator_hash = Hash.new { |h, k| h[k] = 0 } text.split(BLANK_LINE_REGEXP).map do |paragraph| words = paragraph.gsub(/[\s]+/, ' ').split.each_with_object(aggregator_hash.dup) do |word, memo| sanitary_word = word.gsub(PUNCTUATION_REGEXP, '').downcase.stem memo[sanitary_word] += 1 if whitelisted_word?(sanitary_word) end if words.length >= self.minimum_words { text: paragraph.gsub("\n", " ").gsub(/\s+/, ' ').gsub(/^\s+/, '').gsub(/\s$/, ''), words: words } end end.compact end def write_result dir, results_dir, result destination_dir = File.join(results_dir, dir) FileUtils.mkdir_p destination_dir id = File.split(dir).last json = JSON.pretty_generate({ id: id, paragraphs: result }) File.open(File.join(destination_dir, "#{id}.json"), "wb") do |f| f.write(json) end end def get_textfile dir file = Dir.glob("*.zip").sort.first return nil if !file unzip file Dir.glob("**/*.txt").first end def process_directory dir puts "Processing: #{dir}" if verbose rt = Benchmark.realtime do results_dir = File.expand_path('./results') Dir.chdir dir do textfile = get_textfile dir if !textfile $stderr.puts "Error getting textfile for #{dir}" return false end file_data = nil File.open(textfile, 'rb') do |f| file_data = f.read end start_index = file_data.index START_REGEXP end_index = file_data.index END_REGEXP if start_index.nil? || end_index.nil? $stderr.puts "#{File.join(dir, textfile)} did not match expected regular expressions (s:#{start_index} e:#{end_index})" return false end file_data = file_data[start_index..end_index] .encode('UTF-8', invalid: :replace, undef: :replace, replace: '?') .gsub("\r", '') .gsub(INITIAL_CHOMP_REGEXP, '') .gsub(/^\s*$/,'') if file_data.length > 0 write_result dir, results_dir, paragraphs(file_data) else $stderr.puts "#{File.join(dir, textfile)} contains no data" end ensure cleanup end end puts "Complete: #{dir} #{rt}s" if verbose end def parse! count = 1 rt = Benchmark.realtime do whitelisted_word? "foo" # generates the whitelist in the right place all_files = directories.map do |dir| Dir.glob(File.join(dir, "**/*.zip")) end.flatten.uniq files_by_dir = all_files.group_by { |f| f.gsub(/(.*)\/[^\/]*/, "\\1") } count = files_by_dir.length puts "#{count} directories detected" progressbar.total = count if progressbar files_by_dir.each_key.sort.each do |dir| process_directory dir progressbar.increment if progressbar end end puts "Complete in #{rt}s" end end parser = Parser.new OptionParser.new do |opts| opts.banner = "Usage: parse.rb [options]" opts.on("-v", "--[no-]verbose", "Run verbosely") do |v| options[:verbose] = v end opts.on("-d=dir", "--directory=dir,dir,dir", Array, "directory to parse") do |v| parser.directories = v end opts.on("-p", "show progress") do parser.progressbar = ProgressBar.create title: "Directories", format: "%t (%c/%C): %w" end end.parse! parser.parse!
    true
    be653cd5e01d9bf7faeae459adedf0f05a71e694
    Ruby
    Steimel/Thomas
    /lib/thomas/canvas.rb
    UTF-8
    910
    3.0625
    3
    [ "MIT" ]
    permissive
    module Thomas class Canvas attr_reader :width, :height, :things def initialize(width, height) @width = width @height = height @things = [] end def drawable_things @things.select{|thing| thing.drawable} end def place_thing(thing, r, c) thing.set_position(r,c) thing.canvas = self @things.push(thing) end def draw(border=false) self.to_s(border) end def to_s(border=false) output = Util.build_empty_string_box(@width, @height) drawable_things.each do |thing| output = thing.draw(output, @width, @height) end if border top_bottom_bar = ('-' * (@width + 2)) return top_bottom_bar + "\n\r" + output.map{|row| '|' + row.join('') + '|'}.join("\n\r") + "\n\r" + top_bottom_bar else return output.map{|row| row.join('')}.join("\n\r") end end end end
    true
    7191bae7995ed1457716218e7d945de263d3e8c2
    Ruby
    soutaro/querly
    /lib/querly/pattern/kind.rb
    UTF-8
    1,603
    2.734375
    3
    [ "MIT" ]
    permissive
    module Querly module Pattern module Kind class Base attr_reader :expr def initialize(expr:) @expr = expr end end module Negatable attr_reader :negated def initialize(expr:, negated:) @negated = negated super(expr: expr) end end class Any < Base def test_kind(pair) true end end class Conditional < Base include Negatable def test_kind(pair) !negated == !!conditional?(pair) end def conditional?(pair) node = pair.node parent = pair.parent&.node case parent&.type when :if node.equal? parent.children.first when :while node.equal? parent.children.first when :and node.equal? parent.children.first when :or node.equal? parent.children.first when :csend node.equal? parent.children.first else false end end end class Discarded < Base include Negatable def test_kind(pair) !negated == !!discarded?(pair) end def discarded?(pair) node = pair.node parent = pair.parent&.node case parent&.type when :begin if node.equal? parent.children.last discarded? pair.parent else true end else false end end end end end end
    true
    75136031563b97cec3cbbc1ec40018eee9b8ca04
    Ruby
    splashinn/Warmups
    /main.rb
    UTF-8
    1,268
    3.84375
    4
    []
    no_license
    # Load in all the shakespeare and remove newline characters def load_shakespeare File.read(File.dirname(__FILE__) + '/Shakespeare.txt').delete("\n") end shakespeare = load_shakespeare() # ******************** # REGEX DRILLS # Use regular expressions to answer the following questions: # How many words does Shakespeare use? shakespeare.split(/\w+/).count # How many different words does Shakespeare use? shakespeare.scan(/\w+/).uniq.count # How many times does Shakespeare use the word 'the'? shakespeare.scan.(/the/i).count # How many times does Shakespeare write "guildenstern" or "Guildenstern" shakespeare.scan.(/guildenstern/i).count # Find the entire "To be, or not to be- that is the question:" with as few regex characters as possible shakespeare.scan(/To be, or[-: \w+]/) # ******************** # Write a method that accepts a word and returns all the words in Shakespeare.txt that follow that word. # In other words, words_after('to') will return an array of words which include 'be'... since Shakespeare writes "to be" def words_after(word) shakespeare = File.read(File.dirname(__FILE__) + '/Shakespeare.txt') shakespeare.scan(Regexp.new(word + ' (\w+)')).uniq.flatten end #This should be true: # words_after('to').include?('be') #=> true
    true