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