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
a3b09fe814314ada6a00a6e2717fae8ca37673f8
Ruby
chooyan-eng/cardgame
/src/handler/join.rb
UTF-8
1,411
2.71875
3
[]
no_license
require 'etc' require 'model/player' require 'util/data_io' module Handler class Join def initialize(command_args) if !command_args.nil? && command_args.any? then @dryrun = command_args[0] != "y" @status = command_args[0] == "st" else @dryrun = true @status = false end @result = Handler::Result.new end def exec if @status then result_code = game_started? ? "203" : "202" @result.push(result_code, joined_players) return end if game_started? then @result.push("400", joined_players) return end if @dryrun then @result.push("200", joined_players) return end @result.push("201") new_player = Model::Player.new(Etc.getlogin) Util::DataIo.save_player(new_player) if game_started? then @result.push("204") else @result.push("205") end end def result @result.type = "join" @result end def save end private def joined_players player_dirs = Util::DataIo.player_dirs return [] if player_dirs.nil? return player_dirs.map { |dir| dir.basename.to_s } if player_dirs.is_a?(Array) return [player_dirs.basename.to_s] end def game_started? return 0 if joined_players.nil? joined_players.size >= 2 end end end
true
f0a314032db7918be5f3f45d864bcac32a0e90c9
Ruby
taw/paradox-tools
/lib/multi_range.rb
UTF-8
2,600
3.078125
3
[ "MIT" ]
permissive
class MultiRange def initialize(*args) points = [] args.each do |arg| parse_arg(arg) do |s,e| raise ArgumentError, "MultiRange start #{s} > #{e}" if s and e and s > e next if s == e # Just fast skip, would get filtered later anyway points << [s ? 0 : -1, s, 1] points << [e ? 0 : 1, e, -1] end end yield(points) if block_given? build!(points) end def |(other) MultiRange.new(self, other) end def +(other) MultiRange.new(self, other) end def &(other) other = other.to_multi_range MultiRange.new do |points| points << [-1, nil, -1] points << [ 1, nil, 1] to_list.each do |s,e| points << [s ? 0 : -1, s, 1] points << [e ? 0 : 1, e, -1] end other.to_list.each do |s,e| points << [s ? 0 : -1, s, 1] points << [e ? 0 : 1, e, -1] end end end def -(other) other = other.to_multi_range MultiRange.new do |points| to_list.each do |s,e| points << [s ? 0 : -1, s, 1] points << [e ? 0 : 1, e, -1] end other.to_list.each do |s,e| points << [s ? 0 : -1, s, -1] points << [e ? 0 : 1, e, 1] end end end # This only works for finite values def to_ranges @points.each_slice(2).map{|a,b| a..b} end def to_list @points.each_slice(2).to_a end def to_multi_range self end def ==(other) other = other.to_multi_range to_list == other.to_list end def empty? @points.empty? end def to_s to_list.map{|a,b| "#{a}..#{b}"}.join(" ") end def inspect "MultiRange.new(#{ to_list.map{|a,b| "#{a}..#{b}"}.join(", ") })" end private def build!(points) cuts = [] cover = 0 point_totals = Hash.new(0) points.each do |c, v, diff| point_totals[[c,v]] += diff end point_totals.sort.each do |(c,v), diff| next if diff == 0 cuts << [c,v] if diff > 0 and cover <= 0 and cover + diff > 0 cuts << [c,v] if diff < 0 and cover > 0 and cover + diff <= 0 cover += diff end @points = cuts.map{|(_,v)| v} end def parse_arg(arg) case arg when Range if arg.exclude_end? yield(arg.begin, arg.to_a.last) else yield(arg.begin, arg.end) end when MultiRange arg.to_list.each do |s,e| yield(s,e) end when Array raise ArgumentError unless arg.size == 2 yield(*arg) else raise ArgumentError end end end class Range def to_multi_range MultiRange.new(self) end end
true
cc264416f213fa607d2b03e9a3cad26be7c48b68
Ruby
anvil-src/anvil-core
/lib/anvil/task/projects.rb
UTF-8
1,422
2.625
3
[ "MIT" ]
permissive
require 'git' module Anvil class Task module Projects def project_path(project) Anvil::Config.base_projects_path + "/#{project}" end def change_project(project) Dir.chdir(project_path(project)) rescue Errno::ENOENT log_project_does_not_exists project end # Yields a block in which PWD is the folder of a project managed # by anvil. # # @param [String] project the name of a project managed by anvil # @return [Object] anything returned by the yielded block def on_project(project) Dir.chdir(project_path(project)) do yield(git) end rescue Errno::ENOENT log_project_does_not_exists project end # Runs on_project on an array of projects # # @param [Array] projects an array of projects managed by anvil # @return [Array] an array with the values returned by each # on_project run def on_each_project(projects) projects.map do |project| on_project(project) { |project_git| yield project, project_git } end end protected def log_project_does_not_exists(project) logger.info "Anvil knows nothing about #{project}." logger.info 'Please, check anvil help projects:add first to add the project to anvil.' end def git Git.open(Dir.pwd) end end end end
true
9baa9dfdf23bcaef9ddf9a38f45164f184f924b1
Ruby
lewcastles/RB101
/lesson_6/twenty_one.rb
UTF-8
7,315
3.421875
3
[]
no_license
GAME_VALUE = 21 DEALER_HITS_BELOW = 17 SCORE_TO_WIN_GAME = 3 MOVE_DELAY = 1.2 ROUND_DELAY = 3 CARD_VALUES = %w[2 3 4 5 6 7 8 9 J Q K A] CARD_SUITS = %w[D C H S] def joinor(arr, delim = ',', word = 'or') arr.map.with_index do |element, idx| case idx when 0 then element.to_s when arr.size - 1 then " #{word} #{element}" else "#{delim} #{element}" end end.join end def initialize_deck cards = [] CARD_SUITS.each do |suit| CARD_VALUES.each do |value| cards << [value, suit] end end cards end def value_of_hand(hand) values = hand.map { |card| card[0] } total = 0 values.each do |value| total += if value == 'A' 11 elsif value.to_i.zero? 10 else value.to_i end end values.select { |value| value == 'A' }.count.times do total -= 10 if total > GAME_VALUE end total end def retrieve_player_move loop do puts 'Hit or Stay? (press H to Hit, S to Stay):' move = gets.chomp.downcase return move if move =~ /^[hs]{1}$/ puts 'Invalid Input. Please select from the options provided.' end end def deal_card!(deck) deck.delete(deck.sample) end def busted?(value) value > GAME_VALUE end def display_move_selected(move, cur_player) if move == 'h' puts "#{cur_player.upcase} HITS!" else puts "#{cur_player.upcase} STAYS!" end sleep(MOVE_DELAY) end def display_current_score_and_turn(score) system 'clear' || 'cls' puts "Playing #{GAME_VALUE} - First player to #{SCORE_TO_WIN_GAME} Wins!" puts "Dealer Score: #{score[:dealer]}" puts "Player Score: #{score[:player]}" puts '-' * 20 end def display_hands(playerhand, dealerhand, cur_player, scr) list_player_cards = playerhand.map { |e| e[0] } list_dealer_cards = dealerhand.map { |e| e[0] } display_current_score_and_turn(scr) if cur_player == 'player' puts "Dealer has #{list_dealer_cards[0]} and ?" else puts "Dealer has #{joinor(list_dealer_cards, ',', 'and')}" end puts "Player has #{joinor(list_player_cards, ',', 'and')}" puts '-' * 20 end def retrieve_dealers_move(hand) value_of_hand(hand) < DEALER_HITS_BELOW ? 'h' : 's' end def prompt_user_play_again puts 'Would you like to play another game? ' puts "Enter the 'Y' key to restart the game, "\ "'N' key to close the program." loop do answer = gets.chomp return answer if valid_y_n_key(answer) puts 'Invalid Entry. Please try again.' end end def valid_y_n_key(str) str.match(/^[yn]?$/i) && !str.empty? end def play_again?(str) str.match(/^[y]?$/i) end def deal_starting_hands!(playerhand, dealerhand, card_deck) 2.times do playerhand << deal_card!(card_deck) dealerhand << deal_card!(card_deck) end end def increment_score_counters!(busted_flags, dealerval, playerval, scr) if busted_flags[:player] then scr[:dealer] += 1 elsif busted_flags[:dealer] then scr[:player] += 1 elsif dealerval > playerval then scr[:dealer] += 1 elsif playerval > dealerval then scr[:player] += 1 end end def display_round_result(busted_flags, dealerval, playerval) if busted_flags[:player] puts 'You Busted! Dealer Wins the Round!' elsif busted_flags[:dealer] puts 'Dealer Busted! You Win the Round!' elsif dealerval == playerval puts 'Round Tied!!!' elsif dealerval > playerval puts "Dealer's #{dealerval} vs Player's #{playerval} | Dealer Wins Round!" else puts "Player's' #{playerval} vs Dealer's #{dealerval} | Player Wins Round!" end sleep(ROUND_DELAY) end def display_game_results(score) system 'clear' || 'cls' puts '-' * 40 if score[:dealer] > score[:player] puts "Dealer wins the game: #{score[:dealer]} to #{score[:player]}" else puts "Player wins the game: #{score[:player]} to #{score[:dealer]}" end puts '-' * 40 end def match_ended?(scr) scr.values.any? { |e| e >= SCORE_TO_WIN_GAME } end def display_hands_with_move(player_hand, dealer_hand, cur_player, move, score) display_hands(player_hand, dealer_hand, cur_player, score) display_move_selected(move, cur_player) display_hands(player_hand, dealer_hand, cur_player, score) end def hit?(move) move == 'h' end def stayed?(move) move == 's' end def game_target_value?(value) value == GAME_VALUE end def blackjack?(hand) hand.size == 2 && value_of_hand(hand) == GAME_VALUE end loop do score = { player: 0, dealer: 0 } loop do card_deck = initialize_deck players_hand = [] dealers_hand = [] players_hand_value = 0 dealers_hand_value = 0 current_player = 'player' busted_flags = { player: false, dealer: false } # DEAL STARTING HANDS AND SHOW CARDS ------------------ deal_starting_hands!(players_hand, dealers_hand, card_deck) display_hands(players_hand, dealers_hand, current_player, score) if blackjack?(players_hand) || blackjack?(dealers_hand) current_player = 'dealer' display_hands(players_hand, dealers_hand, current_player, score) puts 'BLACKJACK!!' display_round_result(busted_flags, value_of_hand(dealers_hand), value_of_hand(players_hand)) increment_score_counters!(busted_flags, value_of_hand(dealers_hand), \ value_of_hand(players_hand), score) match_ended?(score) ? break : next end # PLAYERS TURN ---------------------------------------- loop do players_move = retrieve_player_move players_hand << deal_card!(card_deck) if hit?(players_move) display_hands_with_move(players_hand, dealers_hand, current_player, \ players_move, score) players_hand_value = value_of_hand(players_hand) break if stayed?(players_move) || busted?(players_hand_value) || \ game_target_value?(players_hand_value) end if busted?(players_hand_value) busted_flags[:player] = true display_round_result(busted_flags, dealers_hand_value, players_hand_value) increment_score_counters!(busted_flags, dealers_hand_value, \ players_hand_value, score) match_ended?(score) ? break : next end # DEALERS TURN ----------------------------------------- current_player = 'dealer' display_hands(players_hand, dealers_hand, current_player, score) dealers_hand_value = value_of_hand(dealers_hand) loop do dealers_move = retrieve_dealers_move(dealers_hand) dealers_hand << deal_card!(card_deck) if hit?(dealers_move) display_hands_with_move(players_hand, dealers_hand, current_player, \ dealers_move, score) dealers_hand_value = value_of_hand(dealers_hand) break if stayed?(dealers_move) || busted?(dealers_hand_value) end # ROUND END UPDATE SCORE -------------------------------- busted_flags[:dealer] = true if busted?(dealers_hand_value) display_round_result(busted_flags, dealers_hand_value, players_hand_value) increment_score_counters!(busted_flags, dealers_hand_value, \ players_hand_value, score) break if match_ended?(score) end # MATCH END ------------------------------------------------ display_game_results(score) response = prompt_user_play_again break unless play_again?(response) end
true
ce1671a92ea14e1b4761ccfd68f1edf66ca7342e
Ruby
beathyate/developer-exercise
/ruby/youtube/test.rb
UTF-8
580
2.53125
3
[]
no_license
require 'minitest/autorun' require_relative 'simple_youtube' class SimpleYoutubeTest < MiniTest::Test def setup @query = "google" end def test_returns_three_results_by_default results = SimpleYoutube.search @query assert_equal 3, results.size end def test_can_return_more_results max_results = 6 results = SimpleYoutube.search @query, max: max_results assert_equal max_results, results.size end def test_all_results_are_urls results = SimpleYoutube.search @query assert results.all? { |r| r =~ /^#{ URI::regexp }$/ } end end
true
a2f28abafd02ca3a4f8311b53a9624ac52d81e07
Ruby
rizowski/Ruby-TexasHoldem
/Deck.rb
UTF-8
543
3.375
3
[]
no_license
require_relative 'card' class Deck attr_accessor :deck_cards def initialize @deck_cards = Array.new fill_deck end def fill_deck 13.times do |i| @deck_cards.push(Card.new("S", i)) end 13.times do |i| @deck_cards.push(Card.new("H", i)) end 13.times do |i| @deck_cards.push(Card.new("C", i)) end 13.times do |i| @deck_cards.push(Card.new("D", i)) end end def deal_player @deck_cards.sample(2) end def deal_house @deck_cards.sample(5) end end
true
0293ce7501d567971aaa22be559a9e0322219fc0
Ruby
MisterDeejay/space-management-api
/spec/requests/stores_spec.rb
UTF-8
3,940
2.5625
3
[]
no_license
require 'rails_helper' RSpec.describe 'Stores API', type: :request do let!(:stores) { create_list(:store, 10) } let(:store_id) { stores.first.id } describe 'GET /stores' do context 'without query params' do before { get '/stores' } it 'returns stores' do expect(json).not_to be_empty expect(json.size).to eq(10) end it 'returns status code 200' do expect(response).to have_http_status(200) end end context 'with query params' do let(:query_param) { "Elm" } let!(:store_1) { FactoryBot.create(:store, title: "#{query_param}_1") } let!(:store_2) { FactoryBot.create(:store, title: "#{query_param}_2") } context 'correctly formed' do before { get "/stores?title=like:#{query_param}" } it 'returns the matching records' do expect(json.count).to eq(2) titles = json.map { |s| s['title'] } expect(titles.include?(store_1.title)).to be_truthy expect(titles.include?(store_2.title)).to be_truthy end end context 'incorrectly formed' do before { get "/stores?title=between:#{query_param}" } it 'returns status code 404' do expect(response).to have_http_status(422) end it 'returns a query finder error' do expect(response.body).to match(/Query failed: Comparison operator does not exist/) end end end end # Test suite for GET /stores/:id describe 'GET /stores/:id' do before { get "/stores/#{store_id}" } context 'when the record exists' do it 'returns the store' do expect(json).not_to be_empty expect(json['id']).to eq(store_id) end it 'returns status code 200' do expect(response).to have_http_status(200) end end context 'when the record does not exist' do let(:store_id) { 0 } it 'returns status code 404' do expect(response).to have_http_status(404) end it 'returns a not found message' do expect(response.body).to match(/Couldn't find Store/) end end end # Test suite for POST /stores describe 'POST /stores' do # valid payload let(:valid_attributes) { { title: 'Elm', city: 'Los Angeles', street: '711 Wilshire Blvd', spaces_count: 6 } } context 'when the request is valid' do before { post '/stores', params: valid_attributes } it 'creates a store' do expect(json['title']).to eq('Elm') expect(json['city']).to eq('Los Angeles') expect(json['street']).to eq('711 Wilshire Blvd') expect(json['spaces_count']).to eq(6) end it 'returns status code 201' do expect(response).to have_http_status(201) end end context 'when the request is invalid' do before { post '/stores', params: { title: 'Foobar' } } it 'returns status code 422' do expect(response).to have_http_status(422) end it 'returns a validation failure message' do expect(response.body) .to match(/Validation failed: City can't be blank/) end end end # Test suite for PUT /stores/:id describe 'PUT /stores/:id' do let(:valid_attributes) { { title: 'Shopping' } } context 'when the record exists' do before { put "/stores/#{store_id}", params: valid_attributes } it 'updates the record' do expect(response.body).to_not be_empty record = Store.find(store_id) expect(record.title).to eq('Shopping') end it 'returns status code 200' do expect(response).to have_http_status(200) end end end # Test suite for DELETE /stores/:id describe 'DELETE /stores/:id' do before { delete "/stores/#{store_id}" } it 'returns status code 204' do expect(response).to have_http_status(204) end end end
true
9ab31d9ae35cf86002cf8fff043eeb39e83d06fa
Ruby
ray0h/TOP_Ruby_Chess
/lib/pieces/king.rb
UTF-8
3,915
3.046875
3
[]
no_license
require_relative './piece' require './lib/modules/checks' # King piece class class King < Piece include Checks attr_reader :symbol def initialize(color, player_id) super(color, player_id) @symbol = @color == 'white' ? "\u2654" : "\u265A" @history = [] end def possible_moves(board) current_square = @history.last current_coords = parse_coord(current_square) poss_moves = king_moves(current_coords, board) + castle_moves(board) # king can not move to spot where he would be placed in check opp_moves = opponent_poss_moves(board) check_filter = poss_moves.filter { |move| !opp_moves.include?(move) } # king can not capture piece that would place him in check opp_pieces = get_opponent_pieces(board) check_filter.filter { |final_sq| !still_in_check?([current_square, final_sq], [self], opp_pieces, board) } end private # functions related to normal king moves def one_space_move(coord, row_coef, col_coef, board) next_square = parse_square([coord[0] + (1 * row_coef), coord[1] + (1 * col_coef)]) piece = square_occupied?(next_square, board) (piece && !my_piece?(piece)) || (!piece && on_board?(next_square)) ? [next_square] : [] end def king_moves(coords, board) surrounding = [[1, 1], [1, -1], [-1, 1], [-1, -1], [1, 0], [-1, 0], [0, 1], [0, -1]] poss_moves = [] surrounding.each { |pair| poss_moves += one_space_move(coords, pair[0], pair[1], board) } poss_moves end # functions related to prevent king moving into check space def get_opponent_pieces(board) opp_pieces = [] 0.upto(7) do |i| 0.upto(7) do |j| opp_pieces.push(board.grid[i][j]) if !board.grid[i][j].nil? && !my_piece?(board.grid[i][j]) end end opp_pieces end def opponent_poss_moves(board) poss_moves = [] opp_pieces = get_opponent_pieces(board) opp_pieces.each do |piece| coords = parse_coord(piece.history.last) moves = piece.class.name == 'King' ? king_moves(coords, board) : piece.possible_moves(board) poss_moves += moves end poss_moves.uniq end # functions related to castling def between_rook_king(king_coord, rook_coord) squares = [] row = king_coord[0] min = (rook_coord[1] == 7 ? king_coord[1] : rook_coord[1]) + 1 max = (rook_coord[1] == 7 ? rook_coord[1] : king_coord[1]) - 1 min.upto(max) { |col| squares.push(parse_square([row, col])) } squares end def get_between_squares(rook) king_coord = parse_coord(@history.last) rook_coord = parse_coord(rook.history.last) between_squares = between_rook_king(king_coord, rook_coord) between_squares end def between_squares_empty?(rook, board) btwn_squares = get_between_squares(rook) status = btwn_squares.map { |square| square_occupied?(square, board) } status.all? { |square| square == false } end def no_check_between_squares?(rook, board) opp_moves = opponent_poss_moves(board) btwn_squares = get_between_squares(rook) status = btwn_squares.map { |square| opp_moves.include?(square) } status.all? { |square| square == false } end def can_castle?(rook, board) first_move? && rook.first_move? && between_squares_empty?(rook, board) && no_check_between_squares?(rook, board) end def get_rooks(board) rooks = [] 0.upto(7) do |i| 0.upto(7) do |j| space = board.grid[i][j] rooks.push(space) if !space.nil? && my_piece?(space) && space.class.name == 'Rook' end end rooks end def castle_moves(board) rooks = get_rooks(board) castle_moves = [] rooks.each do |rook| king_coord = parse_coord(@history.last) rook_coord = parse_coord(rook.history.last) row = king_coord[0] col = rook_coord[1] == 7 ? 6 : 2 castle_moves.push(parse_square([row, col])) if can_castle?(rook, board) end castle_moves end end
true
138ccd177d96b443fd1c4757f2348b81c8e9c337
Ruby
stixbunny/desafio-methods-ruby
/1.rb
UTF-8
32
2.84375
3
[]
no_license
def par(x) return x.even? end
true
ebf33181bbd23aca58265268620f8b1d4ff1fe97
Ruby
thomis/db_meta
/spec/db_meta_spec.rb
UTF-8
2,180
2.734375
3
[ "Apache-2.0" ]
permissive
require "spec_helper" meta_args = { username: "a_username", password: "a_password", instance: "an_instance" } class Example < DbMeta::Abstract register_type(:example) end RSpec.describe DbMeta do it "has a version number" do expect(DbMeta::VERSION).not_to be nil end it "validates allowed database types" do expect(DbMeta::DATABASE_TYPES.size).to eq(1) expect(DbMeta::DATABASE_TYPES[0]).to eq(:oracle) end it "expects a username" do expect { DbMeta::DbMeta.new }.to raise_error(RuntimeError, "username is mandatory, pass a username argument during initialization") end it "expects a password" do expect { DbMeta::DbMeta.new(username: "a_username") }.to raise_error(RuntimeError, "password is mandatory, pass a password argument during initialization") end it "expects an instance" do expect { DbMeta::DbMeta.new(username: "a_username", password: "a_password") }.to raise_error(RuntimeError, "instance is mandatory, pass a instance argument during initialization") end it "expects a valid database type" do expect { DbMeta::DbMeta.new(username: "a_username", password: "a_password", instance: "an_instance", database_type: :unknown) }.to raise_error(RuntimeError, "allowed database types are [oracle], but provided was [unknown]") end it "creates an valid instance" do expect { DbMeta::DbMeta.new(meta_args) }.not_to raise_error end it "fails with unknown abstract type" do expect { DbMeta::Abstract.from_type(:unkown, meta_args) }.to raise_error(RuntimeError, "Abstract type [unkown] is unknown") end it "fails with missing instance methods" do meta = DbMeta::Abstract.from_type(:example, meta_args) expect { meta.fetch }.to raise_error(RuntimeError, "Needs to be implemented in derived class") expect { meta.extract }.to raise_error(RuntimeError, "Needs to be implemented in derived class") end it "failes to extract with unknown format" do meta = DbMeta::Abstract.from_type(:oracle, meta_args) expect { meta.extract(format: :unknown) }.to raise_error(RuntimeError, "Format [unknown] is not supported") end end
true
82f7fdbacb3d7fbd94bc90f2fe8d450936384497
Ruby
sunspot/sunspot
/sunspot_rails/lib/sunspot/rails/adapters.rb
UTF-8
2,525
2.578125
3
[ "MIT" ]
permissive
module Sunspot #:nodoc: module Rails #:nodoc: # # This module provides Sunspot Adapter implementations for ActiveRecord # models. # module Adapters class ActiveRecordInstanceAdapter < Sunspot::Adapters::InstanceAdapter # # Return the primary key for the adapted instance # # ==== Returns # # Integer:: Database ID of model # def id @instance.id end end class ActiveRecordDataAccessor < Sunspot::Adapters::DataAccessor # options for the find attr_accessor :include attr_accessor :scopes attr_reader :select def initialize(clazz) super(clazz) @inherited_attributes = [:include, :select, :scopes] end # # Set the fields to select from the database. This will be passed # to ActiveRecord. # # ==== Parameters # # value<Mixed>:: String of comma-separated columns or array of columns # def select=(value) value = value.join(', ') if value.respond_to?(:join) @select = value end # # Get one ActiveRecord instance out of the database by ID # # ==== Parameters # # id<String>:: Database ID of model to retreive # # ==== Returns # # ActiveRecord::Base:: ActiveRecord model # def load(id) @clazz.where(@clazz.primary_key => id).merge(scope_for_load).first end # # Get a collection of ActiveRecord instances out of the database by ID # # ==== Parameters # # ids<Array>:: Database IDs of models to retrieve # # ==== Returns # # Array:: Collection of ActiveRecord models # def load_all(ids) @clazz.where(@clazz.primary_key => ids).merge(scope_for_load) end private def scope_for_load scope = relation scope = scope.includes(@include) if @include.present? scope = scope.select(@select) if @select.present? Array.wrap(@scopes).each do |s| scope = scope.send(s) end scope end # COMPATIBILITY: Rails 4 has deprecated the 'scoped' method in favour of 'all' def relation ::Rails.version >= '4' ? @clazz.all : @clazz.scoped end end end end end
true
2c22a83867b88ec525b594f4b81a8f783706a5ee
Ruby
HungryShark-t/rrr
/AirportSite/lib/flight.rb
UTF-8
773
3.25
3
[]
no_license
# frozen_string_literal: true # Class class Flight attr_reader :number, :where_from, :where_to, :time_from, :time_to, :date_from, :date_to, :type, :cost def initialize(number, where_from, where_to, time_from, time_to, date_from, date_to, type, cost) @number = number @where_from = where_from @where_to = where_to @time_from = time_from @time_to = time_to @date_from = date_from @date_to = date_to @type = type @cost = cost end def to_s "Number: #{@number}" \ "\nWhere from: #{@where_from}" \ "\nWhere to: #{@where_to}" \ "\nTime from: #{@time_from}" \ "\nTime to: #{@time_to}" \ "\nDate from: #{@date_from}" \ "\nDate to: #{@date_to}" \ "\nType: #{@type}" \ "\nCost: #{@cost}\n\n" end end
true
17ff829f7e36fa40e952ad805488e5939261467d
Ruby
ugodiiorio/experiment
/code/builders/schemas/script/monitor_schema.rb
UTF-8
1,785
2.765625
3
[]
no_license
#!/usr/bin/ruby -w # simple.rb - simple MySQL script using Ruby MySQL module class BuildMonitorSchema def initialize(db_host, db_user, db_pwd, db_default_monitor) @db_host = db_host @db_user = db_user @db_pwd = db_pwd @db_default_monitor = db_default_monitor end def run() puts "\nLa attivita' di creazione tabelle dello schema monitor su host: "+ @db_host +" e' stata inizializzata..." mysql = Mysql.init() mysql = Mysql.real_connect(@db_host, @db_user, @db_pwd) mysql.query("CREATE SCHEMA IF NOT EXISTS " + @db_default_monitor + " ;") mysql.query("CREATE TABLE " + @db_default_monitor + ".scheduler ( key_insurance_profiles_id_num int(5) UNSIGNED NOT NULL, key_provider_id_str VARCHAR(20) NOT NULL, key_sector_id_str VARCHAR(20) NOT NULL, key_company_id_str VARCHAR(20) NOT NULL, key_working_set_id_str VARCHAR(20) NOT NULL, key_rate_id_str varchar(8) NOT NULL, state_str varchar(10) DEFAULT 'NOT RUN', result_str varchar(10) DEFAULT NULL, result_message_str varchar(1024) DEFAULT NULL, start_update TIMESTAMP DEFAULT 0, last_update TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (key_insurance_profiles_id_num,key_provider_id_str,key_sector_id_str,key_company_id_str,key_working_set_id_str,key_rate_id_str) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci ;" ) mysql.query(" CREATE INDEX state_index ON " + @db_default_monitor + ".scheduler(state_str) ;") mysql.close() puts "\n - " + @db_default_monitor + " schema tables creation finished" end end
true
7b24c5e4b3ef82fe2b597671c1f87196807da1b6
Ruby
njpa/launchschool-rb101
/lesson_3/3_medium_1/question_10.rb
UTF-8
431
4.34375
4
[]
no_license
# Consider these two simple methods: def foo(param = "no") "yes" end def bar(param = "no") param == "no" ? "yes" : "no" end # What would be the return value of the following method invocation? bar(foo) # ANSWER # We'll start by evaluating the `foo` invocation that is sent in as argument. # This invocation evaluates to `'yes'`. Invoking `bar` passing in `'yes'` # as argument gives a return value of `'no'`. p bar(foo)
true
67aba38289f9544eb2114c36b4b62e1adb8f0eba
Ruby
Salaizrm/square_array-onl01-seng-pt-052620
/square_array.rb
UTF-8
88
3.53125
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def square_array(array) squared = [] array.each {|x| squared << x**2} squared end
true
5c8f40dee606dfed671150abfa5e500192a818b6
Ruby
yortz/UNIX-FU
/mini-unicorn.rb
UTF-8
4,255
2.578125
3
[]
no_license
require 'socket' require 'rack' require 'rack/builder' require 'http_tools' class MiniUnicorn NUM_WORKERS = 4 CHILD_PIDS = [] SIGNAL_QUEUE = [] SELF_PIPE_R, SELF_PIPE_W = IO.pipe def initialize(port=8080) if listener_fd = ENV['LISTENER_FD'] @listener = TCPServer.for_fd(listener_fd.to_i) else @listener = TCPServer.new(port) @listener.listen(512) end end def start load_app spawn_workers trap_signals set_title loop do ready = IO.select([SELF_PIPE_R]) #go to sleep until the pipe has something red to it SELF_PIPE_R.read(1) case SIGNAL_QUEUE.shift when :INT, :QUIT, :TERM shutdown when :USR2 reexec when :CHLD # avoids zombie process pid = Process.wait if CHILD_PIDS.delete(pid) spawn_worker end end end end # When a signal comes in put it in the queue so the main queue can pull it off # Then write a byte to the pipe: this will wake up the sleeping call (line 32) # So the pipe now will be ready for data and can read the byte and consume it # off the pipe so it doesn't show up next time on the loop. # We are now good to shift off the signal queue because the only time the pipe (line 32) # should get data is when a pending signal arrives, that's to say there is # no more sleeping and running through the loop (line 30) endlessly wasting cycles # basically it # loads the app, # spawn the workers, # then go to sleep # until the pipe gets data (line 32) # when the signal arrives we put a little bit of data in the pipe to wake it up # and then in processes the signal. def trap_signals [:INT, :QUIT, :TERM, :USR2, :CHLD].each do |sig| Signal.trap(sig) { SIGNAL_QUEUE << sig sleep 5 SELF_PIPE_W.write_nonblock('.') } end end def reexec fork { $PROGRAM_NAME = "MiniUnicorn (NewMaster)" ENV['LISTENER_FD'] = @listener.fileno.to_s exec "ruby mini-unicorn.rb", { @listener.fileno => @listener } } end def shutdown CHILD_PIDS.each do |cpid| Process.waitpid(cpid, :WNOHANG) Proces.kill[:INT, cpid] end # Once it sends the signal sleep the child processes to give them time to tear down # and wait to see if the child processes are dead. # If the child process to kill it's still alive returns immediately so it's non blocking # then terminate the child process forcefully so it can exit and all child processes are tore down. #sleep 10 CHILD_PIDS.each do |cpid| begin Process.waitpid(cpid, :WNOHANG) Proces.kill[:INT, cpid] rescue Errno::ECHILD end end #exit end def set_title $PROGRAM_NAME = "MiniUnicorn Master" end # config after_fork do #ActiveRecord::Base.establish_connection #Redis::Client.reconnect end def spawn_workers NUM_WORKERS.times do |num| spawn_worker(num) end end def spwan_worker(num) CHILD_PIDS << fork { after_fork #avoids issues due to load balancing between processes e.g.: db queries $PROGRAM_NAME = "MiniUnicorn Worker #{num}" trap_child_signals worker_loop } end def trap_child_signals #Signal.trap(:INT) { #@should_exit = true #} end def load_app rackup_file = 'config.ru' @app, options = Rack::Builder.parse_file(rackup_file) end def worker_loop loop do connection, _ = @listener.accept # read = lazy read # it blocks until it gets EOF # # readpartial = greedy read raw_request = connection.readpartial(4096) parser = HTTPTools::Parser.new parser.on(:finish) do env = parser.env.merge!("rack.multiprocess" => true) status, header, body = @app.call(env) header["Connection"] = "close" connection.write HTTPTools::Builder.response(status, header) body.each {|chunk| connection.write chunk } body.close if body.respond_to?(:close) end parser << raw_request connection.close end end end # $:> ruby mini-unicorn.rb # $:> echo foo | nc localhost 8080 server = MiniUnicorn.new server.start
true
1741e78d5d5f7f5f129eb3af940c2d30d9cc6d7d
Ruby
nealchawn/ruby-lofi
/rlfi/checkbox.rb
UTF-8
1,821
3.015625
3
[ "MIT" ]
permissive
class Checkbox attr_accessor :x, :y, :size, :tag, :phases def initialize x, y, size, checked = false, tag = nil, enabled = true, phases = 1, allow_uncheck = true @x = x @y = y @size = size @checking = false @checked = checked @tag = tag @enabled = enabled @hidden = false @phases = phases @phase = checked ? 1 : 0 @allow_uncheck = allow_uncheck end def set_checked c, bubble = true @checked = !!c @phase = @checked ? 1 : 0 @callback.call @checked, @tag, @phase, @phases if @callback && bubble end def allow_uncheck= u @allow_uncheck = !!u end def allow_uncheck? @allow_uncheck end def enabled= e @enabled = !!e end def hidden= h @hidden = !!h end def hidden? @hidden end def enabled? @enabled end def on_change &block @callback = block end def contains? x, y @x <= x && @x + @size >= x && @y <= y && @y + @size >= y end def mouse_down x, y return unless enabled? @checking = true end def mouse_up x, y, b = :lmb return unless enabled? if @checking if @phase + 1 > @phases if @allow_uncheck @checked = false @phase = 0 end else @checked = true @phase += 1 end @checking = false @callback.call @checked, @tag, @phase, @phases if @callback end end def mouse_update x, y end def draw return if hidden? color = @enabled ? Gosu::Color::BLACK : Gosu::Color::GRAY Gosu::draw_rect @x, @y, @size, @size, color Gosu::draw_rect @x + 1, @y + 1, @size - 2, @size - 2, Gosu::Color::WHITE if @checked color = Gosu::Color::RED if @phases > 1 && @phase > 1 Gosu::draw_rect @x + 2, @y + 2, @size - 4, @size - 4, color end end end
true
2b5d317a6a362491a555c1a0b46b09f8c5d919b9
Ruby
IsaevPavel/AddressBook
/address_book_ui.rb
UTF-8
2,403
3.296875
3
[]
no_license
require 'active_record' require './lib/address' require './lib/contact' require './lib/email' require './lib/number' database_configuration = YAML::load(File.open('./db/config.yml')) development_configuration = database_configuration["development"] ActiveRecord::Base.establish_connection(development_configuration) def welcome puts "Welcome to awesome address-book!" main end def main choice=nil until choice == 'exit' puts "Press 'a' to add a date of new contacts, 'l' to list your contacts, 'c' to edit, or 'd' to delete contact" puts "Press 'exit' to exit." choice=gets.chomp case choice when 'l' list when 'a' add when 'e' edit when 'd' del else invalid end end end def prompt text puts text gets.chomp end def list puts "All contact:" Contact.all.each do |contact| puts contact end end def add contact_name=prompt "Input name new contact" contact=Contact.new(:name => contact_name) contact.save email_name=prompt "Input email new contact" type_name=prompt "Input email type new contact" email=Email.new(:name => email_name, :email_type => type_name) email.save new_number=prompt "Input number new contact" number_type=prompt "Input number type new contact" number=Number.new(:name => new_number, :number_type => number_type) number.save new_address=prompt "Input address new contact" address=Address.new(:name => new_address) address.save end def edit list id=prompt"Press number to edit or 'exit' to exit" until id == 'exit' Contact.view_id id choice=prompt "Press 'n' to change name, 'e' to change email, 'e_t' to change email type, 'num' to change number, 'n_t' "+ "to change number type, or 'a' to change address" change=prompt "Input change" Contact.edit id, choice, change puts "Change successful!" break end end def del list delete_id=prompt"Press number to delete or 'exit' to exit" until delete_id=='exit' find_id=[] Contact.all.each do |contact| find_id<<contact.id end if find_id.count(delete_id.to_i)!=0 Contact.find(delete_id).delete Email.find(delete_id).delete Number.find(delete_id).delete puts "Delete is complete!" else puts "Incorrect number" end break end end def invalid "Something is wrong!" end welcome
true
3032261c7a7429ed1cae040a1890c0a96ab9d9b9
Ruby
tlgakn/codewars
/29_split_springs.rb
UTF-8
1,804
4.59375
5
[]
no_license
=begin Complete the solution so that it splits the string into pairs of two characters. If the string contains an odd number of characters then it should replace the missing second character of the final pair with an underscore ('_'). =end # first time def solution(string) string_arr = string.chars paired_arr = string_arr.each_slice(2).to_a result_arr = paired_arr.map do |sub_arr| if sub_arr.length.even? sub_arr.join else sub_arr.push("_").join end end result_arr end # second time =begin 29. Split Strings https://www.codewars.com/kata/515de9ae9dcfc28eb6000001 6 kyu Complete the solution so that it splits the string into pairs of two characters. If the string contains an odd number of characters then it should replace the missing second character of the final pair with an underscore ('_'). =end # input: string # output: array of strings # rules: # If the string contains an odd number of characters then it should replace the missing second character of the final pair with an underscore _ # algorithm: # using each slice, slice the string to two element sub_arrays # check the length of each sub_arr # if the length is odd # add _ to the last sub_array # push the underscore to last arr # return the result def solution(string) sliced = string.chars.each_slice(2).to_a if string.chars.length.odd? sliced.last.push("_") end sliced.map {|sub_arr| sub_arr.join} end p solution('abc') == ['ab', 'c_'] p solution('abcdef') == ['ab', 'cd', 'ef'] p solution("abcdef") == ["ab", "cd", "ef"] p solution("abcdefg") == ["ab", "cd", "ef", "g_"] p solution("") == [] p solution('abc') == ['ab', 'c_'] p solution("abcdef") == ["ab", "cd", "ef"] p solution("abcdefg") == ["ab", "cd", "ef", "g_"] p solution("") == []
true
067e19346d1069ca611a161c25f176ffbffa5306
Ruby
kevinYCKim33/oo-student-scraper-v-000
/lib/scraper.rb
UTF-8
4,216
3.0625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'open-uri' require 'pry' require 'nokogiri' class Scraper def self.scrape_index_page(index_url) index_page = Nokogiri::HTML(open(index_url)) index_page.css("div.student-card").map do |profile| { :name => profile.css("h4.student-name").text, :location => profile.css("p.student-location").text, :profile_url => profile.css("a").attribute("href").value } end end # Alternative Soln. # def self.scrape_index_page(index_url) # index_page = Nokogiri::HTML(open(index_url)) # students = [] # index_page.css("div.roster-cards-container").each do |card| # card.css(".student-card a").each do |student| # student_profile_link = "#{student.attr('href')}" # student_location = student.css('.student-location').text # student_name = student.css('.student-name').text # students << {name: student_name, location: student_location, profile_url: student_profile_link} # end # end # students # end def self.scrape_profile_page(profile_url) profile_page = Nokogiri::HTML(open(profile_url)) media = {} profile_page.css("div.social-icon-container a").each do |sns| url = sns.attribute("href").value if url.match(/twitter|linkedin|github/) key = url.match(/twitter|linkedin|github/)[0].to_sym media[key] = url else media[:blog] = url end end media[:profile_quote] = profile_page.css("div.profile-quote").text media[:bio] = profile_page.css("div.description-holder p").text media end # alternative solution: # def self.scrape_profile_page(profile_slug) # student = {} # profile_page = Nokogiri::HTML(open(profile_slug)) # links = profile_page.css(".social-icon-container").children.css("a").map { |el| el.attribute('href').value} # links.each do |link| # if link.include?("linkedin") # student[:linkedin] = link # elsif link.include?("github") # student[:github] = link # elsif link.include?("twitter") # student[:twitter] = link # else # student[:blog] = link # end # end # # student[:twitter] = profile_page.css(".social-icon-container").children.css("a")[0].attribute("href").value # # # if profile_page.css(".social-icon-container").children.css("a")[0] # # student[:linkedin] = profile_page.css(".social-icon-container").children.css("a")[1].attribute("href").value if profile_page.css(".social-icon-container").children.css("a")[1] # # student[:github] = profile_page.css(".social-icon-container").children.css("a")[2].attribute("href").value if profile_page.css(".social-icon-container").children.css("a")[2] # # student[:blog] = profile_page.css(".social-icon-container").children.css("a")[3].attribute("href").value if profile_page.css(".social-icon-container").children.css("a")[3] # student[:profile_quote] = profile_page.css(".profile-quote").text if profile_page.css(".profile-quote") # student[:bio] = profile_page.css("div.bio-content.content-holder div.description-holder p").text if profile_page.css("div.bio-content.content-holder div.description-holder p") # # student end # Scraper.scrape_index_page(index_url) # # => [ # {:name => "Abby Smith", :location => "Brooklyn, NY", :profile_url => "./fixtures/student-site/students/abby-smith.html"}, # {:name => "Joe Jones", :location => "Paris, France", :profile_url => "./fixtures/student-site/students/joe-jonas.html"}, # {:name => "Carlos Rodriguez", :location => "New York, NY", :profile_url => "./fixtures/student-site/students/carlos-rodriguez.html"}, # {:name => "Lorenzo Oro", :location => "Los Angeles, CA", :profile_url => "./fixtures/student-site/students/lorenzo-oro.html"}, # {:name => "Marisa Royer", :location => "Tampa, FL", :profile_url => "./fixtures/student-site/students/marisa-royer.html"} # ] # Scraper.scrape_profile_page(profile_url) # # => {:twitter=>"http://twitter.com/flatironschool", # :linkedin=>"https://www.linkedin.com/in/flatironschool", # :github=>"https://github.com/learn-co, # :blog=>"http://flatironschool.com", # :profile_quote=>"\"Forget safety. Live where you fear to live. Destroy your reputation. Be notorious.\" - Rumi", # :bio=> "I'm a school" # }
true
e8c1d46e52b51942d384ac2dda070b931f18c1a5
Ruby
joedean/registration_old
/app/models/course_parser.rb
UTF-8
2,810
3.25
3
[]
no_license
class CourseParser < Parser def parse_model @model = Course.new parse_course line["Class"] parse_age line["Age"] parse_day_and_time line["Day and Time"] parse_studio line["Studio"] end def parse_course(course) @model.name = course.strip @model.category = parse_category @model.name @model.level = parse_level @model.name end def parse_age age return unless age age.strip! ages = /^(\d\d?) ?- ?(\d\d?) ?.*/.match(age) if ages @model.start_age = ages[1] @model.end_age = ages[2] else if age.downcase.include? "teen" @model.start_age = 13 elsif age.downcase.include? "adult" @model.start_age = 18 elsif age.downcase.include? "and up" @model.start_age = age.split(' ').first else Rails.logger.info("No age requirement") end end end def parse_day_and_time day_time day_time.strip! time_data = /^(\w*) (\d\d?:\d\d) - (\d\d?:\d\d)$/.match(day_time) return unless time_data @model.wday = day_as_int(time_data[1]) @model.start_at = parse_time(time_data[2]) @model.end_at = parse_time(time_data[3]) end def day_as_int day_name Date::DAYNAMES.index day_name.strip end def parse_time time period = "pm" hour = hour time period = "am" if @model.wday == 6 && hour < 12 && hour > 8 DateTime.strptime("2001-01-#{@model.wday} #{time} #{period}", "%Y-%m-%d %l:%M %P") end def parse_studio studio @model.studio = studio.strip end def parse_category course_name name = course_name.downcase.strip if name.include?("ballet") || name.include?("pointe") || name.include?("barre") "Ballet" elsif name.include? "tap" "Tap" elsif name.include? "jazz" "Jazz" elsif name.include? "hip hop" "Hip Hop" elsif name.include? "modern" "Modern" elsif name.include? "acro" "Acro" elsif name.include? "pilates" "Pilates" elsif name.include? "zumba" "Zumba" elsif name.include? "lyrical" "Lyrical" elsif name.include? "pure dance" "Pure Dance" else Rails.logger.info "No course catalog can be determined." nil end end def parse_level course_name name = course_name.strip course_data = /^.*\s(I\S* ?(?:Prep)?).*/.match(name) level = course_data[1] if course_data name.downcase! if name.include?("pre") || name.include?("begin") level ||= "Beginner" elsif name.include? "adult" level ||= "Adult" elsif name.include? "int" level ||= "Intermediate" elsif name.include? "adv" level ||= "advanced" else Rails.logger.info "No level can be determined." end level end private def hour time time.split(":")[0].to_i end end
true
df2c3cfe056817d219129f1307be0e5de9863dec
Ruby
feigningfigure/WDI_NYC_Apr14_String
/w01/d02/INSTRUCTORS/drinking_age.rb
UTF-8
200
3.734375
4
[]
no_license
print "What is your age? " user_age = gets.chomp.to_i if user_age > 100 print "Your age is: " print user_age puts "" puts "You are way old!" else puts "Enjoy the rest of your youth!" end
true
23c34a749fed38239b8cb675d93034d431a138aa
Ruby
derwind/machine_learning
/font_analysis/uni2char.rb
UTF-8
157
2.609375
3
[]
no_license
#! /usr/bin/ruby -Ku while line = gets line.chomp! cid, uni = line.split(/\s+/).map { |n| n.to_i } char = [uni].pack("U*") print "#{uni} #{char}\n" end
true
6f9e15ea279e40bcf249c4311905e564a6d41eb0
Ruby
jackrobinrye/greatreads-rails
/db/seeds.rb
UTF-8
3,093
3.09375
3
[]
no_license
#users jack = User.create(name: "Jack", email: "jack@gmail.com", password: "password") sarah = User.create(name: "Sarah", email: "sarah@gmail.com", password: "password") #authors tolkein = Author.create( name: "J R R Tolkein", birthdate: Time.new(1892, 1, 3), bio: "John Ronald Reuel Tolkien was an English writer, poet, philologist, and academic, who is best known as the author of the classic high fantasy works The Hobbit, The Lord of the Rings, and The Silmarillion." ) brown = Author.create( name: "Dan Brown", birthdate: Time.new(1964, 6, 22), bio: "The son of a mathematics teacher and a church organist, Brown was raised on a prep school campus where he developed a fascination with the paradoxical interplay between science and religion. These themes eventually formed the backdrop for his books. He is a graduate of Amherst College and Phillips Exeter Academy, where he later returned to teach English before focusing his attention full time to writing. He lives in New England with his wife." ) rowling = Author.create( name: "JK Rowling", birthdate: Time.new(1965, 7, 31), bio: "Joanne Rowling, better known by her pen name J. K. Rowling, is a British author, film producer, television producer, screenwriter, and philanthropist. She is best known for writing the Harry Potter fantasy series, which has won multiple awards and sold more than 500 million copies, becoming the best-selling book series in history. The books are the basis of a popular film series, over which Rowling had overall approval on the scripts and was a producer on the final films. She also writes crime fiction under the name Robert Galbraith." ) #genres fantasy = Genre.create(name: "Fantasy") mystery = Genre.create(name: "Mystery") nonfiction = Genre.create(name: "Nonfiction") romance = Genre.create(name: "Romance") scifi = Genre.create(name: "Science Fiction") thriller = Genre.create(name: "Thriller") young_adult = Genre.create(name: "Young Adult Fiction") #books lotr1 = Book.create(title: "Fellowship of the Ring", author_id: tolkein.id, genre_id: fantasy.id) lotr2 = Book.create(title: "Twin Towers", author_id: tolkein.id, genre_id: fantasy.id) lotr3 = Book.create(title: "Return of the King", author_id: tolkein.id, genre_id: fantasy.id) hp1 = Book.create(title: "Harry Potter and the Sorcerer's Stone", author_id: rowling.id, genre_id: fantasy.id) divinci_code = Book.create(title: "The Di Vinci Code", author_id: brown.id, genre_id: mystery.id) #jack's book_records BookRecord.create(user_id: jack.id, book_id: lotr1.id, read: true) BookRecord.create(user_id: jack.id, book_id: lotr2.id, read: false) BookRecord.create(user_id: jack.id, book_id: lotr3.id, read: false) BookRecord.create(user_id: jack.id, book_id: hp1.id, read: true) BookRecord.create(user_id: jack.id, book_id: divinci_code.id, read: true) #sarah's book_records BookRecord.create(user_id: sarah.id, book_id: hp1.id, read: true) BookRecord.create(user_id: sarah.id, book_id: lotr1.id, read: false) BookRecord.create(user_id: sarah.id, book_id: lotr2.id, read: false) BookRecord.create(user_id: sarah.id, book_id: lotr3.id, read: false)
true
f02bb995389d5a47eb53a184ceefcbb273f1345d
Ruby
Jackmt9/programming-univbasics-nds-green-grocer-nyc-web-030920
/grocer.rb
UTF-8
2,628
3.5
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'pry' def find_item_by_name_in_collection(name, collection) # Implement me first! # # Consult README for inputs and outputs collection.each do |hash| if hash[:item] == name return hash end end return nil end def consolidate_cart(cart) # Consult README for inputs and outputs # # REMEMBER: This returns a new Array that represents the cart. Don't merely # change `cart` (i.e. mutate) it. It's easier to return a new thing. count = 0 new_array = [] while count < cart.length temp_name = cart[count][:item] found_item = find_item_by_name_in_collection(temp_name, new_array) if found_item found_item[:count] += 1 else cart[count][:count] = 1 new_array << cart[count] end count += 1 end new_array end def apply_coupons(cart, coupons) # Consult README for inputs and outputs # # REMEMBER: This method **should** update cart # binding.pry new_cart = [] cart.each do |cart_hash| coupons.each do |coupon_hash| if coupon_hash[:item] == cart_hash[:item] if coupon_hash[:num] == cart_hash[:count] # binding.pry new_hash = cart_hash.clone new_hash[:count] = 0 new_cart << new_hash cart_hash[:item] = cart_hash[:item] + " W/COUPON" cart_hash[:price] = coupon_hash[:cost] / coupon_hash[:num] elsif coupon_hash[:num] < cart_hash[:count] cart_hash[:count] -= coupon_hash[:num] new_hash = cart_hash.clone new_hash[:item] = new_hash[:item] + " W/COUPON" new_hash[:price] = coupon_hash[:cost] / coupon_hash[:num] new_hash[:count] = coupon_hash[:num] cart << new_hash end end end end # binding.pry cart << new_cart[0] if new_cart[0] cart end def apply_clearance(cart) # Consult README for inputs and outputs # # REMEMBER: This method **should** update cart cart.each do |hash| if hash[:clearance] == true hash[:price] = hash[:price] * 0.8 end end end def checkout(cart, coupons) # Consult README for inputs and outputs # # This method should call # * consolidate_cart # * apply_coupons # * apply_clearance # # BEFORE it begins the work of calculating the total (or else you might have # some irritated customers total = 0 cons_cart = consolidate_cart(cart) # binding.pry new_cart = apply_clearance(apply_coupons(cons_cart, coupons)) # binding.pry new_cart.each do |hash| total += hash[:price] * hash[:count] end total > 100 ? total = total * 0.9 : nil total = '%.1f' % total return total.to_f end
true
2040558f87a9d2f0cf48512c421a6b7f741e812a
Ruby
rwadstein/eventq
/eventq_aws/lib/eventq_aws/aws_queue_manager.rb
UTF-8
1,843
2.625
3
[ "MIT" ]
permissive
module EventQ module Amazon class QueueManager VISIBILITY_TIMEOUT = 'VisibilityTimeout'.freeze def initialize(options) if options[:client] == nil raise ':client (QueueClient) must be specified.'.freeze end @client = options[:client] end def get_queue(queue) if queue_exists?(queue) update_queue(queue) else create_queue(queue) end end def create_queue(queue) response = @client.sqs.create_queue({ queue_name: queue.name, attributes: { VISIBILITY_TIMEOUT => 300.to_s #5 minutes } }) return response.queue_url end def drop_queue(queue) q = get_queue(queue) @client.sqs.delete_queue({ queue_url: q}) return true end def drop_topic(event_type) topic_arn = @client.get_topic_arn(event_type) @client.sns.delete_topic({ topic_arn: topic_arn}) return true end def queue_exists?(queue) return @client.sqs.list_queues({ queue_name_prefix: queue.name }).queue_urls.length > 0 end def update_queue(queue) url = @client.get_queue_url(queue) @client.sqs.set_queue_attributes({ queue_url: url, # required attributes: { VISIBILITY_TIMEOUT => 300.to_s # 5 minutes } }) return url end end end end
true
f72800041477634679025c099450030e1e3cdb06
Ruby
leuchtetgruen/webcam-server
/video.rb
UTF-8
1,544
2.59375
3
[]
no_license
require 'tempfile' SECONDS_PER_SEGMENT = 10 PLAYLIST_LENGTH = 6 KEEP_SEGMENTS = 100 def video_streaming_enabled? @@mode == :video end def video_available? @@segment_ctr > 1 end def keep_segments ret = (@@config['keep_minutes'].to_i * 60) / SECONDS_PER_SEGMENT (ret == 0) ? KEEP_SEGMENTS : ret end def start_video_capture FileUtils.rm_r "segments" if Dir.exist?("segments") FileUtils.mkdir "segments" Thread.new do loop do @@segment_ctr = @@segment_ctr + 1 if @@segment_ctr > keep_segments # cleanup File.delete(segment_filename(@@segment_ctr - keep_segments)) end filename = segment_filename(@@segment_ctr) capture_video(filename, SECONDS_PER_SEGMENT) end end end def segment_filename(segment_id) "segments/video_#{segment_id}.mpg" end def live_playlist(token, entries) entries = PLAYLIST_LENGTH if entries == 0 video_playlist(@@segment_ctr - 1, @@segment_ctr + entries, token) end def video_playlist(from_segment, to_segment, token) s = "#EXTM3U\r\n" (from_segment..to_segment).each do |i| s = s + "#EXTINF:#{SECONDS_PER_SEGMENT}, Video\r\n" s = s + "#{base_url}/#{token}/video_#{i}.mpg\r\n" end s end def video_concatenate(from_segment, to_segment, outputfile) files = (from_segment..to_segment).map do |i| "file '#{segment_filename(i)}'" end File.write("playlist", files.join("\n")) puts "Converting" cmd = "ffmpeg -f concat -i playlist -c copy #{outputfile} > /dev/null 2>&1" pid = Process.spawn(cmd) Process.wait(pid) File.delete("playlist") puts "Done" true end
true
cb63472d1258128c7db0d94e93589293b9be183f
Ruby
case-iot/model_evaluation
/spec/spec_helper.rb
UTF-8
1,039
2.546875
3
[]
no_license
require 'case_model' require 'webmock/rspec' RSpec.configure do |config| config.expect_with :rspec do |c| c.syntax = :expect end end class UseCaseLoader def read_def(repo, path) RDF::N3::Reader.open(path) do |reader| reader.each_statement do |statement| # ruby-rdf created very long names for variables with the # full path to the folder, which Eye couldn't reason about # so here, the name is shortened to remove the path if statement.subject.variable? statement.subject = process_var_name(statement.subject) end if statement.predicate.variable? statement.predicate = process_var_name(statement.predicate) end if statement.object.variable? statement.object = process_var_name(statement.object) end repo << statement end end repo end def process_var_name(object) full_name = object.to_s var_name = full_name.split('#').last.to_sym RDF::Query::Variable.new(var_name) end end
true
618092afc5479a0da2288741fd1bb424ccdb136a
Ruby
cinexin/MiniShoppingList
/test/examples/spec/bacon_spec.rb
UTF-8
258
2.625
3
[]
no_license
require_relative 'lib/bacon' describe Bacon do # one specification it "is edible" do expect(Bacon.new.edible?).to be_true end # another specification it "expired!" do bacon = Bacon.new bacon.expired! expect(bacon).to_not be_edible end end
true
b14266c25f0f0d3c384184a77996ad96bee0fffb
Ruby
rshakhb10/alternative-fuel-stations-locator
/lib/data_request.rb
UTF-8
824
3.296875
3
[]
no_license
# Class that wraps up a data request to the API # Currently support JSON format # Requires an API key to access the data # Also includes parameters of request. # e.g., return only fuel stations in a particular state. class DataRequest attr_accessor :url, :api_key, :params, :output_format def initialize url, api_key, params, output_format @url = url @api_key = api_key @params = params @output_format = output_format end def get_data # Will return data in JSON format # Construct the request request = @url + @params + '&api_key='+@api_key+'&format='+@output_format puts "\n#Request: "+request if @output_format.upcase == 'JSON' data = JSON.load(RestClient.get(request)) #elsif @output_format.upcase == 'XML' # data = Document.new(RestClient.get(request)) end return data end end
true
52ec1c83195a242c7e74ce1a5ea827003511f400
Ruby
Gettekt/APT
/app/models/searchresult.rb
UTF-8
2,075
3.21875
3
[]
no_license
class SearchResult @@results = [] @array = [] attr_reader :name, :price, :rating, :address, :open attr_accessor :num def initialize(place) @num = @@results.length + 1 @name = place["name"] if @name == nil @name = "?" end @price = place["price_level"] if @price == nil @price = "?" end @rating = place["rating"] if @rating == nil @rating = "?" end @address = place["vicinity"] if @address == nil @address = "?" end if place["opening_hours"] != nil @open = place["opening_hours"]["open_now"] end if @open == nil @open = "?" end @@results << self end def self.all @@results end def self.sort_by_price @@results.sort_by! do |result| result.price.to_f end @@results.each do |result| if result.price == '?' @array << result end end @@results.map! do |result| if result.price != '?' result end end @@results.compact! @@results+= @array a = File.open("./open", "r+") if eval(File.read(a)) == false @@results.map! do |result| if result.open == true result end end end @@results.compact! @@results.each_with_index do |result,index| result.num=(index+1) end end def self.sort_by_rating @@results.sort_by! do |result| result.rating.to_f end @@results.reverse! a = File.open("./open", "r+") if eval(File.read(a)) == false @@results.map! do |result| if result.open == true result end end end @@results.each_with_index do |result,index| result.num=(index+1) end end def self.sort_by_open @@results.collect! do |result| if result.open == true result end end @@results.compact! @@results.each_with_index do |result,index| result.num=(index+1) end end def self.sort_by_name @@results.sort_by! do |result| result.name end a = File.open("./open", "r+") if eval(File.read(a)) == false @@results.map! do |result| if result.open == true result end end end @@results.each_with_index do |result,index| result.num=(index+1) end end end
true
accbe3270e2fe3101d972d2d192e27a8e80ed6f9
Ruby
dkandalov/katas
/ruby/sort/insertsort/insert_sort_spec.rb
UTF-8
751
3.53125
4
[ "Unlicense" ]
permissive
require "rspec" describe "Insert sort" do it "sorts things" do sorted([]).should == [] sorted([1]).should == [1] [1, 2, 3].permutation.each { |it| sorted(it).should == [1, 2, 3] } [1, 2, 3, 4].permutation.each { |it| sorted(it).should == [1, 2, 3, 4] } end def sorted(list) return list if list.size < 2 (1...list.size).each do |i| j = find_insert_index(i) { |it| list[it] <= list[i]} swap_elements_in(list, i, j) end list end def find_insert_index(from_index, &predicate) j = from_index - 1 while j >= 0 and not predicate.call(j) do j = j - 1 end j + 1 end def swap_elements_in(list, from, to) element = list.delete_at(from) list.insert(to, element) end end
true
cbf5b7fc8bb608aa10e803de4103fda037b240b4
Ruby
btiddle/cd-ror-01ruby-01learn
/asgn-01-tryruby-C-misch.rb
UTF-8
3,268
3.53125
4
[]
no_license
# Fiels and direcories # Anything listed after a method is considered an attachment. print Dir.entries "/" puts # => [".", "..", ".DocumentRevisions-V100", ".file", ".fseventsd", ".PKInstallSandboxManager", ".Spotlight-V100", ".Trashes", ".vol", "Applications", "backup", "balsmiq-demo-file.bmml", "bin", "cores", "dev", "etc", "home", "Library", "mach_kernel", "net", "Network", "private", "sbin", "Software", "System", "tmp", "User Information", "Users", "usr", "var", "Volumes"] print "pre", "event", "ual", "ism" # => preeventualism puts print File.read("/comics.txt") FileUtils.cp('/comics.txt', '/Home/comics.txt') File.open("/Home/comics.txt", "a") do |f| f << "Cat and Girl: http://catandgirl.com/" end print File.read("/Home/comics.txt") # What time was it when you changed the file? File.mtime("/Home/comics.txt") # Files - Lots of methods for editing files and lookin around in directories. # Arguments - Arguments are a list of things sent into a method. With commas between. # do and end are another way to make a block. # Creating a method def load_comics( path ) comics = {} File.foreach(path) do |line| name, url = line.split(': ') comics[name] = url.strip end comics end comics = load_comics('/comics.txt') require 'popup' Popup.goto "http://ruby-lang.org" Popup.make { h1 "My Links" link "Go to Ruby", "http://ruby-lang.org/" } Popup.make do h1 "Things To Do" list do p "Try out Ruby" p "Ride a tiger" p "(down River Euphrates)" end end Popup.make do h1 "Comics on the Web" list do comics.each do |name, url| link name, url end end end # Empty curly braces {} is a shortcut for Hash.new. class BlogEntry attr_accessor :title, :time, :fulltext, :mood end entry = BlogEntry.new. # In the class definition, you used a method called attr_accessor. # There are many attribute methods like this which add little # settings to classes. These attributes are just variables # attached to a class. entry.time = Time.now entry.mood = :sick entry.fulltext = "I can't believe Mt. Hood was stolen! I am speechless! It was stolen by a giraffe who drove away in his Cadillac Seville very nonchalant!!" class BlogEntry def initialize( title, mood, fulltext ) @time = Time.now @title, @mood, @fulltext = title, mood, fulltext end end # Classes - Everything in Ruby is some kind of object. Classes explain objects. How a certain object works. For example, you made a few blog entry objects and these objects are explained in the BlogEntry class. In other words: you call them BlogEntry objects. # Accessors - Are variables attached to an object which can be used outside the object. (entry.time = Time.now) # Instance variables - Are the same variables you're using for accessors when inside the object. Like in a method definition. (@time = Time.now) # sort your entries from newest to oldest. blog.sort_by { |entry| entry.time }.reverse #search your blog for anything related to "cadillac" blog.find_all { |entry| entry.fulltext.match(/cadillac/i) } # add new entries with blog << <new_entry> # The map method cycles through an array and replaces each item with something new blog.map { |entry| entry.mood } blog.map { "Bruce Willis" }
true
50e2d8d3ee80bb2cf24e10eb8e8c1ad5cf2147c9
Ruby
prynt/inscriber
/spec/spec_helpers/test_database.rb
UTF-8
1,854
2.578125
3
[]
no_license
require 'sequel' require 'rspec' require 'spec_helpers/config_helpers' module Inscriber # The TestDatabase is responsible for creating a SQLite database with tables and columns for testing. # It is dumped after every example. To create a database, use the following format: # # Inscriber::TestDatabase.setup do # create_table :test do # primary_key :id # string :body # integer :test_app_id # end # end # # Inscriber::TestDatabase.setup will return an instance of Inscriber::Database, which can be used for testing: # database = Inscriber::TestDatabase.setup # it 'should do something' do # Inscriber::Downloader.new(database).download # end # class TestDatabase class << self def setup(&block) self_config = new.tap do |config| config.instance_eval(&block) if block end self_config.database end def reset location = "./#{Inscriber::ConfigHelpers.config[:database_name]}" File.unlink(location) if File.exists?(location) end end attr_accessor :database def initialize @database ||= Inscriber::Database.new(Inscriber::ConfigHelpers.config) end def db_connection database.connection end def create_table(name, &block) opts = { name: name, database: database } TableCreator.new(opts).setup(&block) end end class TableCreator attr_accessor :name, :database def initialize(opts) @name = opts[:name] @database = opts[:database] end def setup(&block) db_connection.create_table(name) { instance_eval &block } end private def db_connection database.connection end end end RSpec.configure do |config| config.around(:each) do |example| Inscriber::TestDatabase.reset example.run end end
true
92b5d3a55286411120870f1ecf88bc204dfbaee8
Ruby
crapooze/epo
/example/models.rb
UTF-8
662
2.703125
3
[ "MIT" ]
permissive
require 'welo' class Item include Welo::Resource perspective :default, [:name, :price] identify :default, [:uuid] identify :flat_db, [:uuid] attr_reader :name, :price, :uuid def initialize(name, price=0, uuid=nil) @name = name @price = price @uuid = uuid || rand(65535) end end class Person include Welo::Resource perspective :default, [:name, :age, :items] perspective :all, [:name, :age, :run_id] identify :flat_db, [:name, :run_id] relationship :items, :Item, [:many] attr_reader :name, :age, :run_id, :items def initialize(name, age, id=0) @name = name @age = age @run_id = id @items = [] end end
true
b3b0ef5275f3efb0e532107f40d1d7037a7718ce
Ruby
mackied0g/sinatra-basic-routes-lab-dumbo-web-071519
/app.rb
UTF-8
352
2.578125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require_relative 'config/environment' class App < Sinatra::Base get "/" do "Hello, World!" end get "/name" do "My name is Mackenzie." end get "/hometown" do "My hometown is Northfield, Minnesota." end get "/favorite-song" do "My favorite song is Butterfly by Crazy Town." end end
true
5c92ec987852655c600b6ef4a40ba992b64c0989
Ruby
DanielMatney/activerecord-validations-lab-online-web-pt-090919
/app/models/post.rb
UTF-8
542
2.53125
3
[]
no_license
class Post < ActiveRecord::Base include ActiveModel::Validations validates :title, presence: true validates :content, length: { minimum: 250 } validates :summary, length: { maximum: 250 } validates :category, inclusion: { in: %w(Fiction Non-Fiction), message: "%{value} must be Fiction or Non-Fiction" } validate :non_clickbait def non_clickbait unless title && title.include?("Won't Believe" || "Secret" || "Top" || "Guess") errors.add(:non_clickbait, "Title not clickbaitey enough!") end end end
true
84e3ff7fe0e7c2e5172c0cb6321b0ea41ec62bfc
Ruby
stovermc/practice-repo
/cracking_the_coding_interview/rotate_array/lib/rotate_array.rb
UTF-8
876
4.5
4
[]
no_license
# Given an image represented by an NxN matrix, where each pixel in the image is # 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in # place? # [[1, 2, 3], # [4, 5, 6], # [7, 8, 9]] # [[7, 4, 1], # [8, 5, 2], # [9, 6, 3]] # [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # [[7, 4, 1], [8, 5, 2], [9, 6, 3]] # 2, 4, 6 # 0,0 --> 0,2 # 0,1 --> 1,2 # 0,2 --> 2,2 # 1,0 --> 0,1 # 1,1 --> 1,1 # 1,2 --> 2,1 # 2,0 --> 0,0 # 2,1 --> 1,0 # 2,2 --> 2,0 ### Solution Steph and I came up with def rotate(matrix) # 4 groups of two a = 0 b = 2 c = 2 2.times do |num| matrix[num][c], matrix[c][b], matrix[b][a], matrix[a][num] = matrix[a][num], matrix[num][c], matrix[c][b], matrix[b][a] b -=1 end p matrix end ###Solution using ruby methods def rotate(matrix) p matrix.reverse.transpose end rotate([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
true
0b546b5f3b2e5edb8255577567cc380491c438f8
Ruby
amohamedali/routes_coverage
/lib/routes_coverage/formatters/full_text.rb
UTF-8
3,342
2.5625
3
[ "MIT" ]
permissive
module RoutesCoverage module Formatters class FullText < SummaryText class RouteFormatter attr_reader :buffer def initialize result=nil, _settings=nil, output_hits=false @buffer = [] @result = result @output_hits = output_hits @output_prefix = false end def result @buffer.join("\n") end def section_title(title) @buffer << "\n#{title}:" end def section(routes) @buffer << draw_section(routes) end def header(routes) @buffer << draw_header(routes) end def no_routes _routes_from_rails5=nil @buffer << "\tNone" end private HEADER = ['Prefix', 'Verb', 'URI Pattern', 'Controller#Action'] def draw_section(routes) header_lengths = HEADER.map(&:length) name_width, verb_width, path_width, reqs_width = widths(routes).zip(header_lengths).map(&:max) hits = nil routes.map do |r| # puts "route is #{r.inspect}" if @output_hits # hits = " ?" if r[:original].respond_to?(:__getobj__) original_route = r[:original].__getobj__ # SimpleDelegator else original_route = r[:original] end hits = " #{@result.route_hit_counts[original_route]}" end "#{r[:name].rjust(name_width) if @output_prefix} #{r[:verb].ljust(verb_width)} #{r[:path].ljust(path_width)} #{r[:reqs].ljust(reqs_width)}#{hits}" end end def draw_header(routes) name_width, verb_width, path_width, reqs_width = widths(routes) "#{"Prefix".rjust(name_width) if @output_prefix} #{"Verb".ljust(verb_width)} #{"URI Pattern".ljust(path_width)} #{"Controller#Action".ljust(reqs_width)}#{' Hits' if @output_hits}" end def widths(routes) [routes.map { |r| r[:name].length }.max || 0, routes.map { |r| r[:verb].length }.max || 0, routes.map { |r| r[:path].length }.max || 0, routes.map { |r| r[:reqs].length }.max || 0, ] end end def routes_section formatter, title, routes formatter.buffer << title if routes.none? formatter.no_routes else formatter.header routes formatter.section routes end formatter.result end def hit_routes routes = result.hit_routes # engine routes now are in the same list if Result::Inspector::NEW_RAILS hit_routes = Result::Inspector.new(result.hit_routes).collect_all_routes pending_routes = Result::Inspector.new(result.pending_routes).collect_all_routes else #rails 3 hit_routes = Result::Inspector.new.collect_all_routes(result.hit_routes) pending_routes = Result::Inspector.new.collect_all_routes(result.pending_routes) end return routes_section(RouteFormatter.new(result, settings, true), "Covered routes:", hit_routes) + "\n\n" + routes_section(RouteFormatter.new(result, settings), "Pending routes:", pending_routes) end def format "#{super}\n\n#{hit_routes}" end end end end
true
cf4df8ab7a802718ce1ff21d7d5824aa45c84b7f
Ruby
cbarcroft/kitchenomicon-rr
/app/helpers/application_helper.rb
UTF-8
917
3.265625
3
[]
no_license
module ApplicationHelper def mixed_number_to_rational(amount) rational_to_return = 0 amount.split(" ").each { |string| if is_rational?(string) # Number? if string.include?("/") # Fraction? rational_to_return += Rational(string) elsif string.to_i == string.to_f # Whole number? rational_to_return += string.to_i elsif string.include?(".") # Decimal? rational_to_return += Rational(string) else # Not a fraction, decimal, or whole number. return false end else return false # Not a number. end } rational_to_return end def numeric_to_mixed_number(amount) amount_as_integer = amount.to_i if (amount_as_integer != amount.to_f) && (amount_as_integer > 0) fraction = amount - amount_as_integer "#{amount_as_integer} #{fraction}" else amount.to_s end end end
true
625ff005d46f223b7b75acb49ea5c7d598268020
Ruby
lemanchester/routes-api
/app/validators/map_route_points_validator.rb
UTF-8
407
2.71875
3
[]
no_license
class MapRoutePointsValidator < Struct.new(:map) def validate!(origin, destination) raise StandardError.new("This map does not contain #{origin} as a route") unless route_points.include?(origin) raise StandardError.new("This map does not contain #{destination} as a route") unless route_points.include?(destination) true end def route_points @points ||= map.route_points end end
true
7876fdc863b4815e2fd794e7e6c8b20914b79f5f
Ruby
Rstinkho/ruby-oop-cards
/test.rb
UTF-8
1,698
4.1875
4
[]
no_license
require 'byebug' # playerOneScore = 0 # playerTwoScore = 0 # put = 1.times.map{ Random.rand(52) } # puts put # if (put[0] >= put[1]) # playerOneScore += 1 # puts "Player One + 1" # elsif (put[0] <= put[1]) # playerTwoScore += 1 # puts "Player Two + 1" # end # puts "SCORE: Player1 = #{playerOneScore}, player2 = #{playerTwoScore}" # Create a card class that, when you initialize it, creates an array of "cards" that are of value 1-52. class Cards attr_accessor :cards def initialize @cards = Array.new(52) {|i| i+1 } end end # Create a game class that uses the card class to play a game. class Game attr_accessor :deck, :score, :hands, :name def initialize puts "what is your name" @deck = Cards.new.cards.shuffle @score = 0 @hands = [] @name = gets.chomp end def play user_hand = @deck.pop house_hand = @deck.pop @hands << [user_hand, house_hand] if user_hand > house_hand @score += 1 puts "#{@name}'s card: #{user_hand}, computer: #{house_hand}" else @score -= 1 puts "#{@name}'s card: #{user_hand}, computer: #{house_hand}" end end def check_game @score end end # Inside the game class, keep a record of each hand played in an instance variable array. # Show the score to the player puts "STARTING NEW GAME" game = Game.new loop do game.play puts "CURRENT SCORE: #{game.check_game.to_s}" puts "CONTINUE?" answer = gets.chomp if answer == "no" abort end if game.check_game <= -2 puts "YOU LOOOOOOOOOSE LOL" puts "FINAL SCORE: #{game.check_game.to_s}" abort end end # byebug # puts "end"
true
929d1a2998ec07fc1c277699f5fe72c920ca713f
Ruby
sasdevs/ruby-course
/exercises/x.rb
UTF-8
85
2.9375
3
[]
no_license
t = Thread.new do puts "first" sleep 1 puts "second" end puts "outside" t.join
true
683c735835ed34655e3e577486073a529fb18b60
Ruby
edhowland/viper
/lib/runtime/regex_hash.rb
UTF-8
459
3.5
4
[ "MIT" ]
permissive
# regex_hash - class RegexHash - data structor to use regex'es as keys # When stored, the key is a Regexp # and retrieved it is some potetially matching string # rubocop:disable Style/DoubleNegation class RegexHash def initialize @storage = [] end attr_reader :storage def []=(key, value) @storage << [key, value] end def [](key) results = @storage.select { |e| !!(key =~ e[0]) } results[0][1] unless results.empty? end end
true
27ae8dc1782d27a5d5e37beb12a64f47fc4d88ce
Ruby
kaji-hiro/AtCoder_beginner_contest
/ABC182/B-Almost_GCD.rb
UTF-8
249
3.171875
3
[]
no_license
require 'prime' n = gets.to_i k = gets.split.map(&:to_i) ans = 0 max_count = 0 Prime.take(168).each do |p| count = 0 k.each do |k| count += 1 if k % p == 0 end if max_count < count ans = p max_count = count end end puts ans
true
3552f0df05b5192b40fe8461dc450f38fb37b4ab
Ruby
ArturTTN/xrates
/lib/xrates/currency/arithmetic.rb
UTF-8
669
2.953125
3
[ "MIT" ]
permissive
module Xrates class Currency module Arithmetic def -(curr); calculate('-', curr) end def +(curr); calculate('+', curr) end def /(curr); calculate('/', curr) end def *(curr); calculate('*', curr) end def calculate(math_method, currency) raise TypeError, "Should be Xrates::Currency" unless currency.is_a?(Xrates::Currency) if self.code != currency.code currency = currency.convert_to(@code) end self.class.new( (BigDecimal(@amount.to_s).send( math_method, BigDecimal(currency.amount.to_s))).to_f.round(@round), @code, @driver) end end end end
true
e68c945486e83531ed623cb886ac06843a80d118
Ruby
OpenLinkSoftware/Documentation
/virtdoc2md/virtdoc2md.rb
UTF-8
7,459
3.15625
3
[]
no_license
#!/usr/bin/env ruby require 'fileutils' require 'nokogiri' # # Converts portions of the Virtuoso DocBook documentation to Markdown # using pandoc. # class VirtDocConv attr_accessor :doc attr_reader :output_dir # Root folder for holding the converted book attr_reader :virt_docs_root_dir # Root folder holding the source Virtuoso DocBook documentation to be converted def initialize (output_dir, xmlDoc, virt_docs_root_dir) @output_dir = output_dir @virt_docs_root_dir = virt_docs_root_dir self.doc = Nokogiri::XML(File.read(xmlDoc)) do |config| config.huge end self.doc.remove_namespaces! end def check_for_pandoc unless system("pandoc --version >/dev/null 2>&1") raise "ERROR: pandoc is not available. Please install it." end end # # Extracts the chapter names # def chapter_names rChapters = [] chapter_index = 0 self.doc.xpath('//chapter').each do |el_chapter| el_chapter.xpath('./title | ./info/title').each do |el_title| chapter_index += 1 chapter_title = el_title.content.strip.gsub(/\s+/, ' ') rChapters << "#{chapter_index} - #{chapter_title}" end end rChapters end # # Creates a tree of folders, one per chapter # def create_folder_tree root_dir = self.output_dir if File.exist? root_dir if !File.directory? root_dir raise "File #{root_dir} is preventing creation of a directory of the same name" else # Clear the existing tree # TO DO: Ask for confirmation FileUtils.rm_r root_dir, :force => true end end FileUtils.mkdir root_dir FileUtils.cd(root_dir) do FileUtils.mkdir(chapter_names) end end # # Creates a Markdown version of a chapter abstract in the chapter's folder # # The pandoc conversion of DocBook to Markdown is lossy. # It loses a good deal of information including any chapter abstract. # So we extract the abstract here and convert is separately. def create_abstract(ch_indx, ch_name) chapter_abstract = extract_docbook_abstract(ch_indx, ch_name) # if chapter_abstract.length # puts "chapter #{ch_indx} [#{ch_name}]: abstract >>>" # puts chapter_abstract # puts "<<<" # else # puts "!No abstract" # end f_basename = "abstract#{ch_indx + 1}" write_file(chapter_abstract, "#{self.output_dir}/#{ch_name}", f_basename, ".md") end def convert_chapter(ch_indx, ch_name) chapter_xml = extract_docbook_chapter(ch_indx, ch_name) # Write the XML to a temp file f_basename = "chapter#{ch_indx + 1}" xml_f_path = write_file(chapter_xml, "#{self.output_dir}/#{ch_name}", f_basename, ".xml") md_f_path = "#{self.output_dir}/#{ch_name}/#{f_basename}.md" # Convert using pandoc docbook_to_md(xml_f_path, md_f_path) # Remove the temp file FileUtils.rm(xml_f_path) end # The returned abstract is raw text, separated into paragraphs. # FIX ME: # Any other structural elements contained in the abstract are lost. # e.g. Some abstracts contain simple lists. These lists are collapsed # to raw text in the paragraph. They will require manually reformatting # in the emitted Markdown. def extract_docbook_abstract(ch_indx, ch_name) abstract = "" el_chapter = self.doc.xpath('//chapter')[ch_indx] el_chapter.xpath('./info').each do |el_info| el_info.xpath('./abstract').each do |el_abstract| el_abstract.xpath('./para').each do |el_para| para = el_para.content.strip.gsub(/\s+/, ' ') + "\n\n" abstract << para end end end abstract end def extract_docbook_chapter(ch_indx, ch_name) el_chapter = self.doc.xpath('//chapter')[ch_indx] chapter_xml = el_chapter.to_s #chapter_xml end # in_file: input file containing DocBook XML # out_file: output file to receive the Markdown def docbook_to_md(in_file, out_file) begin cmd = %Q{pandoc -f docbook -t gfm -o "#{out_file}" "#{in_file}"} puts(cmd) cmd_output = %x{#{cmd} 2>&1} if $?.exitstatus == 0 puts("#{in_file}: Conversion successful") else puts("!ERROR: pandoc conversion failed - #{cmd_output}") end end end def write_file(f_content, f_dir, f_name, f_ext) f_path = "#{f_dir}/#{f_name}#{f_ext}" FileUtils.cd(f_dir) do open("#{f_name}#{f_ext}", "w") do |f| f << f_content end end f_path end # # The virtuoso docbook source keeps all the book's images # in a single folder. # # For easier management, gather the images belonging to a chapter into # their own folder, with the chapter folder as the parent. # def fix_chapter_image_links(ch_indx, ch_name) f_basename = "chapter#{ch_indx + 1}" md_f_path = "#{self.output_dir}/#{ch_name}/#{f_basename}.md" md_fixed_f_path = "#{self.output_dir}/#{ch_name}/#{f_basename}.fixed.md" File.open md_f_path, 'r' do |f_in| File.open md_fixed_f_path, 'w' do |f_out| previous_line = nil f_in.each do |line| # Search for image links like: # ![Virtuoso.ini file in notepad](virttour33.gif) # Change the image path to a subdirectory of the chapter directory # Copy the image to a /image/ subdirectory of the chapter directory if previous_line line = previous_line + line end match = /^(\s*)!\[(.+)\]\((.*)\)/.match(line) partial_match = /^(\s*)!\[/.match(line) if match m = match fixed_image_link = "#{m[1]}![#{m[2]}](./images/#{m[3]})" f_out << fixed_image_link + "\n" previous_line = nil src_img_dir = File.dirname(m[3]) src_img_path = "#{self.virt_docs_root_dir}/images/#{m[3]}" dest_img_dir = "#{self.output_dir}/#{ch_name}/images/#{src_img_dir}" copy_image_to_chapter_subdir(src_img_path, dest_img_dir) elsif partial_match # the image link is split across 2 lines previous_line = line else f_out << line previous_line = nil end end end end FileUtils.mv md_fixed_f_path, md_f_path end def copy_image_to_chapter_subdir(src_img_path, dest_img_dir) FileUtils.mkdir_p("#{dest_img_dir}") begin FileUtils.cp("#{src_img_path}","#{dest_img_dir}") rescue Exception puts "Error: Unable to copy image file." puts $! end end end # =========================================================================== virt_docs_root = "/Users/carl/dev/oplsrc/git_repos/git_openlink_documentation/Documentation/virtuoso-docs-source" # all_docs_xml = virt_docs_root + "/xmlsource/alldocs.xml" all_docs_xml = "./alldocs.xml" output_dir = "./virtdoc_md_conversion" converter = VirtDocConv.new(output_dir, all_docs_xml, virt_docs_root) # Check pandoc is installed begin converter.check_for_pandoc rescue Exception => e puts e exit 1 end converter.create_folder_tree ch_names = converter.chapter_names ch_names.each_index do |ch_indx| ch_name = ch_names[ch_indx] puts "Chapter: " + ch_name puts "Creating abstract..." converter.create_abstract(ch_indx, ch_name) puts "Converting chapter..." converter.convert_chapter(ch_indx, ch_name) puts "Fixing image links..." converter.fix_chapter_image_links(ch_indx, ch_name) end puts "Done!"
true
078fa2a18af20f2ebaa1f3e2f6a2f3f0614b3dce
Ruby
Ksy1993/Ruby
/regexp/metachars.rb
UTF-8
198
2.875
3
[]
no_license
match1 = /Hello\, welcome to our site\./.match('Does Hello, welcome to our site.') puts match1 m2 = /2\*2\+3\-1=\?/.match('Does 2*2+3-1=?') puts m2 m2 = /2*2+3-1=?/.match('Does 2*2+3-1=?') puts m2
true
d5b46f51ed47e6b62daae595a58f2291a307c909
Ruby
Efseykho/6502-emulator
/6502-aslink/tokenizer.rb
UTF-8
3,573
3.71875
4
[]
no_license
#a simple tokenizer interface class Tokenizer attr_accessor :buffer #buffer of tokens attr_accessor :curr_line #current line we're on attr_accessor :temp def initialize( filename ) @buffer = Array.new File.open(filename).each { |line| @buffer.push(line) } #split on white space @buffer.each_index{ |i| if @buffer[i].gsub(" ","").gsub("\n","").size == 0 @buffer[i] = nil else @buffer[i] = @buffer[i].split(" ") end } combine_tokens #initial step @curr_line = -1 @avail = get_next #is there data available to be read @temp = Array.new(@buffer[@curr_line]) if @avail end def has_more? return true if @temp != nil and (@temp.empty? == false) return false if @avail == false ct = @curr_line + 1 while ct < @buffer.size and @buffer[ct] == nil do ct += 1 end return false if ct == @buffer.size return true end def peek return nil if has_more? == false return nil if @temp == nil return @temp[0] if (@temp.empty? == false) #case when array is empty; must load next line into @temp if @temp.empty? get_next @temp = Array.new(@buffer[@curr_line]) if @avail end return @temp[0] end #this will break the line numbers, so dont use it unless you have to #specifically, dont put back last element in line #def put_back(elem) # @temp.unshift(elem) #end #there's a subtelty here #mainly, if next is called and an empty @temp results, this must be ok #we'll load the new line on next call to def next return nil if @temp == nil if @temp.empty? get_next @temp = Array.new(@buffer[@curr_line]) if @avail end return @temp.shift if @avail return nil end #returns rest of current line and attempts to read in next line def get_line return nil if @temp == nil ret = @temp.join(" ") get_next if @avail @temp = Array.new(@buffer[@curr_line]) else @temp = nil end ret end #some assemblers allow looser token syntax #ex: $40,X == $40, X == $40 , X #we'll combine latter 2 forms into former form #we wont deal with case like: $40 ,X - that's just stupid! def combine_tokens #first, get rid of tokens of form ",", they get combined to token to left of them @buffer.each{ |i| #each element is an array next if i == nil i.each_index{ |j| #each element here is a token if i[j] == "," and i[j-1] != nil and i[j+1] != nil i[j-1] = i[j-1] + "," i.delete_at(j) redo end } } #next, combine form "A," , "B" into "A,B" @buffer.each{ |i| #each element is an array next if i == nil i.each_index{ |j| #each element here is a token if i[j].size > 1 and i[j][-1] == 44 and i[j+1] != nil #44 == "," i[j] = i[j] + i[j+1] i.delete_at(j+1) redo end } } end #PRIVATE #this throws out current line and attempts to #load in next non-empty lie #returns true if there exists more to read (in which case @curr_line set to it) #false otherwise def get_next @curr_line += 1 while @curr_line < @buffer.size and @buffer[@curr_line] == nil do @curr_line += 1 end if @curr_line == @buffer.size @avail = false return false end return true end private :get_next end #class Tokenizer
true
f9bd4f03fd9ef9e689469bbb2ca6110d7508ff4c
Ruby
tigershen23/reed
/app/models/domain/book_factory.rb
UTF-8
252
2.65625
3
[]
no_license
module Domain # Factories instantiate domain objects class BookFactory def create(record) Domain::Book.new(record) end def create_for(record, reader) record.reader = reader Domain::Book.new(record) end end end
true
f13de2169b9e00e6cbfea7175b5115de54016e3f
Ruby
cmaher92/launch_school
/coursework/rb100/small_problems/easy_9/double_double.rb
UTF-8
1,743
4.53125
5
[]
no_license
=begin A double number is a number with an even number of digits whose left-side digits are exactly the same as its right-side digits. For example, 44, 3333, 103103, 7676 are all double numbers. 444, 334433, and 107 are not. Write a method that returns 2 times the number provided as an argument, unless the argument is a double number; double numbers should be returned as-is. =end # input # - integer # output # - intger # given a number # if the number is odd, return the number * 2 # if the number is even, check if it's a double number # - turn the number to a string # - retrieve the first half of the number # - half = str / 2 # - string[0, half] # - string[half, half] # - if the first half is equal to the second half, return num, otherwise num * 2 # def twice(num) # num_str = num.to_s # half = num_str.size / 2 # num_str[0, half] == num_str[half..-1] ? num : num * 2 # end # Zac's answer def twice(num) # He's dividing the number by the half-way point # So if it's 999999, he would divmod by 1000 # This would be 999, 999 -> 999999 # This is a great solution left, right = num.divmod(10**(num.digits.size / 2)) left == right ? num : num * 2 end # Examples: p twice(0) == 0 p twice(8) == 16 p twice(37) == 74 p twice(44) == 44 p twice(334433) == 668866 p twice(444) == 888 p twice(107) == 214 p twice(103103) == 103103 p twice(3333) == 3333 p twice(7676) == 7676 p twice(123_456_789_123_456_789) == 123_456_789_123_456_789 p twice(5) == 10 # Note: underscores are used for clarity above. # Ruby lets you use underscores when writing long numbers; # however, it does not print the underscores when printing long numbers. # Don't be alarmed if you don't see the underscores when running your tests.
true
6d08bd4364ce86e2338a364b76732d36f8be3b0f
Ruby
lukasgor/back-end-school
/db/seeds.rb
UTF-8
2,058
2.609375
3
[]
no_license
require 'ffaker' # Admin account User.create(first_name: "Adam", last_name: "Nowak", email: "admin@example.com", password: "password", password_confirmation: "password", account_type: "admin") # Teacher account User.create(first_name: "Jan", last_name: "Kowalski", email: "teacher@example.com", password: "password", password_confirmation: "password", account_type: "teacher") #Student account User.create(first_name: "Janusz", last_name: "Galla", email: "student@example.com", password: "password", password_confirmation: "password", account_type: "student") ## Bunch of students 30.times do User.create(first_name: FFaker::Name.first_name, last_name: FFaker::Name.last_name, email: FFaker::Internet.email, password: "password", password_confirmation: "password", account_type: "student") end ## Bunch of teachers 5.times do User.create(first_name: FFaker::Name.first_name, last_name: FFaker::Name.last_name, email: FFaker::Internet.email, password: "password", password_confirmation: "password", account_type: "teacher") end ## Some groups 5.times do |i| Group.create(name: "1k11#{i}") end ## Some lessons 10.times do |i| Lesson.create(name: "Lesson #{i}") end ## Some messages u = User.second u.send_message(User.third, "Hello, this is just a test message", "Testing") users = User.where(account_type: "student") ## Message to students from teacher u.send_message(users, "I just wanna say hello :)", "Announcement") ## Associations ## Teacher-Lesson, each teacher with one lesson. teachers = User.where(account_type: "teacher") teachers.each do |t| TeacherLesson.create(teacher_id: t.id, lesson_id: rand(1..10)) end ## Group-lesson, each lesson at least one group. 10.times do |i| GroupLesson.create(lesson_id: i, group_id: rand(1..5)) end ## Student-group, each student one group. students = User.where(account_type: "student") students.each do |s| GroupStudent.create(student_id: s.id, group_id: rand(1..5)) end
true
fa410aa9e6f4946556ec8bc5f4a489733409ef4f
Ruby
UbuntuEvangelist/therubyracer
/vendor/bundle/ruby/2.5.0/gems/rubytree-1.0.0/examples/example_basic.rb
UTF-8
2,032
3.40625
3
[ "MIT", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#!/usr/bin/env ruby # # example_basic.rb:: Basic usage of the tree library. # # Author: Anupam Sengupta # Time-stamp: <2015-12-31 22:17:30 anupam> # Copyright (C) 2013, 2015 Anupam Sengupta <anupamsg@gmail.com> # # The following example implements this tree structure: # # +------------+ # | ROOT | # +-----+------+ # +-------------+------------+ # | | # +-------+-------+ +-------+-------+ # | CHILD 1 | | CHILD 2 | # +-------+-------+ +---------------+ # | # | # +-------+-------+ # | GRANDCHILD 1 | # +---------------+ # ..... Example starts. require 'tree' # Load the library # ..... Create the root node first. Note that every node has a name and an optional content payload. root_node = Tree::TreeNode.new('ROOT', 'Root Content') root_node.print_tree # ..... Now insert the child nodes. Note that you can "chain" the child insertions for a given path to any depth. root_node << Tree::TreeNode.new('CHILD1', 'Child1 Content') << Tree::TreeNode.new('GRANDCHILD1', 'GrandChild1 Content') root_node << Tree::TreeNode.new('CHILD2', 'Child2 Content') # ..... Lets print the representation to stdout. This is primarily used for debugging purposes. root_node.print_tree # ..... Lets directly access children and grandchildren of the root. The can be "chained" for a given path to any depth. child1 = root_node['CHILD1'] grand_child1 = root_node['CHILD1']['GRANDCHILD1'] # ..... Now lets retrieve siblings of the current node as an array. siblings_of_child1 = child1.siblings # ..... Lets retrieve immediate children of the root node as an array. children_of_root = root_node.children # ..... Retrieve the parent of a node. parent = child1.parent # ..... This is a depth-first and L-to-R pre-ordered traversal. root_node.each { |node| node.content.reverse } # ..... Lets remove a child node from the root node. root_node.remove!(child1)
true
bda37a58314daa916850dcfd941047371850e1de
Ruby
christinetran825/ttt-with-ai-project-v-000
/lib/board.rb
UTF-8
1,548
4.3125
4
[]
no_license
require 'pry' class Board attr_accessor :cells #has an attribute to store the cells of the board def initialize reset! end def reset! #can reset the state of the cells in the board, @cells = Array.new(9," ") #sets the cells of the board to a 9 element array of " " end def display #prints the board puts " #{@cells[0]} | #{@cells[1]} | #{@cells[2]} " puts "-----------" puts " #{@cells[3]} | #{@cells[4]} | #{@cells[5]} " puts "-----------" puts " #{@cells[6]} | #{@cells[7]} | #{@cells[8]} " end def position(input) #takes in user input and returns the value of the board cell' #binding.pry cells[input.strip.to_i - 1] #why not the below code? #input = gets.strip.to_i #index = input - 1 #cells[index] end def full? #returns true (boolean search) for a full board #returns false for an in-progress game cells.all? { |token| token == "X" || token == "O"} end def turn_count #returns the amount of turns based on cell value cells.count { |token| token == "X" || token == "O"} end def taken?(input) #returns true if the position is X or O, returns false if the position is empty or blank !(position(input) == " " || position(input) == "") end def valid_move?(input) #returns true for user input between 1-9 that is not taken input.to_i.between?(1,9) && !(taken?(input)) end def update(input, player) #updates the cells in the board with the player token according to the input cells[input.strip.to_i - 1] = player.token end end
true
a3c4b166a4c649160028236ecdf872a3f6c81573
Ruby
matthewrpacker/api_curious
/app/models/user_info.rb
UTF-8
430
2.9375
3
[]
no_license
class UserInfo attr_reader :name, :followers, :following, :bio, :member_since, :location def initialize(hash) @name = hash['name'] @followers = hash['followers'] @following = hash['following'] @bio = hash['bio'] @member_since = hash['created_at'] @location = hash['location'] end def member_since date = DateTime.parse(@member_since) formatted_date = date.strftime('%b %d, %Y') end end
true
90a1e6fec1d718d27bdd81d055590e28db4038ca
Ruby
bigfix/erector
/spec/erector/needs_spec.rb
UTF-8
3,516
3.015625
3
[ "MIT" ]
permissive
require File.expand_path("#{File.dirname(__FILE__)}/../spec_helper") describe Erector::Needs do it "doesn't complain if there aren't any needs declared" do class Thing1 < Erector::Widget end Thing1.new end it "allows you to say that you don't want any parameters" do class Thing2 < Erector::Widget needs nil end lambda { Thing2.new }.should_not raise_error lambda { Thing2.new(:foo => 1) }.should raise_error end it "doesn't complain if you pass it a declared parameter" do class Thing2b < Erector::Widget needs :foo end lambda { Thing2b.new(:foo => 1) }.should_not raise_error end it "complains if you pass it an undeclared parameter" do class Thing3 < Erector::Widget needs :foo end lambda { Thing3.new(:bar => 1) }.should raise_error end it "allows multiple declared parameters" do class Thing4 < Erector::Widget needs :foo, :bar end lambda { Thing4.new(:foo => 1, :bar => 2) }.should_not raise_error end it "complains when passing in an extra parameter after declaring many parameters" do class Thing5 < Erector::Widget needs :foo, :bar end lambda { Thing5.new(:foo => 1, :bar => 2, :baz => 3) }.should raise_error end it "complains when you forget to pass in a needed parameter" do class Thing6 < Erector::Widget needs :foo, :bar end lambda { Thing6.new(:foo => 1) }.should raise_error end it "doesn't complain if you omit a parameter with a default value" do class Thing7 < Erector::Widget needs :foo needs :bar => 7 needs :baz => 8 end lambda { thing = Thing7.new(:foo => 1, :baz => 3) thing.instance_variable_get(:@bar).should equal(7) thing.instance_variable_get(:@baz).should equal(3) }.should_not raise_error end it "allows multiple values on a line, including default values at the end of the line" do class Thing8 < Erector::Widget needs :foo, :bar => 7, :baz => 8 end lambda { thing = Thing8.new(:foo => 1, :baz => 2) thing.instance_variable_get(:@foo).should equal(1) thing.instance_variable_get(:@bar).should equal(7) thing.instance_variable_get(:@baz).should equal(2) }.should_not raise_error end it "allows nil to be a default value" do class Thing9 < Erector::Widget needs :foo => nil end lambda { thing = Thing9.new thing.instance_variable_get(:@foo).should be_nil }.should_not raise_error end it "accumulates needs across the inheritance chain even with modules mixed in" do module Something end class Vehicle < Erector::Widget needs :wheels end class Car < Vehicle include Something needs :engine end lambda { Car.new(:engine => 'V-8', :wheels => 4) }.should_not raise_error lambda { Car.new(:engine => 'V-8') }.should raise_error lambda { Car.new(:wheels => 4) }.should raise_error end it "no longer defines accessors for each of the needed variables" do class NeedfulThing < Erector::Widget needs :love end thing = NeedfulThing.new(:love => "all we need") lambda {thing.love}.should raise_error(NoMethodError) end it "no longer complains if you attempt to 'need' a variable whose name overlaps with an existing method" do class ThingWithOverlap < Erector::Widget needs :text end lambda { ThingWithOverlap.new(:text => "alas") }.should_not raise_error(ArgumentError) end end
true
17e7e06cc1cc8e80e4b68e800811a547099e427b
Ruby
towerhe/hightouch
/lib/hightouch/blog.rb
UTF-8
1,433
2.640625
3
[]
no_license
module Hightouch class Blog include Virtus attribute :archive_cache, Hash, default: {} attribute :category_cache, Hash, default: {} attribute :tag_cache, Hash, default: {} attribute :blog_posting_cache, Hash, default: {} attr_reader :app def initialize(app = nil) @app = app end def archives Hash[archive_cache.sort_by { |k, v| v.name }.reverse] end def categories Hash[category_cache.sort_by { |k, v| v.name }] end def tags Hash[tag_cache.sort_by { |k, v| v.name }] end def blog_postings Hash[blog_posting_cache.sort_by { |k, v| v.date_created }.reverse] end def create_archive(type, attrs) send("#{type.name.split(/::/).last.downcase}_cache".to_sym)[attrs[:name]] = type.new(attrs) end def find_archive(type, key) send("#{type.name.split(/::/).last.downcase}_cache".to_sym)[key] end def remove_archive(archive) key = archive.name send("#{archive.class.name.split(/::/).last.downcase}_cache".to_sym).delete(key) end def touch_blog_posting(page) key = page.data.title blog_posting = blog_posting_cache[key] if blog_posting blog_posting.update else blog_posting_cache[key] = BlogPosting.new(page, self) end end def blog_posting(path) blog_posting_cache.values.select { |v| v.url == path }.first end end end
true
9140f32cbc1d0a82ee555ed348d5ff6d61ace547
Ruby
ben-harvey/Small-problems-Ruby
/procedural/easy8/2.rb
UTF-8
614
3.53125
4
[]
no_license
# input: four strings representing a noun, verb, adjective and # adverb # output: a new string inserting input strings into a story # rules: input is provided by user # data structures: string # logic: gets.chomp and store in string # string inpterpolation # def madlibs() parts_of_speech = %w(noun verb adjective adverb) input = {} parts_of_speech.each do |part| puts "Please enter a#{'n' if part[0] == 'a'} #{part}: " response = gets.chomp input[part.to_sym] = response end story = "The #{input[:adjective]} #{input[:noun]} #{input[:verb]}s #{input[:adverb]}" end p madlibs()
true
9a3e13a1739a3b9067168f4f5cc79cd346a44cfa
Ruby
lucidenis/redis-copy
/lib/redis-copy/key-emitter.rb
UTF-8
2,936
2.640625
3
[ "MIT" ]
permissive
# encoding: utf-8 module RedisCopy # A Key emitter emits keys. # This is built to be an abstraction on top of # redis.keys('*') (implemented by RedisCopy::KeyEmitter::Default), # but should allow smarter implementations to be built that can handle # billion-key dbs without blocking on IO. module KeyEmitter def self.load(redis, ui, options = {}) key_emitter = options.fetch(:key_emitter, :default) scan_compatible = Scan::compatible?(redis) emitklass = case key_emitter when :keys then Keys when :scan raise ArgumentError unless scan_compatible Scan when :auto then scan_compatible ? Scan : Keys end emitklass.new(redis, ui, options) end # @param redis [Redis] # @param options [Hash<Symbol:String>] def initialize(redis, ui, options = {}) @redis = redis @ui = ui @options = options end # @return [Enumerable<String>] def keys return super if defined?(super) raise NotImplementedError end def dbsize @redis.dbsize end def to_s self.class.name.demodulize.humanize end # The default strategy blindly uses `redis.keys('*')` class Keys include KeyEmitter def keys dbsize = self.dbsize # HT: http://stackoverflow.com/a/11466770 dbsize_str = dbsize.to_s.reverse.gsub(/(\d{3})(?=\d)/, '\\1,').reverse @ui.abort unless (dbsize < 10_000) || (@ui.confirm? <<-EOWARNING.strip_heredoc) WARNING: #{self} key emitter uses redis.keys('*') to get its list of keys, and you have #{dbsize_str} keys in your source DB. The redis keys command [reference](http://redis.io/commands/keys) says this: > Warning: consider KEYS as a command that should only be used > in production environments with extreme care. It may ruin > performance when it is executed against large databases. > This command is intended for debugging and special operations, > such as changing your keyspace layout. Don't use KEYS in your > regular application code. If you're looking for a way to find > keys in a subset of your keyspace, consider using sets. EOWARNING @ui.debug "REDIS: #{@redis.client.id} KEYS *" @redis.keys('*').to_enum end def self.compatible?(redis) true end end class Scan include KeyEmitter def keys @redis.scan_each(count: 1000) end def self.compatible?(redis) bin_version = Gem::Version.new(redis.info['redis_version']) bin_requirement = Gem::Requirement.new('>= 2.7.105') return false unless bin_requirement.satisfied_by?(bin_version) redis.respond_to?(:scan_each) end end end end
true
01846f8ff139673e7849a49355dec42561b49fd2
Ruby
michalasobczak/q
/01/obsluga.rb
UTF-8
249
3.078125
3
[]
no_license
# 1 # Don't do this begin do_something() rescue Exception => e ... end # 2 begin do_something() rescue => e # This is the same as rescuing StandardError end # 3 begin do_something() rescue Errno::ETIMEDOUT, Errno::ECONNREFUSED => e end
true
0cf0fd1451353862246d19032865dc1173c8d997
Ruby
trbradley/stu-test
/Exercise 2/spec/vehicle_spec.rb
UTF-8
617
2.75
3
[]
no_license
require 'vehicle' describe Vehicle do describe ".move" do let(:driver) { "John Doe" } subject { -> { Vehicle.move(vehicle) } } context "when vehicle is a bicycle" do let(:vehicle) { Bicycle.new(driver) } it { is_expected.to change(vehicle, :distance).by(2) } end context "when vehicle is a motorbike" do let(:vehicle) { Motorbike.new(driver) } it { is_expected.to change(vehicle, :distance).by(4) } end context "when vehicle is a car" do let(:vehicle) { Car.new(driver) } it { is_expected.to change(vehicle, :distance).by(6) } end end end
true
095748ffb340996ab47fc9d0e7d9c9cc8dca7e4f
Ruby
hashmaster3k/backend_module_0_capstone
/day_6/exercises/my_car.rb
UTF-8
943
4
4
[]
no_license
class MyCar attr_accessor :color attr_reader :year def initialize(y, mk, md, c) @year = y @make = mk @model = md @color = c @current_speed = 0 puts "You sit into your #{@color} #{@make} #{@model}.\n\n" end def current_speed puts "Your current speed is #{@current_speed} MPH." end def speed_up(num) @current_speed += num print "You sped up by #{num} MPH. " current_speed end def brake(num) @current_speed -= num print "You slow down by #{num} MPH. " current_speed end def shut_down @current_speed = 0 puts "Stopped and shut off vehicle." end def spray_paint=(color) self.color = color puts "Successfully painted your car #{color}!" end end # create instance object of class MyCar audi = MyCar.new(2005, "Audi", "S4", "blue") puts audi.current_speed puts audi.speed_up(30) puts audi.brake(15) puts audi.shut_down audi.spray_paint = "Gray"
true
1a9d150a614953d142bf05334d3cf627efffaa30
Ruby
Feza786/learn-to-program
/ex9.5.rb
UTF-8
1,053
4.125
4
[]
no_license
#improved ask method def ask question puts question answer = gets.chomp.downcase while answer != 'yes' && answer != 'no' puts 'Please answer "yes" or "no".' puts question answer = gets.chomp.downcase end if answer == 'yes' return true else return false end end puts 'Hello, and thank you for ...' puts ask 'Do you like eating tacos?' ask 'Do you like eating burritos?' wets_bed = ask 'Do you wet the bed?' ask 'Do you like eating chimichangas?' ask 'Do you like eating sopapillas?' puts 'Just a few more questions...' ask 'Do you like drinking horchata?' ask 'Do you like eating flautas?' puts puts 'DEBRIEFING' puts 'Thank you for ...' puts puts wets_bed #old school roman numerals def old_roman_numeral num roman = '' roman = roman + 'M' * (num /1000) roman = roman + 'D' * (num % 1000 / 500) roman = roman + 'C' * (num % 500 / 100) roman = roman + 'L' * (num % 100 / 50) roman = roman + 'X' * (num % 50 / 10) roman = roman + 'V' * (num % 10 / 5) roman = roman + 'I' * (num % 5 / 1) end puts(old_roman_numeral(1999))
true
a00e08484305557b0b4077b9008b8134f8263bfd
Ruby
r0tiart/sinatra-mvc-lab-v-000
/models/piglatinizer.rb
UTF-8
938
4
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class PigLatinizer def piglatinize(word) word_array = word.split("") first_letter = word_array[0] second_letter = word_array[1] third_letter = word_array[2] new_word = "" if vowel?(first_letter.downcase) new_word = word + "way" elsif vowel?(second_letter.downcase) && word.size > 1 other_letters = word_array[2..-1].join new_word = "#{second_letter}#{other_letters}#{first_letter}ay" elsif vowel?(third_letter.downcase) other_letters = word_array[2..-1].join new_word = "#{other_letters}#{first_letter+second_letter}ay" else other_letters = word_array[3..-1].join new_word = "#{other_letters}#{first_letter+second_letter+third_letter}ay" end end def vowel?(letter) if letter.scan(/[aeiou]/).count>0 true else false end end def to_pig_latin(words) words_array = words.split(" ") words_array.collect {|word| piglatinize(word)}.join(" ") end end
true
ee2e49ec3fdd6e0ca3d558f2d3a68d537c5cbd62
Ruby
lkfken/npi_registry
/lib/report.rb
UTF-8
1,155
2.71875
3
[]
no_license
class Report attr_reader :logger def initialize(providers:, taxonomy_data:, primary_only: false, logger: Logger.new($stderr)) @providers = providers @taxonomy_data = taxonomy_data @primary_only = primary_only @logger = logger end def rows @providers.inject(Array.new) do |a, provider| logger.error "#{provider.npi} not found in the NPI Registry!" if provider.not_found? provider.taxonomies.each do |taxonomy| if @primary_only && !taxonomy.primary logger.debug [provider.npi, provider.name, taxonomy.code, taxonomy.desc, classification(taxonomy.code), specialization(taxonomy.code), taxonomy.primary].join(' ') next end a << [provider.npi, provider.type, provider.name, taxonomy.code, taxonomy.desc, classification(taxonomy.code), specialization(taxonomy.code), taxonomy.primary] end a end end def headings %w[NPI TYPE NAME CODE DESC CLASSIFICATION SPECIALIZATION PRIMARY] end private def classification(code) @taxonomy_data[code][:classification] end def specialization(code) @taxonomy_data[code][:specialization] end end
true
b4e27c055628b5e2af2957bdb18b3cfc5d928d36
Ruby
IFilonov/Ruby_basics
/10_lesson/train.rb
UTF-8
2,304
3.328125
3
[]
no_license
require_relative 'manufacturer' require_relative 'instance_counter' require_relative 'validation' require_relative 'accessors' class Train include Manufacturer include InstanceCounter include Validation extend Accessors NUMBER_REGEXP = /^[a-zA-Z0-9]{3}-?[a-zA-Z0-9]{2}$/ attr_reader :wagons attr_accesor_with_history :route strong_attr_accessor :speed, Integer strong_attr_accessor :number, String strong_attr_accessor :type, String validate :type, :presence validate :number, :presence validate :number, :format, NUMBER_REGEXP alias info number @trains = {} ERR_MESSAGES = { ERR_TRAIN_NUM: 'Error: train number not valid!', ERR_TRAIN_TYPE: 'Error: train type cannot be null!' }.freeze def initialize(number, type) @number = number @speed = 0 @type = type @wagons = [] validate! self.class.add_train(self) register_instance end def self.add_train(train) @trains[train.number] = train end def add_wagon(wagon) return unless speed.zero? @wagons << wagon end def unhook_wagon(wagon) @wagons.delete(wagon) if !@wagons.empty? && @speed.zero? end def route(route) @route = route @current_station = 0 current_station.train_arrive(self) end def go_next_station if next_station current_station.send_train(self) @current_station += 1 current_station.train_arrive(self) else puts 'Train is at the final station' end end def go_previous_station if previous_station current_station.send_train(self) @current_station -= 1 current_station.train_arrive(self) else puts 'Train is at the starting station' end end def self.find(number) @trains[number] end def each_wagon @wagons.each { |wagon| yield(wagon) } end private # methods below dont used out of class train def wagons_number @wagons.length end def increase_speed(value) @speed += value end def decrease_speed(value) value < @speed ? @speed -= value : @speed = 0 end def current_station @route.stations[@current_station] end def next_station @route.stations[@current_station + 1] end def previous_station @route.stations[@current_station - 1] if @current_station > 0 end end
true
46fe3a6a3df1c7a337539dc9b5a8a31ac7da1ba0
Ruby
willian/validators
/lib/validators/validates_datetime.rb
UTF-8
2,755
2.609375
3
[ "MIT" ]
permissive
module ActiveModel module Validations class DatetimeValidator < EachValidator def date?(value) value.kind_of?(Date) || value.kind_of?(Time) end def validate_each(record, attribute, value) unless date?(value) record.errors.add(attribute, :invalid_date, :message => options[:message], :value => value ) end if date?(value) validate_after_option(record, attribute, value) validate_before_option(record, attribute, value) end end private def date_for(record, value, option) date = case option when :today Date.today when :now Time.now when Time, Date, DateTime, ActiveSupport::TimeWithZone option when Proc option.call(record) else record.__send__(option) if record.respond_to?(option) end if date.kind_of?(Time) value = value.to_time elsif date.kind_of?(Date) value = value.to_date end [date, value] end def validate_after_option(record, attribute, value) return unless options[:after] date, value = date_for(record, value, options[:after]) record.errors.add(attribute, :invalid_date_after, { :message => options[:after_message], :value => value, :date => (date?(date) ? I18n.l(date) : date.inspect) }) unless value.present? && date.present? && (value && date && value > date) end def validate_before_option(record, attribute, value) return unless options[:before] date, value = date_for(record, value, options[:before]) record.errors.add(attribute, :invalid_date_before, { :message => options[:before_message], :value => value, :date => I18n.l(date) }) unless value.present? && date.present? && (value && date && value < date) end end module ClassMethods # Validates weather or not the specified e-mail address is valid. # # class User < ActiveRecord::Base # validates_datetime :birth # end # # Other usages: # # validates_datetime :starts_at, :after => 2.years.ago # validates_datetime :starts_at, :before => 2.years.ago # validates_datetime :starts_at, :before => :today # validates_datetime :starts_at, :before => :now # validates_datetime :starts_at, :before => :ends_at # validates_datetime :ends_at, :after => :starts_at # def validates_datetime(*attr_names) validates_with DatetimeValidator, _merge_attributes(attr_names) end end end end
true
d3eb39b61ed7f822a05865c2064575acbf13d62c
Ruby
wegowise/polymorpheus
/lib/polymorpheus/mysql_adapter.rb
UTF-8
6,965
2.625
3
[ "MIT" ]
permissive
module Polymorpheus module ConnectionAdapters module MysqlAdapter INSERT = 'INSERT' UPDATE = 'UPDATE' # See the README for more information about the use of these methods. # # table: a string equal to the name of the db table # # columns: a hash, with keys equal to the column names in the table we # are operating on, and values indicating the foreign key # association through the form "table.column". # # For example: # # { # 'employee_id' => 'employees.ssn', # 'product_id' => 'products.id' # } # # This indicates that the `employee_id` column in `table` # should have a foreign key constraint connecting it to the # `ssn` column in the `employees` table, and the `product_id` # column should have a foreign key constraint with the `id` # column in the `products` table. # # options: a hash, accepting the following options # # :unique # # If the columns hash was specified as above, and :unique is true: # # { :unique => true } # # Then this creates a uniqueness constraint in the database that # will ensure that any given employee_id can only be in the table # once, and that any given product_id can only be in the table # once. # # Alternatively, you can supply a column name or array of column # names to the :unique option: # # { :unique => 'picture_url' } # # This will allow an employee_id (or product_id) to appear multiple # times in the table, but no two employee IDs would be able to have # the same picture_url. # # :on_delete # # Action that happens ON DELETE. Valid values are :nullify, # :cascade and :restrict. # # :on_update # # Action that happens ON UPDATE. Valid values are :nullify, # :cascade and :restrict. def add_polymorphic_constraints(table, columns, options={}) column_names = columns.keys.sort add_polymorphic_triggers(table, column_names) options.symbolize_keys! if options[:unique].present? poly_create_indexes(table, column_names, Array(options[:unique])) end column_names.each do |col_name| ref_table, ref_col = columns[col_name].to_s.split('.') fk_options = { :column => col_name, :name => "#{table}_#{col_name}_fk", :primary_key => (ref_col || 'id' ) }.merge(generate_constraints(options)) add_foreign_key(table, ref_table, **fk_options) end end def remove_polymorphic_constraints(table, columns, options = {}) poly_drop_triggers(table, columns.keys.sort) columns.each do |(col, reference)| remove_foreign_key table, :column => col, :name => "#{table}_#{col}_fk" end if options[:unique].present? poly_remove_indexes(table, columns.keys, Array(options[:unique])) end end def triggers execute("show triggers").collect {|t| Polymorpheus::Trigger.new(t) } end # # DO NOT USE THIS METHOD DIRECTLY # # it will not create the foreign key relationships you want. the only # reason it is here is because it is used by the schema dumper, since # the schema dump will contains separate statements for foreign keys, # and we don't want to duplicate those def add_polymorphic_triggers(table, column_names) column_names.sort! poly_drop_triggers(table, column_names) poly_create_triggers(table, column_names) end ########################################################################## private def poly_trigger_name(table, action, columns) prefix = "pfk#{action.first}_#{table}_".downcase generate_name prefix, columns.sort end def poly_drop_trigger(table, action, columns) trigger_name = poly_trigger_name(table, action, columns) execute %{DROP TRIGGER IF EXISTS #{trigger_name}} end def poly_create_trigger(table, action, columns) trigger_name = poly_trigger_name(table, action, columns) colchecks = columns.collect { |col| "IF(NEW.#{col} IS NULL, 0, 1)" }. join(' + ') sql = %{ CREATE TRIGGER #{trigger_name} BEFORE #{action} ON #{table} FOR EACH ROW BEGIN IF(#{colchecks}) <> 1 THEN SET NEW = 'Error'; END IF; END} execute sql end def poly_drop_triggers(table, columns) poly_drop_trigger(table, 'INSERT', columns) poly_drop_trigger(table, 'UPDATE', columns) end def poly_create_triggers(table, columns) poly_create_trigger(table, 'INSERT', columns) poly_create_trigger(table, 'UPDATE', columns) end def poly_create_index(table, column, unique_cols) if unique_cols == [true] unique_cols = [column] else unique_cols = [column] + unique_cols end name = poly_index_name(table, unique_cols) execute %{ CREATE UNIQUE INDEX #{name} ON #{table} (#{unique_cols.join(', ')}) } end def poly_remove_index(table, column, unique_cols) if unique_cols == [true] unique_cols = [column] else unique_cols = [column] + unique_cols end name = poly_index_name(table, unique_cols) execute %{ DROP INDEX #{name} ON #{table} } end def poly_index_name(table, columns) prefix = "pfk_#{table}_" generate_name prefix, columns end def poly_create_indexes(table, columns, unique_cols) columns.each do |column| poly_create_index(table, column, unique_cols) end end def poly_remove_indexes(table, columns, unique_cols) columns.each do |column| poly_remove_index(table, column, unique_cols) end end def generate_name(prefix, columns) # names can be at most 64 characters long col_length = (64 - prefix.length) / columns.length prefix + columns.map { |c| c.to_s.gsub('_','').first(col_length-1) }.join('_') end def generate_constraints(options) options.slice(:on_delete, :on_update) end end end end [:MysqlAdapter, :Mysql2Adapter].each do |adapter| begin ActiveRecord::ConnectionAdapters.const_get(adapter).class_eval do include Polymorpheus::ConnectionAdapters::MysqlAdapter end rescue end end
true
a352e4c491bab34bc21701e2bccec01e9e9b9c9b
Ruby
BFriedland/ruby-web-test-examples
/utils.rb
UTF-8
2,700
3.078125
3
[ "MIT" ]
permissive
require 'inifile' module SeleniumUtilities # Reference for mixins, including reasoning on include vs. extend: # http://stackoverflow.com/a/549273 # Example use: # record_video_toggle = # find_subelements_with_text("tag_name", "label", "Record Video") def find_subelements_with_text(findable_type, findable_name, text) # Note that @driver means this utility depends on # being a mixin for a class that has a driver attribute. elements = @driver.find_elements findable_type.to_sym, findable_name found_elements = [] elements.each do |each_subelement| if each_subelement.text == text found_elements << each_subelement end end if found_elements.length == 1 return found_elements[0] elsif found_elements.length == 0 return [] end end # This method is not used by the tests, # but it did help with creating them. # Example use: # find_elements_and_print_text("class", "hljs-ruby") def find_elements_and_print_text(findable_attribute, findable_name) elements = @driver.find_elements findable_attribute.to_sym, findable_name elements.each do |each_subelement| puts "#{each_subelement.text}" end end end module IniFileUtilities # inifile source and docs: # https://github.com/TwP/inifile def load_and_flatten_ini_file loaded_ini_file = IniFile.load('./configuration.ini') # Remove unnecessary section titles, store in class attribute: @ini_file = Hash.new loaded_ini_file.each do |section| loaded_ini_file[section].each do |each_key_value_pair| key = each_key_value_pair[0] value = each_key_value_pair[1] @ini_file[key] = value end end generate_implied_data end # After the file is loaded, we should add a few pieces # of data that the configuration file is not required # to contain (because these data are necessarily # implied by what is required). def generate_implied_data if @ini_file['device'].downcase == "pc" or @ini_file['device'].downcase == "mac" then @ini_file['device_category'] = "Desktop" elsif @ini_file['device'].downcase.include? "iphone" or @ini_file['device'].downcase.include? "ipad" then @ini_file['device_category'] = "iOS" else # Noncompliant ini input is # going to be "Android" today. @ini_file['device_category'] = "Android" end end end
true
218846dab09d0e32b9a0d09b570d2efba2c81deb
Ruby
shraker13/LS_IntroBook_Ruby
/chptr10Exercises/exercise8.rb
UTF-8
150
2.953125
3
[]
no_license
#Exercise 10.8 measurements = { :weight => '180 pounds', :height => '6 feet'} puts measurements desc = { color: 'red', shape: 'triangle' } puts desc
true
41677e4a88458fd9c2608ecb25014f277ea81515
Ruby
steven989/CRM_commandline
/classnotes/rolodex.rb
UTF-8
493
3.078125
3
[]
no_license
class Rolodex def initialize @contacts = [] end def create_contact(name) contact = Contact.new contact.name = name @contacts << contact end def view_contacts @contacts.each {|contact| puts contact; puts "------------"} end def remove_contact(id) @contacts.delete_if {|contact| contact.id == id} end def edit_contact(id,name) @contacts.each {|contact| if contact.id == id contact.name = name end } end end
true
567d8054caacc75339e2df058c6c4769c67878ac
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/src/3294.rb
UTF-8
165
2.859375
3
[]
no_license
def compute(lhs, rhs) throw ArgumentError.new("Arguments of inequal length.") if lhs.length != rhs.length lhs.length.times.count {|i| lhs[i] != rhs[i]} end
true
8d2e6976fac7ff13c6f30c08cf58f54cffa01de4
Ruby
caridadrivera/sinatra-dynamic-routes-lab-nyc-web-career-031119
/app.rb
UTF-8
594
2.96875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require_relative 'config/environment' class App < Sinatra::Base get '/reversename/:name' do @reversed_name = params[:name].reverse "#{@reversed_name}" end get '/square/:number' do @squared_num = params[:number].to_i * params[:number].to_i "#{@squared_num}" end get '/say/:word1/:word2/:word3/:word4/:word5' do @words = params[:word1].to_s + params[:word2].to_s + params[:word3].to_s + params[:word4].to_s + params[:word5].to_s " #{@words}" end get '/:operation/:number1/:number2' do @operation = params[:number1](+, -, *, /) params[:number2] "#{@operation}" end end
true
167554e4450ed844a11342d056550af44517a4ef
Ruby
Sindarus/tsumegomaker
/app/controllers/test_minimax.rb
UTF-8
263
2.671875
3
[]
no_license
load("board.rb") load("minimax.rb") b = Board.new(2,3,[false,false,false,false]) b.load_board("111\n000") m = Minimax.new(b,8) max_score, win_nodes = m.launch_minimax puts "Max score is : #{max_score}" win_nodes.each do |wn| m.show_path_to wn end m.show_tree
true
12d40344d01a6aa4fb8b6060b2752765a7f2820f
Ruby
andrelaszlo/photogun
/lib/email_whitelist.rb
UTF-8
513
2.796875
3
[]
no_license
module EmailWhitelist def self.whitelisted?(email, whitelist: nil) if whitelist.nil? whitelist = Rails.application.secrets.email_whitelist || '' end if whitelist.empty? puts "EMAIL_WHITELIST is empty" return false end patterns = self.parse_whitelist whitelist !!patterns.match(email) end private def self.parse_whitelist(whitelist) regexps = whitelist.split(';').map do |pattern| Regexp.new pattern end Regexp::union regexps end end
true
0cc129b361f432d8e75f2bcc00628a8b340206a4
Ruby
jwhitis/AudioFile
/test/test_colorize.rb
UTF-8
269
2.546875
3
[ "MIT" ]
permissive
require "test_helper" include Colorize class ColorizeUnitTest < Test::Unit::TestCase def test_01_colorize_returns_color_coded_text text = "Some green text." expected = "\e[32mSome green text.\e[0m" assert_equal(expected, text.colorize(GREEN)) end end
true
96eaed28cde4c0d3b9c3dd60b89eb43d8a663f31
Ruby
gabdelaun/dotfiles
/car.rb
UTF-8
614
3.578125
4
[]
no_license
class car # attr_reader : color # getters # def color # return @color # end # attr_writer : color #setters # def color=(new_color) # @color = new_color # end attr_accessor: color # = Attr_reader & attr_writer def initialize(color) @engine_started = false @color = color @kms = 0 end def move @kms += 10 end def kilometers return @kms end def engine_started? return @engine_started end def start_the_engine start_petrol_pump @engine_started = true end private def start_petrol_pump puts "the petrol pump has been started" end end
true
935c93e838700e79ae13939fcde41d366b894dab
Ruby
shirwet/programming-univbasics-4-intro-to-hashes-lab-dc-web-030920
/intro_to_ruby_hashes_lab.rb
UTF-8
1,006
3.609375
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def new_hash # return an empty hash new_hash = {} end def my_hash # return a valid hash with any key/value pair of your choice my_hash = { name: "Shirwet", age: 31 } end def pioneer # return a hash with a key of :name and a corresponding value of 'Grace Hopper' hash = { :name => "Grace Hopper" } end def id_generator # return a hash with a key :id assigned to positive integer hash_2 = {:id => 3} end def my_hash_creator(key, value) # return a hash that includes the key and value parameters passed into this method hash_3 = { key=>value } end def read_from_hash(hash, key) # return the correct value using the hash and key parameters hash[key] end def update_counting_hash(hash, key) # given a hash an a key as parameters, return an updated hash # if the provided key is not present in the hash, add it and assign it to the value of 1 # if the provided key is present, increment its value by 1 if hash[key] hash[key]+=1 else hash[key] = 1 end return hash end
true
7b7efc6dde822808487c8f6ecc8cca6b96b2b778
Ruby
BogdanGermanchuk/rubytut
/lesson7/ex4.rb
UTF-8
1,164
4.125
4
[]
no_license
array = [] index = 1 while index <= 9 do array << index index += 1 end puts 'Исходный массив: ' puts array.to_s puts 'Новый массив, полученный из исходного массива: ' puts "#{array.unshift(9)}\n\n" # encoding: utf-8 # Записываем массив в переменную numbers и выводим его на экран numbers = [1, 2, 3, 4, 5, 6, 7] puts 'Исходный массив:' puts numbers.to_s # Создадим новый массив (пока пустой), куда будем класть элементы исходного в # обратном порядке reverse_numbers = [] # Проходим в цикле по исходному массиву numbers for item in numbers do # И добавляем каждый элемент в начало нового массива методом unshift (добавить # в начало) reverse_numbers.unshift(item) end # Осталось вывести полученный массив на экран puts 'Новый массив, полученный из исходного:' puts reverse_numbers.to_s
true
433080b45d5457e03c5d186a95f60b1de05275c4
Ruby
pivotalexperimental/bookmark_fu
/lib/bookmark_fu/configuration.rb
UTF-8
1,016
2.703125
3
[ "MIT" ]
permissive
module BookmarkFu class << self def services Configuration.services end end class Configuration class << self def instance @instance ||= new end attr_writer :instance def all_services @all_services ||= [] end def to_yaml all_services.collect {|service| service.to_s.split("::").last}.to_yaml end def method_missing(method_name, *args, &block) self.instance.__send__(method_name, *args, &block) end end def initialize refresh! end def configuration_file @configuration_file ||= "#{RAILS_ROOT}/config/bookmark_fu.yml" end attr_writer :configuration_file attr_accessor :services def refresh! if File.exists?(configuration_file.to_s) service_names = YAML.load_file(configuration_file) @services = service_names.collect {|name| BookmarkFu.const_get(name)} else @services = self.class.all_services end end end end
true
296ee22cbca5edb790bdcb2609ee48baa518df47
Ruby
viperior/cloud-golem
/start-instance.rb
UTF-8
1,649
2.734375
3
[]
no_license
puts "Cloud Golem EC2 Instance Start Script Started..." require 'aws-sdk-ec2' # v2: require 'aws-sdk' require_relative 'ec2-credentials.rb' client = Aws::EC2::Client.new( access_key_id: cloud_golem_ec2_access_key_id, secret_access_key: cloud_golem_ec2_secret_access_key, region: 'us-east-1' ) ec2 = Aws::EC2::Resource.new( client: client ) i = ec2.instance(cloud_golem_ec2_instance_id) if i.exists? case i.state.code when 0 # pending puts "#{cloud_golem_ec2_instance_id} is pending, so it will be running in a bit" when 16 # started puts "#{cloud_golem_ec2_instance_id} is already started" when 48 # terminated puts "#{cloud_golem_ec2_instance_id} is terminated, so you cannot start it" else puts "Starting instance with ID #{cloud_golem_ec2_instance_id}. Current state code: #{i.state.code}" i.start puts "Instance starting..." end end c = 60 60.times { if (c % 10 == 0) puts "#{c} seconds elapsed" end c -= 1 sleep 1 } if i.exists? case i.state.code when 0 # pending puts "There was a problem starting instance ID #{cloud_golem_ec2_instance_id}..." puts "#{cloud_golem_ec2_instance_id} is still pending" when 16 # started puts "#{cloud_golem_ec2_instance_id} has been successfully started" when 48 # terminated puts "There was a problem starting instance ID #{cloud_golem_ec2_instance_id}..." puts "#{cloud_golem_ec2_instance_id} is terminated" else puts "There was an unknown problem (state code: #{i.state.code}) starting instance ID #{cloud_golem_ec2_instance_id}..." end end puts "Cloud Golem EC2 Instance Start Script Terminated..."
true
621fc9d89b32ed28ab5df40931fd67a88741b495
Ruby
mtcameron5/RB101_Programming_Foundations_Exercises
/medium_2/exercise_1.rb
UTF-8
2,611
3.546875
4
[]
no_license
# Write a program that reads the content of a text file # and then prints the longest sentence in the file based # on number of words. Sentences may end with periods (.), # exclamation points (!), or question marks (?). Any # sequence of characters that are not spaces or # sentence-ending characters should be treated as a # word. You should also print the number of words in the longest sentence. def get_longest_sentence(file=nil) if file file_data = File.read(file) words = file_data.split() else string = "Four score and seven years ago our fathers brought forth on this continent a new nation, conceived in liberty, and dedicated to the proposition that all men are created equal. Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived and so dedicated, can long endure. We are met on a great battlefield of that war. We have come to dedicate a portion of that field, as a final resting place for those who here gave their lives that that nation might live. It is altogether fitting and proper that we should do this. But, in a larger sense, we can not dedicate, we can not consecrate, we can not hallow this ground. The brave men, living and dead, who struggled here, have consecrated it, far above our poor power to add or detract. The world will little note, nor long remember what we say here, but it can never forget what they did here. It is for us the living, rather, to be dedicated here to the unfinished work which they who fought here have thus far so nobly advanced. It is rather for us to be here dedicated to the great task remaining before us -- that from these honored dead we take increased devotion to that cause for which they gave the last full measure of devotion -- that we here highly resolve that these dead shall not have died in vain -- that this nation, under God, shall have a new birth of freedom -- and that government of the people, by the people, for the people, shall not perish from the earth." words = string.split end sentence = [] longest_sentence = [] length_of_sentence = 0 words.each do |word| length_of_sentence += 1 sentence << word if word.include?('.') || word.include?('?') || word.include?('!') if length_of_sentence > longest_sentence.size longest_sentence = sentence end sentence = [] length_of_sentence = 0 end end p longest_sentence return longest_sentence.size end p get_longest_sentence("pg84_gutenberg.txt")
true
50760f07f096ba0d32dea984091ed556add6beb5
Ruby
codeloopy/appacademy
/Soft_eng_foundations/RSPEC/rspec_exercise_1/lib/part_1.rb
UTF-8
391
3.96875
4
[]
no_license
def average(num1, num2) (num1 + num2) / 2.0 end def average_array(arr) arr_sum = arr.inject { |a,n| a + n } arr_sum / (arr.length * 1.0) end def repeat(str, num) str * num end def yell(str) "#{str.upcase}!" end def alternating_case(str) words = str.upcase.split(' ') i = 1 while i < words.length words[i] = words[i].downcase i += 2 end str = words.join(' ') str end
true
5eac4d17b036653096ce57e32a26019f154b25f1
Ruby
mattijsvandruenen/smite_ruby
/lib/smite/full_match.rb
UTF-8
1,001
2.78125
3
[]
no_license
module Smite class FullMatch < Smite::Object attr_accessor :queue, :match def initialize(data) data = { 'competitors' => data.map { |k, v| Smite::Competitor.new(k) } } super @queue = competitors[0].queue @match = competitors[0].match end def teams { team1: team1, team2: team2 } end def parties competitors.group_by(&:party_id) end def players competitors end def size competitors.count end def ranked? queue =~ /Ranked/ end def size_str "#{size/2} v #{size/2}" end def team1 competitors[0...size/2] end def team2 competitors[size/2..-1] end def winning_team return @winner unless @winner.nil? @winner = teams.find do |team, competitors| competitors.all? { |competitor| competitor.winner? } end @winner = @winner[0] end def inspect "#<Smite::FullMatch #{match} #{queue}>" end end end
true
30d53e3711892be14b2a2bb741ff2f731a01af01
Ruby
T-o-s-s-h-y/Learning
/Ruby/exercises/app/mission_c_093.rb
UTF-8
1,008
3.828125
4
[]
no_license
=begin ボブとアリスがテストの点数で勝負をし、どちらが勝ったか、あるいは引き分けたかを求める。 ただし、テストの点数をそのまま比較するのではなく、テストの点数の各桁の数を足した数の一の位で勝負する。 例えば、85点であれば 8 + 5 = 13、13の一の位である3が勝負する際の点となる。 =end class MissionC093 def run # 各人のスコア(ボブの点数 アリスの点数) scores = $stdin.gets.split # それぞれの最終的に使用する点 bob_score = 0 alice_score = 0 # 各桁の数を足す scores[0].length.times { |num| bob_score += scores[0][num, 1].to_i } scores[1].length.times { |num| alice_score += scores[1][num, 1].to_i } # 勝者を求める if (bob_score % 10) > (alice_score % 10) puts 'Bob' elsif (alice_score % 10) > (bob_score % 10) puts 'Alice' else puts 'Draw' end end end
true
0b9eb4b6586b5ff530d3236e05fa675419cebec6
Ruby
EJWebber/yield-and-blocks-london-web-060319
/lib/hello.rb
UTF-8
170
3.328125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def hello_t(array) if block_given? i=0 while i<array.length yield (array[i]) i+=1 end array else puts "Hey! No block was given!" end end # call your method here!
true
2b06e1572ec03e513112282f1e124de622506f11
Ruby
gwhn/clean_cv
/app/controllers/skills_controller.rb
UTF-8
3,961
2.578125
3
[]
no_license
class SkillsController < ApplicationController before_filter :load_person before_filter :load_skill, :only => [:show, :edit, :update, :delete, :destroy, :move_top, :move_up, :move_down, :move_bottom] before_filter :new_skill, :only => [:new, :create, :index] filter_access_to :all, :attribute_check => true filter_access_to [:reposition, :move_top, :move_up, :move_down, :move_bottom], :require => :update # GET /people/1/skills # GET /people/1/skills.xml def index @skills = @person.skills respond_to do |format| format.html # index.html.haml format.xml { render :xml => @skills } end end # GET /people/1/skills/1 # GET /people/1/skills/1.xml def show respond_to do |format| format.html # show.html.haml format.xml { render :xml => @skill } end end # GET /people/1/skills/new # GET /people/1/skills/new.xml def new respond_to do |format| format.html # new.html.haml format.xml { render :xml => @skill } end end # GET /people/1/skills/1/edit def edit end # POST /people/1/skills # POST /people/1/skills.xml def create respond_to do |format| if @skill.save flash[:notice] = "#{@skill.name} was successfully created." format.html { redirect_to @person } format.xml { render :xml => @skill, :status => :created, :location => @skill } format.js { render :layout => false } else format.html { render :action => :new } format.xml { render :xml => @skill.errors, :status => :unprocessable_entity } format.js { render :action => :invalid, :layout => false } end end end # PUT /people/1/skills/1 # PUT /people/1/skills/1.xml def update respond_to do |format| if @skill.update_attributes(params[:skill]) flash[:notice] = "#{@skill.name} was successfully updated." format.html { redirect_to @person } format.xml { head :ok } format.js { @skill.reload and render :layout => false } else format.html { render :action => :edit } format.xml { render :xml => @skill.errors, :status => :unprocessable_entity } format.js { render :action => :invalid, :layout => false } end end end # GET /people/1/skills/1/delete def delete respond_to do |format| format.html # delete.html.haml end end # DELETE /people/1/skills/1 # DELETE /people/1/skills/1.xml def destroy redirect_to @person and return if params[:cancel] flash[:notice] = "#{@skill.name} was successfully deleted." if @skill.destroy respond_to do |format| format.html { redirect_to @person } format.xml { head :ok } format.js end end # PUT /people/1/skills/reposition def reposition @person.skills.each do |skill| skill.position = params[:skill].index(skill.id.to_s) + 1 skill.save end render :nothing => true end # GET /people/1/skill/1/move_top def move_top @skill.move_to_top @skill.save respond_to do |format| format.html { redirect_to(@person) } format.xml { head :ok } end end # GET /people/1/skill/1/move_up def move_up @skill.move_higher @skill.save respond_to do |format| format.html { redirect_to(@person) } format.xml { head :ok } end end # GET /people/1/skill/1/move_down def move_down @skill.move_lower @skill.save respond_to do |format| format.html { redirect_to(@person) } format.xml { head :ok } end end # GET /people/1/skill/1/move_bottom def move_bottom @skill.move_to_bottom @skill.save respond_to do |format| format.html { redirect_to(@person) } format.xml { head :ok } end end protected def load_skill @skill = @person.skills.find params[:id] end def new_skill @skill = @person.skills.new params[:skill] end end
true
dbf585dd835e828cbc01f47e48ba98b02dfce39c
Ruby
usarekoski/mastermind
/codemaker.rb
UTF-8
1,479
3.25
3
[]
no_license
class AiCodemaker attr_reader :code def initialize @code = (0..5).to_a.shuffle.take(4) end def give_feedback(guess_numbers) col_and_pos = guess_numbers .zip(@code) .map { |x| x[1] == x[0] } guess_left = feedback_help(guess_numbers, col_and_pos) code_left = feedback_help(@code, col_and_pos) only_col = guess_left.select do |x| if code_left.member?(x) code_left.delete_at(code_left.index(x) || code_left.length) true else false end end return [col_and_pos.select { |x| x }.size, only_col.size] end private def feedback_help(numbers, filter) filter.zip(numbers).select { |x| x[0] == false }.map { |x| x[1] } end end class HumanCodemaker < AiCodemaker require_relative 'graphics' include Graphics def initialize @code = select_code end def select_code colors = [] puts `clear` puts "Now select your secret code. It must be 4 colors (can be same colors):".colorize(:white) puts "Give one number at a time, numbers represent following colors:" puts colors_to_s until colors.size > 3 begin print "Color #{colors.size + 1}:" color = Kernel.gets.chomp.match(/\d+/)[0].to_i if color < 1 || color > 6 raise "wrong size" end rescue puts "Not a valid number. Try again." else colors.push(color - 1) end end colors end end
true
f19ab6b813e7c23479da21f65271c6091f805b8c
Ruby
brabemi/ctu-fit-mi-rub16
/hw2/grid.rb
UTF-8
4,161
3.625
4
[]
no_license
#!/usr/bin/env ruby # Contains sudoku game board class Grid include Enumerable attr_reader :dimension, :block_width # Create Sudoku game grid of given dimension def initialize(dimension) @dimension = dimension @block_width = Math.sqrt(@dimension).to_i @grid = [] @dimension.times do row = [] @dimension.times { row.push(Cell.new(0, @dimension)) } @grid.push(row) end end # Return string with game board in a console friendly format def to_s(width = 3) separator = '' @dimension.times do |c| separator << '+' if c%width == 0 and c>0 separator << '---' end separator << "\n" output = '' @dimension.times do |r| output << separator if r%width == 0 line = '' @dimension.times do |c| line << '|' if c%width == 0 and c>0 line << ' ' << (@grid[r][c].filled? ? @grid[r][c].value.to_s : ' ') << ' ' end output << line << "\n" end output << separator output end # First element in the sudoku grid def first @grid.first.first end # Last element in the sudoku grid def last @grid.last.last end # Return value at given position def value(x, y) @grid[x][y].value end # Marks number +z+ which shouldn't be at position [x, y] def exclude(x, y, z) @grid[x][y].exclude(z) end # True when there is already a number def filled?(x, y) @grid[x][y].filled? end # True when no game was loaded def empty? @grid[x][y] end # Yields elements in given row def row_elems(x) return @grid[x].each unless block_given? @grid[x].each { |item| yield item } end # Yields elements in given column def col_elems(y) return @grid.collect { |row| row[y] }.each unless block_given? @grid.each { |row| yield row[y] } end # Yields elements from block which is # containing element at given position def block_elems(x, y) row_start = x - x%@block_width col_start = y - y%@block_width for row in @grid[row_start..row_start+(@block_width-1)] do row[col_start..col_start+(@block_width-1)].each { |e| yield e } end end # With one argument return row, with 2, element # at given position def [](*args) return @grid[args[0]].map(&:to_i) if args.size == 1 @grid[args[0]][args[1]].to_i end # With one argument sets row, with 2 element def []=(*args) @dimension.times { |i| @grid[args[0]][i].value = args[1][i] } if args.size == 2 @grid[args[0]][args[1]].value = args[2] if args.size == 3 end # Return number of missing numbers in grid def missing missing = 0 each { |e| missing+=1 if e.filled? == false } missing end # Number of filled cells def filled filled = 0 each { |e| filled+=1 if e.filled? } filled end # Number of rows in this sudoku def rows @dimension end # Number of columns in this sudoku def cols @dimension end # Iterates over all elements, left to right, top to bottom def each return @grid.flatten.each unless block_given? @grid.each { |row| row.each { |cell| yield cell } } end # Iterates over all elements, left to right, top to bottom def block(id) row = id / @block_width col = id % @block_width rs = row * @block_width cs = col * @block_width my_block = @grid[rs..rs+(@block_width-1)].collect { |row| row[cs..cs+(@block_width-1)] } return my_block.flatten.each unless block_given? my_block.flatten.each { |cell| yield cell } end # false no duplicit value (1..dimension) in elements def check_duplicity(elements) counter = Array.new(@dimension+1, 0) elements.each { |e| counter[e.value]+=1} counter[0] = 0 counter.detect { |e| e>1 } != nil end # Return true if no filled number break sudoku rules def valid? @dimension.times { |i| return false if check_duplicity(row_elems(i)) } @dimension.times { |i| return false if check_duplicity(col_elems(i)) } @dimension.times { |i| return false if check_duplicity(block(i)) } true end # Serialize grid values to a one line string def solution each.map(&:to_i).join() end end
true
a651f2c9b4e49650c8219ae6cc65611f05ced7ab
Ruby
hgeorgii/hangman
/lib/hangman_methods.rb
UTF-8
3,185
3.625
4
[]
no_license
module HangmanMethods def select_difficulty puts 'Select difficulty:' puts 'easy ----- 7 guesses' puts 'medium ----- 6 guesses' puts 'hard ----- 5 guesses' input = gets.chomp.downcase message = "You selected #{input}." case input when 'easy' puts message puts 7 when 'medium' puts message puts 6 when 'hard' puts message puts 5 else puts "I don't understand, selected medium as default" puts 6 end end def generate_word word = '' word = File.readlines('dictionary.txt').sample.gsub(/\s+/, '') until word.size > 4 && word.size < 13 word.downcase.split('') # TODO: Clean this up 'test'.split('') end def display_game system('clear') puts '################################################################' puts puts "You have #{remaining_guesses} guesses left" puts p word_to_display(secret_word, correct_guesses) puts puts "Wrong guesses: #{incorrect_guesses}" puts puts '################################################################' puts end def word_to_display(word, correct_guesses) coded_word = word.map { '_' } correct_guesses.each do |guess| word.each_with_index do |correct_char, index| if guess == correct_char coded_word[index] = guess end end end coded_word end def get_input input = '' until input.size == 1 && input.match(/[a-z]/) puts "Please input a single unselected character from \'a\' to \'z\' or input \'save\' to save the game:" puts input = gets.chomp.downcase if input == 'save' input = '' save_game puts 'Game saved.' puts elsif all_guesses.include?(input) input = '' puts 'You already chose that one. Try again.' puts else puts "You chose \"#{input}\"" puts end end input end def all_guesses correct_guesses + incorrect_guesses end def change_state(input) if secret_word.include?(input) correct_guesses << input puts "#{input} was correct." puts else incorrect_guesses << input remove_remaining_guess puts "#{input} was incorrect." puts end end def save_game game_attributes = { word: current_game.word, remaining_guesses: current_game.remaining_guesses, correct_guesses: current_game.correct_guesses, incorrect_guesses: current_game.incorrect_guesses } File.open('saves/saved_game.json', 'w') { |f| f.puts game_attributes.to_json } end def game_over?(game) if game.remaining_guesses.zero? true else word_to_display(game.word, game.correct_guesses).include?('_') == false end end private def correct_guesses current_game.correct_guesses end def remaining_guesses current_game.remaining_guesses end def incorrect_guesses current_game.incorrect_guesses end def secret_word current_game.word end def remove_remaining_guess current_game.remove_remaining_guess end end
true
0058dfeb8da186cefae2b57d096edd740857d964
Ruby
nix12/chess
/spec/board/setup_display_spec.rb
UTF-8
5,548
2.71875
3
[]
no_license
require 'board/setup_display' RSpec.describe SetupDisplay do describe 'setup of display with pieces' do let(:gameboard) { Board.new } let(:setup) { SetupDisplay.new(gameboard) } before { gameboard.build_display } describe '#setup_display' do it "calls gameboard's build_board method" do allow(gameboard).to receive(:build_board) setup.setup_display end it 'calls build_white_side method' do allow(setup).to receive(:build_white_side) setup.setup_display end it 'calls build_white_side method' do allow(setup).to receive(:build_black_side) setup.setup_display end end describe '#build_white_side' do it 'calls method to place white knights' do allow(setup).to receive(:create_white_knights) setup.build_white_side end it 'calls method to place white rooks' do allow(setup).to receive(:create_white_rooks) setup.build_white_side end it 'calls method to place white bishops' do allow(setup).to receive(:create_white_rooks) setup.build_white_side end it 'calls method to place white queen' do allow(setup).to receive(:create_white_queen) setup.build_white_side end it 'calls method to place white king' do allow(setup).to receive(:create_white_king) setup.build_white_side end it 'calls method to place white pawn' do allow(setup).to receive(:create_white_pawns) setup.build_white_side end end describe '#create_white_knights' do it 'places the white knights on the board' do setup.create_white_knights expect(gameboard.display[0][1]).to eq(setup.white_knight.icon) expect(gameboard.display[0][6]).to eq(setup.white_knight.icon) end end describe '#create_white_rooks' do it 'places the white rooks on the board' do setup.create_white_rooks expect(gameboard.display[0][0]).to eq(setup.white_rook.icon) expect(gameboard.display[0][7]).to eq(setup.white_rook.icon) end end describe '#create_white_bishops' do it 'places the white bishops on the board' do setup.create_white_bishops expect(gameboard.display[0][2]).to eq(setup.white_bishop.icon) expect(gameboard.display[0][5]).to eq(setup.white_bishop.icon) end end describe '#create_white_queen' do it 'places the white queen on the board' do setup.create_white_queen expect(gameboard.display[0][3]).to eq(setup.white_queen.icon) end end describe '#create_white_king' do it 'places the white king on the board' do setup.create_white_king expect(gameboard.display[0][4]).to eq(setup.white_king.icon) end end describe '#create_white_pawns' do it 'places the white pawns on the board' do setup.create_white_pawns 8.times do |space| expect(gameboard.display[1][space]).to eq(setup.white_pawn.icon) end end end describe '#build_white_side' do it 'calls method to place black knights' do allow(setup).to receive(:create_black_knights) setup.build_black_side end it 'calls method to place black rooks' do allow(setup).to receive(:create_black_rooks) setup.build_black_side end it 'calls method to place black bishops' do allow(setup).to receive(:create_black_rooks) setup.build_black_side end it 'calls method to place black queen' do allow(setup).to receive(:create_black_queen) setup.build_black_side end it 'calls method to place black king' do allow(setup).to receive(:create_black_king) setup.build_black_side end it 'calls method to place black pawn' do allow(setup).to receive(:create_black_pawns) setup.build_black_side end end describe '#create_black_knights' do it 'places the black knights on the board' do setup.create_black_knights expect(gameboard.display[7][1]).to eq(setup.black_knight.icon) expect(gameboard.display[7][6]).to eq(setup.black_knight.icon) end end describe '#create_black_rooks' do it 'places the black rooks on the board' do setup.create_black_rooks expect(gameboard.display[7][0]).to eq(setup.black_rook.icon) expect(gameboard.display[7][7]).to eq(setup.black_rook.icon) end end describe '#create_black_bishops' do it 'places the black bishops on the board' do setup.create_black_bishops expect(gameboard.display[7][2]).to eq(setup.black_bishop.icon) expect(gameboard.display[7][5]).to eq(setup.black_bishop.icon) end end describe '#create_black_queen' do it 'places the black queen on the board' do setup.create_black_queen expect(gameboard.display[7][3]).to eq(setup.black_queen.icon) end end describe '#create_black_king' do it 'places the black king on the board' do setup.create_black_king expect(gameboard.display[7][4]).to eq(setup.black_king.icon) end end describe '#create_black_pawns' do it 'places the black pawns on the board' do setup.create_black_pawns 8.times do |space| expect(gameboard.display[6][space]).to eq(setup.black_pawn.icon) end end end end end
true
4a28969c8088c0fea048bc0cb832d096601d44af
Ruby
MOSapeizer/SOS-Cache-Server
/lib/tasks/SOS/lib/employees/sos/time.rb
UTF-8
1,056
2.921875
3
[]
no_license
require_relative '../gml/gmlTime.rb' module SOSHelper class SOSTime def initialize(time) @time = checkTimeType time end def timeInstant(time) time.xpath(".//gml:TimeInstant") end def timePeriod(time) time.xpath(".//gml:TimePeriod") end def range(beginTime=beginPosition, endTime=endPosition) beginTime.toTimeZone + " " + endTime.toTimeZone end def timePosition @instant ||= gmlTime find("gml:timePosition") end def beginPosition @begin ||= gmlTime find("gml:beginPosition") end def endPosition @end ||= gmlTime find("gml:endPosition") end def gmlTime(time) GMLTime.new time unless time.empty? end def find(tag) @time.xpath(".//" + tag).text end def checkTimeType(time) type = timeInstant time type = timePeriod time if type.empty? end def inspect time = timePosition.nil? ? "@begin: #{beginPosition}, @end: #{endPosition}" : "@intant: #{@instant}" "PhenomenonTime: #{time}" end end class PhenomenonTime < SOSTime end class ResultTime < SOSTime end end
true
500a9c7cecf08f2e1aff7e8d46937dc353eee49c
Ruby
Kaiwee/Kwly_Bitly_Clone
/app/models/url.rb
UTF-8
396
2.53125
3
[ "MIT" ]
permissive
class Url < ActiveRecord::Base # This is Sinatra! Remember to create a migration! before_create :shorten, :counter validates :long_url, presence: true, uniqueness: true, format: { with: /https?:\/\/[\S]+/} def shorten range = [*'0'..'9',*'A'..'Z',*'a'..'z'] @short_url = (0...7).map{ range.sample }.join self.short_url = @short_url end def counter self.click_count = 0 end end
true
c9bf93da7ca98cacf792a50a3a73bbf82c101bc7
Ruby
ivaverka/Learn-Ruby-the-Hard-Way
/arrays.rb
UTF-8
371
4.15625
4
[]
no_license
#Ex 1 =begin array = [1, 3, 5, 7, 9, 11] number = 3 =end =begin array.each do |x| if x == number puts "#{number} is in the array." end end =end # OR =begin if array.include?(number) puts "#{number} is in the array." end =end # Ex3 arr = [["test", "hello", "world"],["example", "mem"]] =begin arr.flatten word = arr.flatten puts word[3] =end puts arr.last.first
true
e3382a2e3596d71fcd7870562802a83ab64808d2
Ruby
chrisd1dev/my-first-repository
/TeaLeaf_Exercises/Hashes/hashes_ex7.rb
UTF-8
157
2.671875
3
[]
no_license
#Hashes exercise 7 x = "hi there" my_hash = {x: "some value"} my_hash2 = {x => "some value"} puts x puts my_hash puts my_hash2
true
502e0e40c3b8467bb4d0041b5ee32b7c164d3b65
Ruby
nettan20/qae
/app/models/reports/admin_report_builder.rb
UTF-8
2,735
2.65625
3
[ "MIT" ]
permissive
require "csv" class Reports::AdminReportBuilder MAPPING = [ { label: "URN", method: :urn }, { label: "ApplicantName" }, { label: "RegisteredUserId", method: :user_id }, { label: "RegisteredUserTitle", method: :title }, { label: "RegisteredUserFirstname", method: :first_name }, { label: "RegisteredUserSurname", method: :last_name }, { label: "RegisteredUserEmail", method: :head_email }, { label: "RegisteredUserCompany", method: :company_name }, { label: "RegisteredUserAddressLine1", method: :address_line1 }, { label: "RegisteredUserAddressLine2", method: :address_line2 }, { label: "RegisteredUserAddressLine3", method: :address_line3 }, { label: "RegisteredUserPostcode", method: :postcode }, { label: "RegisteredUserTelephone1", method: :telephone1 }, { label: "RegisteredUserTelephone2", method: :telephone2 }, { label: "RegisteredUserMobile" }, { label: "FormType", method: :award_type }, { label: "PercentageComplete", method: :percentage_complete }, { label: "Section 1", method: :section1 }, { label: "Section 2", method: :section2 }, { label: "Section 3", method: :section3 }, { label: "Section 4", method: :section4 }, { label: "Section 5", method: :section5 }, { label: "Section 6", method: :section6 }, { label: "Created", method: :created_at }, { label: "UserCreationDate", method: :user_creation_date }, { label: "BusinessSector", method: :business_sector }, { label: "BusinessSectorOther", method: :business_sector_other }, { label: "Region" }, { label: "Employees" }, { label: "QAOPermission", method: :qao_permission }, { label: "HowDidYouHearAboutQA", method: :qae_info_source }, { label: "HowDidYouHearAboutQAOther", method: :qae_info_source_other } ] def initialize @scope = ::FormAnswer.all.includes(:user) end def build csv_string = CSV.generate do |csv| csv << headers @scope.each do |form_answer| form_answer = Reports::FormAnswer.new(form_answer) csv << MAPPING.map do |m| form_answer.call_method(m[:method]) end end end csv_string end private def headers MAPPING.map { |m| m[:label] } end end
true
d95bd26db05cf8a3f7b0fa63300518f525b4fcd3
Ruby
eremeyev/thinknetika-course
/ruby_basics/task_3/lib/train.rb
UTF-8
3,116
3.125
3
[]
no_license
require_relative 'base' class Train < Base attr_accessor :speed, :route, :current_station, :wagons, :number, :type attr_writer :current_position validates :number, presence: true, format: /[\w\d]{3}[-|]?[\w]{2}/i, uniqueness: true validates :type, presence: true, inclusion: Types::ALL def initialize(number) @number = number @wagons = [] @speed = 0 validate! register_instance end def each_wagon @wagons.each { |wagon| yield(wagon) } end def increase_speed(num) self.speed += num self end def stop self.speed = 0 self end def add_wagon(wagon) return Train.wagon_already_added if @wagons.include?(wagon) return Train.wagon_has_incompatible_type unless type == wagon.type return Train.speed_is_not_zero unless speed.zero? @wagons << wagon self end def remove_wagon(wagon_number) return Train.speed_is_not_zero unless speed.zero? wagon = wagons.detect { |w| w.number == wagon_number } return Train.wagon_not_in_list unless wagons.include?(wagon) wagons.delete(wagon) self end def accept(route) @route = route @current_station = route.stations.first @current_position = 0 @route.stations.first.receive_train(self) self end def go_forward res = can_go_forward? return res if res.is_a?(String) current_station.dispatch_train(self) next_station.receive_train(self) @current_station = next_station @current_position = route.stations.index(current_station) self end def can_go_forward? return Train.there_is_no_route + Train.add_route unless route return Train.at_last_station unless next_station return Train.speed_is_zero if speed.zero? true end def go_backward return Train.there_is_no_route + Train.add_route unless route return Train.at_first_station unless previous_station return Train.speed_is_zero if speed.zero? @current_station = previous_station self end def get_station(position) return Train.there_is_no_route + Train.add_route unless route return next_station || Train.no_next_station if position == 'next' return previous_station || Train.no_previous_station if position == 'previous' current_station end def info "Поезд ##{number}: Тип: #{type} Маршрут: #{route ? route.info : 'Пока не задан.'} Текущая станция: #{current_station_info} Вагоны(#{wagons.size}): #{wagons_info}" end def wagons_info return 'Вагонов нет. Только локомотив.' if wagons.empty? wagons.map(&:info).join("\n\t") end def current_station_info current_station ? current_station.info : 'Пока не задана.' end def previous_station return if current_position.zero? route.stations[current_position - 1] end def next_station return if current_position == route.stations.size - 1 route.stations[current_position + 1] end def current_position route.stations.index(current_station) end end
true
ce55c213b7a8915834ac14a56a4859b7e215dae5
Ruby
preetness/phase-0-tracks
/ruby/gps2_2.rb
UTF-8
1,548
4.46875
4
[]
no_license
# Method to create a list # input: string of items separated by spaces (example: "carrots apples cereal pizza") # steps: Take some words, and convert it into a grocery shopping list. # [fill in any steps here] # set default quantity to one # print the list to the console [can you use one of your other methods here?] # output: a hash of grocery list items def create_list(items) list = {} items.split(' ').each { |item| add_item(list, item) } list end # Method to add an item to a list # input: list, item name, and optional quantity # steps: Add items to the list, using the name and quantity # output: An item that we add to the list def add_item(list, item, quantity = 1) list[item] = quantity list end # Method to remove an item from the list # input: # steps: # output: An updated hash without the item removed def remove_from_list(list, item) list.delete_if {|key, value| key == item} list end # Method to update the quantity of an item # input: # steps: # output: An updated hash with the new quantity def update_quantity(list, item, quantity) add_item(list, item, quantity) list end # Method to print a list and make it look pretty # input: # steps: # output: A "prettier" grocery list def print_list(list) list.each do |key, value| puts "#{key}: #{value}" end end list = create_list("carrots apples cereal pizza") #print_list(list) add_item(list, 'squash', 5) add_item(list, 'oranges', 7) #print_list(list) remove_from_list(list, 'squash') update_quantity(list,'carrots', 10) print_list(list)
true
d27f93e35dd947f606568824327660e446d13e0c
Ruby
kirel/armchair
/lib/armchair.rb
UTF-8
2,332
2.96875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require 'rest_client' require 'json' # An Armchair is <em>very</em> a minimal interface to a CouchDB database. It is Enumarable. class Armchair include Enumerable # Pass in the database url and optionally # a <tt>batch_size</tt> which is used when iterating over the armchair in Armchair#each # couch = Armchair.new 'http://127.0.0.1:5984/mycouch' # def initialize dburl, batch_size = 100 @dburl = dburl.gsub(/\/$/,'') @batch_size = batch_size end # Create the CouchDB database at <tt>dburl</tt> (see Armchair#new) if it does not exist yet def create! RestClient.get @dburl, :accept => :json do |response| case response.code when 404 RestClient.put @dburl, nil, :content_type => :json, :accept => :json else response.return! end end end # Shift a document into the Armchair. <tt>doc</tt> should be a Hash. # armchair << { 'a' => 'document' } << { 'another' => 'document' } def << doc RestClient.post @dburl, JSON(doc), :content_type => :json, :accept => :json do |response| response.return! unless response.code == 201 end self end # Returns the size of the Armchair (the number of documents stored). def size RestClient.get(@dburl + '/_all_docs?limit=0', :accept => :json) do |r| case r.code when 200 JSON(r.body)['total_rows'] else r.return! end end end # yields each document def each # iterate in batches of @batch_size # initial query res = RestClient.get(@dburl + "/_all_docs?limit=#{@batch_size+1}&include_docs=true", :accept => :json) do |r| case r.code when 200 JSON(r.body) else r.return! end end rows = res['rows'] last = rows.size > @batch_size ? rows.pop : nil rows.each { |row| doc = row['doc']; yield doc } # subsequent queries while last startkey = last['key'] res = RestClient.get(@dburl + "/_all_docs?startkey=%22#{startkey}%22&limit=#{@batch_size+1}&include_docs=true", :accept => :json) do |r| case r.code when 200 JSON(r.body) else r.return! end end rows = res['rows'] last = rows.size > @batch_size ? rows.pop : nil rows.each { |row| yield row['doc'] } end end end
true
02c4150724139a398d986d16239e43b5ce54ce2e
Ruby
firetimli/Viking
/rubybasic/Fibonacci.rb
UTF-8
288
3.59375
4
[]
no_license
def fibonacci range value1 = 2 value2 = 3 sum = 0 while value2 < range value1 = value1 + value2 value2 = value2 + value1 if value1%2 == 0 sum = sum + value1 elsif value2%2 == 0 sum = sum + value2 end end sum+2 end puts"#{fibonacci 4000000}"
true