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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
5982724dbec6e12e0057439c8a6a396661fc227a | Ruby | sharonshlee/TwO-O-Player_Math_Game | /player.rb | UTF-8 | 211 | 3.34375 | 3 | [] | no_license | class Player
attr_accessor :lives
attr_accessor :name
def initialize(name)
@lives = 3
@name = name
end
def deduct_scores()
@lives -= 1
end
def to_s
"Player #{name}:"
end
end | true |
da141240dab17fb1bfe01a7b2c78a90f018f0faa | Ruby | lyhourlay1/aa_classwork | /w7/w7d5/reddit_clone/app/models/user.rb | UTF-8 | 1,022 | 2.578125 | 3 | [] | no_license | class User < ApplicationRecord
validates :username, :password_digest, :session_token, presence:true
validates :username, uniqueness:true
validates :password, length: {minimum: 6}, allow_nil: true
attr_reader :password
after_initialize :ensure_session_token
def password=(password)
@password = password
self.password_digest = BCrypt::Password.create(password)
end
def self.find_by_credentials(password, username)
@user = User.find_by(username: username)
if @user && @user.is_valid_password?(password)
@user
else
nil
end
end
def is_valid_password?(password)
pw_obj = BCrypt::Password.new(self.password_digest)
pw_obj.is_password?(password)
end
def reset_session_token!
self.session_token = SecureRandom::base64(64)
self.save!
self.session_token
end
def ensure_session_token
self.session_token ||= SecureRandom::base64(64)
end
end
| true |
85b883f72bb3e943d0b6fdafc32ce2aa9a4c31b7 | Ruby | IlluminusLimited/pgdice | /lib/pgdice/period_fetcher.rb | UTF-8 | 862 | 2.578125 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
module PgDice
# Used to find the period of a postgres table using the comment on the table created by pgslice
class PeriodFetcher
def initialize(query_executor:)
@query_executor = query_executor
end
def call(params)
sql = build_table_comment_sql(params.fetch(:table_name), params.fetch(:schema))
values = @query_executor.call(sql)
convert_comment_to_hash(values.first)[:period]
end
private
def convert_comment_to_hash(comment)
return {} unless comment
comment.split(',').reduce({}) do |hash, key_value_pair|
key, value = key_value_pair.split(':')
hash.merge(key.to_sym => value)
end
end
def build_table_comment_sql(table_name, schema)
"SELECT obj_description('#{schema}.#{table_name}'::REGCLASS) AS comment"
end
end
end
| true |
8c70d32d1c96e70a8677f04bd8f649a666e0b837 | Ruby | Sayantini11/Ruby | /array_largest.rb | UTF-8 | 264 | 3.765625 | 4 | [] | no_license | puts "Enter the size of the array"
size = gets.chomp.to_i
puts "Enter the array element"
arr = []
i = 0
while i < size
arr[i] = gets.chomp.to_i
i += 1
end
max_value = 0
arr.each do |i|
if i > max_value
max_value = i
end
end
puts "Max value is #{max_value}"
| true |
c46dba40b295707c2945d79711b723efbfe248ef | Ruby | realalien/rubyplayground | /news.tool/yangtze_collector.rb | UTF-8 | 3,680 | 2.984375 | 3 | [] | no_license | #encoding:UTF-8
require 'date'
require 'nokogiri'
require 'json'
require File.join(File.dirname(__FILE__),"./util.rb")
class YangtzeDailyCollector
# NOTE: because the section/page-titles and article-titles are among different rows of the same table, data will be gathered by processing each row sequentially.
def self.daily_news_links(date)
pages_and_articles = []
# http://epaper.yzwb.net/html_t/2012-12/30/node_1.htm
pages_dir = "http://epaper.yzwb.net/html_t/#{date.year}-#{date.strftime('%m')}/#{date.strftime('%d')}"
first_index_page = "#{pages_dir}/node_1.htm" # ends with node_1.html
second_index_page = "#{pages_dir}/node_201.htm"
row_xpath = "//*[@id='layer43']//table/tbody/tr"
one_page = {} # cache for articles
pages = [] # container for all hashes of page TOC
# A bundle, B bundle
[first_index_page, second_index_page].each do | idx|
index_page = WebPageTool.retrieve_content idx
if index_page
index_page.parser.xpath(row_xpath).each do | node|
# test sub <a> node if has 'pageLink' or not
row_links = node.xpath(".//a[@id='pageLink']")
if row_links.size == 1 # suppose one for row with page link
# find new page/section
pages << one_page unless one_page.empty?
# refill
one_page = {}
one_page = { :page_link => "#{pages_dir}/#{row_links[0]['href'].gsub('./','')}" ,
:page_title => node.content.gsub("\r\n", "") }
else
articles_hash = []
row_links = node.xpath(".//a") # recollect
row_links.each do |lnk|
articles_hash << {:article_link => "#{File.join(pages_dir, lnk['href'].gsub('?div=-1',''))}" ,
:article_title => lnk.content.gsub("\r\n", " ") }
end
one_page[:articles_links] = articles_hash
end # of if else
end # each row
end # if index_page
#puts "pages total #{pages.size}"
#puts pages
end # each index page
return { :date_of_news => date.strftime("%Y-%m-%d"), :pages_links => pages }
end
def similar_word
end
end
def lcs(a, b)
lengths = Array.new(a.size+1) { Array.new(b.size+1) { 0 } }
# row 0 and column 0 are initialized to 0 already
a.split('').each_with_index { |x, i|
b.split('').each_with_index { |y, j|
if x == y
lengths[i+1][j+1] = lengths[i][j] + 1
else
lengths[i+1][j+1] = \
[lengths[i+1][j], lengths[i][j+1]].max
end
}
}
# read the substring out from the matrix
result = ""
x, y = a.size, b.size
while x != 0 and y != 0
if lengths[x][y] == lengths[x-1][y]
x -= 1
elsif lengths[x][y] == lengths[x][y-1]
y -= 1
else
# assert a[x-1] == b[y-1]
result << a[x-1]
x -= 1
y -= 1
end
end
result.reverse
end
if __FILE__ == $0
toc = YangtzeDailyCollector.daily_news_links(DateTime.new(2012,12,31))
page_hashes = []
toc[:pages_links].each do | page|
page_hashes << page
end
puts page_hashes
similar = {}
word = page_hashes.shift
while page_hashes.size > 0
page_hashes.each do | art|
s = lcs(word[:page_title].split(":")[1], art[:page_title].split(":")[1])
if s and not s.gsub(/\s*/,'').gsub(/·/,'').empty? and s.size > 1
similar[s] ||= []
title_name = art[:page_title].split(":")[0]
similar[s] << title_name unless similar[s].include?(title_name)
end
end
word = page_hashes.shift
end
puts similar
end
| true |
a7e8b19d45e54d5a4033dfde3878b1c8cfa7974b | Ruby | gautamsawhney/BrainStorm | /app/models/level.rb | UTF-8 | 549 | 2.5625 | 3 | [] | no_license |
class Level < ActiveRecord::Base
attr_accessible :answer, :next_id, :prev_id, :question, :image
before_save :sterlize_answer
mount_uploader :image, ImageUploader
has_many :attempts
validates :answer , :presence => true, :length => {:maximum => 50}
def self.set(params)
next_id = nil
prev_id = (Level.last and Level.last.id) ? Level.last.id : nil
params[:prev_id] = prev_id
level = Level.new(params)
level
end
def sterlize_answer
self.answer = self.answer.chomp.downcase.gsub(/[\W\n\s]/,'')
end
end
| true |
643e367fc42fab20ac287cfb2b2774f9ab775bad | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/ruby/bob/675480c69bef443589571311cf592828.rb | UTF-8 | 619 | 3.484375 | 3 | [] | no_license | class Bob
# Approach taken from Bozhidar Batsov's recent blog post:
# http://batsov.com/articles/2013/09/24/lambdas-slash-procs-in-case-expressions/
def hey(message)
case message
when silence?
'Fine. Be that way!'
when shout?
'Woah, chill out!'
when question?
'Sure.'
else
'Whatever.'
end
end
private
def question?
@question ||= -> (message) { message.end_with?('?') }
end
def shout?
@shout ||= -> (message) { message == message.upcase && message =~ /[[:alpha:]]/ }
end
def silence?
@silence ||= -> (message) { message =~ /\A\s*\z/ }
end
end
| true |
03cf20274a3b48762dffe619728118ce0afd4815 | Ruby | a-gerlach/LaunchSchool_101_Programming_Foundations | /lesson_4/loop_improvement_21.rb | UTF-8 | 8,846 | 4.15625 | 4 | [] | no_license | require "pry"
# we initialize the deck as an Array containing every card of every color.
DCK = ["2heart", "3heart", "4heart", "5heart", "6heart", "7heart", "8heart", "9heart", "10heart", "jackheart", "queenheart", "kingheart", "aceheart",
"2dia", "3dia", "4dia", "5dia", "6dia", "7dia", "8dia", "9dia", "10dia", "jackdia", "queendia", "kingdia", "acedia",
"2clu", "3clu", "4clu", "5clu", "6clu", "7clu", "8clu", "9clu", "10clu", "jackclu", "queenclu", "kingclu", "aceclu",
"2spa", "3spa", "4spa", "5spa", "6spa", "7spa", "8spa", "9spa", "10spa", "jackspa", "queenspa", "kingspa", "acespa" ]
# in this method we select one of the values in our array for the player
def draw_card(dck)
dck[rand(0..51)]
end
# the drawn card is played in the "draw" variable
# and then if draw begin with 2 through 10 we will add than number.
# if it begins with anything else we return 10
def calculate_values!(cards, user)
if cards.start_with?("2", "3", "4", "5", "6", "7", "8", "9")
cards.byteslice(0).to_i
elsif cards.start_with?("10", "j", "q", "k")
10
elsif cards.start_with?("a")
11
end
end
# we use this method to check for aces by inputting the score and the draw
# if the score is over 21 and the cards start with an "a", we subtract 10 points form the score
# this means that Aces will only give one point.
def check_for_aces(score, cards)
if score > 21 && cards.start_with?("a")
true
end
end
# this is slight improvement on the first method
# it takes the score and if the conditions are met it subtracts 10 points.
# otherwise it returns the score.
def check_for_aces_v2(score, cards)
if score > 21 && cards.start_with?("a")
score -= 10
score
end
score
end
# this method checks for by iterating throught the array if the score is over 21 and
# if the array includes an Ace, it is removed and 10 is returned.
# if nothing is found we return 0
# later we subtract the returned value with our current_score
def check_for_aces_v4(array, score)
if score > 21
if array.include?("acespa")
array.delete("acespa")
10
elsif array.include?("acedia")
array.delete("acedia")
10
elsif array.include?("aceclu")
array.delete("aceclu")
10
elsif array.include?("aceheart")
array.delete("aceheart")
10
else
0
end
else
0
end
end
# this method return true if the player goes over 21.
# it then break the loop and puts the score to the screen.
def busted(score, string)
if score > 21
puts "The #{string} has a score of #{score}, which is over 21."
puts "The #{string} goes bust and looses this game."
true
end
end
# all the conditions in this method work
def compare_scores(p_score, c_score, p_hand, c_hand)
if p_score > c_score
puts "The player wins with #{p_score} points against the #{c_score} of the dealer!"
puts "Your hand was #{p_hand}"
puts "The dealer had #{c_hand}"
elsif c_score > p_score
puts "The computer wins with #{c_score} points against the #{p_score} of the player!"
puts "Your hand was #{p_hand}"
puts "The dealer had #{c_hand}"
elsif p_score == c_score
puts "You both have the same score of #{p_score}."
puts "There is no winner in this round."
puts "Your hand was #{p_hand}"
puts "The dealer had #{c_hand}"
end
end
def win_or_lose(score, string, cards)
if score > 21
puts "The #{string} has a score of #{score}, which is over 21."
puts "The #{string} goes bust and looses this game."
puts "The #{string}'s hand in the end was: #{cards}"
true
elsif score == 21
puts "The #{string} has hit 21 points and wins this game!"
puts "The #{string}'s hand in the end was: #{cards}"
true
else
false
end
end
# append the cards to an array. This way the cards are score permanently.
def add_cards_to_hand(player_cards, cards)
player_cards << cards
end
# The Introduction
puts ""
puts "Welcome to 21. Draw some cards and don't get a score over 21!"
puts ""
puts "Have fun!"
puts ""
loop do
# we have to insert the first two cards herethis means
# all the variables
# PLAYER TURN
# Initializing the score variable and the player hand variable.
player_total_score = 0
player_hand = []
# first draw, calculate the score and add the card to the hand (array)
# of the player.
draw = draw_card(DCK)
player_total_score += calculate_values!(draw, "player")
add_cards_to_hand(player_hand, draw)
# the second draw. Rest is same as above
draw = draw_card(DCK)
player_total_score += calculate_values!(draw, "player")
player_total_score -= check_for_aces_v4(player_hand, player_total_score)
add_cards_to_hand(player_hand, draw)
break if win_or_lose(player_total_score, "player", player_hand)
# tell the player score and his hand
puts "You have drawn two cards. These cards are #{player_hand}. Your total score is #{player_total_score}."
puts ""
# COMPUTER FIRST DRAW OF TWO CARDS. ONE IS REVEALED, THE OTHER CARD IS HIDDEN
# Now the computer draws two cards but only reveals one of them
# Initializing the score variable and the computer hand variable.
computer_shown_score = 0
computer_complete_hand = []
computer_hand = []
computer_hidden_card = []
computer_hidden_score = 0
player_stay = false
computer_stay = false
# first draw, calculate the score and add the card to the hand (array)
# of the computer.
draw = draw_card(DCK)
computer_shown_score += calculate_values!(draw, "computer")
add_cards_to_hand(computer_hand, draw)
add_cards_to_hand(computer_complete_hand, draw)
# tell the player score and hand of computer
puts "The computer has drawn two cards. The one card you are seeing is #{computer_hand}."
puts "The other card of the computer is hidden. The dealers score is #{computer_shown_score}."
puts ""
# draw another card but hide it
draw = draw_card(DCK)
computer_hidden_score += calculate_values!(draw, "computer")
computer_hidden_score += computer_shown_score
# check for aces
if check_for_aces(computer_hidden_score, draw)
computer_shown_score -= 10
computer_hidden_score -= 10
end
# the cards are added to their respective hands
add_cards_to_hand(computer_hidden_card, draw)
add_cards_to_hand(computer_complete_hand, draw)
# break if win_or_lose condition is met
break if win_or_lose(computer_hidden_score, "dealer", computer_complete_hand)
# ask to hit or stay to the player
puts "Hit or stay?"
puts ""
answer = gets.chomp
if answer.downcase.start_with?('s')
player_stay = true
elsif answer.downcase.start_with?('h')
player_stay = false
end
loop do
if player_stay == false
# PLAYER TURN
draw = draw_card(DCK)
player_total_score += calculate_values!(draw, "player")
add_cards_to_hand(player_hand, draw)
player_total_score -= check_for_aces_v4(player_hand, player_total_score)
# display the draw to the player
puts "You have drawn a #{draw}."
break if win_or_lose(player_total_score, "player", player_hand)
puts "Your hand is now #{player_hand} and your score is now #{player_total_score}."
puts ""
else
puts "You have decided to stay."
end
# COMPUTER TURN
if computer_hidden_score < 17
draw = draw_card(DCK)
computer_shown_score += calculate_values!(draw, "computer")
computer_hidden_score += calculate_values!(draw, "computer")
add_cards_to_hand(computer_hand, draw)
add_cards_to_hand(computer_complete_hand, draw)
# computer_complete_hand = computer_hand + computer_hidden_card
computer_hidden_score -= check_for_aces_v4(computer_complete_hand, computer_hidden_score)
puts "The dealer draws a #{draw}."
break if win_or_lose(computer_hidden_score, "dealer", computer_complete_hand)
puts "Dealers shown score is #{computer_shown_score}"
else
puts "The Dealer stays"
computer_stay = true
break if win_or_lose(computer_hidden_score, "dealer", computer_complete_hand)
end
# check fot the stay condition
if player_stay && computer_stay
compare_scores(player_total_score, computer_hidden_score, player_hand, computer_complete_hand)
break
end
# ask to hit or stay to the player
if player_stay == false
puts "Hit or stay?"
puts ""
answer = gets.chomp
if answer.downcase.start_with?('s')
player_stay = true
elsif answer.downcase.start_with?('h')
player_stay = false
end
end
if player_stay && computer_stay
compare_scores(player_total_score, computer_hidden_score, player_hand, computer_complete_hand)
break
end
end
puts ""
puts "Do you want to play another game? (Y/N)"
puts ""
answer = gets.chomp
break unless answer.downcase.start_with?('y')
puts ""
end
| true |
b6a359ddfc28dbe91cf111f51df2a727fcf315cd | Ruby | njenga-kariuki/sql-crowdfunding-lab-seattle-web-career-021819 | /lib/sql_queries.rb | UTF-8 | 2,056 | 3.109375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | # Write your sql queries in this file in the appropriate method like the example below:
#
# def select_category_from_projects
# "SELECT category FROM projects;"
# end
# Make sure each ruby method returns a string containing a valid SQL statement.
def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name
"Write your SQL query Here"
"
SELECT
projects.title,
SUM(pledges.amount) as pledge_amount
FROM
projects
JOIN pledges ON pledges.project_id = projects.id
GROUP BY projects.title ORDER BY projects.title ASC
"
end
def selects_the_user_name_age_and_pledge_amount_for_all_pledges_alphabetized_by_name
"Write your SQL query Here"
"
SELECT
users.name,
users.age,
SUM(pledges.amount) as pledge_amount
FROM users
JOIN pledges on pledges.user_id = users.id
GROUP BY users.name ORDER BY users.name ASC
"
end
def selects_the_titles_and_amount_over_goal_of_all_projects_that_have_met_their_funding_goal
"Write your SQL query Here"
"
SELECT
projects.title,
(SUM(pledges.amount) - projects.funding_goal) as amt_over
FROM projects
JOIN pledges on pledges.project_id = projects.id
GROUP BY projects.title HAVING (SUM(pledges.amount) - projects.funding_goal) >-1
"
end
def selects_user_names_and_amounts_of_all_pledges_grouped_by_name_then_orders_them_by_the_amount_and_users_name
##CANNOT GET THIS TO PASS
"Write your SQL query Here"
"
SELECT
users.name,
SUM(pledges.amount) pldg_amt
FROM users
JOIN pledges on pledges.user_id = users.id
GROUP BY users.name ORDER BY SUM(pledges.amount) ASC
"
end
def selects_the_category_names_and_pledge_amounts_of_all_pledges_in_the_music_category
"Write your SQL query Here"
"
SELECT
projects.category,
pledges.amount
FROM projects
JOIN pledges ON pledges.project_id = projects.id
WHERE projects.category = 'music'
"
end
def selects_the_category_name_and_the_sum_total_of_the_all_its_pledges_for_the_books_category
"Write your SQL query Here"
"
SELECT
projects.category,
SUM(pledges.amount)
FROM projects
JOIN pledges ON pledges.project_id = projects.id
WHERE projects.category = 'books'
"
end
| true |
451aeae27c2820ae08a98449df91c9eca8591c10 | Ruby | Scoutski/adventOfCode2018 | /day5q2/solution.rb | UTF-8 | 1,196 | 3.5 | 4 | [] | no_license | def extractLinesFromFile (fileName)
return IO.readlines(fileName)
end
def testCharacters (line)
shortestPolymer = 999999999
testedChars = []
for i in 0..(line.length-1) do
if line[i].is_a?(String)
if !testedChars.include? line[i]
testedChars.push(line[i].downcase, line[i].upcase)
lineTest = line.dup.tr("#{line[i].downcase}#{line[i].upcase}", "")
processedLine = processLine(lineTest)
if processedLine.length < shortestPolymer
puts "New length is #{processedLine.length}"
shortestPolymer = processedLine.length
end
end
end
end
return shortestPolymer
end
def processLine (line)
noMatches = false
while !noMatches
changeMade = false
for i in 0..(line.length-1) do
if (i <= line.length-1 && line[i].is_a?(String) && line[i+1].is_a?(String))
if (line[i].upcase == line[i+1].upcase && line[i] != line[i+1])
changeMade = true
line.slice!(i..i+1)
end
end
end
if !changeMade
noMatches = true
end
end
return line
end
def main ()
line = extractLinesFromFile('./input.txt')[0]
return testCharacters(line)
end
puts main() | true |
f88babda1aab485929097108948b0b3a30baf377 | Ruby | amunguia/poker | /app/models/game.rb | UTF-8 | 13,315 | 2.890625 | 3 | [] | no_license | require 'json'
class Game < ActiveRecord::Base
belongs_to :table
def initialize(min_bet)
super()
deck = Deck.new_deck
self.stream = deck.slice(0,5).join ","
self.p1_cards = deck.slice(5,2).join ","
self.p2_cards = deck.slice(7,2).join ","
self.p3_cards = deck.slice(9,2).join ","
self.p4_cards = deck.slice(11,2).join ","
self.p1_contrib = 0
self.p2_contrib = 0
self.p3_contrib = 0
self.p4_contrib = 0
self.each_contrib = 0
self.round_count = 0
self.players_left = 4
self.message = ""
self.min_bet = min_bet
self.new_round = true
self.perm_table ||= self.table_id
self.order = "p1,p2,p3,p4"
end
def add_player(id)
if (p1 == id || p2 == id || p3 == id || p4 == id)
return false
end
user = User.find(id)
if self.p1 == nil
self.p1 = id
self.current_player = id
self.message = "#{user.username} joined the game."
self.save
"p1"
elsif self.p2 == nil
self.p2 = id
self.message = "#{user.username} joined the game."
self.save
"p2"
elsif self.p3 == nil
self.p3 = id
self.message = "#{user.username} joined the game."
self.save
"p3"
elsif self.p4 == nil
self.p4 = id
self.message = "#{user.username} joined the game."
self.save
"p4"
else
false
end
end
def cards_for_player(id)
if self.p1 == nil || self.p2 == nil || self.p3 == nil || self.p4 == nil
return [] #Game hasn't started, do not reveal cardss
end
if self.p1 == id
cards = self.p1_cards.split ","
elsif self.p2 == id
cards = self.p2_cards.split ","
elsif self.p3 == id
cards = self.p3_cards.split ","
elsif self.p4 == id
cards = self.p4_cards.split ","
end
if cards
array = []
array<< Card.url_for(cards[0])
array<< Card.url_for(cards[1])
array
else
[]
end
end
def current_player_obj
if self.current_player_str == "p1"
User.find(self.p1)
elsif self.current_player_str == "p2"
User.find(self.p2)
elsif self.current_player_str == "p3"
User.find(self.p3)
else self.current_player_str == "p4"
User.find(self.p4)
end
end
def current_player_str
if self.winner_id
"G-O"
else
self.order.split(",")[0]
end
end
def current_player_folds
self.message = "#{current_player_obj.username} folds."
array = self.order.split(",")
array = array.slice(1, array.length - 1)
self.order = array.join(",")
set_current_player array[0]
self.players_left -= 1
self.save
self.players_left
end
def determine_winner
#Call codd
end
def get_opponents_cards
if self.winner_id == nil
{:message => "Called Game.get_opponents_cards too early."}
elsif self.order.split(",").length < 2
nil
else
cards = {}
self.order.split(",").each do |p|
if p.eql? "p1"
cards[p] = cards_for_player p1
elsif p.eql? "p2"
cards[p] = cards_for_player p2
elsif p.eql? "p3"
cards[p] = cards_for_player p3
else
cards[p] = cards_for_player p4
end
end
cards
end
end
def get_winner
if (!next_card? && table_even?) || (self.players_left == 1)
self.winner_id = calculate_winner
if (self.each_contrib > 0)
user = User.find self.winner_id
self.message = "The winner is #{user.username}"
self.save
user.balance += (self.p1_contrib +
self.p2_contrib + self.p3_contrib + self.p4_contrib)
user.save
self.each_contrib = 0
end
self.save
else
nil
end
end
def is_full?
!(self.p1 == nil || self.p2 == nil || self.p3 == nil || self.p4 == nil)
end
def is_not_turn(user)
current_player_obj.id != user.id
end
def is_user_in_game?(user)
if p1 == user.id
"p1"
elsif p2 == user.id
"p2"
elsif p3 == user.id
"p3"
elsif p4 == user.id
"p4"
else
false
end
end
def next_card?
if self.card1 == nil
self.reveal_first_three_cards
self.round_count = 0
self.new_round = true
self.save
true
elsif self.card4 == nil
self.reveal_fourth_card
self.round_count = 0
self.new_round = true
self.save
true
elsif self.card5 == nil
self.reveal_fifth_card
self.round_count = 0
self.new_round = true
self.save
true
else
false
end
end
def next_player
array = self.order.split(",")
array = array.slice(1, array.length - 1)<< array[0]
self.order = array.join(",")
self.round_count += 1
set_current_player array[0]
self.save
array[0]
end
def one_player_left?
(self.players_left <= 1)
end
def two_players_left?
end
def player_antes(player)
if player.deduct(min_bet)
if player.id == p1
self.update(p1_contrib: min_bet)
elsif player.id == p2
self.update(p2_contrib: min_bet)
elsif player.id == p3
self.update(p3_contrib: min_bet)
elsif player.id == p4
self.update(p4_contrib: min_bet)
end
true
else
false
end
end
def player_bets(amt, calls)
player_str = current_player_str
if player_str.eql? "p1"
if (p1_contrib + amt) < each_contrib
return false
end
elsif player_str.eql? "p2"
if (p2_contrib + amt) < each_contrib
return false
end
elsif player_str.eql? "p3"
if (p3_contrib + amt) < each_contrib
return false
end
elsif player_str.eql? "p4"
if (p4_contrib + amt) < each_contrib
return false
end
end
if amt == 0 && !calls
message = "#{current_player_obj.username} stays."
elsif calls
message = "#{current_player_obj.username} calls."
else
message = "#{current_player_obj.username} bet $#{amt}"
end
if current_player_obj.deduct(amt)
if player_str.eql? "p1"
if (p1_contrib + amt) > each_contrib
self.update each_contrib: (p1_contrib + amt)
end
if new_round && amt >= min_bet
self.update new_round: false
end
self.update p1_contrib: self.p1_contrib + amt
self.update message: message
elsif player_str.eql? "p2"
if (p2_contrib + amt) > each_contrib
self.update each_contrib: (p2_contrib + amt)
end
if new_round && amt >= min_bet
self.update new_round: false
end
self.update p2_contrib: self.p2_contrib + amt
self.update message: message
elsif player_str.eql? "p3"
if (p3_contrib + amt) > each_contrib
self.update each_contrib: (p3_contrib + amt)
end
if new_round && amt >= min_bet
self.update new_round: false
end
self.update p3_contrib: self.p3_contrib + amt
self.update message: message
else
if (p4_contrib + amt) > each_contrib
self.update each_contrib: (p4_contrib + amt)
end
if new_round && amt >= min_bet
self.update new_round: false
end
self.update p4_contrib: self.p4_contrib + amt
self.update message: message
end
else
false
end
end
def set_current_player(string)
if string.eql? "p1"
self.current_player = self.p1
elsif string.eql? "p2"
self.current_player = self.p2
elsif string.eql? "p3"
self.current_player = self.p3
else
self.current_player =self.p4
end
end
def table_even?
if self.round_count < self.players_left
return false
end
match = -1
self.order.split(",").each do |p|
if p.eql? "p1"
contrib = self.p1_contrib
elsif p.eql? "p2"
contrib = self.p2_contrib
elsif p.eql? "p3"
contrib = self.p3_contrib
else
contrib = self.p4_contrib
end
if match < 0
match = contrib
elsif match != contrib
return false
end
end
true
end
def valid_player(user)
user.id == p1 || user.id == p2 || user.id == p3 || user.id == p4
end
def to_json()
self.save
self.reload
state = {}
users = {}
if self.p1
player = User.find_by_id(self.p1)
object = {:username => player.username, :balance => player.balance}
users["p1"] = object
else
users["p1"] = {:username => "----", :balance => "----"}
end
if self.p2
player = User.find_by_id(self.p2)
object = {:username => player.username, :balance => player.balance}
users["p2"] = object
else
users["p2"] = {:username => "----", :balance => "----"}
end
if self.p3
player = User.find_by_id(self.p3)
object = {:username => player.username, :balance => player.balance}
users["p3"] = object
else
users["p3"] = {:username => "----", :balance => "----"}
end
if self.p4
player = User.find_by_id(self.p4)
object = {:username => player.username, :balance => player.balance}
users["p4"] = object
else
users["p4"] = {:username => "----", :balance => "----"}
end
state[:started] = (is_full? && winner_id == nil)
state[:users] = users
state[:current_player] = current_player_str
state[:message] = message
state[:new_round] = new_round
state[:min_bet] = get_min_bet
state[:each_contrib] = each_contrib
state[:p1_contrib] = p1_contrib
state[:p2_contrib] = p2_contrib
state[:p3_contrib] = p3_contrib
state[:p4_contrib] = p4_contrib
state[:result] = true
if self.winner_id
state[:winner_id] = self.winner_id
end
state[:pot_bal] = self.p1_contrib + self.p2_contrib + self.p3_contrib + self.p4_contrib
if (card1)
state[:card1] = Deck.card_for_string(self.card1).to_url
else
state[:card1] = nil
end
if (card2)
state[:card2] = Deck.card_for_string(self.card2).to_url
else
state[:card2] = nil
end
if (card3)
state[:card3] = Deck.card_for_string(self.card3).to_url
else
state[:card3] = nil
end
if (card4)
state[:card4] = Deck.card_for_string(self.card4).to_url
else
state[:card4] = nil
end
if (card5)
state[:card5] = Deck.card_for_string(self.card5).to_url
else
state[:card5] = nil
end
if self.winner_id
state[:opponents_cards] = self.get_opponents_cards
end
state.to_json
end
def self.get_users
users = []
users<< (User.new email: 'aaaaa12', username: 'aaaaa1', password: 'aa', password_confirmation: 'aa')
users<< (User.new email: 'bbbbb12', username: 'bbbbb1', password: 'bb', password_confirmation: 'bb')
users<< (User.new email: 'ccccc12', username: 'ccccc1', password: 'cc', password_confirmation: 'cc')
users<< (User.new email: 'ddddd12', username: 'ddddd1', password: 'dd', password_confirmation: 'dd')
users<< (User.new email: 'eeeee12', username: 'eeeee1', password: 'ee', password_confirmation: 'ee')
users
end
def reveal_first_three_cards
self.card1 = self.stream.split(",")[0]
self.card2 = self.stream.split(",")[1]
self.card3 = self.stream.split(",")[2]
self.message = "The stream is shown."
self.save
end
def reveal_fourth_card
self.card4 = self.stream.split(",")[3]
self.message = "The turn is shown."
self.save
end
def reveal_fifth_card
self.card5 = self.stream.split(",")[4]
self.message = "The river is shown."
self.save
end
def get_min_bet
if new_round
min_bet
else
player = current_player_str
if player.eql? "p1"
each_contrib - p1_contrib
elsif player.eql? "p2"
each_contrib - p2_contrib
elsif player.eql? "p3"
each_contrib - p3_contrib
else
each_contrib - p4_contrib
end
end
end
def calculate_winner
if self.players_left == 1
winner = self.order.split(",")[0]
else
winning_score = -1
winner = ""
hands = hands_for_players
hands.each_key do |p|
hand = hands[p]
if hand.bestscore > winning_score
winner = p
winning_score = hand.bestscore
end
end
end
if winner.eql? "p1"
p1
elsif winner.eql? "p2"
p2
elsif winner.eql? "p3"
p3
else
p4
end
end
def hands_for_players
hands = {}
self.order.split(",").each do |player|
hands[player] = Hand.new(card_array_for(player))
hands[player].best_hand
end
hands
end
def card_array_for(player)
if player.eql? "p1"
array = self.p1_cards.split ","
elsif player.eql? "p2"
array = self.p2_cards.split ","
elsif player.eql? "p3"
array = self.p3_cards.split ","
else
array = self.p4_cards.split ","
end
cards = []
append_as_cards(self.stream.split(","),
append_as_cards(array, cards))
end
def append_as_cards(string_array, card_array)
string_array.each do |s|
card_array<< Card.for_string(s)
end
card_array
end
end | true |
2b31d1b45428f1f9e03f7e86b0b4abe4b21cde21 | Ruby | dscottcole/ruby-oo-object-relationships-collaborating-objects-lab-hou01-seng-ft-071320 | /lib/variables.rb | UTF-8 | 1,237 | 2.703125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require 'pry'
require_relative './artist'
require_relative './song'
require_relative './mp3_importer.rb'
# elton = Artist.new("Elton John")
# yoursong = Song.new("Your Song")
# yoursong.artist_name = ("Elton John")
# artist = Artist.new('Michael Jackson')
# dirty_diana = Song.new("Dirty Diana")
# billie_jean = Song.new("Billie Jean")
# piano_man = Song.new("Piano Man")
# dirty_diana.artist = artist
# billie_jean.artist = artist
# artist = Artist.new('Michael Jackson')
# song_one = Song.new("Rock With You")
# song_two = Song.new("Smooth Criminal")
# smells_like_teen_spirit = Song.new("Smells Like Teen Spirit")
# artist.add_song(song_one)
# artist.add_song(song_two)
# artist_1 = Artist.find_or_create_by_name("Michael Jackson")
# artist_2 = Artist.find_or_create_by_name("Michael Jackson")
# artist_1 = Artist.find_or_create_by_name("Drake")
# artist = Artist.new('Michael Jackson')
# dirty_diana = Song.new("Dirty Diana")
# billie_jean = Song.new("Billie Jean")
# piano_man = Song.new("Piano Man")
# artist.add_song(dirty_diana)
# artist.add_song(billie_jean)
test_music_path = "./spec/fixtures/mp3s"
music_importer = MP3Importer.new(test_music_path)
music_importer.files
music_importer.import
# Song.new_by_filename("Real Estate - It's Real - hip-hop.mp3")
binding.pry
| true |
ee343a38be08d0f3807cb74602fdcfc730aabbf9 | Ruby | matiasgarcia/cabify_challenge | /lib/cabify_challenge/line_item.rb | UTF-8 | 417 | 2.8125 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
module CabifyChallenge
class LineItem
attr_reader :product, :quantity, :checkout
def initialize(product:, quantity: 0, checkout:)
@product = product
@quantity = quantity
@checkout = checkout
end
def add
@quantity += 1
end
def total
product_price * quantity
end
def product_price
@product.price
end
end
end
| true |
d2de051d6da5be4da92dd14f73239d86be7ec7b5 | Ruby | NikitaSmall/ruby-lessons | /vasya-bot/lib/greeter.rb | UTF-8 | 320 | 3.15625 | 3 | [] | no_license | class Greeter
def self.run(message)
{ chat_id: message.chat.id, text: message_text(message) }
end
def self.message_text(message)
case message.text.downcase
when 'hello', '/start'
"Hello, #{message.from.first_name}"
when '/stop'
"Farewell, #{message.from.first_name}"
end
end
end
| true |
83d31c0a5b35b619fad58792e53d2313de95b824 | Ruby | dantrovato/launch-school | /lesson_4/loop_experiments/double_odd_numbers.rb | UTF-8 | 1,566 | 4.84375 | 5 | [] | no_license | # We previously said that transformation is an operation that is performed on every element in the collection. In the next example, we'll study a method that only transforms a subset of the elements in the collection. Here, we only multiply by 2 if the value is odd. The if condition will only evaluate to true if current_number is odd (we check this using Integer#odd?).
#
# def double_odd_numbers(numbers)
# doubled_numbers = []
# counter = 0
#
# loop do
# break if counter == numbers.size
#
# current_number = numbers[counter]
# current_number *= 2 if current_number.odd?
# doubled_numbers << current_number
#
# counter += 1
# end
#
# doubled_numbers
# end
# Once again, note that we are working with a method that does not mutate its argument and instead returns a new array. We can call it like so
#
# my_numbers = [1, 4, 3, 7, 2, 6]
# double_odd_numbers(my_numbers) # => [2, 4, 6, 14, 2, 6]
#
# # not mutated
# my_numbers # => [1, 4, 3, 7, 2, 6]
# Exercise for the reader: What if we wanted to transform the numbers based on their position in the array rather than their value?
#
# Try coding a solution that doubles the numbers that have odd indices:
def double_odd_numbers(numbers)
counter = 0
loop do
break if counter == numbers.size
current_number = numbers[counter]
numbers[counter] *= 2 if numbers.index(current_number).odd?
counter += 1
end
numbers
end
my_numbers = [1, 4, 3, 4, 2, 6]
p double_odd_numbers(my_numbers) # => [2, 4, 6, 14, 2, 6]
# not mutated
p my_numbers
| true |
ef46cec981304aa2df85efeded3c75ef36fa82f6 | Ruby | hleeldc/jira-ticket-graph | /scripts/harvest.rb | UTF-8 | 427 | 2.859375 | 3 | [
"MIT"
] | permissive | #! /usr/bin/env ruby
require 'json'
require 'dbm'
def get_db
db_file = ARGV[0]
db = DBM::open(db_file, DBM::WRCREAT)
return db
end
def update_db(db, jira_data)
jira_data['issues'].each do |issue|
key = issue['key']
db[key] = issue.to_s
puts "--#{key}"
end
end
def test
db = get_db
file = File.open(ARGV[1])
data = JSON::load(file)
update_db(db, data)
db.each_value do |k|
puts k
end
db.close
end
test | true |
e6369b2cb84f93e35e8c0998dfcd08ab40d1fa6d | Ruby | Rockster160/Portfolio | /app/service/bowling_stats.rb | UTF-8 | 4,781 | 2.640625 | 3 | [] | no_license | class BowlingStats
def self.pickup(bowler, str_pins)
new(nil).pickup(bowler, str_pins)
end
def self.pickup_stats_by_name(bowler_name, str_pins)
new(nil).pickup_stats_by_name(bowler_name, str_pins)
end
delegate :pickup, to: :class
def initialize(league, set=nil)
@league = league
@set = set
end
def percent(num, total, round: 0)
return "N/A" unless total&.positive?
"#{((num / total.to_f)*100).round(round)}%"
end
def pickup_stats_by_name(bowler_name, str_pins)
frames = BowlingFrame.joins(:bowler).where(bowlers: { name: bowler_name })
if str_pins.nil?
[frames.where(strike: true).count, frames.count]
else
str_pins = JSON.parse(str_pins) rescue str_pins
str_pins = "[#{str_pins.sort.join(", ")}]" unless str_pins.is_a?(String)
left = frames.where(throw1_remaining: str_pins)
# tleft = frames.where(throw1_remaining: "[]", throw2_remaining: str_pins)
[left.where(spare: true).count, left.count]
end
end
def pickup(bowler, str_pins)
if str_pins.nil?
[frames(bowler).where(strike: true).count, frames(bowler).count]
else
str_pins = JSON.parse(str_pins) rescue str_pins
str_pins = "[#{str_pins.sort.join(", ")}]" unless str_pins.is_a?(String)
left = frames(bowler).where(throw1_remaining: str_pins)
# tleft = frames(bowler).where(throw1_remaining: "[]", throw2_remaining: str_pins)
[left.where(spare: true).count, left.count]
end
end
def strike_points(bowler)
frames(bowler).where(strike: true).group_by(&:strike_point).transform_values(&:count)
end
def frames(bowler)
if @set.present?
bowler.frames.joins(:set).where(bowling_sets: { id: @set.id })
else
bowler.frames
end
end
def spare_data(bowler)
[frames(bowler).where(spare: true).count, frames(bowler).where(strike: false).count]
end
def closed_games(bowler)
games = @set.present? ? bowler.games.where(set: @set) : bowler.games
closed_frame_count_sql = "
COUNT(bowling_frames.id) FILTER(
WHERE(
bowling_frames.strike IS true OR bowling_frames.spare IS true
)
)
"
closed_games = games.left_joins(:new_frames).attended.
select("bowling_games.id, #{closed_frame_count_sql} AS closed_frame_count").
having("#{closed_frame_count_sql} = 10").
group("bowling_games.id")
# map { |game_id, closed_count| game = BowlingGame.find(game_id); "https://ardesian.com/bowling/#{game.set_id}/edit?game=#{game.game_num}&bowler_id=#{game.bowler_id}" }
# .map { |c| [c.id, c.closed_frame_count] }
[closed_games.length, games.attended.count]
end
def split_conversions(bowler)
splits = frames(bowler).where(split: true)
return "N/A" if splits.none?
"#{((splits.where(spare: true).count / splits.count.to_f) * 100).round}%"
end
def split_data(bowler)
splits = frames(bowler).where(split: true)
grouped = splits.group(:throw1_remaining, :spare).count(:throw1_remaining)
counts = grouped.each_with_object({}) do |((pins, spare), count), obj|
obj[pins] ||= [0, 0]
obj[pins][0] += count if spare
obj[pins][1] += count
end.sort_by { |pins, (picked, total)| pins.length }.sort_by { |pins, (picked, total)| -total }
counts.map { |pins, (picked, total)|
{
pins: JSON.parse(pins),
picked: picked,
total: total,
ratio: "#{((picked/total.to_f)*100).round}%",
}
}
end
def set_strike_frames(set, missed=0, min=2)
set.frames.
where(throw1: 10).
joins(:game).
group("bowling_games.set_id", "bowling_games.game_num", "bowling_frames.frame_num").
count(:id).
select { |set_game_frame, num|
next if num < min
num == (set.games.attended.where(game_num: set_game_frame[1]).count - missed)
}
end
def strike_count_frames(missed=0)
return set_strike_frames(@set, missed) if @set.present?
{}.tap do |set_game_frames|
@league.sets.order(:created_at).joins(:games).distinct.each do |set|
set_game_frames.merge!(set_strike_frames(set, missed))
end
end
end
def missed_drink_frames
# ActiveRecord::Base.logger.level = 1
# ActiveRecord::Base.logger.level = 0
set_game_frames = strike_count_frames(1).keys
set_game_frames.each_with_object({}) do |(set_id, game_num, frame_num), obj|
blamed_bowler_id = BowlingFrame.joins(:game).where(
bowling_frames: { frame_num: frame_num },
bowling_games: { set_id: set_id, game_num: game_num, absent: [nil, false] }
).where.not(throw1: 10).take&.game&.bowler_id
next if blamed_bowler_id.nil?
obj[blamed_bowler_id] ||= 0
obj[blamed_bowler_id] += 1
end
end
end
| true |
67eaac8fda4e636f991f9d9a1de844f4102779be | Ruby | armi1189/ruby-kickstart | /session2/3-challenge/3_array.rb | UTF-8 | 341 | 4.125 | 4 | [
"MIT"
] | permissive | # Write a method named every_other_char for strings that,
# returns an array containing every other character
#
# example:
# "abcdefg".every_other_char # => "aceg"
# "".every_other_char # => ""
class String
def every_other_char
ret = ""
self.split('').each_with_index {|x, y| if y.even?; ret << x; end}
ret
end
end
| true |
1aa9d5b97815c52c975148c4ce4a5dc5e6d561a6 | Ruby | fmorales/flor | /lib/flor/pcore/define.rb | UTF-8 | 1,440 | 2.546875 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive |
class Flor::Pro::Define < Flor::Procedure
#
# Defines a function.
#
# In its `define` flavour, will take a function body and assign it to
# variable.
# ```
# define sum a, b # make variable 'sum' hold the function
# +
# a
# b
# # yields the function, like `fun` and `def` do
#
# sum 1 2
# # will yield 3
# ```
#
# In the `fun` and `def` flavours, the function is unnamed, it's thus not
# bound in a local variable.
# ```
# map [ 1, 2, 3 ]
# def x
# + x 3
# # yields [ 4, 5, 6 ]
# ```
#
# It's OK to generate the function name at the last moment:
# ```
# sequence
# set prefix "my"
# define "$(prefix)-sum" a b
# + a b
# ```
names %w[ def fun define ]
def execute
if i = att_children.index { |c| %w[ _dqs _sqs ].include?(c[1].first.first) }
execute_child(i)
else
receive_att
end
end
def receive_att
t = tree
cnode = lookup_var_node(@node, 'l')
cnid = cnode['nid']
fun = counter_next('funs') - 1
(cnode['closures'] ||= []) << fun
val = [
'_func',
{ 'nid' => nid, 'tree' => t, 'cnid' => cnid, 'fun' => fun },
t[2] ]
if t[0] == 'define'
name =
if @message['point'] == 'execute'
t[1].first[1].first[0]
else
payload['ret']
end
set_var('', name, val)
end
payload['ret'] = val
wrap_reply
end
end
| true |
336959b1dd58736d86c27e95dd25947eee7b69a5 | Ruby | ivanpilot/tweet | /app/lib/api_constraints.rb | UTF-8 | 497 | 2.6875 | 3 | [] | no_license | class ApiConstraints
attr_reader :version, :default
def initialize(version, default = false)
@version = version
@default = default
end
def matches?(request)
version = check_headers(request.headers) || default
# binding.pry
version
end
def check_headers(headers)
accept = headers[:accept]
accept && accept.include?("application/vnd.tweet.#{version}+json")
# @default || req.headers['Accept'].include?("application/vnd.tweet.v#{@version}")
end
end
| true |
1ad8646020d1bf6d29c4dfd66de0a48b2cdef429 | Ruby | Chanson9892/programming-univbasics-nds-green-grocer-part-1-sea01-seng-ft-082420 | /lib/grocer.rb | UTF-8 | 607 | 3.453125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def find_item_by_name_in_collection(name, collection)
index = 0
collection.each do |item|
if item[:item] == name
return item
end
index += 1
end
nil
end
def consolidate_cart(cart)
new_cart = []
cart.each do |grocery_item|
current_item = find_item_by_name_in_collection(grocery_item[:item], new_cart)
if current_item
new_cart.each do |new_cart_item|
if new_cart_item[:item] == current_item[:item]
new_cart_item[:count] += 1
end
end
else
grocery_item[:count] = 1
new_cart << grocery_item
end
end
new_cart
end
| true |
42a65d4388d1a591108e545d4f56aeab53e38b36 | Ruby | laamia/glassdoor_scraper | /lib/glassdoor_scraper/scraper.rb | UTF-8 | 1,422 | 2.609375 | 3 | [] | no_license | class GlassdoorJobs::Scraper
def self.get_page(url)
Nokogiri::HTML(open(url))
end
def self.get_job_list(url)
self.get_page(url).css("div.jobTitleContainer.cell.middle")
end
def self.create_jobs(url)
self.get_job_list(url).each do |job|
company = job.css("div.small").text
salary = job.css("div.hideDesk.meanPay.padTop.aboveRangeBar strong").text
role = job.css("div.employerSalaryInfo.tightVert a.noMargVert.jobTitle").text.strip
url = 'https://www.glassdoor.com' + job.css("div.employerSalaryInfo.tightVert a.noMargVert.jobTitle").attribute("href").value
GlassdoorJobs::Job.new(role, company, salary, url)
end
end
def self.get_job_details(company_name)
job = GlassdoorJobs::Job.all.find{|job| job.company == company_name}
job_page = get_page(job.url)
job.company_url = 'https://www.glassdoor.com' + job_page.css("div.empLinks.tbl a.eiCell.cell.overviews").attribute("href").value
company_page = get_page(job.company_url)
other_details = {}
company_page.css("div.info.flexbox.row.col-hh div.infoEntity").each do |text|
other_details[text.css("label").text] = text.css("span.value").text
end
job.company_rating = company_page.css("div.ratingNum").text
job.company_size = other_details['Size']
job.company_revenue = other_details['Revenue']
job.company_headquarters = other_details['Headquarters']
end
end
| true |
9f823acb24b3fb27c28802968a9b5ce8dcfe9def | Ruby | ZhenyingZhu/StudyNotes | /ruby-example/thread-args.rb | UTF-8 | 108 | 2.90625 | 3 | [] | no_license | #! /bin/env ruby
arr = []
a, b, c = 1, 2, 3
Thread.new(a, b, c) { |d, e, f| arr << d << e << f }.join
arr
| true |
2e249a2a3d45975e98ccb02b8ecc9e1907d7a70f | Ruby | mallibone/SeriesNamer | /lib/renamer.rb | UTF-8 | 1,629 | 2.890625 | 3 | [] | no_license | module SeriesNamer
require_relative 'find_episodes'
require_relative 'get_episode_names'
require_relative 'parse_path'
require_relative 'rename_episodes'
class Renamer
attr_reader :path, :series_info
@dir #defaults to ruby dir used for tests
@file #defaults to ruby file used for tests
def initialize( path, dir = Dir, file = File )
@dir = dir
raise ArgumentError, "Path #{path} does not exist" unless @dir.exists?( path )
@path = path
@file = file
end
def execute( file_utils = FileUtils )
@series_info = ParsePath.new(@path, @dir, @file).series_info
@series_info.add_episodes(@series_info.seasons.first, get_dir_entries)
@series_info.add_new_episodes(
@series_info.seasons.first, get_episode_names
)
rename_episodes(file_utils)
end
private
def get_dir_entries
return FindEpisodes.new(@series_info, @dir, @file).results
end
def get_episode_names
return GetEpisodeNames.new(@series_info).episode_names(
@series_info.seasons.first[@series_info.seasons.first.size-1].to_i,
@series_info.episodes(@series_info.seasons.first).size )
end
def rename_episodes(file_utils)
@series_info.seasons.each do |season|
current_episode_names = @series_info.episodes(season)
new_episode_names = @series_info.new_episodes(season)
RenameEpisodes.new(@series_info.path,
current_episode_names,
new_episode_names,
@dir).now(file_utils)
end
end
end
end
| true |
91667692f928c51c20bb8be5bd5d96fe34094418 | Ruby | aussiDavid/obvious | /spec/contract_spec.rb | UTF-8 | 1,724 | 2.796875 | 3 | [
"MIT"
] | permissive | require_relative 'spec_helper'
require_relative '../lib/obvious/contract'
describe Hash do
describe '#has_shape?' do
it 'should return true for a valid shape' do
{ id: 1 }.has_shape?(id: Fixnum).should be true
end
it 'should return false for an invalid shape' do
{ id: 1 }.has_shape?(id: String).should be false
end
it 'should retrn the invalid field if return_field flag is set' do
{ id: 1 }.has_shape?({id: String}, true).should eq [false, :id]
end
it 'should allow for nil values to be returned' do
{ id: nil }.has_shape?({id: String}).should be true
end
end
end
class TestContract < Obvious::Contract
contract_for :test, {
input: { id: Fixnum },
output: { id: Fixnum, value: String }
}
def test input
{ id: 1, value: 'this is a test' }
end
end
describe Obvious::Contract do
describe "#call_method" do
it 'should return the correct output for valid input and output shapes' do
tc = TestContract.new
result = tc.test id: 1
result.should eq id: 1, value: 'this is a test'
end
it 'should raise a contract input error with bad input' do
tc = TestContract.new
expect { tc.test Hash.new }.to raise_error ContractInputError
end
it 'should raise a DataNotFound error if {} is returned' do
tc = TestContract.new
tc.should_receive(:test_alias).and_return({})
expect { tc.test id: 1 }.to raise_error DataNotFoundError
end
it 'should raise a contract output error if nil is returned' do
tc = TestContract.new
tc.should_receive(:test_alias).and_return(nil)
expect { tc.test id: 1 }.to raise_error ContractOutputError
end
end
end
| true |
816bc0418e73732b18864f0c46f4b6655b6262ef | Ruby | ksummerill/ttt-5-move-rb-online-web-sp-000 | /lib/move.rb | UTF-8 | 663 | 4.34375 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def display_board(board)
puts " #{board[0]} | #{board[1]} | #{board[2]} "
puts "-----------"
puts " #{board[3]} | #{board[4]} | #{board[5]} "
puts "-----------"
puts " #{board[6]} | #{board[7]} | #{board[8]} "
end
# code your input_to_index
# converts a user_input to an integer ("5" becomes 5)
# subtracts 1 from the user_input
# returns -1 for strings without integers
def input_to_index(input)
# convert input to integer and subtracts 1
input.to_i - 1
end
# # code the move method here!
# # take integer and convert to board position (5 becomes position 4)
def move(array, index, character = "X")
array[index] = character
end
| true |
d5d2ce5992c2d0b19cbc21a058df45a61eeabfb1 | Ruby | aahmad94/algorithm_projects | /05_binary_search_tree/lib/binary_search_tree.rb | UTF-8 | 2,988 | 3.46875 | 3 | [] | no_license | # There are many ways to implement these methods, feel free to add arguments
# to methods as you see fit, or to create helper methods.
require 'bst_node'
class BinarySearchTree
attr_reader :root
def initialize
@root = nil
end
def insert(value)
unless @root
@root= BSTNode.new(value)
return @root
end
current_node = @root
loop do
if current_node.left && value <= current_node.value
current_node = current_node.left
elsif current_node.right && value > current_node.value
current_node = current_node.right
else
break
end
end
value <= current_node.value ?
current_node.left = BSTNode.new(value) :
current_node.right = BSTNode.new(value)
end
def find(value, tree_node = @root)
return tree_node if tree_node.value == value
if value <= tree_node.value
return nil unless tree_node.left
find(value, tree_node.left)
else
return nil unless tree_node.right
find(value, tree_node.right)
end
end
def delete(value)
target = self.find(value)
target_position = "#{target.rel_pos}="
parent = target.parent
if target.count == 0
# if no children
# set target to nil if root, otherwise set itself to nil
return @root = nil if target == @root
parent.send(target_position, nil)
elsif target.count == 1
# if 1 child
# set the target position equal to that of it's child
parent.send(target_position, target.first_child)
else
# if 2 children:
# pick the largest value from the left tree (lower val than parent)
# if replacement has left child (only possibility), we want to append it directly to replacement's parent right branch
replacement = maximum(target.left)
replacement_parent = replacement.parent
replacement_child = replacement.left
replacement_parent.right = replacement_child
# swap
parent.send(target_position, replacement)
end
end
# helper method for #delete:
def maximum(tree_node = @root)
while tree_node.right
tree_node = tree_node.right
end
tree_node
end
def depth(tree_node = @root)
depth = 0
if tree_node.count > 0
depth += 1
tree_depths = tree_node.child_nodes.map do |child_node|
depth(child_node)
end
depth += tree_depths.max
end
depth
end
def is_balanced?(tree_node = @root)
return true if depth(tree_node) <= 1
left = depth(tree_node.left)
right = depth(tree_node.right)
difference = (left - right).abs
difference <= 1 && is_balanced?(tree_node.left) && is_balanced?(tree_node.right)
end
def in_order_traversal(tree_node = @root, arr = [])
in_order_traversal(tree_node.left, arr) if tree_node.left
arr << tree_node.value
in_order_traversal(tree_node.right, arr) if tree_node.right
arr
end
private
# optional helper methods go here:
end
| true |
8638b3a7314ec134371592d931cfd4f542a6791c | Ruby | Shopify/giffy | /lib/giffy/pipeline.rb | UTF-8 | 316 | 2.8125 | 3 | [
"MIT"
] | permissive | module Giffy
class Pipeline
attr_reader :processors
def initialize(processors)
@processors = processors
end
def process(input, options)
processors.reduce(input) do |input, processor|
instance = processor.new(options)
instance.process(input)
end
end
end
end
| true |
e53b6a037ad3ae74e3987ca1226ad7722707f3e1 | Ruby | ozeron/casting | /test/actor_test.rb | UTF-8 | 520 | 2.8125 | 3 | [
"MIT"
] | permissive | require 'minitest/autorun'
require_relative '../src/actor'
class ActorTest < MiniTest::Unit::TestCase
def setup
@speech = Casting::Speech.new "Great Title", "Great Text"
@actor = Casting::Actor.new :m, 20, @speech
end
def test_new_initialize
title = "Thats "
text = "it!"
@act = Casting::Actor.new :f,18, title, text
assert_equal @act.speech, Casting::Speech.new( title,text)
end
def test_speech
assert_equal @speech, @actor.speech
end
def test_gender
assert_equal :male, @actor.gender
end
end
| true |
1dc9453d5417075845da58271fd3b24a8a8aa300 | Ruby | KhalilC/collections_practice_vol_2-001-prework-web | /collections_practice.rb | UTF-8 | 1,068 | 3.453125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | # your code goes here
def begins_with_r(collection)
collection.all? {|tool| tool[0] == 'r' }
end
def contain_a(collection)
collection.select {|word| word.include?('a')}
end
def first_wa(collection)
collection.each {|word| return word if word[0..1] == "wa"}
end
def remove_non_strings(collection)
collection.select {|word| word.is_a?(String)}
end
def count_elements(collection)
counted_objects = []
collection.each do |element|
element[:count] = collection.count(element)
counted_objects << element
collection.delete(element)
end
counted_objects
end
def merge_data(keys, data)
new_array = []
keys.each do |key|
data.each do |info|
new_array << key.merge!(info[key.values[0]])
end
end
new_array
end
def find_cool(cool)
answer = []
cool.each {|hash| answer << hash if hash.values.include?("cool") }
answer
end
def organize_schools(schools)
organized_schools = Hash.new { |key, value| key[value] = [] }
schools.each {|school| organized_schools[school[1].values[0]] << school[0] }
organized_schools
end | true |
3c86fdac20304257f6666ce0715c4ac596cdcec2 | Ruby | lechris1/theodinproject | /webdevelopment101/projecteuler/prob2.rb | UTF-8 | 177 | 3.28125 | 3 | [] | no_license | sum = 0
n1, n2 = 1, 2
next_num = n1+n2
sum += n2
while next_num < 4000000
if next_num%2==0
sum += next_num
end
n1 = n2
n2 = next_num
next_num = n1+n2
end
puts sum
| true |
e934fb3f84a9cd71844856a0f37bfe19596902a3 | Ruby | amitdoshi93/SimpleStartupNameGenerator | /generate.rb | UTF-8 | 768 | 3.578125 | 4 | [] | no_license | def startup
puts "Enter the number of letters you want in your startup name:"
n_letters = gets.chomp.to_i
end
n_letters = startup
unless n_letters>1
puts "The number should be more than 1!"
n_letters = startup
end
puts "Now enter positions where you want your vowels starting from 1"
vowels = gets.chomp().split(",")
vowels_list = %w{a e i o u}
alphabets = ('a'..'z').to_a
alphabets = alphabets - vowels_list
begin
arr=[]
vowels.each do |x|
x=x.to_i-1
arr[x]=vowels_list.sample
end
i = 1
loop do
if not vowels.include? i.to_s
arr[i-1]=alphabets.sample.to_s
end
if i == n_letters
break
end
i+=1
end
puts arr.join
puts "Are you happy? (yes|y|no|n)"
ans = gets.chomp
ans = (ans=="yes"||ans=="y") ? false : true
end while ans
| true |
9ac1046fe3c375c2b40dcc63f2fd891c8d5c3936 | Ruby | Markentoine/codewars | /ruby/airstrike.rb | UTF-8 | 1,906 | 4.03125 | 4 | [] | no_license | =begin
Introduction
There is a war and nobody knows - the alphabet war!
There are two groups of hostile letters.
The tension between left side letters and right side letters was too high and the war began.
The letters called airstrike to help them in war - dashes and dots are spreaded everywhere on the battlefield.
Task
Write a function that accepts fight string consists of only small letters and * which means a bomb drop place.
Return who wins the fight.
When the left side wins return Left side wins!,
when the right side wins return Right side wins!, in other case return Let's fight again!.
The left side letters and their power:
w - 4
p - 3
b - 2
s - 1
The right side letters and their power:
m - 4
q - 3
d - 2
z - 1
The other letters don't have power and are only victims.
The * bombs kills the adjacent letters ( i.e. aa*aa => a___a, **aa** => ______ );
Example
AlphabetWar("s*zz"); //=> Right side wins!
AlphabetWar("*zd*qm*wp*bs*"); //=> Let's fight again!
AlphabetWar("zzzz*s*"); //=> Right side wins!
AlphabetWar("www*www****z"); //=> Left side wins!
=end
def alphabet_war(fight)
forces = ['w', 'p', 'b', 's', 'm', 'q', 'd', 'z'].zip([-4, -3, -2, -1, 4, 3, 2, 1]).to_h
sub = fight.gsub(/[a-z](?=\*)/, '').gsub(/(?<=\*)[a-z]/, '').gsub('*', '')
fight = sub.chars.map { |char| forces.keys.include?(char) ? forces.fetch(char) : 0 }.reduce(:+)
if fight.nil?
"Let's fight again!"
elsif fight.negative?
"Left side wins!"
elsif fight.positive?
"Right side wins!"
else
"Let's fight again!"
end
end
#other solutions
def alphabet_war(fight)
left, right = fight.gsub(/.?\*+.?/, '').tr('sbpwzdqm', '12345678')
.chars.map(&:to_i).partition { |n| n < 5 }
result_idx = left.reduce(0, :+) <=> right.map { |n| n - 4 }.reduce(0, :+)
["Let's fight again!", 'Left side wins!', 'Right side wins!'][result_idx]
end
| true |
817010386088ee2ea6f2384fec68f9f09347a43a | Ruby | mindless/dm-sinatra-security | /lib/sinatra/security/login_field.rb | UTF-8 | 1,738 | 2.71875 | 3 | [
"MIT"
] | permissive | module Sinatra
module Security
# This module allows you to customize the name of the login field used
# in your datastore. By default :email is used.
#
# @example
#
# # somewhere in your code during bootstrapping
# require 'sinatra/security'
# Sinatra::Security::LoginField.attr_name :login
#
# # then in your actual user.rb or something...
# class User < Ohm::Model
# include Sinatra::Security::User
# # at this point the following are done:
# # attribute :login
# # index :login
# end
module LoginField
EMAIL_FORMAT = /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i
# @example
#
# Sinatra::Security::LoginField.attr_name :username
#
# class User < Ohm::Model
# include Sinatra::Security::User
# # effectively executes the following:
# # attribute :username
# # index :username
# end
#
# @overload attr_name()
# Get the value of attr_name.
# @overload attr_name(attr_name)
# @param [#to_sym] attr_name the attr_name to be used e.g.
# :username, :login.
# @return [Symbol] the current attr_name.
def self.attr_name(attr_name = nil)
@attr_name = attr_name.to_sym if attr_name
@attr_name
end
attr_name :email
def self.included(user)
if @attr_name == :email
user.property LoginField.attr_name, String, :unique => true, :required => true, :format => EMAIL_FORMAT. :length => 100
else
user.property LoginField.attr_name, String, :unique => true, :required => true
end
end
end
end
end
| true |
ad5b691d3bfc4737b90b0889fd8250fd9dc6cc47 | Ruby | Bonemind/D3Edps | /edps.rb | UTF-8 | 1,468 | 3.296875 | 3 | [] | no_license | # Weapon damage values
min_weapon = 1398
max_weapon = 1813
#Off-hand damage values
min_offhand = 461
max_offhand = 570
# Effective weapon damage
weapon_damage = ((min_weapon + min_offhand + max_weapon + max_offhand)/2.0)
# Primary stat (Int, Dex, etc.)
primary_stat = 10102
# Attack speed
attack_speed = 1.4
# The base weapon damage
base_damage = weapon_damage * (primary_stat / 100.0)
# Base actual damage, i.e attacks for base_damage per second
edps_base = base_damage * attack_speed
# Crit chance
chc = 38.0
# Crit damage
chd = 395.0
# Primary skill damage modifier
pskill_damage = 400
# Prints numbers in a more sensible way
# TODO: Actually do what is said above
def human_readable_number(number)
return number.to_s
number.to_s.reverse.gsub(/(\d{3})(?=\d)/, '\\1,').reverse
end
# Base damage modified for crits
total_crit_damage = (((chc / 100.0) * (chd / 100.0)) + 1.0) * base_damage
# Outputs
puts "Base damage: " << (human_readable_number base_damage)
puts "Effective base damage :" << (human_readable_number edps_base)
puts "Crit damage base: " << total_crit_damage.to_s
# Damage value, should map to sheet dps
damage = (human_readable_number total_crit_damage * attack_speed)
puts "Damage: " << damage
# Theoretical damage values of primary skill
#pskill_base_damage = edps_base * (pskill_damage / 100.0)
#pskill_crit_damage = damage * (pskill_damage / 100.0)
#puts "Primary skill base damage: " << (human_readable_number pskill_base_damage)
| true |
fb4e3442e332fe0af0056e3a30b2efe68d46f71e | Ruby | chuck0523/atCoder | /practise-ruby/inject-array.rb | UTF-8 | 100 | 3.109375 | 3 | [] | no_license | array = [1, 2, 3]
puts [1, 1, 1].inject(array) {|sum_array, a| sum_array << a}
# [1, 1, 1, 1, 2, 3]
| true |
b6a9b50ec1f0312a1a1e3fa0725fda06505ec81d | Ruby | RudeWalrus/PatentAgent | /spec/patentagent/patentagent_spec.rb | UTF-8 | 1,725 | 2.765625 | 3 | [] | no_license | require 'spec_helper'
module PatentAgent
describe PatentAgent do
context "#validate_patent_numbers" do
let(:all_good) { %w[US5551212 6661113 us8081555.b1 Us7776655.A1] }
let(:all_bad) { %w[US9551212 661113 2081555.b1 b3] }
it "accepts an array, returns array" do
result = PatentAgent.validate_patent_numbers(all_good)
expect(result).to be_kind_of(Array)
end
it "accepts a string, returns a string" do
mixed = all_good + all_bad
result = PatentAgent.validate_patent_numbers("US5551212")
expect(result).to eq("US5551212")
expect(result).to be_kind_of(String)
end
it "accepts several strings, returns array" do
mixed = all_good + all_bad
result = PatentAgent.validate_patent_numbers("US5551212", "6661113")
expect(result).to include("US5551212", "6661113")
expect(result).to be_kind_of(Array)
end
it "accepts good array list" do
result = PatentAgent.validate_patent_numbers(all_good)
expect(result).to eq(all_good)
end
it "rejects bad array list" do
result = PatentAgent.validate_patent_numbers(all_bad)
expect(result).to be_empty
end
it "returns only good values" do
mixed = all_good + all_bad
result = PatentAgent.validate_patent_numbers(mixed)
expect(result).to eq(all_good)
end
it "list with commas" do
inp = %w[7,308,060 B1 7,342,942 B1 7,142,564 B1 7,369,574 B1 7,327,760 B1]
out = %w[7,308,060 7,342,942 7,142,564 7,369,574 7,327,760]
result = PatentAgent.validate_patent_numbers(inp)
expect(result).to eq(out)
end
end
end
end | true |
35f79c6d1ed053610c43095cd0c269e419df4a0e | Ruby | Garima1125/ruby-maths-game | /main.rb | UTF-8 | 1,710 | 3.796875 | 4 | [] | no_license | require_relative 'player'
require_relative 'question'
#REPL + game logic
@repl_bool = true
#0 for p1 1 for p2
@turn = 0
puts "Welcome to ruby_math_game (OOP edition)"
puts
print 'Player 1 name: '
@username = gets.chomp
p1 = Player.new(@username)
p1.name = p1.name
print 'Player 2 name: '
@username = gets.chomp
p2 = Player.new(@username)
p2.name = p2.name
puts
puts "let's begin."
puts
while @repl_bool
question = Question.new
case @turn
when 0
print "#{p1.name}: "
else
print "#{p2.name}: "
end
print question.to_string
@user_input = gets.chomp.to_i
if @turn == 0 && question.is_correct?(@user_input)
puts "CORRECT!"
p1.gain_point
@turn += 1
elsif @turn == 0 && !question.is_correct?(@user_input)
puts "WRONG!"
p1.lose_life
@turn += 1
elsif @turn == 1 && question.is_correct?(@user_input)
puts "CORRECT!"
p2.gain_point
@turn -= 1
elsif @turn == 1 && !question.is_correct?(@user_input)
puts "WRONG!"
p2.lose_life
@turn -= 1
end
puts
puts "The score so far:
#{p1.name}: #{p1.correct_answers} CORRECT ANSWERS #{p1.lives} REMAINING LIVES
#{p2.name}: #{p2.correct_answers} CORRECT ANSWERS #{p2.lives} REMAINING LIVES"
puts
if p1.lives < 1 || p2.lives <1
puts "-----Game OVER------"
if p1.lives < 1
puts "Congratulations!!#{p2.name} you won the game!"
elsif p2.lives < 1
puts "Congratulations!!#{p1.name} you won the game!"
end
puts "The final score was:
#{p1.name}: #{p1.correct_answers} CORRECT ANSWERS #{p1.lives} REMAINING LIVES
#{p2.name}: #{p2.correct_answers} CORRECT ANSWERS #{p2.lives} REMAINING LIVES"
@repl_bool = false
end
end | true |
36a27611bf709ca9cc86332b84f6907146572f34 | Ruby | Snerzel/programming-univbasics-4-square-array-online-web-prework | /lib/square_array.rb | UTF-8 | 186 | 3.03125 | 3 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | def square_array(array)
# your code here
new_numbers = []
counter = 0
while counter < array.length do
new_numbers << array[counter] ** 2
counter += 1
end
return new_numbers
end
| true |
9a0c01606a767d14da513d225aaef65b8966dd05 | Ruby | loriculberson/chisel | /lib/document_splitter.rb | UTF-8 | 130 | 2.703125 | 3 | [] | no_license | class DocumentSplitter
attr_reader :doc
def initialize(doc)
@doc = doc
end
def to_a
doc.split("\n\n")
end
end | true |
efb2c802f7b83926c31ecadcbbdaa5c48a9549e4 | Ruby | andywenk/page_performance | /lib/page_performance/utils/prerequisites.rb | UTF-8 | 538 | 2.578125 | 3 | [
"Apache-2.0"
] | permissive | module PagePerformance
module Utils
# check if everything in the environment is available to start the program
class Prerequisites
class << self
def check_prerequisites
ruby_version
phantomjs_available
end
def ruby_version
raise PagePerformance::Error::RubyVersion unless `ruby -v` =~ /2.2.*/
end
def phantomjs_available
raise PagePerformance::Error::Phantomjs unless `which phantomjs` =~ /phantomjs/
end
end
end
end
end | true |
a1ac6214c68b6f78599d9bffdac780b4d4fa6059 | Ruby | kaidee/kaidee | /ruby/test.rb | UTF-8 | 60 | 2.765625 | 3 | [] | no_license | puts "#{1.0e3}"
# puts "0b10"
50.step(80,5){|i| print i," "} | true |
fe908240826deeca516f35bc576ce4d614387997 | Ruby | abracadabra89/rails-cru-form_for-lab-nyc-web-091619 | /db/seeds.rb | UTF-8 | 758 | 2.515625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | # 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 rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
kanye = Artist.create(name: "Kanye", bio: "I'm the Yeezy")
britney = Artist.create(name:"Briney Spears", bio: "It's Britney, b..ch!")
elton = Artist.create(name:"Elton John", bio:"Call me Sir")
hip_hop = Genre.create(name:"hip hop")
pop = Genre.create(name:"pop")
rock = Genre.create(name: rock)
# stronger = Song.create(kanye.id, hip_hop.id)
# oops = Song.create(britney.id, pop.id)
# leon = Song.create(elton.id, rock.id)
| true |
ef21699a7015c1d0b3607e1a6b8a514f71b5b14c | Ruby | jrharper224/RoR_April_2017 | /WilliamBlackwell/wiz_nin_sam/human.rb | UTF-8 | 380 | 3.53125 | 4 | [] | no_license | class Human
attr_accessor :strength, :intelligence, :health, :stealth
def initialize strength=3, intelligence=3, stealth=3, health=100
@strength = strength
@intelligence = intelligence
@stealth = stealth
@health = health
end
def attack(obj)
if obj.class.ancestors.include?(Human)
obj.health -= 10
true
else
false
end
end
end | true |
6d1ca24aa6e3d45de0c5b9b566d2dd06dd02017b | Ruby | aws/aws-sdk-ruby | /gems/aws-sdk-core/spec/aws/token_spec.rb | UTF-8 | 846 | 2.515625 | 3 | [
"Apache-2.0"
] | permissive | # frozen_string_literal: true
require_relative '../spec_helper'
module Aws
describe Token do
it 'provides access to the token' do
expect(Token.new('token').token).to eq('token')
end
it 'defaults the expiration nil' do
expect(Token.new('token').expiration).to be(nil)
end
it 'provides access to the expiration' do
expiration = Time.now
expect(Token.new('token', expiration).expiration).to be(expiration)
end
describe '#set?' do
it 'returns true when the token is a non nil value' do
expect(Token.new('token').set?).to be(true)
end
it 'returns false if the token is nil' do
expect(Token.new(nil).set?).to be(false)
end
it 'returns false if the token is empty' do
expect(Token.new('').set?).to be(false)
end
end
end
end
| true |
a3e40eeba1cda294275884176e5c0b875c946f4a | Ruby | aman199002/Data-Structures-and-Algorithms-in-Ruby | /searching/first_bad_version.rb | UTF-8 | 513 | 3.546875 | 4 | [] | no_license | # The is_bad_version API is already defined for you.
# @param {Integer} version
# @return {boolean} whether the version is bad
# def is_bad_version(version):
# @param {Integer} n
# @return {Integer}
def first_bad_version(n)
left = 1
right = n
while right > left do
mid = left + (right - left)/2
puts "left=#{left} right=#{right} mid = #{mid}"
if is_bad_version(mid)
right = mid
else
left = mid+1
end
end
left
end | true |
7f9c3db524e6a8feb19d8b6cd0e87cf8623c0cec | Ruby | booglysticks/ruby-tests | /kidsort.rb | UTF-8 | 666 | 4.5 | 4 | [] | no_license | # a little programme to find scattered children and line them up
# array of children
children = ['Titus', 'Angelica', 'Henry', 'Max', 'Alice', 'Hank', 'John', 'Ghost']
# sort array
puts 'I found these children'
puts children
# finding more children, until there are none left
while true
puts 'Did you find any more children?'
newchild = gets.chomp
if newchild.downcase == 'no'
break
else
children.push newchild
end
end
puts 'Ok, is that your lot? Line up in order, kids'
puts children.sort
# current state, no ends game instead of lining up kids
# current state 2 adding a kids name brings up alphabetised list, instead of just asking again.
| true |
200bcc95c8bc06cfdaaf4eab8a06be872555d4b8 | Ruby | honorarac/vagrant | /plugins/commands/plugin/action/expunge_plugins.rb | UTF-8 | 2,280 | 2.53125 | 3 | [
"MIT"
] | permissive | require "vagrant/plugin/manager"
module VagrantPlugins
module CommandPlugin
module Action
# This middleware removes user installed plugins by
# removing:
# * ~/.vagrant.d/plugins.json
# * ~/.vagrant.d/gems
# Usage should be restricted to when a repair is
# unsuccessful and the only reasonable option remaining
# is to re-install all plugins
class ExpungePlugins
def initialize(app, env)
@app = app
end
def call(env)
if !env[:force]
result = nil
attempts = 0
while attempts < 5 && result.nil?
attempts += 1
result = env[:ui].ask(
I18n.t("vagrant.commands.plugin.expunge_confirm") +
" [N]: "
)
result = result.to_s.downcase.strip
result = "n" if result.empty?
if !["y", "yes", "n", "no"].include?(result)
result = nil
env[:ui].error("Please answer Y or N")
else
result = result[0,1]
end
end
if result != 'y'
abort_action = true
end
end
if !abort_action
files = []
dirs = []
# Do not include global paths if local only
if !env[:env_local_only] || env[:global_only]
files << Vagrant::Plugin::Manager.instance.user_file.path
dirs << Vagrant::Bundler.instance.plugin_gem_path
end
# Add local paths if they exist
if Vagrant::Plugin::Manager.instance.local_file && (env[:env_local_only] || !env[:global_only])
files << Vagrant::Plugin::Manager.instance.local_file.path
dirs << Vagrant::Bundler.instance.env_plugin_gem_path
end
# Expunge files and directories
files.find_all(&:exist?).map(&:delete)
dirs.find_all(&:exist?).map(&:rmtree)
env[:ui].info(I18n.t("vagrant.commands.plugin.expunge_complete"))
@app.call(env)
else
env[:ui].info(I18n.t("vagrant.commands.plugin.expunge_aborted"))
end
end
end
end
end
end
| true |
0f3421b94bcdf0b96a59346301b1b6b023843957 | Ruby | minhajuddin/sessions2 | /ruby/def2.rb | UTF-8 | 207 | 3.625 | 4 | [] | no_license | def exec
f = Dog.new("Fido")
f.bark_twice
end
class Dog
def initialize(n)
@name = n
end
def bark_twice
bark
bark
end
def bark
puts @name + " says woof woof"
end
end
exec
| true |
d32d1dd5c2e2d1ad0dec38e852e95e1bbd5ef18f | Ruby | driscoll-brook-press/book-compiler | /lib/dbp/book_compiler/scriv2tex.rb | UTF-8 | 2,111 | 2.625 | 3 | [
"MIT"
] | permissive | require 'dbp/scrivener/project'
require 'dbp/book_compiler/util/cli'
require 'open3'
require 'yaml'
module DBP
module BookCompiler
class Scriv2TeX
include Open3
include CLI
HEADINGS = %w(wtf chapter scene)
def initialize
super 'scriv2tex'
end
def run
parse_command_line do |operands|
complain unless operands.length == 2
@mss_source = Pathname(operands.shift)
@manuscript_dir = Pathname(operands.shift) / 'manuscript'
end
scrivener = DBP::Scrivener::Project.new(@mss_source)
write_listing_file(scrivener)
write_tex_files(scrivener)
end
def declare_options(p)
p.banner << ' file dir'
end
def check_options(errors)
errors << "No such scrivener file: #{@mss_source}" unless @mss_source.directory?
end
def write_tex_files(scrivener)
scrivener.documents.each { |document| write_tex_file(document) }
end
def write_tex_file(document)
tex_path(document).open('w') do |f|
f.puts tex_header(document)
f.write tex_content(document)
end
end
private
def tex_content(document)
capture2('rtf2tex', document.rtf_path.to_s).first
end
def tex_path(document)
@manuscript_dir / document.path.sub_ext('.tex')
end
def tex_header(document)
header = document.header
[
'\markdown{---}',
guide(header),
heading(header),
'\markdown{---}'
]
end
def heading(header)
"\\#{HEADINGS[header['depth']]}{#{header['title']}}"
end
def guide(header)
'\\markdown{guide: start}' if header['position'] == 1 && header['depth'] == 1
end
def write_listing_file(scrivener)
listing_file = @manuscript_dir / '_listing.yaml'
listing_file.dirname.mkpath
listing_file.open('w') do |l|
l.puts scrivener.documents.map { |doc| doc.path.sub_ext('').to_s }.to_yaml
end
end
end
end
end | true |
8a2f15088a7e4f9ff9b4eb259d13929a15222e4b | Ruby | mcwaller422/Intro_to_Ruby | /FlowControl/exercises/ex3.rb | UTF-8 | 260 | 4.15625 | 4 | [] | no_license | puts "Write a number, please"
number = gets.chomp.to_i
if number <=50
puts "Your number is less than, or equal to 50!"
elsif (number >50) && (number <100)
puts "Your number is between 51 and 100!"
else
puts "Your number is greater than 100!"
end
| true |
72b5bbd16c23d365cf4dde3be3b7c3a6d8a92578 | Ruby | michaelurquhart79/loops-and-hashes-lab- | /my_functions.rb | UTF-8 | 444 | 3.484375 | 3 | [] | no_license | def add_array_lengths (array1, array2)
array_plus_array = array1.length.to_i + array2.length.to_i
return array_plus_array
end
def sum_array(numbers)
counter = 0
for number in numbers
counter += number
end
return counter
end
def find_item(array, item)
for house in array
if house == item
return true
end
end
return false
end
def get_first_key(hash)
first_hash = hash.keys[0]
return first_hash
end
| true |
bd16192b3c60b20089d109e505f33ea94fd78e03 | Ruby | mkim4247/nyc-pigeon-organizer-dc-web-100818 | /nyc_pigeon_organizer.rb | UTF-8 | 693 | 3.078125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def nyc_pigeon_organizer(data)
pigeon_hash = {}
data.each do |main_stat, stat_name|
stat_name.each do |attribute, array|
array.each do |name|
pigeon_hash[name] = {:color => [], :gender => [], :lives => []}
end
end
end
data[:color].each do |color_name, pig_array|
pig_array.each do |name|
pigeon_hash[name][:color] << color_name.to_s
end
end
data[:gender].each do |sex, pig_array|
pig_array.each do |name|
pigeon_hash[name][:gender] << sex.to_s
end
end
data[:lives].each do |loc, pig_array|
pig_array.each do |name|
pigeon_hash[name][:lives] << loc.to_s
end
end
pigeon_hash
end
| true |
6e291c9fac34e184a5f3c35901a67e38dabbb258 | Ruby | alextfish/free-dom | /app/models/hinterlands/silk_road.rb | UTF-8 | 425 | 2.71875 | 3 | [] | no_license | class Hinterlands::SilkRoad < Card
victory {player.cards.select(&:is_victory?).count / 4}
costs 4
card_text "Victory (cost: 4) - Worth 1 point for every 4 Victory cards in your deck (round down)."
pile_size {|num_players| case num_players
when 1..2
8
when 3..6
12
end}
end | true |
15e988bae8696cf97b075b92c10656cb3f7e70b2 | Ruby | rlee0525/Algorithms | /LeetCode/Problems/010_is_match.rb | UTF-8 | 2,358 | 3.640625 | 4 | [] | no_license | # '.' Matches any single character.
# '*' Matches zero or more of the preceding element.
# The matching should cover the entire input string (not partial).
# The function prototype should be:
# bool isMatch(const char *s, const char *p)
# Some examples:
# isMatch("aa","a") → false
# isMatch("aa","aa") → true
# isMatch("aaa","aa") → false
# isMatch("aa", "a*") → true
# isMatch("aa", ".*") → true
# isMatch("ab", ".*") → true
# isMatch("aab", "c*a*b") → true
def is_match(string, pattern)
return string.empty? if pattern.empty?
if pattern[1] == "*"
is_match(string, pattern[2..-1]) || !string.empty? && (string[0] == pattern[0] || pattern[0] == ".") && is_match(string[1..-1], pattern)
else
!string.empty? && (string[0] == pattern[0] || pattern[0] == '.') && is_match(string[1..-1], pattern[1..-1])
end
end
# Recursive - TLE solution
# class Solution {
# public:
# bool isMatch(string s, string p) {
# /**
# * f[i][j]: if s[0..i-1] matches p[0..j-1]
# * if p[j - 1] != '*'
# * f[i][j] = f[i - 1][j - 1] && s[i - 1] == p[j - 1]
# * if p[j - 1] == '*', denote p[j - 2] with x
# * f[i][j] is true iff any of the following is true
# * 1) "x*" repeats 0 time and matches empty: f[i][j - 2]
# * 2) "x*" repeats >= 1 times and matches "x*x": s[i - 1] == x && f[i - 1][j]
# * '.' matches any single character
# */
# int m = s.size(), n = p.size();
# vector<vector<bool>> f(m + 1, vector<bool>(n + 1, false));
# f[0][0] = true;
# for (int i = 1; i <= m; i++)
# f[i][0] = false;
# // p[0.., j - 3, j - 2, j - 1] matches empty iff p[j - 1] is '*' and p[0..j - 3] matches empty
# for (int j = 1; j <= n; j++)
# f[0][j] = j > 1 && '*' == p[j - 1] && f[0][j - 2];
# for (int i = 1; i <= m; i++)
# for (int j = 1; j <= n; j++)
# if (p[j - 1] != '*')
# f[i][j] = f[i - 1][j - 1] && (s[i - 1] == p[j - 1] || '.' == p[j - 1]);
# else
# // p[0] cannot be '*' so no need to check "j > 1" here
# f[i][j] = f[i][j - 2] || (s[i - 1] == p[j - 2] || '.' == p[j - 2]) && f[i - 1][j];
# return f[m][n];
# }
# }; | true |
0ec2454d584ab9872623a4ddeb16496c15812874 | Ruby | joshnevius/badges-and-schedules-v-000 | /conference_badges.rb | UTF-8 | 558 | 3.703125 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def badge_maker(name)
return "Hello, my name is #{name}."
end
attendees = ["Edsger", "Ada", "Charles", "Alan", "Grace", "Linus", "Matz"]
def batch_badge_creator(attendees)
attendees.collect do |name|
badge_maker(name)
end
end
def assign_rooms(attendees)
attendees.each_with_index.map do |name, num|
"Hello, #{name}! You'll be assigned to room #{num+1}!"
end
end
def printer(attendees)
batch_badge_creator(attendees).each do |name|
puts "#{name}"
end
assign_rooms(attendees).each do |message|
puts "#{message}"
end
end
| true |
d55ac5990dd28b1f0c6299f344d9f4c01447c0bb | Ruby | Jschles1/ttt-with-ai-project-v-000 | /lib/players/human.rb | UTF-8 | 249 | 3.203125 | 3 | [] | no_license | module Players
# Inherits from Player.
class Human < Player
# Asks the user for input and returns it.
def move(board)
print "Where would you like to move (1-9)? "
move_input = gets.chomp
move_input
end
end
end
| true |
5210278d1be2b6e3ea39904d571045baf4513dee | Ruby | iomelchenko/diff | /diff.rb | UTF-8 | 733 | 2.890625 | 3 | [] | no_license | class Diff
def initialize(compared_objects)
@compared_objects = compared_objects
end
def execute
show_result(sdiff_object)
end
def show_result(sdiff_object)
sdiff_object.each do |line|
line_number = (line.old_position + 1).to_s
if line.changed?
puts line_number + ' ' + '* ' + line.old_element + '|' + line.new_element
elsif line.adding?
puts ' ' + '+ ' + line.new_element
elsif line.deleting?
puts line_number + ' ' + '- ' + line.old_element
else
puts line_number.to_s + ' ' + ' ' + line.old_element
end
end
end
private
def sdiff_object
@sdiff_object = Diff::LCS.sdiff @compared_objects[0], @compared_objects[1]
end
end
| true |
212d6d70af1ad0f7730b7ffd562676ef1c360b92 | Ruby | jwworth/exercism | /ruby/resistor-color-duo/resistor_color_duo.rb | UTF-8 | 242 | 2.71875 | 3 | [] | no_license | module ResistorColorDuo
extend self
COLORS = %w[black brown red orange yellow green blue violet grey white].freeze
def value(colors)
first, second = colors[0..1]
[COLORS.index(first), COLORS.index(second)].join.to_i
end
end
| true |
6b41eec095eb6293a815f856b9bda0e1c1eb0257 | Ruby | taoliu12/arrays_and_iteration-lecture | /arrays_and_iteration.rb | UTF-8 | 2,131 | 4.8125 | 5 | [] | no_license | require "pry"
## What is an ARRAY?
# An array is an ordered list of elements (such as: numbers, strings, other arrays, etc)
# Making an Array
my_array = ["hey there", "everyone", "howdy", "neighbor"]
# Accessing an Item in the Array
my_array[0] #=> "hey there"
my_array[1] #=> "everyone"
## What if I want to change the array?
# The following are DESTRUCTIVE ARRAY METHODS
# change an element in the array:
my_array[0] = "hi"
# add an item to the end of the array
my_array.append("Flanders")
my_array.push("Flanders")
my_array << "Flanders"
# binding.pry
# add an item to the beginning of the array
my_array.insert(0, "Hello")
my_array.insert(1, "Hello")
my_array.unshift("HEY")
# remove item from end of array
my_array.pop
# remove item from beginning
my_array.shift
## The following are NON-DESTRUCTIVE ARRAY METHODS
# grab only a section of an array
index = 0
number_of_items_to_grab = 3
my_array.slice(index, number_of_items_to_grab)
## HELPFUL ARRAY METHODS
# checking length of an array
array = [1,2,3,4,5,6,7,8]
array.length
array.size
array.count
# check if item is included?
array.include?(4) #=> true
array.include?(9) #=> false
# joining array into a string (non-destructive)
letters = ['h', 'e', 'l', 'l', 'o', '!']
letters.join("-")
# binding.pry
# string convert into an array (non-destructive)
string = "hello"
string.split("")
str2 = "Hi,There,Homer,Simpson"
str2.split(",")
# only retain unique item (non-destructive)
shopping_list = ["Milk", "Chocolate", "Tomato", "Tomato"]
shopping_list.uniq #=> ["Milk", "Chocolate", "Tomato"]
### ITERATORS
# each
array = [1,2,3,4]
array.each do |number|
puts number + 2
end
#returns the original array
# collect/map
array2 = array.collect do |number|
number + 2
end
#returns the modified array
# if you want to find an element inside an array, use .find or .detect
# find/detect grabs a single element in array
str = ["Homer", "Marge", "Maggie", "Lisa", "Bart"]
binding.pry
str.find do |name|
name == "Marge"
end
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
numbers.select do |n|
n.even?
end
# https://ruby-doc.org/core-2.7.0/Array.html
| true |
8912a5c2d1e2c04ca33d505f3b375686ade1f862 | Ruby | joeyates/imap-backup | /lib/imap/backup/file_mode.rb | UTF-8 | 280 | 2.546875 | 3 | [
"MIT",
"JSON"
] | permissive | module Imap; end
module Imap::Backup
class FileMode
attr_reader :filename
def initialize(filename:)
@filename = filename
end
def mode
return nil if !File.exist?(filename)
stat = File.stat(filename)
stat.mode & 0o777
end
end
end
| true |
8ddf03b5b05959579171444cf9204290d974b071 | Ruby | mlapshin/ruby_revisor_client | /lib/revisor/client/session.rb | UTF-8 | 1,339 | 2.53125 | 3 | [
"MIT"
] | permissive | module Revisor
class Client
class Session
attr_reader :client, :name
def initialize(client, name)
@client = client
@name = name
@tabs = {}
end
def stop
@client.stop_session(self.name)
end
def create_tab(tab_name)
@client.command("session.tab.create",
:session_name => @name,
:tab_name => tab_name)
@tabs[tab_name] = Tab.new(self, tab_name)
end
def destroy_tab(tab_name)
@client.command("session.tab.destroy",
:session_name => @name,
:tab_name => tab_name)
@tabs.delete(tab_name)
end
def set_cookies(cookies, url)
cookies.each do |cookie|
if cookie[:expires_at] && cookie[:expires_at].is_a?(Time)
cookie[:expires_at] = Client.datetime_to_json(cookie[:expires_at])
end
end
@client.command("session.set_cookies",
:session_name => @name,
:cookies => cookies,
:url => url)
end
def get_cookies(url)
@client.command("session.get_cookies",
:session_name => @name,
:url => url)[:cookies]
end
end
end
end
| true |
a40053635b63a61e68ebfe77f20199d2b6a6cc40 | Ruby | millarba/deliberate_practice | /research_method_map.rb | UTF-8 | 772 | 4.28125 | 4 | [] | no_license | a = [ "a", "b", "c", "d" ]
# collect is a synonym for map
p a.map { |x| x + "!" } #=> ["a!", "b!", "c!", "d!"]
# map can be used with index, allows us to track index as well as element
# here x * i is multiplying a string by the index
p a.map.with_index { |x, i| x * i } #=> ["", "b", "cc", "ddd"]
p a #=> ["a", "b", "c", "d"]
# this is the equivalent code manually using an each loop
b = []
a.each do |x|
b << x + "!"
end
letters = [ "a", "b", "c", "d" ]
# better variable names
mapped_letters = []
letters.each do |letter|
mapped_letters << letter + "!"
end
p mapped_letters
# Example: given an array of integers, divide each by 2 returns [1,2,2.5,3,4,5]
numbers = [2,4,5,6,8,10]
p numbers.map {|number|number/2.to_f}
| true |
526a0caa34bb4a7ab1b9b71792b57f60d00ef30d | Ruby | PhilippePerret/Proximit | /bin/TextAnalyzer/Analyse/TableResultats/Mot/inst/initialize.rb | UTF-8 | 898 | 2.734375 | 3 | [] | no_license | # encoding: UTF-8
=begin
Classe TextAnalyzer::Analyse::TableResultats::Mot
---------------------------------------------------
Instance pour les mots (pour UN mot de résultat)
)
=end
class TextAnalyzer
class Analyse
class TableResultats
class Mot
def initialize imot = nil, data = nil
unless imot.nil? # rechargement
self.real = imot.real
self.downcase = imot.downcase
self.sortish = imot.downcase.normalize
self.data = data
self.ids = []
end
end
# Ajout d'un mot (on ajoute son ID. On pourra retrouver le mot avec
# <analyse>.mots[<ID>])
# Noter qu'avant on parlait d'index, mais comme des mots peuvent être
# ajoutés et retirés, il vaut mieux parler d'identifiant maintenant.
def << imot
# self.indexes << imot.index
self.ids << imot.id
end
end #/Mot
end #/TableResultats
end #/Analyse
end #/TextAnalyzer
| true |
07ee4dd04b4cecdec119233101302fd2d13122d6 | Ruby | ndo7/online-shop-app | /spec/models/inventory_spec.rb | UTF-8 | 3,778 | 3.015625 | 3 | [] | no_license | # require 'rails_helper'
#
# RSpec.describe Inventory, type: :model do
#
# let(:bman) { User.create(username: "Batman", first_name: "Bruce", last_name: "Wayne", credit_card_number: 101011110000, is_seller: true, email: "bman@wayne_industries.net", password: "not_password") }
#
#
# let(:not_bman) { User.create(username: "Not Batman", first_name: "Not Bruce", last_name: "Not Wayne", credit_card_number: 101011110000, is_seller: true, email: "not_bman@wayne_industries.net", password: "password") }
#
# let(:bman_inventory) { Inventory.create(seller: bman) }
#
# let(:valid_product) { Product.create(name: "candy", price: 11.00, description: "a sweet for the sweet", seller: bman, inventory: bman_inventory, quantity: 11) }
#
# let(:valid_product_2) { Product.create(name: "junk food", price: 1.00, description: "cheap junk food", seller: bman, inventory: bman_inventory, quantity: 100)
# }
#
# let(:bman_cart) { Cart.create(user: bman) }
#
# let(:not_bman_cart) { Cart.create(user: bman) }
#
# let(:cart_product_1) { CartProduct.create(cart: bman_cart, product: valid_product, quantity: 2) }
#
# let(:cart_product_2) { CartProduct.create(cart: bman_cart, product: valid_product, quantity: 3) }
#
# let(:cart_product_3) { CartProduct.create(cart: not_bman_cart, product: valid_product, quantity: 3) }
#
# before do
# bman_inventory.products << [valid_product, valid_product_2]
# end
#
# it 'is valid with valid attributes' do
# expect(bman_inventory).to be_valid
# end
#
# it 'is invalid without a seller' do
# bman_inventory.seller = nil
# expect(bman_inventory).to_not be_valid
# end
#
# it 'has many distinct products' do
# expect(bman_inventory.products.count).to eq(2)
# end
#
# context '#product available' do
# it 'accepts a product name and returns if the item is available' do
# evaluated = bman_inventory.product_available(valid_product.name)
# expect(evaluated).to eq(true)
# end
# end
#
# context '#verify_quantity' do
# it '#verify_quantity accepts a product name and returns how many of that item is in the seller\'s inventory' do
# verified_quantity = bman_inventory.verify_quantity("candy")
# expect(verified_quantity).to eq(11)
# end
# end
#
# context '#decrease_quantity'do
# it 'takes a product name and a quantity, and returns true if item quantity in seller\'s inventory has decreased' do
# initial_quantity = bman_inventory.verify_quantity("candy")
# value = bman_inventory.decrease_quantity("candy", 1)
# final_quantity = initial_quantity - 1
# expect(value).to eq(true)
# expect(final_quantity).to be(10)
# end
# end
#
# context '#increase_quantity' do
# it '#increase_quantity takes a product name and a quantity, and returns true if item quantity in seller\'s inventory has increased' do
# initial_quantity = bman_inventory.verify_quantity("candy")
# value = bman_inventory.increase_quantity("candy", 3)
# final_quantity = initial_quantity + 3
# expect(value).to eq(true)
# expect(final_quantity).to eq(14)
# end
# end
#
# context '#add_product' do
# it '#add_product takes a hash of information for a product, creates a product, and returns true if product is successfully added to seller\'s inventory' do
# new_product = bman_inventory.add_product(name: "frozen burrito", price: 1.50, description: "a college staple", seller: bman, inventory: bman_inventory, quantity: 3)
# expect(new_product).to be(true)
# end
# end
#
# context '::most_commonly_stocked_product' do
# it '::most_commonly_stocked_product returns the most commonly stocked product' do
# result = Inventory.most_commonly_stocked_product
# expect(result).to eq("junk food")
# end
# end
#
# end
| true |
b8ad5292479e618da1804786ef680a0e7dc559a0 | Ruby | sbfaulkner/rsql | /lib/rsql/rsql.rb | UTF-8 | 7,573 | 2.796875 | 3 | [
"MIT"
] | permissive | require 'getoptlong'
require 'readline'
include Readline
require 'shellwords'
include Shellwords
require 'singleton'
module RSQL
OPTIONS = { :mode => 'column', :password => '', :user => ENV['USER'] }
class RSQL < Object
include Singleton
class << self
def execute(command)
# split command into POSIX tokens
if args = shellwords(command)
# extract the actual command name
method_name = args.shift
# make sure there was a command
unless method_name.nil?
# if the command name corresponds to a method
if instance.respond_to?(method_name)
# invoke it
instance.send(method_name, *args)
else
# otherwise, hand it off to ODBC
instance.send :execute, command
end
end
end
rescue => error
puts "ERROR: #{error}"
end
end
private
def initialize
@dsn = nil
@database = nil
end
def execute(command)
unless @database.nil?
begin
@database.run(command) do |result|
begin
if result.ncols > 0
case nrows = result.print
when 0
puts "Empty set" unless OPTIONS[:quiet]
when 1
puts "1 row in set" unless OPTIONS[:quiet]
else
puts "#{nrows} rows in set" unless OPTIONS[:quiet]
end
else
puts "#{result.nrows} #{result.nrows == 1 ? 'row' : 'rows'} affected" unless OPTIONS[:quiet]
end
rescue
raise
ensure
result.drop
end
end
rescue
raise
end
else
puts "No dsn selected"
end
end
public
def commit
unless @database.nil?
begin
@database.commit
rescue
puts "ERROR: Commit failed"
raise
end
else
puts "No dsn selected"
end
end
def describe(table, column = nil)
unless @database.nil?
begin
if column
statement = @database.columns(table, column)
else
statement = @database.columns(table)
end
rescue
raise
else
begin
statement.print :COLUMN_NAME => 'Field', :TYPE_NAME => 'Type', :COLUMN_SIZE => 'Size', :IS_NULLABLE => 'Null', :COLUMN_DEF => 'Default'
rescue
raise
ensure
statement.drop
end
end
else
puts "No dsn selected"
end
end
def help
puts "COMMIT"
puts "DESCRIBE table"
puts "HELP"
puts "QUIT"
puts "ROLLBACK"
puts "SET AUTOCOMMIT=value"
puts "SHOW TABLES [LIKE pattern]"
puts "USE dsn"
end
def quit
exit
end
def rollback
unless @database.nil?
begin
@database.rollback
rescue
puts "ERROR: Rollback failed"
raise
end
else
puts "No dsn selected"
end
end
def set(expression)
unless @database.nil?
matches = /([a-z]*)=(.*)/.match(expression)
if matches
variable,value = matches[1,2]
case variable.downcase
when "autocommit"
begin
@database.autocommit = (1.coerce(value)[0] != 0)
rescue ArgumentError
raise(StandardError, "Variable '#{variable}' can't be set to the value of '#{value}'")
else
puts "autocommit set to #{@database.autocommit}"
end
else
raise(StandardError, "Unknown system variable '#{variable}'")
end
else
raise(StandardError, "Syntax error at '#{expression}'")
end
else
puts "No dsn selected"
end
end
def show(what, *args)
unless @database.nil?
case what.downcase
when 'tables'
source = @dsn
begin
if opt = args.shift
if opt.downcase == 'like'
if pattern = args.shift
statement = @database.tables(pattern)
source += " (#{pattern})"
else
raise(StandardError, "Missing pattern after '#{opt}'")
end
else
raise(StandardError, "Syntax error at '#{opt}'")
end
else
statement = @database.tables
end
rescue
raise
else
unless statement.nil?
begin
statement.print :TABLE_NAME => "Tables_in_#{source}"
rescue
raise
ensure
statement.drop
end
else
puts "No tables to show"
end
end
else
raise(StandardError, "Syntax error at '#{what}'")
end
else
puts "No dsn selected"
end
end
def use(dsn)
begin
unless @database.nil?
begin
if @database.connected?
# in case of pending transaction
@database.rollback unless @database.autocommit
@database.disconnect
end
rescue
end
end
@dsn = dsn
@database = ODBC.connect(@dsn, OPTIONS[:user], OPTIONS[:password])
rescue
puts "ERROR: Unable to connect to DSN '#{@dsn}' as user '#{OPTIONS[:user]}'"
@database = nil
@dsn = nil
raise
else
puts "Database changed" unless OPTIONS[:quiet]
end
end
end
COMMAND = File.basename($0)
opts = GetoptLong.new(
[ "--execute", "-e", GetoptLong::REQUIRED_ARGUMENT ],
[ "--mode", "-m", GetoptLong::REQUIRED_ARGUMENT ],
[ "--password", "-p", GetoptLong::REQUIRED_ARGUMENT ],
[ "--quiet", "-q", GetoptLong::NO_ARGUMENT ],
[ "--user", "-u", GetoptLong::REQUIRED_ARGUMENT ],
[ "--verbose", "-v", GetoptLong::NO_ARGUMENT ]
)
opts.each do |opt, arg|
OPTIONS[opt[/--(.*)/,1].to_sym] = arg
end
# to hide the noise from the ODBC driver
STDERR.reopen("/dev/null") unless OPTIONS[:verbose]
if ARGV.length > 1
puts "#{COMMAND}: too many arguments"
exit
end
if OPTIONS[:execute]
# a command requires a database
if ARGV.length < 1
puts "#{COMMAND}: no database specified"
exit
end
# force quiet-mode if command provided
OPTIONS[:quiet] = true
end
# set format for output
begin
ODBC::Statement.mode = OPTIONS[:mode]
rescue => e
puts "#{COMMAND}: #{e}"
exit
end
# quiet-mode wins over verbose-mode
OPTIONS.delete :verbose if OPTIONS[:quiet]
puts "#{COMMAND} v1.0.5 - Copyright (c) 2007-2008 unwwwired.net" unless OPTIONS[:quiet]
begin
# use dsn if provided
begin
RSQL.instance.use(ARGV[0]) if ARGV.length > 0
rescue ODBC::Error => error
puts "ERROR: #{error}"
end
if OPTIONS[:execute]
RSQL.execute OPTIONS[:execute]
else
# get (and process) each command line in turn
while command = readline("#{COMMAND}> ", true)
RSQL.execute command
end
end
rescue SystemExit
puts "Bye" unless OPTIONS[:quiet]
rescue => exception
puts %Q(INTERNAL ERROR: #{exception}\n#{exception.backtrace.join("\n")})
end
end | true |
bb13980f7ce2206fd25868abe907b6e5ef76fb2b | Ruby | bumpouce/ruby-oo-object-relationships-collaborating-objects-lab-seattle-web-030920 | /lib/mp3_importer.rb | UTF-8 | 329 | 3.015625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require 'pry'
class MP3Importer
attr_accessor :path
@@all = []
def initialize (path)
@path = path
@@all << self
end
def files
Dir[path + "/*.mp3"].map{ |fullpath| File.basename(fullpath) }
end
def import
files.each {|item| Song.new_by_filename(item)}
end
end | true |
6f34496ec34bfa04ab6c787ee4448616e94b81df | Ruby | krekoten/SimpleQS | /lib/simple_qs/request/base.rb | UTF-8 | 2,864 | 2.65625 | 3 | [
"MIT"
] | permissive | require 'uri'
require 'net/http'
require 'base64'
require 'hmac-sha1'
module SimpleQS
module Request
class Base
RESERVED_CHARACTERS = /[^a-zA-Z0-9\-\.\_\~]/
SIGNATURE_VERSION = 2
SIGNATURE_METHOD = 'HmacSHA1'
def initialize(params = {})
self.query_params = params
end
def ==(other)
self.class.http_method == other.class.http_method\
&& query_params == other.query_params\
&& query_string == other.query_string
end
def timestamp
@timestamp ||= _timestamp
end
def timestamp=(time)
raise ArgumentError, "expected Time object, bug got #{time.class.to_s} instead." unless time.kind_of?(Time)
@timestamp = time.utc.strftime("%Y-%m-%dT%H:%M:%SZ")
end
def query_params
@query_params ||= {}
@query_params = {
'SignatureVersion' => SIGNATURE_VERSION,
'SignatureMethod' => SIGNATURE_METHOD,
'Version' => SimpleQS::API_VERSION,
'Timestamp' => timestamp,
'AWSAccessKeyId' => SimpleQS.access_key_id
}.merge(@query_params)
@query_params.delete('Timestamp') if @query_params['Expires']
@query_params
end
attr_writer :query_params
def update_query_params(params)
@query_params = query_params.merge params
end
def query_string
@query_string ||= "/"
end
def query_string=(value)
value = value.join('/') if value.kind_of?(Array)
@query_string = (value =~ /^\// ? value : "/#{value}")
end
# Canonicalizes query string
def canonical_query_string
params_to_query(query_params.sort)
end
def signature_base_string
[
self.class.http_method.to_s.upcase,
SimpleQS.host.downcase,
query_string,
canonical_query_string
].join("\n")
end
def uri(with_query_params = false)
"http://#{SimpleQS.host}#{query_string}" << (with_query_params ? "?#{params_to_query(query_params)}" : '')
end
def sign!
update_query_params({
'Signature' => Base64.encode64(HMAC::SHA1.digest(SimpleQS.secret_access_key, signature_base_string)).chomp
})
self
end
def params_to_query(params)
params.map {|pair| pair.map {|value| URI.escape(value.to_s, RESERVED_CHARACTERS)}.join('=')}.join('&')
end
class << self
def http_method(value = nil)
@http_method = value if value
@http_method
end
end
protected
# Generates UTC timestamp in dateTime object format
def _timestamp
Time.now.utc.strftime("%Y-%m-%dT%H:%M:%SZ")
end
end
end
end
| true |
5947fa0a90f228fccb4ba085676703e21e6ba8e4 | Ruby | glassjoseph/classroom_exercises | /Week 1/rando_guesser.rb | UTF-8 | 526 | 3.921875 | 4 | [] | no_license |
#set up secret, guess variable, compare
=begin
secret_number = rand(1..10)
puts "(The secret number is #{secret_number})"
guess = gets.chomp
until guess == secret_number
puts "Guess is #{guess}"
puts "Guess again!"
guess = gets.chomp.to_i
end
puts "You guessed it!"
=end
secret_number = rand(1..10)
puts "(The secret number is #{secret_number})"
guess = gets.chomp.to_i
while guess != secret_number
puts "Guess is #{guess}"
puts "Guess again!"
guess = gets.chomp.to_i
end
puts "You guessed it!"
| true |
c590688f6d24bea67880efceb4db46381baa2af2 | Ruby | sawaezamin/backend_mod_1_prework | /section4/exercises/mycar_launchschool.rb | UTF-8 | 992 | 3.796875 | 4 | [] | no_license | class MyCar
attribute_accessor :color
attribute_view :year
def spray_paint(color)
self.color = color
puts "change the color to #{color}"
end
end
def initialize(year, model, color)
@year = year
@model = model
@color = color
@instant_current_speed = 0
end
def shut_off
@instant_current_speed = 0
puts "My car is turned off"
end
def speed_up(mph)
@instant_current_speed += mph
puts "We are gaining speed of #{mph} miles per hour"
end
def brake_down(mph)
@instant_current_speed -= mph
puts "We are slowing down to #{mph} miles per hour"
end
def instant_current_speed
puts "Currently we are traveling at#{mph} mph"
end
end
tesla = MyCar.new(2021, "Model S", "Matte Black")
tesla.instant_current_speed
tesla.shut_off
tesla.instant_current_speed
tesla.speed_up(100)
tesla.brake_down(59)
tesla.instant_current_speed
tesla.color = "sunshine orange"
puts tesla.color
puts tesla.year
tesla.spray_paint('midnight blue')
| true |
bb6146f115855bb6981d968f0e821d9c3e081f54 | Ruby | bkleinen/bkleinen.github.io | /bin/hugo_migration/rename_section_header.rb | UTF-8 | 611 | 2.609375 | 3 | [] | no_license | all_index_files = Dir.glob("**/index.md")
all_index_files.each do | index_file_name |
f = File.new(index_file_name)
dir_name = File.dirname(index_file_name)
siblings = Dir.glob(File.join(dir_name,"*.md"))
subdirectories = Dir[File.join(dir_name,"*/")]
children = siblings.size + subdirectories.size
if children > 1
new_name = index_file_name.gsub("index.md","_index.md")
command = "git mv #{index_file_name} #{new_name}"
system(command)
# puts "has #{children} children, should be section"
# puts "siblings: #{siblings}"
# puts "subdirectories: #{subdirectories}"
end
end
| true |
50e5aa54d8e1e580660dd639fc6fe9d0f4784e42 | Ruby | nicooga/cannabase_test | /lib/game/attack.rb | UTF-8 | 1,272 | 3.6875 | 4 | [] | no_license | # A command object that allows a player to attack another one.
class Game::Attack
# @param game [Game]
# @param player_a [Player]
# @param player_b [Player]
def initialize(game, player_a, player_b)
if (!game.players[player_a.id] || !game.players[player_b.id])
raise 'A player does not belong to this game'
end
self.game = game
self.player_a = player_a
self.player_b = player_b
end
def perform
if draw?
kill_random_units(player_a)
kill_random_units(player_b)
return
end
loser, winner = [player_a, player_b].sort_by(&:strength_points)
kill_strongest_units(loser)
winner.gold += 100
game.players[loser.id] = loser
game.players[winner.id] = winner
end
private
attr_accessor :game, :player_a, :player_b
def draw?
player_a.strength_points == player_b.strength_points
end
# Player units are guarenteed to be sorted by strength ASC
# each time a player or a unit is added to the game,
# so we can just remove the last 2 units.
def kill_strongest_units(player)
player.units.last(2).each { |u| player.delete_unit(u) }
end
def kill_random_units(player)
rand(1..3).times do
unit = player.units.sample
player.delete_unit(unit)
end
end
end
| true |
35e636a10e5e51268d449ee09d81caf80481c74f | Ruby | jainpuja/learnruby | /case_expressions.rb | UTF-8 | 929 | 3.8125 | 4 | [] | no_license | # upcase or downcae
# what def....
def get_day_name(day)
day_name = ""
case day
when "mon"
day_name = "Monday"
when "tue"
day_name = "Tuesday"
when "wed"
day_name = "Wednesday"
when "thu"
day_name = "Thrusday"
when "fri"
day_name = "Friday"
when "sat"
day_name = "Saturday"
when "sun"
day_name = "Sunday"
else
day_name = "Invalid aberiviation"
end
return day_name
end
def get_day_name2(day)
case day
when "mon"
return "Monday"
when "tue"
return "Tuesday"
when "wed"
return "Wednesday"
when "thu"
return "Thrusday"
when "fri"
return "Friday"
when "sat"
return "Saturday"
when "sun"
return "Sunday"
else
return "Invalid aberiviation"
end
end
puts get_day_name("mon")
puts get_day_name2("mon")
| true |
e96433a0059d530df75b43171331eece78948832 | Ruby | BirukAbreham/AppAcademy | /Ruby/Data Structures/DIY ADT/map.rb | UTF-8 | 1,021 | 4.21875 | 4 | [] | no_license | class Map
def initialize
@map = []
end
def set(key, value)
# either create a new key-value pair or update the
# value for a pre-existing key
if @map.flatten.include?(key)
@map.each_with_index do |pair, idx|
if pair[0] == key
@map[idx] = [key, value]
end
end
else
@map << [key, value]
end
end
def get(key)
@map.each do |pair|
return pair if pair[0] == key
end
nil
end
def delete(key)
@map.each do |pair|
if pair[0] == key
return @map.delete(pair)
end
end
nil
end
def show
p @map
end
end
map = Map.new
map.set(1, "one")
map.set(2, "two")
map.set(3, "three")
map.set(4, "four")
map.set(5, "five")
map.show # [[1, "one"], [2, "two"], [3, "three"], [4, "four"], [5, "five"]]
p map.get(1) # one
p map.get(2) # two
p map.get(10) # nil
p map.delete(1) # [1, "one"]
p map.delete(2) # [2, "two"]
p map.delete(10) # nil
map.show # [[3, "three"], [4, "four"], [5, "five"]]
| true |
e77e435dc226662c93ecaabc9d0fb9d637e885d4 | Ruby | ShannonLCapper/zorkda | /lib/zorkda-web/Actions/Utils/equate_with_obj_to_obj_player_has.rb | UTF-8 | 2,556 | 2.9375 | 3 | [] | no_license | module Zorkda
module Actions
module Utils
#DONE
def self.equate_with_obj_to_obj_player_has(player, with_obj, action) #returns nil if no appropriate item found, returns object if item found
if with_obj == "hands" || with_obj == "hand" || with_obj == "fists" || with_obj == "fist"
Zorkda::GameOutput.add_line("You don't want to hurt your delicate hands, do you?")
return nil
end
#check inventory and carrying first
matches = find_matches(player.inventory, with_obj).concat(find_matches(player.carrying, with_obj))
if matches.length > 1
Zorkda::GameOutput.add_line("You need to be more specific about what you want to #{action} with.")
list_options(matches)
Zorkda::GameOutput.add_line("Retype the "#{action}" command with the tool you want.")
return nil
elsif matches.length == 1
return matches[0]
else
#search equipment
matches, matched_parent, parent_singular, parent_plural = find_matches_id_parent(player.equipment, with_obj)
#no matches
if matches.length == 0
Zorkda::GameOutput.add_line("You can't #{action} something with an object you don't have.")
return nil
#more than one found, user typed a general equipment type
elsif matched_parent && matches.length > 1
#find the specific piece of equipment that is equipped
piece_equipped = false
matches.each do |piece|
if piece.equipped
return piece
piece_equipped = true
end
end
#you have multiple of the equipment type, but none are equipped. This option should generally not be reached
if piece_equipped == false
Zorkda::GameOutput.add_line("You don't have any of that equipment type equipped.")
return nil
end
#this option should never be reached since no equipment items should have the same name
elsif matches.length > 1
Zorkda::GameOutput.add_line("You need to be more specific about what you want to #{action} with.")
list_options(matches)
Zorkda::GameOutput.add_line("Retype the "#{action}" command with the tool you want.")
return nil
#the user typed a specific piece of equipment, which is not equipped
elsif !matches[0].equipped
Zorkda::GameOutput.add_line("That item is not currently equipped. You can equip it with the "equip <item>" command.")
return nil
#the user typed a specific piece of equipment, which is equipped
else
return matches[0]
end
end
end
end
end
end | true |
b37f5cf758421954789778e97ddd4b01ce44dea1 | Ruby | phanhaiquang/table-tennis | /app/models/cup_player.rb | UTF-8 | 1,276 | 2.734375 | 3 | [] | no_license | class CupPlayer < ApplicationRecord
INIT_SCORE = 10
belongs_to :cup
belongs_to :player
def update_player_score
w, l = 0, 0
Match.where(cup: self.cup, player_1: self.player).each do |match|
w += 1 if match.score_1 > match.score_2
l += 1 if match.score_1 < match.score_2
end
Match.where(cup: self.cup, player_2: self.player).each do |match|
w += 1 if match.score_2 > match.score_1
l += 1 if match.score_2 < match.score_1
end
self.update_attributes(win: w, loose: l)
end
def p1_matches
Match.where(cup_id: self.cup_id, player_1: self.player_id)
end
def p2_matches
Match.where(cup_id: self.cup_id, player_2: self.player_id)
end
def score_for_winner
1
end
def score_for_looser
-1
end
def init_score
INIT_SCORE
end
def score
score = init_score
p1_matches.each do |match|
score += (score_for_winner + match.star_1) if match.score_1 > match.score_2
score += (score_for_looser - match.star_1) if match.score_1 < match.score_2
end
p2_matches.each do |match|
score += (score_for_winner + match.star_2) if match.score_2 > match.score_1
score += (score_for_looser - match.star_2) if match.score_2 < match.score_1
end
score
end
end
| true |
f54272b7bbd87a25ce349ab08a4e686b2e75505a | Ruby | charlenef/tts_ruby | /homework/practice.rb | UTF-8 | 234 | 3.515625 | 4 | [] | no_license | # puts "What is you first name?"
# first_name = gets.chomp
# puts "What is you last name?"
# last_name = gets.chomp
# puts "Hi #{first_name} #{last_name}. Your name is #{first_name.length + last_name.length} characters long."
| true |
d9656e67a40393c322927a28a491f5cd3b9a8199 | Ruby | zhiyuan2007/useful_tools | /ruby/beacon/server/lib/beacon/grid/connection.rb | UTF-8 | 1,018 | 2.765625 | 3 | [] | no_license | require "bunny"
require "forwardable"
module Beacon
class Connection
extend Forwardable
def_delegators :@channel, :topic, :fanout, :direct, :default_exchange, :ack
def_delegators :@connection, :queue_exists?, :exchange_exists?
def initialize(host_name)
@connection = Bunny.new({:host => host_name})
@connection.start
@channel = @connection.create_channel
end
def queue(name, exclusive = false)
@channel.queue(name, {:exclusive => exclusive, :durable => false})
end
def stop
@channel.close
@connection.close
end
end
end
if $0 == __FILE__
con = Beacon::Connection.new("127.0.0.1")
puts con.direct("test_direct")
puts con.fanout("test_fanout")
puts con.queue_exists?("test_queue")
puts con.exchange_exists?("SystemInfo")
puts con.direct("test_direct").delete
puts con.fanout("test_fanout").delete
end
| true |
9d999b1aafb73367998de62eaf3893f6f572610e | Ruby | wachin/Windows-WachiManuales | /Sketchup/Extensiones/Window_Tools/WindowTools1.1/WindowTools1.1/3PointTool.rb | UTF-8 | 5,654 | 2.71875 | 3 | [] | no_license | =begin
# Copyright 2004, @Last Software, Inc.
# The code related to click 3 points was reused here from an original
# example titled rectangle.rb by @Last Software, Inc.
# To it I added the window code.
# Name: 3 Point Rectangle
# Usage: click 3 points, into an EXISTING OPENING, for use with WindowTools
# Date: 2008
# Type: Tool
# Revised: 2008,09,20 Thanks to Jim Foltz for rewriting this routine
#------------------------------------------------------------------------------------------------
=end
require 'sketchup.rb'
class ThreePointTool
def initialize
@ip = Sketchup::InputPoint.new
@ip1 = Sketchup::InputPoint.new
reset
end
def reset
@pts = []
@state = 0
@ip1.clear
@drawn = false
Sketchup::set_status_text "", SB_VCB_LABEL
Sketchup::set_status_text "", SB_VCB_VALUE
Sketchup::set_status_text "Click Top Left to start"
@shift_down_time = Time.now
end
def activate
self.reset
end
def deactivate(view)
view.invalidate if @drawn
end
def set_current_point(x, y, view)
if( !@ip.pick(view, x, y, @ip1) )
return false
end
need_draw = true
# Set the tooltip that will be displayed
view.tooltip = @ip.tooltip
# Compute points
case @state
when 0
@pts[0] = @ip.position
@pts[4] = @pts[0]
need_draw = @ip.display? || @drawn
when 1
@pts[1] = @ip.position
@length = @pts[0].distance @pts[1]
Sketchup::set_status_text @length.to_s, SB_VCB_VALUE
when 2
pt1 = @ip.position
pt2 = pt1.project_to_line @pts
vec = pt1 - pt2
@pt1 = @ip.position
@pt2 = pt1.project_to_line @pts
@vec = @pt1 - @pt2
@width = vec.length
if( @width > 0 )
# test for a square
square_point = pt2.offset(vec, @length)
if( view.pick_helper.test_point(square_point, x, y) )
@width = @length
@pts[2] = @pts[1].offset(vec, @width)
@pts[3] = @pts[0].offset(vec, @width)
view.tooltip = "Square"
else
@pts[2] = @pts[1].offset(vec)
@pts[3] = @pts[0].offset(vec)
end
else
@pts[2] = @pts[1]
@pts[3] = @pts[0]
end
Sketchup::set_status_text @width.to_s, SB_VCB_VALUE
end
view.invalidate if need_draw
end
def onMouseMove(flags, x, y, view)
self.set_current_point(x, y, view)
end
def increment_state
@state += 1
case @state
when 1
@ip1.copy! @ip
Sketchup::set_status_text "Click Top Right for 2nd point"
Sketchup::set_status_text "", SB_VCB_LABEL
Sketchup::set_status_text "", SB_VCB_VALUE
when 2
@ip1.clear
Sketchup::set_status_text "Click Btm Right for 3rd point"
Sketchup::set_status_text "", SB_VCB_LABEL
Sketchup::set_status_text "", SB_VCB_VALUE
when 3
self.create_geometry #refers back to the main drawing routines that use > def create_geometry
end
end
def onLButtonDown(flags, x, y, view)
self.set_current_point(x, y, view)
self.increment_state
view.lock_inference
end
def onCancel(flag, view)
view.invalidate if @drawn
self.reset
end
# This is called when the user types a value into the VCB
def onUserText(text, view)
# The user may type in something that we can't parse as a length
# so we set up some exception handling to trap that
begin
value = text.to_l
rescue
# Error parsing the text
UI.beep
value = nil
Sketchup::set_status_text "", SB_VCB_VALUE
end
return if !value
case @state
when 1
# update the width
vec = @pts[1] - @pts[0]
if( vec.length > 0.0 )
vec.length = value
@pts[1] = @pts[0].offset(vec)
view.invalidate
self.increment_state
end
when 2
# update the height
vec = @pts[3] - @pts[0]
if( vec.length > 0.0 )
vec.length = value
@pts[2] = @pts[1].offset(vec)
@pts[3] = @pts[0].offset(vec)
self.increment_state
end
end
end
def getExtents
bb = Geom::BoundingBox.new
case @state
when 0
# We are getting the first point
if( @ip.valid? && @ip.display? )
bb.add @ip.position
end
when 1
bb.add @pts[0]
bb.add @pts[1]
when 2
bb.add @pts
end
bb
end
def draw(view)
@drawn = false
# Show the current input point
if( @ip.valid? && @ip.display? )
@ip.draw(view)
@drawn = true
end
# show the rectangle
if( @state == 1 )
# just draw a line from the start to the end point
view.set_color_from_line(@ip1, @ip)
inference_locked = view.inference_locked?
view.line_width = 3 if inference_locked
view.draw(GL_LINE_STRIP, @pts[0], @pts[1])
view.line_width = 1 if inference_locked
@drawn = true
elsif( @state > 1 )
# draw the curve
view.drawing_color = "black"
view.draw(GL_LINE_STRIP, @pts)
@drawn = true
end
end
def onKeyDown(key, rpt, flags, view)
if( key == CONSTRAIN_MODIFIER_KEY && rpt == 1 )
@shift_down_time = Time.now
# if we already have an inference lock, then unlock it
if( view.inference_locked? )
view.lock_inference
elsif( @state == 0 )
view.lock_inference @ip
elsif( @state == 1 )
view.lock_inference @ip, @ip1
end
end
end
def onKeyUp(key, rpt, flags, view)
if( key == CONSTRAIN_MODIFIER_KEY &&
view.inference_locked? &&
(Time.now - @shift_down_time) > 0.5 )
view.lock_inference
end
end
end # class ThreePointTool
| true |
cf97b2c2d60ce55d90ac045ee47561ea1793a432 | Ruby | kranthie/garden-rhythms | /ullas/mod_1_intro/assorted.rb | UTF-8 | 2,315 | 3.53125 | 4 | [] | no_license | class Array
def bubble_sort
sorted = self.dup
(sorted.length-1).downto(0) do
|i|
0.upto(i-1) do
|j|
if sorted[j] > sorted[j+1]
sorted[j], sorted[j+1] = sorted[j+1], sorted[j]
end
end
end
sorted
end
def selection_sort
sorted = self.dup
0.upto(sorted.length-1) do
|i|
min = sorted[i]
i.upto(sorted.length-1) do
|j|
if min > sorted[j]
min, sorted[j] = sorted[j], min
end
end
sorted[i] = min
end
sorted
end
def insertion_sort
sorted = self.dup
sorted.each_index do
|i|
i.downto(1) do
|j|
if sorted[j] < sorted[j-1]
sorted[j], sorted[j-1] = sorted[j-1], sorted[j]
end
end
end
sorted
end
def merge_sort(array=self)
return array if array.size == 1 or array.empty?
left = merge_sort(array[0...array.size/2])
right = merge_sort(array[array.size/2...array.size])
merge(left, right)
end
def merge(left, right)
l, r, sorted = left.dup, right.dup, []
while not l.empty? and not r.empty? do
if l[0] <= r[0]
sorted << l.shift
else
sorted << r.shift
end
end
sorted += l if not l.empty?
sorted += r if not r.empty?
sorted
end
def qsort(array=self)
return array if array.size <= 1
a = array.dup
p = rand(a.size)
pivot = a[p]
a.delete_at(p)
left, right = Array.new, Array.new
a.each do
|x|
if x <= pivot
left << x
else
right << x
end
end
qsort(left) + [pivot] + qsort(right)
end
# Helper functions for heap-sort
def parent(i)
i/2
end
def left(i)
i==0? 1 : (2*i - 1)
end
def right(i)
i==0? 2 : 2*i
end
def max_heapify!(i)
l, r = left(i), right(i)
largest = (l <= (self.size-1) && self[l] > self[i])? l : i
largest = r if r <= (self.size-1) && self[r] > self[largest]
if largest != i
self[i], self[largest] = self[largest], self[i]
max_heapify!(largest)
end
self
end
def build_max_heap!()
((self.size-1)/2).downto 0 do
|i|
max_heapify!(i)
end
self
end
def heapsort!()
self.build_max_heap!
end
end
puts [1,2,3,4].max_heapify!(0)
| true |
fb094880bc242acee0d6d04274c3bfa661a7fd33 | Ruby | scoter-oracle/vagrant | /plugins/provisioners/container/client.rb | UTF-8 | 6,445 | 2.59375 | 3 | [
"MIT"
] | permissive | require 'digest/sha1'
module VagrantPlugins
module ContainerProvisioner
class Client
def initialize(machine, container_command)
@machine = machine
@container_command = container_command
end
# Build an image given a path to a Dockerfile
#
# @param [String] - Path to the Dockerfile to pass to
# container build command
def build_images(images)
@machine.communicate.tap do |comm|
images.each do |path, opts|
@machine.ui.info(I18n.t("vagrant.container_building_single", path: path))
comm.sudo("#{@container_command} build #{opts[:args]} #{path}") do |type, data|
handle_comm(type, data)
end
end
end
end
# Pull image given a list of images
#
# @param [String] - Image name
def pull_images(*images)
@machine.communicate.tap do |comm|
images.each do |image|
@machine.ui.info(I18n.t("vagrant.container_pulling_single", name: image))
comm.sudo("#{@container_command} pull #{image}") do |type, data|
handle_comm(type, data)
end
end
end
end
def run(containers)
containers.each do |name, config|
cids_dir = "/var/lib/vagrant/cids"
config[:cidfile] ||= "#{cids_dir}/#{Digest::SHA1.hexdigest name}"
@machine.ui.info(I18n.t("vagrant.container_running", name: name))
@machine.communicate.sudo("mkdir -p #{cids_dir}")
run_container({
name: name,
original_name: name,
}.merge(config))
end
end
# Run a OCI container. If the container does not exist it will be
# created. If the image is stale it will be recreated and restarted
def run_container(config)
raise "Container's cidfile was not provided!" if !config[:cidfile]
id = "$(cat #{config[:cidfile]})"
if container_exists?(id)
if container_args_changed?(config)
@machine.ui.info(I18n.t("vagrant.container_restarting_container_args",
name: config[:name],
))
stop_container(id)
create_container(config)
elsif container_image_changed?(config)
@machine.ui.info(I18n.t("vagrant.container_restarting_container_image",
name: config[:name],
))
stop_container(id)
create_container(config)
else
start_container(id)
end
else
create_container(config)
end
end
def container_exists?(id)
lookup_container(id, true)
end
# Start container
#
# @param String - Image id
def start_container(id)
if !container_running?(id)
@machine.communicate.sudo("#{@container_command} start #{id}")
end
end
# Stop and remove container
#
# @param String - Image id
def stop_container(id)
@machine.communicate.sudo %[
#{@container_command} stop #{id}
#{@container_command} rm #{id}
]
end
def container_running?(id)
lookup_container(id)
end
def container_image_changed?(config)
# Returns true if there is a container running with the given :name,
# and the container is not using the latest :image.
# Here, "<cmd> inspect <container>" returns the id of the image
# that the container is using. We check that the latest image that
# has been built with that name (:image) matches the one that the
# container is running.
cmd = ("#{@container_command} inspect --format='{{.Image}}' #{config[:name]} |" +
" grep $(#{@container_command} images -q #{config[:image]})")
return !@machine.communicate.test(cmd)
end
def container_args_changed?(config)
path = container_data_path(config)
return true if !path.exist?
args = container_run_args(config)
sha = Digest::SHA1.hexdigest(args)
return true if path.read.chomp != sha
return false
end
def create_container(config)
args = container_run_args(config)
@machine.communicate.sudo %[rm -f "#{config[:cidfile]}"]
@machine.communicate.sudo %[#{@container_command} run #{args}]
sha = Digest::SHA1.hexdigest(args)
container_data_path(config).open("w+") do |f|
f.write(sha)
end
end
# Looks up if a container with a given id exists using the
# `ps` command. Returns Boolean
#
# @param String - Image id
def lookup_container(id, list_all = false)
container_ps = "sudo #{@container_command} ps -q"
container_ps << " -a" if list_all
@machine.communicate.tap do |comm|
return comm.test("#{container_ps} --no-trunc | grep -wFq #{id}")
end
end
def container_name(config)
name = config[:name]
# If the name is the automatically assigned name, then
# replace the "/" with "-" because "/" is not a valid
# character for a container name.
name = name.gsub("/", "-").gsub(":", "-") if name == config[:original_name]
name
end
# Compiles run arguments to be appended to command string.
# Returns String
def container_run_args(config)
name = container_name(config)
args = "--cidfile=#{config[:cidfile]} "
args << "-d " if config[:daemonize]
args << "--name #{name} " if name && config[:auto_assign_name]
args << "--restart=#{config[:restart]}" if config[:restart]
args << " #{config[:args]}" if config[:args]
"#{args} #{config[:image]} #{config[:cmd]}".strip
end
def container_data_path(config)
name = container_name(config)
@machine.data_dir.join("#{@container_command}-#{name}")
end
protected
# This handles outputting the communication data back to the UI
def handle_comm(type, data)
if [:stderr, :stdout].include?(type)
# Clear out the newline since we add one
data = data.chomp
return if data.empty?
options = {}
#options[:color] = color if !config.keep_color
@machine.ui.info(data.chomp, options)
end
end
end
end
end
| true |
567e86c3a3625a355dd979ce15c2d3cc7110f47f | Ruby | johlym/johnathan-org | /src/resources/wxdata/code/wx_maxes_json.rb | UTF-8 | 316 | 2.96875 | 3 | [
"MIT"
] | permissive | require 'csv'
require 'json'
# read the CSV file into a 2D array
data = CSV.read('3421718_maxes.csv')
# convert the data array to an array of arrays
rows = data.map { |row| row.to_a }
# write the rows array to a JSON file
File.open('3421718_maxes.json', 'w') do |file|
file.write(JSON.pretty_generate(rows))
end | true |
2e5c0a70a31b938639211f3ff23a5333ac8d57ab | Ruby | smolinsg23/lucha-app | /app/helpers/form_inputs_helper.rb | UTF-8 | 4,785 | 2.53125 | 3 | [] | no_license |
module FormInputsHelper
# Helper for Client update and create forms
def education
[
["No High School Diploma", "No High School Diploma"],
["High School Diploma", "High School Diploma"],
["GED", "GED"],
["Vocational Certificate", "Vocational Certificate"],
["Some College/Never Completed", "Some College/Never Completed"],
["Associates Degree", "Associates Degree"],
["Bachelor's Degree", "Bachelor's Degree"],
["Master's Degree", "Master's Degree"],
["Doctoral Degree", "Doctoral Degree"]
]
end
def pref_language
[['English', 'English'], ['Spanish', 'Spanish'], ['Polish', 'Polish']]
end
def pref_contact
[['Home Phone', 'Home Phone'],
['Cell Phone', 'Cell Phone'],
['Email', 'Email']]
end
def marital_status
[ ['Married', 'married'],
[ 'Separated', 'separated'],
[ 'Divorced', 'divorced'],
[ 'Single', 'single']
]
end
def income_range
# This helper was originally intended for the estimated_household_income model for the Client model. However, I changed that attribute to be a decimal for the purposes of reporting and data collection.
# The client may want to change back to a range instead of an decimal, in which case, use this helper
[
["$15,000 or Less", "$15,000 or Less"],
["$15,001–$20,000", "$15,001–$20,000"],
["$20,001—$25,000", "$20,001—$25,000"],
["$25,001—$30,000", "$25,001—$30,000"],
["$30,001—$35,000", "$30,001—$35,000"],
["$35,001—$40,000", "$35,001—$40,000"],
["$40,001—$45,000", "$40,001—$45,000"],
["$45,001—$50,000", "$45,001—$50,000"],
["$50,001—$55,000", "$50,001—$55,000"],
["$35,001—$40,000", "$35,001—$40,000"],
["$40,001—$45,000", "$40,001—$45,000"],
["$45,001—$50,000", "$45,001—$50,000"],
["$50,001—$55,000", "$50,001—$55,000"],
["$55,001—$60,000", "$55,001—$60,000"],
["$60,001—$65,000", "$60,001—$65,000"],
["$65,000+", "$65,000+"]
]
end
def racial_options
[['White', 'White'], ['Hispanic/Latino', 'Hispanic/Latino'], ['African-American', 'African-American'], ['Asian', 'Asian']]
end
def num_in_house
[[1,1],[2,2], [3,3], [4,4], [5,5], [6,6], [7,7], [8,8], [9,9]]
end
# Helper for Foreclosure update and create forms
def foreclosure_status
[
["I am not yet behind on my mortgage but close to it", "I am not yet behind on my mortgage but close to it"],
["Have not yet gone through the process, but am behind on payment", "Have not yet gone through the process, but am behind on payment"],
["I am over three months behind", "I am over three months behind"],
["I am over three months behind and have received a court summons", "I am over three months behind and have received a court summons"],
]
end
def cause_for_default
# Helper for reason_for_default attribute in Foreclosure model
[
["Reduction in Income", "Reduction in Income"],
["Divorce/Separation", "Divorce/Separation"],
["Loss of Income", "Loss of Income"],
["Medical Issues", "Medical Issues"],
["Business Venture Failed", "Business Venture Failed"],
["Increase in Loan Payment", "Increase in Loan Payment"],
["Poor Budgeting", "Poor Budgeting"],
["Increase in Expenses", "Increase in Expenses"],
["Death of Family Member", "Death of Family Member"],
["Other", "Other"]
]
end
# Helper for Homebuying update and create forms
def learned_from
[
["A Friend", "A Friend"],
["Referred by my loan officer", "Referred by my loan officer"],
["Referred by my realtor", "Referred by my realtor"],
["Saw an ad in Hoy", "Saw an ad in Hoy"],
["Facebook", "Facebook"],
["Email blast", "Email blast"],
]
end
def loan_type
[
["Fixed", "Fixed"],
["Adjustable", "Adjustable"],
["FHA", "FHA"],
["Interest Only", "Interest Only"],
["Conventional", "Conventional"],
["VA", "VA"],
["ARM", "ARM"],
["Hybrid ARM", "Hybrid ARM"]
]
end
def down_payment_assistance_program
[
["DDP", "DDP"],
["IHDA", "IHDA"],
["CCLT", "CCLT"],
["Home Steps", "Home Steps"],
["New Homes for Chicago", "New Homes for Chicago"],
["Inclusive Community", "Inclusive Community"],
["Chicago NSP", "Chicago NSP"],
["City Lots for City Living", "City Lots for City Living"],
["Other", "Other"]
]
end
def gender_options
[
['Male', 'Male'],
['Female', 'Female']
]
end
def contact_method_options
[
['Email', 'Email'],
['Cell Phone', 'Cell Phone'],
['Home Phone', 'Home Phone'],
['Work Phone', 'Work Phone']
]
end
def language_options
[
['English', 'English'],
['Spanish', 'Spanish']
]
end
def marital_status_options
[
['Married', 'Married'],
['Divorced', 'Divorced'],
['Single', 'Single'],
['Widowed', 'Widowed']
]
end
end | true |
487e7695adcf0886fb92b64c167b04ea5b03e2cf | Ruby | virajkulkarni14/Jukutatsu | /lib/DataStructures/sll.rb | UTF-8 | 333 | 2.734375 | 3 | [] | no_license | require_relative 'LinkedListNodeADT'
class DataStructures::SinglyLinkedListADT
LLNode = DataStructures::LinkedListNodeADT.new(:value, :next)
attr_accessor :head
def initialize self
self.head = LLNode.new(nil, nil)
end
def length
end
def appendToTail
end
def insertNode
end
def deleteNode
end
end
| true |
24f125d926b433c3e2cfaf0842c3cf2510123fc4 | Ruby | Code-Alliance-Archive/ChartClassifier | /utils.rb | UTF-8 | 112 | 2.625 | 3 | [] | no_license | def is_image?(file)
file.to_s.include?(".gif") or file.to_s.include?(".png") or file.to_s.include?(".jpg")
end | true |
ca901af90f08832d2122ccf0fe52689401712b70 | Ruby | guerilla-di/tracksperanto | /lib/tracksperanto/format_detector.rb | UTF-8 | 1,002 | 3 | 3 | [
"MIT"
] | permissive | # Finds a suitable importer for the chosen file path. Or at least tries to, based on the file extension.
# Will then examine all the importers and ask them if they can handle the specified file
class Tracksperanto::FormatDetector
def initialize(with_path)
perform_detection(with_path)
freeze
end
# Tells if an importer has been found for this file
def match?
!!@importer_klass
end
# Returns the importer if there is one
def importer_klass
@importer_klass
end
# Tells if comp size needs to be provided
def auto_size?
match? ? importer_klass.autodetects_size? : false
end
# Returns the human name of the importer
def human_importer_name
match? ? importer_klass.human_name : "Unknown format"
end
private
def perform_detection(for_path)
return unless (for_path && !for_path.to_s.empty?)
ext = File.extname(for_path.downcase)
@importer_klass = Tracksperanto.importers.find{ |i| i.distinct_file_ext == ext }
end
end
| true |
17b982e5b9c885a574f1ebd6c658c5191ac5af0c | Ruby | pathways2050/excel_to_code | /spec/simplify/count_formula_references_spec.rb | UTF-8 | 792 | 2.75 | 3 | [
"MIT"
] | permissive | require_relative '../spec_helper'
describe CountFormulaReferences do
it "should be able to count the number of times a formula is referenced" do
references = {
'sheet1' => {
'A1' => [:cell, "$A$2"],
'A2' => [:cell, "A3"],
'A3' => [:number, 1]
},
'sheet2' => {
'A1' => [:cell, "A2"],
'A2' => [:sheet_reference,'sheet3',[:cell,'A1']],
'A3' => [:cell, "A2"]
},
'sheet3' => {
'A1' => [:number, 5],
'A5' => [:number, 10]
}
}
reference_count = {
'sheet1' => {
'A1' => 0,
'A2' => 1,
'A3' => 1
},
'sheet2' => {
'A1' => 0,
'A2' => 2,
'A3' => 0
},
'sheet3' => {
'A1' => 1,
'A5' => 0
}
}
counter = CountFormulaReferences.new
counter.count(references).should == reference_count
end # / do
end # / describe
| true |
e49f15c2c306418b5ada05620e10a9ee302ba85d | Ruby | cfis/tensorflow-ruby | /lib/tensorflow/name_scope.rb | UTF-8 | 1,124 | 2.953125 | 3 | [
"MIT"
] | permissive | require 'set'
module Tensorflow
class NameScope
attr_reader :stack, :names
def initialize
@stack = Array.new
@names = Set.new
end
def name_scope(base_name)
name = self.unique_name(base_name)
stack.push(name)
begin
yield current_scope if block_given?
ensure
stack.pop
end
end
def current_scope
if self.stack.last.nil?
nil
else
self.stack.join("/")
end
end
def scoped_name(name)
base_name = case
when self.stack.empty?
name
when self.stack.last.nil?
name
else
"#{self.current_scope}/#{name}"
end
self.unique_name(base_name)
end
def unique_name(name)
return nil unless name
i = 0
check_name = name
while self.names.include?(check_name.downcase)
i += 1
check_name = "#{name}_#{i}"
end
self.names << check_name.downcase unless check_name.nil?
check_name
end
end
end
| true |
c615c64e40644e41eb668d72aa2b98b9ac3cd002 | Ruby | servsecCrucible/hw_3-credit_card_crypto | /aes_cipher.rb | UTF-8 | 1,013 | 3.203125 | 3 | [] | no_license | ## AesCipher
require 'openssl'
require 'base64'
require 'json'
require 'digest/sha1'
## AesCipher
module AesCipher
def self.encrypt(document, key)
# TODO: Return JSON string of array: [iv, ciphertext]
# where iv is the random intialization vector used in AES
# and ciphertext is the output of AES encryption
# NOTE: Use base64 for ciphertext so that it is screen printable
# Use cipher block chaining mode only!
cipher = OpenSSL::Cipher::AES.new(256, :CBC)
cipher.encrypt
cipher.key = Digest::SHA1.hexdigest(key.to_s)
iv = cipher.random_iv
encrypted = cipher.update(document.to_s) + cipher.final
[iv, encrypted]
end
def self.decrypt(aes_crypt, key)
# TODO: decrypt from JSON output (aes_crypt) of encrypt method above
decipher = OpenSSL::Cipher::AES.new(256, :CBC)
decipher.decrypt
decipher.key = Digest::SHA1.hexdigest(key.to_s)
decipher.iv = aes_crypt[0]
decipher.update(aes_crypt[1].to_s) + decipher.final
end
end
| true |
330dd2fc8a1065a8b0271b0fe4c7ca9791b16f3d | Ruby | FrankYadon/AppAcademyOpen | /week0/hotel_project/lib/hotel.rb | UTF-8 | 808 | 3.625 | 4 | [] | no_license | require_relative "room"
class Hotel
def initialize(name, room_hash)
@name = name
@rooms = {}
room_hash.each { |k, v| @rooms[k] = Room.new(v) }
end
def name
@name.split.map(&:capitalize).join(" ")
end
def rooms
@rooms
end
def room_exists?(room)
@rooms.keys.include?(room)
end
def check_in(person, room)
if self.room_exists?(room)
if @rooms[room].add_occupant(person)
puts "check in successful"
else
puts "sorry, room is full"
end
else
puts "sorry, room does not exist"
end
end
def has_vacancy?
@rooms.each do |room, v|
return true if @rooms[room].full? == false
end
false
end
def list_rooms
@rooms.each do |room, v|
puts "#{room} #{v.available_space}"
end
end
end
| true |
d4c54b2f4b532b653c60d41ca7d3f06e16db185c | Ruby | PhilippePerret/WriterToolbox | /objet/quiz/new.rb | UTF-8 | 1,113 | 2.71875 | 3 | [] | no_license | # encoding: UTF-8
# Seulement pour un administrateur
raise_unless_admin
class Quiz
class << self
# Méthode qui crée la nouvelle base de données de quiz
def create_new_database
@db_name = param(:new_base_test_name).nil_if_empty
check_value_new_database || return
# === CRÉATION DE LA BASE ===
q = new(nil, @db_name)
q.database_create
flash "Création de la nouvelle base de données de quiz : #{@db_name}"
end
def check_value_new_database
@db_name != nil || raise('Il faut donner le nom de la nouvelle base de données.')
reste = @db_name.gsub(/[a-z_]/,'')
reste == '' || raise('Le nom ne doit contenir que des minuscules et le trait plat.')
nexiste_page = (false == all_suffixes_quiz.include?( @db_name ))
nexiste_page || raise('Cette base de données existe déjà.')
true
rescue Exception => e
error( "Impossible de créer la base de données de quiz “#{@db_name}” : #{e.message}" )
end
end #/<<self
end #/Quiz
case param(:operation)
when 'creer_new_base_test'
Quiz.create_new_database
end
| true |
94d2f0be335dbdf305ae0cb6fa0623e0a0f4fc0f | Ruby | stanleysx/w3d1 | /animals.rb | UTF-8 | 353 | 4.59375 | 5 | [] | no_license | print "Enter an animal: "
animal = gets.chomp
puts "The animal is #{animal}"
if animal.downcase == "dog" # Note use == to compare values. = is asigning variables.
puts "woof"
elsif animal.downcase == "cow"
puts "moo"
elsif animal.downcase == "cat"
puts "meow"
else # runs if no other if conditions are true
puts "Don't know about #{animal}"
end | true |
b82687183e2e479e632c0dee9cda226df1484f0d | Ruby | onerobotics/tp_plus | /lib/tp_plus/nodes/for_node.rb | UTF-8 | 665 | 2.78125 | 3 | [
"MIT"
] | permissive | module TPPlus
module Nodes
class ForNode < BaseNode
def initialize(var_node, initial_value_node, final_value_node, block)
@var_node = var_node
@initial_value_node = initial_value_node
@final_value_node = final_value_node
@block = block.flatten.reject {|n| n.is_a?(TerminatorNode) }
end
def block(context)
@s ||= @block.inject("") {|s,n| s << "#{n.eval(context)} ;\n" }
end
def eval(context)
"FOR #{@var_node.eval(context)}=#{@initial_value_node.eval(context)} TO #{@final_value_node.eval(context)} ;\n#{block(context)}ENDFOR"
end
end
end
end
| true |
5a43b2aadc12e148324f978a00da09995a7725d5 | Ruby | 16sheep/oop-practice | /app/models/character.rb | UTF-8 | 387 | 3.1875 | 3 | [] | no_license | class Character
# belongs to movie
# belongs to show
# belongs to actor
attr_accessor :name, :actor, :movie, :show
ALL = []
def initialize(name)
@name = name
ALL << self
end
def self.all
ALL
end
def self.most_apperances
grouped_characters = ALL.group_by{|character| character.name}
grouped_characters.max_by{|k,v| v.length}.name
end
end
| true |
5d142a9cc7e42def10035c761f4b00f9e8ed8ffb | Ruby | sundayspecial/ita | /hw24/lib/script24_01.rb | UTF-8 | 711 | 3.015625 | 3 | [] | no_license | # ========================================================================
# Script = script24_01.rb
# ========================================================================
# Description = "This script outputs plural form from the JSON file"
# Name = "Kristina Rudzinskaya"
# Email = "kristina.rudzinskaya@gmail.com"
# ========================================================================
require 'optparse'
require 'json'
OptionParser.new do |opts|
opts.on("-i", "--input") do
$file_name=ARGV[0]
end
end.parse!
json_file=File.read($file_name)
element=JSON.parse(json_file)
script_name=__FILE__.split("/").to_a.last
puts "My favorite fruits are #{element[script_name]["fruit_a"]}s and #{element[script_name]["fruit_b"]}s" | true |
9a147fb593806b59a14a1bf2e01475bdc1cbe41a | Ruby | YashUppal/appAcademy | /Intro to Programming/Conditionals/larger_number.rb | UTF-8 | 284 | 4.9375 | 5 | [] | no_license | # Write a method larger_number(num1, num2) that takes in two numbers and returns the larger of the two numbers.
def larger_number(num1, num2)
if num1 > num2
return num1
else
return num2
end
end
puts larger_number(42, 28) # => 42
puts larger_number(99, 100) # => 100 | true |
a600db30b32df7c5c17dba6895eefe53cb0bcf48 | Ruby | abetty1218/hotel_app | /app/models/favorite.rb | UTF-8 | 372 | 2.59375 | 3 | [] | no_license | class Favorite < ApplicationRecord
belongs_to :user
validates :name, presence: true
validates :memo, presence: true
validate :memo_length
def memo_length
memo_for_validation = memo.gsub(/\r\n/,"").gsub(/r/,"").gsub(/\s/,"")
if memo_for_validation.length > 250
errors.add(:memo, "は250文字以内で入力してください")
end
end
end
| true |
f013c4520bbeec293ca540f5887a7e4910acf0f9 | Ruby | basman/Sea-Defender | /utils/svg_to_m.rb | UTF-8 | 1,681 | 2.921875 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env ruby
# converts SVG paths to .m
#
# .m format is equivalent to SVG path element, with no whitespace, commands 'a-zA-Z' unchanged,
# and each number normalized into 0.0-1.0 range and converted into unsigned short (0-65535)
require 'rexml/document'
include REXML
require 'vector.rb'
#ARGV = ["../data/model/kronika.svg","../data/model/kronika.mfont"]
if ARGV.count <2
puts "Usage: #{$0} infile.svg outfile.mfont"
exit
end
def normalize(num)
num -= @adder
num /= @divisor
num
end
infile,outfile,*other = ARGV
fo = File.open(outfile,"w")
File.open(infile,"r") {|f|
doc = Document.new(f)
paths = []
allnums = []
["svg/g/path","svg/path"].each do |ename|
doc.elements.each(ename) { |element|
path = element.attributes["d"] || ""
# SVG spec allows for whitespace(and commas) omission in cases where it's considered superfluous,
# so fill the spaces back in to simplify parsing
path.gsub!(","," ")
# 2 passes for ABA -> A B A matching
2.times do
path.gsub!(/([a-zA-Z](\d|\-))|(\d[a-zA-Z])|([a-zA-Z][a-zA-Z])/) {|m| m[0].chr+" "+m[1].chr }
end
path = path.split
# store values for normalization
path.each do |p|
next if p =~ /[a-zA-Z]/
allnums << p.to_f
end
paths << path
}
end
# normalize
min = allnums.min
max = allnums.max
@adder = min.to_f
@divisor = 1/65535.0 * (max - min).to_f
paths.each do |path|
(path).each do |pe|
if pe =~ /[a-zA-Z]/
fo << pe
else
nor = normalize(pe.to_f).round
# puts nor
fo << [nor].pack("S")
end
end
end
}
| true |
7700354d6a2fcdcc5f158897bc7fab51f65c4914 | Ruby | learn-academy-2019-charlie/ruby-assessment-lali20021 | /ruby.rb | UTF-8 | 1,943 | 4.90625 | 5 | [] | no_license | # Ruby Assessments
#### 1. Use two different Ruby loops to loop over this array, multiplying each element by 2.
tempArray = [1, 2, 6, 9, 3, 21]
tempArray = [1, 2, 6, 9, 3, 21]
tempArray.each do |a|
puts a*2
end
puts tempArray.map { |a| a * 2}
#### 2. From all the built in Ruby methods we've seen in class this week, choose three that you think are particularly helpful and create examples to show how they work.
# .lenght
tempArray = [1, 2, 6, 9, 3, 21]
puts tempArray.length
# .reverse
puts tempArray.reverse
# .include?
puts tempArray.include?1
#### 3. Create a method that takes in a sentence and returns a new sentence with the first letter of each word capitalized.
sentence = "hello there, how are you?"
def capsent (str)
newArr = str.split(' ')
newArr.map! { |s|
s.capitalize }
newArr.join(' ')
end
puts capsent (sentence)
# expected output = "Hello There, How Are You?"
#### 4. Create a method that takes in a string and returns a new string with all the vowels removed. HINT: there's a built in string method for this
no_vowels = "I have no vowels"
expected output = " hv n vwls"
no_vowels = "I have no vowels"
def noVowels (str)
str.delete("aeiouAEIOU")
end
puts noVowels(no_vowels)
# expected output = " hv n vwls"
#### 5. Look at this horrible ruby code, and fix it to be good ruby code.
class Example
def initialize(day)
@day=day
end
def say_hi
if @day == 'Friday'
puts "TGIF!"
elsif @day == 'Monday'
puts "Its monday again"
else
puts 'another day'
end
end
end
#### 6a. Create a class called Animal that initializes with a color. Create a method in the class called legs that returns 4.
class Animal
def initialize(color)
@color = color
@leg = 4
end
def legs
return @leg
end
end
#### 6b. Create a new instance of an Animal with a brown color. Return how many legs the animal has.
a = Animal.new("brown")
p a
p a.legs | true |
ae61e2b8c146ab11b13bdbf7a06035fad72380d2 | Ruby | IanMadlenya/Portfolio-Manager | /lib/core_ext/fixnum.rb | UTF-8 | 149 | 2.765625 | 3 | [] | no_license | class Fixnum
def as_currency
((self * 100).round)/100.0
end
end
class Float
def as_currency
((self * 100).round)/100.0
end
end | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.