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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
809b938ea7a323121a8234168bc29806eedbe047 | Ruby | JuanSaieh/Koombea | /Ruby-exercises/palindromo.rb | UTF-8 | 1,794 | 3.9375 | 4 | [] | no_license | # frozen_string_literal: true
# A palindromic number reads the same both ways. The largest palindrome made from the product
# of two 2 digit numbers is 9009 = 91 Ã 99.
# Find the largest palindrome made from the product of two 3-digit numbers.
# TODO
# - 2 rangos de 100...999
#
require 'minitest/autorun'
start = Time.now
class Palindrome
def palindrome?(num)
str = num.to_s
str == str.reverse
end
def largest_palindrome_digit(lower_limit, upper_limit)
num = 0
(lower_limit..upper_limit).each do |i|
(i..upper_limit).each do |j|
num = i*j if palindrome?(i*j) && num < i * j #Necesary condition -- line 31
end
end
num
end
end
puts "The largest palindrome multiplied by two 3-digit integers is: " +
Palindrome.new.largest_palindrome_digit(100, 999).to_s
finish = Time.now
puts diff = finish - start
# 924*962 = 888888 since it finds the palindrome 906609 first, then if we dont add the second condition it will return 888888
# 913 993 = 906609
describe Palindrome do
before do
@palindrome = Palindrome.new
end
describe '10 as lower_limit and 99 as upper_limit' do
it 'must return 9009' do
@palindrome.largest_palindrome_digit(10, 99).must_equal 9_009
end
end
describe '100 as lower_limit and 999 as upper_limit' do
it 'must return 906609' do
@palindrome.largest_palindrome_digit(100, 999).must_equal 906_609
end
end
describe '1 as lower_limit and 9 as upper_limit' do
it 'must fail, the answer is 9' do
@palindrome.largest_palindrome_digit(1, 9).wont_match 8
end
end
end
#================================
# def is_palindrome(num)
# arr = num.digits
# 0.upto(arr.length / 2) do |l|
# return false if arr[l] != arr[arr.length - 1 - l]
# end
# true
# end
| true |
f92594be8f31dcc29ef86b53661498cb4e916e44 | Ruby | ShaneTron/number_to_words | /lib/numbers_to_words.rb | UTF-8 | 1,465 | 3.71875 | 4 | [] | no_license | class Integer
def numbers_to_words()
one_to_ten = Hash.new()
one_to_ten.store(1,"one")
one_to_ten.store(2,"two")
one_to_ten.store(3,"three")
one_to_ten.store(4,"four")
one_to_ten.store(5,"five")
one_to_ten.store(6,"six")
one_to_ten.store(7,"seven")
one_to_ten.store(8,"eight")
one_to_ten.store(9,"nine")
one_to_ten.store(10,"ten")
# eleven_to_nineteen = Hash.new()
# eleven_to_nineteen.store(11,"eleven")
# eleven_to_nineteen.store(12,"twelve")
# eleven_to_nineteen.store(13,"thirteen")
# eleven_to_nineteen.store(14,"fourteen")
# eleven_to_nineteen.store(15,"fifteen")
# eleven_to_nineteen.store(16,"sixteen")
# eleven_to_nineteen.store(17,"seventeen")
# eleven_to_nineteen.store(18,"eighteen")
# eleven_to_nineteen.store(19,"nineteen")
#
twenty_to_ninetynine = Hash.new()
twenty_to_ninetynine.store(0, "")
twenty_to_ninetynine.store(1,"teen")
twenty_to_ninetynine.store(2,"twenty")
twenty_to_ninetynine.store(3,"thirty")
twenty_to_ninetynine.store(4,"fourty")
twenty_to_ninetynine.store(5,"fifty")
twenty_to_ninetynine.store(6,"sixty")
twenty_to_ninetynine.store(7,"seventy")
twenty_to_ninetynine.store(8,"eighty")
twenty_to_ninetynine.store(9,"ninety")
return twenty_to_ninetynine.fetch((self % 100)/10).concat(one_to_ten.fetch((self % 10)))
end
end
| true |
2b0433ae96752f854c2b601afd0fae407a4a3158 | Ruby | codeforamerica/vita-min | /spec/validators/alphanumeric_validator_spec.rb | UTF-8 | 917 | 2.546875 | 3 | [
"MIT"
] | permissive | require "rails_helper"
describe AlphanumericValidator do
before do
@validatable = Class.new do
include ActiveModel::Validations
validates_with AlphanumericValidator, attributes: :number
attr_accessor :number
end
end
subject { @validatable.new }
context "not allowed characters: supertext" do
before do
allow(subject).to receive(:number).and_return "101619702¹1"
end
it "is not valid" do
expect(subject).not_to be_valid
end
end
context "not allowed characters: dashes" do
before do
allow(subject).to receive(:number).and_return "101-619702-1"
end
it "is not valid" do
expect(subject).not_to be_valid
end
end
context "only allowed characters" do
before do
allow(subject).to receive(:number).and_return "WADLFKadjj94856"
end
it "is valid" do
expect(subject).to be_valid
end
end
end
| true |
7cd480d07abae9372539ddb05db846173f61b6a9 | Ruby | zeteticl/udonarium | /src/src_bcdice/diceBot/DemonParasite.rb | UTF-8 | 42,194 | 3 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
# frozen_string_literal: true
class DemonParasite < DiceBot
# ã²ãŒã ã·ã¹ãã ã®èå¥å
ID = 'DemonParasite'
# ã²ãŒã ã·ã¹ãã å
NAME = 'ãã¢ã³ãã©ãµã€ã'
# ã²ãŒã ã·ã¹ãã åã®èªã¿ããª
SORT_KEY = 'ãŠããã¯ããããš'
# ãã€ã¹ãããã®äœ¿ãæ¹
HELP_MESSAGE = <<INFO_MESSAGE_TEXT
ã»è¡å衚ã(URGEx)
ã"URGEè¡åã¬ãã«"ã®åœ¢ã§æå®ããŸãã
ãè¡å衚ã«åŸã£ãŠèªåã§éª°åããŒã«ãè¡ããçµæã衚瀺ããŸãã
ã骰åããŒã«ãšåæ§ã«ãä»ã®ç©å®¶ã«é ããŠããŒã«ããããšãå¯èœã§ãã
ãé ã«è奿åã远å ããŠãããã©ã«ã以å€ã®è¡å衚ãããŒã«ã§ããŸãã
ãã»NURGExãé ã«ãNããä»ãããšãæ°è¡å衚ãã
ãã»AURGExãé ã«ãAããä»ãããšã誀äœå衚ãã
ãã»MURGExãé ã«ãMããä»ãããšããã¥ãŒã¿ã³ãè¡å衚ãã«ãªããŸãã
ãã»UURGExãé ã«ãUããä»ããšé¬ŒåŸ¡éã®æŠéå€è¡å衚ã
ãã»CURGExãé ã«ãCãã§é¬ŒåŸ¡éã®æŠéäžè¡å衚ã«ãªããŸãã
äŸïŒURGE1ãããurge5ãããSurge2
ã»D66骰åãã
INFO_MESSAGE_TEXT
setPrefixes(['[NAMUC]?URGE\d+'])
def initialize
super
@sendMode = 2
@sortType = 1
@d66Type = 1
end
# ã²ãŒã 奿å床å€å®(nD6)
def check_nD6(total, _dice_total, dice_list, cmp_op, target)
if dice_list.count(1) >= 2 # ïŒã®ç®ãïŒå以äžãªããã¡ã³ãã«
return " ïŒ èŽåœç倱æ"
elsif dice_list.count(6) >= 2 # ïŒã®ç®ãïŒå以äžãã£ããã¯ãªãã£ã«ã«
return " ïŒ å¹æçæå"
elsif target == "?"
return ''
end
if [:>=, :>].include?(cmp_op)
if total.send(cmp_op, target)
" ïŒ æå"
else
" ïŒ å€±æ"
end
end
end
def rollDiceCommand(command)
return get_urge(command)
end
# è¡å衚
def get_urge(string)
m = /([NAMUC])?URGE\s*(\d+)/i.match(string)
unless m
return '1'
end
initialWord = m[1]
urgelv = m[2].to_i
case initialWord
when nil
title = "è¡å衚"
urge = URGE_TABLE
when "N"
title = "æ°è¡å衚"
urge = NEW_URGE_TABLE
when "A"
title = "誀äœå衚"
urge = MALFUNCTION_TABLE
when "M"
title = "ãã¥ãŒã¿ã³ãè¡å衚"
urge = MUTANT_TABLE
when "U"
title = "鬌埡é(æŠéå€)è¡å衚"
urge = ONIMITAMA_OUT_OF_BATTLE_TABLE
when "C"
title = "鬌埡é(æŠéäž)è¡å衚"
urge = ONIMITAMA_BATTLE_TABLE
else
# ããåŸãªãæå
return '1'
end
if urgelv < 1 || urgelv > 5
return 'è¡å段éã¯1ãã5ã§ã'
end
dice_now, = roll(2, 6)
resultText = urge[urgelv - 1][dice_now - 2]
return "#{title}#{urgelv}-#{dice_now}:#{resultText}"
end
# è¡å衚
URGE_TABLE = [
[
'ãæããçªç¶åŒ·ãæãã«é§ããããè¿ãã®å¯Ÿè±¡ã«(éæŽåã®)æããå
šåã§ã¶ã€ããããã®ã¿ãŒã³ã®çµäºãŸã§ãè¡åäžèœããšãªãã[çµéšå€20ç¹]',
'ãçµ¶å«ãå¯ççç©ãäœå
ã§è ¢ãããã®ææã«çµ¶å«ããã®ã¿ãŒã³ã®çµäºãŸã§ãè¡åäžèœããšãªãã[çµéšå€10ç¹]',
'ãæ²åãæ¥ã«æ²ããããšãæãåºããŠåããæ¢ãŸãããã®ã¿ãŒã³ã®çµäºãŸã§ãè¡åäžèœããšãªãã[çµéšå€10ç¹]',
'ã埮ç¬ãå¯ç¬ãããŠãããããªããããããç¬ããæ¢ãŸããããã®ã¿ãŒã³ã®çµäºãŸã§ãè¡åäžèœããšãªãã[çµéšå€10ç¹]',
'ãéæãè¡åã«æ°ãä»ããªãã£ããäœãèµ·ãããªãã[çµéšå€0ç¹]',
'ãæå¶ãè¡åãæã蟌ãã ãäœãèµ·ãããªãã[çµéšå€0ç¹]',
'ãææ
¢ãè¡åãææ
¢ãããäœãèµ·ãããªãã[çµéšå€0ç¹]',
'ãåå
ãæªéçç¹åŸŽãäžç¬ç®ç«ã€ãïŒã¿ãŒã³(10ç§)æç¶ãå€èº«äžãªã圱é¿ãªãã[çµéšå€10ç¹]',
'ãçºçŸãæªéçç¹åŸŽãæ¥ã«ç®ç«ã€ã60ã¿ãŒã³(10å)æç¶ãå€èº«äžãªã圱é¿ãªãã[çµéšå€10ç¹]',
'ãå€åãå©ãè
/åèãïŒã¿ãŒã³(20ç§)ãããŠæªéåããã18ã¿ãŒã³(3å)æç¶ãå€èº«äžãªã圱é¿ãªãã[çµéšå€20ç¹]',
'ãé¡çŸãå©ãè
/åèãç¬æã«æªéåã60ã¿ãŒã³(10å)æç¶ãå€èº«äžãªã圱é¿ãªãã[çµéšå€20ç¹]',
],
[
'ãè«ç¶ãæèãæ¢ãŸãããã®ã¿ãŒã³ã®çµäºãŸã§ãæ»æãè¡åãè¡ããªããåé¿è¡åã«åœ±é¿ã¯ãªãã[çµéšå€20ç¹]',
'ãæ¿æãåŽã«ãããã®(çç©ãç©äœåãã)ãæããæ®Žããå€èº«åŸãªãã°æ¬¡ã®ã¿ãŒã³ã®çµäºãŸã§ããã¹ãŠã®åœäžå€å®+5ãåé¿å€å®-5ã[çµéšå€20ç¹]',
'ãæ®å¿ã殺æãç Žå£è¡åãäžç¬å¢ããæŠéäžãªãã°æ¬¡ã®ã¿ãŒã³ã«è¡ããããæ»æãè¡åã®éæå€ã«+5ã[çµéšå€20ç¹]',
'ãèœæ¶ãéå»ã®æ²ããæ³ãåºã廿¥ããæ¶ãæº¢ãããïŒã¿ãŒã³(10ç§)ãéåžžãè¡åãè¡ããªããåé¿è¡åã«åœ±é¿ã¯ãªãã[çµéšå€10ç¹]',
'ãæå¶ãè¡åãæã蟌ãã ãäœãèµ·ãããªãã[çµéšå€0ç¹]',
'ãææ
¢ãè¡åãææ
¢ãããäœãèµ·ãããªãã[çµéšå€0ç¹]',
'ãå¿èãèäœãå·ã€ããŠè¡åã«èãããïŒãã¡ãŒãžã[çµéšå€10ç¹]',
'ãèŸæ±ãã»ãã®äžç¬ãå
šèº«ãå€èº«ãããããç¡çã«æããã®ã§ãïŒãã¡ãŒãžãå€èº«äžãªã圱é¿ãªãã[çµéšå€10ç¹]',
'ãç°è²ãïŒã¿ãŒã³(30ç§)ãããŠé¡ãå€èº«ããã18ã¿ãŒã³(3å)æç¶ãå€èº«äžãªã圱é¿ãªãã[çµéšå€20ç¹]',
'ãèŠçãå¯ççç©ãäœå
ã§æŽããçã¿ã«ã®ãããã10ãã¡ãŒãžã[çµéšå€20ç¹]',
'ãå€è²ãå€èº«åŸã®(ç¹ç°ãª)å€èŠçç¹åŸŽãïŒã¿ãŒã³(30ç§)ãããŠçŸããã18ã¿ãŒã³(3å)æç¶ãå€èº«äžãªã圱é¿ãªãã[çµéšå€20ç¹]',
],
[
'ãæ€æãæãã«å
šèº«ãæºãããããæ¬¡ã®ã¿ãŒã³ã®çµäºãŸã§ããã¹ãŠã®ãã¡ãŒãžã®ãµã€ã³ãã+1åããã[çµéšå€20ç¹]',
'ãå éãã»ãšã°ããè¡åã«ãããæ¬¡ã®ã¿ãŒã³ã¯ãè¡åå€ããïŒåã«ãªãã[çµéšå€20ç¹]',
'ãçºé²ãåãæº¢ãåºããæ¬¡ã®ã¿ãŒã³ã®çµäºãŸã§ããã¹ãŠã®ãã¡ãŒãžã«+5ãé²åŸ¡ç¹-5(æäœ0)ãããã[çµéšå€20ç¹]',
'ã也ããæ»æè¡åãæããããªããæ¬¡ã®ã¿ãŒã³ã®çµäºãŸã§å
šãŠã®åœäžå€å®+5ãåé¿å€å®-5ã[çµéšå€10ç¹]',
'ãçµ¶å«ããããéãã®å£°ã§å«ã¶ããã®ã¿ãŒã³ã®çµäºãŸã§ãå
šãŠã®åé¿å€å®ã«-10ã[çµéšå€10ç¹]',
'ãææ
¢ãè¡åãææ
¢ãããäœãèµ·ãããªãã[çµéšå€0ç¹]',
'ãéçãè¡åãç¡çç¢çæã蟌ãããã¡ãã¡ã®è¡ç®¡ãç Žè£ãã10ãã¡ãŒãžã[çµéšå€10ç¹]',
'ãè§£æŸãè¡åã«èããããå€èº«ãå§ãŸããïŒã¿ãŒã³(30ç§)ãããŠå€èº«ãå€èº«äžãªã圱é¿ãªãã[çµéšå€10ç¹]',
'ãæ¬èœãè¡åã«é§ãããç¬æã«å€èº«ã次ã®ã¿ãŒã³ãç®ã®åã®åããã®ãæµå³æ¹åºå¥ç¡ãæ»æããã[çµéšå€20ç¹]',
'ãä¿èº«ã次ã®ã¿ãŒã³ã®çµäºãŸã§ãæµãæ»æã§ããªããå
šãŠã®é²åŸ¡åã«+5ã[çµéšå€20ç¹]',
'ãææžãæªéå¯çäœã屿©ãå¯ç¥ããããšããžãŒãã20ç¹å埩ããã[çµéšå€20ç¹]',
],
[
'ãçããè¡åãïŒç¹äœ¿ã£ãå埩ãè¡ãã[çµéšå€20ç¹]',
'ãé¢è±ããã®å Žããéãåºããéããããªãå Žåã¯ãããããŸã£ãŠåããªããªããïŒã¿ãŒã³(10ç§)çµéããã°æã«è¿ãã[çµéšå€20ç¹]',
'ãè±åãæ¥ã«åãæãããæ¬¡ã®ã¿ãŒã³ã®çµäºãŸã§ãå
šãŠã®å€å®ã«-5ãããã[çµéšå€20ç¹]',
'ãå
šåãæ¿ããèºç¶æ
ãæ¬¡ã®ã¿ãŒã³ã®çµäºãŸã§ãåœäžå€å®ã«+10ãåé¿å€å®ã«-10[çµéšå€20ç¹]',
'ãæ··æ²ãæå³ã®ããèšèã話ããªããªããïŒæéæç¶ããã[çµéšå€10ç¹]',
'ãéçãè¡åãç¡çç¢çæã蟌ãããã¡ãã¡ã®è¡ç®¡ãç Žè£ãã10ãã¡ãŒãžã[çµéšå€10ç¹]',
'ãæ¬èœãè¡åã«é§ãããç¬æã«å€èº«ã次ã®ã¿ãŒã³ãç®ã®åã®åããã®ãæµå³æ¹åºå¥ç¡ãæ»æããã[çµéšå€20ç¹]',
'ãçŠç¥ãçŠãããã転åãããã[çµéšå€20ç¹]',
'ãççã峿¹ãæ¥ã«æµã«æãããå³åº§ã«è¿ãã®å³æ¹ã«äžåæ»æããèªååœäžãšãªããããªããã°åœ±é¿ãªãã[çµéšå€20ç¹]',
'ãèªèãèªåãèš±ããªããèªåãžæ»æ(èªååœäžããã¡ãŒãžã¯éåžž)ã[çµéšå€20ç¹]',
'ãèªæµãå°ãæã«è¿ããè¡åãïŒç¹å埩ããã[çµéšå€20ç¹]',
],
[
'ãçµ¶æãèªæ®ºã詊ã¿ããå€èº«äžãªãã°æåŒ·ã®æ»æ(ç¹æ®èœåçã䜿çšããŠã®æ»æ)ãèªåãžäžããã[çµéšå€30ç¹]',
'ãè³çŸãæµ(è€æ°ããå Žåã¯ãªãŒããŒæ Œ)ãäž»ãšæããããäž»ãåããããããã®ã¿ãŒã³ã®çµäºãŸã§äž»ã®åœä»€ãèãã[çµéšå€30ç¹]',
'ãæçµ¶ãå€èº«ãè§£é€ããããå€èº«ããŠããªããã°åœ±é¿ãªãã[çµéšå€20ç¹]',
'ã飢é€ãè¿ãã®ç¡é²åãªå¯Ÿè±¡ãå°ããããšãããéªéããç©ã¯æµãšããŠæ»æãããæ¬¡ã¿ãŒã³ã®çµäºæã«æã«è¿ãã[çµéšå€20ç¹]',
'ãæéãèŠç¥çµã«åœ±é¿ãåºãã以åŸïŒæ¥ãæéãã«ãªãã[çµéšå€20ç¹]',
'ãæ··ä¹±ãæå³ã®ããèšèã話ããªããªããïŒæéæç¶ããã[çµéšå€20ç¹]',
'ãå«åЬã仲éã«ççãªå«åЬãèŠãããå³åº§ã«äžçªè¿ãã®å³æ¹ãæ»æãå€å®ã¯èªåçã«å¹æçæåãšãªããããªããã°åœ±é¿ãªãã[çµéšå€20ç¹]',
'ãæŽåãèªåãæåŒ·ã«æããŠãããããªãã60ã¿ãŒã³(10å)æ»æå€å®ã®éæå€ã«+10ãåé¿å€å®ã®éæå€ã¯-10ã[çµéšå€20ç¹]',
'ãç¡åãå
šåã ãç¡é²åã60ã¿ãŒã³(10å)ãå
šãŠã®ãã¡ãŒãžã«+10ãé²åŸ¡ç¹0ããè¡åå€ã0ã[çµéšå€20ç¹]',
'ãå®çãå€èº«ããŠããªããã°ãå³åº§ã«å€èº«ãèäœãå€èº«ã«éŠŽæãã§ããŸãã24æéãå€èº«ãè§£é€ãããªããªãã[çµéšå€30ç¹]',
'ãç ããççãªç¡éã«è¥²ãããã60ã¿ãŒã³(10å)ããããã¯æŠéçµäºãŸã§èµ·ãããŠãèµ·ããªãã[çµéšå€30ç¹]',
]
].freeze
# æ°è¡å衚
NEW_URGE_TABLE = [
[
'ãéçŒãæœåšèœåãçºæ®ãããã10åéãããããæŠé以å€ã®å€å®ã«+5ã',
'ãéäžãæèŠãç ãæŸãŸããããæ¬¡ã®ã¿ãŒã³ã®çµäºãŸã§ãå°æã®åœäžå€å®ã«+5ã',
'ãè¿
éãéåç¥çµãäžæããã20åéãæŠé以å€ã®ãæ©æãå€å®ã«+5ã',
'ãæªåãæªåãçºæ®ããã20åéãæŠé以å€ã®ãèäœãå€å®ã«+5ã',
'ãéæãè¡åã«æ°ãä»ããªããäœãèµ·ãããªãã',
'ãæå¶ãè¡åãæã蟌ããäœãèµ·ãããªãã',
'ãææ
¢ãè¡åãææ
¢ãããäœãèµ·ãããªãã',
'ãç¡å¿ãå·éã«ãªãã20åéãæŠé以å€ã®ã粟ç¥ãå€å®ã«+5ã',
'ãè§£æŸãæèŠãè§£æŸãããã20åéãæŠé以å€ã®ãæèŠãå€å®ã«+5ã',
'ãæ»æãæ»æã®å§¿å¢ãåããæ¬¡ã®ã¿ãŒã³ã®çµäºãŸã§ããã¹ãŠã®ãã¡ãŒãžã+5ã',
'ãé²åŸ¡ãé²åŸ¡ã®å§¿å¢ãåãããã®ã¿ãŒã³ã®çµäºãŸã§ããã¹ãŠã®é²åŸ¡åã+5ã',
],
[
'ãæµèŠãæ¿ããæ»ææ¬èœã«é§ããããæ¬¡ã®ã¿ãŒã³ã®çµäºãŸã§ãè匟ãã¡ãŒãž+10ã',
'ãå¿æãæãã«çã¿ãå¿ããããšããžãŒ5ç¹å埩ã',
'ãéããé ãåŽããã20åéãæŠé以å€ã®ãç¥åãå€å®ã«+5ã',
'ãå
šåãçèã®ãªããã¿ãŒãäžæçã«ã¯ããããæ¬¡ã®ã¿ãŒã³ã®çµäºãŸã§ãè匟ãã¡ãŒãžã«+5ã',
'ãæå¶ãè¡åãæã蟌ããäœãèµ·ãããªãã',
'ãææ
¢ãè¡åãææ
¢ãããäœãèµ·ãããªãã',
'ãåå°ãåå°ç¥çµãç ãæŸãŸããããæ¬¡ã®ã¿ãŒã³ã®çµäºãŸã§ãå°æã®åé¿å€å®ã«+5ã',
'ãæ©è»¢ãããããªãã£ã³ã¹ãèŠéããªããªãã20åéãæŠé以å€ã®ã幞éãå€å®ã«+5ã',
'ãèæ§ã粟ç¥åãäžæãããæ¬¡ã®ã¿ãŒã³ã®çµäºãŸã§ãç¹æ®é²åŸ¡å+5ã',
'ãæããæµã«å¯Ÿããæãã«ãšãããããæ¬¡ã®ã¿ãŒã³ã®çµäºãŸã§ãè匟ã®åœäžå€å®ã«+10ã',
'ãæŽ»çºãæããæŽ»çºã«ãªããæŠéçµäºãŸã§ãè¡åå€ã+5ã',
],
[
'ãæŒ²ããäœã®å¥¥åºããåãã¿ãªãã£ãŠããããšããžãŒ10ç¹å埩ã',
'ãåæãçžæã®åããå·éã«åæã§ããããã«ãªãã5ã¿ãŒã³ã®éãå°æãã¡ãŒãžã«+10ã',
'ãæ
æãäžäººã«å¯ŸããŠæ
æãæããããã«ãªãã5ã¿ãŒã³ã®éãååŸ©ã«æ¯ã骰åã+1dã',
'ãæ
éãæµã®æ»æã«æ
éã«ãªããæ¬¡ã®ã¿ãŒã³ã®çµäºãŸã§ããã¹ãŠã®åé¿å€å®ã«+5ã',
'ãæ¬èœãæ»ææ¬èœãããåºãã«ãªãã5ã¿ãŒã³ã®éãç¹æ®ã®åœäžå€å®ã«+5ã',
'ãæ§æ¥ãæ°ãæ©ããªããæ¬¡ã®ã¿ãŒã³ã®çµäºãŸã§ããè¡åå€ãã«+3',
'ãå¶æŽãã€ã©ã€ã©ãæ¢ãŸããªããªãã5ã¿ãŒã³ã®éãè匟ã®åœäžå€å®ã«+5ã',
'ãæ¥œèŠ³ãæ°åããªã©ãã¯ã¹ããããšããžãŒ5ç¹å埩ã',
'ãèªéãèªåã®æ®»ã«éããããããšããã5ã¿ãŒã³ã®éãç¹æ®é²åŸ¡åã«+5ã',
'ãåå°ãæµã®æ»æã«å³åº§ã«åå¿ã§ããã5ã¿ãŒã³ã®éãè匟ã®åé¿å€å®ã«+10ã',
'ãå¿«æãå¿«æãèŠãããè¡åã1ç¹å埩ããã',
],
[
'ãæ
ç±ãæ¿ããæ
ç±ãåŽãåºããŠããããšããžãŒ10ç¹ãšè¡å1ç¹å埩ã',
'ãæ°åãäœäžã«æ°åããå
¥ãã10ã¿ãŒã³ã®éããã¹ãŠã®ãã¡ãŒãžã«+10ã',
'ãå éãäœäžã®ç¥çµãå éããã10ã¿ãŒã³ã®éããã¹ãŠã®åœäžå€å®ã«+10ã',
'ãå©å·±ãèãæ¹ãå©å·±çã«ãªãã10ã¿ãŒã³ã®éãç¹æ®ã®åœäžå€å®ã«+10ã',
'ãé 匷ãèäœãéŒã®ããã«åŒ·ããªãã10ã¿ãŒã³ã®éãè匟é²åŸ¡åã«+5ã',
'ãå¯ç¥ãçžæã®åããå¯ç¥ã§ããã10ã¿ãŒã³ã®éãå°æé²åŸ¡åã«+5ã',
'ãæ®ºæãæ¿ããæ®ºæã«ãšããããã10ã¿ãŒã³ã®éãç¹æ®ãã¡ãŒãžã«+10ã',
'ãé芳ãå¿ãèœã¡çãå·éã«ãªãã10ã¿ãŒã³ã®éãå°æã®åé¿å€å®ã«+5ã',
'ãæ¯ç©ºãé ãåŽããŠæµã®è¡åãèªããã10ã¿ãŒã³ã®éããã¹ãŠã®åé¿å€å®ã«+5ã',
'ãå¿çŒãå¿ã®ç®ã§çžæã®è¡åãèªããã5ã¿ãŒã³ã®éãå°æã®åé¿å€å®ã«+10ã',
'ãèªæãäœããããŠãèªåãæããæããã5ã¿ãŒã³ã®éãç¹æ®ã®åé¿å€å®ã«+10ã',
],
[
'ãç¥éã人ç¥ãè¶
ããã¹ããŒãã«ç®èŠãããæŠéçµäºãŸã§ãéåžžãè¡åãïŒåè¡ããããã«ãªãã',
'ãæµæ°Žãè¶
æèŠã«ç®èŠããã10ã¿ãŒã³ã®éããã¹ãŠã®åé¿å€å®ã«+10ã',
'ãèŠéãèäœã®å埩åãéççªç ŽããšããžãŒ20ç¹å埩ã',
'ãå¿èãããããèŠçã«èããéŒã®ç²Ÿç¥ã宿ãã10ã¿ãŒã³ã®éããã¹ãŠã®é²åŸ¡åã«+5ã',
'ãäºç¥ã第å
æãç ãæŸãŸãããã10ã¿ãŒã³ã®éãå°æã®åœäžãšãã¡ãŒãžã«+10ã',
'ã豪åã身äœèœåãéçãè¶
ããŠäžæããã10ã¿ãŒã³ã®éãè匟ã®åœäžãšãã¡ãŒãžã«+10ã',
'ãæ®ºæ°ãççãªæ®ºæãã¿ãªããã10ã¿ãŒã³ã®éãç¹æ®ã®åœäžå€å®ãšãã¡ãŒãžã«+10ã',
'ãçºåãåå°ç¥çµãé£èºçã«å éãããã10ã¿ãŒã³ã®éããè¡åå€ã+10ã',
'ãæ¿æ
ãæ¿ããææ
ãããµãåºãã10ã¿ãŒã³ã®éããã¹ãŠã®ãã¡ãŒãžã«+10ã',
'ãè¶
人ãéåç¥çµãé£èºçã«å éãããã10ã¿ãŒã³ã®éããã¹ãŠã®åœäžå€å®ã«+15ã',
'ãæããå¿ãè§£æŸããç¡æã®å¢å°ã«éãããè¡åãïŒç¹å埩ãã',
]
].freeze
# 誀äœå衚
MALFUNCTION_TABLE = [
[
'ãç·æ¥åæ¢ãæ©èœã«ç°åžžçºçãæ¬¡ã®ã¿ãŒã³ã®çµäºãŸã§ããè¡åäžèœãã«ãªãã[30ç¹]',
'ãååäžèª¿ãååè£
眮ã«ç°åžžçºçããã®ã¿ãŒã³ã®çµäºæãŸã§ããè¡åäžèœãã«ãªãã[30ç¹]',
'ãè
éšåæ¢ãè
éšæ©æ§ã«ç°åžžçºçããã®ã¿ãŒã³ã®çµäºæãŸã§ããã¿ã€ãã³ã°ïŒæ»æããè¡ããªãã[20ç¹]',
'ãèéšåæ¢ãèéšæ©æ§ã«ç°åžžçºçããã®ã¿ãŒã³ã®çµäºæãŸã§ããããããç§»åããè¡ããªãã[20ç¹]',
'ãæ©èœå¶åãæ©èœãäžç¬åæ¢ãããã圱é¿ãªãã[10ç¹]',
'ãäžè¯èª¿æŽãæ©èœã«éåæã圱é¿ãªãã[10ç¹]',
'ãæ©èœå®å®ãæ©èœãå®å®ããã圱é¿ãªãã[10ç¹]',
'ãæ©èœæŽçºãçŽåã«äœ¿çšãããå
抜
ãããã®ã¿ãŒã³ã®çµäºæãŸã§äœ¿çšäžèœãæªäœ¿çšãªã圱é¿ãªãã[20ç¹]',
'ãé¢è±æ©èœãæ©èœã®ç°åžžçºçãè¡åãæ¶è²»ããããšãªããå³åº§ã«æµãããç§»å(å
šå)ãã§é¢ããã[20ç¹]',
'ãæç±æŽèµ°ãæç±æ©èœã«ç°åžžçºçãæ¬¡ã®ã¿ãŒã³çµäºæãŸã§ãçç«ãç¶æ
ãšãªãã[30ç¹]',
'ãäœåäºæž¬ã次ã«èµ·ãã誀äœåãäºæž¬ã§ãããã第2éçç¹ãã«éãããšãããäœåäºæž¬ã以å€ã®ä»»æã®èª€äœåãéžæã§ããã[30ç¹]',
],
[
'ãå®å
šæ©èœãå®å
šæ©èœãäœåããã®ã¿ãŒã³ã®çµäºæãŸã§ãããããå€å®ã«-5ã[40ç¹]',
'ãçèèçž®ã人工çèã«ç°åžžçºçãæ¬¡ã®ã¿ãŒã³çµäºæãŸã§ããèäœãå€å®ã«-2ã[30ç¹]',
'ãåºåäœäžãé§åéšã«ç°åžžçºçãæ¬¡ã®ã¿ãŒã³ã®çµäºæãŸã§ããæ©æãå€å®ã«-2ã[30ç¹]',
'ãæèŠç°åžžãèŠçæ©èœã«ç°åžžçºçãæ¬¡ã®ã¿ãŒã³ã®çµäºæãŸã§ããæèŠãå€å®ã«-2ã[20ç¹]',
'ãèŠçäžè¯ãèŠçæ©èœã«ç°åžžçºçãæ¬¡ã®ã¿ãŒã³ã®çµäºæãŸã§ãã幞éãå€å®ã«-2ã[20ç¹]',
'ãæ©èœå¶åãæ©èœãäžç¬åæ¢ãããã圱é¿ãªãã[10ç¹]',
'ãäžè¯èª¿æŽãæ©èœã«éåæã圱é¿ãªãã[10ç¹]',
'ãæŽè·äžéãæŽè·ãœããã誀äœåãæ¬¡ã®ã¿ãŒã³ã®çµäºæãŸã§ããç¥åãå€å®-2ã[20ç¹]',
'ãçºå£°å€èª¿ãçºå£°æ©èœã«ç°åžžçºçãæ¬¡ã®ã¿ãŒã³ã®çµäºæãŸã§ãã粟ç¥ãå€å®-2ã[30ç¹]',
'ãè£
ç²è»åãé²åŸ¡æ©æ§ã«ç°åžžçºçãããããé²åŸ¡åã«-5ã[30ç¹]',
'ãäœåäºæž¬ã次ã«èµ·ãã誀äœåãäºæž¬ã§ãããã第3éçç¹ãã«éãããšãããäœåäºæž¬ã以å€ã®ä»»æã®èª€äœåãéžæã§ããã[40ç¹]',
],
[
'ãååæŒé»ãååããæŒé»ããè² è·ãã2ç¹äžæã[40ç¹]',
'ãé§åç°åžžãèéšã«ç°åžžçºçãæ¬¡ã®ã¿ãŒã³ã®çµäºæãŸã§ããç§»åãè·é¢åæžã[40ç¹]',
'ãè¶³äžè»¢åããã©ã³ãµãŒã«ç°åžžçºçãã転åãç¶æ
ãšãªãã[30ç¹]',
'ãåºååäžããå
抜
ãæ©èœãåäžã次ã®ã¿ãŒã³ã®çµäºæãŸã§ãç¹æ®ãã¡ãŒãžã«+1dç¹ã[30ç¹]',
'ãæ©èœå¶åãæ©èœãäžç¬åæ¢ãããã圱é¿ãªãã[20ç¹]',
'ãæ©èœæŽèµ°ãæ»ææ©èœãæŽèµ°ããæŠéèœåãäžæããçç«ãç¶æ
ã«ãªããããããããã¡ãŒãžã«+10ã[20ç¹]',
'ã身äœåäžãæ Œéæ©èœãåäžã次ã®ã¿ãŒã³ã®çµäºæãŸã§ãè匟ãã¡ãŒãžã«+1dç¹ã[30ç¹]',
'ãåå°åäžãåå¿é床ãåäžã次ã®ã¿ãŒã³ã®çµäºæãŸã§ããè¡åå€ãã+5ã[30ç¹]',
'ã粟床åäžãæšæºæ©èœãåäžã次ã®ã¿ãŒã³ã®çµäºæãŸã§ãå°æãã¡ãŒãžã«+1dç¹ã[30ç¹]',
'ãé»å賊掻ãé»ç£éå£ãçªåŠå埩ããé»åãã10ç¹å埩ããã[30ç¹]',
'ãäœåäºæž¬ã次ã«èµ·ãã誀äœåãäºæž¬ã§ãããã第4éçç¹ãã«éãããšãããäœåäºæž¬ã以å€ã®ä»»æã®èª€äœåãéžæã§ããã[40ç¹]',
],
[
'ãç
§æºèª€èªãç
§æºæ©èœã«ç°åžžçºçãå³åº§ã«æãè¿ã峿¹ãå
šåæ»æã[50ç¹]',
'ãæ»æç¹åãæ»ææ©èœãäžæãæ¬¡ã®ã¿ãŒã³çµäºæãŸã§ããããããã¡ãŒãžã«+2dãããããã¿ã€ãã³ã°ïŒé²åŸ¡ããè¡ããªãã[40ç¹]',
'ãæ©å
çªæ¯ãåŒåžè£å©æ©èœã«ç°åžžçºçãæ¬¡ã®ã¿ãŒã³çµäºæãŸã§ããçªæ¯ãç¶æ
ã[40ç¹]',
'ãæ©èœå¢åŒ·ãå
šæ©èœãé£èºçã«åäžã次ã®ã¿ãŒã³çµäºæãŸã§ããå
抜
ãã®ã³ã¹ããæããªããŠè¯ãã[30ç¹]',
'ãé³å£°é®æãèŽèŠæ©èœã«ç°åžžçºçãæ¬¡ã®ã¿ãŒã³çµäºæãŸã§ãäžåã®ç©é³ãèããããããããåé¿å€å®ã«-5ã[30ç¹]',
'ã黿µå éãé»ç£éå£ãå¹ççã«æµããããè² è·ãã1ç¹å埩ã[20ç¹]',
'ã粟å¯å°æãç
§æºã®ç²ŸåºŠãåäžããããããã¡ãŒãžã«+5ç¹ã[30ç¹]',
'ãé»å浪費ãé»ç£éå£ãéå°ã«äœ¿çšãããããé»åãã10ç¹æžå°ã[30ç¹]',
'ãè·é»æŽèµ°ããé»åãã5ç¹æ¶è²»ããããæ¬¡ã®ã¿ãŒã³çµäºæãŸã§ããããããã¡ãŒãžã«+10ç¹ã[40ç¹]',
'ãç¶æ³åæãèŠçæ©èœãåäžãããããåœäžå€å®ã«+5ã[40ç¹]',
'ãäœåäºæž¬ã次ã«èµ·ãã誀äœåãäºæž¬ã§ãããã第5éçç¹ãã«éãããšãããäœåäºæž¬ã以å€ã®ä»»æã®èª€äœåãéžæã§ããã[50ç¹]',
],
[
'ãåºåéå°ãå
šåºåãéå°ã次ã®ã¿ãŒã³çµäºæãŸã§ããããããã¡ãŒãžã®ç·èšã2åã«ãªãããå
抜
ãã®ã³ã¹ãã2åã«ãªãã[50ç¹]',
'ãæ©é¢æŽèµ°ãæŸç±æ©èœãæŽèµ°ãèªåãäžå¿ã«ååŸ5m以å
ãã¹ãŠã®å¯Ÿè±¡ããçç«ãç¶æ
ã«ããã[50ç¹]',
'ãæ©äœæž
åœãæ©èœç°åžžãã埩垰ããæ°çµ¶ããæ»äº¡ããé€ããããããç¶æ
å€åããã¹ãŠæ¶æ»
ã[40ç¹]',
'ãéå£è£
ç²ãé²åŸ¡æ©èœãåäžã次ã®ã¿ãŒã³çµäºæãŸã§ãããããé²åŸ¡åã«+5ã[30ç¹]',
'ãç·æ¥é§åãåé¿æ©èœãåäžã次ã®ã¿ãŒã³çµäºæãŸã§ãããããåé¿å€å®ã«+5ã[30ç¹]',
'ãåºåå¢å€§ãè£
åè£å©æ©èœãåäžã次ã®ã¿ãŒã³çµäºæãŸã§ããææåããããã¯ãå
抜
ãã䜿çšãããã¡ãŒãžç·èšã2åã«ãªãã[30ç¹]',
'ãæ©äœå éãéåæ©èœãæŽèµ°ã次ã®ã¿ãŒã³çµäºæãŸã§ããè¡åå€ãã2åãšãªãã[30ç¹]',
'ãèªå远尟ãèªå远尟æ©èœãçºåãæ¬¡ã®ã¿ãŒã³çµäºæãŸã§ãããããåœäžå€ã«+5ã[40ç¹]',
'ãéå®è§£é€ãå
šæ©èœã®éçãè§£é€ã次ã®ã¿ãŒã³çµäºæãŸã§ããããããã¡ãŒãžã«+10ã[50ç¹]',
'ãè² è·è»œæžãæ¥æ¿ã«æ©äœã®è² è·ãäœäžããè² è·ãã2ç¹å埩ããã[50ç¹]',
'ãè€ååå¿ããã®è¡šã2忝ãããã ããåãçµæãåºãå Žåã¯é©çšããã®ã¯äžåºŠã ããç²åŸçµéšå€ã¯çޝç©ããã[0ç¹]',
]
].freeze
# ãã¥ãŒã¿ã³ãè¡å衚
MUTANT_TABLE = [
[
'ãæããçªç¶åŒ·ãæãã«é§ããããè¿ãã®å¯Ÿè±¡ã«ãããã¡ããããã®ã¿ãŒã³ã®çµäºãŸã§ãè¡åäžèœããšãªãã[20ç¹]',
'ãçµ¶å«ãæªéå¯çäœãè ¢ãã ãããã®ææã«çµ¶å«ããã®ã¿ãŒã³ã®çµäºãŸã§ãè¡åäžèœããšãªãã[10ç¹]',
'ãæ²åãæ¥ã«æ²ããããšãæãåºãããã®ã¿ãŒã³ã®çµäºãŸã§ãè¡åäžèœããšãªãã[10ç¹]',
'ã埮ç¬ãå¯ç¬ãããŠãããããªããããããç¬ããæ¢ãŸããããã®ã¿ãŒã³ã®çµäºãŸã§ãè¡åäžèœããšãªãã[10ç¹]',
'ãéæãè¡åã«æ°ãä»ããªãã£ããäœãèµ·ãããªãã[0ç¹]',
'ãæå¶ãè¡åãæã蟌ãã ãäœãèµ·ãããªãã[0ç¹]',
'ãææ
¢ãè¡åãææ
¢ãããäœãèµ·ãããªãã[0ç¹]',
'ãåå
ãæªéçç¹åŸŽãäžç¬ç®ç«ã€ãïŒã¿ãŒã³(10ç§)æç¶ããæ¬æ
å€åããè§£ããŠãããªã圱é¿ãªãã[10ç¹]',
'ãçºçŸãæªéçç¹åŸŽãæ¥ã«ç®ç«ã€ã60ã¿ãŒã³(10å)æç¶ããæ¬æ
å€åããè§£ããŠãããªã圱é¿ãªãã[10ç¹]',
'ãè§£é€ãå©ãè
/åèã®ãæ¬æ
å€åããïŒã¿ãŒã³(20ç§)ãããŠè§£é€ãããã18ã¿ãŒã³(3å)æç¶ããæ¬æ
å€åããè§£ããŠãããªã圱é¿ãªãã[20ç¹]',
'ãé¡çŸãå©ãè
/åèã®ãæ¬æ
å€åããç¬æã«è§£é€ã60ã¿ãŒã³(10å)æç¶ããæ¬æ
å€åããè§£ããŠãããªã圱é¿ãªãã[20ç¹]',
],
[
'ãè«ç¶ãæèãæ¢ãŸãããã®ã¿ãŒã³ã®çµäºãŸã§ãæ»æãè¡åãè¡ããªãããã®ä»ã®è¡åã¯åœ±é¿ãªãã[20ç¹]',
'ãæ¿æãåŽã«ãããã®(çç©ãç©äœåãã)ãæããªããæ®Žãããæ¬æ
å€åããè§£ããŠãããªãã°æ¬¡ã®ã¿ãŒã³ã®çµäºãŸã§ããã¹ãŠã®åœäžå€å®+5ãåé¿å€å®-5ã[20ç¹]',
'ãæ®å¿ã殺æãç Žå£è¡åãäžç¬å¢ããæŠéäžãªãã°æ¬¡ã®ã¿ãŒã³ã«è¡ããããæ»æãè¡åã®éæå€ã«+5ã[20ç¹]',
'ãèœæ¶ãéå»ã®æ²ããæ³ãåºã廿¥ããæ¶ãæº¢ãããïŒã¿ãŒã³(10ç§)ãéåžžãè¡åãè¡ããªãããã®ä»ã®è¡åã«åœ±é¿ã¯ãªãã[10ç¹]',
'ãæå¶ãè¡åãæã蟌ãã ãäœãèµ·ãããªãã[0ç¹]',
'ãææ
¢ãè¡åãææ
¢ãããäœãèµ·ãããªãã[0ç¹]',
'ãå¿èãèäœãå·ã€ããŠè¡åã«èããã5ç¹ãã¡ãŒãžã[10ç¹]',
'ãèŸæ±ãã»ãã®äžç¬ããæ¬æ
å€åããè§£ãããããç¡çã«æããã®ã§5ç¹ãã¡ãŒãžããæ¬æ
å€åããè§£ããŠãããªã圱é¿ãªãã[10ç¹]',
'ãç°è²ãïŒã¿ãŒã³(30ç§)ãããŠãæ¬æ
å€åããè§£é€ãããã18ã¿ãŒã³(3å)æç¶ããæ¬æ
å€åããè§£ããŠãããªã圱é¿ãªãã[20ç¹]',
'ãèŠçãå¯ççç©ãäœå
ã§æŽãçãã10ç¹ãã¡ãŒãžã[20ç¹]',
'ãå€è²ãç¹ç°ãªå€èŠçç¹åŸŽãïŒã¿ãŒã³(30ç§)ãããŠçŸããã18ã¿ãŒã³(3å)æç¶ããæ¬æ
å€åããè§£ããŠãããªã圱é¿ãªãã[20ç¹]',
],
[
'ãæ€æãæãã«å
šèº«ãæºãããããæ¬¡ã®ã¿ãŒã³ã®çµäºãŸã§ããã¹ãŠã®ãã¡ãŒãžã+1dç¹ããã[20ç¹]',
'ãå éãã»ãšã°ããè¡åã«ãããæ¬¡ã®ã¿ãŒã³ã¯ãè¡åå€ããïŒåã«ãªãã[20ç¹]',
'ãçºé²ãåãæº¢ãåºããæ¬¡ã®ã¿ãŒã³ã®çµäºãŸã§ããã¹ãŠã®ãã¡ãŒãžã«+5ãé²åŸ¡ç¹-5(æäœ0)ãããã[20ç¹]',
'ã也ããæ»æè¡åãæããããªããæ¬¡ã®ã¿ãŒã³ã®çµäºãŸã§å
šãŠã®åœäžå€å®+5ãåé¿å€å®-5ã[10ç¹]',
'ãçµ¶å«ããããéãã®å£°ã§å«ã¶ããã®ã¿ãŒã³ã®çµäºãŸã§ãããããåé¿å€å®ã«-10ã[10ç¹]',
'ãææ
¢ãè¡åãææ
¢ãããäœãèµ·ãããªãã[0ç¹]',
'ãéçãè¡åãç¡çç¢çæã蟌ãã10ç¹ãã¡ãŒãžã[10ç¹]',
'ãè§£æŸãè¡åã«èããããæ¬æ
ãè§£ãããïŒã¿ãŒã³(30ç§)ãããŠè§£é€ããæ¬æ
å€åããè§£ããŠãããªã圱é¿ãªãã[10ç¹]',
'ãæ¬èœãè¡åã«é§ããããæ¬æ
å€åããç¬æã«è§£é€ã次ã®ã¿ãŒã³ã¯ãç®ã®åã®åããã®ãæµå³æ¹åºå¥ç¡ãæ»æããã[20ç¹]',
'ãä¿èº«ã次ã®ã¿ãŒã³ã®çµäºãŸã§ãæµãæ»æã§ããªããå
šãŠã®é²åŸ¡åã«+5ã[20ç¹]',
'ãææžãæªéå¯çäœã屿©ãå¯ç¥ããããšããžãŒãã20ç¹å埩ããã[20ç¹]',
],
[
'ãçããããšããžãŒããå³åº§ã«3dç¹å埩ã[20ç¹]',
'ãé¢è±ããã®å Žããéãåºããéããããªãå Žåã¯ãããããŸã£ãŠåããªããªããïŒã¿ãŒã³(10ç§)çµéããã°æã«è¿ãã[20ç¹]',
'ãè±åãæ¥ã«åãæãããæ¬¡ã®ã¿ãŒã³ã®çµäºãŸã§ãå
šãŠã®å€å®ã«-5ãããã[20ç¹]',
'ãå
šåãæ¿ããèºç¶æ
ãæ¬¡ã®ã¿ãŒã³ã®çµäºãŸã§ãåœäžå€å®ã«+10ãåé¿å€å®ã«-10ã[20ç¹]',
'ãæ··æ²ã1æéã®éãæå³ã®ããèšèã話ããªããªãã[10ç¹]',
'ãäºä¹±ãäœå
ã§å
±ççç©å士ãäºããæŽãåããè¡åã1ç¹å¢ããã[10ç¹]',
'ãæ¬èœãè¡åã«é§ããããæ¬æ
å€åããç¬æã«è§£é€ã次ã®ã¿ãŒã³ãç®ã®åã®åããã®ãæµå³æ¹åºå¥ç¡ãæ»æããã[20ç¹]',
'ãçŠç¥ãçŠãããã転åãããã[20ç¹]',
'ãççã峿¹ãæ¥ã«æµã«æãããå³åº§ã«è¿ãã®å³æ¹ã«1åæ»æ(èªååœäžããã¡ãŒãžã¯éåžž)ãããªããã°åœ±é¿ãªãã[20ç¹]',
'ãèªèãèªåãèš±ããªããèªåãžçŽ ææ»æ(èªååœäžããã¡ãŒãžã¯éåžž)ã[20ç¹]',
'ãèªæµãå°ãæã«è¿ããè¡åã2ç¹å埩ããã[20ç¹]',
],
[
'ãçµ¶æãç¡åæã«ãããªãŸãããæ¬¡ã®ã¿ãŒã³ã®çµäºæãŸã§ãè¡åäžèœããšãªãã[30ç¹]',
'ãç ããççãªç¡éã«è¥²ãããã60ã¿ãŒã³(10å)ããããã¯æŠéçµäºãŸã§èµ·ãããŠãèµ·ããªãã[30ç¹]',
'ã誀åãçªç¶ãæ¬æ
å€åãã䜿çšããã人éã®å§¿ã«ãªã(è¡åãéåžžéã䜿çšãã)ãæ¢ã«äœ¿çšããŠããå Žåã¯å€åç¡ãã[20ç¹]',
'ãæéãèŠç¥çµã«åœ±é¿ãåºãã以åŸ1æ¥ãæéãã«ãªãã[20ç¹]',
'ãåçãå
±ççç©ã屿©ãå¯ç¥ããããšããžãŒãã10ç¹å埩ããã[20ç¹]',
'ãæ··ä¹±ã1æéã®éãæå³ã®ããèšèã話ããªããªãã[20ç¹]',
'ã硬åãæ¥ã«äœã硬çŽããããã®ã¿ãŒã³ã®çµäºæãŸã§ãããããåœäžå€å®ã«-10ãé²åŸ¡åã«+10ã[20ç¹]',
'ãæŽåãèªåãæåŒ·ã«æããŠãããããªãã60ã¿ãŒã³(10å)æ»æå€å®ã«+10ãåé¿å€å®ã«-10ã[20ç¹]',
'ãç¡åãå
šåã ãç¡é²åã60ã¿ãŒã³(10å)ãå
šãŠã®ãã¡ãŒãžã«+10ãé²åŸ¡ç¹ãšãè¡åå€ãã¯0ã[20ç¹]',
'ãåªå€±ããæ¬æ
å€åãã䜿çšäžãªããå³åº§ã«è§£é€ãããã«24æéããæ¬æ
å€åãã䜿ããªããªãã[30ç¹]',
'ãé²åãå
±ççç©ãã¡ãäžæãæ··ãã£ãŠèº«äœèœåãåäžãããæ¬¡ã®å€å®ã®éæå€+10ã[30ç¹]',
]
].freeze
# 鬌埡é(æŠéå€)è¡å衚
ONIMITAMA_OUT_OF_BATTLE_TABLE = [
[
'ãææãææã®ææ
ãççºããç®ã«æ ããã¹ãŠãæããããªãã[20ç¹]',
'ãèœæ¶ãéå»ã®æ²ããæãåºã廿¥ããæ¶ãæº¢ããã[10ç¹]',
'ãåç¬ãçªåŠãšããŠç²Ÿç¥ã髿ããçã£ãããã«ç¬ãã[10ç¹]',
'ãåå®ã<åé>ã«ãã£ãŠæããå¢ããçªåŠãšããŠéããã³ãäžããã[10ç¹]',
'ãæå¶ãè¡åãå®å
šã«åŸãããäœãèµ·ãããªãã[0ç¹]',
'ãæ²éãç©ãããªæ°åã«ãªãã[0ç¹]',
'ãçæ§ãè¡åãçæ§ã§æŒãã蟌ããäœãèµ·ãããªãã[0ç¹]',
'ãç Žè£ãè¡åãæŒãã蟌ãããšããŠäœå
ã®æ¬ é¥ãç Žè£ãåè¡ããã[10ç¹]',
'ãåªå€±ãäžç¬ããåéãã®ç¥éåã倱ãããã[10ç¹]',
'ãæ¯æžãåžè¡ãžã®æžæãæŒããããããäžè¬äººãè¡èµ°ã£ãç®ã§èŠã€ããã[10ç¹]',
'ãå
å
ãåãŸããå¢ãã§äœå
ã«åŠæ°ãå
å
ãããåãå¢ãã[20ç¹]',
],
[
'ã飢é€ãçªç¶ã®åžè¡è¡åãäžè¬äººãççã«è¥²ããããªãã[20ç¹]',
'ãå°å°ãåŠæ°ãæäœã§ããã1åéãç¹æ®èœåãã䜿çšã§ããªãã[20ç¹]',
'ãæçµ¶ãæ
ç·ãäžå®å®ãšãªãã峿¹ãæ¥ã«æããªãã[20ç¹]',
'ãæ¡æ£ãçªåŠãšããŠå
šèº«ããåŠæ°ãåŽåºãç®ã®åã®å¯Ÿè±¡ãå¹ãé£ã°ãã[10ç¹]',
'ãæå¶ãè¡åãå®å
šã«åŸããããªã«ãèµ·ãããªãã[0ç¹]',
'ãæ²»çãç²ããçãããã[0ç¹]',
'ãæ¬èœãæŽåè¡åã«é§ãããç¬æã«"ç°åœ¢å"ããŠããŸãã[10ç¹]',
'ãç Žç ãç Žå£è¡åãå·»ãèµ·ãããç®ã®åã®é害ç©ãç Žå£ããã[20ç¹]',
'ãæªå¯ãçªåŠãšããŠæªå¯ãèµ°ããç©äºã«éäžã§ããªããªãã',
'ãå¿å·ãçªåŠãšããŠãã©ãŠããæãåºããç«ã¡ã€ããã[20ç¹]',
'ãåæ³ãéå»ã®æãåºã廿¥ã掻åãã¿ãªããã[30ç¹]',
],
[
'ãäžåãåŠæ°ãå
šèº«ãé§ãå·¡ããæ¿çã«ãã£ãŠåããªããªãã[20ç¹]',
'ãè±åãçªåŠãšããŠåŠæ°ãè¡°ããè±åã®ããŸãèãã€ãã[20ç¹]',
'ãç°åœ¢ãç¬æã«ããŠç¬æ¯ãè¥å€§ããç®ãçŽ
ããéªæªã«èŒãã[20ç¹]',
'ã粟å¯ãçªåŠãšããŠèŠçãåºãããç®èŠãããšãèåŸã®é¢šæ¯ã人ç©ãèŠéããã[10ç¹]',
'ãç°çãçªåŠãšããŠæãã®ææ
ãæ¹§ãèµ·ãããç®åã®å¯Ÿè±¡ã眵åããã[0ç¹]',
'ã髿ããåéãã®åœ±é¿ã«ãã粟ç¥ã髿ãèºç¶æ
ãšãªãã[0ç¹]',
'ãææªãçªåŠãšããŠææªã沞ãèµ·ãããç®åã®å¯Ÿè±¡ã«æŽã¿ãããã[0ç¹]',
'ãå éãå
šèº«ã«åŠæ°ãé§ãå·¡ããåå°é床ãå¢ãã10ç§ã1åã®ããã«æããã[10ç¹]',
'ãå¹³ç©ã粟ç¥ã«å€èª¿ãèµ·ãããç°åžžãªã»ã©çæ§çã«ãªãã[20ç¹]',
'ãæ
æãããããè
ã«èªæãæ±ããèŠªèº«ã«æ¥ããã[20ç¹]',
'ãæ¯é
ãäžç¬ãåéããå®å
šæ¯é
ãæ¬¡ã«è¡ãæŠéå€ã®å€å®ã1åã ã广çæåããã[20ç¹]',
],
[
'ãå€è³ªãçªåŠãšããŠåŠæ°ãå€è³ªãååŸ5mã«ããã£ãŠéæãªå£ãå±éããã[30ç¹]',
'ãå¢åŒ·ãåŠæ°ã«ãã£ãŠèº«äœèœåãå¢åŒ·ããã10åé[éå]äžçŽãååŸããã[20ç¹]',
'ãæ¡å€§ãåŠæ°ãç®èŠã§ããã»ã©äž¡è
ããçºæ£ã20må
ã®ç©äœãæäœã§ããã[20ç¹]',
'ãæž
æµãåŠæ°ãéæŸã<鬌埡é>ãæããªãååŸ10må
å
šãŠã®çç©ãç ãããã[10ç¹]',
'ãéèŠãæ¿å¯ãªåŠæ°ãç³ã«å®¿ãã1åé20mã®è·é¢ãéèŠã§ããã[10ç¹]',
'ã匷è¡ãçªåŠãšããŠåŠæ°ãå¢ããæ¥è§Šãã察象ããèäœãx2må¹ãé£ã°ãã[0ç¹]',
'ãè¡æãåŠæ°ã殺å·èœåã垯ã³ãæ¥è§Šããç©äœãç Žå£ã20ç§éãæè¶³ãç°¡æã®è匟æŠåšãšãªãã[10ç¹]',
'ãææ»
ãåŠæ°ã皲劻ãç«çœãžãšå€ç°ããæ¥è§Šããç©äœããçç«ããããã[20ç¹]',
'ãå±éãå
šèº«ãå
ãåŠæ°ã®å±€ãåããªãã1åéç©ççãªæ¥è§Šãè¡ããªãã[20ç¹]',
'ãæš¡å£ã<åé>ã粟ç¥ã掻æ§åãããç°åžžãªèšæ¶åãæã«å
¥ããã[20ç¹]',
'ãæ¯é
ãäžç¬<åé>ãå®å
šæ¯é
ãæ¬¡ã«è¡ãæŠéå€ã®å€å®ã1åã ã广çæåããã[20ç¹]',
],
[
'ãè§£æŸãåŠæ°ãç¡å°œèµã«è§£æŸã1åéãæŠéå€ã§äœ¿çšãããã³ã¹ãããç¡èŠã§ããã[30ç¹]',
'ãå éãåŠæ°ã䞡足ã«éäžã1åéãæé50kmã§çŸèµ°ã§ããã[20ç¹]',
'ãä»äžãåŠæ°ãæèŠã«éäžã1åé50må
ãéèŠã§ããã[20ç¹]',
'ã匷åºãåŠæ°ãå
šèº«ã«æµžéã1åéãçªæ¯ããç¶æ
å€åãã®ãã¡ãŒãžãç¡å¹ã[20ç¹]',
'ãç Žå£ãå
šåŠæ°ãèåã«å€æããã1åéãèäœãå€å®ã®éæå€ã2åã«ããã[20ç¹]',
'ãçæ£ã1åéåŠæ°ãå€è³ªãæ¥è§Šãã察象ãçç Žã§ããé害ç©ãç¬æã«ç Žå£ã[10ç¹]',
'ãæµåãååŸ10må
šãŠãæµåãç¯å²å
ã§æç¶ãããç¹æ®èœåãã®å¹æãç¡å¹åã[20ç¹]',
'ãåŸåãååŸ10må
ã®<鬌埡é>ãæããªãçç©ã1åéæ°çµ¶ãããã[20ç¹]',
'ã修埩ãåŠæ°ã極éãŸã§æŽ»æ§åãããç²åŽãåãæãã[20ç¹]',
'ãæ¬æ§ãç¬æã«ç°åœ¢åãç°åœ¢åäžã§ããã°ãããã«çŠã
ããå§¿ãžå€è³ªããã[20ç¹]',
'ãèŠéã1æéãå
šèº«ããéå
ãçºããé«ããã粟ç¥ãmã®"å
ã®æ±"ã«å
ãŸããã[30ç¹]',
]
].freeze
# 鬌埡é(æŠéäž)è¡å衚
ONIMITAMA_BATTLE_TABLE = [
[
'ãææã广ãçºçããã¿ãŒã³ã®çµäºæãŸã§ãè¡åäžèœãç¶æ
ãšãªãã',
'ãèœæ¶ã1ã¿ãŒã³(10ç§)ãéåžžãè¡åãè¡ããªããåé¿è¡åã«åœ±é¿ã¯ãªãã',
'ãåç¬ã广ãçºçããã¿ãŒã³ã®çµäºæãŸã§ãè¡åäžèœããšãªãã',
'ãåå®ã广ãçºçããã¿ãŒã³ã®çµäºæãŸã§ãè¡åäžèœããšãªãã',
'ãæå¶ã圱é¿ãªãã',
'ãæ²éãããšããžãŒãã3ç¹å埩ããã',
'ãçæ§ã圱é¿ãªãã',
'ãç Žè£ãããšããžãŒãã5ç¹æžå°ããã',
'ãåªå€±ã次ã¿ãŒã³ã®ãè¡åå€ããåæž(端æ°åæšãŠ)ã',
'ãæ¯æžã次ã¿ãŒã³ã®çµäºæãŸã§ããããããã¡ãŒãžã«ã+2ãç¹ã',
'ãå
å
ããè¡åãã2ç¹å埩ããã',
],
[
'ã飢é€ãæãè¿ãã®ç¡é²åãªå¯Ÿè±¡ããè¡æ¶²æåã詊ã¿ãã察象ã<鬌埡é>ãæããªãå Žåãè¡æ¶²æ¡åã®å¹æãåŸãããã',
'ãå°å°ã广ãçºçããã¿ãŒã³ã®çµäºæãŸã§ãç¹æ®èœåãã䜿çšã§ããªãã',
'ãæçµ¶ã广ãçºçããã¿ãŒã³ã®çµäºæãŸã§ã峿¹ã察象ãšãããç¹æ®å¹æãã䜿çšäžå¯ã',
'ãæ¡æ£ãååŸ5m以å
ã®å¯Ÿè±¡å
šãŠã®ããšããžãŒãã1dç¹æžå°ãã(æµæäžå¯ãé²åŸ¡åç¡èŠ)ã',
'ãæå¶ã圱é¿ãªãã',
'ãæ²»çãããšããžãŒãã5ç¹å埩ããã',
'ãæ¬èœãå³åº§ã«"ç°åœ¢å"ãã¿ãŒã³çµäºãŸã§ä»»æã®ãã¡ãŒãž1ã€ã«ã+1dãç¹ã',
'ãç Žç ãè¡åãæ¶è²»ããããšãªããè¿ãã«ååšããé害ç©1ã€ãç¬æã«ç Žå£ã',
'ãæªå¯ã广ãçºçããã¿ãŒã³ã®çµäºæãŸã§ãããããå€å®ã®éæå€ã«ã-5ãã',
'ãå¿å·ã广ãçºçããã¿ãŒã³ã®çµäºæãŸã§ããã¿ã€ãã³ã°:æ»æããè¡ããªãã',
'ãåæ³ããè¡åãã3ç¹å埩ããã',
],
[
'ãäžåãæ¬¡ã®ã¿ãŒã³ã®çµäºæãŸã§ãã¿ã€ãã³ã°:éåžžããè¡ããªãã',
'ãè±åãæ¬¡ã®ã¿ãŒã³ã®çµäºæãŸã§ã転åãç¶æ
ãšãªãã',
'ãç°åœ¢ã次ã«è¡ãè¡çºå€å®ã¯ãåºç®ã«é¢ä¿ãªã广çæåãšããŠæ±ãã',
'ã粟å¯ã次ã®ã¿ãŒã³ã®çµäºæãŸã§ãå°æãã¡ãŒãžã«ã+5ãç¹ã',
'ãç°çãæ¬¡ã®ã¿ãŒã³ã®çµäºæãŸã§ãè匟ãã¡ãŒãžã«ã+5ãç¹ã',
'ãé«æãæ¬¡ã®ã¿ãŒã³ã®çµäºæãŸã§ããããããã¡ãŒãžã«ã+1dãç¹ã',
'ãææªã次ã®ã¿ãŒã³ã®çµäºæãŸã§ãç¹æ®ãã¡ãŒãžã«ã+5ãç¹ã',
'ãå éãæ¬¡ã®ã¿ãŒã³ã®çµäºæãŸã§ãè¡åå€ãã«ã+5ãã',
'ãå¹³ç©ããããããç¶æ
å€åããä»»æã§1ã€æ¶æ»
ãããã',
'ãæ
æãååŸ5må
ã®å³æ¹å
šãŠã®ããšããžãŒãã5ç¹å埩ããã',
'ãæ¯é
ããè¡å衚ãã®çµæããç¬¬äžæ®µéã®äžããä»»æã®ãã®ãã1ã€éžæã§ããã',
],
[
'ãå€è³ªã次ã®ã¿ãŒã³ã®çµäºæãŸã§ãä»»æã®é²åŸ¡åã®1ã€ã«ã+10ãç¹ã',
'ãå¢åŒ·ã次ã®ã¿ãŒã³ã®çµäºæãŸã§ãä»»æã®åé¿å€å®1ã€ã«ã+5ãã',
'ãæ¡å€§ãæ¬¡ã®ã¿ãŒã³ã®çµäºæãŸã§ãä»»æã®åœäžå€å®1ã€ã«ã+5ãã',
'ãæž
æµãååŸ10må
ã®å³æ¹å
šãŠã®ããšããžãŒãã5ç¹å埩ããã',
'ãéèŠã次ã®ã¿ãŒã³çµäºæãŸã§ãå°æãã¡ãŒãžã«ã+10ãç¹ã',
'ã匷è¡ã次ã®ã¿ãŒã³ã¯ããã¿ã€ãã³ã°:æ»æããäœåã«1åè¡ãããšãã§ããã',
'ãè¡æãæ¬¡ã®ã¿ãŒã³ã®çµäºæãŸã§ãè匟ãã¡ãŒãžã«ã+10ãç¹ã',
'ãææ»
ãæ¬¡ã®ã¿ãŒã³ã®çµäºæãŸã§ãç¹æ®ãã¡ãŒãžã«ã+10ãç¹ã',
'ãå±éãæ¬¡ã®ã¿ãŒã³ã®çµäºæãŸã§ãæ¬äººãåãããããããã¡ãŒãžãåæžã§ããã',
'ãæš¡å£ã次ã®ã¿ãŒã³ã®çµäºæãŸã§ãæµã䜿çšãããç¹æ®èœåã1ã€ã1åã ã䜿çšå¯èœã',
'ãæ¯é
ããè¡å衚ãã®çµæããç¬¬åæ®µéã®äžããä»»æã®ãã®ãã1ã€éžæã§ããã',
],
[
'ãè§£æŸã次ã®ã¿ãŒã³ã®çµäºæãŸã§ãããããæŠéä¿®æ£ã2åãšãªãã',
'ãå éãæ¬¡ã®ã¿ãŒã³ã®çµäºæãŸã§ããè¡åå€ãã2åãšãªãã',
'ãä»äžã次ã®ã¿ãŒã³ã®çµäºæãŸã§ãå°æãã¡ãŒãžã®ç·èšã2åã«ã§ããã',
'ã匷åºã次ã®ã¿ãŒã³ã®çµäºæãŸã§ãããããé²åŸ¡åã«ã+10ãç¹ã',
'ãç Žå£ã次ã®ã¿ãŒã³ã®çµäºæãŸã§ãè匟ãã¡ãŒãžã®ç·èšã2åã«ã§ããã',
'ãçæ£ãæ¬¡ã®ã¿ãŒã³ã®çµäºæãŸã§ããããããã¡ãŒãžã«ã+2dãç¹ã',
'ãæµåããè¡åãã1dç¹å埩ããã',
'ãåŸåãæ¬¡ã®ã¿ãŒã³ã®çµäºæãŸã§ãç¹æ®ãã¡ãŒãžã®ç·èšã2åã«ã§ããã',
'ã修埩ãããšããžãŒããæå€§å€ãŸã§å埩ããã',
'ãæ¬æ§ããã®æŠéäžã®ã¿ãæçµèœåã2å䜿çšã§ããã',
'ãèŠéãç¬¬äºæ®µéã2忝ããåæ¹ã®å¹æãé©å¿ããã',
]
].freeze
end
| true |
ea58cc3ec227423fa5d3064ad77a12e52b68d089 | Ruby | joaonetoo/world-cup-api | /db/seeds.rb | UTF-8 | 2,436 | 2.625 | 3 | [] | no_license | # This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
require 'csv'
teams = []
names_groups = %w(A B C D E F G H)
groups = []
names_groups.each do |name|
group = Group.create(name: name)
groups << group
end
groups_include_teams = {
Russia: groups[0], Uruguay: groups[0],
Egypt: groups[0], 'Saudi Arabia': groups[0],
Spain: groups[1], Portugal: groups[1],
'IR Iran': groups[1], Morocco: groups[1],
France: groups[2], Denmark: groups[2],
Australia: groups[2], Peru: groups[2],
Croatia: groups[3], Nigeria: groups[3],
Iceland: groups[3], Argentina: groups[3],
Brazil: groups[4], Switzerland: groups[4],
Serbia: groups[4], 'Costa Rica': groups[4],
Mexico: groups[5], Germany: groups[5],
Sweden: groups[5], 'Korea Republic': groups[5],
Belgium: groups[6], England: groups[6],
Panama: groups[6], Tunisia: groups[6],
Japan: groups[7], Senegal: groups[7],
Poland: groups[7], Colombia: groups[7]
}
team = Team.new
options = { headers: true, header_converters: :symbol }
CSV.foreach('lib/fifa.csv',options) do |row|
player_team, player_position = row[0], row[1]
player_name, player_age = row[2], row[4].to_i
unless teams.include?(player_team)
teams << player_team
group_team = groups_include_teams[player_team.to_sym]
code = player_team[0..2].upcase
team = Team.create(name: player_team, code: code, group: group_team)
end
Player.create(name: player_name, position: player_position,
age: player_age, team: team)
end
CSV.foreach('lib/stadiums.csv') do |row|
stadium_city, stadium_name = row[0], row[1]
Stadium.create(name: stadium_name,city: stadium_city)
end
groups.each do |group|
teams_group = group.teams
teams_group.length.times do
for i in (0...3) do
game = Match.create(date: Time.at(rand * Time.now.to_i), stadium: Stadium.all.sample)
teams_group[i].matches << game
teams_group[i+1].matches << game
end
end
end
Player.reindex
Team.reindex
| true |
663b7557b826ff9e5dfdd7825aeff2929fb3eb00 | Ruby | gdiodati/metaheuristicas | /ldo_ido/sudoku_graph.rb | UTF-8 | 3,964 | 3.171875 | 3 | [] | no_license | require 'matrix'
class SudokuGraph
attr_reader :size
def initialize(size = 4)
@limit = Math.sqrt(size).to_i
fail "Size must be a square number" unless @limit**2 == size
@size = size
@matrix = Matrix.build(size) { |row, col| Node.new self, row, col }
end
def [](r,c)
@matrix[r,c]
end
def adjacent(node)
(horizontal_for(node) + vertical_for(node) + block_for(node)).uniq - [node]
end
def conflictive_nodes
vertices.select(&:conflict?)
end
def resolve_conflict(node)
v = vertical_for node
h = horizontal_for node
b = block_for node
intersections = [
[possible_colors_from(v, b) - fixed_colors(h), h],
[possible_colors_from(h, b) - fixed_colors(v), v],
[possible_colors_from(v, h) - fixed_colors(b), b]
]
colors, conflictive_adjacents = intersections.find { |n| !n.first.empty? }
if colors.nil?
# It means there is no combination of 2 sets to get 1 color.
# So I clear out all the block
conflictive_adjacents = b
else
node.color = colors.first
conflictive_adjacents -= [node]
end
conflictive_adjacents.each{|n| n.color = nil}
self
end
def wipe(amount = 3)
to_wipe = []
to_wipe += @matrix.row_vectors.select { |nodes| sum_colors(nodes) != 45 }
to_wipe += @matrix.column_vectors.select { |nodes| sum_colors(nodes) != 45 }
to_wipe.shuffle.take(amount).each { |ns| wipe_nodes ns }
self
end
# Given it is a Sudoku graph, all the nodes has the same degree
def degree(node)
2 * (@size - 1) + (@limit - 1) ** 2
end
def vertices
@matrix.row_vectors.map(&:to_a).flatten
end
def total_nodes
@size * @size
end
def inspect
horizonal_separator = "-" + "-".rjust(4) * (@size + @limit -2) + "\n"
fixed = vertices.select(&:fixed?).size
str = "<SudokuGraph:#{@size} conflictive:#{conflictive_nodes.size} fixed:#{fixed}> \n"
@matrix.row_vectors.each_with_index do |row, idx|
print_row = row.to_a.map(&:color).map! { |e| e.to_s.rjust(3) }
sum = sum_colors(row).to_s.rjust 3
str << horizonal_separator if idx % @limit == 0 && idx > 0
extra = 0
(0..row.size).step(@limit) do |insert_index|
print_row.insert insert_index + extra, '|'
extra += 1
end
str << print_row.join(" ") + "> #{sum}\n"
end
str << horizonal_separator
print_row = @matrix.column_vectors.map do |col|
sum_colors(col).to_s.rjust 3
end
extra = 0
(0..@size).step(@limit) do |insert_index|
print_row.insert insert_index + extra, '|'
extra += 1
end
str << print_row.join(" ") + "\n"
str
end
def to_s
inspect
end
def dup
dup_sudoku = SudokuGraph.new @size
dup_sudoku.vertices.each do |node|
node.copy self[*node.coords]
end
dup_sudoku
end
def solved?
conflict_nodes = conflictive_nodes.size.zero?
rows_and_columns = @matrix.row_vectors + @matrix.column_vectors
valid_sums = rows_and_columns.all? { |nodes| sum_colors(nodes) == 45 }
conflict_nodes && valid_sums
end
private
def fixed_colors(nodes)
nodes.select(&:fixed?).map(&:color)
end
def possible_colors_from(array1, array2)
colors = ->(nodes) { nodes.map(&:color) }
intersection = colors.call(array1) & colors.call(array2)
(1..size).to_a - intersection
end
def horizontal_for(node)
@matrix.row(node.row).to_a
end
def vertical_for(node)
@matrix.column(node.col).to_a
end
def block_for(node)
start_row = node.row - (node.row % @limit)
start_col = node.col - (node.col % @limit)
block = []
@limit.times do |row|
@limit.times do |col|
block << @matrix[row + start_row, col + start_col]
end
end
block
end
def sum_colors(nodes)
nodes.to_a.map(&:color).compact.reduce(:+)
end
def wipe_nodes(nodes)
nodes.each {|n| n.color = nil}
self
end
end
| true |
3ed3ed2d79d010ff60144b1cf558975c67de5985 | Ruby | bogusoft/cukehead | /examples/roundtrip.rb | UTF-8 | 1,922 | 3.046875 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env ruby
class CukeheadRoundtripRunner
def initialize
@tmp = File.expand_path(File.join(File.dirname(__FILE__), '..', 'tmp'))
@bin = File.expand_path(File.join(File.dirname(__FILE__), '..', 'bin'))
end
def usage
puts <<xxx
Usage: roundtrip.rb features_path
Where:
features_path = Path to the features directory of a project to use for
a roundtrip comparison.
xxx
end
def roundtrip_test features_dir
project_name = File.basename File.dirname(features_dir)
output_dir = File.join @tmp, 'roundtrip', project_name
mm_filename = File.join output_dir, 'mm', project_name + '.mm'
features_output_dir = File.join output_dir, 'features'
cukehead = File.join @bin, 'cukehead'
# Create a mind map from the project features.
cmd = "#{cukehead} map -o -f #{features_dir} -m #{mm_filename}"
system(cmd)
# Create a set of features from the resulting mind map.
cmd = "#{cukehead} cuke -o -f #{features_output_dir} -m #{mm_filename}"
system(cmd)
# # Use Beyone Compare to view the results.
# cmd = "bcompare #{features_dir} #{features_output_dir}"
# system(cmd)
# Use diff to view the results.
diff_filename = File.join output_dir, 'diff.txt'
puts "Senfing diff output to #{diff_filename}"
cmd = "diff -a -b -u #{features_dir} #{features_output_dir} > #{diff_filename}"
system(cmd)
end
def run
if ARGV.length != 1
usage
exit(1)
end
features_path = File.expand_path ARGV[0]
if File.directory? features_path
if Dir[File.join(features_path, '*.feature')].empty?
puts "ERROR: No files matching *.feature in directory " + features_path
exit(1)
else
roundtrip_test features_path
end
else
puts "ERROR: Directory not found " + features_path
exit(1)
end
end
end
app = CukeheadRoundtripRunner.new
app.run
| true |
656d145825a3c5fb86405e550aeb0eec3a6497f2 | Ruby | greatscotty/Head_first_ruby | /chapter_10/include_enum.rb | UTF-8 | 411 | 3.890625 | 4 | [] | no_license | class WordSplitter
include Enumerable
attr_accessor :string
def each
string.split(" ").each do |word|
yield word
end
end
end
splitter = WordSplitter.new
splitter.string = "How do you do"
splitter.each do |word|
puts word
end
p splitter.find_all {|word| word.include?("d") }
p splitter.reject {|word| word.include?("d")}
p splitter.map {|word| word.reverse} | true |
a6885cc6b7f6563fe03d682b5df1c9f72820a1f8 | Ruby | bschwartz10/tic_tac_toe | /test/private/board_private_test.rb | UTF-8 | 727 | 2.59375 | 3 | [] | no_license | require './test/test_helper'
require './lib/board'
class BoardPrivateTest < Minitest::Test
attr_reader :board
def setup
@board = Board.new
end
def test_spot_is_available_returns_true_when_spot_is_available
assert_equal true, board.send(:spot_available?, '0')
end
def test_spot_is_available_returns_false_when_spot_is_unavailable
board.spaces = ['X', '1', '2', '3', '4', '5', '6', '7', '8']
assert_equal false, board.send(:spot_available?, '0')
end
def test_spot_is_valid_returns_true_when_spot_is_valid
assert_equal true, board.send(:spot_valid?, '0')
end
def test_spot_is_valid_returns_false_when_spot_is_invalid
assert_equal false, board.send(:spot_valid?, '99')
end
end
| true |
16f14c9300c0518354c117a29ec83cdce7645da5 | Ruby | Muriel-Salvan/riffola | /spec/riffola_spec.rb | UTF-8 | 16,320 | 3.140625 | 3 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | permissive | require 'riffola'
require 'tempfile'
require 'hex_string'
describe Riffola do
# Are we in debug mode?
#
# Result::
# * Boolean: Are we in debug mode?
def debug?
ENV['TEST_DEBUG'] == '1'
end
HEX_DUMP_CHARS_SIZE = 16
# Convert a given string in a debuggable hexadecimal format
#
# Parameters::
# * *str* (String): String to be converted
# Result::
# * String: The output
def hex_dump(str)
str.scan(/.{1,#{HEX_DUMP_CHARS_SIZE}}/m).map do |line|
"#{"%-#{HEX_DUMP_CHARS_SIZE * 3}s" % line.to_hex_string}| #{line.gsub(/[^[:print:]]/, '.')}"
end.join("\n")
end
# Get a string encoding chunks
#
# Parameters::
# * *chunks* (Array< Hash<Symbol,Object> >): List of chunks data:
# * *name* (String): Chunk's name
# * *data* (String): Chunk's data
# * *data_size* (Integer): Chunk's data size [default = data.size]
# * *header* (String): Chunk's header [default = '']
# * *size_length* (Integer): Size in bytes for size encoding [default = 4]
# Result::
# * String: The encoded chunks
def chunks_to_str(chunks)
chunks.map do |chunk_info|
chunk_info[:header] = '' unless chunk_info.key?(:header)
chunk_info[:size_length] = 4 unless chunk_info.key?(:size_length)
chunk_info[:data_size] = chunk_info[:data].size unless chunk_info.key?(:data_size)
size_pack_code =
case chunk_info[:size_length]
when 2
'S'
when 4
'L'
else
raise "Unknown size length to encode: #{chunk_info[:size_length]}"
end
"#{chunk_info[:name]}#{[chunk_info[:data_size]].pack(size_pack_code)}#{chunk_info[:header]}#{chunk_info[:data]}"
end.join
end
# Create a file with some chunks content and call code with its file name
#
# Parameters::
# * *chunks* (Array< Hash<Symbol,Object> >): List of chunks data (check chunks for details). [default = []]:
# * Proc: Code called once the file has been created. File is deleted after code execution.
# * Parameters::
# * *file* (String): File name
def with_file_content(chunks = [])
Tempfile.open do |tmp_file|
tmp_file.write(chunks_to_str(chunks))
tmp_file.flush
puts "[Test Debug] - File #{tmp_file.path} has content:\n#{hex_dump(File.read(tmp_file))}" if debug?
yield tmp_file.path
end
end
# Return the chunks read from a file content
#
# Parameters::
# * *chunks* (Array< Hash<Symbol,Object> >): List of chunks data. See with_file_content to understand the structure. [default = []]
# * *chunks_format* (Object): The chunks_format parameter give to Riffola.read [default: {}]
# * Proc: Code called with the chunks decoded from the file
# * Parameters::
# * *chunks* (Array<Riffola::Chunk>): List of chunks read from the file
def read_chunks(chunks = [], chunks_format: {})
with_file_content(chunks) do |file|
yield Riffola.read(file, chunks_format: chunks_format, debug: debug?)
end
end
it 'reads an empty file' do
read_chunks do |chunks|
expect(chunks).to eq []
end
end
it 'reads a file containing 1 chunk' do
chunk_name = 'ABCD'
chunk_data = 'TestData'
read_chunks([
{
name: chunk_name,
data: chunk_data
}
]) do |chunks|
expect(chunks.size).to eq 1
chunk = chunks.first
expect(chunk.name).to eq chunk_name
expect(chunk.size).to eq chunk_data.size
expect(chunk.data).to eq chunk_data
expect(chunk.header).to eq ''
expect(chunk.parent_chunk).to eq nil
expect(chunk.next).to eq nil
end
end
it 'reads a file containing several chunks' do
read_chunks([
{
name: 'CHK1',
data: 'ChunkData1'
},
{
name: 'CHK2',
data: 'ChunkData2'
},
{
name: 'CHK3',
data: 'ChunkData3'
}
]) do |chunks|
expect(chunks.size).to eq 3
chunk = chunks.first
expect(chunk.name).to eq 'CHK1'
expect(chunk.size).to eq 10
expect(chunk.data).to eq 'ChunkData1'
expect(chunk.header).to eq ''
expect(chunk.parent_chunk).to eq nil
expect(chunk.next).to eq chunks[1]
chunk = chunk.next
expect(chunk.name).to eq 'CHK2'
expect(chunk.size).to eq 10
expect(chunk.data).to eq 'ChunkData2'
expect(chunk.header).to eq ''
expect(chunk.parent_chunk).to eq nil
expect(chunk.next).to eq chunks[2]
chunk = chunk.next
expect(chunk.name).to eq 'CHK3'
expect(chunk.size).to eq 10
expect(chunk.data).to eq 'ChunkData3'
expect(chunk.header).to eq ''
expect(chunk.parent_chunk).to eq nil
expect(chunk.next).to eq nil
end
end
it 'reads a file containing several chunks with size encoded in 2 bytes' do
read_chunks([
{
name: 'CHK1',
data: 'ChunkData1',
size_length: 2
},
{
name: 'CHK2',
data: 'ChunkData2',
size_length: 2
},
{
name: 'CHK3',
data: 'ChunkData3',
size_length: 2
}
], chunks_format: { '*' => { size_length: 2 } }) do |chunks|
expect(chunks.size).to eq 3
chunk = chunks.first
expect(chunk.name).to eq 'CHK1'
expect(chunk.size).to eq 10
expect(chunk.data).to eq 'ChunkData1'
expect(chunk.header).to eq ''
expect(chunk.parent_chunk).to eq nil
expect(chunk.next).to eq chunks[1]
chunk = chunk.next
expect(chunk.name).to eq 'CHK2'
expect(chunk.size).to eq 10
expect(chunk.data).to eq 'ChunkData2'
expect(chunk.header).to eq ''
expect(chunk.parent_chunk).to eq nil
expect(chunk.next).to eq chunks[2]
chunk = chunk.next
expect(chunk.name).to eq 'CHK3'
expect(chunk.size).to eq 10
expect(chunk.data).to eq 'ChunkData3'
expect(chunk.header).to eq ''
expect(chunk.parent_chunk).to eq nil
expect(chunk.next).to eq nil
end
end
it 'reads a file containing several chunks with headers' do
read_chunks([
{
name: 'CHK1',
data: 'ChunkData1',
header: 'ChunkHeader1'
},
{
name: 'CHK2',
data: 'ChunkData2',
header: 'ChunkHeader2'
},
{
name: 'CHK3',
data: 'ChunkData3',
header: 'ChunkHeader3'
}
], chunks_format: { '*' => { header_size: 12 } }) do |chunks|
expect(chunks.size).to eq 3
chunk = chunks.first
expect(chunk.name).to eq 'CHK1'
expect(chunk.size).to eq 10
expect(chunk.data).to eq 'ChunkData1'
expect(chunk.header).to eq 'ChunkHeader1'
expect(chunk.parent_chunk).to eq nil
expect(chunk.next).to eq chunks[1]
chunk = chunk.next
expect(chunk.name).to eq 'CHK2'
expect(chunk.size).to eq 10
expect(chunk.data).to eq 'ChunkData2'
expect(chunk.header).to eq 'ChunkHeader2'
expect(chunk.parent_chunk).to eq nil
expect(chunk.next).to eq chunks[2]
chunk = chunk.next
expect(chunk.name).to eq 'CHK3'
expect(chunk.size).to eq 10
expect(chunk.data).to eq 'ChunkData3'
expect(chunk.header).to eq 'ChunkHeader3'
expect(chunk.parent_chunk).to eq nil
expect(chunk.next).to eq nil
end
end
it 'reads a file containing several chunks with data size correction' do
read_chunks([
{
name: 'CHK1',
data: 'ChunkData1',
data_size: 4
},
{
name: 'CHK2',
data: 'ChunkData2',
data_size: 4
},
{
name: 'CHK3',
data: 'ChunkData3',
data_size: 4
}
], chunks_format: { '*' => { data_size_correction: 6 } }) do |chunks|
expect(chunks.size).to eq 3
chunk = chunks.first
expect(chunk.name).to eq 'CHK1'
expect(chunk.size).to eq 10
expect(chunk.data).to eq 'ChunkData1'
expect(chunk.header).to eq ''
expect(chunk.parent_chunk).to eq nil
expect(chunk.next).to eq chunks[1]
chunk = chunk.next
expect(chunk.name).to eq 'CHK2'
expect(chunk.size).to eq 10
expect(chunk.data).to eq 'ChunkData2'
expect(chunk.header).to eq ''
expect(chunk.parent_chunk).to eq nil
expect(chunk.next).to eq chunks[2]
chunk = chunk.next
expect(chunk.name).to eq 'CHK3'
expect(chunk.size).to eq 10
expect(chunk.data).to eq 'ChunkData3'
expect(chunk.header).to eq ''
expect(chunk.parent_chunk).to eq nil
expect(chunk.next).to eq nil
end
end
it 'reads a file containing several chunks with data size correction given as a Proc' do
read_chunks([
{
name: 'CHK1',
data: 'ChunkData1',
data_size: 4
},
{
name: 'CHK2',
data: 'ChunkData2',
data_size: 4
},
{
name: 'CHK3',
data: 'ChunkData3',
data_size: 4
}
], chunks_format: { '*' => { data_size_correction: proc { |_file| 6 } } }) do |chunks|
expect(chunks.size).to eq 3
chunk = chunks.first
expect(chunk.name).to eq 'CHK1'
expect(chunk.size).to eq 10
expect(chunk.data).to eq 'ChunkData1'
expect(chunk.header).to eq ''
expect(chunk.parent_chunk).to eq nil
expect(chunk.next).to eq chunks[1]
chunk = chunk.next
expect(chunk.name).to eq 'CHK2'
expect(chunk.size).to eq 10
expect(chunk.data).to eq 'ChunkData2'
expect(chunk.header).to eq ''
expect(chunk.parent_chunk).to eq nil
expect(chunk.next).to eq chunks[2]
chunk = chunk.next
expect(chunk.name).to eq 'CHK3'
expect(chunk.size).to eq 10
expect(chunk.data).to eq 'ChunkData3'
expect(chunk.header).to eq ''
expect(chunk.parent_chunk).to eq nil
expect(chunk.next).to eq nil
end
end
it 'reads a file containing several chunks with data size correction on some chunks only' do
read_chunks([
{
name: 'CHK1',
data: 'ChunkData1'
},
{
name: 'CHK2',
data: 'ChunkData2',
data_size: 4
},
{
name: 'CHK3',
data: 'ChunkData3',
data_size: 14
}
], chunks_format: { 'CHK2' => { data_size_correction: 6 }, 'CHK3' => { data_size_correction: -4 } }) do |chunks|
expect(chunks.size).to eq 3
chunk = chunks.first
expect(chunk.name).to eq 'CHK1'
expect(chunk.size).to eq 10
expect(chunk.data).to eq 'ChunkData1'
expect(chunk.header).to eq ''
expect(chunk.parent_chunk).to eq nil
expect(chunk.next).to eq chunks[1]
chunk = chunk.next
expect(chunk.name).to eq 'CHK2'
expect(chunk.size).to eq 10
expect(chunk.data).to eq 'ChunkData2'
expect(chunk.header).to eq ''
expect(chunk.parent_chunk).to eq nil
expect(chunk.next).to eq chunks[2]
chunk = chunk.next
expect(chunk.name).to eq 'CHK3'
expect(chunk.size).to eq 10
expect(chunk.data).to eq 'ChunkData3'
expect(chunk.header).to eq ''
expect(chunk.parent_chunk).to eq nil
expect(chunk.next).to eq nil
end
end
it 'reads a file containing several chunks with sub-chunks' do
chunk2_data = chunks_to_str([
{
name: 'SCK1',
data: 'SubChunkData1'
},
{
name: 'SCK2',
data: 'SubChunkData2'
},
{
name: 'SCK3',
data: 'SubChunkData3'
}
])
read_chunks([
{
name: 'CHK1',
data: 'ChunkData1'
},
{
name: 'CHK2',
data: chunk2_data
},
{
name: 'CHK3',
data: 'ChunkData3'
}
]) do |chunks|
expect(chunks.size).to eq 3
chunk = chunks.first
expect(chunk.name).to eq 'CHK1'
expect(chunk.size).to eq 10
expect(chunk.data).to eq 'ChunkData1'
expect(chunk.header).to eq ''
expect(chunk.parent_chunk).to eq nil
expect(chunk.next).to eq chunks[1]
chunk = chunk.next
expect(chunk.name).to eq 'CHK2'
expect(chunk.size).to eq chunk2_data.size
expect(chunk.data).to eq chunk2_data
expect(chunk.header).to eq ''
expect(chunk.parent_chunk).to eq nil
expect(chunk.next).to eq chunks[2]
chunk = chunk.next
expect(chunk.name).to eq 'CHK3'
expect(chunk.size).to eq 10
expect(chunk.data).to eq 'ChunkData3'
expect(chunk.header).to eq ''
expect(chunk.parent_chunk).to eq nil
expect(chunk.next).to eq nil
sub_chunks = chunks[1].sub_chunks
expect(sub_chunks.size).to eq 3
chunk = sub_chunks.first
expect(chunk.name).to eq 'SCK1'
expect(chunk.size).to eq 13
expect(chunk.data).to eq 'SubChunkData1'
expect(chunk.header).to eq ''
expect(chunk.parent_chunk).to eq chunks[1]
expect(chunk.next).to eq sub_chunks[1]
chunk = chunk.next
expect(chunk.name).to eq 'SCK2'
expect(chunk.size).to eq 13
expect(chunk.data).to eq 'SubChunkData2'
expect(chunk.header).to eq ''
expect(chunk.parent_chunk).to eq chunks[1]
expect(chunk.next).to eq sub_chunks[2]
chunk = chunk.next
expect(chunk.name).to eq 'SCK3'
expect(chunk.size).to eq 13
expect(chunk.data).to eq 'SubChunkData3'
expect(chunk.header).to eq ''
expect(chunk.parent_chunk).to eq chunks[1]
expect(chunk.next).to eq nil
end
end
it 'reads a file containing several chunks with sub-chunks having specific formats' do
chunk2_data = chunks_to_str([
{
name: 'SCK1',
data: 'SubChunkData1'
},
{
name: 'SCK2',
data: 'SubChunkData2',
data_size: 7
},
{
name: 'SCK3',
data: 'SubChunkData3'
}
])
read_chunks([
{
name: 'CHK1',
data: 'ChunkData1'
},
{
name: 'CHK2',
data: chunk2_data
},
{
name: 'CHK3',
data: 'ChunkData3'
}
], chunks_format: { 'SCK2' => { data_size_correction: 6 } }) do |chunks|
expect(chunks.size).to eq 3
chunk = chunks.first
expect(chunk.name).to eq 'CHK1'
expect(chunk.size).to eq 10
expect(chunk.data).to eq 'ChunkData1'
expect(chunk.header).to eq ''
expect(chunk.parent_chunk).to eq nil
expect(chunk.next).to eq chunks[1]
chunk = chunk.next
expect(chunk.name).to eq 'CHK2'
expect(chunk.size).to eq chunk2_data.size
expect(chunk.data).to eq chunk2_data
expect(chunk.header).to eq ''
expect(chunk.parent_chunk).to eq nil
expect(chunk.next).to eq chunks[2]
chunk = chunk.next
expect(chunk.name).to eq 'CHK3'
expect(chunk.size).to eq 10
expect(chunk.data).to eq 'ChunkData3'
expect(chunk.header).to eq ''
expect(chunk.parent_chunk).to eq nil
expect(chunk.next).to eq nil
sub_chunks = chunks[1].sub_chunks
expect(sub_chunks.size).to eq 3
chunk = sub_chunks.first
expect(chunk.name).to eq 'SCK1'
expect(chunk.size).to eq 13
expect(chunk.data).to eq 'SubChunkData1'
expect(chunk.header).to eq ''
expect(chunk.parent_chunk).to eq chunks[1]
expect(chunk.next).to eq sub_chunks[1]
chunk = chunk.next
expect(chunk.name).to eq 'SCK2'
expect(chunk.size).to eq 13
expect(chunk.data).to eq 'SubChunkData2'
expect(chunk.header).to eq ''
expect(chunk.parent_chunk).to eq chunks[1]
expect(chunk.next).to eq sub_chunks[2]
chunk = chunk.next
expect(chunk.name).to eq 'SCK3'
expect(chunk.size).to eq 13
expect(chunk.data).to eq 'SubChunkData3'
expect(chunk.header).to eq ''
expect(chunk.parent_chunk).to eq chunks[1]
expect(chunk.next).to eq nil
end
end
end
| true |
ad92bbbb3add194dfac7d10152fd6685eb871694 | Ruby | ajasja/Rgle | /lib/examples/3_color_map/color_map.rb | UTF-8 | 1,192 | 2.6875 | 3 | [] | no_license | require 'rgle'
include RGle
#change working directory to current dir
Dir.chdir(File.dirname(__FILE__))
def create_xyz_file(dest_name)
datax =[]
datay =[]
dataz =[]
i = 0;
Dir['data/*'].each do |file_name|
File.open(file_name, "r") do |file|
#skip first line
file.gets
y_val = /(\d\d)$/.match(file_name)[0].to_i
file.each_line { |line|
la = line.split
datax[i]=la[0]
datay[i]=y_val
dataz[i]=la[1]
i=i+1
}
end
end
File.open(dest_name, "w") { |f|
0.upto(datax.size-1) { |j| f.puts "#{datax[j]},#{datay[j]},#{dataz[j]}"}
}
end
create_xyz_file "saxs.dat" unless File.exists? "saxs.dat"
gle = RGleBuilder.build "saxs" do
size 12, 12
beg :fitz do
data "saxs.dat"
x "from 0.02388324 to 0.4858713 step 0.0001"
y "from 1 to 23 step 1"
ncontour 5
end unless File.exists? "saxs.z"
beg :graph do
title "SAXS"
xtitle "lambda^{-1}"
ytitle "temperature series"
colormap "saxs.z", 500, 500, :color
end
end
puts gle
#gle.preview!
gle.plot! :format => :png, :options => "-resolution 600"
gle.plot! :format => :png, :options => "-resolution 600"
| true |
2409c97c05f6392a12f4c985b966f4b8f957f17f | Ruby | gnilrets/Remi | /spec_old/interfaces/canonical_interface_spec.rb | UTF-8 | 2,120 | 2.578125 | 3 | [
"MIT"
] | permissive | require 'remi_spec'
describe Interfaces::CanonicalInterface do
# Reset the work directory before each test
before { RemiConfig.work_dirname = Dir.mktmpdir("Remi-work-", Dir.tmpdir) }
let(:mylib) { Datalibs::CanonicalDatalib.new(RemiConfig.work_dirname) }
let(:interface) { Interfaces::CanonicalInterface.new(mylib, 'test') }
describe 'writing the header' do
before do
@test_header = { some: "kind of header", with: "stuff" }
writer = interface
writer.open_for_write
writer.write_header(@test_header)
writer.close
end
it 'creates a header and detail file' do
expect(File.exists?(interface.header_file_full_path)).to be true
expect(File.exists?(interface.data_file_full_path)).to be true
end
describe 'reading the header that has been written' do
before do
reader = interface
reader.open_for_read
@header = reader.read_header
reader.close
end
it 'returns the same header that was written' do
expect(@header).to eq @test_header
end
end
end
describe 'writing rows' do
before do
@test_data = [ [1,2,3], [4,5,6], [7,8,9] ]
writer = interface
writer.open_for_write
@test_data.each do |row|
writer.write_row(Row.new(row))
end
writer.close
end
it 'creates a header and detail file' do
expect(File.exists?(interface.header_file_full_path)).to be true
expect(File.exists?(interface.data_file_full_path)).to be true
end
describe 'reading rows that have been written' do
before do
reader = interface
reader.open_for_read
@result_data = []
@test_data.each do
@result_data << reader.read_row
end
reader.close
end
it 'gives back the same data that was written' do
expect(@result_data.collect { |r| r.to_a }).to eq @test_data
end
it 'has the correct eof flags' do
expect(@result_data.collect { |r| r.last_row }).to eq ([false] * (@test_data.length - 1) + [true])
end
end
end
end
| true |
a5441385ada69b739c9e2e8aaf0e9c4226039c53 | Ruby | gveve/anagram-detector-web-100817 | /lib/anagram.rb | UTF-8 | 205 | 3.40625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class Anagram
attr_accessor :word
def initialize(word)
@word = word
end
def match(array)
array.delete_if do |x|
x.chars.sort != @word.chars.sort
end
end
end
| true |
3642589d345faf548a68945faca00b24d3278d59 | Ruby | garrmark/mohawk | /lib/mohawk/accessors/table_row.rb | UTF-8 | 1,314 | 2.546875 | 3 | [
"MIT"
] | permissive | module Mohawk
module Accessors
class TableRow
include RAutomation::Adapter::MsUia
attr_reader :row
def initialize(table, row_index)
@table = table
@row = Row.new(@table.view, :index => row_index)
end
def selected?
row.selected?
end
def select
UiaDll::table_single_select(@table.view.search_information, row.row)
self
end
def add_to_selection
row.select
self
end
def clear
row.clear
self
end
def cells
row.cells.map &:text
end
def all_match?(hash)
hash.all? do |key, value|
send(key) == "#{value}"
end
end
def value_from_header(name)
which_column = header_methods.index(name)
raise ArgumentError, "#{name} column does not exist in #{header_methods}" if which_column.nil?
Cell.new(row, :index => which_column).text
end
def method_missing(name, *args)
value_from_header name
end
def to_hash
{:text => row.text, :row => row.row }
end
private
def header_methods
@headers ||= @table.headers.map(&:to_method)
end
end
end
end
| true |
0fc462b4da51f064098d1354bb80375e6e6de33d | Ruby | dougjohnson/holiday_machine | /app/models/vacation.rb | UTF-8 | 5,210 | 2.703125 | 3 | [
"MIT"
] | permissive | class Vacation < ActiveRecord::Base
belongs_to :holiday_status
belongs_to :holiday_year
belongs_to :user
before_save :save_working_days
before_destroy :check_if_holiday_has_passed
after_destroy :add_days_remaining
after_create :decrease_days_remaining
scope :team_holidays, lambda { |manager_id| where(:manager_id => manager_id) }
scope :user_holidays, lambda {|user_id| where(:user_id => user_id)}
scope :per_holiday_year, lambda { |holiday_year_id| where(:holiday_year_id => holiday_year_id) }
validates_presence_of :date_from
validates_presence_of :date_to
validates_presence_of :description
validate :holiday_must_not_straddle_holiday_years
validate :dont_exceed_days_remaining, :on => :create
validate :date_from_must_be_before_date_to#, :unless => self.errors.size > 1
validate :working_days_greater_than_zero#, :unless => self.errors.size > 1
validate :no_overlapping_holidays, :on => :create#, :unless => self.errors.size > 1
def date_from= val
self[:date_from] = convert_uk_date_to_iso val
end
def date_to= val
self[:date_to] = convert_uk_date_to_iso val
end
def self.team_holidays_as_json current_user, start_date, end_date
#TODO filter this to show all hols, by team, and by user
date_from = Time.at(start_date.to_i).to_date
date_to = Time.at(end_date.to_i).to_date
holidays = self.where "date_from >= ? and date_to <= ? and (manager_id=? or user_id=?)", date_from, date_to, current_user.manager_id, current_user.id
bank_holidays = BankHoliday.where "date_of_hol between ? and ? ", date_from, date_to
self.convert_to_json holidays, bank_holidays
end
private
def check_if_holiday_has_passed
unless holiday_status_id == 1
if date_to < Date.today
errors.add(:base, "Holiday has passed")
false
end
end
end
def self.convert_to_json holidays, bank_holidays
#TODO the colour class should be per user not per holiday
hol_colors = ['yellow', 'green', 'red', 'blue']
text_colors = ['black', 'white', 'white', 'white']
json = []
holidays.each do |hol|
email = hol.user.email
hol_hash = {:id => hol.id, :title=>hol.user.forename + ": "+ hol.description, :start=>hol.date_from.to_s, :end=>hol.date_to.to_s, :color=>hol_colors[hol.holiday_status_id-1], :textColor=>text_colors[hol.holiday_status_id-1], :borderColor=>'black'}
json << hol_hash
end
bank_holidays.each do |hol|
hol_hash = {:id => hol.id, :title=>hol.name, :start=>hol.date_of_hol.to_s, :color=>"black"}
json << hol_hash
end
json
end
#TODO add the overlaps between team members
# def intra_team_holiday_clashes
# end
def date_from_must_be_before_date_to
errors.add(:date_from, " must be before date to.") if date_from > date_to
end
def working_days_greater_than_zero
@working_days = business_days_between
errors.add(:working_days_used, " - This holiday request uses no working days") if @working_days==0
end
def holiday_must_not_straddle_holiday_years
#TODO this query will not be right - test with sql
number_years = HolidayYear.holiday_years_containing_holiday(date_from, date_to).count
errors.add(:base, "Holiday must not cross years") if number_years> 1
end
def no_overlapping_holidays
holidays = Vacation.where("user_id = ?", self.user_id)
holidays.each do |holiday|
errors.add(:base, "A holiday already exists within this date range") if overlaps?(holiday)
end
end
def overlaps?(holiday)
(date_from - holiday.date_to) * (holiday.date_from - date_to) >= 0
end
def convert_uk_date_to_iso date_str
split_date=date_str.split("/")
Date.new(split_date[2].to_i, split_date[1].to_i, split_date[0].to_i)
end
def save_working_days #TODO rename method
self[:working_days_used] = @working_days
unless self[:uuid]
guid = UUID.new
self[:uuid] = guid.generate
end
unless self[:holiday_year]
self.holiday_year = HolidayYear.holiday_year_used(self[:date_from], self[:date_to]).first
end
end
def business_days_between
holidays = BankHoliday.where("date_of_hol BETWEEN ? AND ?", date_from, date_to)
holidays_array = holidays.collect { |hol| hol.date_of_hol }
weekdays = (date_from..date_to).reject { |d| [0, 6].include? d.wday or holidays_array.include?(d) }
business_days = weekdays.length
end
def decrease_days_remaining
holiday_allowance = self.user.get_holiday_allowance_for_dates self.date_from, self.date_to
holiday_allowance.days_remaining -= business_days_between
holiday_allowance.save
end
def add_days_remaining
holiday_allowance = self.user.get_holiday_allowance_for_dates self.date_from, self.date_to
holiday_allowance.days_remaining += business_days_between
holiday_allowance.save
end
def dont_exceed_days_remaining
holiday_allowance = self.user.get_holiday_allowance_for_dates self.date_from, self.date_to
if holiday_allowance == 0 or holiday_allowance.nil? then return end
errors.add(:working_days_used, "-Number of days selected exceeds your allowance!") if holiday_allowance.days_remaining < business_days_between
end
end
| true |
3fbc07a0ebff38efab74df017eb3bb84cb983a09 | Ruby | roomorama/concierge | /lib/concierge/suppliers/avantio/commands/quote_fetcher.rb | UTF-8 | 2,752 | 2.875 | 3 | [] | no_license | module Avantio
module Commands
# +Avantio::Commands::QuoteFetcher+
#
# This class is responsible for wrapping the logic related to making a price
# quotation to Avantio, parsing the response.
#
# NOTE: Avantio GetBookingPrice method returns valid response even
# if accommodation is not available for given period, so it's important
# to check availability before using this fetcher.
# Usage
#
# command = Avantio::Commands::QuoteFetcher.new(credentials)
# result = command.call(params)
#
# if result.success?
# result.value # Avantio::Entities::Quotation instance
# end
# The +call+ method returns a +Result+ object that, when successful,
# encapsulates the instance of +Avantio::Entities::Quotation+.
class QuoteFetcher
OPERATION_NAME = :get_booking_price
attr_reader :credentials
def initialize(credentials)
@credentials = credentials
end
def call(params)
property_id = Avantio::PropertyId.from_roomorama_property_id(params[:property_id])
message = xml_builder.booking_price(property_id, params[:guests], params[:check_in], params[:check_out])
result = soap_client.call(OPERATION_NAME, message)
return result unless result.success?
result_hash = to_safe_hash(result.value)
return error_result unless valid_result?(result_hash)
quotation = mapper.build(result_hash)
Result.new(quotation)
end
private
def xml_builder
@xml_builder ||= Avantio::XMLBuilder.new(credentials)
end
def mapper
@mapper ||= Avantio::Mappers::Quotation.new
end
def soap_client
@soap_client ||= Avantio::SoapClient.new
end
def valid_result?(result_hash)
!!fetch_room_only_final(result_hash) &&
!!fetch_currency(result_hash)
end
def fetch_room_only_final(result_hash)
result_hash.get('get_booking_price_rs.booking_price.room_only_final')
end
def fetch_currency(result_hash)
result_hash.get('get_booking_price_rs.booking_price.currency')
end
def to_safe_hash(hash)
Concierge::SafeAccessHash.new(hash)
end
def error_result
message = 'Unexpected `get_booking_price` response structure'
mismatch(message, caller)
Result.error(
:unexpected_response_structure,
message
)
end
def mismatch(message, backtrace)
response_mismatch = Concierge::Context::ResponseMismatch.new(
message: message,
backtrace: backtrace
)
Concierge.context.augment(response_mismatch)
end
end
end
end
| true |
18a3dff89e12f1c73938bc8262f3c484f2908dff | Ruby | ssiarules/collections_practice-online-web-pt-011419 | /collections_practice.rb | UTF-8 | 847 | 3.96875 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | #1
def sort_array_asc (num)
num.sort
end
#2
def sort_array_desc (num)
num.sort do |a, b|
b <=> a
end
end
#3
def sort_array_char_count(num)
num.sort do |a, b|
a.length <=> b.length
end
end
#4
def swap_elements(num)
num[1], num[2] = num[2], num[1]
num
end
#Advanced
def swap_elements_from_to(array, index, destination_index)
array[index], array[destination_index] = array[destination_index], array[index]
array
end
#5
def reverse_array (num)
num.reverse!
end
def kesha_maker(array)
array.each do |x|
x[2] = '$'
end
end
#7
def find_a(array)
array.select do |x| x.start_with?("a")
end
end
def sum_array(num)
num.inject { |sum,num| sum + num}
end
def add_s(array)
array.collect do |x|
if x == "feet"
x
else
x << "s"
end
end
end
| true |
6c80066ee72e39b49e4cac172fc14447fb515608 | Ruby | DorianCBrwn/LaunchSchoolDCB | /RB101/small_problems/Easy_3/arithmetic_int.rb | UTF-8 | 958 | 4.28125 | 4 | [] | no_license | =begin
Write a program that prompts the user for two positive integers, and then prints
the results of the following operations on those two numbers: addition,
subtraction, product, quotient, remainder, and power.
Do not worry about validating the input.
=end
def prompt(message)
puts "==> #{message}"
end
prompt( "Enter the first number" )
first_num = gets.chomp.to_i
prompt("Enter the second number")
second_num = gets.chomp.to_i
sum = first_num + second_num
difference = first_num - second_num
product = first_num * second_num
quotient = first_num / second_num
remainder = first_num % second_num
power = first_num ** second_num
prompt("#{first_num} + #{second_num} = #{sum} ")
prompt("#{first_num} - #{second_num} = #{difference} ")
prompt("#{first_num} * #{second_num} = #{product} ")
prompt("#{first_num} / #{second_num} = #{quotient} ")
prompt("#{first_num} % #{second_num} = #{remainder} ")
prompt("#{first_num} ** #{second_num} = #{power} ")
| true |
955ffc7b8da47ed8c77b206a1875319777e3c598 | Ruby | lbrian357/bubble_sort | /spec/bubble_sort_spec.rb | UTF-8 | 560 | 3.546875 | 4 | [] | no_license | require 'bubble_sort'
describe '#bubble_sort' do
it 'takes an array and returns a sorted array' do
expect(bubble_sort([4,3,78,2,0,2])).to eq([0,2,2,3,4,78])
end
end
describe '#bubble_sort_by' do
it 'sorts an array of numbers based on a block' do
expect(bubble_sort_by([2,5,4,3,2,1]){|left,right| left - right}).to eq([1,2,2,3,4,5])
end
end
describe '#bubble_sort_by' do
it 'sorts an array based on a block' do
expect(bubble_sort_by(["hi","hello","hey"]){|left, right| left.length-right.length}).to eq(["hi", "hey", "hello"])
end
end
| true |
3e50cbab2f2236dc8ae2b55516b4ce375cca6751 | Ruby | Lastimoso/sorting | /sorting_benchmarks.rb | UTF-8 | 2,903 | 3.40625 | 3 | [] | no_license | # frozen_string_literal: true
require 'benchmark'
require './bubble'
require './selection'
require './insertion'
require './merge'
def sorted?(array)
array.each_cons(2).all? { |a, b| (a <=> b) <= 0 }
end
def array_is_ok?(array)
array.each_with_index do |value, index|
return false unless value == index + 1
end
true
end
examples = [100, 1_000, 10_000]
examples.each do |example|
array = (1..example).to_a.shuffle.freeze
puts "Example: Array Length = #{example}"
Benchmark.bm(7) do |x|
x.report('Bubble: ') { @bubble = SelectionSort.new(array.dup).sort }
x.report('Selection:') { @selection = SelectionSort.new(array.dup).sort }
x.report('Insertion:') { @insertion = InsertionSort.new(array.dup).sort }
x.report('Merge :') { @merge = MergeSort.new(array.dup).sort }
x.report('RubySort: ') { array.dup.sort }
end
puts ''
puts "ALERT!! BubbleSort is NOT sorted" unless sorted? @bubble
puts "ALERT!! SelectionSort is NOT sorted" unless sorted? @selection
puts "ALERT!! InsertionSort is NOT sorted" unless sorted? @insertion
puts "ALERT!! MergeSort is NOT sorted" unless sorted? @merge
puts "ALERT!! BubbleSort array has been modified" unless array_is_ok? @bubble
puts "ALERT!! SelectionSort arrys has been modified" unless array_is_ok? @selection
puts "ALERT!! InsertionSort arrys has been modified" unless array_is_ok? @insertion
puts "ALERT!! MergeSort arrys has been modified" unless array_is_ok? @merge
puts ''
end
example2_lenght = 10_000
examples2 = []
examples2 << ['Best Case', (1..example2_lenght).to_a.freeze]
examples2 << ['Worst Case', (1..example2_lenght).to_a.reverse.freeze]
examples2 << ['Random Case1', (1..example2_lenght).to_a.shuffle.freeze]
examples2 << ['Random Case2', (1..example2_lenght).to_a.shuffle.freeze]
examples2.each do |example|
array = example[1]
puts "Example: Array Length = #{example[0]}"
Benchmark.bm(7) do |x|
x.report('Bubble: ') { @bubble = SelectionSort.new(array.dup).sort }
x.report('Selection:') { @selection = SelectionSort.new(array.dup).sort }
x.report('Insertion:') { @insertion = InsertionSort.new(array.dup).sort }
x.report('Merge :') { @merge = MergeSort.new(array.dup).sort }
x.report('RubySort: ') { array.dup.sort }
end
puts ''
puts "ALERT!! BubbleSort is NOT sorted" unless sorted? @bubble
puts "ALERT!! SelectionSort is NOT sorted" unless sorted? @selection
puts "ALERT!! InsertionSort is NOT sorted" unless sorted? @insertion
puts "ALERT!! MergeSort is NOT sorted" unless sorted? @merge
puts "ALERT!! BubbleSort array has been modified" unless array_is_ok? @bubble
puts "ALERT!! SelectionSort arrys has been modified" unless array_is_ok? @selection
puts "ALERT!! InsertionSort arrys has been modified" unless array_is_ok? @insertion
puts "ALERT!! MergeSort arrys has been modified" unless array_is_ok? @merge
puts ''
end | true |
e24a2714b80e81fbb5bc925fccb5f8da6566ebd9 | Ruby | shahpriyesh2005/CAD_Project | /app/models/wishlist.rb | UTF-8 | 535 | 2.5625 | 3 | [] | no_license | class Wishlist < ApplicationRecord
belongs_to :user
EVENT_NAME = []
@events = Event.distinct.pluck(:title)
@events.each do |names|
EVENT_NAME << names
end
validates :wishlist_date,:user_id,:event_id, :presence => true
validate :check_wishlist_date
private
def check_wishlist_date
return if wishlist_date.blank?
if wishlist_date.strftime("%Y-%m-%d") < Time.now.strftime("%Y-%m-%d")
errors.add(:wishlist_date, "should be greater than current time")
end
end
end
| true |
b5d530475bbfb475bf7ae1254f9dcae89deeeb6b | Ruby | martom87/ror_and_ruby_exercises | /ruby_excercises/algorithms/sorting/sorter.rb | UTF-8 | 1,240 | 3.8125 | 4 | [] | no_license | class Sorter
def bubble_sort (input)
swap = true
return input if input.size <= 1
while swap
swap = false
((input.size) - 1).times do |i|
if input[i] > input[i + 1]
swap = true
input[i], input[i + 1] = input[i + 1], input[i]
end
end
end
return input
end
def insertion_sort (input)
return input if input.size <= 1
(input.size).times do |i|
while i > 0
if input[i] < input[i - 1]
input[i - 1], input[i] = input[i], input[i - 1]
else
break
end
i -= 1
end
end
return input
end
def quick_sort (input)
return input if input.size <= 1
pivot = input.delete_at(rand(input.size))
left = []
right = []
input.each do |i|
if i < pivot
left << i
else
right << i
end
end
return *quick_sort(left), pivot, *quick_sort(right)
end
end
################DEMO##############################################
sorter = Sorter.new
#print (sorter.bubble_sort ([1, 4, 2, 100, 5, 234, 12, 66, 777]))
#print (sorter.insertion_sort ([1, 4, 2, 100, 5, 234, 12, 66, 777]))
print (sorter.quick_sort ([1, 4, 2, 100, 5, 234, 12, 66, 777]))
| true |
292e5575b3e660e61ee2a5089c39a207a2fca8ac | Ruby | brandnewbox/gush-control | /lib/gush/control/logger.rb | UTF-8 | 1,817 | 2.734375 | 3 | [
"MIT"
] | permissive | require 'logger'
require 'time'
module Gush
module Control
class Logger
include ::Logger::Severity
attr_accessor :level, :progname
def initialize(redis, channel, level = DEBUG)
@progname = nil
@redis = redis
@level = level
@channel = channel
end
def add(severity = UNKNOWN, message = nil, prog = nil, &block)
return true if severity < level
if message.nil?
if block_given?
message = yield
else
message = prog
prog = progname
end
end
write(format_message(severity, prog || progname, message))
true
end
alias log add
def <<(message)
write(message)
end
def debug(message = nil, &block)
add(DEBUG, message, nil, &block)
end
def info(progname = nil, &block)
add(INFO, nil, progname, &block)
end
def warn(progname = nil, &block)
add(WARN, nil, progname, &block)
end
def error(progname = nil, &block)
add(ERROR, nil, progname, &block)
end
def fatal(progname = nil, &block)
add(FATAL, nil, progname, &block)
end
def unknown(progname = nil, &block)
add(UNKNOWN, nil, progname, &block)
end
def close
# noop
end
private
LABELS = %w(DEBUG INFO WARN ERROR FATAL ANY)
attr_reader :redis, :channel
def write(message)
redis.rpush(channel, message)
end
def format_message(severity, prog, message)
current_time = Time.now.utc
severity = LABELS[severity]
"%s, [%s.%s #%s] %5s -- %s: %s\n" % [severity[0], current_time.iso8601, current_time.usec, $$, severity, prog, message]
end
end
end
end
| true |
3092c6f0ee25bb493e7965d1a1943751cf158ce9 | Ruby | andrefaria/where-to-go | /app/models/event.rb | UTF-8 | 521 | 2.8125 | 3 | [] | no_license | class Event < ActiveRecord::Base
has_many :options
validates_presence_of :date
def pick_a_place
if self.options.empty? or self.options.length <= 1 then
self.errors.add :place, 'To pick a place you should first add at least two options to the event'
return false
else
old_place = self.place
while self.place.nil? or self.place == old_place do
self.place = self.options[rand(self.options.size())].name
end
return true
end
puts self.place
end
end | true |
f7130eba4ced2ca25b5f0b7c47fd1240b9385492 | Ruby | iagomoure/important-programs | /chess_validator/chess_validator.rb | UTF-8 | 1,085 | 3.25 | 3 | [] | no_license | require 'pry'
class Rock
end
class Knight
end
class Bishop
end
class Queen
end
class King
end
class Pawn
end
class Board
def initialize
@grid = [
[:bR,:bN,:bB,:bQ,:bK,:bB,:bN,:bR],
[:bP,:bP,:bP,:bP,:bP,:bP,:bP,:bP],
[nil,nil,nil,nil,nil,nil,nil,nil],
[nil,nil,nil,nil,nil,nil,nil,nil],
[nil,nil,nil,nil,nil,nil,nil,nil],
[nil,nil,nil,nil,nil,nil,nil,nil],
[:wP,:wP,:wP,:wP,:wP,:wP,:wP,:wP],
[:wR,:wN,:wB,:wQ,:wK,:wB,:wN,:wR]
]
@kyes = {
:bR => Rock,
:bN => Knight,
:bB => Bishop,
:bQ => Queen,
:bK => King,
:bP => Pawn,
:wR => Rock,
:wN => Knight,
:wB => Bishop,
:wQ => Queen,
:wK => King,
:wP => Pawn
}
end
end
b = Board.new
binding.pry
=begin
class Piece
def initialize color,origin
@color = color
@origin = origin
end
end
class Rock < Piece
def initialize color,origin,motion
super color,origin
@motion = motion
end
def check_move origin, destination
if @origin[0] == destination[0] || @origin[1] == @destination [1]
return LEGAL
end
end
end
class Empty
end
=end
| true |
74c79f5a3cba68adc1d46e2e9025e8406d725fe7 | Ruby | ztaylorpossible/DailyProg | /Ruby/30e.rb | UTF-8 | 863 | 4.375 | 4 | [] | no_license | # Daily Programmer Easy Challenge #30 July 8, 2013
# Summary:
# Write a program that takes a list of integers and a target number and
# determines if any two integers in the list sum to the target number. If
# so, return the two numbers. If not, return an indication that no such
# integers exist.
puts "Enter a list of numbers separated by spaces: "
list = gets.chomp.split(/ /)
list.map! { |x| x.to_i }
list.sort!
min_index = 0
max_index = list.length - 1
found = false
puts "Enter sum to search for: "
sum = gets.chomp.to_i
while not found
test_sum = list[min_index] + list[max_index]
if min_index == max_index
puts "Sum not found"
break
elsif test_sum == sum
puts "#{list[min_index]} + #{list[max_index]} at indices #{min_index} and #{max_index}"
found = true
elsif test_sum > sum
max_index -= 1
else
min_index += 1
end
end
| true |
299833ec14e5e852d8b8320ed67e34acf9594380 | Ruby | rakibulislam/BDDPackage | /table_h.rb | UTF-8 | 385 | 3.15625 | 3 | [] | no_license | class Table_H
attr_accessor :h
def initialize
@h = Hash.new
end
def member?(triple)
key = build_key(triple)
h.keys.include? key
end
def lookup(triple)
key = build_key(triple)
h[key]
end
def insert(triple, u)
key = build_key(triple)
h[key] = u
end
def build_key(triple)
"i: #{triple.i}, l: #{triple.l}, h: #{triple.h}"
end
end
| true |
d5f0e5ab4cec19588de0a62dd0d1a02eeeaaed2a | Ruby | r7kamura/rnes | /lib/rnes/dma_controller.rb | UTF-8 | 745 | 2.703125 | 3 | [
"MIT"
] | permissive | module Rnes
class DmaController
TRANSFER_BYTESIZE = 2**8
# @param [Rnes::Ppu] ppu
# @param [Rnes::Ram] working_ram
def initialize(ppu:, working_ram:)
@ppu = ppu
@requested = false
@working_ram = working_ram
end
def transfer_if_requested
if @requested
transfer
end
end
# @param [Integer] address_hint
def request_transfer(address_hint:)
@requested = true
@working_ram_address = address_hint << 8
end
private
def transfer
TRANSFER_BYTESIZE.times do |index|
value = @working_ram.read(@working_ram_address + index)
@ppu.transfer_sprite_data(index: index, value: value)
end
@requested = false
end
end
end
| true |
017cab8d49520e1d223073fafaac962aec92c40f | Ruby | BrownCow371/rack-intro-v-000 | /application.rb | UTF-8 | 193 | 2.53125 | 3 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | class Application
def call(env)
resp = Rack::Response.new
resp.write "Hello, World \n"
resp.write "Hello, my name is Simon and I like to do drawings!"
resp.finish
end
end
| true |
36f191b472e7266fbb9007052278622b57765c75 | Ruby | anumolusrikanth/training | /srikanth/ruby_prgms/first.rb | UTF-8 | 679 | 3.875 | 4 | [] | no_license | #!/usr/bin/env ruby
$global_var=3
Const ='welcome'
class Print
@@no_of_persons=0
def first_method
puts "Hello : #$global_var"
::Const + 'Macys'
end
def initialize(id, firstname)
@person_id=id
@person_name=firstname
end
def display
puts "Person ID is #@person_id"
puts "Person Name is #@person_name"
end
def no_of_persons
@@no_of_persons +=1
puts "No of Persons : #@@no_of_persons"
end
end
obj=Print.new("1","Srikanth")
obj1=Print.new("2","Anumolu")
obj2=Print.new("4","Nisum")
obj.first_method
obj.display
obj1.display
obj2.display
obj.no_of_persons
obj1.no_of_persons
obj2.no_of_persons
puts Object::Const
"puts Print::Const"
| true |
ff76a87a00dc06877f0b0876fe3be7989aae2b2e | Ruby | byroot/parsr | /lib/parsr/rules/hash.rb | UTF-8 | 1,206 | 2.84375 | 3 | [
"MIT"
] | permissive | module Parsr::Rules::Hash
class MissingValue < Parsr::SyntaxError
message "unexpected '%{rest}'"
end
class MissingSeparator < Parsr::SyntaxError
message "unexpected '%{rest}', expecting '=>'"
end
class Unterminated < Parsr::SyntaxError
message "unexpected '%{rest}', expecting '}'"
end
class << self
def match(scanner, &block)
if scanner.scan(/\{\s*/)
hash = []
while pair = parse_pair(scanner, &block)
hash << pair
break unless scanner.scan(/\s*\,\s*/)
end
raise Unterminated.new(scanner) unless scanner.scan(/\s*\}\s*/)
Parsr::Token.new(Hash[hash])
end
end
def parse_pair(scanner, key=nil)
unless key.is_a?(Parsr::Token)
if scanner.scan(/[a-zA-Z_][0-9a-zA-Z_]*\:/)
key = Parsr::Token.new(scanner.matched.chomp(':').to_sym)
elsif key = yield and key.is_a?(Parsr::Token)
raise MissingSeparator.new(scanner) unless scanner.scan(/\s*=>\s*/)
else
return false
end
end
value = yield
raise MissingValue.new(scanner) unless value && value.is_a?(Parsr::Token)
[key, value].map(&:value)
end
end
end | true |
f33c46fe95524c556438d62b35121bcd3fbd4ee7 | Ruby | Dpalazzari/module_3_assessment | /app/site_models/store_total.rb | UTF-8 | 186 | 2.71875 | 3 | [] | no_license | class StoreTotal
attr_reader :count
def initialize(total={})
@count = total
end
def self.find_total(zip)
total = StoreService.find_total(zip)
new(total)
end
end | true |
58df1bca7169f78b28da51a6b0997c806990d98b | Ruby | intrip/ruby-algorithms | /geeks_for_geeks/bottom_view_binary_tree.rb | UTF-8 | 3,825 | 3.953125 | 4 | [] | no_license | # https://practice.geeksforgeeks.org/problems/bottom-view-of-binary-tree/1
# Given a binary tree, print the bottom view from left to right.
# A node is included in bottom view if it can be seen when we look at the tree from bottom.
# 20
# / \
# 8 22
# / \ \
# 5 3 25
# / \
# 10 14
# For the above tree, the bottom view is 5 10 3 14 25.
# If there are multiple bottom-most nodes for a horizontal distance from root, then print the later one in level traversal. For example, in the below diagram, 3 and 4 are both the bottommost nodes at horizontal distance 0, we need to print 4.
# 20
# / \
# 8 22
# / \ / \
# 5 3 4 25
# / \
# 10 14
# For the above tree the output should be 5 10 4 14 25.
# Input Format:
# The first line of input contains T denoting number of testcases. T testcases follow. Each testcase contains two lines of input. The first line contains the number of edges. The second line contains the relation between nodes.
# Output Format:
# The function should print nodes in bottom view of Binary Tree. Your code should not print a newline, it is added by the caller code that runs your function.
# User Task:
# This is a funcitonal problem, you don't need to care about input, just complete the function bottomView() which should print the bottom view of the given tree.
# Constraints:
# 1 <= T <= 30
# 0 <= Number of nodes <= 100
# 0 <= Data of a node <= 1000
# Example:
# Input:
# 2
# 2
# 1 2 R 1 3 L
# 4
# 10 20 L 10 30 R 20 40 L 20 60 R
# Output:
# 3 1 2
# 40 20 60 30
# Explanation:
# Testcase 1: First case represents a tree with 3 nodes and 2 edges where root is 1, left child of 1 is 3 and right child of 1 is 2.
class Node
attr_accessor :k, :l, :r
def initialize(k, l=nil, r=nil)
@k = k
@l = l
@r = r
end
end
# This algorithm takes O(n) time to complete and uses O(k) extra memory
def bottom_view(root)
path = [[root, 0]]
nodes_by_height = { 0 => root }
min_height = 0
loop do
current, height = path.shift
break unless current
if current.l
path << [current.l, height - 1]
nodes_by_height[height - 1] = current.l
min_height = (height - 1) if min_height > (height - 1)
end
if current.r
path << [current.r, height + 1]
nodes_by_height[height + 1] = current.r
end
end
# p nodes_by_height.map { |k,v| [k, v.k] }
i = min_height
while nodes_by_height[i] do
print "#{nodes_by_height[i].k} "
i += 1
end
end
#Â this function is tail recursive and can benefit from Tail recursive optimization
def build_nodes_by_height(node, hor_height, height, nodes_by_height = {})
if node.l
build_nodes_by_height(node.l, hor_height - 1, height + 1, nodes_by_height)
end
# overwrite only if node has higher height
if nodes_by_height[hor_height].nil? || nodes_by_height[hor_height][1] <= height
nodes_by_height[hor_height] = [node, height]
end
if node.r
build_nodes_by_height(node.r, hor_height + 1, height + 1, nodes_by_height)
end
end
def bottom_view_rec(root)
nodes_by_height = {}
build_nodes_by_height(root, 0, 0, nodes_by_height)
# p nodes_by_height.map { |k,v| [k, v.k] }
i = nodes_by_height.keys.min
while nodes_by_height[i] do
print "#{nodes_by_height[i][0].k} "
i += 1
end
end
# 10
# / \
# 20 30
# / \
# 40 60
n_60 = Node.new(60)
n_40 = Node.new(40)
n_20 = Node.new(20, n_40, n_60)
n_30 = Node.new(30)
root = Node.new(10, n_20, n_30)
bottom_view(root)
# expected: 40 20 60 30
print "\n"
bottom_view_rec(root)
| true |
ebb0f8ec705233ac36fc7e275d2eae5cecd12d15 | Ruby | isatakebayashi/stock-management | /app/services/stock_management_service.rb | UTF-8 | 535 | 2.953125 | 3 | [] | no_license | class StockManagementService
attr_accessor :amount, :stock
def initialize(id, amount)
@stock = find_stock(id)
@amount = amount.to_i
end
def update_stock(operation)
new_amount = send(operation)
@stock.update!(amount: new_amount)
rescue ActiveRecord::RecordInvalid => e
{ error: 'Quantidade de items indisponÃvel.' }
end
def add
@stock.amount += @amount
end
def remove
@stock.amount -= @amount
end
private
def find_stock(id)
@stock ||= StockItem.find_by(id: id)
end
end
| true |
10af836fcf8684f10b59f0a47a0fb0ab9622c17a | Ruby | Rxbsxn/factorialize_recursion | /factorialize_by_recursion_spec.rb | UTF-8 | 774 | 2.921875 | 3 | [] | no_license | require "./factorialize_by_recursion"
describe Factorialize do
describe ".factorialize" do
context "Given -4" do
it "should return -1" do
expect(Factorialize.factorialize(-3)).to eql(-1)
end
end
context "Given 0" do
it 'should return 1' do
expect(Factorialize.factorialize(0)).to eql(1)
end
end
context "Given various number" do
it 'should return expected factorialize' do
expect(Factorialize.factorialize(5)).to eql(120)
expect(Factorialize.factorialize(6)).to eql(720)
expect(Factorialize.factorialize(3)).to eql(6)
end
end
end
end | true |
16d8bc8cc74909d3dac6114645d223b413083fd2 | Ruby | bellmyer/genetic-algorithm | /lib/hello_world.rb | UTF-8 | 597 | 3.4375 | 3 | [] | no_license | class HelloWorld
attr_reader :target, :letters
LETTER_POOL = (
('a'..'z').to_a +
('A'..'Z').to_a +
'!?.,-_ '.split('')
)
TARGET = "Hello, World!"
class << self
def top_score
return @top_score if defined?(@top_score)
@top_score = TARGET.size
end
end
def initialize *letters
@letters = letters
@target = TARGET.split('')
end
def score
total = 0
target.each_with_index do |target_letter, i|
total += 1 if target_letter == letters[i]
end
total
end
def to_s
letters.join('')
end
end | true |
df7835cd10f0d7f3b624f218ba53e79ec7ebc68f | Ruby | isabella232/twitter-search-sample | /lib/twitter_search.rb | UTF-8 | 2,364 | 2.609375 | 3 | [
"Apache-2.0"
] | permissive | require 'tweetstream'
require 'twitter'
require 'nokogiri'
require 'uuidtools'
require 'httpclient'
class TwitterSearch
attr_reader :hash_tags
def initialize(params = {})
@hash_tags = params[:hash_tags]
authenticate_twitter
end
def authenticate_twitter
Twitter.configure do |config|
config.consumer_key = ""
config.consumer_secret = ""
config.oauth_token = ""
config.oauth_token_secret = ""
end
end
def fetch
Twitter.search("#{hash_tags}", count: 500, result_type: "recent").results.each do |status|
tweet = clean_tweet(status.text)
output = get_kaf(tweet)
puts tweet
end
end
def clean_tweet(tweet)
tweet
.gsub("RT", "")
.gsub(/#\S*/, "")
.gsub(/@\S*/, "")
.gsub(/http\S*/, "")
.gsub(" ", " ")
.rstrip
.lstrip
end
def get_kaf(tweet)
client = HTTPClient.new
language_identifier = "http://opener.olery.com/language-identifier"
output = client.post(language_identifier, :input => tweet, :kaf => true )
if no_error?(output)
res = output
tokenizer = "http://opener.olery.com/tokenizer"
output = client.post(tokenizer, :input => res.body, :kaf => true)
end
if no_error?(output)
res = output
pos_tagger = "http://opener.olery.com/POS-tagger"
output = client.post(pos_tagger, :input => res.body)
end
if no_error?(output)
res = output
polarity_tagger = "http://opener.olery.com/polarity-tagger"
output = client.post(polarity_tagger, :input => res.body)
end
if no_error?(output)
res = output
ner = "http://opener.olery.com/ner"
output = client.post(ner, :input => res.body)
end
if no_error?(output)
res = output
opinion_detector = "http://opener.olery.com/opinion-detector"
output = client.post(opinion_detector, :input => res.body)
end
if no_error?(output)
res = output
end
unless res.nil?
File.open(["tmp/", create_uuid, ".txt"].join, 'w') { |file| file.write(res.body) }
end
end
def no_error?(output)
if output.status == 200 && output.body.index('Internal Server Error').nil? && !output.nil?
true
else
false
end
end
def create_uuid
UUIDTools::UUID.random_create.to_s
end
end | true |
cd146d0ed57b4cc0451986e7788f3cba7aaafee2 | Ruby | tijn/reactive_array | /lib/serializing_array.rb | UTF-8 | 860 | 2.796875 | 3 | [] | no_license | # calls #rewrite! upon any method that is not used for reading
class SerializingArray < ReactiveArray
# these methods are only used for reading, not for writing so we don't have to #rewrite! when they are used.
SAFE_METHODS = [:[], :abbrev, :assoc, :at, :collect, :compact, :empty?, :eql?, :first, :flatten, :frozen, :hash, :include?, :index, :inspect, :join, :last, :length, :map, :nitems, :pack, :reject, :reverse, :reverse_each, :rindex, :select, :size, :slice, :sort, :to_a, :to_s, :transpose, :uniq, :values_at, :zip, :all?,
:any?, :detect, :each_cons, :each_slice, :each_with_index, :each, :entries, :find, :find_all, :grep, :member?, :inject, :max, :min, :partition, :to_set]
def react!(m)
rewrite! unless SAFE_METHODS.include? m
end
def rewrite!
raise NotImplemented, "responsibility of subclass"
# puts "rewriting"
end
end
| true |
505821cd136d66b9a93f002f8375d6766f050d79 | Ruby | YogiZoli/studiogame-2015 | /lib/studio_game/game.rb | UTF-8 | 3,534 | 3.40625 | 3 | [] | no_license | #require "player"
#require 'pry'
#pry.binding
require 'studio_game/player'
require 'studio_game/die'
require 'studio_game/game_turn'
require 'studio_game/treasure_trove'
module StudioGame
class Game
attr_reader :title
def initialize(title)
@title = title
@players = []
end
def add_player(a_player)
@players << a_player
end
def load_players(source_file)
File.readlines(source_file).each do |line|
add_player(Player.from_csv(line))
end
end
def play(rounds=2)
puts "\nThere are #{@players.size} players in #{@title}: "
1.upto(rounds) do |round|
puts '###############################################################'
puts "This is round number #{round}: \n"
@players.each do |player|
GameTurn.take_turn(player)
puts player.name
end
end
@players.each do |player|
puts player.name
end
treasures = TreasureTrove::TREASURES
puts "\nThere are #{treasures.size} treasures to be found:\n"
treasures.each do |treasure|
puts "A #{treasure.name} is worth #{treasure.points} points."
end
end
def print_stats
strong_players, wimpy_players = @players.partition { |p| p.strong? }
#strong_players = @players.select { |player| player.strong? }
#wimpy_players = @players.reject { |player| player.strong? }
puts "\n#{@title} Statistics:"
puts "\n#{strong_players.size} strong players:"
strong_players.each do |player|
print_name_and_health(player)
end
puts "\n#{wimpy_players.size} wimpy players:\n"
wimpy_players.each do |player|
print_name_and_health(player)
end
puts "\n#{title} High Scores:"
@players.sort.each do |player|
puts high_score_entry(player)
end
puts "\nTotal points of players:\n\n"
@players.each do |player|
puts "\n#{player.name}\'s point totals:"
player.each_found_treasure do |treasure|
puts "#{treasure.points} total #{treasure.name} points"
end
puts "#{player.points} grand total points \n"
end
puts "\n#{total_points} total points from treasures found\n "
end
def print_name_and_health(player)
puts "#{player.name} (#{player.health})"
end
def high_score_entry(player)
formatted_name = player.name.ljust(20, '.')
"#{formatted_name} #{player.score}\n"
end
def total_points
@players.reduce(0) { |sum, player| sum + player.points }
end
def save_high_scores(target_file="high_scores.txt")
File.open(target_file, "w") do |file|
file.puts "#{@title} High Scores:"
@players.sort.each do |player|
file.puts high_score_entry(player)
end
end
end
end
end
if __FILE__ == $0
puts "this is the game file"
end | true |
716fc9f16dfdda00236f757f29267de0a5860bb0 | Ruby | manavt/E-commerce | /lib/mygem.rb | UTF-8 | 181 | 2.6875 | 3 | [] | no_license | class Mygem
class << self
def calc(op, *args)
array = *args
return array if array.count == 1
result = array.inject(op)
return result
end
end
end
| true |
dbc0d22ae8c534a74baf1786b19f3080526cc36f | Ruby | rsmith167/cartoon-collections-onl01-seng-pt-030220 | /cartoon_collections.rb | UTF-8 | 743 | 3.609375 | 4 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | def roll_call_dwarves(array)# code an argument here
# Your code here
array.each_with_index do |name, index|
puts "#{index+1} #{name}"
end
end
def summon_captain_planet(array)# code an argument here
# Your code here
array.collect do |call|
call = call.capitalize
call << "!"
end
end
def long_planeteer_calls(array)# code an argument here
# Your code here
array.any? do |call| call.length > 4 end
end
def find_the_cheese(array)# code an argument here
# the array below is here to help
cheese_types = ["cheddar", "gouda", "camembert"]
if( !array.include?("cheddar") && !array.include?("gouda") && !array.include?("camembert"))
return nil
else
array.detect{|cheese| cheese == "cheddar"}
end
end
| true |
d4db2412d8d0ca0f2b6f82d7a7ebd8bcec53ed4f | Ruby | jbharwood/code-challenges | /sumzero/temperature.rb | UTF-8 | 1,303 | 3.4375 | 3 | [] | no_license | require 'pry'
class TemperatureTracker
def initialize
@temperatures = []
end
def insert(temp)
@temperatures << temp
end
def getMax
@temperatures.max
end
def getMin
@temperatures.min
end
def getMean
sum = 0
@temperatures.each do |t|
sum += t
end
mean = sum/@temperatures.length.to_f
end
def getMode
hash = {}
@temperatures.each do |t|
if hash[t].nil?
hash[t] = 1
else
hash[t] += 1
end
end
sorted = hash.sort_by do |k,v|
v
end
sorted.last[0]
end
def isEligible?(citizenID)
sentEmails = Email.connection.select_all("
SELECT COUNT(id) AS number_of_emails, SUM(LEN(content)) AS char_count
FROM emails
WHERE sender_id = #{citizenID}
AND created_at BETWEEN DATEADD(DAY, -7, GETDATE()) AND DATEADD(DAY, 1, GETDATE())
ORDER BY created_at DESC
").to_hash
if sentEmails.number_of_emails > 5
return false
end
if sentEmails.char_count > 200
return false
end
return true
end
end
temps = TemperatureTracker.new()
temps.insert(1)
temps.insert(2)
temps.insert(2)
temps.insert(2)
temps.insert(3)
temps.insert(4)
temps.insert(4)
temps.insert(4)
temps.insert(4)
temps.getMean()
temps.getMode()
| true |
1454292db150a52a5afb3444c11ca811417af392 | Ruby | ArjunAranetaCodes/MoreCodes-Ruby | /Conversions/problem5.rb | UTF-8 | 133 | 3.53125 | 4 | [] | no_license | #Problem 5: Write a program that converts an array/list to string.
arrNumbers = [1,2,3]
numbers = arrNumbers.join("")
print numbers
| true |
3fb1af8343372618ec473692dd135b2ff4afc483 | Ruby | SebCodesStuff/ar-exercises | /exercises/exercise_5.rb | UTF-8 | 438 | 3.03125 | 3 | [] | no_license | require_relative '../setup'
require_relative './exercise_1'
require_relative './exercise_2'
require_relative './exercise_3'
require_relative './exercise_4'
puts "Exercise 5"
puts "----------"
@totalRevenue = Store.sum(:annual_revenue)
puts "Total revenue is $#{@totalRevenue}"
count = Store.count(:annual_revenue)
puts "Average revenue is $#{@totalRevenue/count}"
over1M = Store.where("annual_revenue > '1000000'").count
puts over1M
| true |
f35e9bd09db177b14fe2d3f05a027f72b2762f8d | Ruby | smodiz/quiznerd | /app/models/flash_card_importer.rb | UTF-8 | 1,629 | 3.109375 | 3 | [] | no_license | # This class is for creating a flash
# card deck from a quiz. The questions
# on the quiz become flash cards on the
# deck. This is only currently used from
# the console and not from the web interface
# of the application.
class FlashCardImporter
attr_reader :deck
delegate :errors, to: :deck
def initialize(deck)
@deck = deck
end
def import_from_quiz(quiz, difficulty = nil)
@quiz = quiz
@difficulty = difficulty
deck.flash_cards = flash_cards_from_questions(start_sequence)
deck.save
end
private
def start_sequence
(@deck.flash_cards.map(&:sequence).max || 0) + 1
end
def flash_cards_from_questions(start_sequence)
flash_cards = []
@quiz.questions.each_with_index do |question, index|
flash_cards << FlashCard.new(deck_id: @deck.id,
front: build_front(question),
back: build_back(question),
sequence: index + start_sequence,
difficulty: @difficulty)
end
flash_cards
end
def build_back(question)
''.tap do |back|
back << get_answer(question.answers)
back << get_remarks(question) if question.remarks.present?
end
end
def get_answer(answers)
answers.each_with_object('') do |a, back|
back << "#{a.content}\n" if a.correct?
end
end
def get_remarks(question)
"Remarks: \n\n #{question.remarks}"
end
def build_front(question)
if question.question_type == 'T/F'
"True or False:\n\n#{question.content}"
else
question.content
end
end
end
| true |
a94f50884bf1c42beeb1172b71983db177ac313f | Ruby | Sh1pley/enigma | /lib/encrypt.rb | UTF-8 | 730 | 3.234375 | 3 | [] | no_license | require_relative 'file_worker'
require_relative 'encryption'
require_relative "encryption_rotations"
class Encrypt
# binding.pry
attr_reader :file_worker,
:encryption
def initialize
@file_worker = FileWorker.new
end
def open_file
message = file_worker.file_reader(ARGV[0])
encrypt_the_message(message)
end
def encrypt_the_message(message)
@encryption = Encryption.new(message)
encrypted = encryption.splits_the_message
write_file(encrypted)
end
def write_file(encrypted)
file_worker.file_writer(encrypted)
puts "You created #{ARGV[1]} with a key of #{encryption.key.join} and a date of #{Time.now.strftime("%d%m%y")} "
end
end
e = Encrypt.new
e.open_file
| true |
984fb0d3ab65298bcbc7993189e94de25d8f2533 | Ruby | kinasmith/kinasmith.com | /_plugins/vimeo.rb | UTF-8 | 713 | 2.515625 | 3 | [
"Apache-2.0"
] | permissive | # A plugin for embedding videos from Vimeo using a simple Liquid tag, ie: {% vimeo 12345678 %}.
# Based of the Youtube plugin from https://www.portwaypoint.co.uk/jekyll-youtube-liquid-template-tag-gist/
# bug. Videos don't scale
module Jekyll
class Vimeo < Liquid::Tag
@@width = 690
@@height = 471
def initialize(name, id, tokens)
super
@id = id
end
def render(context)
%(<div class="embed-responsive embed-responsive-16by9"><iframe class="embed-responsive-item" src="https://player.vimeo.com/video/#{@id}" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe></div>)
end
end
end
Liquid::Template.register_tag('vimeo', Jekyll::Vimeo) | true |
f0dbcfc268d28aab840d762bc0028ef6e9fc8bd6 | Ruby | lefarmer/uk_mail | /lib/uk_mail/ireland_data.rb | UTF-8 | 1,189 | 2.6875 | 3 | [
"MIT"
] | permissive | module UKMail
class IrelandData
IRELAND_COUNTY_PREFIXES = %w[County Cnty CC. CC Ct. Ct Co. Co C.]
IRELAND_COUNTIES = %w[
Carlow Cavan Clare Cork Donegal Dublin Galway Kerry Kildare Kilkenny Laois Leitrim
Limerick Longford Louth Mayo Meath Monaghan Offaly Roscommon Sligo Tipperary Waterford
Westmeath Wexford Wicklow
]
def initialize(county, postcode)
@county = county.to_s.strip.downcase
@postcode = postcode.to_s.strip.downcase
end
def ireland_county
@ireland_county ||=
begin
IRELAND_COUNTY_PREFIXES.each do |prefix|
@county.gsub!(/^#{Regexp.escape(prefix.downcase)} /i, '')
end
@county.capitalize!
@county if IRELAND_COUNTIES.include?(@county)
end
end
def ireland_postcode
@ireland_postcode ||=
if ireland_county == 'Dublin'
dublin_postcode
else
row = PostcodeData.row_from_county(ireland_county)
row.nil? ? nil : row.postcode.strip
end
end
private
def dublin_postcode
if match = /^(d|dublin)? *(\d+)$/.match(@postcode)
'D' + match.captures[1].to_i.to_s
end
end
end
end
| true |
682d9734780cfeb10bc767d073ba94b42e2d8316 | Ruby | dancarter/FlashTerminal | /menuselector.rb | UTF-8 | 2,072 | 3.578125 | 4 | [] | no_license | class MenuSelector
attr_reader :decks
OPTIONS = ['done','delete','new','edit']
def initialize(decks)
@decks = decks.nil? ? {} : decks
@reviewing = true
end
def menu
puts "Decks--------------------------------"
@decks.each_key do |name|
puts "#{name}"
end
puts "No decks made yet!" if @decks.size == 0
puts "-------------------------------------"
puts "Type 'new' to create a new deck"
puts "Type 'delete (name)' to delete a deck"
puts "Type 'edit (name)' to edit a deck"
puts "Type 'done' to exit the program"
print "Enter the name of a deck to review\n> "
end
def perform_menu_selection
option = gets.chomp
if !good_menu_choice?(option)
print "Invalid selection.\n> "
perform_menu_selection
elsif option.downcase == 'new'
create_deck
elsif option.downcase.include?('delete')
delete_deck(option)
elsif option.downcase.include?('edit')
edit_deck(option)
elsif option.downcase == 'done'
@reviewing = false
else
review(option)
end
end
def review(option)
reviewer = Reviewer.new(@decks[option])
reviewer.begin_review
end
def create_deck
creater = DeckCreater.new
@decks = creater.new_deck(@decks)
end
def delete_deck(option)
deck_name = option.split(" ")[1,option.size-1].join(" ")
if @decks.keys.include?(deck_name)
puts "'#{deck_name}' has been deleted."
@decks.delete(deck_name)
else
puts "Deck '#{deck_name}' was not found."
end
gets
end
def edit_deck(option)
deck_name = option.split(" ")[1,option.size-1].join(" ")
if @decks.keys.include?(deck_name)
editor = DeckEditor.new(@decks[deck_name])
@decks[deck_name] = editor.edit
else
puts "Deck '#{deck_name}' was not found."
gets
end
end
def good_menu_choice?(choice)
return false if choice.nil?
return true if @decks.keys.include?(choice) || OPTIONS.include?(choice.downcase.split(" ")[0])
false
end
def reviewing?
@reviewing
end
end
| true |
a1561b522ba032d94994e88b3cd8bb20529dbdaf | Ruby | envylabs/Gister | /spec/middleware_spec.rb | UTF-8 | 2,870 | 2.578125 | 3 | [
"MIT"
] | permissive | require 'gister/middleware'
require_relative 'helper'
require 'rack'
describe Gister::Middleware do
let(:app) { load_app }
let(:response) { request(app, path) }
subject { response }
describe "when responding to a request with a gist path" do
context "and the path has a github username in it" do
let(:path) {
"/gist/codeschool-courses/1111.json?file=app.js&callback=jQueryCallback&_=12012981921"
}
context 'and getting content from the fetcher works' do
let(:response_body) {
"{hello:'world'}"
}
before do
app.stub(:fetch_by_path).and_return(response_body)
end
it "should use the url as the key to fetcher with the callback or timestamp" do
app.should_receive(:fetch_by_path).with("https://gist.github.com/codeschool-courses/1111.json?file=app.js").and_return(response_body)
subject
end
end
end
context "and the path doesn't have a github username in it" do
let(:path) {
"/gist/1111.json?file=app.js&callback=jQueryCallback&_=12012981921"
}
context 'and getting content from the fetcher works' do
let(:response_body) {
"{hello:'world'}"
}
before do
app.stub(:fetch_by_path).and_return(response_body)
end
it "should use the url as the key to fetcher with the callback or timestamp" do
app.should_receive(:fetch_by_path).with("https://gist.github.com/1111.json?file=app.js").and_return(response_body)
subject
end
it "should wrap the response from fetcher in the callback param" do
subject[2].should == ["jQueryCallback(#{response_body})"]
end
it "should return a 200" do
subject[0].should == 200
end
it "should have a content type of application/javascript" do
subject[1]['Content-Type'].should == "application/javascript"
end
end
context 'and getting content from the fetcher raises a ClientError' do
before do
app.stub(:fetch_by_path).and_raise(Gister::Fetcher::ClientError)
end
it "should return a 404" do
subject[0].should == 404
end
it "should have an empty body" do
subject[2].should == [""]
end
end
end
end
describe "when responding to a request without a gist path" do
let(:path) { "/hello" }
it "should pass through to the inner app" do
subject[2].should == 'Success'
end
end
def load_app
described_class.new inner_app, fetcher
end
def inner_app
lambda { |env| [200, {'Content-Type' => 'text/plain'}, 'Success'] }
end
def request(app, path, options = {})
app.call Rack::MockRequest.env_for(path, options)
end
def fetcher
Gister::Fetcher.new
end
end
| true |
c55b1868cd281af536500599d8bd0650ec6b0b2d | Ruby | benrodenhaeuser/exercises | /small_problems/04_Easy_04/10_integer_to_string.rb | UTF-8 | 479 | 3.796875 | 4 | [] | no_license | def to_string(positive_integer)
number = positive_integer
str_array = []
loop do
str_array.unshift(number % 10)
number /= 10
break if number == 0
end
str_array.join
end
def signed_integer_to_string(integer)
if integer > 0
'+' + to_string(integer)
elsif integer < 0
'-' + to_string(integer.abs)
else
'0'
end
end
p signed_integer_to_string(4321) == '+4321'
p signed_integer_to_string(-123) == '-123'
p signed_integer_to_string(0) == '0'
| true |
f7b57043f13e6da49cbce85b8ae720fcc9f4aac0 | Ruby | ignacy/invaders | /lib/invaders/potential_match.rb | UTF-8 | 1,710 | 3.078125 | 3 | [] | no_license | require 'forwardable'
module Invaders
class PotentialMatch
THRESHOLD = 0.8
extend Forwardable
def_delegators :@lower_right_point, :x, :y
def_delegators :@invader, :width, :height
def initialize(radar_reading:, invader:, lower_right_point:, match_strategy: MatchStrategies::Lexical, threshold: THRESHOLD)
@radar_reading = radar_reading
@invader = invader
@lower_right_point = lower_right_point
@match_strategy = match_strategy
@threshold = threshold
end
attr_reader :invader
# A potential match is valid when it is contained in the RadarReading.
# For example if the Radar gives the following reading:
# ~~~
# abcd
# abcd
# abcd
# ~~
#
# Potential match x = 1, y = 1, width = 2, height = 2 would be valid and represent:
# ~~
# ab
# ab
# ~~
#
# Potential match x = 1, y = 1, widht = 2, height = 3 would not be valid
def valid?
return false if x >= radar_reading.width || x.negative?
return false if y >= radar_reading.height || y.negative?
(x + 1) - width >= 0 && (y + 1) - height >= 0
end
def good_enough?
return false unless valid?
match_level >= threshold
end
# Returns the view of the RadarReading rows as narrowed by this potential match
def rows
@rows ||= radar_reading.rows[(y + 1 - height)..y].map do |row|
row[(x + 1 - width)..x]
end
end
def match_level
@match_level ||= match_strategy.new(invader.rows_string, rows_string).compute
end
private
def rows_string
@rows_string ||= rows.join
end
attr_reader :radar_reading, :match_strategy, :threshold
end
end
| true |
93cc6a596645c516aabfce12885a9f56ab36e5b7 | Ruby | lucatironi/aoc2017 | /day15.rb | UTF-8 | 2,225 | 3.28125 | 3 | [] | no_license | require "minitest/autorun"
CONSTANT = 2147483647
class Generator
attr_reader :value, :factor, :div
def initialize(value, factor, div = 1)
@value = value
@factor = factor
@div = div
end
def next_value
loop do
@value = (@value * @factor) % CONSTANT
break if @value % @div < 1
end
end
end
class TestDay15 < Minitest::Test
def test_init
a = Generator.new(65, 16807)
assert_equal 65, a.value
assert_equal 16807, a.factor
assert_equal 1, a.div
end
def test_part1
a = Generator.new(65, 16807)
b = Generator.new(8921, 48271)
a.next_value
assert_equal 1092455, a.value
a.next_value
assert_equal 1181022009, a.value
a.next_value
assert_equal 245556042, a.value
a.next_value
assert_equal 1744312007, a.value
a.next_value
assert_equal 1352636452, a.value
b.next_value
assert_equal 430625591, b.value
b.next_value
assert_equal 1233683848, b.value
b.next_value
assert_equal 1431495498, b.value
b.next_value
assert_equal 137874439, b.value
b.next_value
assert_equal 285222916, b.value
end
def test_part2
a = Generator.new(65, 16807, 4)
b = Generator.new(8921, 48271, 8)
a.next_value
assert_equal 1352636452, a.value
a.next_value
assert_equal 1992081072, a.value
a.next_value
assert_equal 530830436, a.value
a.next_value
assert_equal 1980017072, a.value
a.next_value
assert_equal 740335192, a.value
b.next_value
assert_equal 1233683848, b.value
b.next_value
assert_equal 862516352, b.value
b.next_value
assert_equal 1159784568, b.value
b.next_value
assert_equal 1616057672, b.value
b.next_value
assert_equal 412269392, b.value
end
end
# Part 1
a = Generator.new(699, 16807)
b = Generator.new(124, 48271)
c = 65535
judge_count = 0
40_000_000.times do
a.next_value
b.next_value
judge_count += 1 if 0 == (a.value & c) ^ (b.value & c)
end
p judge_count
# Part 2
a = Generator.new(699, 16807, 4)
b = Generator.new(124, 48271, 8)
c = 65535
judge_count = 0
5_000_000.times do
a.next_value
b.next_value
judge_count += 1 if 0 == (a.value & c) ^ (b.value & c)
end
p judge_count
| true |
3f1f433aff7ca78b2c758649062d5dca158be609 | Ruby | Rahul-Krishnan/challenges | /fizz-buzz/lib/fizz_buzz.rb | UTF-8 | 178 | 3.671875 | 4 | [] | no_license | # YOUR CODE HERE
(1..100).each do |n|
if n%3 == 0 && n%5 == 0
puts "Fizzbuzz"
elsif n%3 == 0
puts "Fizz"
elsif n%5 == 0
puts "Buzz"
else
puts n
end
end
| true |
32a3030b51d671ec2b7e0ba89a20faae0c9fd99d | Ruby | tekpub/rack | /model/haiku.rb | UTF-8 | 929 | 2.90625 | 3 | [] | no_license | class Haiku
def initialize
@poems = [
"An old silent pond...
A frog jumps into the pond,
splash! Silence again.",
"Sick and feverish
Glimpse of cherry blossoms
Still shivering",
"Without flowing wine
How to enjoy lovely
Cherry blossoms",
"The first soft snow!
Enough to bend the leaves
Of the jonquil low",
"In the cicada's cry
No sign can foretell
How soon it must die",
"In my old home
which I forsook, the cherries
are in bloom",
"A giant firefly:
that way, this way, that way, this -
and it passes by",
"My grumbling wife -
if only she were here!
This moon tonight...",
"From a bathing tub
I throw water into the lake -
slight muddiness appears"
]
end
def random
index = rand(8)+1
@poems[index].gsub("\n","<br/>")
end
end | true |
47f5814c67b09bd6fc3133eab924a3b2c650e1dc | Ruby | petekinnecom/check_up | /integration_test.rb | UTF-8 | 2,187 | 2.5625 | 3 | [] | no_license | require "minitest/autorun"
require "open3"
require "securerandom"
class IntegrationTest < Minitest::Test
def setup
raise "Compile the binary first" unless File.exist?("./_build/check_up_test")
end
def test_integration__success
Tempfile.open do |file|
file.puts <<~YAML
services:
- name: service_1
command: exit 0
- name: service_2
command: exit 0
YAML
file.flush
out, status = Open3.capture2e("./_build/check_up_test --file #{file.path}")
assert status == 0
assert out.empty?, "no news is good news"
end
end
def test_integration__fail
Tempfile.open do |file|
file.puts <<~YAML
services:
- name: service_1
command: exit 0
- name: service_2
command: exit 1
YAML
file.flush
out, status = Open3.capture2e("./_build/check_up_test --file #{file.path}")
assert status != 0
assert out.match(/service_2 | down/)
end
end
def test_integration__wait
random_file = File.join("/tmp", SecureRandom.uuid)
Tempfile.open do |file|
file.puts <<~YAML
services:
- name: service_1
command: test -f #{random_file}
interval: 1
YAML
file.flush
# ensure our preconditions
out, status = Open3.capture2e("./_build/check_up_test --file #{file.path}")
refute status == 0
assert out.match(/service_1 | down/)
thread = Thread.new {
out, status = Open3.capture2e("./_build/check_up_test --file #{file.path} --wait --verbose")
}
sleep 1 # Magic number to let the executable spin up
File.open(random_file, "w") {}
thread.join
assert status == 0
expected_lines = [
"service_1 | trying",
"service_1 | test -f #{random_file}",
"service_1 | exit status 1",
"service_1 | down",
"retrying check up",
"service_1 | trying",
"service_1 | test -f #{random_file}",
"service_1 | up",
].each do |line|
assert out.match(line), "expected to find #{line} in:\n#{out}"
end
end
end
end
| true |
a298a17ca10bccef7fe58b906eb70265603fe481 | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/ruby/bob/d16fdc044a0e4428812eac8fa34452c6.rb | UTF-8 | 477 | 3.59375 | 4 | [] | no_license | require 'active_support'
class Bob
def hey message
return "Fine. Be that way!" if empty?(message)
return "Woah, chill out!" if yell?(message)
return "Sure." if question?(message)
"Whatever."
end
private
def empty? message
message.gsub(/\s/, '').empty?
end
def yell? message
meaning = message.gsub(/[^[:alpha:]]/, '')
!empty?(meaning) and meaning.upcase == meaning
end
def question? message
message.end_with? "?"
end
end
| true |
5eaef8dbd1ad96432384b6572e639ce4669ff586 | Ruby | alexshev91/ruby_challenges_lab | /calculator.rb | UTF-8 | 1,326 | 4.8125 | 5 | [] | no_license | # # ### Challenge 2 - Calculator
# # Create a simple calculator that first asks the user what method they would like to use (addition, subtraction, multiplication, division)
# and then asks the user for two numbers, returning the result of the method with the two numbers. Here is a sample prompt:
# # ```
# # What calculation would you like to do? (add, sub, mult, div)
# # add
# # What is number 1?
# # 3
# # What is number 2?
# # 6
# # Your result is 9
# # ```
puts "Please enter the action you'd like to perform (add, subtr, mult, div)"
action = gets.chomp
if action == "add"
puts "please enter first summand"
x = gets.chomp.to_i
puts "please enter second summand"
y = gets.chomp.to_i
sum = x+y
puts "Your result is #{sum}"
elsif action == "subtr"
puts "please enter the number you want to subtract from"
x = gets.chomp.to_i
puts "please enter the number you want to subtract"
y = gets.chomp.to_i
sub = x-y
puts "Your result is #{sub}"
elsif action == "mult"
puts "please enter the first mult"
x = gets.chomp.to_f
puts "please enter the second mult"
y = gets.chomp.to_f
prod = x*y
puts "Your result is #{prod}"
elsif action == "div"
puts "please enter the dividend"
x = gets.chomp.to_f
puts "please enter the divisor"
y = gets.chomp.to_f
divson = x/y
puts "Your result is #{divson}"
end
| true |
b52c40a429e064b34d0d0c55de78b547b4673669 | Ruby | rapid7/ruby_smb | /examples/enum_registry_values.rb | UTF-8 | 1,089 | 2.625 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"Ruby"
] | permissive | #!/usr/bin/ruby
# This example script is used for testing values enumeration of a specific Winreg registry.
# It will attempt to connect to a host and enumerate values of a specified registry key.
# Example usage: ruby enum_registry_values.rb 192.168.172.138 msfadmin msfadmin HKLM\\My\\Key
# This will try to connect to \\192.168.172.138 with the msfadmin:msfadmin credentialas and enumerate HKLM\\My\\Key values.
require 'bundler/setup'
require 'ruby_smb'
address = ARGV[0]
username = ARGV[1]
password = ARGV[2]
registry_key = ARGV[3]
smb_versions = ARGV[4]&.split(',') || ['1','2','3']
sock = TCPSocket.new address, 445
dispatcher = RubySMB::Dispatcher::Socket.new(sock, read_timeout: 60)
client = RubySMB::Client.new(dispatcher, smb1: smb_versions.include?('1'), smb2: smb_versions.include?('2'), smb3: smb_versions.include?('3'), username: username, password: password)
protocol = client.negotiate
status = client.authenticate
puts "#{protocol} : #{status}"
enum_result = client.enum_registry_values(address, registry_key)
puts enum_result
client.disconnect!
| true |
847b032d02faf2d8836678f41b48f12c7e986c13 | Ruby | SleepingInsomniac/minecraft-scripts | /ChangeLog.rb | UTF-8 | 1,523 | 2.921875 | 3 | [] | no_license | #!/usr/bin/env ruby
require 'yaml'
# ===================================================
# = Track the changes made to a directory structure =
# ===================================================
# Written by Alex Clink, 2014-07-10
class ChangeLog
def initialize(directory)
@directory = File.expand_path directory
end
attr_reader :directory
def read_files(dir = @directory, paths = [])
paths.push dir
dir = paths.join("/")
unless File.directory?(dir)
puts "#{dir} Is not a directory!"
return false
end
file_hash = Hash.new
Dir.foreach dir do |file|
next if file[0] == "."
if File.directory?(File.join(dir, file))
file_hash[File.join(dir, file)] = read_files(file, paths)
paths.pop
else
file_hash[File.join(dir,file)] = File.mtime(File.join(dir,file)).to_s
end
end
file_hash
end
def save_state
files = read_files
save = File.open("#{@directory}.yaml", "w")
save.write(files.to_yaml)
save.close
files
end
def diff
begin
last_check = YAML.load_file("#{@directory}.yaml")
rescue
return save_state
end
def check(thing1, thing2, level = 0)
diffs = []
thing1.zip(thing2).each do |one, two|
if (one[1].class == Hash)
diffs += check one[1], two[1], level+1
else
diffs.push one[0] if one[1] != two[1]
end
end
diffs
end
check last_check, read_files
end
end | true |
7e060c72c10791318753337664c495c33f5dbc42 | Ruby | Yuni-Q/blog | /TIL/Ruby/Ruby_opentutorials/Logical/logical_operation1.rb | UTF-8 | 352 | 3.640625 | 4 | [
"MIT"
] | permissive | #if ì€ì²©
puts("ììŽë륌 ì
ë ¥íŽì£Œìžì")
input_id = gets.chomp()
puts("ë¹ë°ë²ížë¥Œ ì
ë ¥íŽì£Œìžì")
input_pwd = gets.chomp()
real_id = "egoing"
real_pwd = "11"
if real_id == input_id
if real_pwd == input_pwd
puts("Hello!")
else
puts("ì못ë ë¹ë°ë²ížì
ëë€")
end
else
puts("ì못ë ììŽëì
ëë€")
end
| true |
b75b43eb59056747b497b7384e0e97213cdcd121 | Ruby | radiohead/knn | /lib/knn/knn.rb | UTF-8 | 886 | 3.515625 | 4 | [
"MIT"
] | permissive | module KNN
class KNN
attr_reader :data, :unknown_index, :distance
def initialize(data, unknown_index, distance = :euclidean)
fail 'Only euclidean distance is currently implemented!' if distance != :euclidean
@data = data
@distance = distance
@unknown_index = unknown_index
end
def find_nearest(pivot, neighbors_count)
data_with_distances = data.map do |data_point|
[euclidean_distance(data_point, pivot), data_point]
end
data_with_distances.sort! do |left, right|
left.first <=> right.first
end
data_with_distances[0...neighbors_count]
end
private
def euclidean_distance(left = [], right = [])
sum = 0
left.each_with_index do |left_v, idx|
next if idx == unknown_index
sum += (left_v - right[idx])**2
end
Math.sqrt(sum)
end
end
end
| true |
96da5c6a22aa9d3d376e00d711f7b2b445bc4be4 | Ruby | Rdrandle/ttt-3-display_board-example-q-000 | /lib/display_board.rb | UTF-8 | 281 | 3.515625 | 4 | [] | no_license | # Define a method display_board that prints a 3x3 Tic Tac Toe Board
board =[" "," "," "," "," "," "," "," "," "]
def display_board(name)
puts" | |
-----------
| |
-----------
| |
#{name[x]}"
end
display_board(board)
| true |
160fafd9e194c62f98c87e40232731e8802c8cec | Ruby | DigitalKnight0/recursion | /merge-sort.rb | UTF-8 | 578 | 3.59375 | 4 | [] | no_license | def merge_sort(arr)
return arr if arr.length < 2
mid = arr.length/2
merge(merge_sort(arr[0..(mid-1)]),merge_sort(arr[mid..arr.length]))
end
def merge(left,right)
sorted = []
count = 0
until (left.empty? && right.empty?)
if left.empty?
sorted << right.shift
elsif right.empty?
sorted << left.shift
elsif left[0] >= right[0]
sorted[count] = right.shift
elsif right[0] >= left[0]
sorted[count] = left.shift
end
count += 1
end
return sorted
end
p merge_sort([1,4,2,3,6,7,5,9,1]) | true |
709690e78f050cc3d7a37fb2fdca95c1c32b523b | Ruby | JisuKim82/cake | /spec/2-flatten_method_spec.rb | UTF-8 | 347 | 3.078125 | 3 | [] | no_license | require_relative 'spec_helper'
require_relative '../2-flatten_method'
describe 'Flatten Method' do
it 'returns itself if array passed in is a single dimensional array' do
expect(flatten_method([1,2,3])).to eq [1,2,3]
end
it 'returns [1,2,3] when [1,[2,3]] is passed in' do
expect(flatten_method([1,[2,3]])).to eq [1,2,3]
end
end | true |
7e9f0e5addcb1a18d421549e939477e3d7ee73be | Ruby | AgileTrossDev/job_manager | /lib/jm/job.rb | UTF-8 | 3,143 | 3.203125 | 3 | [] | no_license | # Job - Executes an action and optional post-processing/exception handling. It's intended purpose is to be executed by a thread manager.
# The creator of jobs should be conservative when deciding the time-out period for the job. A post processing/error handling
# call-back can be defined. This counts against the jobs total execution time. If a time-out occurs then the handler (if defined)
# will be called with the Timeout::Error exception. If an exception slips out of the execute operation, then a owner of the job
# may call the handler directly.
require 'timeout'
require 'jm/logger'
module JM
class Job
attr_accessor :name, :state, :exception, :time_out, :input, :logger
def initialize action, input =nil, handler = nil, name = "undefined_job", time_out=10, logger = JM::Logger.new
@action = action # Sets the action to be performed by the job
@input = input # Input into the Action being executed.
@handler = handler # Optional lambda call back from Job for any post-procesing/job handling. IMPORTANT- This work counts against the execution time-out.
@name = name # Name give to the job
@time_out = time_out # Indicates when to assume execution has stalled
@state = "pending" # Current State of the Job
@exception = nil # Exception (if any) encoutnered during execution
@logger = logger # Sets logger to be used by the Job Manager. # TODO: Make sure that it responds to RLOG operations
logger.info "Job Created: #{name}"
logger.info "Handler object #{@handler.class} not supported." if not @handler.nil? and not @handler.respond_to?("call")
end
# Executes the job and calls the handler if it is turned on.
def execute input =nil
Timeout::timeout(@time_out) {
@state = "started"
@input = input unless input.nil?
handler_input =nil
begin
@state = @action.call(@input)
logger.info "Job #{@name} action complete."
handler_input = @state
rescue => e
logger.info "Job #{@name} encountered exception during execution: #{e.message}"
@exception = e
@state= "exception"
handler_input= e
end
# Call handler if turned on
call_handler handler_input
}
@state
rescue Timeout::Error => e
call_handler(e)
ensure
# Return the state of the job
@state
end
# Calls Handler and updates state if error
def call_handler(handler_input=nil)
if not @handler.nil? and @handler.respond_to?("call")
@handler.call (handler_input)
end
true
rescue => e
logger.info "Job #{@name} encountered exception raised from handler call: #{e.message}"
@exception = e unless not @exception.nil? # Don't overwrite previous exception
@state="handler_exception"
ensure
@state
end
end # Class
end # Module | true |
779ce44642bd7fada211d3f981bf7f754eaeac70 | Ruby | vizjerai/google-checkout | /examples/google_notifications_controller.rb | UTF-8 | 4,983 | 2.671875 | 3 | [
"MIT"
] | permissive | ##
# Skeleton for handing Level 2 notifications from GoogleCheckout with Rails.
#
# You'll need to write the individual handlers. SSL is required.
#
# SAMPLE ONLY! Modify for your own use. Extra error handling may be needed.
class GoogleNotificationsController < ApplicationController
before_filter :verify_access
after_filter :log_google_notification
##
# Google calls this with notifications.
def create
@notification = GoogleCheckout::Notification.parse(request.raw_post)
case @notification
when GoogleCheckout::NewOrderNotification
handle_new_order_notification(@notification)
when GoogleCheckout::OrderStateChangeNotification
handle_order_state_change_notification(@notification)
when GoogleCheckout::RiskInformationNotification
handle_risk_information_notification(@notification)
when GoogleCheckout::ChargeAmountNotification
handle_charge_amount_notification(@notification)
when GoogleCheckout::AuthorizationAmountNotification
handle_authorization_amount_notification(@notification)
when GoogleCheckout::ChargebackAmountNotification
handle_chargeback_amount_notification(@notification)
when GoogleCheckout::RefundAmountNotification
handle_refund_amount_notification(@notification)
end
render :xml => @notification.acknowledgment_xml
end
private
##
# Use basic authentication in my realm to get a user object.
# Since this is a security filter - return false if the user is not authenticated.
def verify_access
return false unless (request.ssl? || (RAILS_ENV == 'development') || (RAILS_ENV == 'test'))
authenticate_or_request_with_http_basic("PeepCode") do |merchant_id, merchant_key|
(merchant_id == GOOGLE_ID) && (merchant_key == GOOGLE_KEY)
end
end
##
#
def log_google_notification
# TODO Write to your log or to a DB table
end
##
#
def handle_new_order_notification(notification)
logger.info "Got NewOrderNotification"
# NOTE You should have passed your own order number to Google when
# making the initial order. Subsequent notifications will use
# Google's order number instead.
@order = Order.find_by_order_number(notification.my_order_number)
if @order
# NOTE You may want to check the amount being charged vs. the amount
# you expected the user to pay.
@order.google_order_number = notification.google_order_number
@order.email = notification.email
# Fee is 20 cents plus 2% of total.
@order.fee_cents = (20 + (notification.order_total.cents * 0.02)).round
@order.gross_cents = notification.order_total.cents
@order.net_cents = @order.gross_cents - @order.fee_cents
# NOTE Also of interest is notification.email_allowed, a boolean
@order.save
@order.new_order!
end
end
##
#
def handle_order_state_change_notification(notification)
@order = Order.find_for_notification(notification)
@order.update_attribute(:google_state, notification.state)
case notification.state
when "REVIEWING" # Initial state of orders. Rarely seen by client.
when "CHARGEABLE" # You can now charge the customer for the order.
@order.chargeable!
when "CHARGING" # Google is charging the customer.
@order.charging!
when "CHARGED" # You have charged the customer.
@order.charged!
when "PAYMENT_DECLINED" # Google was unable to charge the client
@order.denied!
when "CANCELLED" # Order was cancelled by the merchant
@order.denied!
@order.update_attribute(:payment_note, notification.reason) rescue nil
when "CANCELLED_BY_GOOGLE" # Order was cancelled by Google
@order.denied!
# notification.reason
end
end
##
#
def handle_risk_information_notification(notification)
logger.info "Got RiskInformationNotification"
@order = Order.find_for_notification(notification)
@order.risk!
# TODO You need to ping Google after this to trigger the next state.
# Do this in the model, but for reference, here's the basic code.
if @order.google_state == "CHARGEABLE"
charge_order_command = GoogleCheckout::ChargeOrder.new(GOOGLE_ID, GOOGLE_KEY, @order.google_order_number)
# To string, to float in order to get a float representation of the money
charge_order_command.amount = total_price.to_s.to_f
# Will throw error on failure
notification = charge_order_command.post
else
logger.error("Order was not in CHARGEABLE state")
end
end
##
#
def handle_charge_amount_notification(notification)
@order = Order.find_for_notification(notification)
@order.charge!
end
##
#
def handle_refund_amount_notification(notification)
# NOTE Notification includes amount refunded.
@order = Order.find_for_notification(notification)
@order.refund!
end
end
| true |
9f1fd20ce27d4831b483d0f95bc9f2e3b4523bbc | Ruby | KaiKaspar/intro-to-simple-array-manipulations-london-web-career-021819 | /lib/intro_to_simple_array_manipulations.rb | UTF-8 | 1,681 | 3.75 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def using_push(countries_in_western_africa, element)
# ads element to back of array
countries_in_western_africa.push("Niger")
end
def using_unshift(neighborhoods_in_northwest_brooklyn, element)
# ads element to front of array
neighborhoods_in_northwest_brooklyn.unshift("Brooklyn Heights")
end
def using_pop(great_hits_of_the_nineties)
# removes last elements and return it
great_hits_of_the_nineties.pop
end
def pop_with_args(chars_in_game_of_thrones)
# removes last 'x' amount of elements and returns them
chars_arya_killed = chars_in_game_of_thrones.pop(2)
end
def using_shift(my_favorite_cities)
# removes first element and returs it
my_favorite_cities.shift
end
def shift_with_args(ice_cream_brands)
# removes and returs the first 'x' amount of elements
ice_cream_brands.shift(2)
end
def using_concat(my_favorite_things, more_favs)
# combines arrays
my_favorite_things.concat(more_favs)
end
def using_insert(list_of_esoteric_programming_languages, another_esoteric_language)
# inserts specific element at specific location
list_of_esoteric_programming_languages.insert(4, another_esoteric_language)
end
def using_uniq(captain_planet_and_the_planeteers)
# removes duplicates
captain_planet_and_the_planeteers.uniq
end
def using_flatten(private_colleges_in_newyork)
# takes in combined arrays and returns as one string
private_colleges_in_newyork.flatten
end
def using_delete(instructors, element)
# removes specific element
instructors.delete("Steven")
end
def using_delete_at(famous_robots, number)
# removes specific location
famous_robots.delete_at(2)
end
| true |
afbe9492f903f9f634f797387a0a72b76260fd85 | Ruby | Aurabelle/boost-challenge | /atbash.rb | UTF-8 | 891 | 3.609375 | 4 | [] | no_license | class Atbash
CIPHER = 'oephjizkxdawubnytvfglqsrcm'
ENCRYPTED_TEXT = 'knlfgnb, sj koqj o yvnewju'
def initialize
Decryptor.new(cipher: CIPHER, encrypted_text: ENCRYPTED_TEXT ).run_decryption
end
end
class Decryptor
ALPHABET_CONSTANT = 'abcdefghijklmnopqrstuvwxyz'
attr_reader :original_text
def initialize(cipher:, encrypted_text:)
@cipher = cipher
@encrypted_text = encrypted_text
@original_text = ''
end
def run_decryption
decoder = Hash[@cipher.chars.zip(ALPHABET_CONSTANT.chars)]
remove_punctuation
@original_text = decrypt(decoder).join
print_solution
end
def decrypt(decoder)
@encrypted_text.chars.map{ |char| decoder[char] }
end
def remove_punctuation
@encrypted_text.downcase.gsub(/[^\w\s\d]/, '')
end
def print_solution
puts "Solution: #{@original_text}"
end
end
Atbash.new
| true |
0f922d33bd11be76aee9918c5794043acb543e31 | Ruby | nathanworden/RB101-Programming-Foundations | /RB101-RB109_small_problems/01.easy_1/08.array_average.rb | UTF-8 | 2,456 | 5 | 5 | [] | no_license | # Understand the Problem
# Write a method with one argument
# input: an array containing integers
# output: the average of all numbers in the array
# The array will never be empty and the numbers will always be positive integers
# Examples / Test Cases:
# puts average([47, 78, 9876, 2, 3, 5, 7]) == 1431
# puts average([1, 5, 87, 45, 8, 8]) == 25
# puts average([9, 47, 23, 95, 16, 52]) == 40
# Data structure
# Arrays
# Algorithm
# Divide the sum of all the elements in the array by the length of the array.
# MY ANSWER
# def average(array)
# array.sum / array.length
# end
# puts average([47, 78, 9876, 2, 3, 5, 7]) == 1431
# puts average([1, 5, 87, 45, 8, 8]) == 25
# puts average([9, 47, 23, 95, 16, 52]) == 40
# puts average([1, 2, 3]) == 2
# BOOK ANSWER
# Solution
# def average(numbers)
# sum = numbers.reduce { |sum, number| sum + number }
# sum / numbers.count
# end
# Discussion
# Two things need to be done to find the average. First, add every number together. Second, divide the sum by the number of elements. We accomplish the first part by using Enumerable#reduce(also known as #inject), which combines all elements of the given array by applying a binary operation. This operation is specified by a block or symbol. We used a block in our solution, but we could have just as easily used a symbol, like this:
# numbers.reduce(:+)
# Once we have the sum, all that's left is to divide it by the number of elements. To do that, we use #count to count the number of elements in numbers. Then, we divide sum by the number of elements and return the quotient.
# Further Exploration
# Currently, the return value of average is an Integer. When dividing numbers, sometimes the quotient isn't a whole number, therefore, it might make more sense to return a Float. Can you change the return value of average from an Integer to a Float?
# def average(array)
# array.sum.to_f / array.length
# end
# More Exploration with .reduce
# def average(array)
# array.reduce(:+) / array.size
# end
# puts average([1, 5, 87, 45, 8, 8]) == 25
# puts average([9, 47, 23, 95, 16, 52]) == 40
# ----------------------------------------------------------------
# More Exploration with .reduce
def average(numbers)
output = numbers.reduce do |accumulator, num|
accumulator + num
end
output / numbers.size
end
puts average([1, 5, 87, 45, 8, 8]) == 25
puts average([9, 47, 23, 95, 16, 52]) == 40
| true |
694d23d8106c6927ac7d66b56bba78abd3c40fed | Ruby | athio92/launchschool | /courses/100/L1T13/09_More_Stuff/exercise1.rb | UTF-8 | 186 | 2.75 | 3 | [] | no_license | def contains?(str)
/lab/.match(str) ? (puts str) : (puts "Not found")
end
["laboratory", "experiment", "Pans Labyrinth", "elaborate", "polar bear"].each do |str|
contains?(str)
end
| true |
990982e3829cba2bd4aaa7c3d845f3e2bf76642f | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/ruby/robot-name/41c5fd9c919648479e910da85b1ffa4e.rb | UTF-8 | 781 | 3.46875 | 3 | [] | no_license | require 'set'
class Robot
def name
@name ||= UniqueNameGenerator.generate
end
def reset
@name = nil
end
end
class UniqueNameGenerator
DIGITS = ('0'..'9').to_a
LETTERS = ("A".."Z").to_a
def self.generate
name = generate_name
name = generate_name while generated?(name)
add(name) && name
end
def self.generated_names
@generated_names ||= Set.new
end
private
def self.generated?(name)
generated_names.include?(name)
end
def self.add(name)
generated_names.add(name)
end
def self.generate_name
[rand_letters, rand_digits].flatten.join
end
def self.rand_letters
[LETTERS.sample(1), LETTERS.sample(1)]
end
def self.rand_digits
[DIGITS.sample(1), DIGITS.sample(1), DIGITS.sample(1)]
end
end
| true |
a80585cae275b3d46e44f874a9c706b484c9e3b2 | Ruby | SeanWelshBrown/ruby-oo-relationships-practice-art-gallery-exercise-dumbo-web-120919 | /app/models/painting.rb | UTF-8 | 513 | 3.359375 | 3 | [] | no_license | class Painting
attr_reader :artist, :title
attr_accessor :price, :gallery
@@all = []
# INITIALIZATION #
def initialize(artist, title, price, gallery) # WORKS #
@artist = artist
@title = title
@price = price
@gallery = gallery
@@all << self
end
# CLASS METHODS #
def self.all # WORKS #
@@all
end
def self.total_price # WORKS #
all_prices = @@all.collect { |painting| painting.price }
total = all_prices.inject { |sum, n| sum += n}
end
# END #
end
| true |
676fd3f5526b85e507b7df3baaeadf79ae92090c | Ruby | cbeer/solr_wrapper | /lib/solr_wrapper/downloader.rb | UTF-8 | 888 | 2.671875 | 3 | [
"MIT"
] | permissive | require 'ruby-progressbar'
require 'http'
module SolrWrapper
class Downloader
def self.fetch_with_progressbar(url, output)
pbar = SafeProgressBar.new(title: File.basename(url), total: nil, format: '%t: |%B| %p%% (%e )')
response = HTTP.follow.get(url)
pbar.total = response.headers['content-length'].to_i
File.open(output, 'wb') do |f|
response.body.each do |chunk|
f.write(chunk)
pbar.progress += chunk.length
end
nil
end
rescue HTTP::Error => e
raise SolrWrapperError, "Unable to download solr from #{url}\n#{e}"
end
class SafeProgressBar < ProgressBar::Base
def progress=(new_progress)
self.total = new_progress if total.to_i <= new_progress
super
end
def total=(new_total)
super if new_total && new_total >= 0
end
end
end
end
| true |
7f82c8e24e591c4851ffd69f2bbe1f80842c276e | Ruby | tobymao/mistery | /app/views/plays/result.rb | UTF-8 | 759 | 2.515625 | 3 | [] | no_license | class Views::Plays::Result < Views::Layouts::Page
needs :play
def main
h1 "Finished Game"
div 'Solution:' do
text simple_format play.scenario.solution, class: 'mainText'
end
div "Score #{play.points}"
guesses = Guess
.includes({question: {answers: [:location, :suspect]}}, :answer, :location, :suspect)
.where(play: play)
guesses.each do |guess|
br
div class: 'mainText' do
text "Question: #{guess.question.text}"
br
text "Your answer: #{guess.guess_string}"
br
if guess.points
text "You earned #{guess.question.points} points"
else
text "Correct answer: #{guess.question.answer_string}"
end
end
end
end
end
| true |
678fbec60d4fe97793fd6890be5f277ef0697a09 | Ruby | yoshixmk/yomi | /md5-verifier/main.rb | UTF-8 | 261 | 2.53125 | 3 | [] | no_license | require "./zpai"
require "./dpai"
require "./npai"
require "./pg"
all_pai = npai() + zpai() + dpai()
conn = open()
i = 0
while(1) do
shuffled = 100000.times.map{|i| all_pai.shuffle.take(83).join()}
insert(shuffled, conn)
i += 1
p i
end
close(conn)
| true |
0f3a2cbdd940f9e7c4caaaa4e2d4ba185bb26256 | Ruby | karask/bitstampbot | /bot.rb | UTF-8 | 3,063 | 2.890625 | 3 | [] | no_license | require "bitstamp"
require "logger"
logfile = "logbot.log"
#logfile = Time.now.strftime("log-%Y%m%d-%H%M%S") + ".log"
File.delete(logfile) if File.exist?(logfile)
$LOG = Logger.new(logfile);
Bitstamp.setup do |config|
config.key = ENV['BITSTAMP_KEY']
config.secret = ENV['BITSTAMP_SECRET']
config.client_id = ENV['BITSTAMP_CLIENT_ID']
end
buy_max_price = 804.0
buy_max_amount = 0.02
profitPercentage = 0.50
commissionPercentage = 0.50
tickEverySecs = 5
retries = 50
# check if last price is below buy_max_price every 60 secs
attempt = 0
begin
begin
sleep(tickEverySecs)
tick = Bitstamp.ticker
puts "tick #{tick.last} -- will buy #{buy_max_amount} BTC at <= #{buy_max_price} dollars"
end until tick.last.to_f <= buy_max_price
rescue StandardError => se
# propably a network error occurred
$LOG.info "Exception raised: #{se}"
$LOG.info "Didn't place buy order of #{buy_max_amount} BTC at <= #{buy_max_price} dollars with attempt ##{attempt + 1}"
attempt += 1
sleep 0.1
retry if attempt < retries
raise se
end
# buy buy_max bitcoins (assumes you have the cash for now)
Bitstamp.orders.buy(amount: buy_max_amount, price: tick.last)
$LOG.info "Placed Order: Buy #{buy_max_amount} at #{tick.last}"
puts "Placed Order: Buy #{buy_max_amount} at #{tick.last}"
# price to sell is commissionPercentage x2 (buy/sell) plus profitInDollars
# note: we calculate commission at the higher sell price so it is
# slightly less commission (however, the commission is only base at
# buy price!)
percentageMultiplier = 1 + commissionPercentage*2.0/100.0 + profitPercentage/100
sellPrice = tick.last.to_f * percentageMultiplier
$LOG.info "Will try to sell at #{sellPrice} for a #{profitPercentage}% percentage profit"
# check if last price is above calculated sellPrice every 60 secs
attempt = 0
begin
begin
sleep(tickEverySecs)
tick = Bitstamp.ticker
puts "tick #{tick.last} -- will sell #{buy_max_amount} BTC for at least #{sellPrice} dollars"
end until tick.last.to_f >= sellPrice
rescue StandardError => se
# propably a network error occurred
$LOG.info "Exception raised: #{se}"
$LOG.info "Didn't place sell order of #{buy_max_amount} BTC at #{sellPrice} dollars with attempt ##{attempt+1}"
attempt += 1
sleep 0.1
retry if attempt < retries
raise se
end
# sell buy_max bitcoins at sellPrice
Bitstamp.orders.sell(amount: buy_max_amount, price: tick.last)
$LOG.info "Placed Order: Sell #{buy_max_amount} at #{tick.last}"
puts "Placed Order: Sell #{buy_max_amount} at #{tick.last}"
#puts tick.volume
#puts tick.high
#puts tick.low
#if tick.high > tick.low
# puts "Bid " + tick.bid
# puts "Ask " + tick.ask
#end
#order = Bitstamp.orders.sell(amount: 0.01, price: 1111)
# get all orders
#orders = Bitstamp.orders.all
#puts orders.size
# get all transactions
#transx = Bitstamp.user_transactions.all
#
#orders.each do |o|
# puts o.id , o.datetime , o.type , o.price , o.amount
#end
#
#transx.each do |t|
# puts t.datetime , t.id , t.type , t.usd , t.btc , t.fee , t.order_id
#end
| true |
1b542d7a9af31296e9ef78b830a9aacadd49d203 | Ruby | KevinMcHugh/mustached-nemesis | /app/models/events/hit.rb | UTF-8 | 823 | 3.0625 | 3 | [] | no_license | module Hit
def hit!(hitter=nil)
@health -= 1
Event.new(event_listener, self, hitter)
if dead?
beer
if dead? #The beer *may* have brought you back to life.
PlayerKilledEvent.new(event_listener, self, hitter)
raise PlayerKilledException.new
end
end
end
class Event < ::Event
attr_reader :hitter, :health
def initialize(event_listener, player, hitter)
@player = player
@health = player.health
@hitter = hitter
super(event_listener)
end
def to_s
from = hitter ? hitter.class : DynamiteCard.killer
["#{player.class} hit by #{from}, at #{health}", "#{player.class} has dropped down to #{health} because of #{from}",
"#{player.class} is feelin' the pain at #{health}, thanks to #{from}"].sample
end
end
end
| true |
df1b4f30bb92cbe697e9635647d534c7756703ff | Ruby | jewel/clone-terminal-window | /clone-terminal-window | UTF-8 | 837 | 2.5625 | 3 | [] | no_license | #!/usr/bin/ruby
# Clone a gnome-terminal window. This will attempt to connect to the same
# directory, connect to the same remote host, and run sudo if necessary.
require 'shellwords'
def se arg
Shellwords.shellescape arg
end
title = `xdotool getactivewindow getwindowname`.chomp
title = ARGV.first if ARGV.first
case title
when /^(.*)@(.*): (.*)$/
user = $1
host = $2
dir = $3
when /^.* \((.*)\) - VIM$/
dir = $1
else
$stderr.puts "Invalid terminal title: #{title.inspect}"
system "gnome-terminal"
exit 1
end
dir = File.expand_path dir
command = %{cd #{se dir}; bash --login}
command = "bash -c #{se command}"
command = "sudo #{command}" if user == 'root'
if host != `hostname`.chomp
command = "ssh -t #{se host} #{se command}"
end
$stderr.puts "Launching #{command}"
system "gnome-terminal -e #{se command}"
| true |
11a5032d7d4f5689b3b010405a6354abd933b295 | Ruby | Rmole57/launch-school | /rb130/rb130-ruby_foundations_exercises/easy1/encrypted_pioneers.rb | UTF-8 | 5,765 | 3.796875 | 4 | [] | no_license | ENCRYPTED_PIONEERS = [
"Nqn Ybirynpr",
"Tenpr Ubccre",
"Nqryr Tbyqfgvar",
"Nyna Ghevat",
"Puneyrf Onoontr",
"Noqhyynu Zhunzznq ova Zhfn ny-Xujnevmzv",
"Wbua Ngnanfbss",
"Ybvf Unvog",
"Pynhqr Funaaba",
"Fgrir Wbof",
"Ovyy Tngrf",
"Gvz Orearef-Yrr",
"Fgrir Jbmavnx",
"Xbaenq Mhfr",
"Fve Nagbal Ubner",
"Zneiva Zvafxl",
"Lhxvuveb Zngfhzbgb",
"Unllvz Fybavzfxv",
"Tregehqr Oynapu"
].freeze
def rot13(encrypted_text)
encrypted_text.split('').map { |char| decipher_character(char) }.join
end
def decipher_character(char)
case char
when 'a'..'m', 'A'..'M' then (char.ord + 13).chr
when 'n'..'z', 'N'..'Z' then (char.ord - 13).chr
else
char
end
end
ENCRYPTED_PIONEERS.each { |pioneer| puts rot13(pioneer) }
# ALTERNATIVE SOLUTIONS:
# 1) - Launch School solution
# def rot13(encrypted_text)
# encrypted_text.each_char.reduce('') do |result, encrypted_char|
# result + decipher_character(encrypted_char)
# end
# end
# def decipher_character(encrypted_char)
# case encrypted_char
# when 'a'..'m', 'A'..'M' then (encrypted_char.ord + 13).chr
# when 'n'..'z', 'N'..'Z' then (encrypted_char.ord - 13).chr
# else encrypted_char
# end
# end
# ENCRYPTED_PIONEERS.each do |encrypted_name|
# puts rot13(encrypted_name)
# end
# 2) - An interesting solution from another student
# def rot13(string)
# string.tr("a-zA-Z", "n-za-mN-ZA-M")
# end
# 3) - A generic version using our own hard-coded alphabet arrays and their indices
# def rot13(encrypted_text)
# encrypted_text.split('').map { |char| decipher_character(char) }.join
# end
# def decipher_character(char)
# lower_case = ('a'..'z').to_a
# upper_case = ('A'..'Z').to_a
# if lower_case.include?(char)
# rotate_char(lower_case, char)
# elsif upper_case.include?(char)
# rotate_char(upper_case, char)
# else
# char
# end
# end
# def rotate_char(alpha_arr, char)
# if alpha_arr.index(char) < 13
# alpha_arr[alpha_arr.index(char) + 13]
# else
# alpha_arr[alpha_arr.index(char) - 13]
# end
# end
# FURTHER EXPLORATION:
# Running this program on data that uses the EBCDIC representation could
# drastically change and complicate our implementation (of course this
# depends on the problem requirements and the specific type of input).
# Currently, our algorithm is based off of using the ASCII ordinals of the characters.
# The methods we use are designed to work directly with the ASCII representation. However,
# EBCDIC and ASCII have very clear differences in how they encode the letters of the
# alphabet. For example, in ASCII, upper case letters come first, then lower case. In
# EBCDIC, it's the opposite. But what's even more complicated is that, unlike ASCII,
# the code points for the letters of the alphabet are not consecutive in EBCDIC. There
# are gaps in both the lower case alphabet and the upper case alphabet.
# So trying to apply an encryption key like Rot13 directly would be a bit difficult since
# you can't just increment or decrement the code point value by 13 places since not all
# of the letters are consecutive.
# All that being said, if the data given to us is the string representation of the
# EBCDIC encoding, we could just convert it to ASCII using String#encode, carry out
# our implementation as is, and then output the result:
# def rot13(encrypted_text)
# ascii_version = encrypted_text.encode("ASCII", "IBM037") # after some digging, found that "IBM037" is the encoding name for EBCDIC
# ascii_version.split('').map { |char| decipher_character(char) }.join
# end
# def decipher_character(char)
# case char
# when 'a'..'m', 'A'..'M' then (char.ord + 13).chr
# when 'n'..'z', 'N'..'Z' then (char.ord - 13).chr
# else
# char
# end
# end
# # Finding the EBCDIC string representation to use as a test case:
# orig_encrypt = "Lhxvuveb Zngfhzbgb"
# ebcdic_encrypt = orig_encrypt.encode("IBM037") # => "\xD3\x88\xA7\xA5\xA4\xA5\x85\x82\x40\xE9\x95\x87\x86\x88\xA9\x82\x87\x82"
# # Test case:
# p rot13("\xD3\x88\xA7\xA5\xA4\xA5\x85\x82\x40\xE9\x95\x87\x86\x88\xA9\x82\x87\x82") # => "Yukihiro Matsumoto"
# But again, this is assuming a very specific type of input. Notice the '\x' prefix
# in the EBCDIC encoding. In Ruby, this is a 'hex escape' sequence, which denotes
# a hex number/representation. So if the input did not include this sequence as a
# delimiter, you would have to replace/substitute whatever delimiter the input
# currently has (if any) with a hex escape sequence, in order to convert it into a
# proper string representation of EBCDIC encoding.
# Or maybe the input is just a straight hexadecimal string providing no escape
# characters. In this case, the String#unpack and Array#pack methods might be of use:
# def rot13(encrypted_text)
# ebcdic_string = [encrypted_text].pack('H*')
# ascii_version = ebcdic_string.encode("ASCII", "IBM037") # after some digging, found that "IBM037" is the encoding name for EBCDIC
# ascii_version.split('').map { |char| decipher_character(char) }.join
# end
# def decipher_character(char)
# case char
# when 'a'..'m', 'A'..'M' then (char.ord + 13).chr
# when 'n'..'z', 'N'..'Z' then (char.ord - 13).chr
# else
# char
# end
# end
# # Finding the EBCDIC string representation to use as a test case:
# orig_encrypt = "Lhxvuveb Zngfhzbgb"
# ebcdic_encrypt = orig_encrypt.encode("IBM037") # => "\xD3\x88\xA7\xA5\xA4\xA5\x85\x82\x40\xE9\x95\x87\x86\x88\xA9\x82\x87\x82"
# hex_string = ebcdic_encrypt.unpack('H*').first # => "d388a7a5a4a5858240e995878688a9828782"
# # Test case:
# p rot13("d388a7a5a4a5858240e995878688a9828782") # => "Yukihiro Matsumoto"
# Another interesting challenge would be writing a program that can detect different
# types of encodings and convert them to their ASCII representations appropriately.
| true |
ae1ff7b5831dfb044ac959909649ac10bb068034 | Ruby | joseantoniopb/tuenti-Challenge-2012-Solutions | /erpheus (13, Ruby)/decimo.rb | UTF-8 | 1,824 | 3.90625 | 4 | [] | no_license | class StrangeLanguage
#0,3 and 4 aren't actual numbers of arguments, but this was an easy implementation for each functions particularities
NUM_ARGUMENTS = Hash["."=>0,"mirror"=>1,"breadandfish"=>4,"#"=>2,"fire"=>2,"$"=>2,"dance"=>3,"conquer"=>2,"&"=>2,"@"=>2]
METHOD_CALL = Hash["mirror"=>:inverse,"breadandfish"=>:absolute_value,"#"=>:*,"fire"=>:max,"$"=>:-,"dance"=>:swap,"conquer"=>:%,"&"=>:/,"@"=>:+]
def interpretar(expresion)
pila=Array.new
tokens = expresion.split(" ")
tokens.each do |token|
if token.is_number?
pila << token.to_i
else
case NUM_ARGUMENTS[token]
when 1
operand = pila.pop
pila << operand.send(METHOD_CALL[token])
when 2
operand2 = pila.pop
operand1 = pila.pop
pila << operand1.send( METHOD_CALL[token], operand2 )
when 3
operand2 = pila.pop
operand1 = pila.pop
pila << operand2
pila << operand1
when 4
operand = pila.last
pila << operand
end
end
end
#if pila.length != 1
# raise "Malformed expression"
#end
return pila.first
end
end
class String
def is_number?
if self.to_i.to_s == self
return true
end
return false
end
end
class Numeric
def inverse
return -self
end
def absolute_value
if self < 0
return -self
else
return self
end
end
def squared
return self**2
end
def max(other)
if self>other
return self
else
return other
end
end
end
strange = StrangeLanguage.new
while line=gets
line=line.chomp
puts strange.interpretar(line)
end
| true |
b72fb011c95d6cc4331446445e6ddfe5fc800885 | Ruby | kendraash/recipe_box | /spec/recipe_spec.rb | UTF-8 | 475 | 2.59375 | 3 | [
"MIT"
] | permissive | require('spec_helper')
describe(Recipe) do
it('changes the rating into an integer') do
new_recipe = Recipe.create({name: 'chicken stir fry suprise', rating: '3'})
expect(new_recipe.rating).to(eq(3))
end
describe('#dishes') do
it('returns a recipe') do
new_recipe = Recipe.create({name: 'chicken stir fry suprise'})
new_dish = new_recipe.dishes.create({name: 'stir fry'})
expect(new_recipe.dishes).to(eq([new_dish]))
end
end
end
| true |
7483465c5e06468a1f8dd8c9e6022ba91c98bf00 | Ruby | JunePaloma/open_mic | /lib/joke.rb | UTF-8 | 401 | 3.0625 | 3 | [] | no_license | require 'minitest/autorun'
require 'minitest/pride'
require './lib/joke'
require './lib/user'
require "pry"
class Joke
attr_reader :jokes
def initialize
@jokes = {id: 1, question: "Why did the strawberry cross the road?", answer: "Because his mother was in a jam."}
end
def id
@jokes[:id]
end
def question
@jokes[:question]
end
def answer
@jokes[:answer]
end
end
| true |
b07aa51b30b630587d1c81e382bfbfd8002c2ae5 | Ruby | noahschultz/dealesque | /app/services/amazon_search_response_parser.rb | UTF-8 | 2,708 | 2.5625 | 3 | [] | no_license | require 'nokogiri'
class AmazonSearchResponseParser
include AmazonParser
def parse(response)
root = Nokogiri::XML(response.body).remove_namespaces!
attributes = {}
attributes[:search_terms] = parse_search_terms(root)
attributes[:items] = parse_items(root)
SearchResult.new(attributes)
end
private
def parse_search_terms(node)
parse_value(node, '//OperationRequest/Arguments/Argument[@Name="Keywords"]/@Value')
end
def parse_items(node)
node.xpath('//Items/Item').map do |item_node|
create_item_from(item_node)
end
end
def create_item_from(node)
attributes = {}
attributes[:id] = parse_value(node, './ASIN')
attributes[:title] = parse_value(node, './ItemAttributes/Title')
attributes[:url] = parse_value(node, './DetailPageURL')
attributes[:group] = parse_value(node, './ItemAttributes/ProductGroup')
attributes[:more_offers_url] = parse_value(node, './Offers/MoreOffersUrl')
attributes[:list_price] = create_price_from(node.xpath('./ItemAttributes/ListPrice').first)
attributes[:images] = parse_item_images(node)
attributes[:offers] = parse_item_offers(node)
Item.new(attributes)
end
def parse_item_images(node)
image_sets = node.xpath('./ImageSets/ImageSet')
return if image_sets.children.size == 0
image_set = image_sets.find {|image_set| image_set.attribute('Category').value == 'primary'} || image_sets.first
image_set.xpath('./*').inject(Hash.new) do |images, image_node|
image = create_item_image_from(image_node)
images[image.type] = image
images
end
end
def create_item_image_from(node)
attributes = {}
attributes[:url] = parse_value(node, './URL')
attributes[:height] = parse_value(node, './Height', :to_i)
attributes[:width] = parse_value(node, './Width', :to_i)
attributes[:type] = node.name.gsub("Image", "").downcase
ItemImage.new(attributes)
end
def parse_item_offers(node)
node.xpath('./Offers/Offer').map do |offer|
create_item_offer_from(offer)
end
end
def create_item_offer_from(node)
attributes = {}
attributes[:id] = parse_value(node, './OfferListing/OfferListingId')
attributes[:merchant] = parse_value(node, './Merchant')
attributes[:condition] = Condition.from(parse_value(node, './OfferAttributes/Condition'))
attributes[:price] = create_price_from(node.xpath('./OfferListing/Price').first)
Offer.new(attributes)
end
def create_price_from(node)
return unless node
attributes = {}
attributes[:fractional] = parse_value(node, './Amount', :to_i)
attributes[:currency] = parse_value(node, './CurrencyCode')
Price.new(attributes)
end
end | true |
cd0d45e0810f70c870e7726267327a5cb2fec6e8 | Ruby | teashton/learning_ruby_oop | /redo_brain_teaser.rb | UTF-8 | 222 | 3.484375 | 3 | [] | no_license | @array = []
def add_element
puts 'please input a numer to add to the array'
element = gets.strip
puts 'added to array'
@array << element
puts 'numbers in your array'
puts @array
add_element
end
add_element
| true |
389eef0ec8addfd8b5db330c77eca7484cb7925e | Ruby | ongaeshi/9ccr | /tokenize.rb | UTF-8 | 2,526 | 3.75 | 4 | [] | no_license | #
# tokenize.rb
#
TK_RESERVED = 0
TK_NUM = 1
TK_EOF = 2
# Token type
Token = Struct.new(
:kind, # Token kind
:next, # Next token
:val, # If kind is TK_NUM, its value
:str, # Token string
:pos # Token position in user_input
)
# Input program
$user_input = nil
# Current token
$token = nil
# Reports an error and exit.
def error(msg)
STDERR.puts msg
exit(1)
end
# Reports an error location and exit.
def error_at(msg, pos)
STDERR.puts $user_input
STDERR.puts " " * pos + "^ "
STDERR.puts msg
exit(1)
end
# Consumes the current token if it matches `op`.
def consume(op)
if $token.kind != TK_RESERVED || $token.str != op
return false
end
$token = $token.next
true
end
# Ensure that the current token is `op`.
def expect(op)
if $token.kind != TK_RESERVED || $token.str != op
error_at("expected '#{op}'", $token.pos)
end
$token = $token.next
end
# Ensure that the current token is TK_NUM.
def expect_number
error_at("expected a number", $token.pos) if $token.kind != TK_NUM
val = $token.val
$token = $token.next
val
end
def at_eof
$token.kind == TK_EOF
end
# Create a new token and add it as the next token of `cur`.
def new_token(kind, cur, str, pos)
tok = Token.new
tok.kind = kind
tok.str = str
tok.pos = pos
cur.next = tok
tok
end
def startswith(p, q)
p.include?(q)
end
# Tokenize `user_input` and returns new tokens.
def tokenize
s = StringScanner.new($user_input)
head = Token.new
head.str = ""
head.next = nil
cur = head
until s.eos? do
# Skip whitespace characters.
next if s.scan(/\s+/)
# Keywords
if s.scan(/return\b/)
cur = new_token(TK_RESERVED, cur, s[0], s.pos - s.matched_size)
next
end
# Multi-letter punctuator
if s.scan(/(==)|(!=)|(<=)|(>=)/)
cur = new_token(TK_RESERVED, cur, s[0], s.pos - s.matched_size)
next
end
# Single-letter punctuator
if s.scan(/[[:punct:]]/)
cur = new_token(TK_RESERVED, cur, s[0], s.pos - s.matched_size)
next
end
# Integer literal
if s.scan(/[0-9]+/)
cur = new_token(TK_NUM, cur, s[0], s.pos - s.matched_size)
cur.val = s[0].to_i
next
end
error_at("invalid token", s.pos)
end
new_token(TK_EOF, cur, "", s.pos)
# cur = head.next
# while cur do
# p "#{cur.kind}: #{cur.str}"
# cur = cur.next
# end
head.next
end
| true |
2053d26abfd74d8781588c4c1a26d80dbc85dd24 | Ruby | igel84/aquamarket | /app/models/cart.rb | UTF-8 | 1,869 | 3.109375 | 3 | [] | no_license | class Cart
attr_reader :items
def initialize
@items = []
end
def add_product(product, product_type, quantity=1)
if product_type == nil
current_item = @items.find { |item| item.product == product }
if current_item
current_item.increment_quantity(quantity)
else
@items << CartItem.new(product, nil, quantity)
end
else
current_item = @items.find { |item| item.product_type == product_type }
if current_item
current_item.increment_quantity(quantity)
else
@items << CartItem.new(product, product_type, quantity)
end
end
end
def price
@items.sum{ |item| item.price }
end
def quantity
@items.sum{ |item| item.quantity }
end
def conversion(product, product_type, product_quantity)
if product_type.nil?
current_item = @items.find { |item| item.product == product }
if current_item
product_quantity == 'sub' ? current_item.set_quantity(current_item.quantity - 1) : current_item.set_quantity(current_item.quantity + 1)
else
@items << CartItem.new(product, product_quantity)
end
else
current_item = @items.find { |item| item.product_type == product_type }
if current_item
product_quantity == 'sub' ? current_item.set_quantity(current_item.quantity - 1) : current_item.set_quantity(current_item.quantity + 1)
else
@items << CartItem.new(product, product_type, product_quantity)
end
end
end
def destroy_item(product, product_type)
if product_type.nil?
@items.delete_if { |item| item.product.id == product.to_i }
else
@items.delete_if { |item| item.product.id == product.to_i && item.product_type.id == product_type.to_i }
end
end
def empty?
self.items.empty?
end
def empty!
@items.delete_if { |i| true }
end
end
| true |
baf3ebf0e5e55640d38fbc195448faefa85fe235 | Ruby | Markhenn/LS-RB101 | /Exercises/Advanced 1/ex7.rb | UTF-8 | 1,112 | 4.46875 | 4 | [] | no_license | # Merge Sorted Lists
# Problem
# merge sorted lists one element at a time
# input: 2 arrays
# output: 1 array sorted
# no mutation
# how to do it:
# if one array is empty add the rest of the other
# compare first elements
# write the smaller to to the new array
# compare second and first -> write the smaller to array
# Data structure / algorithm
# couter1 == ary1.size
# couter2 == ary2.size
# new_ary = []
# loop
# break new_ary += ary2[counter2..-1] if counter1 >= ary1.size
# break new_ary += ary1[counter1..-1] if counter2 >= ary2.size
def merge(ary1, ary2)
counter1 = 0
counter2 = 0
new_ary = []
loop do
break new_ary += ary2[counter2..-1] unless counter1 < ary1.size
break new_ary += ary1[counter1..-1] unless counter2 < ary2.size
if ary1[counter1] <= ary2[counter2]
new_ary.push(ary1[counter1])
counter1 += 1
else
new_ary.push(ary2[counter2])
counter2 += 1
end
end
end
p merge([1, 5, 9], [2, 6, 8]) == [1, 2, 5, 6, 8, 9]
p merge([1, 1, 3], [2, 2]) == [1, 1, 2, 2, 3]
p merge([], [1, 4, 5]) == [1, 4, 5]
p merge([1, 4, 5], []) == [1, 4, 5]
| true |
719055ddb7fdd5c177db23083bf29ecb037877e1 | Ruby | darrylclarke/CodeCore | /week1/2015.08.12/ternary.rb | UTF-8 | 90 | 3.0625 | 3 | [] | no_license | a = true
# Need ' ' after a or else it looks for a? method
puts a ?"is true":"is false"
| true |
95d03ce2975de6986bfcca37e02f234bf66b2c5e | Ruby | Grifo89/Algorithms | /square_binary_search/ruby.rb | UTF-8 | 476 | 3.5625 | 4 | [] | no_license | def sqrt(number)
sqrt_recursive(number, 0, number)
end
def sqrt_recursive(number, min_interval, max_interval)
return number if number == 0 || number == 1
ans = 0
start = min_interval
end_ = max_interval
while start <= end_ do
mid = (start + end_)/2
return mid if mid * mid == number
if mid * mid < number
start = mid + 1
ans = mid
else
end_ = mid - 1
end
end
return end_
end
puts sqrt(25)
puts sqrt(7056787676898798798)
| true |
f888f7096e6a85084a556725a1ad659958491c14 | Ruby | BenRKarl/WDI_work | /w01/d02/Tim_Hannes/guess_the_number.rb | UTF-8 | 390 | 3.8125 | 4 | [] | no_license | def random_number
user_input = nil
x = rand(0-10)
until user_input == x
puts "Hello, please guess a number between 0 and 10."
user_input = gets.chomp.to_i
if x == user_input
puts "Congrats!" #they got it right
elsif user_input > x
puts "Your guess was too high."
elsif user_input < x
puts "Your guess was too low."
end
end
end
random_number
| true |
90d889b4f40613185aa8f5e260333a7372e86882 | Ruby | OneCuteLiz/forms-and-basic-associations-rails-lab-cb-000 | /app/models/song.rb | UTF-8 | 642 | 2.671875 | 3 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | class Song < ActiveRecord::Base
belongs_to :artist
belongs_to :genre
has_many :notes
# The Song's genre
def genre_name=(name)
self.genre = Genre.find_or_create_by(name: name)
end
def genre_name
self.genre ? self.genre.name : nil
end
# The Song's artist
def artist_name=(name)
self.artist = Artist.find_or_create_by(name: name)
end
def artist_name
self.artist ? self.artist.name : nil
end
# The Song's note(s)
def note_contents=(notes)
notes.each do |note|
if note != ""
self.notes.build(content: note)
end
end
end
def note_contents
self.notes.map do |note|
note.content
end
end
end
| true |
8bfd3bade7e8556f35b7c3570660297dad3e5078 | Ruby | schambers/learning-ruby | /scripts/callbacks.rb | UTF-8 | 548 | 4.28125 | 4 | [] | no_license |
# Callback without arguments
def hello(name)
puts "Hello #{name}"
yield
puts "Done saying hello to #{name}"
end
# Callback with arguments
def hello_again(name)
puts "Hello Again, #{name}"
yield("Alan", "Chambers")
puts "Done with hello_again"
end
def insert_space
puts "\n\n"
end
hello('Sean') { puts 'in callback' }
insert_space
hello_again('Sean') { |middleName, lastName| puts "#{middleName}, #{lastName}" }
insert_space
# Callback used in array iteration
animals = %w{ cat dog bird mouse }
animals.each {|animal| puts animal}
| true |
e32c8485c847f588b27920b0aba34f6477655c5f | Ruby | peetucket/eol-ingestion-form | /app/models/entry.rb | UTF-8 | 1,963 | 2.625 | 3 | [] | no_license | class Entry < ActiveRecord::Base
include GeoKit::Mappable
belongs_to :organism
belongs_to :user
has_many :images
has_many :assets, :dependent => :delete_all
has_many :data_points, :dependent => :delete_all
has_enumerated :habitat
validates_presence_of :date, :message=>"^Please enter the observation date."
validates_presence_of :user_id
validates_presence_of :organism_id
validates_presence_of :habitat_id
validates_date :date, :before => Proc.new { 1.day.from_now.to_date }
validates_numericality_of :lat, :message=>"^Latitude must be a number."
validates_numericality_of :lon, :message=>"^Longitude must be a number."
validates_numericality_of :number, :message=>"^Please enter the number seen as an integer.", :only_integer=>true
validates_numericality_of :temperature, :message=>"^Please enter a numeric temperature.", :allow_nil=>true
validates_numericality_of :salinity, :message=>"^Please enter a numeric salinity.", :allow_nil=>true
validates_numericality_of :confidence_range, :message=>"^The confidence range of your observation location must be a number."
validates_inclusion_of :lat, :in=> -90..90, :message=>"^Latitude must be between -90 and 90 degrees"
validates_inclusion_of :lon, :in=> -180..180, :message=>"^Longitude must be between -180 and 180 degrees"
validates_inclusion_of :number, :in=> 1..10000, :message=>"^Number seen must be at least 1"
acts_as_mappable :distance_field_name => :distance,
:lat_column_name=>"lat", :lng_column_name => "lon"
def distance_kms
# convert distance in miles to distance in kilometers
self.distance.to_f * 1.609344
end
def displayed_location
if self.location.length < 3
"Location:" + self.location
elsif self.location == "null" || self.location.nil?
"--"
else
self.location
end
end
end
| true |
e48d2c8b5bde05e4c658c0d1472e06d6d7b78805 | Ruby | xexiu/Ruby-ironhack | /accessor.rb | UTF-8 | 247 | 3.453125 | 3 | [] | no_license | class Car
attr_accessor :sound
def initialize(sound)
@sound = sound
end
def make_sound
puts @sound
end
end
my_car = Car.new "meeek"
other_car = Car.new "moook"
my_car.sound = "miiiiik"
my_car.make_sound
other_car.make_sound
| true |
e92f294a36922c20cb7e6aac6b0b8e34b046b88d | Ruby | cesarecamurani/chitter-challenge | /lib/user.rb | UTF-8 | 1,953 | 3.0625 | 3 | [] | no_license | require 'pg'
require 'bcrypt'
require_relative './database_connection'
require_relative './peep'
class User
attr_reader :id, :email, :name, :username
def initialize(id:, email:, name:, username:)
@id = id
@email = email
@name = name
@username = username
end
def self.create(email:, password:, name:, username:)
encrypted_password = BCrypt::Password.create(password)
user = DatabaseConnection.query("INSERT INTO users (email, password, name, username) VALUES('#{email}', '#{encrypted_password}', '#{name}', '#{username}') RETURNING id, email, username;")
User.new(
id: user[0]['id'],
email: user[0]['email'],
name: user[0]['name'],
username: user[0]['username']
)
end
def self.delete(id:)
DatabaseConnection.query("DELETE FROM users WHERE id = #{id}")
end
def self.list
users = DatabaseConnection.query "SELECT * FROM users;"
users.map do |user|
User.new(
id: user['id'],
email: user['email'],
name: user['name'],
username: user['username']
)
end
end
def self.find(id:)
return nil unless id
user = DatabaseConnection.query("SELECT * FROM users WHERE id = #{id}")
User.new(
id: user[0]['id'],
email: user[0]['email'],
name: user[0]['name'],
username: user[0]['username']
)
end
def self.authenticate(password:, username:)
user = DatabaseConnection.query("SELECT * FROM users WHERE username = '#{username}'")
return unless user.any?
return unless BCrypt::Password.new(user[0]['password']) == password
User.new(
id: user[0]['id'],
email: user[0]['email'],
name: user[0]['name'],
username: user[0]['username']
)
end
def peeps(peep_class = Peep)
peep_class.where(user_id: id)
end
end
| true |
6ee67907007ff4bed03f5363ba26691265d05e05 | Ruby | LeeCooper6/Ternary | /Ternary.rb | UTF-8 | 2,379 | 4.59375 | 5 | [] | no_license | # Binary is base 2 meaning binary numbers are 0 or 1.
# Ternary is base 3 meaning ternary numbers are 0, 1, or 2.
# This ternary allows -1, 0, or 1 for symmetry's sake.
# This ternary "rotates" circularly through values: -1 => 0 => 1.
# This ternary spins in either direction: -1 => 0 => 1 or 1 => 0 => -1.
# This ternary rolls over and loops circularly from 1 to -1 or -1 to 1. So -1 => 0 => 1 => -1... or 1 => 0 => -1 => 1...
class Ternary
# Creates reader for value attribute.
attr_reader :value
# Alias for set. See set.
def initialize value
set value
end
# Sets value to legal values: -1, 0, or 1.
# Parameters: Anything that can be converted to an integer. Out-of-bounds values will be curbed to -1 or 1.
# Returns: New value: -1, 0, or 1.
def set value
# Duck typing.
raise "Invalid argument type." unless value.respond_to?(:to_i)
value = value.to_i
# Set value within legal range (-1, 0, 1).
@value = value
@value = 1 if @value > 1
@value = -1 if @value < -1
# Return value.
@value
end
# Resets value to 0.
# Parameters: None.
# Returns: 0.
def reset
@value = 0
end
# Negates current value. Sets -1 to 1, 1 to -1, and does nothing to 0.
# Parameters: None.
# Returns: Negation of value.
def negate
@value *= -1
end
# Rotates through legal values: -1 => 0 => 1, rolls over back to -1.
# Parameters: Anything that can be converted to an integer. Sign determines whether to rotate forwards or backwards, magnitued determines how many times to rotate. Rotations default to 1.
# Returns: New value.
def rotate rotations = 1
# Duck typing.
raise "Invalid argument type." unless rotations.respond_to?(:to_i)
rotations = rotations.to_i
# Rotate the specified nmber of times.
rotations.abs.times do
rotations >= 0 ? @value += 1 : @value -= 1 # Rotate forwards or backwards depending on sign of rotations.
@value = -1 if @value > 1
@value = 1 if @value < -1
end
# Return value.
@value
end
# Alias method. See rotate.
def spin rotations = 1
rotate rotations
end
# Alias method. See rotate.
def next rotations = 1
rotate rotations
end
# Semi-alias method. Rotates, but in reverse order, as if rotate's argument was inversed. See rotate.
def prev rotations = 1
rotate -1 * rotations
end
end | true |
b64190b96811c3df34548197067404a44cc0911a | Ruby | amcrawford/tealeaf_intro_to_programming_workbook_exercises | /easy_questions/quiz2.rb | UTF-8 | 1,186 | 3.5 | 4 | [] | no_license | #1.
ages = { "Herman" => 32, "Lily" => 30, "Grandpa" => 402, "Eddie" => 10 }
ages.key?("Spot")
#2.
ages = { "Herman" => 32, "Lily" => 30, "Grandpa" => 5843, "Eddie" => 10, "Marilyn" => 22, "Spot" => 237 }
def add_age(hash)
total_age = 0
hash.each do |name, age|
total_age = total_age + age
end
puts total_age
end
puts add_age(ages)
#3.
p ages.delete_if {|name, age| age >= 100}
#4.
munsters_description = "The Munsters are creepy in a good way."
puts munsters_description.downcase.capitalize
puts munsters_description.swapcase
puts munsters_description.downcase
puts munsters_description.upcase
#5.
ages = { "Herman" => 32, "Lily" => 30, "Grandpa" => 5843, "Eddie" => 10 }
additional_ages = { "Marilyn" => 22, "Spot" => 237 }
ages.merge!(additional_ages)
puts ages
#6.
ages.values.min
#7.
advice = "Few things in life are as important as house training your pet dinosaur."
puts advice.include?("Dino")
#8.
flintstones = %w(Fred Barney Wilma Betty BamBam Pebbles)
puts flintstones.index{|name| name.start_with?('Be')}
#9.
flintstones.map! do |name|
name[0,3]
end
#10.
flintstones.map!{|name| name[0,3]}
| true |
bcf96a5a0a9c3373ed58dd8584a0911cf1000398 | Ruby | redxeagle/befdata | /test/unit/dataworkbook_test.rb | UTF-8 | 3,001 | 2.890625 | 3 | [
"MIT"
] | permissive | require 'test_helper'
require 'spreadsheet'
class DataworkbookTest < ActiveSupport::TestCase
def setup
@dataset = Dataset.find(5)
@spreadsheet = Spreadsheet.open @dataset.upload_spreadsheet.file.path
@spreadsheet.io.close
@book = Dataworkbook.new(@dataset.upload_spreadsheet)
end
test "workbook was loaded correctly" do
assert_not_nil @book
end
test "workbook should have five worksheets" do
assert @book.general_metadata_sheet.kind_of?(Spreadsheet::Excel::Worksheet)
assert @book.data_description_sheet.kind_of?(Spreadsheet::Excel::Worksheet)
assert @book.data_responsible_person_sheet.kind_of?(Spreadsheet::Excel::Worksheet)
assert @book.data_categories_sheet.kind_of?(Spreadsheet::Excel::Worksheet)
assert @book.raw_data_sheet.kind_of?(Spreadsheet::Excel::Worksheet)
end
test "workbook should have four column headers" do
assert_equal 4, @book.columnheaders_raw.length
end
test "workbook should have unique column headers" do
assert @book.columnheaders_unique?
end
test "workbook should contain two people" do
assert_equal 2, @book.members_listed_as_responsible.length
end
test "start date of workbook should be April 18th, 2011" do
assert_equal Date.new(2011, 4, 18), @book.datemin
end
test "end date of workbook should be April 18th, 2011" do
assert_equal Date.new(2011, 4, 18), @book.datemax
end
test "general metadata hash should fill up correctly" do
assert_equal 'Test species name import', @book.general_metadata_hash[:title]
assert_match /Comparative Study Plots/, @book.general_metadata_hash[:abstract]
assert_match /National Forest Reserve/, @book.general_metadata_hash[:spatialextent]
end
test "hash of people named in the workbook is correct" do
assert_equal 2, @book.members_listed_as_responsible.length
assert_equal "Karin", @book.members_listed_as_responsible.first[0]
assert_equal "Verena", @book.members_listed_as_responsible.second[0]
end
test "method index for a specific columnheader is correct" do
assert_equal 9, @book.method_index_for_columnheader('height')
end
test "column info for columnheader is correct" do
assert_equal 6, @book.data_column_info_for_columnheader('height').keys.length
assert_equal 'height in m', @book.data_column_info_for_columnheader('height')[:definition]
end
test "datagroup information for columnheader is correct" do
assert_equal 5, @book.methodsheet_datagroup('height').keys.length
assert_equal 'number', @book.methodsheet_datagroup('height')[:methodvaluetype]
end
test "data with head is correct for columnheader" do
assert_equal 5, @book.data_with_head('height').length
assert_equal 3.0, @book.data_with_head('height').third
end
test "datagroup title for columnheader is correct" do
assert_equal 4, @book.data_for_columnheader('height')[:rowmax]
assert_equal 'na', @book.data_for_columnheader('height')[:data][4]
end
end | true |
87af9e6492afc03e6f6a32b1a7ecc2e40a8b45de | Ruby | jtp184/inkblot | /lib/inkblot/display.rb | UTF-8 | 3,314 | 3.09375 | 3 | [] | no_license | module Inkblot
# Singleton class for the e-Paper display
class Display
class << self
# Set each time display is written to, represents what is being displayed
attr_reader :current
# Disambiguation function to take in an +obj+ and try to display it.
# In order of resolution:
# * Anything that responds to +to_display+ will have that method called,
# and the result sent back to call
# * Any Components::Component will be passed to an HtmlConverter and displayed
# * Any Converter will have its output displayed by path
# * Any File or Tempfile will have its output displayed by path
# * Any string which is an existing path on system will be displayed
# * Any string will be passed to a Components::SimpleText component, which will be
# passed to call
# * Anything else raises an ArgumentError
#
# After being displayed, the value of current is set to the object passed in
def call(obj)
if obj.respond_to?(:to_display)
call(obj.to_display)
elsif obj.is_a?(Components::Component)
call(obj.convert)
elsif obj.is_a?(Converters::Converter)
image(obj.output.path)
elsif obj.is_a?(File) || obj.is_a?(Tempfile)
image(obj.path)
elsif obj.is_a?(String) && Pathname.new(obj).exist?
image(obj)
elsif obj.is_a?(String)
call(Components::SimpleText.new(text: obj))
else
raise ArgumentError, "Cannot display #{obj.class.name}"
end
@current = obj
end
# Show the current object again, presumably after changing it
def redisplay
call current
end
# Syntactic sugar options
alias show call
alias [] call
alias again redisplay
# Clears screen on device, and sets current to nil
def clear
`#{pyscript('clear')}`
@current = nil
end
# Checks if +current+ is nil
def empty?
current.nil?
end
# Aspect ratio of the screen, from Inkblot.screen_size
def size
Inkblot.screen_size
end
# Returns the +size+ as CSS style attributes
def size_css
size.transform_values { |n| "#{n}px" }
.to_a
.reverse
.map { |k, v| "#{k}: #{v};" }
.join(' ')
end
private
# Takes in an image +img+ to display on the device.
# Can be a File, filepath string, or a Converter subclass.
# Automatically switches display script based on color depth
def image(img)
disp_script = case Inkblot.color_depth
when 1
'display'
when 4
'display_4gray'
end
`#{pyscript(disp_script, img)}`
end
# Create a python script string. +skript+ is the script's name
# subsequent strings are treated as arguments
def pyscript(skript, *args)
cmd = 'python '
cmd << Inkblot.vendor_path("#{skript}.py")
cmd << ' ' << Inkblot.vendor_path
unless args.nil? || args.empty?
args[0..-1].each do |arg|
cmd << ' ' << arg
end
end
cmd
end
end
end
end
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.