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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
dc48c7a640260e50b40884d83df901ccf75f8f33 | Ruby | iancanderson/ormivore | /app/converters/account_sql_storage_converter.rb | UTF-8 | 752 | 2.546875 | 3 | [] | no_license | module App
class AccountSqlStorageConverter
STATUS_MAP = Hash.new { |h, k|
raise ArgumentError, "Status #{k.inspect} not known"
}.update(
active: 1,
inactive: 2,
deleted: 3
).freeze
REVERSE_STATUS_MAP = Hash.new { |h, k|
raise ArgumentError, "Status #{k.inspect} not known"
}.update(
Hash[STATUS_MAP.to_a.map(&:reverse)]
).freeze
def attributes_list_to_storage(list)
list
end
def from_storage(attrs)
attrs.dup.tap { |copy|
copy[:status] = REVERSE_STATUS_MAP[copy[:status]] if copy[:status]
}
end
def to_storage(attrs)
attrs.dup.tap { |copy|
copy[:status] = STATUS_MAP[copy[:status]] if copy[:status]
}
end
end
end
| true |
2abbf5ad4639a7aa4da0a232d30795465ada485e | Ruby | javieku/shortest-paths-revisited-np-complete-problems-coursera | /week3/tsp.rb | UTF-8 | 2,536 | 3.765625 | 4 | [] | no_license | require 'singleton'
FIXNUM_MAX = (2**(0.size * 8 - 2) - 1)
FIXNUM_MIN = -(2**(0.size * 8 - 2))
class TravellingSalesmanHeuristic
attr_reader :cost
attr_reader :path
def execute(input)
cities = input.clone
current_city = cities.shift
@cost = 0
@path = []
path.push(current_city)
start = Time.now
while(!cities.empty?) do
next_city = select_next(cities, current_city)
@cost += euclidean_distance(next_city, current_city)
cities.delete(next_city)
current_city = next_city
@path.push(next_city)
if (cities.size % 100 == 0)
puts 'Remaining cities ' + cities.size.to_s + " " + (Time.now - start).to_s
end
end
@path.push(input.first)
@cost += euclidean_distance(current_city, input.first)
end
def select_next(cities, current_city)
closest_city = nil
closest_distance = FIXNUM_MAX
cities.each{ |city|
distance = euclidean_distance(current_city, city)
if distance < closest_distance
closest_city = city
closest_distance = distance
elsif distance == closest_distance
closest_city = city if closest_city.id > city.id
end
}
closest_city
end
def euclidean_distance(point1, point2)
sum_of_squares = 0
sum_of_squares += (point2.x - point1.x)**2
sum_of_squares += (point2.y - point1.y)**2
Math.sqrt(sum_of_squares)
end
end
class City
attr_reader :x
attr_reader :y
attr_reader :id
def initialize(x, y, id)
@x = x
@y = y
@id = id
end
def to_s
'(id: ' + @id.to_s + ' x: ' + @x.to_s + ' y: ' + @y.to_s + ')'
end
end
class InputLoader
include Singleton
def read_cities(filename)
cities = []
File.open(filename, 'r') do |f|
f.each_with_index do |line, index|
if index == 0
next
else
position = line.split(/\s/).reject(&:empty?)
x = position[1].to_f
y = position[2].to_f
cities.push(City.new(x, y, index))
end
end
end
cities
end
end
def main
start = Time.now
city_distances = InputLoader.instance.read_cities 'nn.txt' #"first_1000_sol_48581.txt"
puts 'Cities loaded in memory ' + (Time.now - start).to_s
start = Time.now
heuristic = TravellingSalesmanHeuristic.new
heuristic.execute(city_distances)
puts 'Travelling Salesman Heuristic executed ' + (Time.now - start).to_s
puts 'Minimun cost of a cycle around all the cities is ' + heuristic.cost.to_s
#puts 'Path ' + heuristic.path.to_s
end
main
| true |
9114a27f837079f9d22f7751f459110c350c1cb9 | Ruby | eliottealderson/Week_3_Morpion | /class_tableau.rb | UTF-8 | 3,605 | 3.171875 | 3 | [] | no_license | #3ème partie :
# Maintient l'état du tableau de jeu
require_relative 'class_joueur'
class Tableau
# Initialiser
def initialize
# Configuration de la structure de données à vide
@tableau = Array.new(3){Array.new(3)}
end
# retourne_etat_du_tableau
def retourne_etat_du_tableau
puts
# itère (each do) sur la structure de donnée
@tableau.each do |ligne|
ligne.each do |cellule|
#Afficher un marqueur existant, SI il existe SINON vide
cellule.nil? ? print("-") : print(cellule.to_s)
end
puts
end
puts
end
# ajouter_un_picto
def ajouter_un_picto(position, picto)
# SI case_souhaite_est_valide ?
if case_souhaite_est_valide?(position)
# place le marqueur
@tableau[position[0]][position[1]] = picto
true
# SINON
else
# Message d'erreur
false
end
end
# case_souhaite_est_valide ?
def case_souhaite_est_valide?(position)
# coordonnee_valide
if coordonnee_valide?(position)
# case_non_occupee ?
case_disponible?(position)
end
end
# coordonnee_valide ?
def coordonnee_valide?(position)
# A MOINS QUE la position souhaitee est incluse dans la limite 3 X 3
if (0..2).include?(position[0]) && (0..2).include?(position[1])
true
# SINON Message d'erreur d'affichage
else
puts "la case demandée est hors limite"
end
end
# case_disponible ?
def case_disponible?(position)
# À MOINS QUE la case sur le tableau ne soit occupée
if @tableau[position[0]][position[1]].nil?
true
# SINON Affiche un message d'erreur
else
puts "La case est déjà occupée"
end
end
# diagonale
def diagonale
# Retourner les pictos sur la diagonale
[[ @tableau[0][0],@tableau[1][1],@tableau[2][2] ],
[ @tableau[2][0],@tableau[1][1],@tableau[0][2] ]]
end
# verticale
def verticale
# Retrouner les pictos verticaux
@tableau
end
# horizontale
def horizontale
# Retrouner les pictos horizontaux
horizontale = []
3.times do |i|
horizontale << [@tableau[0][i],@tableau[1][i],@tableau[2][i]]
end
horizontale
end
# complet
def complet?
# toutes les cases sont occupées
@tableau.all? do |ligne|
ligne.none?(&:nil?)
end
end
# combinaison_gagnante
def combinaison_gagnante?(picto)
# victoire_diagonale
# ou victoire_verticale
# ou victoire_horizontale
victoire_diagonale?(picto) ||
victoire_horizontale?(picto) ||
victoire_verticale?(picto)
end
# victoire_diagonale
def victoire_diagonale?(picto)
diagonale.any? do |diag|
diag.all?{|cellule| cellule == picto }
end
end
# victoire_verticale
def victoire_verticale?(picto)
verticale.any? do |vert|
vert.all?{|cellule| cellule == picto }
end
end
# victoire_horizontal ?
def victoire_horizontale?(picto)
horizontale.any? do |horiz|
horiz.all?{|cellule| cellule == picto }
end
#FIN
end
end
| true |
f19e166181fd872bc656370bd79b6e9d7b20502b | Ruby | Zhann/Dinklebot | /lib/plugins/subchecker.rb | UTF-8 | 1,399 | 2.796875 | 3 | [] | no_license | require 'cinch'
require 'snoo'
# This class needs refactoring!
# original source: i
# https://gist.githubusercontent.com/makzu/4166608/raw/caeb58500a4d4496ec41bb9114f6d05f7587e116/subchecker.rb
class SubChecker
include Cinch::Plugin
def initialize(*args)
super
@reddit = Snoo::Client.new
listings = get_listings
@already_checked = listings['data']['children'].map { |post| post['data']['id'] }
@already_checked.reverse!
end
def get_listings
@reddit.get_listing(
subreddit: 'DestinyTheGame',
page: 'top',
sort: 'new'
)
end
timer 61, method: :check
def check
listings = get_listings
debug 'Checking sub. Got ids: ' + listings['data']['children'].map { |post| post['data']['id'] }.to_s
listings['data']['children'].each do |post|
unless @already_checked.include? post['data']['id']
posttitle = post['data']['title'].gsub(/[\x00-\x1f]/, '')
posttitle.gsub!("\n", '')
# TODO add formatting?
Channel('#destinythegame').send "#{posttitle} - #{post['data']['over_18'] ? "\cB[NSFW]\cB " : ''}post by #{post['data']['author']} at http://redd.it/#{post['data']['id']}"
@already_checked.push post['data']['id']
@already_checked.shift if @already_checked.length > 100
end
end
end
end
| true |
40402314f91db8a673298318349df3806e088064 | Ruby | kalifs/notonthehightstreet | /specs/app/product_spec.rb | UTF-8 | 371 | 2.65625 | 3 | [] | no_license | require 'minitest/autorun'
require 'product'
describe Product do
def product
@product ||= Product.new(code: 'the_code', name: 'the name', price: 9.99)
end
it 'has code' do
assert_equal('the_code', product.code)
end
it 'has name' do
assert_equal('the name', product.name)
end
it 'has price' do
assert_equal(9.99, product.price)
end
end
| true |
11c403af378e44200a2187d667ddaeebc25d429c | Ruby | enowmbi/Ruby-Exercises | /exponentiation.rb | UTF-8 | 162 | 3.578125 | 4 | [] | no_license | =begin
Exponentiation
x^n = x * x^n-1
=end
def pow(x,n)
return 1 if n == 0
return x * pow(x,n-1)
end
puts pow(2,10)
puts pow(3,10)
puts pow(5,10)
| true |
aaead7bdcef3971e66eeab4897495e4069767c0c | Ruby | massun1999/fourth-wave | /spec/models/user_spec.rb | UTF-8 | 7,080 | 2.546875 | 3 | [] | no_license | require 'rails_helper'
RSpec.describe User, type: :model do
before do
@user = FactoryBot.build(:user)
end
describe 'ユーザー新規登録' do
context '新規登録ができる時' do
it "全ての項目が正しく入力されている時" do
expect(@user).to be_valid
end
end
context '新規登録ができない時' do
it "nicknameが空のとき" do
@user.nickname = ""
@user.valid?
expect(@user.errors.full_messages).to include("Nickname can't be blank")
end
it "emailが空のとき" do
@user.email = ""
@user.valid?
expect(@user.errors.full_messages).to include("Email can't be blank")
end
it "すでに登録されているemailアドレスは登録できない" do
@user.save
another_user = FactoryBot.build(:user)
another_user.email = @user.email
another_user.valid?
expect(another_user.errors.full_messages).to include("Email has already been taken")
end
it "passwordが5文字以下だと登録できない" do
@user.password = "abcd5"
@user.valid?
expect(@user.errors.full_messages).to include("Password is too short (minimum is 6 characters)")
end
it "passwordに半角数字が含まれていないと登録できない" do
@user.password = "abcdefg"
@user.valid?
expect(@user.errors.full_messages).to include("Password is invalid")
end
it "passwordに全角漢字が含まれると登録できない" do
@user.password = "abcd2山"
@user.valid?
expect(@user.errors.full_messages).to include("Password is invalid")
end
it "passwordに全角かなが含まれると登録できない" do
@user.password = "abcd1やまだ"
@user.valid?
expect(@user.errors.full_messages).to include("Password is invalid")
end
it "passwordに全角カナが含まれると登録できない" do
@user.password = "abcd1ヤマダ"
@user.valid?
expect(@user.errors.full_messages).to include("Password is invalid")
end
it "passwordに記号が含まれると登録できない" do
@user.password = "abcde.1"
@user.valid?
expect(@user.errors.full_messages).to include("Password is invalid")
end
it "passwordが正しく入力されていてもpassword_confirmationが空だと登録できない" do
@user.password_confirmation = ""
@user.valid?
expect(@user.errors.full_messages).to include("Password confirmation doesn't match Password")
end
it "passwordとpassword_confirmationが一致していないと登録できない" do
@user.password = "yamada628"
@user.password_confirmation = "tanaka123"
@user.valid?
expect(@user.errors.full_messages).to include("Password confirmation doesn't match Password")
end
it "first_nameが空だと登録できない" do
@user.first_name = ""
@user.valid?
expect(@user.errors.full_messages).to include("First name can't be blank")
end
it "first_nameに数字が含まれると登録できない" do
@user.first_name = "やマ田1"
@user.valid?
expect(@user.errors.full_messages).to include("First name is invalid")
end
it "first_nameに半角英字が含まれると登録できない" do
@user.first_name = "やマ田a"
@user.valid?
expect(@user.errors.full_messages).to include("First name is invalid")
end
it "last_nameが空だと登録できない" do
@user.last_name = ""
@user.valid?
expect(@user.errors.full_messages).to include("Last name can't be blank")
end
it "last_nameに数字が含まれると登録できない" do
@user.last_name = "やマ田1"
@user.valid?
expect(@user.errors.full_messages).to include("Last name is invalid")
end
it "last_nameに半角英字が含まれると登録できない" do
@user.last_name = "やマ田a"
@user.valid?
expect(@user.errors.full_messages).to include("Last name is invalid")
end
it "first_rubyが空だと登録できない" do
@user.first_ruby = ""
@user.valid?
expect(@user.errors.full_messages).to include("First ruby can't be blank")
end
it "first_rubyに全角漢字が含まれると登録できない" do
@user.first_ruby = "ヤマ田"
@user.valid?
expect(@user.errors.full_messages).to include("First ruby is invalid")
end
it "first_nameに全角かなが含まれると登録できない" do
@user.first_ruby = "やマダ"
@user.valid?
expect(@user.errors.full_messages).to include("First ruby is invalid")
end
it "first_rubyに半角英字が含まれると登録できない" do
@user.first_ruby = "yaマダ"
@user.valid?
expect(@user.errors.full_messages).to include("First ruby is invalid")
end
it "first_rubyに数字が含まれると登録できない" do
@user.first_ruby = "ヤマダ1"
@user.valid?
expect(@user.errors.full_messages).to include("First ruby is invalid")
end
it "first_rubyに記号が含まれると登録できない" do
@user.first_ruby = "ヤマダ。"
@user.valid?
expect(@user.errors.full_messages).to include("First ruby is invalid")
end
it "last_rubyが空だと登録できない" do
@user.last_ruby = ""
@user.valid?
expect(@user.errors.full_messages).to include("Last ruby can't be blank")
end
it "last_rubyに全角漢字が含まれると登録できない" do
@user.last_ruby = "ヤマ田"
@user.valid?
expect(@user.errors.full_messages).to include("Last ruby is invalid")
end
it "last_nameに全角かなが含まれると登録できない" do
@user.last_ruby = "やマダ"
@user.valid?
expect(@user.errors.full_messages).to include("Last ruby is invalid")
end
it "last_rubyに半角英字が含まれると登録できない" do
@user.last_ruby = "yaマダ"
@user.valid?
expect(@user.errors.full_messages).to include("Last ruby is invalid")
end
it "last_rubyに数字が含まれると登録できない" do
@user.last_ruby = "ヤマダ1"
@user.valid?
expect(@user.errors.full_messages).to include("Last ruby is invalid")
end
it "last_rubyに記号が含まれると登録できない" do
@user.last_ruby = "ヤマダ。"
@user.valid?
expect(@user.errors.full_messages).to include("Last ruby is invalid")
end
it "birthdayが空だと登録できない" do
@user.birthday = ""
@user.valid?
expect(@user.errors.full_messages).to include("Birthday can't be blank")
end
end
end
end
| true |
82b333d7d30ca6f89358d99df3dc22ac8e3a0b3f | Ruby | lshimokawa/activegraph | /spec/unique_class.rb | UTF-8 | 700 | 2.71875 | 3 | [
"MIT"
] | permissive | module UniqueClass
@counter = 1
class << self
def _unique_random_number
"#{Time.now.year}#{Time.now.to_i}#{Time.now.usec.to_s[0..2]}".to_i
end
def set(klass, name = nil)
name ||= "Model_#{@counter}_#{_unique_random_number}"
@counter += 1
klass.class_eval <<-RUBY
def self.to_s
"#{name}"
end
RUBY
# Object.send(:remove_const, name) if Object.const_defined?(name)
Object.const_set(name, klass) # unless Kernel.const_defined?(name)
klass
end
def create(class_name = nil, &block)
clazz = Class.new
set(clazz, class_name)
clazz.class_eval(&block) if block
clazz
end
end
end
| true |
d3e53296669834ed278188129edefd593a114a19 | Ruby | MAWAAW/rogue-like | /carte/Coord.rb | UTF-8 | 451 | 3.3125 | 3 | [] | no_license | #== Définition de la classe coord pour la gestion des cases dans une matrice
class Coord
@coordX
@coordY
attr_accessor :coordX, :coordY
private_class_method :new
#=== redéfinition de initialize
def initialize(x,y)
@coordX,@coordY = x,y
end
#=== Constructeur de coord
def Coord.creer(x,y)
new(x,y)
end
#=== affichage de coordonnée
def affiche()
print("x=",coordX,"\ny=",coordY,"\n")
end
end
| true |
213fec00e9e02e48a4e0574f20cf47fda2b9d4d0 | Ruby | Joewebsta/futbol | /lib/league_statistics.rb | UTF-8 | 2,279 | 2.8125 | 3 | [] | no_license | module LeagueStatistics
def count_of_teams
teams.count
end
def best_offense
best_offense_id = avg_goals_per_game_by_team(game_teams).max_by { |_id, goals| goals }[0]
team_name_by_id[best_offense_id]
end
def worst_offense
worst_offense_id = avg_goals_per_game_by_team(game_teams).min_by { |_id, goals| goals }[0]
team_name_by_id[worst_offense_id]
end
def highest_scoring_visitor
away_games_arr = filter_by_hoa('away')
highest_scoring_visitor_by_id = avg_goals_per_game_by_team(away_games_arr).max_by { |_id, goals| goals }[0]
team_name_by_id[highest_scoring_visitor_by_id]
end
def highest_scoring_home_team
home_games = filter_by_hoa('home')
high_scoring_home_team_id = avg_goals_per_game_by_team(home_games).max_by { |_id, goals| goals }[0]
team_name_by_id[high_scoring_home_team_id]
end
def lowest_scoring_visitor
away_games_arr = filter_by_hoa('away')
lowest_scoring_visitor_by_id = avg_goals_per_game_by_team(away_games_arr).min_by { |_id, goals| goals }[0]
team_name_by_id[lowest_scoring_visitor_by_id]
end
def lowest_scoring_home_team
home_games = filter_by_hoa('home')
low_scoring_home_team_id = avg_goals_per_game_by_team(home_games).min_by { |_id, goals| goals }[0]
team_name_by_id[low_scoring_home_team_id]
end
private
def tot_goals_by_team(data)
data.sort_by { |game| game.team_id.to_i }.each_with_object({}) do |game, hash|
hash.default = 0
hash[game.team_id] += game.goals.to_i
end
end
def tot_games_by_team(data)
data.sort_by { |game| game.team_id.to_i }.each_with_object({}) do |game, hash|
hash.default = 0
hash[game.team_id] += 1
end
end
def avg_goals_per_game_by_team(data)
tot_goals_by_team(data).each_with_object({}) do |team_id_goals, hash|
team_id = team_id_goals[0]
team_goals = team_id_goals[1].to_f
tot_team_games = tot_games_by_team(data)[team_id]
hash[team_id] = (team_goals / tot_team_games).round(2)
end
end
def team_name_by_id
teams.sort_by { |team| team.team_id.to_i }.each_with_object({}) do |team, hash|
hash[team.team_id] = team.team_name
end
end
def filter_by_hoa(type)
game_teams.select { |game| game.hoa == type }
end
end
| true |
0fcb3222999eb9d4e9dd0f47367ffd76614ed4cf | Ruby | renatobiohazard/JogoRuby | /Game/jogmaquina.rb | UTF-8 | 449 | 2.75 | 3 | [] | no_license | require 'gosu'
require 'Gerar_cartas'
class Jogmaquina
def initialize (window)
@calculo=0
@maior=0
@mjogada=Gerar_cartas.new(self)
end
def calcular(cal)
if(cal[0]>cal[1] and cal[0]>cal[2]) then
@maior=cal[0]
@mjogada.jogadamaquina(@maior)
elsif (cal[1]>cal[0] and cal[1]>cal[2]) then
@maior=cal[1]
@mjogada.jogadamaquina(@maior)
elsif (cal[2]>cal[0] and cal[2]>cal[1]) then
@maior=cal[2]
@mjogada.jogadamaquina(@maior)
end
end
end
| true |
bfe4573981bbb4520fa41f0f8343699412eb729c | Ruby | marlonmarcos21/alpha7 | /app/lib/hacker_news_request.rb | UTF-8 | 735 | 2.5625 | 3 | [] | no_license | class HackerNewsRequest
attr_reader :net_http, :uri
ENDPOINT = 'http://hn.algolia.com/api/v1/search_by_date'.freeze
def initialize(**args)
args.reverse_merge!(
hitsPerPage: 10, # limited to 10 so pagination can be used, only has 13 results, default was 20
restrictSearchableAttributes: 'url',
query: 'github',
numericFilters: 'points>1000'
)
@uri = URI ENDPOINT
@uri.query = args.to_param
@net_http = Net::HTTP.new(uri.host, uri.port)
end
def results(page = 0)
JSON.parse(
net_http.request(
request(page)
).body
)
end
private
def request(page = 0)
uri.query = "#{uri.query}&page=#{page}"
Net::HTTP::Get.new(uri.request_uri)
end
end
| true |
fa35e4e2b8ea2a75759d159ed3223b20b3ab5c24 | Ruby | laurenkruczyk/Dive_In | /dive_in/spec/features/visitor_search_for_divesite_spec.rb | UTF-8 | 1,240 | 2.515625 | 3 | [] | no_license | require 'spec_helper'
feature 'visitor can search for a divesite based on his preferences', %Q{
As an unauthenticated user
I can search for a divesite based on certain criteria
So I can find the perfect place to dive
} do
#Acceptance Critera
#A visitor can search for a divesite given:
#1. Category 2. Month 3. Country
#A list of divesites matching his preferences is shown, with links to the individual divesite page
#If no divesite is found matching his preferences, an error message is shown
before :each do
@divesite = FactoryGirl.create(:divesite)
category = FactoryGirl.create(:category)
month = FactoryGirl.create(:month)
@divesite.categories << category
@divesite.months << month
end
scenario 'visitor inputs preferences that match an existing divesite' do
visit root_path
click_on "Search for the Perfect Divesite"
select @divesite.categories.first, from: "Category"
select @divesite.months.first, from: "Month"
select @divesite.country, from: "Country"
select "Search for Divesite"
expect(page).to have_content(@divesite.name)
expect(page).to have_content("1 divesite found matching your preferences")
end
scenario 'visitor inputs preferences that do not match an existing divesite'
end
| true |
cfd0aced5d4a4c41ca4a273a26dee9c42d38dcfc | Ruby | cmirnow/Tic-Tac-Toe-AI-with-Neural-Network | /bin/starting.rb | UTF-8 | 443 | 2.59375 | 3 | [
"MIT"
] | permissive | require_relative './game.rb'
puts ' '
puts '********* MASTERPRO.WS PROJECT ***********'
puts 'Welcome to Tic Tac Toe with Artificial Intelligence!'
puts '--------------------------------'
puts 'Loading data...'
puts 'Please wait.'
puts ' '
class Starting
Array_of_games = CSV::WithProgressBar.read('ss.csv').each.to_a
def self.beginning_of_game
game = Interface.new
game.start
game.play
end
end
Starting.beginning_of_game
| true |
67648a2b943e6842f3770989b6d9a569a1b7b83f | Ruby | alxersov/bootcamp | /task-03/notes.rb | UTF-8 | 1,269 | 3.515625 | 4 | [] | no_license | FILE_NAME = 'notes.txt'
def help_command
puts %{
Available commands:
-a or --add adds an item into the list
-l or --list displays the list
-r or --remove removes the n-th note from the list
-c or --clear clears the list
-h or --help shows list of available commands
}
end
def add_command(params)
open(FILE_NAME, 'a') do |file|
params.each do |note|
file.write(note)
file.write("\n")
end
end
end
def list_command
open(FILE_NAME) do |file|
n = 0
file.each do |line|
puts "<#{n}>: #{line}"
n += 1
end
end
end
def remove_command(params)
index = params.first.to_i
open(FILE_NAME, 'r+') do |file|
notes = file.inject([]) { |notes, note| notes.push(note) }
notes.delete_at(index)
file.truncate(0)
notes.each { |note| file.write(note) }
end
end
def clear_command
open(FILE_NAME, 'w') { |file| file.truncate(0) }
end
command, *params = ARGV
case command
when '-a', '--add'
add_command(params)
when '-l', '--list'
list_command
when '-r', '--remove'
remove_command(params)
when '-c', '--clear'
clear_command
else
help_command
end
| true |
5dd870bf60b96358cff8e6c6dd104e0b36b7f1d1 | Ruby | russellschmidt/bloc_works | /lib/bloc_works/router.rb | UTF-8 | 654 | 2.578125 | 3 | [
"MIT"
] | permissive | module BlocWorks
class Application
def controller_and_action(env)
# this just returns elements no. 2, 3 & assigns to variables
# then adjusts to proper naming conventions
# this becomes a reference to the ExampleController class
# not just the string 'ExampleController'
_, controller, action, _ = env["PATH_INFO"].split("/", 4)
controller = controller.capitalize
controller = "#{controller}Controller"
someVar = Object.const_get(controller)
[someVar, action]
end
def fav_icon(env)
if env['PATH_INFO'] == '/favicon.ico'
return [404, {'Content-Type' => 'text/html'}, ['404 Not Found']]
end
end
end
end | true |
409ffbd4602375258b57debc4023fcc883da2bb8 | Ruby | cankayakubra/RubyProject | /ortas.rb | UTF-8 | 1,836 | 3.46875 | 3 | [
"Apache-2.0"
] | permissive |
class Orta
<<<<<<< HEAD
def initialize a
@a = a
end
def oyunabasla
ran=rand(0..1)
if ran==1
sira=1
@a.yazdir("PC basliyor")
else
sira=2
@a.yazdir("Oyuncu basliyor")
=======
def initialize
@ran = nil
@b = nil
@sira = nil
@cev=nil
@isim=nil
end
def oyunabasla
@a.yazdir("Kullanici adi : ")
isim=gets.strip
ran=rand(0..1)
if ran==1
sira=1
@a.yazdir("PC basliyor")
else
sira=2
@a.yazdir("#{isim.strip} basliyor")
>>>>>>> 91016ebbd68a14b4a18b2a3e2ca414c7a00f5088
end
ran = rand(10...100)
@a.yazdir("Baslanacak sayi #{ran}\n")
loop do
if sira==1
sira=2
if ran<=4
cev=ran-1
elsif ran%4==0
cev=3
<<<<<<< HEAD
elsif ran%4==2
cev=1
elsif ran%4==3
cev=2
else
=======
elsif ran%4==2
cev=1
elsif ran%4==3
cev=2
else
>>>>>>> 91016ebbd68a14b4a18b2a3e2ca414c7a00f5088
cev=rand(1..3)
end
ran-=cev
@a.yazdir("PC nin sırası : #{cev}\n")
if ran==1
@a.yazdir("PC kazandı!\n")
break
end
<<<<<<< HEAD
elsif sira==2
=======
elsif sira==2
>>>>>>> 91016ebbd68a14b4a18b2a3e2ca414c7a00f5088
@a.yazdir("oyuncunun sirasi : ")
loop do
cev=gets.to_i
if cev >=0 and cev <=3
break
end
@a.yazdir("Hatali secim!\nTekrar sayı giriniz :")
end
ran-=cev
sira=1
if ran==1
@a.yazdir("Oyuncu #{isim.strip} kazandı!")
@a.yazdir(cev)
break
end
end
<<<<<<< HEAD
@a.yazdir("Sayının son değeri #{ran}\n")
=======
>>>>>>> 91016ebbd68a14b4a18b2a3e2ca414c7a00f5088
end
@a.yazdir("Sayının son değeri #{ran}\n")
end
end
<<<<<<< HEAD
=======
oyun=Orta.new()
oyun.oyunabasla
>>>>>>> 91016ebbd68a14b4a18b2a3e2ca414c7a00f5088
| true |
8dfb96f79e4b8d144ccdf972b82f29eb46183674 | Ruby | moresmiles/ttt-10-current-player-v-000 | /lib/current_player.rb | UTF-8 | 219 | 3.3125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def turn_count(board)
counter = 0
board.each do |count|
if count == "X"||count == "O"
counter += 1
end
end
counter
end
def current_player(board)
if turn_count(board) % 2 == 0
"X"
else
"O"
end
end
| true |
fc99a2a2839fd53c5fa51d152f3eb8987387f877 | Ruby | montch/adjective_animal | /spec/adjective_animal_spec.rb | UTF-8 | 1,927 | 3.609375 | 4 | [
"MIT"
] | permissive | require 'spec_helper'
describe AdjectiveAnimal do
it "creates a name using adjective_animal" do
adjective_animal = AdjectiveAnimal.new
expect(adjective_animal.adj.length).to be > 0
expect(adjective_animal.ani.length).to be > 0
end
it "creates a name using the same starting letter as the symbol or string passed in" do
adjective_animal = AdjectiveAnimal.new(:y)
expect(adjective_animal.adj).to start_with 'Y'
expect(adjective_animal.ani).to start_with 'Y'
adjective_animal = AdjectiveAnimal.new(:K)
expect(adjective_animal.adj).to start_with 'K'
expect(adjective_animal.ani).to start_with 'K'
adjective_animal = AdjectiveAnimal.new('b')
expect(adjective_animal.adj).to start_with 'B'
expect(adjective_animal.ani).to start_with 'B'
adjective_animal = AdjectiveAnimal.new('C')
expect(adjective_animal.adj).to start_with 'C'
expect(adjective_animal.ani).to start_with 'C'
end
it "ignores new() arguments that are not a single character or a single symbol" do
adjective_animal = AdjectiveAnimal.new('woops')
expect(adjective_animal.adj.length).to be > 0
expect(adjective_animal.ani.length).to be > 0
adjective_animal = AdjectiveAnimal.new('1')
expect(adjective_animal.adj.length).to be > 0
expect(adjective_animal.ani.length).to be > 0
end
it "generates an array of 26 objects with letters A-Z" do
adjective_animals = AdjectiveAnimal.all
expect(adjective_animals.length).to eql 26
expect(adjective_animals.first.adjective).to start_with 'A'
expect(adjective_animals.first.animal).to start_with 'A'
expect(adjective_animals.last.adjective).to start_with 'Z'
expect(adjective_animals.last.animal).to start_with 'Z'
end
it "outputs the adjective and animal as two words using to_s" do
adjective_animal = AdjectiveAnimal.new
expect(adjective_animal.to_s.split(' ').length).to eql 2
end
end | true |
0d07a89ef026c2af403a145355d4ea48f9d7fcce | Ruby | cbonnet99/xero_gateway | /lib/xero_gateway/phone.rb | UTF-8 | 1,306 | 2.828125 | 3 | [
"ISC"
] | permissive | module XeroGateway
class Phone
attr_accessor :phone_type, :number, :area_code, :country_code
def initialize(params = {})
params = {
:phone_type => "DEFAULT"
}.merge(params)
params.each do |k,v|
self.instance_variable_set("@#{k}", v) ## create and initialize an instance variable for this key/value pair
self.send("#{k}=", v)
end
end
def to_xml(b = Builder::XmlMarkup.new)
b.Phone {
b.PhoneType phone_type
b.PhoneNumber number
b.PhoneAreaCode area_code if area_code
b.PhoneCountryCode country_code if country_code
}
end
def self.from_xml(phone_element)
phone = Phone.new
phone_element.children.each do |element|
case(element.name)
when "PhoneType" then phone.phone_type = element.text
when "PhoneNumber" then phone.number = element.text
when "PhoneAreaCode" then phone.area_code = element.text
when "PhoneCountryCode" then phone.country_code = element.text
end
end
phone
end
def ==(other)
[:phone_type, :number, :area_code, :country_code].each do |field|
return false if send(field) != other.send(field)
end
return true
end
end
end | true |
cc1a00439379afb2df9661de9767f14edb0ae5ff | Ruby | nakaaza/AtCoder | /practice/practice_contest/B.rb | UTF-8 | 78 | 2.984375 | 3 | [] | no_license | n = gets.to_i
q = gets.chomp.to_i
arr = ('A'..'Z').to_a.slice(0, n)
puts arr
| true |
df86ed14a5dd70a3131f4d626224222f1eb939f6 | Ruby | surfer8137/KataBankOCR | /lib/accountmanager.rb | UTF-8 | 281 | 2.828125 | 3 | [] | no_license | require_relative 'checksum.rb'
class AccountManager
class << self
def check(number)
valid = Checksum.calculate(number)
return number + ' ILL' if valid == -1
return number + ' ERR' if valid != 0
return number if valid == 0
end
end
end
| true |
313f0b6af26567ecb0224cbc0cbb29a58f550105 | Ruby | kennyfrc/puzzlenode-solutions-1 | /13_chess_validator/lib/rules/move_validator.rb | UTF-8 | 769 | 2.953125 | 3 | [] | no_license | require 'rules/rulebook'
class MoveValidator
def initialize(move)
@move = move
end
def valid?
valid_movement? && valid_path? && destination_ok? && !check?
end
def valid_movement?
raise "#valid_movement? must be defined by subclasses"
end
def valid_path?
@move.board.unobstructed_path_between?(@move.movement.from, @move.movement.to)
end
def destination_ok?
target_piece = @move.board.piece_at(@move.movement.to)
target_piece.nil? || @move.board.piece_at(@move.movement.from).can_capture?(target_piece)
end
def check?
Rulebook.new(@move.board.apply(@move.movement)).check?(@move.piece.color)
end
def board
@move.board
end
def movement
@move.movement
end
def piece
@move.piece
end
end
| true |
6b521132caab283d4e198d588d7d7b681f366c4a | Ruby | macosgrove/toy-robot | /lib/toy_robot.rb | UTF-8 | 924 | 3.25 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
require_relative "factory"
# Entry point. Responsible for calling the Factory to initialise the system, then running the input loop.
class ToyRobot
attr_accessor :verbose, :reporting, :mapping, :output
def initialize(input_stream, output_stream)
@input = input_stream
@output = output_stream
@interpreter = Factory.new.build(self)
@verbose = false
@reporting = false
@mapping = false
end
def run
while (command = input.gets)
process(command)
end
end
private
attr :input, :interpreter
def process(command)
response = interpreter.process(command)
output.puts(response) if response
rescue StandardError => e
output.puts e.message if verbose
ensure
augment_output
end
def augment_output
output.puts(interpreter.process("map")) if mapping
output.puts(interpreter.process("report")) if reporting
end
end
| true |
dd3265568a8bd8a8a1e2c56680de945959ede8b2 | Ruby | AMaleh/glimmer-dsl-swt | /samples/elaborate/tic_tac_toe/board.rb | UTF-8 | 3,915 | 3.359375 | 3 | [
"MIT"
] | permissive | # Copyright (c) 2007-2021 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require_relative 'cell'
class TicTacToe
class Board
DRAW = :draw
IN_PROGRESS = :in_progress
WIN = :win
attr :winning_sign
attr_accessor :game_status
def initialize
@sign_state_machine = {nil => "X", "X" => "O", "O" => "X"}
build_grid
@winning_sign = Cell::EMPTY
@game_status = IN_PROGRESS
end
#row and column numbers are 1-based
def mark(row, column)
self[row, column].mark(current_sign)
game_over? #updates winning sign
end
def current_sign
@current_sign = @sign_state_machine[@current_sign]
end
def [](row, column)
@grid[row-1][column-1]
end
def game_over?
win? or draw?
end
def win?
win = (row_win? or column_win? or diagonal_win?)
self.game_status=WIN if win
win
end
def reset!
(1..3).each do |row|
(1..3).each do |column|
self[row, column].reset!
end
end
@winning_sign = Cell::EMPTY
@current_sign = nil
self.game_status=IN_PROGRESS
end
private
def build_grid
@grid = []
3.times do |row_index| #0-based
@grid << []
3.times { @grid[row_index] << Cell.new }
end
end
def row_win?
(1..3).each do |row|
if row_has_same_sign(row)
@winning_sign = self[row, 1].sign
return true
end
end
false
end
def column_win?
(1..3).each do |column|
if column_has_same_sign(column)
@winning_sign = self[1, column].sign
return true
end
end
false
end
#needs refactoring if we ever decide to make the board size dynamic
def diagonal_win?
if (self[1, 1].sign == self[2, 2].sign) and (self[2, 2].sign == self[3, 3].sign) and self[1, 1].marked
@winning_sign = self[1, 1].sign
return true
end
if (self[3, 1].sign == self[2, 2].sign) and (self[2, 2].sign == self[1, 3].sign) and self[3, 1].marked
@winning_sign = self[3, 1].sign
return true
end
false
end
def draw?
@board_full = true
3.times do |x|
3.times do |y|
@board_full = false if self[x, y].empty
end
end
self.game_status = DRAW if @board_full
@board_full
end
def row_has_same_sign(number)
row_sign = self[number, 1].sign
[2, 3].each do |column|
return false unless row_sign == (self[number, column].sign)
end
true if self[number, 1].marked
end
def column_has_same_sign(number)
column_sign = self[1, number].sign
[2, 3].each do |row|
return false unless column_sign == (self[row, number].sign)
end
true if self[1, number].marked
end
end
end
| true |
2a8bb3069ab18e285ffea2675fb217535156f6f9 | Ruby | lychees/em-midori | /lib/em-midori/core_ext/promise.rb | UTF-8 | 1,336 | 3.203125 | 3 | [
"MIT"
] | permissive | ##
# Meta-programming String for Syntactic Sugars
# Referenced from {Qiita}[http://qiita.com/south37/items/99a60345b22ef395d424]
class Promise
# @param [Proc] callback an async method
def initialize(callback)
@callback = callback
end
# Define what to do after a method callbacks
# @param [Proc] resolve what on callback
# @param [Proc] reject what on callback failed
# @return [nil] nil
def then(resolve = ->() {}, reject = ->() {})
@callback.call(resolve, reject)
end
end
module Kernel
# Logic dealing of async method
# @param [Fiber] fiber a fiber to call
def async_internal(fiber)
chain = lambda do |result|
return if result.class != Promise
result.then(lambda do |val|
chain.call(fiber.resume(val))
end)
end
chain.call(fiber.resume)
end
# Define an async method
# @param [Symbol] method_name method name
# @yield async method
# @example
# async :hello do
# puts 'Hello'
# end
def async(method_name)
define_singleton_method method_name, ->(*args) {
async_internal(Fiber.new { yield(*args) })
}
end
# Block the I/O to wait for async method response
# @param [Promise] promise promise method
# @example
# result = await SQL.query('SELECT * FROM hello')
def await(promise)
Fiber.yield promise
end
end
| true |
1ade3b66e234349c28f66a6b1f782d7e8dbafa1b | Ruby | sharat94/family_tree_sharat | /bin/family_tree | UTF-8 | 1,380 | 3.59375 | 4 | [] | no_license | #!/usr/bin/env ruby
require './lib/person'
require './lib/kingdom'
while true # STDIN
puts "Please enter the selection:"
puts "1. Find relatives"
puts "2. Add new family member"
puts "3. Find maximum number of girl daughters"
puts "4. Find the relation"
input = gets.strip
case input.to_i
when 1
puts "Enter the name"
input_name = gets.strip
puts "Enter the relation"
input_relation = gets.strip
family_members = []
family_members = Person.find_relative(input_name, input_relation)
if family_members.empty?
puts 'No person/relative found'
else
puts "The #{input_relation} of #{input_name} are:"
family_members.compact.flatten.each{ |member| puts member.name }
puts '*' * 50
end
when 2
puts "Enter one of the parents name"
input_name = gets.strip
puts "Enter the details of the baby as (relation: name):"
input_relation, input_new_name = gets.strip.split(/\W+/)
Person.add_new_relative(input_name, input_relation, input_new_name)
when 3
Person.find_maximum_girl_child
when 4
puts "enter the person name"
input_name = gets.strip
puts "enter the relative's name"
input_relative = gets.strip
relation = Person.find_relation(input_name, input_relative)
if relation.empty?
puts 'No relation found'
else
puts relation.last
end
end
end
| true |
2e19be462928047f9737e79d96bc8cebad61eb53 | Ruby | Lebeil/RubyExo | /exo_20.rb | UTF-8 | 609 | 3.828125 | 4 | [] | no_license | puts "merci de saisir un nombre entre 1 et 25 :"
chiffre = gets.chomp.to_i
if chiffre > 0 && chiffre < 25
chiffre.times do |i|
num = i + 1
num.times do |i|
print "#"
end
puts
end
else
puts "Attention entre 0 et 25, recommence !"
end
###### EN VERSION "WHILE" #######
# puts "merci de saisir un nombre entre 1 et 25 :"
# chiffre = gets.chomp.to_i
# n = chiffre
# while n != 0 && n <= 25
# chiffre.times do |i|
# num = i + 1
# num.times do |i|
# print "#"
# end
# puts
# n = n - 1
# end
# end
# if n > 25
# puts "CHANGE VITE CE NOMBRE !"
# end | true |
ef4ba6da03317b562032a14e82d6f46f01c4195e | Ruby | sparklemotion/nokogiri | /test/xml/test_attr.rb | UTF-8 | 4,517 | 2.5625 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"LicenseRef-scancode-other-copyleft",
"LGPL-2.1-only",
"X11",
"GPL-1.0-or-later",
"MPL-2.0",
"LicenseRef-scancode-x11-xconsortium-veillard",
"LicenseRef-scancode-warranty-disclaimer",
"Zlib",
"AGPL-3.0-only",
"LGPL-2.0-o... | permissive | # frozen_string_literal: true
require "helper"
module Nokogiri
module XML
class TestAttr < Nokogiri::TestCase
def test_new
100.times do
doc = Nokogiri::XML::Document.new
assert(doc)
assert(Nokogiri::XML::Attr.new(doc, "foo"))
end
end
def test_new_raises_argerror_on_nondocument
document = Nokogiri::XML("<root><foo/></root>")
assert_raises(ArgumentError) do
Nokogiri::XML::Attr.new(document.at_css("foo"), "bar")
end
end
def test_content=
xml = Nokogiri::XML.parse(File.read(XML_FILE), XML_FILE)
address = xml.xpath("//address")[3]
street = address.attributes["street"]
street.content = "Y&ent1;"
assert_equal("Y&ent1;", street.value)
end
#
# note that the set of tests around set_value include
# assertions on the serialized format. this is intentional.
#
def test_set_value_with_entity_string_in_xml_file
xml = Nokogiri::XML.parse(File.read(XML_FILE), XML_FILE)
address = xml.xpath("//address")[3]
street = address.attributes["street"]
street.value = "Y&ent1;"
assert_equal("Y&ent1;", street.value)
assert_includes(%{ street="Y&ent1;"}, street.to_xml)
end
def test_set_value_with_entity_string_in_html_file
html = Nokogiri::HTML("<html><body><div foo='asdf'>")
foo = html.at_css("div").attributes["foo"]
foo.value = "Y&ent1;"
assert_equal("Y&ent1;", foo.value)
assert_includes(%{ foo="Y&ent1;"}, foo.to_html)
end
def test_set_value_with_blank_string_in_html_file
html = Nokogiri::HTML("<html><body><div foo='asdf'>")
foo = html.at_css("div").attributes["foo"]
foo.value = ""
assert_equal("", foo.value)
assert_includes(%{ foo=""}, foo.to_html)
end
def test_set_value_with_nil_in_html_file
html = Nokogiri::HTML("<html><body><div foo='asdf'>")
foo = html.at_css("div").attributes["foo"]
foo.value = nil
assert_equal("", foo.value) # this may be surprising to people, see xmlGetPropNodeValueInternal
if Nokogiri.uses_libxml?
assert_includes(%{ foo}, foo.to_html) # libxml2 still emits a boolean attribute at serialize-time
else
assert_includes(%{ foo=""}, foo.to_html) # jruby does not
end
end
def test_set_value_of_boolean_attr_with_blank_string_in_html_file
html = Nokogiri::HTML("<html><body><div disabled='disabled'>")
disabled = html.at_css("div").attributes["disabled"]
disabled.value = ""
assert_equal("", disabled.value)
assert_includes(%{ disabled}, disabled.to_html) # we still emit a boolean attribute at serialize-time!
end
def test_set_value_of_boolean_attr_with_nil_in_html_file
html = Nokogiri::HTML("<html><body><div disabled='disabled'>")
disabled = html.at_css("div").attributes["disabled"]
disabled.value = nil
assert_equal("", disabled.value) # this may be surprising to people, see xmlGetPropNodeValueInternal
assert_includes(%{ disabled}, disabled.to_html) # but we emit a boolean attribute at serialize-time
end
def test_unlink # aliased as :remove
xml = Nokogiri::XML.parse(File.read(XML_FILE), XML_FILE)
address = xml.xpath("/staff/employee/address").first
assert_equal("Yes", address["domestic"])
attr = address.attribute_nodes.first
return_val = attr.unlink
assert_nil(address["domestic"])
assert_equal(attr, return_val)
end
def test_parsing_attribute_namespace
doc = Nokogiri::XML(<<~EOXML)
<root xmlns='http://google.com/' xmlns:f='http://flavorjon.es/'>
<div f:myattr='foo'></div>
</root>
EOXML
node = doc.at_css("div")
attr = node.attributes["myattr"]
assert_equal("http://flavorjon.es/", attr.namespace.href)
end
def test_setting_attribute_namespace
doc = Nokogiri::XML(<<~EOXML)
<root xmlns='http://google.com/' xmlns:f='http://flavorjon.es/'>
<div f:myattr='foo'></div>
</root>
EOXML
node = doc.at_css("div")
attr = node.attributes["myattr"]
attr.add_namespace("fizzle", "http://fizzle.com/")
assert_equal("http://fizzle.com/", attr.namespace.href)
end
end
end
end
| true |
cecbc090ce6b7e1acbfc9b12b2874a7dc12d5c5d | Ruby | ese-varo/rubyDojo | /hackerrank/jumping-on-clouds.rb | UTF-8 | 276 | 3.3125 | 3 | [] | no_license | def jumping_on_clouds(c)
required_jumps = 0
pos = 0
p c
puts pos
while pos < c.length - 1
(pos + 2 < c.length) && c[pos + 2].zero? ? pos += 2 : pos += 1
required_jumps += 1
puts pos
end
required_jumps
end
puts jumping_on_clouds([0, 0, 0, 1, 0, 0])
| true |
59fbb99257caaad67eb2da1ad1130febb5fbd6d3 | Ruby | Sravya9K/class_topics | /app/models/book.rb | UTF-8 | 469 | 2.546875 | 3 | [] | no_license | class Book < ActiveRecord::Base
self.per_page = 3
validates :name, uniqueness: true
validates :author, presence: true
#validates :cost, numericality: true
validates :name, length: { minimum: 3, message: " - Please enter minimum 3 chars for book name"}
before_save :merge_book_name
after_destroy :merge_book_name
def merge_book_name
self.name = self.name + "by" + self.author
end
def display_message
logger.error "A book has been deleted.."
end
end
| true |
dbf0c26da5eb008c7e68dd74d12870d57572618a | Ruby | justinhwu/alphabetize-in-esperanto-dc-web-career-040119 | /lib/alphabetize.rb | UTF-8 | 192 | 3.296875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | ESPERANTO_ALPHABET = "abcĉdefgĝhĥijĵklmnoprsŝtuŭvz"
def alphabetize(arr)
# code here
arr.sort_by do |a|
a.split("").map do |b|
ESPERANTO_ALPHABET.index(b)
end
end
end | true |
637a075331ad382460a0e7a823d8a78b48faa7b1 | Ruby | dasch/ruby-bencode | /test/benchmark/encoding.rb | UTF-8 | 226 | 2.53125 | 3 | [
"MIT"
] | permissive | $:.unshift(File.dirname(__FILE__)+"/../../lib")
require 'benchmark'
require 'bencode'
Benchmark.bmbm do |x|
x.report("Encoding an array of integers") do
100.times do
((1..50).to_a * 100).bencode
end
end
end
| true |
ef7e993fda554f39fa57bc87bf0889496865ab80 | Ruby | tomwot/CodeIQ | /triangle_calc/trunk/triangle_calc.rb | SHIFT_JIS | 2,082 | 3.28125 | 3 | [] | no_license | #encoding: Windows-31J
# CodeIQFuwFOp`HӁHv
# https://codeiq.jp/ace/nabetani_takenori/q1097
# ^ꂽOp`̎ނB
# wȂ̂ŗ]藝͖{͈Ⴄނ̎Op`ɕނ\B
# ܂ł͍lȂB
def pick_num(source, prm)
prm.map do |pr|
if (answer = (source.find{|s| s[/#{pr}/] || s[/#{pr.reverse}/]}))
answer[/\d+/].to_f
else
nil
end
end
end
def solve(question)
questions = question.split(',')
angle_cond = questions.grep(/\Ap/)
edge_cond = questions - angle_cond
angle = pick_num(angle_cond, %w(A B C))
edge = pick_num(edge_cond, %w(BC CA AB))
# 3ӂ̒ΐOp`łB
angle.each_index{|i| angle[i] = 60.0} if edge.uniq.count == 1 && edge.first
# ӎOp`͊px1ȂĂc̊pxZołB
if edge.count(nil) <= 1 && edge.uniq.count == 2 && angle.compact.count == 1
top = edge.index{|i| edge.count(i) == 1}
if angle[top]
angle.each_index{|i| angle[i] = (180.0 - angle[top]) / 2 unless i == top}
else
angle.each_index{|i| angle[i] = angle.compact.first unless i == top}
end
end
# sȊpx1ł̊px͎ZołB
angle[angle.index(nil)] = 180.0 - angle.compact.inject(&:+) if angle.count(nil) == 1
if angle.all?
%w(_ )[angle.uniq.count]
elsif edge.count(nil) <= 1
%w(_ _ )[edge.uniq.count]
else
''
end
end
if $0 == __FILE__
answer = ARGF.map do |line|
no, question, expect = line.chomp.split("\t")
fact = solve(question)
if fact == expect
puts "#{no}: Correct."
else
puts "#{no}: Wrong."
puts " question: #{question} , expect: #{expect}, fact: #{fact}"
no
end
end
puts
puts "answer:"
puts answer.compact.join(',')
end
| true |
2e5b601010011faa84160076e3d1e6b1e8d68c13 | Ruby | smunozmo/oop-school-library | /main.rb | UTF-8 | 917 | 3.734375 | 4 | [] | no_license | require './app'
puts "\nWelcome to School Library App!".yellow
# rubocop:disable Metrics/CyclomaticComplexity
def main
app = App.new
loop do
puts
puts 'Please choose an option by entering a number:'.yellow
puts '1 - List all books'.green
puts '2 - List all people'.green
puts '3 - Create a person'.light_blue
puts '4 - Create a book'.light_blue
puts '5 - Create a rental'.light_blue
puts '6 - List all rentals for a given person id'.blue
puts '7 - Exit'.red
puts
print 'Option: '.yellow
input = gets.chomp.to_i
case input
when 1
app.list_books
when 2
app.list_people
when 3
app.create_person
when 4
app.create_book
when 5
app.create_rental
when 6
app.display_rentals_by_id
when 7
app.exit_app
end
break if input == 7
end
end
# rubocop:enable Metrics/CyclomaticComplexity
main
| true |
a04764de7133aeeafbb33e6d9e36b5029aeb04df | Ruby | wallacecnzto/ruby_codes | /ruby_codes/list.rb | UTF-8 | 77 | 2.765625 | 3 | [] | no_license | names = ["wallace", "val", "aristotelina"]
for name in names
puts name
end
| true |
6251bf71bddbcd316f984cce32a80ee3812596e5 | Ruby | randyleighton/address-book-ruby | /lib/contact.rb | UTF-8 | 871 | 3.109375 | 3 | [] | no_license | class Contact
@@all_contacts = []
def Contact.all
@@all_contacts
end
def Contact.clear
@@all_contacts = []
end
def save
@@all_contacts << self
end
def initialize(name)
@name = name
@phone_numbers = []
@addresses = []
@emails = []
end
def add_email_address(address)
@emails << address
end
def emails
@emails
end
def add_phone_number(phone)
@phone_numbers << phone
end
def phone_numbers
@phone_numbers
end
def add_address(address)
@addresses << address
end
def addresses
@addresses
end
def set_address(address)
@address = address
end
def set_phone(phone)
@phone = phone
end
def set_email(email)
@email = email
end
def name
@name
end
def address
@address
end
def phone
@phone
end
def email
@email
end
end
| true |
002b3805928e430037dcff1f85e3fc26aca84bc9 | Ruby | sullivant/euler | /ruby/34.rb | UTF-8 | 201 | 3.375 | 3 | [] | no_license | require 'euler.rb'
curious = Array.new()
3.upto(1000000) do |n|
sumDigFactors = (n.to_s.split(//).collect{|d| d.to_i.factorial}).sum
curious << n if n == sumDigFactors
end
puts curious.join("|") | true |
b0766db19e45f9fd75aa602c4680a9b388912265 | Ruby | thiagofb84jp/automation-project | /XX - Backup Project/xx_backup/ruby_rails/xx_archives/exercicios-ruby-2/1 - estrutura-sequencial/18-tamanho-arquivo-download.rb | UTF-8 | 532 | 3.890625 | 4 | [] | no_license | #1.18 Faça um programa que peça o tamanho de um arquivo para download (em MB) e
#a velocidade de um link de Internet (em Mbps), calcule e informe o tempo
#aproximado de download do arquivo usando este link (em minutos).
puts "Qual o tamanho do arquivo para download (em MB)?"
tamArquivo = gets.to_i
puts "Qual a velocidade do link de internet (em MPBS)?"
velLink = gets.to_i
tempoDownload = tamArquivo * velLink
tempMinutos = tempoDownload / 60.0
puts "O tempo aproximado para download é de #{tempMinutos.round(2)} minutos." | true |
30f83a4b8ab247dd275faa906241f8abb64cb581 | Ruby | bkingon/earthquakes | /app/services/map_marker_attributes.rb | UTF-8 | 505 | 2.796875 | 3 | [] | no_license | class MapMarkerAttributes
def initialize(earthquake)
@earthquake = earthquake
end
def time
Time.at(earthquake['properties']['time'] / 1000).to_datetime.strftime('%B %d, %Y - %I:%M%p')
end
def latitude
earthquake['geometry']['coordinates'][1]
end
def longitude
earthquake['geometry']['coordinates'][0]
end
def magnitude
earthquake['properties']['mag'].to_s
end
def place
earthquake['properties']['place']
end
private
attr_accessor :earthquake
end
| true |
7b9a92a0256a8a289bc871611cbcee3c8201f439 | Ruby | lean4728/scraping_app2 | /app/models/scraping4.rb | UTF-8 | 3,050 | 2.890625 | 3 | [] | no_license | require 'mechanize'
HTTPS = "https:"
LINK_0 = "//music.j-total.net/sp/as/"
LINK_2_DIR = "//music.j-total.net/dbsp/"
ERRMSG_GET_LINK = "GETリクエストエラー発生"
XPATH_LINK_0 = "/html/body/table[4]/tr/td/div/a"
XPATH_LINK_1 = "/html/body/ul[3]/li/a"
XPATH_LINK_2 = "/html/body/table[6]/tr/td/div/form/p/a[@target='_blank']"
XPATH_LINK_2_NEXT = "/html/body/center[3]/font/a"
XPATH_LINK_2_NEXT_2 = "/html/body/center[3]/font/a[2]"
def get_child_links(agent, link, xpath)
links = []
page = nil
begin
page = agent.get(HTTPS + link)
rescue
puts ERRMSG_GET_LINK
puts HTTPS + link
puts ""
end
if page
elements = page / xpath
elements&.each { |e| links << e.get_attribute("href") }
# links = elements&.map { |e| e.get_attribute("href") } # linksにnilが代入されてしまう恐れがあるため不可
# links = elements&.map(&:get_attribute("href")) # ("href")の'()'で不可
end
return links, page
end
agent = Mechanize.new
links_1 = get_child_links(agent, LINK_0, XPATH_LINK_0)
links_1[0].uniq.each do |link_1|
links_2 = get_child_links(agent, link_1, XPATH_LINK_1)
links_2[0].each do |link_2|
links_3 = get_child_links(agent, link_2, XPATH_LINK_2)
page = links_3[1]
if element_next = page&.at(XPATH_LINK_2_NEXT)
link_next = element_next.get_attribute("href")
links_3_add = get_child_links(agent, LINK_2_DIR + link_next, XPATH_LINK_2)
links_3[0] += links_3_add[0]
page = links_3_add[1]
while element_next = page&.at(XPATH_LINK_2_NEXT_2)
link_next = element_next.get_attribute("href")
links_3_add = get_child_links(agent, LINK_2_DIR + link_next, XPATH_LINK_2)
links_3[0] += links_3_add[0]
page = links_3_add[1]
end
end
links_3[0].each do |link_3|
# データベースに保存する情報(コード、アーティスト名、曲名)を取得
links_4 = []
page = nil
begin
page = agent.get(HTTPS + link_3)
rescue
puts ERRMSG_GET_LINK
puts HTTPS ################## link_3
puts ""
end
if page
elements = page / xpath
elements&.each { |e| links << e.get_attribute("href") }
# links = elements&.map { |e| e.get_attribute("href") } # linksにnilが代入されてしまう恐れがあるため不可
# links = elements&.map(&:get_attribute("href")) # ("href")の'()'で不可
end
end
end
# chord.song = page.search("/html/body/div[3]/div[1]/div[1]/h1").inner_text
# credits = page.search("/html/body/div[3]/div[1]/div[1]/h2").inner_text
# chord.artist = credits.split("/")[0].slice(2..)
# # elements = page.search("/html/body/div[3]/div[1]/p[1]/tt/a")
# # chords = ""
# # elements.each do |element|
# # chords += element.inner_text
# # end
# # chord.chord1st = chords
# chord.chord1st = page.search("/html/body/div[3]/div[1]/p[1]/tt/a").inner_text
# chord.save
| true |
e7f71dd2e68d98d64996bd07c97fba562a607117 | Ruby | toddt67878/Course_Ruby | /ArrayII/Remove_Array_Items_that_Exist_in_Another_Array.rb | UTF-8 | 223 | 3.640625 | 4 | [] | no_license | a = [1,1,2,2,3,4,5]
b = [1, 2, 3]
def custom_subtraction(arr1, arr2)
final = []
arr1.each { |value| final << value unless arr2.include?(value) }
final
end
p custom_subtraction(a, b)
p ["a", "a", "b"] - ["a", "c"]
| true |
1566dd7bb3ebd2ebb9228c89a687ce84ec1e1275 | Ruby | nick-over/swap | /Translator/models/lang_value.rb | UTF-8 | 406 | 3.28125 | 3 | [] | no_license | # frozen_string_literal: true
# Languages module
module LangValue
ENG = 'английский'
RUS = 'русский'
def self.all_langs
[ENG, RUS]
end
def self.get_lang_by_match(match)
if !match.match(/[а-яА-Я ёЁ]/).nil?
RUS
else
ENG
end
end
def self.get_another_lang(lang)
all_langs.reject { |cur| cur == lang }[0]
end
end
| true |
eacb752235488b12e21845764fb3452d629e028c | Ruby | Atnevon/ruby_programs | /2015-08-10/finals/dice_game_example.rb | UTF-8 | 522 | 4.21875 | 4 | [] | no_license | def roll
dice_array = [1, 2, 3, 4, 5, 6]
first_roll = dice_array.sample
second_roll = dice_array.sample
total = first_roll + second_roll
return total
end
user_score = 0
comp_score = 0
while true
user_roll = roll
comp_roll = roll
if user_roll == comp_roll
puts "Tie"
elsif user_roll > comp_roll
user_score += 1
puts "User get's a point"
else
comp_score += 1
puts "Computer get's a point"
end
if user_score == 5
puts "You win!"
break
elsif comp_score == 5
puts "You Lose!"
break
end
end | true |
5bc9b2701f9e0e4ce059c886ded55bd9a60f1654 | Ruby | Crosse/aoc2020 | /day01_b.rb | UTF-8 | 367 | 3.015625 | 3 | [] | no_license | #!/usr/bin/env ruby
input = File.read("input/day01")
input.each_line do |x|
xi = x.to_i
input.each_line do |y|
yi = y.to_i
input.each_line do |z|
zi = z.to_i
if (xi + yi + zi) == 2020 then
puts "x=#{xi}, y=#{yi}, z=#{zi}, x*y*z=#{xi*yi*zi}"
exit
end
end
end
end
| true |
ceacdebcaf1401a796dfb13b9af82906ac002bff | Ruby | Kadaverin/library_home_task | /f.rb | UTF-8 | 4,654 | 3.296875 | 3 | [] | no_license | # $LOAD_PATH.unshift( File.join( File.dirname(__FILE__), 'library' ) )
$:.unshift File.dirname(__FILE__)
require 'faker'
require 'Human'
class Author < Human
attr_accessor :biography
def initialize(name, biography)
@biography = biography
super(name)
end
end
class Reader < Human
attr_reader :email, :city, :street, :house
def initialize(name, email, city, street, house)
@email, @city, @street, @house = email, city, street, house
super(name)
end
def address
"#{city}, #{street}, #{email}"
end
end
class Book
attr_reader :title, :author
alias :name :title
def initialize(title, author)
@title, @author = title, author
end
end
class Order
attr_reader :book, :reader, :date
def initialize(book , reader , date)
@book, @reader, @date = book, reader, date
end
end
class Catalog
def initialize
@currentItemIndex = 0;
@items = {};
end
def add_item (item)
class << item
def id=(val)
@id = val
end
def id
@id
end
end
item.id = @currentItemIndex
item.instance_eval('undef :id=')
# class << item
# undef id=
# end
@currentItemIndex += 1
@items[item.id] = item
item
end
def get_items_by_name (name)
result_arr = []
@items.each_value {|item| result_arr << item if item.name == name}
return result_arr
end
def get_item_by_id (item_id)
@items[item.id]
end
def delete_item (item)
@items.delete(item.id)
end
def to_s
"#{@items}"
end
end
class BooksCatalog < Catalog
def get_books_by_author
end
def get_statistics
end
def to_s
books_str = ""
@items.each_value { |book| books_str << " \"#{book.title}\" , #{book.author.name} \n" }
books_str
end
end
class AuthorsCatalog < Catalog
def get_author_bio (author_name)
self.get_item_by_name(author_name).biography
end
end
class ReadersCatalog < Catalog
def get_address_by_name (reader_name)
# self.get_item_by_name(reader_name).address
end
def get_email_by_name (reader_name)
# self.get_item_by_name(reader_name).email
end
end
class OrdersCatalog
def initialize
@orders = {}
end
def add_item(order)
@orders[order.book.id] = order
end
def get_statistics
end
end
class Library
def initialize
@books = BooksCatalog.new
@authors = AuthorsCatalog.new
@orders = OrdersCatalog.new
@readers = ReadersCatalog.new
end
def new_book(title, author)
existing_authors = @authors.get_items_by_name(author)
case existing_authors.size
when 0
author = new_author(author)
when 1
author = existing_authors[0]
else
# узнать , какой именно автор имеется в виду и присвоить author
end
book = Book.new(title, author)
@books.add_item (book)
end
def new_order(book , reader)
order = Order.new(book , reader)
@orders.add_item(order)
end
def new_author(name, biography="Биография пока пуста")
author = Author.new(name, biography)
@authors.add_item(author)
end
def new_reader(name, email, city, street, house)
reader = Reader.new(name, email, city, street, house)
@readers.add_item(reader)
end
def show_author_of_book (title)
books = @books.get_items_by_name(title)
case books.size
when 0
puts 'Автор не найден'
when 1
puts "#{books.author.name}"
else
puts "Несколько совпадений : "
books.each { |book| print "#{book.author.name} | "}
puts "\n"
end
end
def print_to_file
end
def scan_from_file
end
def to_s
" #{ "_" * 50}\n Books : \n#{@books} "
end
end
lib = Library.new
20.times {
lib.new_book(Faker::Book.title , Faker::Book.author )
lib.new_reader(Faker::Name.name , Faker::Internet.free_email , Faker::Address.city , Faker::Address.street_name , Faker::Number.between(1, 300))
lib.new_author( Faker::Book.author , Faker::Lovecraft.paragraph)
}
# lib.show_author_of_book('Книга 1')
puts lib
| true |
2f2999a38937419a4766085142a7658e7cc8af90 | Ruby | keldonia/poker | /exercises/lib/towers_of_hanoi.rb | UTF-8 | 864 | 3.53125 | 4 | [] | no_license | class TowersOfHanoi
attr_reader :towers, :winset
def initialize(towersize)
@winset = (1..towersize).to_a.reverse
@towers = {1 => @winset, 2 => [], 3 => []}
end
def move(from_tower, to_tower)
if !towers[from_tower].empty? && !towers[to_tower].empty? &&
towers[to_tower].last < towers[from_tower].last
raise ImproperDiscPlacementError.new "move a larger disc on top of a smaller disc."
elsif towers[from_tower].empty?
raise ImproperDiscPlacementError.new "move a disc from an empty tower."
end
moved_disc = towers[from_tower].pop
towers[to_tower] << moved_disc
end
def won?
(towers[2] == winset || towers[3] == winset) && towers[1].empty?
end
def render
"Tower 1: #{towers[1]}\nTower 2: #{towers[2]}\nTower 3: #{towers[3]}"
end
end
class ImproperDiscPlacementError < StandardError
end
| true |
376039b9711e1915c828d3e0f7a6c7524d7e661b | Ruby | justinkizer/a-A-Daily-Projects | /W1D3/fibonacci.rb | UTF-8 | 519 | 4.125 | 4 | [] | no_license | def fib_r(n)
return nil if n < 1
return [1] if n == 1
return [1,1] if n == 2
array = fib_r(n - 1)
new_element = array[array.length - 2] + array[array.length - 1]
array << new_element
end
def fib_i(n)
return nil if n < 1
return [1] if n == 1
return [1,1] if n == 2
array = [1,1]
for i in 3..n do
new_element = array[array.length - 2] + array[array.length - 1]
array << new_element
end
array
end
p fib_r(0)
p fib_r(1)
p fib_r(2)
p fib_r(8)
p fib_i(0)
p fib_i(1)
p fib_i(2)
p fib_i(8)
| true |
908748b34c9c983b00d40fbfe75512d8f7e2203c | Ruby | GTi-Jr/sistema-hotel-fluxo | /app/helpers/transaction_helper.rb | UTF-8 | 453 | 2.734375 | 3 | [] | no_license | module TransactionHelper
class << self
#Verificar se o produto não tem um preço definido
#Exemplo: hospedagem
#Se não tiver um preço: pegar o preço da tabela de transações e dividir pela quantidade
#Objetivo: obter o preço unitário de produtos que não tem um valor definido
def priceNull(priceUnit,priceTotal,quantity)
if priceUnit.nil?
priceTotal / quantity
else
priceUnit
end
end
end
end
| true |
7fedbb07488f46d863b4b1c39b1472fb75eb05cb | Ruby | allforkedou/nextacademyMY | /week1/chessboard.rb | UTF-8 | 770 | 2.90625 | 3 | [] | no_license | chessboard = Array.new(8){Array.new(8)}
first_line = ['Rook', 'Knight', 'Bishop', 'Queen',
'King', 'Bishop', 'Knight', 'Rook']
second_line = ['Pawn']*8
for i in 0..7
#complete first line
chessboard[0][i] = 'B '+ first_line[i]
chessboard[7][i] = 'W '+ first_line[i]
#complete second line
chessboard[1][i] = 'B '+ second_line[i]
chessboard[6][i] = 'W '+ second_line[i]
end
p chessboard
table = [
["Number", "Name", "Position", "Points per Game"],
[12, "Joe Schmo", "Center", [14, 32, 7, 0, 23]],
[9, "Ms. Buckets", "Point Guard", [19, 0, 11, 22, 0]],
[31, "Harvey Kay", "Shooting Guard", [0, 30, 16, 0, 25]],
[18, "Sally Talls", "Power Forward", [18, 29, 26, 31, 19]],
[22, "MK DiBoux", "Small Forward", [11, 0, 23, 17, 0]]
] | true |
54f16e23061bcfc11d6f87a99d2624a3d6913472 | Ruby | gpclaridge/smart-answers | /test/unit/calculators/country_name_formatter_test.rb | UTF-8 | 2,148 | 2.609375 | 3 | [
"LicenseRef-scancode-proprietary-license",
"MIT"
] | permissive | require_relative '../../test_helper'
require 'gds_api/test_helpers/worldwide'
module SmartAnswer::Calculators
class CountryNameFormatterTest < ActiveSupport::TestCase
include GdsApi::TestHelpers::Worldwide
context '#definitive_article' do
setup do
@formatter = CountryNameFormatter.new
end
should 'return the country name prepended by "the"' do
worldwide_api_has_location('bahamas')
assert_equal 'the Bahamas', @formatter.definitive_article('bahamas')
end
should 'return the country name prepended by "The"' do
worldwide_api_has_location('bahamas')
assert_equal 'The Bahamas', @formatter.definitive_article('bahamas', true)
end
should 'return the country name when definite article is not required' do
worldwide_api_has_location('antigua-and-barbuda')
assert_equal 'Antigua And Barbuda', @formatter.definitive_article('antigua-and-barbuda')
end
end
context '#requires_definite_article?' do
setup do
@formatter = CountryNameFormatter.new
end
should 'return true if the country should be prepended by "the"' do
assert @formatter.requires_definite_article?('bahamas')
end
should 'return false if the country should not be prepended by "the"' do
refute @formatter.requires_definite_article?('antigua-and-barbuda')
end
end
context 'has_friendly_name?' do
setup do
@formatter = CountryNameFormatter.new
end
should 'return true if the country slug has a friendly name' do
assert @formatter.has_friendly_name?('democratic-republic-of-congo')
end
should 'return false if the country slug does not have a friendly name' do
refute @formatter.has_friendly_name?('antigua-and-barbuda')
end
end
context '#friendly_name' do
setup do
@formatter = CountryNameFormatter.new
end
should 'return the friendly name for the country' do
assert_equal 'Democratic Republic of Congo', @formatter.friendly_name('democratic-republic-of-congo')
end
end
end
end
| true |
ea5181c24b36c3c43e87c55e116622a18fc9ca25 | Ruby | Sufl0wer/summer-2019 | /3634/2/helpers/save_files.rb | UTF-8 | 878 | 2.578125 | 3 | [] | no_license | require_relative 'image_loader'
class SaveFiles
attr_reader :session, :session_key, :payload
def initialize(session, session_key)
@session = session
@session_key = session_key
end
def path
@path ||= "public/#{session_key}/#{Time.now.strftime '%Y-%m-%d_%H:%M:%S'}"
end
def save_files
FileUtils.makedirs(path)
save :geoposition, path
save :photo, path
end
def save(type, path)
send(type, path)
end
def geoposition(path)
FileUtils.touch "#{path}/geo.txt"
File.open(File.expand_path("#{path}/geo.txt"), 'w') do |file|
file.write "#{session[session_key]['location']['latitude']}\n"
file.write session[session_key]['location']['longitude']
end
end
def photo(path)
File.open("#{path}/selfie.jpg", 'wb') do |file|
file << ImageLoader.new(session, session_key).download_file
end
end
end
| true |
8395ebb577ea040c6ae20f5e5eefb27fbec326ff | Ruby | kako-jun/Materiaroom | /ruby/rename_by_exif.rb | UTF-8 | 4,808 | 2.53125 | 3 | [
"MIT",
"CC-BY-3.0"
] | permissive | # -*- coding: utf-8 -*-
require 'kconv'
require 'fileutils'
require 'exifr'
class RenameByExif
def initialize()
end
def run( *args )
# 引数をチェック
if ARGV.size == 0 || ARGV.size > 2 then
babel()
puts 'Usage: ' + $PROGRAM_NAME + ' [src_dir_path] ([dst_dir_path])'
exit
end
# -U 付きで実行すると、引数はUTF8になっている
src_dir_path = ARGV[0]
#dst_dir_path = File.expand_path( File.dirname( __FILE__ ) )
dst_dir_path = src_dir_path
dst_dir_path = ARGV[1] if ARGV.size >= 2
src_dir_path = src_dir_path.gsub( '\\', '/' )
dst_dir_path = dst_dir_path.gsub( '\\', '/' )
file_count = 0
done_count = 0
#files = Dir::entries( src_dir_path )
# 再帰的にする
# globはSJISしか受け付けない
file_paths = Dir.glob( src_dir_path.kconv( Kconv::SJIS, Kconv::UTF8 ) + '/' + '**/*' )
file_paths.sort!
# 総数を計算する
total = 0
file_paths.each do |file_path|
# 「~」などが含まれていると、例外が発生する
fileType= ''
begin
fileType = File.ftype( file_path )
rescue
# Do nothing.
end
if fileType == 'file' then
total += 1
end
end
# メインループ
file_paths.each do |file_path|
# basenameはSJISしか受け付けない
file = File.basename( file_path.kconv( Kconv::SJIS, Kconv::UTF8 ) )
file = file.kconv( Kconv::UTF8, Kconv::SJIS )
# 「~」などが含まれていると、例外が発生する
fileType= ''
begin
fileType = File.ftype( file_path )
rescue
puts '[' + file_count.to_s + ' / ' + total.to_s + ']'
puts '- Skip unsupported path: ' + file
puts ''
next
end
if fileType == 'file' then
file_count += 1
# 小文字にする
downFile = file.downcase
# 「desktop.ini」、「.picasa.ini」、「thumbs.db」などは対象外
if downFile =~ /\.ini$/ || downFile =~ /\.db$/ || downFile =~ /^\./ then
puts '[' + file_count.to_s + ' / ' + total.to_s + ']'
puts '- Skip unsupported file: ' + file
puts ''
next
end
# 拡張子を取得する
ext = File.extname( file ).downcase
new_dir_path = ''
# Exif情報を元にリネームする
begin
exif = EXIFR::JPEG.new( file_path )
file = exif.date_time.strftime( '%Y-%m-%d_%H-%M-%S' ) + ext
new_dir_path = dst_dir_path
rescue
if ext == '.avi' || ext == '.mov' then
begin
file = File.mtime( file_path ).strftime( '%Y-%m-%d_%H-%M-%S' ) + ext
new_dir_path = dst_dir_path
rescue
new_dir_path = dst_dir_path + '/' + 'etc'
end
else
new_dir_path = dst_dir_path + '/' + 'etc'
end
end
# 分類先のディレクトリがなかったら作る
# mkdirはSJISしか受け付けない
FileUtils.mkdir_p( new_dir_path.kconv( Kconv::SJIS, Kconv::UTF8 ) ) unless FileTest.exist?( new_dir_path )
new_file_path = new_dir_path + '/' + file
# ファイル更新日時を上書きしない
if File.exist?( new_file_path ) then
puts '[' + file_count.to_s + ' / ' + total.to_s + ']'
puts '- Skip file already exists: ' + new_file_path
puts ''
else
begin
# 入力パス、出力パスに日本語を含む場合は、未対応
# copyの第2引数は、UTF8しか受け付けない
FileUtils.copy( file_path, new_file_path, { :preserve => true, :verbose => true } )
rescue
# Do nothing.
end
# コピーできたか
if FileTest.exist?( new_file_path ) then
puts ''
puts '[' + file_count.to_s + ' / ' + total.to_s + ']'
puts '- Rename to: ' + new_file_path
puts ''
else
puts ''
puts '[' + file_count.to_s + ' / ' + total.to_s + ']'
puts '- Skip unsupported file: ' + file
puts ''
end
done_count += 1
end
end
end
puts '-' * 20
puts 'Done: ' + done_count.to_s + ' file(s).'
puts 'Skip: ' + ( file_count - done_count ).to_s + ' file(s).'
# コマンドプロンプトを残すため
puts ''
puts 'Press any key ...'
STDIN.gets
end
def babel()
system( 'cls' )
system( 'color C' )
print 'BABEL ' * 1000
100.times do
print 'BABEL '
sleep( 0.01 )
end
system( 'cls' )
system( 'color F' )
end
end
inst = RenameByExif.new
inst.run
| true |
0cddd4b284f0be7e45e711e07602807342836fd2 | Ruby | BriOD/-sinatra-assessment-cash-game-tracker | /app/models/user.rb | UTF-8 | 310 | 2.703125 | 3 | [
"MIT"
] | permissive | class User < ActiveRecord::Base
validates_uniqueness_of :username
has_many :sessions
has_secure_password
def total_profit
#this method will display a users total profit.
won = []
self.sessions.each do |session|
won << session.amount_won.to_i
end
won.inject(0, :+)
end
end
| true |
09f21d4eb469303750f43514a80fd8530db5006c | Ruby | kgdskc/sample_app | /ruby/lesson6.rb | UTF-8 | 499 | 3.265625 | 3 | [] | no_license | total_price = 100
if total_price > 100
puts "みかんを購入。所持金に余裕あり"
end
if total_price == 100
puts "みかんを購入。所持金は0円"
end
if total_price < 100
puts "みかんを購入することができません。"
end
# if total_price > 100
# puts "みかんを購入。所持金に余りあり。"
# elsif total_price == 100
# puts "みかんを購入。所持金は0円。"
# else
# puts "みかんを購入することができません。"
# end | true |
8e40796b1c0ba4a0381ab1f736298376b88a2875 | Ruby | Askaks01/furima-31061 | /spec/models/user_spec.rb | UTF-8 | 4,134 | 2.609375 | 3 | [] | no_license | require 'rails_helper'
describe User do
before do
@user = FactoryBot.build(:user)
end
describe 'ユーザー新規登録' do
context 'ユーザー新規登録がうまくいくとき' do
it 'nickname,email,password,password_confirmation,last_name,first_name,last_kana,first_kana,birthdayが存在すれば登録できる' do
expect(@user).to be_valid
end
it 'nicknameが40文字以下で登録できる' do
@user.nickname = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
expect(@user).to be_valid
end
it 'passwordが半角英数混合6文字以上であれば登録できる' do
@user.password = 'abc000'
@user.password_confirmation = 'abc000'
expect(@user).to be_valid
end
end
context 'ユーザー新規登録がうまくいかないとき' do
it 'nicknameが空だと登録できない' do
@user.nickname = ''
@user.valid?
expect(@user.errors.full_messages).to include("Nickname can't be blank")
end
it 'emailが空だと登録できない' do
@user.email = ''
@user.valid?
expect(@user.errors.full_messages).to include("Email can't be blank")
end
it 'emailが一意性でないので登録できない' do
@user.save
another_user = FactoryBot.build(:user)
another_user.email = @user.email
another_user.valid?
expect(another_user.errors.full_messages).to include('Email has already been taken')
end
it 'emailには@が含まれていないと登録できない' do
@user.email = 'abcdef'
@user.valid?
expect(@user.errors.full_messages).to include('Email is invalid')
end
it 'passwordが空だと登録できない' do
@user.password = ''
@user.valid?
expect(@user.errors.full_messages).to include("Password can't be blank")
end
it 'psswordが6文字以上でないので登録できない' do
@user.password = 'abc00'
@user.password_confirmation = 'abc00'
@user.valid?
expect(@user.errors.full_messages).to include('Password is too short (minimum is 6 characters)')
end
it 'passwordが半角英数混合でないので登録できない' do
@user.password = '000000'
@user.password_confirmation = '000000'
@user.valid?
expect(@user.errors.full_messages).to include('Password is invalid')
end
it 'password(確認用)が空だと登録できない' do
@user.password_confirmation = ''
@user.valid?
expect(@user.errors.full_messages).to include("Password confirmation doesn't match Password")
end
it 'passwordが確認用と一致していないので登録できない' do
@user.password = 'abc000'
@user.password_confirmation = 'abcd000'
@user.valid?
expect(@user.errors.full_messages).to include("Password confirmation doesn't match Password")
end
it '本名が空だと登録できない' do
@user.last_name = ''
@user.valid?
expect(@user.errors.full_messages).to include("Last name can't be blank")
end
it '本名が全角(漢字・ひらがな・カタカナ)でないので登録できない' do
@user.last_name = 'aaa'
@user.valid?
expect(@user.errors.full_messages).to include('Last name is invalid')
end
it 'フリガナが空だと登録できない' do
@user.last_kana = ''
@user.valid?
expect(@user.errors.full_messages).to include("Last kana can't be blank")
end
it 'フリガナが全角(カタカナ)でないので登録できない' do
@user.last_kana = 'aaa'
@user.valid?
expect(@user.errors.full_messages).to include('Last kana is invalid')
end
it 'birthdayが空だと登録できない' do
@user.birthday = ''
@user.valid?
expect(@user.errors.full_messages).to include("Birthday can't be blank")
end
end
end
end
| true |
a2ab305baff4caff1195359d01824e5c4b3aad15 | Ruby | shamimevatix/activeadmin-3rd-level-menu | /active_admin_nested_menu.rb | UTF-8 | 5,236 | 2.609375 | 3 | [] | no_license | module ActiveAdmin
# Each Namespace builds up it's own menu as the global navigation
#
# To build a new menu:
#
# menu = Menu.new do |m|
# m.add label: 'Dashboard', url: '/'
# m.add label: 'Users', url: '/users'
# end
#
# If you're interested in configuring a menu item, take a look at the
# options available in `ActiveAdmin::MenuItem`
#
class Menu
module MenuNode
alias_method :original_active_admin_menu_item_add, :_add unless method_defined?(:original_active_admin_menu_item_add)
# The method that actually adds new menu items. Called by the public method.
# If this ID is already taken, transfer the children of the existing item to the new item.
def _add(options)
item = ActiveAdmin::MenuItem.new(options)
item.send :children=, self[item.id].children if self[item.id]
self[item.id] = item
end
end
end
end
module ActiveAdmin
module Views
class TabbedNavigation < Component
alias_method :original_active_admin_build_step0, :build unless method_defined?(:original_active_admin_build_step0)
alias_method :original_active_admin_build_menu_item, :build_menu_item unless method_defined?(:original_active_admin_build_menu_item)
alias_method :original_active_admin_build_menu, :build_menu unless method_defined?(:original_active_admin_build_menu)
alias_method :original_active_admin_default_options, :default_options unless method_defined?(:original_active_admin_default_options)
def build(menu, options = {})
puts "bild #{options}"
@menu = menu
@is_utility = options[:id].eql?("utility_nav")
super(default_options.merge(options))
build_menu
end
def build_menu
@menu_tree ||= {}
@menu_tree_lookup ||= {}
if @is_utility
menu_items.each do |item|
build_menu_item(item)
end
else
rearrange_menu_items
@menu_tree_lookup.each do |menu_item_id, menu_item|
build_menu_tree_item(menu_item)
end
end
end
def rearrange_menu_items
menu_items.each do |item|
rearrange_menu_item(item)
end
@menu_tree_lookup = @menu_tree.dup
@menu_tree.each do |key, hash_item|
found = false
@menu_tree_lookup.each do |key2, hash_item2|
if hash_item2[:children].count > 0
# puts "Oh crap\n\n"
hash_item2[:children].each do |c_item|
if c_item[:item].to_s.eql?(key.to_s)
found = true
c_item[:children] += hash_item[:children].dup
break
end
end
end
if found
break
end
end
if found
@menu_tree_lookup.delete(key)
end
end
end
def rearrange_menu_item(item)
if children = item.items(self).presence
@menu_tree[item.id] = Hash.new
@menu_tree[item.id][:item] = item.id
@menu_tree[item.id][:url] = item.url(self)
@menu_tree[item.id][:label] = item.label(self)
@menu_tree[item.id][:is_current_item] = item.current? assigns[:current_tab]
@menu_tree[item.id][:html_options] = item.html_options
@menu_tree[item.id][:children] = []
children.each{ |child|
@menu_tree[item.id][:children].push({:item => child.id, :url => child.url(self), :label => child.label(self), :is_current_item => child.current?(assigns[:current_tab]), :html_options => child.html_options, children: []})
}
else
@menu_tree[item.id] = {:item => item.id, :url => item.url(self), :label => item.label(self), :is_current_item => item.current?(assigns[:current_tab]), :html_options => item.html_options, children: []}
end
end
def build_menu_item(item)
li id: item.id do |li|
li.add_class "current test" if item.current? assigns[:current_tab]
if url = item.url(self)
text_node link_to item.label(self), url, item.html_options
else
span item.label(self), item.html_options
end
if children = item.items(self).presence
li.add_class "has_nested"
ul do
children.each{ |child| build_menu_item child }
end
end
end
end
def build_menu_tree_item(menu_item)
li id: menu_item[:item] do |level0_li|
level0_li.add_class "current" if menu_item[:is_current_item]
if url = menu_item[:url]
text_node link_to menu_item[:label], menu_item[:url] , menu_item[:html_options]
else
span menu_item[:label], menu_item[:html_options]
end
if menu_item[:children].count > 0
level0_li.add_class "has_nested"
ul do
menu_item[:children].each do |child_menu_item|
build_menu_tree_item(child_menu_item)
end
end
end
end
end
def default_options
{ id: "tabs", class: "" }
end
end
end
end | true |
26b78e804b8c403c1cf56dbe5844e1f6527f9cd6 | Ruby | Ckath/yossarian-bot | /plugins/user_points/user_points.rb | UTF-8 | 2,214 | 2.890625 | 3 | [
"LicenseRef-scancode-proprietary-license",
"MIT"
] | permissive | # frozen_string_literal: true
# user_points.rb
# Author: William Woodruff
# ------------------------
# A Cinch plugin that provides points for users for yossarian-bot.
# ------------------------
# This code is licensed by William Woodruff under the MIT License.
# http://opensource.org/licenses/MIT
require "yaml"
require "fileutils"
require_relative "../yossarian_plugin"
class UserPoints < YossarianPlugin
include Cinch::Plugin
use_blacklist
def initialize(*args)
super
@points_file = File.expand_path(File.join(File.dirname(__FILE__), @bot.server_id, "user_points.yml"))
if File.file?(@points_file)
@points = YAML.load_file(@points_file)
@points.default_proc = Proc.new { |h, k| h[k] = 0 }
else
FileUtils.mkdir_p File.dirname(@points_file)
@points = Hash.new { |h, k| h[k] = 0 }
end
end
def sync_points_file
File.open(@points_file, "w+") do |file|
file.write @points.to_yaml
end
end
def usage
"!point <command> <nick> - Give or take points away from a nickname. Commands are add, rm, and show."
end
def match?(cmd)
cmd =~ /^(!)?point$/
end
match /point add (\S+)/, method: :add_point
def add_point(m, nick)
nickd = nick.downcase
if m.user.nick.downcase != nickd
@points[nickd] += 1
m.reply "#{nick} now has #{@points[nickd]} points.", true
else
@points[nickd] -= 1
m.reply "Nice try. You now have #{@points[nickd]} points.", true
end
sync_points_file
end
match /point rm (\S+)/, method: :remove_point
def remove_point(m, nick)
nickd = nick.downcase
@points[nickd] -= 1
m.reply "#{nick} now has #{@points[nickd]} points.", true
sync_points_file
end
match /point show (\S+)/, method: :show_intro
def show_intro(m, nick)
m.reply "#{nick} has #{@points[nick.downcase]} points.", true
end
match /point leaderboard/, method: :show_leaderboard
def show_leaderboard(m)
top5 = @points.max_by(5) { |_, p| p }
leaderboard = if top5.empty?
"Empty"
else
top5.map { |u, p| "#{u}: #{p}" }.join ", "
end
m.reply "Leaderboard: #{leaderboard}.", true
end
end
| true |
1d28c884c487392a034d8a49068879d1ddfbbb6d | Ruby | rawerner/Hip-Publisher | /test/test_importing_songs.rb | UTF-8 | 1,720 | 2.796875 | 3 | [] | no_license | require_relative 'helper'
require_relative '../lib/importer'
class TestImportingSongs < HipPublisherTest
def import_data
Importer.import("test/sample_songs.csv")
end
def test_the_correct_number_of_songs_are_imported
import_data
assert_equal 5, Song.all.count
end
def test_songs_are_imported_fully
skip
import_data
expected = [
"As Far As You Wanta Go, 8/29/12, yes, yes ,'Rick Ferrell, Wade Kirby','Rainy Graham, Big Tractor'",
"Beautiful Girl, 2/3/12, yes, yes, 'Rick Ferrell, Natalie Murphy','Rainy Graham, Natalie Murphy Publishing'",
"By My Side, 10/25/12, yes, yes, 'Rick Ferrell, Marti Lynn Dodsen','Rainy Graham, Shapiro-Bernstein Music Publishing'",
"Camoflage Girls, 7/13/12,yes,yes,'RickFerrell, Wade Kirby','Rainy Graham, Big Tractor'",
"Country Boy, 8/30/12, yes, yes, 'Rick Ferrell, Wade Kirby, Melanie Morgan', 'Rainy Graham, Big Tractor, Busy Music'"
]
actual = Songs.all.map do |song|
"#{song.title}, #{song.creationdate}, #{song.haslyrics}, #{song.hasworktape}"
end
assert_equal expected, actual
end
def test_extra_songwriters_arent_created
import_data
assert_equal 5, Songwriter.all.count
end
def test_songwriters_are_created_as_needed
Songwriter.find_or_create("Rick Ferrell")
Songwriter.find_or_create("Natalie Murphy")
import_data
assert_equal 5, Songwriter.all.count, "The songwriters were: #{Songwriter.all.map(&:name)}"
end
def test_data_isnt_duplicated
import_data
expected = ["Marti Lynn Dodsen", "Melanie Morgan", "Natalie Murphy", "Rick Ferrell", "Wade Kirby"]
assert_equal expected, Songwriter.all.map(&:name)
# ^equivalent:
# category_names = Songwriter.all.map{ |category| category.name }
# assert_equal expected, category_names
end
end
| true |
fad4572122609aba74c4368a3a14d939bce0c9f3 | Ruby | Capstory/email_testing | /app/helpers/test_program_visits_helper.rb | UTF-8 | 513 | 2.625 | 3 | [] | no_license | module TestProgramVisitsHelper
def version_filter(visits_array, test_version_sought)
filtered = visits_array.select do |v|
v.test_version.to_i == test_version_sought
end
return filtered
end
def phaseline_filter(visits_array, phaseline_sought)
filtered = visits_array.select do |v|
case phaseline_sought
when 1
v.phaseline_one == true
when 2
v.phaseline_two == true
when 3
v.phaseline_three == true
else
raise NoPhaselineError
end
end
return filtered
end
end | true |
7248716c5bc89c64660888c82ca4c04a97b58c93 | Ruby | kikitux/vault-sampleapp-ruby | /app.rb | UTF-8 | 979 | 2.671875 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env ruby
# -*- mode: ruby -*-
# vi: set ft=ruby :
# Sample app
# Uses the vault client tools to:
# - connect to vault
# - read and print the value of an existing secret (secret/hello)
# load libraries
require "vault"
require "mysql"
# load vault-token
vaulttokenfile = File.read '/vagrant/vault-token'
vaulttoken = vaulttokenfile.tr("\n","")
# create new vault client
client = Vault::Client.new(
address: "http://vault.service.consul:8200",
token: vaulttoken
)
# read vault kv kv/mysql
mysecret = client.logical.read("kv/mysqluser")
# run query on database
begin
# create connection to mysql db using password from vault
con = Mysql.new 'mydb.mysql.service.consul', 'user', mysecret.data[:value], 'mydb'
puts con.get_server_info
rs = con.query 'SELECT count(*) FROM mytable'
puts rs.fetch_row
# in case of errors
rescue Mysql::Error => e
puts e.errno
puts e.error
# close connection
ensure
con.close if con
end
| true |
410381eb68746f4d9ca11fc0064345a3a9bfcf43 | Ruby | Hack-Slash/fortune | /app/controllers/fortunes_controller.rb | UTF-8 | 699 | 2.65625 | 3 | [] | no_license | class FortunesController < ApplicationController
@@page_count = 0
def tell_your_fortune
# make an array of fortunes
fortunes = ["You will be rich", "You will be a happy person", "Not as nice of a prediction"]
# pick a random one
fortunes.shuffle!
@prediction = fortunes[1]
# show that to the user
render 'prediction.html.erb'
end
def win_the_lotto
# generate 6 random numbers between 0 and 99
@numbers = []
6.times do
@numbers << rand(0...99)
end
render 'lotto.html.erb'
end
def beer
render 'beers.html.erb'
end
def counter
@@page_count += 1
@view_page_count = @@page_count
render 'counter.html.erb'
end
end
| true |
ba529a82f52fc6d337ba54b502f05c02ab274669 | Ruby | LeoVergara1/cursoRubyOnRails | /Bloques en ruby/block3bloque.rb | UTF-8 | 209 | 3.71875 | 4 | [] | no_license | def suma(n1,n2, &bloque)
puts "Hola desde nuestra funcion"
resultado = n1 + n2
bloque.call resultado
end
suma(6,5) do |resultado|
puts "El resultado de nuestra operación es #{resultado}"
end | true |
1fd58bcb7b218a176975df0a662ff76b1f37884e | Ruby | Merkrow/tasks | /count.rb | UTF-8 | 432 | 3.46875 | 3 | [] | no_license |
def beauty(s)
arr = []
a = s.downcase.split('').sort()
l = a.size-1
prev = 0
max = 26
sum = 0
for i in 0..l
if a[i] != prev
arr.push(1)
else
arr[arr.size-1] += 1
end
prev = a[i]
end
a = arr.sort().reverse()
l = a.length-1
for i in 0..l
sum += a[i]*max
max += -1;
end
return sum
end
log = "aBbcCc"
puts beauty(log)
| true |
0144fc924bd3afc01c1e4286e94d9cea3b0bce85 | Ruby | michelleamazinglin/aA-classworks | /W3D2/memory_puzzle_annotated/card.rb | UTF-8 | 2,371 | 4.40625 | 4 | [] | no_license | # difference between shuffle and shuffle!
# shuffle! 改变原来的array
# shuffle 不改变原来的array
###### https://ruby-doc.org/core-2.7.0/Array.html#method-i-shuffle
# a = [ 1, 2, 3 ] #=> [1, 2, 3]
# a.shuffle #=> [2, 3, 1]
# a #=> [1, 2, 3]
# a = [ 1, 2, 3 ] #=> [1, 2, 3]
# a.shuffle! #=> [2, 3, 1]
# a #=> [2, 3, 1]
##### https://ruby-doc.org/core-2.7.0/Array.html#method-i-take
# a = [1, 2, 3, 4, 5, 0] #=> [1, 2, 3, 4, 5, 0]
# a.take(3) #=> [1, 2, 3]
# a = [1] #=>[1]
# a * 2 #=>[1, 1]
# a = [1,2,3,4,5,6] #=> [1, 2, 3, 4, 5, 6]
# a.shuffle.take(2) * 2 #=> [1, 6, 1, 6]
class Card
VALUES = ("A".."Z").to_a
def self.shuffled_pairs(num_pairs)
values = VALUES
## num_pairs 就是你要选多少个 pair
## for example, 如果你要选 30 pairs 但是字母只有26个
## 30 = num_pairs > values.length = 26, 30 > 26
## 他就把 values 这个array 强行从 ["A",..,"Z"]
## 变成了 ["A",..,"Z","A","B",..."Z"], 此时, values.length = 52 = 26 * 2
## 来避免values 不够用
while num_pairs > values.length
values = values + values
end
values = values.shuffle.take(num_pairs) * 2
## 他又shuffle了一次, shuffle! 会影响到 原本 array 从而打破规律
values.shuffle! ## 可以吧 [1,6,3,2,1,6,3,2] => [3,3,6,1,6,2,1,2]
values.map { |val| self.new(val) } ##array 有多少个item 就创建了多少个card
end
attr_reader :value
# value is face value
# revealed = face-up or face-down, true = face-up , false = face-down
def initialize(value, revealed = false)
@value = value
@revealed = revealed
end
def hide # make it face-down
@revealed = false
end
def to_s # to string
revealed? ? value.to_s : " "
end
def reveal # make it face-up
@revealed = true
end
def revealed? # face-up?
@revealed
end
def ==(object) ##
object.is_a?(self.class) && object.value == value
end
## is_a? 检查 object 属于某个class
## for exmaple
## 100.is_a?(Numeric) ## 100 是 属于 数字类 么
## miumiu.is_a?(Cat) ## miumiu是 属于 猫类 么?
## https://ruby-doc.org/core-2.7.1/Object.html#method-i-is_a-3F
end
| true |
eeec6fd8e093178c8d017e8b8dd84f359751ea59 | Ruby | oreeve/chillow | /lib/modules.rb | UTF-8 | 126 | 2.59375 | 3 | [] | no_license | module Modules
def remove_one
@space += 1
@objects.pop
end
def full?
@space == 0 ? true : false
end
end
| true |
904dfbec29c8829afb5dcd8f97736a5ff1649d68 | Ruby | SurendraSapkale/Terminal_APP | /src/classes/testfile.rb | UTF-8 | 685 | 2.828125 | 3 | [] | no_license | File.open("dairy.txt", "r")
input_lines = File.readlines("dairy.txt")
output_lines = Array.new(0)
input_lines.map do |line|
line_contents = line.split
if line_contents[0] == "Milk"
add_quantity = line_contents[1].to_i + 2
line_contents[1] = add_quantity
output_lines << line_contents.join(' ')
else
output_lines << line_contents.join(' ')
end
end
File.new("dairy_new.txt", 'w+')
File.open("dairy_new.txt", "w+") do |f|
f.puts(output_lines)
end
require 'fileutils'
FileUtils.mv('dairy_new.txt', 'dairy.txt')
#p output_lines
#File.new("dairy_new.txt", 'w+')
#File.open("dairy_new.txt", 'w+') do |i|
# output_lines.each { |element| i.puts(element)}
#end
| true |
dc20027524035b8926e6be464d2854a59af875bd | Ruby | julioprotzek/iddd_ruby | /test/domain/identity/full_name_test.rb | UTF-8 | 3,392 | 2.828125 | 3 | [] | no_license | require './test/test_helper'
class FullNameTest < IdentityAccessTest
FIRST_NAME = 'Zoe'
LAST_NAME = 'Doe'
MARRIED_LAST_NAME = 'Jones-Doe'
WRONG_FIRST_NAME = 'Zeo'
test '#with_changed_first_name' do
name = FullName.new(
first_name: WRONG_FIRST_NAME,
last_name: LAST_NAME
)
name = name.with_changed_first_name(FIRST_NAME)
assert_equal FIRST_NAME + ' ' + LAST_NAME, name.as_formatted_name
end
test '#with_changed_last_name' do
name = FullName.new(
first_name: FIRST_NAME,
last_name: LAST_NAME
)
name = name.with_changed_last_name(MARRIED_LAST_NAME)
assert_equal FIRST_NAME + ' ' + MARRIED_LAST_NAME, name.as_formatted_name
end
test '#as_formatted_name' do
name = FullName.new(
first_name: FIRST_NAME,
last_name: LAST_NAME
)
assert_equal FIRST_NAME + ' ' + LAST_NAME, name.as_formatted_name
end
test 'first name is required' do
error = assert_raises(ArgumentError) do
FullName.new(
first_name: nil,
last_name: LAST_NAME
)
end
assert_equal error.message, 'First name is required.'
error = assert_raises(ArgumentError) do
FullName.new(
first_name: '',
last_name: LAST_NAME
)
end
assert_equal error.message, 'First name is required.'
end
test 'first name length limit' do
error = assert_raises(ArgumentError) do
FullName.new(
first_name: 'Loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooonnnng',
last_name: LAST_NAME
)
end
assert_equal error.message, 'First name must have 50 characters or less.'
end
test 'first name format validation' do
error = assert_raises(ArgumentError) do
FullName.new(
first_name: '1',
last_name: LAST_NAME
)
end
assert_equal error.message, 'First name must be at least one character in length, starting with a capital letter.'
end
test 'last name is required' do
error = assert_raises(ArgumentError) do
FullName.new(
first_name: FIRST_NAME,
last_name: nil
)
end
assert_equal error.message, 'Last name is required.'
error = assert_raises(ArgumentError) do
FullName.new(
first_name: FIRST_NAME,
last_name: ''
)
end
assert_equal error.message, 'Last name is required.'
end
test 'last name length limit' do
error = assert_raises(ArgumentError) do
FullName.new(
first_name: FIRST_NAME,
last_name: 'Loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooonnnng'
)
end
assert_equal error.message, 'Last name must have 50 characters or less.'
end
test 'last name format validation' do
error = assert_raises(ArgumentError) do
FullName.new(
first_name: FIRST_NAME,
last_name: '1'
)
end
assert_equal error.message, 'Last name must be at least one character in length.'
end
test 'equality' do
assert_equal FullName.new(
first_name: FIRST_NAME,
last_name: LAST_NAME
), FullName.new(
first_name: FIRST_NAME,
last_name: LAST_NAME
)
assert_not_equal FullName.new(
first_name: FIRST_NAME,
last_name: MARRIED_LAST_NAME
), FullName.new(
first_name: FIRST_NAME,
last_name: LAST_NAME
)
end
end | true |
9969d8bf3649fe441275579865a72d3ab6ff9cf9 | Ruby | scheibo/dat.rb | /bin/test | UTF-8 | 1,027 | 2.671875 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env ruby
require '../lib/dat'
include Dat
require 'pp'
d = Dict.new
l = Logic.new(d)
g = LogGame.new(:players => ['p1', 'p2'])
def to_dict_entry(word, from)
str = "#{word.clone} {#{from}}"
str << (word.type ? " (" << word.type << ") " : " ")
str << word.definition.strip << " " unless word.definition.strip.empty?
str << "[#{word.relatives.to_a.join(" ")}]"
end
leaves = Leaves.new(g)
top = leaves.get(1)
File.open('leaves', 'w') do |f|
top.each do |leaf, neighbor|
f.puts(to_dict_entry(d[leaf], neighbor[0].get))
end
end
1.upto(4) do |i|
p leaves.get(i).size
end
__END__
d = Dict.new
loop do
begin
b = SimpleBot.new
g = Game.new(Logger.new()[0], :players => ['p1', b], :dict => d)
b.init(g)
m = b.move
while m && m.size < 15 do # rough measure to check we're always iterating on words
m = g.play('p1', g.logic.perturb(m.strip, g.used)[0].to_s)
end
rescue InvalidMove => e
puts "#{e.message} =, player (#{g.whos_turn}), m: (#{m}), game: (#{g}), last (#{g.last})"
end
end
| true |
3304bb59352e19262b11dc867f2b5b631fa30736 | Ruby | mwagner19446/wdi_work | /w03/d01/Zack_Stayman/grammys/lib/grammy.rb | UTF-8 | 963 | 3.703125 | 4 | [] | no_license | require "pry"
class Grammy
@@Grammys = []
def initialize(year, category, winner)
@year = year
@category = category
@winner = winner
@@Grammys << self
end
def year
return @year
end
def category
return @category
end
def winner
return @winner
end
def to_s
return "The #{self.year} award for #{self.category} was won by #{self.winner}"
end
def self.all
return @@Grammys
end
def self.clear
return @@Grammys = []
end
def self.save(file)
f = File.new(file, "w+")
@@Grammys.each do |grammy|
f.puts "#{grammy.year}|#{grammy.category}|#{grammy.winner}"
end
f.close
self.clear
end
def self.load(file)
f = File.open(file)
f.each do |award|
award_array = award.split("|")
Grammy.new(award_array[0],award_array[1],award_array[2])
end
f.close
end
def self.delete_at(position)
@@Grammys.delete_at(position)
end
end
| true |
f380585e2257819dcad2371f7fea8339019b6bcb | Ruby | rgilbert82/Data-Structures | /binary_tree_test.rb | UTF-8 | 1,961 | 2.90625 | 3 | [] | no_license | require 'minitest/autorun'
require 'minitest/reporters'
Minitest::Reporters.use!
require_relative 'binary_tree'
class BinaryTreeNodeTest < Minitest::Test
def setup
@left = BinaryTreeNode.new
@right = BinaryTreeNode.new
@tree = BinaryTreeNode.new(@left, @right)
end
def test_children
assert @tree.children.include?(@left)
assert @tree.children.include?(@right)
end
def test_get_by_index
assert_equal @tree[0], @left
assert_equal @tree[1], @right
end
def test_delete_left_child
@tree.delete_left_child
assert_equal @tree.children, [nil, @right]
end
def test_delete_right_child
@tree.delete_right_child
assert_equal @tree.children, [@left, nil]
end
def test_clear
@tree.clear
assert_nil @tree.left_child
assert_nil @tree.right_child
assert_equal @tree.children, [nil, nil]
end
def test_child_count
assert_equal @tree.child_count, 2
end
def test_is_leaf?
assert_equal @tree.is_leaf?, false
assert_equal @left.is_leaf?, true
assert_equal @right.is_leaf?, true
end
def test_is_root?
assert_equal @tree.is_root?, true
assert_equal @left.is_root?, false
assert_equal @right.is_root?, false
end
def test_descendents
@another_node = BinaryTreeNode.new
@left.add_left_child(@another_node)
assert_equal @tree.descendents.size, 3
assert @tree.descendents.include?(@left)
assert @tree.descendents.include?(@right)
assert @tree.descendents.include?(@another_node)
end
def test_sibling
@another_node = BinaryTreeNode.new
@left.add_left_child(@another_node)
assert_equal @tree.sibling, nil
assert_equal @left.sibling, @right
assert_equal @right.sibling, @left
assert_equal @another_node.sibling, nil
end
def test_add_child
@another_node = BinaryTreeNode.new
@tree.delete_left_child
@tree << @another_node
assert_equal @tree.children, [@another_node, @right]
end
end
| true |
0810a90f5269d55b26dcfca0a4f792e544119049 | Ruby | dallinder/ls_small_pbs_round2 | /med_1/5.rb | UTF-8 | 268 | 3.671875 | 4 | [] | no_license | def diamond(number)
1.upto(number) do |num|
if num.odd?
puts ('*' * num).center(number)
end
end
(number - 2).downto(0) do |num|
if num.odd?
puts ('*' * num).center(number)
end
end
end
diamond(3) | true |
08f7584032ed6cef89b58929d09020b2b63c12ce | Ruby | M1ckmason/teth | /lib/teth/minitest.rb | UTF-8 | 3,773 | 2.578125 | 3 | [
"MIT"
] | permissive | require 'minitest/autorun'
require 'ethereum'
require 'teth/configurable'
module Teth
class Minitest < ::Minitest::Test
extend Configurable
include Ethereum
option :contract_dir_name, 'contracts'
option :account_num, 10
option :print_events, false
option :print_logs, true
def setup
path = find_contract_source
raise "Cannot find corresponding contract source" unless path
setup_contract(path)
end
def teardown
@state = nil
@account = nil
@contract = nil
end
def setup_contract(path)
case path
when /\.sol\z/
type = :solidity
when /\.se\z/
type = :serpent
else
raise "Unknown contract source type: #{path}"
end
code = File.read path
log_listener = ->(log) do
if log.instance_of?(Log) # unrecognized event
if self.class.print_logs
topics = log.topics.map {|t| heuristic_prettify Utils.int_to_big_endian(t) }
data = heuristic_prettify(log.data)
puts "[Log] #{Utils.encode_hex(log.address)} >>> topics=#{topics} data=#{data.inspect}"
end
else # user defined event
if self.class.print_logs && self.class.print_events
from = log.delete '_from'
name = log.delete '_event_type'
s = log.keys.map {|k| "#{k}=#{log[k]}" }.join(' ')
puts "[Event] #{from} #{name} >>> #{s}"
end
end
end
@contract = state.abi_contract code,
language: type, sender: privkey, log_listener: log_listener
end
def heuristic_prettify(bytes)
dry_bytes = bytes.gsub(/\A(\x00)+/, '')
dry_bytes = dry_bytes.gsub(/(\x00)+\z/, '')
if (bytes.size - dry_bytes.size) > 3
# there's many ZERO bytes in the head or tail of bytes, it must be padded
if dry_bytes.size == 20 # address
Utils.encode_hex(dry_bytes)
else
dry_bytes
end
else
Utils.encode_hex(bytes)
end
end
def contract
@contract
end
def find_contract_source
name = self.class.name[0...-4]
dir = find_contracts_directory
find_source(dir, name, 'sol') || find_source(dir, name, 'se')
end
def find_contracts_directory
last = nil
cur = ENV['PWD']
while cur != last
path = File.join cur, self.class.contract_dir_name
return path if File.directory?(path)
last = cur
cur = File.dirname cur
end
nil
end
def find_source(dir, name, ext)
name = "#{name}.#{ext}"
list = Dir.glob File.join(dir, "**/*.#{ext}")
list.find {|fn| File.basename(fn) =~ /\A#{name}\z/i }
end
##
# Helpers
#
def transfer(to, value, from: privkey)
state.send_tx from, to, value
end
##
# Fixtures
#
@@privkeys = account_num.times.map do |i|
Utils.keccak256 rand(Constant::TT256).to_s
end
def privkey
privkeys[0]
end
def pubkey
pubkeys[0]
end
def address
addresses[0]
end
def privkeys
@privkeys ||= @@privkeys
end
def pubkeys
@pubkeys ||= privkeys.map {|k| PrivateKey.new(k).to_pubkey }
end
def addresses
@addresses ||= privkeys.map {|k| PrivateKey.new(k).to_address }
end
%w(alice bob carol chuck dave eve mallet oscar sybil).each_with_index do |n, i|
class_eval <<-METHOD
def #{n}
addresses[#{i}]
end
def #{n}_pubkey
pubkeys[#{i}]
end
def #{n}_privkey
privkeys[#{i}]
end
METHOD
end
def state
@state ||= Tester::State.new privkeys: privkeys
end
def head
state.head
end
end
end
| true |
fb5c6218bdac840b5d7954688f28bba6a8f66261 | Ruby | ojab/iodine | /exe/iodine | UTF-8 | 3,574 | 2.625 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env ruby
require 'rack'
require 'iodine'
module Iodine
# The Iodine::Base namespace is reserved for internal use and is NOT part of the public API.
module Base
# Command line interface. The Ruby CLI might be changed in future versions.
module CLI
def print_help
puts <<-EOS
Iodine's HTTP/Websocket server version #{Iodine::VERSION}
Use:
iodine <options> <filename>
Both <options> and <filename> are optional.
Available options:
-b Binding address. Default: nil (same as 0.0.0.0).
-p Port number. Default: 3000.
-t Number of threads. Default: CPU core count.
-w Number of worker processes. Default: CPU core count.
-www Public folder for static file serving. Default: nil (none).
-v Log responses. Default: never log responses.
-warmup Warmup invokes autoloading (lazy loading) during server startup.
-tout HTTP inactivity connection timeout. Default: 40 seconds.
-maxhead Maximum total headers length per HTTP request. Default: 32Kb.
-maxbd Maximum Mb per HTTP message (max body size). Default: 50Mb.
-maxms Maximum Bytes per Websocket message. Default: 250Kb.
-ping WebSocket / SSE ping interval in seconds. Default: 40 seconds.
-logging Server level logging (not HTTP), values between 0..5. Defaults to 4.
<filename> Defaults to: config.ru
Example:
iodine -p 80
iodine -p 8080 path/to/app/conf.ru
iodine -p 8080 -w 4 -t 16
EOS
end
def try_file filename
return nil unless File.exist? filename
return ::Rack::Builder.parse_file filename
end
def filename_argument
return ((ARGV[-2].to_s[0] != '-' || ARGV[-2].to_s == '-warmup' || ARGV[-2].to_s == '-v' || ARGV[-2].to_s == '-q' || (ARGV[-2].to_s[0] == '-' && ARGV[-2].to_i.to_s == ARGV[-2].to_s)) && ARGV[-1].to_s[0] != '-' && ARGV[-1])
end
def get_app_opts
app, opt = nil, nil
filename = filename_argument
if filename
app, opt = try_file filename;
unless opt
puts "* Couldn't find #{filename}\n testing for config.ru\n"
app, opt = try_file "config.ru"
end
else
app, opt = try_file "config.ru";
end
unless opt
puts "WARNING: Ruby application not found#{ filename ? " - missing both #{filename} and config.ru" : " - missing config.ru"}."
if Iodine::DEFAULT_HTTP_ARGS[:public]
puts " Running only static file service."
opt = ::Rack::Server::Options.new.parse!([])
else
puts "For help run:"
puts " iodine -?"
exit(0);
end
end
return app, opt
end
def perform_warmup
# load anything marked with `autoload`, since autoload isn't thread safe nor fork friendly.
Iodine.run do
Module.constants.each do |n|
begin
Object.const_get(n)
rescue Exception => _e
end
end
::Rack::Builder.new(app) do |r|
r.warmup do |a|
client = ::Rack::MockRequest.new(a)
client.get('/')
end
end
end
end
def call
if ARGV[0] =~ /(\-\?)|(help)|(\?)|(h)|(\-h)$/
return print_help
end
app, opt = get_app_opts
perform_warmup if ARGV.index('-warmup')
Iodine::Rack.run(app, opt)
end
extend self
end
end
end
Iodine::Base::CLI.call
| true |
ba1bb3bf7c6a897de1a58dd590809dae353a4054 | Ruby | reidmv/control-repo-2 | /site-modules/pe_infrastructure/lib/puppet_x/puppetlabs/meep/scope.rb | UTF-8 | 1,350 | 2.671875 | 3 | [
"Apache-2.0"
] | permissive | module PuppetX::Puppetlabs::Meep
# A hash that handles stripping the root '::' namespace from scope lookup
# requests (for facts) for hiera so that it can find both 'somekey' and
# '::somekey'.
#
# For the purposes of a hiera lookup, this class is functionally equivalent
# to a Puppet::Parser::Scope, since hiera just treats the scope as a Hash.
#
# A Puppet::Parser::Scope strips this internally during it's own lookup process:
# https://github.com/puppetlabs/puppet/blob/4.8.1/lib/puppet/parser/scope.rb#L290
class Scope < Hash
def initialize(parent_scope)
@parent_scope = parent_scope
end
def merge!(o)
o.each_pair { |k, v| self[k] = v }
self
end
def [](k)
mk = munch_key(k)
key?(mk) ? super(mk) : @parent_scope[k]
end
def exist?(k)
mk = munch_key(k)
key?(mk) || @parent_scope.exist?(k)
end
def include?(k)
mk = munch_key(k)
!self[mk].nil? || @parent_scope.include?(k)
end
def lookupvar(k, options = {})
mk = munch_key(k)
key?(mk) ? self[mk] : @parent_scope.lookupvar(k, options)
end
def munch_key(k)
k = k[2..-1] if k.start_with?('::') && !key?(k)
k
end
def to_hash
@parent_scope.to_hash.merge(super)
end
def compiler
@parent_scope.compiler
end
end
end
| true |
909e1f86b87f5f25f23f4eb1e2a28d2ccb383d51 | Ruby | harlemtraveler/Final-Project | /scripthub/lib/tasks/import.rake | UTF-8 | 863 | 3.0625 | 3 | [] | no_license | require 'csv'
namespace :import do
# My table is called "users" and class/model called "User"
# desc is just a description
desc "Import users from csv "
# :environment is important here!
task users: :environment do
# intializes an empty array for your table
users = []
# the below variable makes a file relative to the root of your app
users_file = File.join Rails.root, "users.csv"
CSV.foreach(users_file, headers: true) do |row|
users << User.new(row.to_h)
end
User.import(users)
end
# this is a csv import for my second table
desc "Imports products from csv"
task products: :environment do
products = []
product_file = File.join Rails.root, "products.csv"
CSV.foreach(product_file, headers: true) do |row|
products << Product.new(row.to_h)
end
Product.import(products)
end
end
| true |
78f15d851d00a18672b33084a2a14eb84d10b282 | Ruby | stefaniacardenas/rebuilding-rails | /runways/erb_test.rb | UTF-8 | 264 | 2.921875 | 3 | [
"MIT"
] | permissive | require "erubis"
template = <<TEMPLATE
HELLO! This is a template
It has <%= whatever %>
TEMPLATE
eruby = Erubis::Eruby.new(template)
# The .src says give me the code for this template
puts eruby.src
puts "============="
puts eruby.result(:whatever => "ponies!") | true |
a8cb9be8bb85f70381ee1669521766172d0c7082 | Ruby | jeromeall/w2d1 | /employee.rb | UTF-8 | 576 | 3.40625 | 3 | [] | no_license | class Employee
attr_accessor :name, :title
@@employee_count = 0
def initialize(name, title, boss) # name, id, title, salary, boss, dept, vacation_days
@name = name
@title = title
@@employee_count += 1
# @id = id
# @title = title
# @salary = salary
@boss = boss
# @dept = dept
# @vacation_days = vacation_days
end
def self.count # use self.count for class methods
@@employee_count
end
def self.resign
@@employee_count -= 1
end
def hate_boss
"I hate my boss: #{@boss}"
end
def introduce
puts "Hi, my name is #{@name}."
end
end
| true |
8feb429b5cc36ac65828212d7c3d63b284684cc6 | Ruby | paulipayne/reverse-each-word-v-000 | /reverse_each_word.rb | UTF-8 | 177 | 3.453125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def reverse_each_word(sentence)
word_array = sentence.split(" ")
reverse_array =[]
word_array.collect {|word| reverse_array << word.reverse}
reverse_array.join(" ")
end
| true |
0c7a87975a3b961bd16ed336a3f6b984dec54e4f | Ruby | risingh1981/AppAcademy | /Intro to Programming/pickPrimes.rb | UTF-8 | 471 | 4.53125 | 5 | [] | no_license | def pick_primes(numbers)
primes = numbers.select { |num| is_prime(num) }
return primes
end
# is_prime returns true is prime, false if not prime
def is_prime(num)
if num < 2
return false
end
(2...num).each do |ele|
if num % ele == 0
return false
end
end
return true
end
print pick_primes([2, 3, 4, 5, 6]) #=> [2, 3, 5]
puts
print pick_primes([101, 20, 103, 2017]) #=> [101, 103, 2017]
puts | true |
77c68c3ebb85be69549c2c027d2f97622cf48485 | Ruby | cavalle/eventwire | /lib/eventwire/middleware/logger.rb | UTF-8 | 829 | 2.546875 | 3 | [
"MIT"
] | permissive | module Eventwire
module Middleware
class Logger < Base
def initialize(app, config)
super(app)
@config = config
end
def subscribe(event_name, handler_id, &handler)
@app.subscribe event_name, handler_id do |data|
begin
logger.info "Starting to process `#{event_name}` with handler `#{handler_id}` and data `#{data.inspect}`"
handler.call data
ensure
logger.info "End processing `#{event_name}`"
end
end
end
def publish(event_name, event_data = nil)
@app.publish event_name, event_data
logger.info "Event published `#{event_name}` with data `#{event_data.inspect}`"
end
private
def logger
@config.logger
end
end
end
end
| true |
4b8b833ba1df85856df1d1b4fd17ed5e0fe6bc69 | Ruby | YashUppal/appAcademy | /Ruby/Reference/memory_puzzle_project/memory_puzzle_game_1.1/board.rb | UTF-8 | 3,407 | 3.78125 | 4 | [] | no_license | require_relative 'card.rb'
class Board
attr_reader :grid, :alphabets, :bomb_count
def initialize(size,bombs=false)
@grid = Array.new(size) { Array.new(size) } # grid of size x size
@alphabets = ("A".."Z").to_a
if bombs
@bomb_count = size / 2
else
@bomb_count = 0
end
end
def render
# renders the board in a slightly nice way
print " #{(0...grid.length).to_a.join(" ")}\n"
grid.each_with_index do |row,row_idx|
print "#{row_idx} "
row.each do |card|
if card.face_up
print "#{card.value} "
else
print "_ "
end
end
puts
end
nil
end
def populate
# populate the board with random cards (letters)
self.drop_bombs
while !self.grid_full?
card_letter = self.random_letter
card = Card.new(card_letter,false)
rand_index = self.random_index
grid[rand_index.first][rand_index.last] = card
card = Card.new(card_letter,false)
rand_index = self.random_index
grid[rand_index.first][rand_index.last] = card
end
end
def size
# returns the total elements of the grid
return grid.length * grid.first.length
end
def random_letter
# returns a random letter from alphabet
rand = self.alphabets.sample
self.alphabets.delete(rand)
return rand
end
def random_index
# returns a random index from the grid
while true
random_index = [(0...grid.length).to_a.sample, (0...grid[(0...grid.length).to_a.sample].length).to_a.sample]
return random_index if self.valid_index(random_index)
end
end
def valid_index(index)
# returns true if passed index in empty, false otherwise
x,y = index
return true if grid[x][y] == nil
return false
end
def within_bounds?(index)
x,y = index
if x < self.grid.length && y < self.grid.length
return true
else
return false
end
end
def grid_full?
# returns true if there are no more empty positions in the grid
self.grid.each do |row|
if row.include?(nil)
return false
end
end
return true
end
def won?
# returns true if all the cards on the grid are face-up
if self.grid.all? { |row| row.all? { |card| card.face_up } }
return true
else
return false
end
end
def reveal(guessed_pos)
# reveals a card on the grid at the guessed position
card_at_pos = grid[guessed_pos.first][guessed_pos.last]
if !card_at_pos.face_up
card_at_pos.reveal
return card_at_pos.value
end
end
def bomb_position
# renders the bomb positions in a slightly nice way
print " #{(0...grid.length).to_a.join(" ")}\n"
grid.each_with_index do |row,row_idx|
print "#{row_idx} "
row.each do |card|
if card.value == "🕱"
print "#{card.value} "
else
print "_ "
end
end
puts
end
nil
end
def drop_bombs
# populate the board with bombs
i = 0
while i < bomb_count
card_letter = "🕱"
card = Card.new(card_letter,false)
rand_index = self.random_index
grid[rand_index.first][rand_index.last] = card
card = Card.new(card_letter,false)
rand_index = self.random_index
grid[rand_index.first][rand_index.last] = card
i += 1
end
end
end | true |
3376a04410ee589609b2142fed7116b4329a4b4d | Ruby | kacy/hipchat-emoticons | /app.rb | UTF-8 | 1,627 | 2.609375 | 3 | [
"MIT"
] | permissive | # By Henrik Nyh <henrik@nyh.se> 2011-07-27 under the MIT license.
# See README.
require "set"
require "rubygems"
require "bundler"
Bundler.require :default, (ENV['RACK_ENV'] || "development").to_sym
set :haml, :format => :html5, :attr_wrapper => %{"}
set :views, lambda { root }
get '/' do
# Cache in Varnish: http://devcenter.heroku.com/articles/http-caching
headers 'Cache-Control' => 'public, max-age=3600'
@file = EmoticonFile.new
@emoticons = @file.emoticons(params[:order])
@updated_at = @file.updated_at
haml :index
end
class EmoticonFile
BY_RECENT = "recent"
def initialize
@file = "./emoticons.json"
end
def emoticons(order=nil)
es = json.map { |e| Emoticon.new(e) }
# The file can have duplicates, e.g. ":)" and ":-)". Only keep the first.
known_images = Set.new
es.reject! { |e|
if known_images.include?(e.path)
true
else
known_images << e.path
false
end
}
if order == BY_RECENT
es.reverse
else # Alphabetical.
es.sort_by { |x| x.shortcut }
end
end
def updated_at
File.mtime(@file)
end
private
def json
raw = File.read(@file)
json = JSON.parse(raw)
end
end
class Emoticon
include Comparable
attr_reader :shortcut, :path, :width, :height
BASE_URL = "https://dujrsrsgsd3nh.cloudfront.net/img/emoticons/"
def initialize(data, opts={})
@standard = opts[:standard]
@path = data["image"]
@width = data["width"].to_i
@height = data["height"].to_i
@shortcut = data["shortcut"]
end
def url
URI.join(BASE_URL, @path)
end
end
| true |
ab69a679da7877d408d3c68c2e3cca34a686200b | Ruby | papapabi/exercism.io | /ruby/clock/clock.rb | UTF-8 | 535 | 3.0625 | 3 | [] | no_license | class Clock
attr_reader :hours, :minutes
def initialize(hours, minutes)
@minutes = minutes % 60
@hours = (hours + minutes / 60) % 24
end
def self.at(hours, minutes)
new(hours, minutes)
end
def to_s
format('%02d:%02d', hours, minutes)
end
def +(mins)
self.class.new(hours, minutes + mins)
end
def -(mins)
self.class.new(@hours, @minutes - mins)
end
def ==(other_clock)
hours == other_clock.hours && minutes == other_clock.minutes
end
end
module BookKeeping
VERSION = 2
end
| true |
7a105dff404d844023db065222777d4e51f95097 | Ruby | marijastojanovic5/ruby-project-guidelines-dc-web-120919 | /db/seeds.rb | UTF-8 | 1,608 | 2.671875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | Reader.destroy_all
Book.destroy_all
Checkout.destroy_all
Genre.destroy_all
50. times do
Reader.create(name: Faker::Name.unique.name)
end
50. times do
Book.create(title: Faker::Book.title, author: Faker::Book.author, genre_id: rand(1..10))
end
Genre.create(id:1,name: "SiFi")
Genre.create(id:2,name: "Romance")
Genre.create(id:3,name: "Mystery")
Genre.create(id:4,name: "Humor")
Genre.create(id:5,name: "Health")
Genre.create(id:6,name: "Fantasy")
Genre.create(id:7,name: "Thriller")
Genre.create(id:8,name: "Art")
Genre.create(id:9,name: "Cooking")
Genre.create(id:10,name: "History")
lowest_book_id = Book.first.id
highest_book_id = Book.last.id
lowest_reader_id = Reader.first.id
highest_reader_id = Reader.last.id
30. times do
book_id = rand(lowest_book_id..highest_book_id)
reader_id = rand(lowest_reader_id..highest_reader_id)
check_out_date = Time.now - (rand(1000000..1100000))
due_date = check_out_date + 1000000
return_date = check_out_date + (rand(100000..1100000))
Checkout.create(book_id: book_id, reader_id: reader_id, rate: rand(1..5),check_out_date: check_out_date,due_date: due_date,return_date: return_date)
end
10. times do
book_id = rand(lowest_book_id..highest_book_id)
reader_id = rand(lowest_reader_id..highest_reader_id)
check_out_date = Time.now - (rand(1000000..1100000))
due_date = check_out_date + 1000000
Checkout.create(book_id: book_id, reader_id: reader_id, rate: rand(1..5),check_out_date: check_out_date,due_date: due_date)
end
| true |
55a4bed5acc1ac029eb9a6daffefaf1243589513 | Ruby | aliyamerali/dealership_2103 | /lib/dealership.rb | UTF-8 | 1,004 | 3.484375 | 3 | [] | no_license | class Dealership
attr_reader :inventory, :total_value, :details
def initialize(name, address)
@name = name
@address = address
@inventory = []
@total_value = 0
end
def inventory_count
@inventory.length
end
def add_car(car)
@total_value += car.total_cost
@inventory << car
end
def has_inventory?
self.inventory_count > 1
end
def cars_by_make(requested_make)
inventory.find_all do |car|
car.make == requested_make
end
end
def details
{"address" => @address, "total_value" => @total_value}
end
def average_price_of_car
@total_value / self.inventory_count
end
def cars_sorted_by_price
inventory.sort_by do |car|
car.total_cost
end
end
def inventory_hash
inventory_hash = {}
inventory.each do |car|
if inventory_hash.has_key?(car.make)
inventory_hash[car.make] << car
else
inventory_hash[car.make] = [car]
end
end
return inventory_hash
end
end
| true |
92dc14eb40ec6defa1c1dff66e0e036f91f08ae3 | Ruby | steveax/beaker-windows | /lib/beaker-windows/registry.rb | UTF-8 | 8,778 | 2.984375 | 3 | [
"Apache-2.0"
] | permissive | module BeakerWindows
module Registry
# Get the data from a registry value.
#
# ==== Attributes
#
# * +hive+ - A symbol representing the following hives:
# * +:hklm+ - HKEY_LOCAL_MACHINE.
# * +:hkcu+ - HKEY_CURRENT_USER.
# * +:hku+ - HKEY_USERS.
#
# ==== Returns
#
# +String+ - A string representing the PowerShell hive path.
#
# ==== Raises
#
# +ArgumentError+ - Invalid registry hive specified!
#
# ==== Example
#
# get_registry_value_on(host, :hklm, "SOFTWARE\Microsoft\Windows NT\CurrentVersion", "SystemRoot")
def _get_hive(hive)
# Translate hives.
case hive
when :hklm
return "HKLM:\\"
when :hkcu
return "HKCU:\\"
when :hku
return "HKU:\\"
else
raise(ArgumentError, 'Invalid registry hive specified!')
end
end
# Get the data from a registry value.
#
# ==== Attributes
#
# * +host+ - A Windows Beaker host.
# * +hive+ - The hive containing the registry value. Allowed values:
# * +:hklm+ - HKEY_LOCAL_MACHINE.
# * +:hkcu+ - HKEY_CURRENT_USER.
# * +:hku+ - HKEY_USERS.
# * +path+ - The key containing the desired registry value.
# * +value+ - The name of the registry value.
#
# ==== Returns
#
# +String+ - A string representing the registry value data. (Always returns a string
# even for DWORD/QWORD and Binary value types.)
#
# ==== Raises
#
# +ArgumentError+ - Invalid registry hive specified!
# +RuntimeError+ - The specified key or path does not exist.
#
# ==== Example
#
# get_registry_value_on(host, :hklm, "SOFTWARE\Microsoft\Windows NT\CurrentVersion", "SystemRoot")
def get_registry_value_on(host, hive, path, value)
# Init
ps_cmd = "(Get-Item -Path '#{_get_hive(hive)}#{path}').GetValue('#{value}')"
# Parse output
result = on(host, exec_ps_cmd(ps_cmd, :EncodedCommand => true), :accept_all_exit_codes => true)
raise(RuntimeError, 'Registry path or value does not exist!') if result.exit_code == 1
return result.stdout.rstrip
end
# Create or update the data for a registry value.
#
# ==== Attributes
#
# * +host+ - A Windows Beaker host.
# * +hive+ - The hive containing the registry value. Allowed values:
# * +:hklm+ - HKEY_LOCAL_MACHINE.
# * +:hkcu+ - HKEY_CURRENT_USER.
# * +:hku+ - HKEY_USERS.
# * +path+ - The key containing the desired registry value.
# * +value+ - The name of the registry value.
# * +data+ - The data for the specified registry value.
# * +data_type+ - The data type for the specified registry value:
# * +:string+ - REG_SZ .
# * +:multi+ - REG_MULTI_SZ.
# * +:expand+ - REG_EXPAND_SZ.
# * +:dword+ - REG_DWORD.
# * +:qword+ - REG_QWORD.
# * +:bin+ - REG_BINARY. This needs to be a string of comma-separated hex values.
# (example: "be,ef,f0,0d")
#
# ==== Raises
#
# +ArgumentError+ - Invalid registry hive specified!
# +ArgumentError+ - Invalid format for binary data!
# +ArgumentError+ - Invalid data type specified!
# +RuntimeError+ - The specified key or path does not exist.
#
# ==== Example
#
# set_registry_value_on(host, :hkcu, 'SOFTWARE\test_key', 'string_value', 'test_data')
# set_registry_value_on(host, :hkcu, 'SOFTWARE\test_key', 'dword_value', 255, :dword)
# set_registry_value_on(host, :hkcu, 'SOFTWARE\test_key', 'bin_value', 'be,ef,f0,0d', :bin)
def set_registry_value_on(host, hive, path, value, data, data_type=:string)
# Init
ps_cmd = "New-ItemProperty -Force -Path '#{_get_hive(hive)}#{path}' -Name '#{value}'"
# Data type coercion.
case data_type
when :string
ps_cmd << " -Value '#{data.to_s}' -PropertyType String"
when :multi
ps_cmd << " -Value '#{data.to_s}' -PropertyType MultiString"
when :expand
ps_cmd << " -Value '#{data.to_s}' -PropertyType ExpandString"
when :dword
ps_cmd << " -Value #{data.to_s} -PropertyType DWord"
when :qword
ps_cmd << " -Value #{data.to_s} -PropertyType QWord"
when :bin
raise(ArgumentError, 'Invalid format for binary data!') unless data =~ /^(,?[\da-f]{2})+$/
hexified = ''
data.split(',').each do |hex|
hexified << ',' unless hexified.empty?
hexified << "0x#{hex}"
end
ps_cmd << " -Value ([byte[]](#{hexified})) -PropertyType Binary"
else
raise(ArgumentError, 'Invalid data type specified!')
end
# Parse output
result = on(host, exec_ps_cmd(ps_cmd, :EncodedCommand => true), :accept_all_exit_codes => true)
raise(RuntimeError, 'Registry path or value does not exist!') if result.exit_code == 1
end
# Remove a registry value.
#
# ==== Attributes
#
# * +host+ - A Windows Beaker host.
# * +hive+ - The hive containing the registry value. Allowed values:
# * +:hklm+ - HKEY_LOCAL_MACHINE.
# * +:hkcu+ - HKEY_CURRENT_USER.
# * +:hku+ - HKEY_USERS.
# * +path+ - The key containing the desired registry value.
# * +value+ - The name of the registry value.
#
# ==== Returns
#
# +String+ - A string representing the registry value data. (Always returns a string
# even for DWORD/QWORD and Binary value types.)
#
# ==== Raises
#
# +ArgumentError+ - Invalid registry hive specified!
# +RuntimeError+ - The specified key or path does not exist.
#
# ==== Example
#
# remove_registry_value_on(host, :hkcu, 'SOFTWARE\test_key', 'string_value')
def remove_registry_value_on(host, hive, path, value)
# Init
ps_cmd = "Remove-ItemProperty -Force -Path '#{_get_hive(hive)}#{path}' -Name '#{value}'"
# Parse output
result = on(host, exec_ps_cmd(ps_cmd, :EncodedCommand => true), :accept_all_exit_codes => true)
raise(RuntimeError, 'Registry path or value does not exist!') if result.exit_code == 1
end
# Create a new registry key. If the key already exists then this method will
# silently fail. This method will create parent intermediate parent keys if they
# do not exist.
#
# ==== Attributes
#
# * +host+ - A Windows Beaker host.
# * +hive+ - The hive containing the registry value. Allowed values:
# * +:hklm+ - HKEY_LOCAL_MACHINE.
# * +:hkcu+ - HKEY_CURRENT_USER.
# * +:hku+ - HKEY_USERS.
# * +path+ - The path of the registry key to create.
#
# ==== Raises
#
# +ArgumentError+ - Invalid registry hive specified!
# +RuntimeError+ - The specified key or path does not exist.
#
# ==== Example
#
# new_registry_key_on(host, :hkcu, 'SOFTWARE\some_new_key')
def new_registry_key_on(host, hive, path)
# Init
ps_cmd = "New-Item -Force -Path '#{_get_hive(hive)}#{path}'"
# Parse output
result = on(host, exec_ps_cmd(ps_cmd, :EncodedCommand => true), :accept_all_exit_codes => true)
raise(RuntimeError, 'Registry path or value does not exist!') if result.exit_code == 1
end
# Remove a registry key. The method will not remove a registry key if the key contains
# nested subkeys and values. Use the "recurse" argument to force deletion of nested
# registry keys.
#
# ==== Attributes
#
# * +host+ - A Windows Beaker host.
# * +hive+ - The hive containing the registry value. Allowed values:
# * +:hklm+ - HKEY_LOCAL_MACHINE.
# * +:hkcu+ - HKEY_CURRENT_USER.
# * +:hku+ - HKEY_USERS.
# * +path+ - The key containing the desired registry value.
# * +recurse+ - Recursively delete nested subkeys and values. (Default: false)
#
# ==== Returns
#
# +String+ - A string representing the registry value data. (Always returns a string
# even for DWORD/QWORD and Binary value types.)
#
# ==== Raises
#
# +ArgumentError+ - Invalid registry hive specified!
# +RuntimeError+ - The specified key or path does not exist.
#
# ==== Example
#
# remove_registry_key_on(host, :hkcu, 'SOFTWARE\test_key')
def remove_registry_key_on(host, hive, path, recurse=false)
# Init
ps_cmd = "Remove-Item -Force -Path '#{_get_hive(hive)}#{path}'"
# Recursively delete key if requested
ps_cmd << " -Recurse" if recurse
# Parse output
result = on(host, exec_ps_cmd(ps_cmd, :EncodedCommand => true), :accept_all_exit_codes => true)
raise(RuntimeError, 'Registry path or value does not exist!') if result.exit_code == 1
end
end
end
| true |
b6e3cae67f977c78a4a175aed0ea3e188109b799 | Ruby | fronx/reincarnation | /lib/reincarnation.rb | UTF-8 | 672 | 2.71875 | 3 | [
"MIT"
] | permissive | require 'active_support'
class Module
def included(base)
bases << base
end
def bases
@bases ||= []
end
def poke_bases(m)
bases.each do |b|
b.module_eval do
include(m)
poke_bases(m)
end
end
end
def name_without_namespace
name.gsub(/.*::/, '')
end
def bury
parent.__send__(:remove_const, name_without_namespace)
end
def reincarnate
buried = bury
reborn = parent.const_set(name_without_namespace, Module.new)
poke_bases(reborn)
reborn.module_eval { include buried }
end
end
class Class
def reincarnate
parent.const_set(name_without_namespace, Class.new(bury))
end
end
| true |
1661be0078fd275857dc73a97345f8f714870bd5 | Ruby | loschtreality/App_Academy | /In_Class/TDD/spec/array_spec.rb | UTF-8 | 1,806 | 3.65625 | 4 | [] | no_license | require 'array'
require 'rspec'
describe Array do
subject(:array) { Array.new }
describe "#my_uniq" do
let(:duplicates) { [1,1,2,2,3] }
it "should return an array" do
expect(duplicates.my_uniq).to be_a(Array)
end
it "should return only unique values" do
expect(duplicates.my_uniq).to eq([1,2,3])
end
end
describe "#two_sum" do
let(:arr) {[-1,0,2,-2,1]}
it "should return an array" do
expect(arr.two_sum).to be_a(Array)
end
it "should return pairs of indexes in order" do
expect(arr.two_sum).to eq([[0,4],[2,3]])
end
it "should not have duplicate indexes" do
expect(arr.two_sum).not_to eql([[0,4],[2,3],[3,2],[4,0]])
end
end
describe "#my_transpose" do
let(:rows) { [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8]
]}
let(:cols) {[
[0, 3, 6],
[1, 4, 7],
[2, 5, 8]
]}
it "should return an array" do
expect(rows.my_transpose).to be_a(Array)
end
it "should return an multi-d array" do
flag = true
rows.each do |el|
flag = false unless el.is_a?(Array)
end
expect(flag).to be true
end
it "should return rows as columns" do
expect(rows.my_transpose).to eq(cols)
end
end #end of array
describe "#stock_picker" do
let(:stocks) { [50,75,92,46,80] }
it "should raise NoMethodError if argument is not array" do
expect{stock_picker(5)}.to raise_error(NoMethodError)
end
it "should return an array" do
expect(stock_picker(stocks)).to be_a(Array)
end
it "returns elements x,y in ascending order" do
expect(stock_picker(stocks)).to eq([0,2])
end
it "should raise error if argument is length" do
expect{stock_picker([5])}.to raise_error("not enough days")
end
end
end #end of Rspec
| true |
7e553d41d93a4778595c3577cc35fe77661bfb0b | Ruby | rsoemardja/Codecademy | /Ruby/Learn Ruby/Looping/Loops & Iterators/The .each Iterator.rb | UTF-8 | 263 | 4.0625 | 4 | [] | no_license | # You can use the {} syntax like this
object.each { |item|
# Do something
}
# or use the do keyword instead of {}
object.each do |item|
# Do something
end
#Example of the .each Iterator
array = [1,2,3,4,5]
array.each do |x|
x += 10
print "#{x}"
end | true |
a4621d76c0e60c88da0587ca626e0292df3916f1 | Ruby | Haira505/Pythoncode | /ruby/mainpunto.rb | UTF-8 | 184 | 3.640625 | 4 | [] | no_license | load "punto.rb"
#creamos los objetos y llamamos a sus metodos
pa = Punto.new(3,4)
pb = Punto.new(0,0)
print"pa: #{pa.getx()}, #{pa.gety()} \n"
print"pb: #{pb.getx()}, #{pb.gety()} \n" | true |
4e12ac666552632f26dd6a5d4cd2babe2a158a66 | Ruby | Jesrogers/ruby-projects | /rspec_testing_intro/spec/calculator_spec.rb | UTF-8 | 600 | 3.03125 | 3 | [] | no_license | require './lib/calculator'
describe Calculator do
describe "#add" do
it "returns the sum of two numbers" do
calculator = Calculator.new
expect(calculator.add(5, 2)).to eql(7)
end
it "returns the sum of more than two numbers" do
calculator = Calculator.new
expect(calculator.add(2, 5, 7)).to eql(14)
end
end
describe "#subtract" do
it "returns the difference of two numbers" do
calculator = Calculator.new
expect(calculator.subtract(10, 5)).to eql(5)
end
end
end | true |
6706d1353a3d81671486a0e729a251bcd6e03da1 | Ruby | ryanmax/searchworks_traject_indexer | /spec/lib/utils_spec.rb | UTF-8 | 1,314 | 2.78125 | 3 | [
"Apache-2.0"
] | permissive | require 'spec_helper'
require 'utils'
describe Utils do
describe '.balance_parentheses' do
it 'works' do
expect(described_class.balance_parentheses('abc')).to eq 'abc'
expect(described_class.balance_parentheses('a(bc')).to eq 'abc'
expect(described_class.balance_parentheses('a(b)c')).to eq 'a(b)c'
expect(described_class.balance_parentheses('abc)')).to eq 'abc'
expect(described_class.balance_parentheses('(a(bc))')).to eq '(a(bc))'
end
end
describe '.longest_common_prefix' do
it 'works' do
expect(described_class.longest_common_prefix(*['interspecies','interstellar','interstate'])).to eq 'inters'
expect(described_class.longest_common_prefix(*['throne','throne'])).to eq 'throne'
expect(described_class.longest_common_prefix(*['throne','dungeon'])).to eq ''
expect(described_class.longest_common_prefix(*['throne','','throne'])).to eq ''
expect(described_class.longest_common_prefix(*['cheese'])).to eq 'cheese'
expect(described_class.longest_common_prefix(*[''])).to eq ''
expect(described_class.longest_common_prefix(*[])).to eq ''
expect(described_class.longest_common_prefix(*['prefix','suffix'])).to eq ''
expect(described_class.longest_common_prefix(*['foo','foobar'])).to eq 'foo'
end
end
end
| true |
893640f1ae978ce777d29d6c021c2639583b8624 | Ruby | manusajith/codejam-google-2012 | /Round_1C/Box_Factory/box_factory_small.rb | UTF-8 | 1,649 | 2.96875 | 3 | [] | no_license | # Copyright 2012 Manu S Ajith <neo@codingarena.in>
# Ruby Kitchen Technosol Pvt Ltd ( http://rubykitchen.in)
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
input = File.new("input_small.txt")
output = File.new("output_small.txt", 'w')
count = input.gets.chomp.to_i
data = []
count.times do
n, m = input.gets.chomp.split.map &:to_i
u = input.gets.chomp.split.map &:to_i
v = input.gets.chomp.split.map &:to_i
data << [n, m, u, v]
end
def compute n, m, u, v
return 0 if n == 0 || m == 0
a, b = u.shift 2
c, d = v.shift 2
if b == d
if a == c
return a + compute(n-1, m-1, u, v)
elsif a > c
return c + compute(n, m-1, u.unshift(a-c, b), v)
else
return a + compute(n-1, m, u, v.unshift(c-a, d))
end
else
r = []
r << compute(n, m-1, u.dup.unshift(a, b), v.dup)
r << compute(n-1, m, u.dup, v.dup.unshift(c, d))
return r.max
end
end
data.each.with_index do |t, i|
s = "Case #%d: %d"%[i+1, compute(*t)]
output.puts s
end
| true |
00a773d7c153ecf1a94d966dac2429d0bd9a3931 | Ruby | gangelo/Splattr | /lib/people/female.rb | UTF-8 | 244 | 2.71875 | 3 | [] | no_license | # To change this template, choose Tools | Templates
# and open the template in the editor.
require 'base/base_creature'
require 'modules/gender'
class Female < BaseCreature
def initialize(name,age)
super Gender::FEMALE,name,age
end
end
| true |
a3092875f79436ec0145d12dbd80c0333d7b3a6f | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/ruby/bob/f38d82ed311d449bb2f7086138118806.rb | UTF-8 | 412 | 3.65625 | 4 | [] | no_license | class Bob
def hey(content)
message = Message.new(content)
return 'Fine. Be that way!' if message.silent?
return 'Woah, chill out!' if message.shouted?
return 'Sure.' if message.question?
'Whatever.'
end
end
class Message < String
def question?
self.end_with?("?")
end
def shouted?
!self.empty? && self.upcase == self
end
def silent?
self.strip.empty?
end
end
| true |
2d3d96efee0462e8551f68a97a319c1b3065edbb | Ruby | deltamualpha/shamwow | /shamwow.rb | UTF-8 | 4,779 | 3.171875 | 3 | [] | no_license | #!/usr/local/bin/ruby
def chunker(string, chunk_size)
return (string.length / chunk_size).times.collect { |i| string[i * chunk_size, chunk_size] }
end
# treat all numbers as if they are 32-bit integers
def ror(num, shift)
(((num >> shift) | (num << (32-shift))) & ((2 ** 32) - 1))
end
def lor(num, shift)
(((num << shift) | (num >> (32-shift))) & ((2 ** 32) - 1))
end
def sha2(message)
# Implementation taken from https://en.wikipedia.org/wiki/SHA-2#Pseudocode
message_in_bits = message.unpack("B*")[0]
# first 32 bits of the fractional parts of the square roots of the first 8 primes 2 through 19:
h0 = 0x6a09e667
h1 = 0xbb67ae85
h2 = 0x3c6ef372
h3 = 0xa54ff53a
h4 = 0x510e527f
h5 = 0x9b05688c
h6 = 0x1f83d9ab
h7 = 0x5be0cd19
# first 32 bits of the fractional parts of the cube roots of the first 64 primes 2 through 311:
k = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
]
len = message_in_bits.length
bits = message_in_bits
bits << "1"
bits << "0" * (512 - ((bits.length + 64) % 512))
bits << "%064b" % len
chunked = chunker(bits, 512)
i = 0
while i < chunked.length
m = []
message = chunker(chunked[i], 32)
message.each_with_index { |word, index| m[index] = word.to_i(2) } # here's where we pass from strings of 1s and 0s back to numbers
(16..63).each { |word|
s0 = ror(m[word-15], 7) ^ ror(m[word-15], 18) ^ (m[word-15] >> 3)
s1 = ror(m[word-2], 17) ^ ror(m[word-2], 19) ^ (m[word-2] >> 10)
m[word] = (m[word-16] + s0 + m[word-7] + s1) & 0xFFFFFFFF
}
a = h0
b = h1
c = h2
d = h3
e = h4
f = h5
g = h6
h = h7
(0..63).each { |word|
s1 = ror(e, 6) ^ ror(e, 11) ^ ror(e, 25)
ch = (e & f) ^ (~(e) & g)
temp1 = (h + s1 + ch + k[word] + m[word]) & 0xFFFFFFFF
s0 = ror(a, 2) ^ ror(a, 13) ^ ror(a, 22)
maj = (a & b) ^ (a & c) ^ (b & c)
temp2 = (s0 + maj) & 0xFFFFFFFF
h = g
g = f
f = e
e = (d + temp1) & 0xFFFFFFFF
d = c
c = b
b = a
a = (temp1 + temp2) & 0xFFFFFFFF
}
h0 = (h0 + a) & 0xFFFFFFFF
h1 = (h1 + b) & 0xFFFFFFFF
h2 = (h2 + c) & 0xFFFFFFFF
h3 = (h3 + d) & 0xFFFFFFFF
h4 = (h4 + e) & 0xFFFFFFFF
h5 = (h5 + f) & 0xFFFFFFFF
h6 = (h6 + g) & 0xFFFFFFFF
h7 = (h7 + h) & 0xFFFFFFFF
i = i + 1
end
("%08x" % h0).concat("%08x" % h1).concat("%08x" % h2).concat("%08x" % h3).concat("%08x" % h4).concat("%08x" % h5).concat("%08x" % h6).concat("%08x" % h7)
end
def sha1(message)
message_in_bits = message.unpack("B*")[0]
h0 = 0x67452301
h1 = 0xEFCDAB89
h2 = 0x98BADCFE
h3 = 0x10325476
h4 = 0xC3D2E1F0
len = message_in_bits.length
bits = message_in_bits
bits << "1"
bits << "0" * (512 - ((bits.length + 64) % 512))
bits << "%064b" % len
chunked = chunker(bits, 512)
i = 0
while i < chunked.length
m = []
message = chunker(chunked[i], 32)
message.each_with_index { |word, index| m[index] = word.to_i(2) }
(16..79).each { |word|
m[word] = lor((m[word-3] ^ m[word-8] ^ m[word-14] ^ m[word-16]), 1)
}
a = h0
b = h1
c = h2
d = h3
e = h4
(0..79).each { |word|
if (0..19).include? word
f = ((b & c) | (~b & d))
k = 0x5A827999
end
if (20..39).include? word
f = (b ^ c ^ d)
k = 0x6ED9EBA1
end
if (40..59).include? word
f = (b & c) | (b & d) | (c & d)
k = 0x8F1BBCDC
end
if (60..79).include? word
f = (b ^ c ^ d)
k = 0xCA62C1D6
end
temp = (lor(a, 5) + f + e + k + m[word]) & 0xFFFFFFFF
e = d
d = c
c = lor(b, 30)
b = a
a = temp
}
h0 = (h0 + a) & 0xFFFFFFFF
h1 = (h1 + b) & 0xFFFFFFFF
h2 = (h2 + c) & 0xFFFFFFFF
h3 = (h3 + d) & 0xFFFFFFFF
h4 = (h4 + e) & 0xFFFFFFFF
i = i + 1
end
("%08x" % h0).concat("%08x" % h1).concat("%08x" % h2).concat("%08x" % h3).concat("%08x" % h4)
end | true |
b45169be75209f12a62d4559e87baec3b3efcdc7 | Ruby | gmacdougall/advent-of-code | /2020/02/part2.rb | UTF-8 | 227 | 2.984375 | 3 | [] | no_license | #!/usr/bin/env ruby
puts(
ARGF.read.lines.count do |line|
range, char, pass = line.split(' ')
p1, p2 = range.split('-').map(&:to_i)
char.gsub!(':', '')
(pass[p1 - 1] == char) ^ (pass[p2 - 1] == char)
end
)
| true |
0cd33b1cfb54fcc972d17edac1d067d8714205b8 | Ruby | dkoslow/blog_scraper | /blog_scraper.rb | UTF-8 | 504 | 3.03125 | 3 | [] | no_license | require 'open-uri'
require 'rubygems'
require 'nokogiri'
class Scraper
def self.scrape(web_page)
page = Nokogiri::HTML(open(web_page))
count = 1
page.css('div#content_inner > *').each do |element|
if element.matches?('h2')
puts "#{count}. #{element.text} \n\n"
count += 1
elsif element.matches?('div.format_text')
images = element.css('img')
images.each do |image|
puts "- #{image['src']} \n\n"
end
end
end
end
end | true |
cb0f9f6a0cc4324bd36e4cbdf80f9951ab1ec38b | Ruby | justinetroyke/who-you-know-backend | /spec/requests/api/v1/cards/cards_request_spec.rb | UTF-8 | 3,430 | 2.6875 | 3 | [] | no_license | require 'rails_helper'
describe "Cards API" do
describe "User has at least 30 unsorted, 8 easy, 8 medium and 8 hard cards" do
before :each do
@user = create(:user)
card = create(:card)
35.times do |num|
UserCard.create!(user_id: @user.id, card_id: card.id)
end
10.times do |num|
UserCard.create!(user_id: @user.id, card_id: card.id, difficulty: 1)
end
10.times do |num|
UserCard.create!(user_id: @user.id, card_id: card.id, difficulty: 2)
end
10.times do |num|
UserCard.create!(user_id: @user.id, card_id: card.id, difficulty: 3)
end
end
context 'User requests unsorted cards' do
it "returns a list of 30 cards without a difficulty level" do
get "/api/v1/users/#{@user.id}/cards"
expect(response).to have_http_status(200)
cards = JSON.parse(response.body)
user_card_1 = UserCard.find_by(card_id: cards.first["id"])
expect(cards.count).to eq(30)
expect(user_card_1['difficulty']).to eq("unsorted")
expect(user_card_1['user_id']).to eq(@user.id)
end
end
context "User requests cards with a difficulty level" do
it "returns a list of 12 cards" do
get "/api/v1/users/#{@user.id}/cards?difficulty=easy"
expect(response).to have_http_status(200)
cards = JSON.parse(response.body)
expect(cards.count).to eq(12)
end
end
end
describe "User has less than 30 unsorted cards" do
context 'User requests unsorted cards' do
it "returns the remaining unsorted cards" do
user = create(:user)
card = create(:card)
20.times do |num|
UserCard.create!(user_id: user.id, card_id: card.id, difficulty: 0)
end
get "/api/v1/users/#{user.id}/cards"
expect(response).to have_http_status(200)
cards = JSON.parse(response.body)
user_card_1 = UserCard.find_by(card_id: cards.first["id"])
expect(cards.count).to eq(20)
expect(user_card_1['difficulty']).to eq("unsorted")
end
end
end
describe "User has 0 unsorted cards" do
context 'User requests unsorted cards' do
it "returns a 400 status and message" do
user = create(:user)
get "/api/v1/users/#{user.id}/cards"
expect(response).to have_http_status(400)
returned = JSON.parse(response.body)
expect(returned["message"]).to eq("User has sorted all their cards.")
end
end
end
describe "User has less than 8 easy cards" do
context 'User requests an easy deck' do
it "returns 400 status and message" do
user = create(:user)
card = create(:card)
20.times do |num|
UserCard.create!(user_id: user.id, card_id: card.id)
end
5.times do |num|
UserCard.create!(user_id: user.id, card_id: card.id, difficulty: 1)
end
10.times do |num|
UserCard.create!(user_id: user.id, card_id: card.id, difficulty: 2)
end
10.times do |num|
UserCard.create!(user_id: user.id, card_id: card.id, difficulty: 3)
end
get "/api/v1/users/#{user.id}/cards?difficulty=easy"
expect(response).to have_http_status(400)
returned = JSON.parse(response.body)
expect(returned["message"]).to eq("User must sort more cards.")
end
end
end
end
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.