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
202a77a1e7bb92c576eb8bf3bcd730409486dc8f
Ruby
WarHatch/Mastermind-ruby
/lib/game.rb
UTF-8
4,086
3.5625
4
[]
no_license
require_relative 'AI' # Component for Board class class BreakAttempt < MastermindObject attr_accessor :break_attempt attr_reader :feedback, :feedback_count def initialize @break_attempt = Array.new(PEG_SPACES) @feedback = Array.new(PEG_SPACES) @feedback_count = 0 end def add_feedback_peg(feedback_type) @feedback[@feedback_count] = feedback_type @feedback_count += 1 end end # Mastermind game board components and game sequence class Board < MastermindObject attr_reader :turns_passed, :guesses def initialize(computer_generated) @guesses = Array.new(TURNS) { BreakAttempt.new } @answer = Array.new(PEG_SPACES) @turns_passed = 0 @ai = AI.new computer_generated ? generate_code : input_code puts "answer: #{@answer.to_s}" puts 'START GUESSING' end def generate_code PEG_SPACES.times do |i| @answer[i - 1] = random_color end end def input_code(input = nil) if input.nil? puts "Codemaker, write #{PEG_SPACES} numbers from 0 to #{COLORS.length} separated by space. 0 represents an empty spot 1-6 represent colors" input = gets end input = input.split(' ') unless input.length == PEG_SPACES puts 'Incorrect input, try again' input = input_code end @answer = input end def computer_guess guess = Array.new(@ai.guess) puts @answer.to_s if guess.eql? @answer @turns_passed += 1 return true else evaluate_guess(guess) @ai.collect_results(@guesses[@turns_passed].feedback) @turns_passed += 1 puts 'TRY AGAIN' if @turns_passed != TURNS end false end def player_guess print 'guess: ' guess = gets.chomp.split(' ') # player guess is converted to array @guesses[@turns_passed].break_attempt = guess puts @guesses[@turns_passed].break_attempt.to_s puts @answer.to_s if guess.eql? @answer @turns_passed += 1 return true else evaluate_guess(guess) @turns_passed += 1 puts 'TRY AGAIN' if @turns_passed != TURNS end false end def evaluate_guess(guess) correctly_guessed = feedback_position(guess) # puts "Position feedback:\n#{@guesses[@turns_passed].feedback}" # puts "The guess after 'pulling out' the correct pegs:\n#{guess.to_s}" feedback_colors(guess, correctly_guessed) puts "Feedback:\n#{@guesses[@turns_passed].feedback}" @guesses[@turns_passed].feedback end # Adds CORRECT_POSITION pegs and returns positions that were guessed correctly def feedback_position(guess) correct_positions = Array.new(PEG_SPACES) guess.each.with_index do |peg, slot| if peg.eql? @answer[slot] @guesses[@turns_passed].add_feedback_peg CORRECT_POSITION guess[slot] = EMPTY correct_positions[slot] = CORRECT_POSITION end end correct_positions end def remove_correctly_guessed_pegs(correctly_guessed) remaining_answer = Array.new(@answer) answer_offset = 0 for index in [email protected] - 1 if correctly_guessed[index] == CORRECT_POSITION remaining_answer.delete_at(index - answer_offset) answer_offset += 1 end # puts "partial remaining answer: #{remaining_answer.to_s}" end remaining_answer end def feedback_colors(guess, correctly_guessed) # puts "remaining_guess: #{guess}" remaining_answer = remove_correctly_guessed_pegs(correctly_guessed) # puts "remaining_answer: #{remaining_answer}" remaining_answer.each do |answer_peg| if index = guess.index(answer_peg) guess[index] = EMPTY @guesses[@turns_passed].add_feedback_peg CORRECT_COLOR end end end def play(player_braker) braker_won = false until braker_won || @turns_passed >= TURNS braker_won = player_braker ? player_guess : computer_guess end if braker_won puts 'Code braker won!' else puts 'Code maker won!' end braker_won end end # puts '* * * M a s t e r m i n d * * *' # game = Board.new(false) # game.play(true)
true
01de4020241292e6af6a6d27b8944582eaf2b0b8
Ruby
ysawa/sengine
/lib/sbot/board.rb
UTF-8
10,449
3.015625
3
[]
no_license
# -*- coding: utf-8 -*- module SBot class Board SIZE = 111 # board sized with 111 pieces attr_accessor :board attr_accessor :number # hands of sente and gote attr_accessor :sente_hand attr_accessor :gote_hand # kikis of sente and gote attr_accessor :sente_kikis attr_accessor :gote_kikis # pins of sente and gote attr_accessor :sente_pins attr_accessor :gote_pins attr_accessor :sente_ou attr_accessor :gote_ou def cancel(move) to_point = move.to_point role = move.role sente = move.sente if move.put? if sente > 0 @sente_hand[role] += 1 else @gote_hand[role] += 1 end @board[to_point] = Piece::NONE replace_kikis_of_inexistent_piece(sente, role, to_point) else from_point = move.from_point if move.sente > 0 @board[from_point] = role @sente_ou = from_point if role == Piece::OU if move.reverse to_role = role + 8 else to_role = role end to_role_abs = to_role else @board[from_point] = - role @gote_ou = from_point if role == Piece::OU if move.reverse to_role = - role - 8 else to_role = - role end to_role_abs = - to_role end replace_kikis_of_inexistent_piece(sente, to_role_abs, to_point) to_piece = take_role = move.take_role if to_piece && to_piece != 0 replace_kikis_of_existent_piece(- sente, take_role, to_point) if to_piece >= 9 to_piece -= 8 end if sente > 0 @board[to_point] = - take_role @sente_hand[to_piece] -= 1 @gote_ou = to_point if to_piece == Piece::OU else @board[to_point] = take_role @gote_hand[to_piece] -= 1 @sente_ou = to_point if to_piece == Piece::OU end else @board[to_point] = Piece::NONE end replace_kikis_of_existent_piece(sente, role, from_point) end @number -= 1 if @sente_ou && @gote_ou load_pins end end def clear_board SIZE.times do |point| if out_of_board?(point) @board[point] = Piece::WALL else @board[point] = Piece::NONE end end end def execute(move) to_point = move.to_point role = move.role sente = move.sente if move.put? @board[to_point] = move.role if sente > 0 @sente_hand[role] -= 1 else @gote_hand[role] -= 1 end replace_kikis_of_existent_piece(sente, role, to_point) else from_point = move.from_point # take piece on to_point to_piece = @board[to_point].abs if to_piece && to_piece != 0 replace_kikis_of_inexistent_piece(- sente, to_piece, to_point) if to_piece >= 9 to_piece -= 8 end if sente > 0 @sente_hand[to_piece] += 1 @gote_ou = nil if to_piece == Piece::OU else @gote_hand[to_piece] += 1 @sente_ou = nil if to_piece == Piece::OU end end @board[to_point] = 0 @board[from_point] = Piece::NONE replace_kikis_of_inexistent_piece(sente, role, from_point) if sente > 0 if move.reverse to_role = role + 8 else to_role = role end @sente_ou = to_point if role == Piece::OU to_role_abs = to_role else if move.reverse to_role = - role - 8 else to_role = - role end to_role_abs = - to_role @gote_ou = to_point if role == Piece::OU end @board[to_point] = to_role replace_kikis_of_existent_piece(sente, to_role_abs, to_point) end @number += 1 if @sente_ou && @gote_ou load_pins end end def get_piece(point) value = @board[point] if value != 0 Piece.new(value) end end def initialize(board = nil, number = 0) @number = number @board = Array.new(SIZE) y_offset = 0 10.times do |i| point = i @board[point] = Piece::WALL point = 101 + i @board[point] = Piece::WALL y_offset += 10 point = y_offset @board[point] = Piece::WALL end @sente_hand = [nil, 0, 0, 0, 0, 0, 0, 0, 0] @gote_hand = [nil, 0, 0, 0, 0, 0, 0, 0, 0] end def load_all load_ous if @sente_ou && @gote_ou load_kikis load_pins end end def load_kikis @sente_kikis = Kikis.new @gote_kikis = Kikis.new 11.upto(99).each do |from_point| piece = @board[from_point] next if piece == Piece::WALL || piece == Piece::NONE if piece > 0 piece_sente = 1 moves = Piece::SENTE_MOVES[piece] jumps = Piece::SENTE_JUMPS[piece] else piece_sente = -1 moves = Piece::GOTE_MOVES[- piece] jumps = Piece::GOTE_JUMPS[- piece] end moves.each do |move| to_point = from_point + move next if out_of_board?(to_point) if piece_sente > 0 @sente_kikis.append_move(to_point, - move) else @gote_kikis.append_move(to_point, - move) end end jumps.each do |jump| to_point = from_point 1.upto(8).each do |i| to_point += jump break if out_of_board?(to_point) if piece_sente > 0 @sente_kikis.append_jump(to_point, - jump) else @gote_kikis.append_jump(to_point, - jump) end piece = @board[to_point] break if piece != Piece::NONE end end end end def load_ous @sente_ou = @gote_ou = nil 11.upto(99).each do |point| piece = @board[point] next if piece == Piece::WALL || piece == Piece::NONE if piece == Piece::OU @sente_ou = point elsif piece == - Piece::OU @gote_ou = point end break if @sente_ou && @gote_ou end nil end def load_pins @sente_pins = Array.new(SIZE) @gote_pins = Array.new(SIZE) Piece::JUMP_DIRECTIONS.each do |move| point = @sente_ou 1.upto(8).each do point += move piece = @board[point] break if piece == Piece::WALL next if piece == Piece::NONE if piece > 0 && @gote_kikis.get_jump_kikis(point).include?(move) @sente_pins[point] = move end break end point = @gote_ou 1.upto(8).each do point += move piece = @board[point] break if piece == Piece::WALL next if piece == Piece::NONE if piece < 0 && @sente_kikis.get_jump_kikis(point).include?(move) @gote_pins[point] = move end break end end nil end def out_of_board?(point) self.class.out_of_board?(point) end def replace_kikis_of_existent_piece(sente, role, point) if sente > 0 proponent_kikis = @sente_kikis opponent_kikis = @gote_kikis moves = Piece::SENTE_MOVES[role] jumps = Piece::SENTE_JUMPS[role] else proponent_kikis = @gote_kikis opponent_kikis = @sente_kikis moves = Piece::GOTE_MOVES[role] jumps = Piece::GOTE_JUMPS[role] end # remove opponent kikis opponent_kikis.get_jump_kikis(point).each do |kiki| to_point = point 8.times do to_point -= kiki piece = @board[to_point] break if piece == Piece::WALL opponent_kikis.remove_jump(to_point, kiki) break if piece != Piece::NONE end end # append proponent kikis moves.each do |move| to_point = point + move piece = @board[to_point] next if piece == Piece::WALL proponent_kikis.append_move(to_point, - move) end jumps.each do |jump| to_point = point 8.times do to_point += jump piece = @board[to_point] break if piece == Piece::WALL proponent_kikis.append_jump(to_point, - jump) break if piece != Piece::NONE end end end def replace_kikis_of_inexistent_piece(sente, role, point) if sente > 0 proponent_kikis = @sente_kikis opponent_kikis = @gote_kikis moves = Piece::SENTE_MOVES[role] jumps = Piece::SENTE_JUMPS[role] else proponent_kikis = @gote_kikis opponent_kikis = @sente_kikis moves = Piece::GOTE_MOVES[role] jumps = Piece::GOTE_JUMPS[role] end # erase proponent kikis moves.each do |move| to_point = point + move piece = @board[to_point] next if piece == Piece::WALL proponent_kikis.remove_move(to_point, - move) end jumps.each do |jump| to_point = point 8.times do to_point += jump piece = @board[to_point] break if piece == Piece::WALL proponent_kikis.remove_jump(to_point, - jump) break if piece != Piece::NONE end end # append opponent kikis opponent_kikis.get_jump_kikis(point).each do |kiki| to_point = point 8.times do to_point -= kiki piece = @board[to_point] break if piece == Piece::WALL opponent_kikis.append_jump(to_point, kiki) break if piece != Piece::NONE end end end def to_str lines = [] lines << 'G: ' + @gote_hand.join(' ') 1.upto(9).each do |y| pieces = [] 9.downto(1).each do |x| point = y * 10 + x value = @board[point] pieces << ("%3d" % value) pieces.join(' ') end lines << pieces.join end lines << 'S: ' + @sente_hand.join(' ') lines.join("\n") end class << self def out_of_board?(point) point % 10 == 0 || point <= 10 || point >= 100 end end end end
true
643c0254bd0ad284fccbcd7f79a46871d7874c5b
Ruby
IlitaKu/ruby-intro-to-arrays-lab-london-web-082619
/lib/intro_to_arrays.rb
UTF-8
373
3.203125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def instantiate_new_array new = [] end def array_with_two_elements new = [1,2] end def first_element(new) new.first end def third_element (new) new[2] end def last_element(new) new[-1] end def first_element_with_array_methods(new) new.first end def last_element_with_array_methods(new) new.last end def length_of_array(new) new.length end
true
90100d74ec329da0ab732df0728bbddc09b4e576
Ruby
kevincai79/phase-0-tracks
/ruby/secret_agents.rb
UTF-8
3,102
4.40625
4
[]
no_license
# OUR ENCRYPT AND DECRYPT METHODS FOR SECRET AGENTS # Input the text # Split the text into single character, # and replace it with a letter forward # combine the new characters as a new string def encrypt(text) i = 0 new_text = "" # Declare an empty string to take the replace character new_string = "" # Declare an empty string we will add to while i < text.length # Set loop times if text[i] == " " || text[i] == "z" if text[i] == " " # Add conditional logic for " " case new_text = " " else new_text = "a" # Add conditional logic for edge case end else new_text = text[i].next # Replace the character with one letter forward end new_string += new_text # Add up the characters to the new string i += 1 end new_string # To avoid debugging and return value of nil end puts encrypt("abc") # Test method and print the result puts encrypt("zed") # Input the text # Split the text into single character, # and replace it with a letter backward # combine the new characters as a new string def is_letter_space(text) alphabet = "abcdefghijklmnopqrstuvwxyz " text_array = [] text.chars.each do |char| if alphabet.index(char) == nil text_array << false else text_array << true end end if !text_array.include?(false) return true end end def decrypt(text) if is_letter_space(text) n = 0 # Declare alphabet string to index letters alphabet = "abcdefghijklmnopqrstuvwxyz" new_text = "" # Declare an empty string to take the replace character new_string = "" # Declare an empty string we will add to while n < text.length # Set loop times if text[n] == " " # Add conditional logic for " " case new_text = " " else # Use alphabet to replace current character with one letter backward new_text = alphabet[alphabet.index(text[n])-1] end new_string += new_text # Add up the characters to the new string n += 1 end new_string # To avoid debugging and return value of nil else "Invalid input, letters and spaces only." end end puts decrypt("bcd") # Test method and print the result puts decrypt("afe") puts decrypt("a*7e") puts decrypt(encrypt("swordfish")) =begin Above code first calls the method encrypt("swordfish") and return encrypt value, then the value as the parameter of the encrypt method and return the encrypt value. =end # Ask a secrect agent what he/she wants to do puts "Would you like to decrypt or encrypt a password (decrypt/encrypt)?" # Prompt for secrect agent's request request = gets.chomp # Ask a secrect agent's password puts "Please enter your password (letters and space only):" # Prompt for secrect agent's password password = gets.chomp.downcase # Conduct the requested operation and print the result # to the screen if request == "decrypt" puts "#{password} decrypt password is: #{decrypt(password)}" else puts "#{password} encrypt password is: #{encrypt(password)}" end # Exit and say bye to the secrect agent puts "Bye!"
true
ef1d5b662bfdba0838f983f364bf37a60e3becff
Ruby
katsuya245126/App-Academy-Projects
/Finished/previous_exercises/Tic-tac-toe/tic_tac_toe_v3/computer_player.rb
UTF-8
213
3.453125
3
[]
no_license
class ComputerPlayer def initialize(mark) @mark = mark end def mark @mark end def get_position(legal_positions) pos = legal_positions.sample puts "BOT chooses #{pos}!" pos end end
true
ebba586e84e5929874cc6483a892aefc98745d05
Ruby
Holy87/rpgvxace
/universal_module.rb
UTF-8
44,702
2.890625
3
[]
no_license
$imported = {} if $imported == nil $imported["H87_UniversalModule"] = 1.6 =begin ============================================================================== ■ Holy87's Universal Module version 1.6.2 - EN User difficulty: ★★★ License: CC-BY. Everyone can distribute this script and use in their free and commercial games. Credit required. ■ This module helps to expand to new levels your scripts and games, allowing you to create unique features unthinkable before, in the simplies possible method. What you can do with this script? ● Saving universal variables that not depend on the savegame ● Obtain system information, like screen resolution, system language, Windows version, user name, documents folder path etc.. ● Download a file and/or obtain response from a web server in the easiest way ● Obtain and set game version information ● Coding and decoding strings in Base64 or ROT13 ● And other features! ============================================================================== ■ Compatibility DataManager -> alias load_normal_database, load_battle_test_database Scene_Base -> alias update Window_Base -> alias update ============================================================================== ■ Installation Install this script under Materials, above Main and all scripts that use the Universal Module ============================================================================== ■ Istructions Use those methods from script calls or inside your scripts: when you see square brackets [] it means that that parameter is optional. ▼ Universal variables The $game_settings global variable saves and stores in game_settings.rvdata2 file (in the gmae folder) a value that not depends on the savegame. You can use this script to save settings in the title screen or unlock an extra option when the player ends the game. Substantially, the Game_Settings class is an hash, so you can use a key to store and load a value. For example: ● $game_settings[key] = value Saves the value with the key. The data is automatically stored when you assign a value, but sometimes you need to manually update the file when for example the value is an object and you may chang a property in that object. So use $game_settings.save to force save. ● $game_settings[key] returns the value provided by key The data is autmatical ● You can set up the game version by creating a file in the project's folder with "version.ini" name, and write inside the version value like 1.0.2.5. You can call the game version with the $game_system.game_version method call. Ex. version = $game_system.game_version print version.major => 1 print version.minor => 0 print version.build => 2 print version.revision => 5 print version => 1.0.2.5 print version > "1.0.1.7" => false vers2 = Version.new("2.0") print version < vers2 => true ▼ System calls ● Win.version: returns a float with the Windows kernel version. 5.0 -> Windows 2000 5.1 -> Windows Xp 5.2 -> Windows Xp (64 bit) 6.0 -> Windows Vista 6.1 -> Windows 7 6.2 -> Windows 8 6.3 -> Windows 8.1 10.0-> Windows 10 ● Win.username Returns a string with the actual user name of Windows account. I.E. print Win.username => "Francesco" ● Win.homepath Returns the user path. I.E.: C:/Users/username/ from Windows Vista C:/Documents and Settings/username in Windows 2000 and Xp ● Win.getFolderPath([symbol]) Returns a folder path defined by symbol: :docs -> My Documents folder :imgs -> My Pictures folder :dskt -> Desktop folder :musc -> Music folder :vdeo -> Movies folder :prog -> Program Files folder (C:\Program Files (x86)) * if a symbol is not defined, it means :docs Example: print Win.getFolderPath(:dskt) => "C:/Users/Francesco/Desktop" ● Win.shutdown[(mode)] Shuts down the PC, settings by mode (0 for default): 0: normal shutdown 1: reset 2: hybernate ● Win.open(filepath) Opens a folder or a file. Specify the path in filepath Win.open(C:/Windows/system32/calc.exe) opens calculator Win.open(Win.getFolderPath(:imgs)) it will open the Images folder ● Win.temp_flush(nomefile) Deletes the temporary data of the file name (if downloaded more times) This method is not used anymore. ● Win.language Returns a int code with the system language in use. For the complete code list, see this link below: http://support.microsoft.com/kb/193080 ● Win.screen_resolution returns an array with two integers containing the screen resolution (es. [1024,730]). You may know that this method doesn't return the full resolution, but only the screen part not covered by the taskbar. ● Screen.resize(width, height) Change the game screen size. This method NOT changes the game resolution, only makes the screen bigger. ▼ String methods ● println like print, but adds automatically \n at the end of the string ● String.random([lenght]) Returns a random string. If lenght is not defined, then the string is 4 Examples: print String.random #=> ajpf print String.random(7) #=> opetnpg ● crypt_rot13 Crypts a string in ROT13 format (moves all characters by 13 steps in the alphabet). Recall this method on the same string to decode print "Casa".crypt_rot13 #=> "Pnfn" print "Pnfn".crypt_rot13 #=> "Casa" ● Base64.encode(string) and Base64.decode(string) Returns a string coded in Base64 for interchange of web data Per other info: wikipedia.org/wiki/Base64 ▼ Internet and HTTP ---------------------------------------------------------------------------- * Simplified method for sync operations ---------------------------------------------------------------------------- The async methods allow an easy handle for download and internet responses, so you can use less code possible and be more efficient. Those methods can be only used within Scene and Window classes, if you want to use in your custom classes, then include the Async_Downloads module. ● download_async(url, method[, folder, priority]) Starts a download from url. It launchs automatically the method when the download is completed. Examples: download_async("www.mysite.com/image.jpg", method(:image_downloaded)) (you must defined the image_downloaded method also) The file download is slow, to not slow the game. If you want speed up the download, set true in priority ● get_response_async(url, method, priority) Starts the reception of a web service response from the URL, and launches the defined method when the response is received. Unlike the previous, the method that will be called must have an input parameter, that will be the string that you receive from the internet call. ● abort_download(filename) Cancels the file download. ● download_status(filename) Retrns a number from 0 to 100 that represents the download progress. ---------------------------------------------------------------------------- * Complex methods for downloads ---------------------------------------------------------------------------- Questi metodi possono essere usati ovunque e permettono una gestione più complessa e funzionale dei download. Possono anche essere usati affiancati ai metodi più semplici. ● await_response(url) Send a request to a web server and wait for the response, then returns the value. Example: print await_response(www.mysite.com) This code will print the HTML code of mysite.com. ● HTTP.domain returns your main server domain (configured below). ● HTTP.download(url[,folderpath[,low_priority]]) Downloads a file from url. If the folderpath is omitted, it will store the file in the game_folder ("./"). Example: HTTP.download("http://www.miosito.it/immagine.png","./Graphics/Pictures") it will download immagine.png in the Pictures folder. HTTP.download("http://www.miosito.it/immagine.png") it will download the immagine.png file in game folder. HTTP.download(HTTP.domain+"/immagine.png", Win.getFolderPath(:dskt)) it will download immagine.png from mysite.com on my desktop. You can set true to download the file more slowly, but you will have less game shuttering. ● HTTP.get_server_response(url, response_name) Sent a request to url and stores the response in an hash with response_name key. ● HTTP.await_response(url) Like await_response ● HTTP.response(response_name) Returns the response stored. ● HTTP.downloaded?(filename/response_name) Returns true if the response is obtained or the file is downloaded. Returns false if is not completely downloaded or the download isn't started. ● HTTP.progress(filename) Return the download progress of filename (from 0.0 to 100.0) ● HTTP.filesize(nomefile) returns the file size of the downloading file ● HTTP.sizeloaded(nomefile) returns the downloaded data of the file in bit. You may divide per 8 to obtain the byte size. ● HTTP.time_passed(nomefile) returns the time passed from the start of the download ● HTTP.downloads returns an hash containing all the download instances ● HTTP.completed returns the number of completed downloads ● HTTP.get_file_size(url) returns the file size on a weblink ● HTTP.file_good?(nomefile) checks if the file is good ● Browser.open(url) opens your default browser on the url. =end #============================================================================== module H87_ModConfig HTTPDOMAIN = "http://mysite.com" SETTINGNAME = "game_settings.rvdata2" VERSIONFILE = "version.ini" end #============================================================================== # ** Win #------------------------------------------------------------------------------ # Questo modulo gestisce le chiamate di sistema e recupera informazioni sul # computer #============================================================================== module Win #----------------------------------------------------------------------------- # *Nome Utente Windows # Restituisce il nome utente di Windows #----------------------------------------------------------------------------- def self.username name = " " * 128 size = "128" Win32API.new('advapi32','GetUserName',['P','P'],'I').call(name,size) username = name.unpack("A*") return username[0] end # -------------------------------------------------------------------------- # * Restituisce la cartella utente di Windows # -------------------------------------------------------------------------- def self.homepath name = " " * 128 size = "128" username = "\0" * 256 #userprofile Win32API.new('kernel32', 'GetEnvironmentVariable', %w(p p l), 'l').call("userprofile", username, 256) username.delete!("\0") return username.gsub("\\","/") end # -------------------------------------------------------------------------- # * Restituisce il percorso di una cartella del computer # -------------------------------------------------------------------------- def self.getFolderPath(symbol = :docs) case symbol when :user; index = 40 when :docs; index = 5 when :imgs; index = 39 when :musc; index = 13 when :vdeo; index = 14 when :strp; index = 2 when :prog; index = 38 when :appd; index = 28 else; index = 0 end path = "\0" * 128 Win32API.new('shell32', 'SHGetFolderPath', 'LLLLP', 'L').call(0, index, 0, 2, path) return path.delete("\0").gsub("\\","/") end # -------------------------------------------------------------------------- # * Restituisce la larghezza della cornice della finestra # -------------------------------------------------------------------------- def self.window_frame_width return Win32API.new("user32", "GetSystemMetrics", ['I'],'I').call(7) end # -------------------------------------------------------------------------- # * Restituisce l'altezza della barra del titolo # -------------------------------------------------------------------------- def self.window_title_height return Win32API.new("user32", "GetSystemMetrics", ['I'],'I').call(4) end #----------------------------------------------------------------------------- # * Elimina il file temporaneo per aggiornarlo prima di un download. # inserire il nome del file. #----------------------------------------------------------------------------- def self.temp_flush(nomefile) if version < 6 path = homepath+"/Impostazioni locali/Temporary Internet Files" unless File.directory?(path) path = homepath+"/Local Settings/Temporary Internet Files" return unless File.directory?(path) end fetch_folder_for_delete(path,nomefile) else path = homepath+"/AppData/Local/Microsoft/Windows/Temporary Internet Files/Content.IE5" unless File.directory?(path) path = cartella_utente_win+"/AppData/Local/Microsoft/Windows/INetCache/IE" end return unless File.directory?(path) Dir.foreach(path) {|x| #per ogni file nel percorso next if x == "." or x == ".." #passa al prossimo se è ind. if File.directory?(path+"/"+x) #se il file è una cartella folder = path+"/"+x #entra nella cartella fetch_folder_for_delete(folder,nomefile) end } end end # -------------------------------------------------------------------------- # * Cerca nella cartella il file da cancellare # path: directory # nomefile: file da cancellare # -------------------------------------------------------------------------- def self.fetch_folder_for_delete(path,nomefile) Dir.foreach(path) {|y| #per ogni file nella cartella next if File.directory?(path+"/"+y) #passa al prossimo se è una c. if no_ext(nomefile) == y[0..no_ext(nomefile).size-1]#se l'inizio del nome corrisp. begin File.delete(path+"/"+y) #eliminalo rescue next end end } end # -------------------------------------------------------------------------- # * Restituisce la versione di Windows in uso # -------------------------------------------------------------------------- def self.version gvex = Win32API.new( 'kernel32', 'GetVersionEx', ['P'], 'I' ) s = [20+128, 0, 0, 0, 0, '' ].pack('LLLLLa128') gvex.call( s ); a = s.unpack( 'LLLLLa128' ) indice = a[1].to_f;dec = a[2].to_f/10 return indice + dec end #----------------------------------------------------------------------------- # * Restituisce il nome del file senza estensione. #----------------------------------------------------------------------------- def self.no_ext(nomefile) nome = nomefile.split(".") return nome[0] end #----------------------------------------------------------------------------- # * Restituisce un array di larghezza e altezza della parte utilizzabile dello # schermo: non conta lo spazio della barra delle applicazioni. #----------------------------------------------------------------------------- def self.screen_resolution x = Win32API.new("user32", "GetSystemMetrics", ['I'],'I').call(16) y = Win32API.new("user32", "GetSystemMetrics", ['I'],'I').call(17) return [x,y] end #----------------------------------------------------------------------------- # * Restituisce un intero come codice della lingua del sistema #----------------------------------------------------------------------------- def self.language return Win32API.new("kernel32", "GetUserDefaultLCID", [], 'I').call end #----------------------------------------------------------------------------- # * Restituisce la data attuale #----------------------------------------------------------------------------- def self.datenow(partition = -1) date = Time.now case partition when -1 return sprintf("%d/%d/%d",date.day,date.month,date.year) when 0 return date.day when 1 return date.month when 2 return date.year end end #----------------------------------------------------------------------------- # * Restituisce l'ora attuale #----------------------------------------------------------------------------- def self.timenow(partition = -1) date = Time.now case partition when -1 return sprintf("%d:%d",date.hour,date.min) when 0 return date.hour when 1 return date.min when 2 return date.sec end end #----------------------------------------------------------------------------- # * arresta il computer in modalità diverse. #----------------------------------------------------------------------------- def self.shutdown(mode = 0) string = "system " case mode when 0 string += "-s" when 1 string += "-r" when 2 string += "-h" end system(string) end end #win #============================================================================== # ** Screen #------------------------------------------------------------------------------ # Questo modulo gestisce il ridimensionamento della finestra di gioco #============================================================================== module Screen #----------------------------------------------------------------------------- # * ridimensiona la finestra e la centra # width = nuova larghezza # height = nuova altezza #----------------------------------------------------------------------------- def self.resize(width ,height) #API getSystemMetrics = Win32API.new("user32", "GetSystemMetrics", 'I', 'I') moveWindow = Win32API.new("user32","MoveWindow",['l','i','i','i','i','l'],'l') findWindowEx = Win32API.new("user32","FindWindowEx",['l','l','p','p'],'i') this_window = findWindowEx.call(0,0,"RGSS Player",0) res_x = Win.screen_resolution[0] #risoluzione x res_y = Win.screen_resolution[1] #risoluzione y width += Win.window_frame_width*2 height += Win.window_frame_width*2 + Win.window_title_height new_x = [(res_x-width)/2, 0].max #ottiene la nuova coordinata, ma non new_y = [(res_y-height)/2, 0].max#fa passare oltre il bordo moveWindow.call(this_window, new_x, new_y, width, height, 1) end end #screen #============================================================================== # ** HTTP #------------------------------------------------------------------------------ # Questo modulo permette di interfacciarsi ad internet e gestire i download. # Ringraziamenti: Berka (il codice è ispirato al suo) #============================================================================== module HTTP SetPrClass = Win32API.new('kernel32','SetPriorityClass','pi','i').call(-1,128) InternetOpenA = Win32API.new("wininet",'InternetOpenA','plppl','l').call('',0,'','',0) InternetConnectA = Win32API.new("wininet",'InternetConnectA','lplpplll','l') InternetOpenUrl = Win32API.new("wininet",'InternetOpenUrl','lppllp','l') InternetReadFile = Win32API.new("wininet",'InternetReadFile','lpip','l') InternetCloseHandle = Win32API.new("wininet",'InternetCloseHandle','l','l') HttpQueryInfo = Win32API.new("wininet",'HttpQueryInfo','llppp','i') #-------------------------------------------------------------------------- # * Scarica un file da internet in un thread separato # url = indirizzo completo del nome del file # folder = cartella dove depositare il file scaricato #-------------------------------------------------------------------------- def self.download(url, folder = "./", low_priority = false, filename = nil, save = true) #inizializzazione @downloaded = 0 if @downloaded.nil? @downloads = {} if @downloads.nil? @counter = -1 if @counter.nil? @size = {} if @size.nil? @received = {} if @received.nil? @timepassed = {} if @timepassed.nil? @response = {} if @response.nil? @completed = {} if @completed.nil? #ottenimento dell'indirizzo address = url.split('/') server = address[2] root = address[3..address.size].join('/') filename = address[-1] if filename == nil #crezione del thread @downloads[filename] = Thread.start(url,folder, save){|url,folder,save| txt = "" t = Time.now "Serv f" if(e=InternetConnectA.call(InternetOpenA,server,80,'','',3,1,0))==0 file = InternetOpenUrl.call(InternetOpenA,url,nil,0,0,0) HttpQueryInfo.call(file,5,k="\0"*1024,[k.size-1].pack('l'),nil) @received[filename] = 0 @size[filename] = k.delete!("\0").to_i loop do buffer = " "*1024 n = 0 r = InternetReadFile.call(file,buffer,1024,o=[n].pack('i!')) n = o.unpack('i!')[0] txt<<buffer[0,n] @response[filename] = txt if !save @received[filename] = txt.size if r&&n==0 break end sleep(0.001) if low_priority end #creazione del file nel percorso if save if File.directory?(folder) obj = File.open(folder + filename,'wb')<<txt obj.close #chiusura del file else string = "%s non è un percorso valido, pertanto %s non verrà salvato." println sprintf(string, folder, filename) end end @received[filename] = @size[filename] @completed[filename] = true @downloaded += @received[filename] InternetCloseHandle.call(file) sleep(0.01) @timepassed[filename] = Time.now-t } end #-------------------------------------------------------------------------- # * Ottiene la dimensione di un file remoto in modo asincrono #-------------------------------------------------------------------------- def self.get_file_size_async(url) @filesize = {} if @filesize.nil? Thread.start(url){|url| @filesize[url] = get_file_size(url) } end #-------------------------------------------------------------------------- # * Restituisce true se la dimensione del file è stata ottenuta #-------------------------------------------------------------------------- def self.size_get?(url) return false if @filesize.nil? return @filesize[url] != nil? end #-------------------------------------------------------------------------- # * Ottiene la dimensione di un file remoto #-------------------------------------------------------------------------- def self.get_file_size(url) file = InternetOpenUrl.call(InternetOpenA,url,nil,0,0,0) HttpQueryInfo.call(file,5,k="\0"*1024,[k.size-1].pack('l'),nil) InternetCloseHandle.call(file) return k.delete!("\0").to_i end #-------------------------------------------------------------------------- # * Ottiene la risposta del server e la piazza nell'array delle rispose # url: indirizzo della richiesta # response_name: nome della risposta (per poterla leggere) # low_priority: priorità (false se normale, true se bassa) #-------------------------------------------------------------------------- def self.get_server_response(url, response_name, low_priority = false) download(url, "", low_priority, response_name, false) end #-------------------------------------------------------------------------- # * Restituisce direttamente il testo di risposta dal server, interrompendo # l'esecuzione del gioco fino a quando non arriva la risposta. # url: indirizzo della richiesta #-------------------------------------------------------------------------- def self.await_get_server_response(url) response = "response" @response.delete(response) if @response != nil @received.delete(response) if @received != nil @downloads.delete(response) if @downloads != nil download(url, "", false, response, false) loop {break if downloaded?(response)} return @response[response] end class << self; alias await_response await_get_server_response; end #-------------------------------------------------------------------------- # * Restituisce true se il file è scaricato. # filename: nome del file #-------------------------------------------------------------------------- def self.downloaded?(filename) return false if @received.nil? return false if @received[filename].nil? return false if @size[filename].nil? return true if @received[filename] >= @size[filename] return true if progress(filename) >= 100 return true if progress(filename).to_s == "NaN" return true if @completed[filename] return false end #-------------------------------------------------------------------------- # * Restituisce la grandezza del file da scaricare in byte # filename: nome del file #-------------------------------------------------------------------------- def self.filesize(filename) return 0 if @size.nil? return 0 if @size[filename].nil? return @size[filename] end #-------------------------------------------------------------------------- # * Restituisce la quantità di byte scaricati # filename: nome del file #-------------------------------------------------------------------------- def self.sizeloaded(filename) return 0 if @received.nil? return 0 if @received[filename].nil? return @received[filename] end #-------------------------------------------------------------------------- # * Restituisce la percentuale di progresso del download # filename: nome del file #-------------------------------------------------------------------------- def self.progress(filename) @received = {} if @received.nil? return 0 if @received[filename].nil? return @received[filename].to_f/@size[filename]*100 end #-------------------------------------------------------------------------- # * Restituisce l'hash dei download #-------------------------------------------------------------------------- def downloads return {} if @downloads.nil? return @downloads end #-------------------------------------------------------------------------- # * Restituisce il numero di secondi che ci sono voluti per scaricare #-------------------------------------------------------------------------- def self.time_passed(filename) return 0 if @timepassed[filename] == nil return @timepassed[filename] end #-------------------------------------------------------------------------- # * Restituisce il numero dei download completati #-------------------------------------------------------------------------- def self.completed return 0 if @downloaded.nil? return @downloaded end #-------------------------------------------------------------------------- # * Restituisce la risposta dal server # response_name: id della risposta #-------------------------------------------------------------------------- def self.response(response_name) return 0 if @response.nil? || @response[response_name].nil? return @response[response_name] end #-------------------------------------------------------------------------- # * Restituisce i download #-------------------------------------------------------------------------- def self.downloads @downloads ||= {} return @downloads end #-------------------------------------------------------------------------- # * Restituisce il dominio principale #-------------------------------------------------------------------------- def self.domain H87_ModConfig::HTTPDOMAIN end #-------------------------------------------------------------------------- # * Controlla se il file scaricato è buono e restituisce true o false #-------------------------------------------------------------------------- def self.file_good?(filename) if File.exist? (filename) #apre il file in sola lett. File.open(filename,"r") do |f| f.lineno = 1 # imposta la riga n.1 txt = f.gets return check_response(txt) end else return false end end #-------------------------------------------------------------------------- # * Restituisce true se il testo non è vuoto #-------------------------------------------------------------------------- def self.check_response(text) return false if text == "" or text.nil? first = text[0].chr return false if first == "" or first == nil return true end end #http #============================================================================== # ** Async_Downloads #------------------------------------------------------------------------------ # Dev'essere incluso nelle classi che fanno uso dei metodi download_async. #============================================================================== module Async_Downloads #-------------------------------------------------------------------------- # * Scarica un file in modo asincrono lanciando automaticamente il metodo. # url: indirizzo del file # method_name: nome del metodo, in simbolo (ad es. :apri) # low: true se è a bassa incidenza, false altrimenti # folder: percorso del file di salvataggio #-------------------------------------------------------------------------- def download_async(url, method, folder = "./", low = true) filename = url.split('/')[-1] if filename.downcase.include? ".php" println "Questo URL chiama un file PHP, pertanto non verrà salvato." println "Utilizzare invece il metodo get_repsonse_async." return end @async_downloads = {} if @async_downloads.nil? @async_downloads[filename] = method HTTP.download(url, folder, low) end #-------------------------------------------------------------------------- # * Ottiene la risposta di un servizio web in modo asincrono, lanciando # automaticamente il metodo associato. # url: indirizzo della richiesta # method_name: nome del metodo, in simbolo (ad es. :apri) # low: true se è a bassa incidenza, false altrimenti # response_id: id della risposta. #-------------------------------------------------------------------------- def get_response_async(url, method, low = true, response_id = String.random(20)) @async_responses = {} if @async_responses.nil? @async_responses[response_id] = method HTTP.get_server_response(url, response_id, low) end #-------------------------------------------------------------------------- # * Restituisce direttamente la stringa di risposta dal server # url: indirizzo della richiesta #-------------------------------------------------------------------------- def await_response(url) return HTTP.await_get_server_response(url) end #-------------------------------------------------------------------------- # * Controlla i download e lancia il metodo associato se completato. #-------------------------------------------------------------------------- def check_async_downloads return if @async_downloads.nil? || @async_downloads.size == 0 @async_downloads.each_key do |key| if HTTP.downloaded?(key) @async_downloads[key].call @async_downloads.delete(key) end end end #-------------------------------------------------------------------------- # * Controlla le risposte e lancia il metodo associato quando ricevuta. #-------------------------------------------------------------------------- def check_async_requests return if @async_responses.nil? || @async_responses.size == 0 @async_responses.each_key do |key| if HTTP.downloaded?(key) && HTTP.response(key) != nil @async_responses[key].call(HTTP.response(key)) @async_responses.delete(key) end end end #-------------------------------------------------------------------------- # * Cancella un download o l'attesa di una risposta # filename: nome del file o id della risposta #-------------------------------------------------------------------------- def abort_download(filename) Thread.kill(HTTP.downloads(filename)) end #-------------------------------------------------------------------------- # * Restituisce la percentuale di download da 0 a 100 # filename: nome del file #-------------------------------------------------------------------------- def download_status(filename) status = HTTP.progress(filename) return [[0, status].max, 100].min.to_i end end #============================================================================== # ** Modulo Browser per aprire il browser predefinito del PC #============================================================================== module Browser #-------------------------------------------------------------------------- # * apre il browser # url: url impostato #-------------------------------------------------------------------------- def self.open(url) #controlla che ci siano prefissi if url[0..6] != "http://" and url[0..7] != "https://" open_url = "http://"+url else open_url = url end shell = Win32API.new("Shell32", "ShellExecute", ['L', 'P', 'P', 'P','P', 'L'], 'L') Thread.new{shell.call(0, "open", open_url, 0, 0, 1)} sleep(0.01) SceneManager.exit end end #browser #============================================================================== # ** Modulo Browser per la codifica/decodifica di stringhe in Base64 #============================================================================== module Base64 #-------------------------------------------------------------------------- # * Restituisce una stringa decodificata da Base64 # string: stringa da decodificare #-------------------------------------------------------------------------- def self.decode(string) return string.gsub(/\s+/, "").unpack("m")[0] end #-------------------------------------------------------------------------- # * Restituisce una stringa codificata in Base64 # string: stringa da codificare #-------------------------------------------------------------------------- def self.encode(string) return [string].pack("m") end end #base64 #============================================================================== # ** Classe Settings (per le impostazioni comuni ai salvataggi) #============================================================================== class H87_Settings #-------------------------------------------------------------------------- # * restituisce l'elemento corrispondente al parametro #-------------------------------------------------------------------------- def [](param) @settings[param] end #-------------------------------------------------------------------------- # * inizializzazione #-------------------------------------------------------------------------- def initialize @settings = {} end #-------------------------------------------------------------------------- # * cambia o aggiunge un elemento dell'hash #-------------------------------------------------------------------------- def []=(param_name,value) @settings[param_name] = value save end #-------------------------------------------------------------------------- # * Registra i dati salvati #-------------------------------------------------------------------------- def save save_data($game_settings,DataManager.settings_path) end end #settings #============================================================================== # ** Game_Version #------------------------------------------------------------------------------ # Questa classe è d'appoggio per gestire la versione del gioco. #============================================================================== class Game_Version include Comparable #per la verifica delle versioni se maggiore o minore attr_accessor :major #numero di major release attr_accessor :minor #numero di minor release attr_accessor :build #numero di versione build attr_accessor :revision #numero di revisione #-------------------------------------------------------------------------- # * Inizializzazione # version_string: versione in stringa (ad es. 1.5.3.1) #-------------------------------------------------------------------------- def initialize(version_string, starting_major = 1) @major = starting_major @minor = 0 @build = 0 @revision = 0 version_string.gsub!(/\s\n\r/,"") return unless version_string =~ /[\d]+([\.[\d]]*)/ version_string = version_string.split(".") @major = version_string[0].to_i return if version_string[1].nil? @minor = version_string[1].to_i return if version_string[2].nil? @build = version_string[2].to_i return if version_string[3].nil? @revision = version_string[3].to_i end #-------------------------------------------------------------------------- # * Restituisce la versione attuale del gioco #-------------------------------------------------------------------------- def self.now if File.exist?(H87_ModConfig::VERSIONFILE) file = File.open(H87_ModConfig::VERSIONFILE,"r") str = file.read file.close return Game_Version.new(str) else return Game_Version.new("1.0.0.0") end end #-------------------------------------------------------------------------- # * Compara una versione o una stringa con se stessa #-------------------------------------------------------------------------- def <=> other return self <=> Game_Version.new(other) if other.is_a?(String) return self.major <=> other.major if self.major != other.major return self.minor <=> other.minor if self.minor != other.minor return self.build <=> other.build if self.build != other.build return self.revision <=> other.revision end #-------------------------------------------------------------------------- # * restituisce la versione in stringa #-------------------------------------------------------------------------- def to_s return sprintf("%d.%d.%d.%d", @major, @minor, @build, @revision) end end #game_version #============================================================================== # ** RPG::System -> aggiunta del metodo per la versione del gioco #============================================================================== class Game_System #-------------------------------------------------------------------------- # * Restituisce la versione del gioco attuale #-------------------------------------------------------------------------- def game_version return Game_Version.now end end #rpg_system #============================================================================== # ** DataManager -> aggiunta dei metodi per caricare i settaggi #============================================================================== module DataManager #-------------------------------------------------------------------------- # * alias #-------------------------------------------------------------------------- class << self alias h87set_load_n_db load_normal_database alias h87set_load_b_db load_battle_test_database end # -------------------------------------------------------------------------- # * caricamento nd # -------------------------------------------------------------------------- def self.load_normal_database load_h87settings h87set_load_n_db end # -------------------------------------------------------------------------- # * caricamento btd # -------------------------------------------------------------------------- def self.load_battle_test_database load_h87settings h87set_load_b_db end # -------------------------------------------------------------------------- # * restituisce il percorso delle impostazioni # -------------------------------------------------------------------------- def self.settings_path H87_ModConfig::SETTINGNAME end #-------------------------------------------------------------------------- # * carica le impostazioni universali #-------------------------------------------------------------------------- def self.load_h87settings return if $game_settings if File.exist?(settings_path) $game_settings = load_data(settings_path) else $game_settings = H87_Settings.new save_data($game_settings,settings_path) end end end #datamanager #============================================================================== # ** Aggiunta di alcuni metodi utili per le stringhe #============================================================================== class String #-------------------------------------------------------------------------- # * Metodo Random: restituisce una stringa a caso # size: numero di caratteri della stringa #-------------------------------------------------------------------------- def self.random(size = 4) stringa = rand(36**size).to_s(36) return stringa end #-------------------------------------------------------------------------- # * Restituisce la stessa stringa ma crittografata in ROT13 # http://it.wikipedia.org/wiki/ROT13 #-------------------------------------------------------------------------- def crypt_rot13 return self.tr("A-Za-z", "N-ZA-Mn-za-m") end end #fine della stringa #============================================================================== # ** Inclusione dei metodi asincroni in Scene_Base #============================================================================== class Scene_Base include Async_Downloads # inclusione del modulo #-------------------------------------------------------------------------- # * Alias del metodo d'aggiornamento #-------------------------------------------------------------------------- alias h87_module_update update unless $@ def update h87_module_update check_async_downloads #controlla i download check_async_requests #controlla le richieste end end #scene_base #============================================================================== # ** Inclusione dei metodi asincroni in Window_Base #============================================================================== class Window_Base include Async_Downloads # inclusione del modulo #-------------------------------------------------------------------------- # * Alias del metodo d'aggiornamento #-------------------------------------------------------------------------- alias h87_module_update update unless $@ def update h87_module_update check_async_downloads #controlla i download check_async_requests #controlla le richieste end end #scene_base class Object #-------------------------------------------------------------------------- # * Metodo di stampa riga #-------------------------------------------------------------------------- def println(*args) print(*args, "\n") end #-------------------------------------------------------------------------- # * Metodi di conversione Base64 #-------------------------------------------------------------------------- def base64_encode(string); Base64.encode(string); end def base64_decode(string); Base64.decode(string); end #-------------------------------------------------------------------------- # * Restituisce direttamente la stringa di risposta dal server # url: indirizzo della richiesta #-------------------------------------------------------------------------- def await_response(url) return HTTP.await_get_server_response(url) end end
true
10488c78e92d0f3cb223c08575ea073b47d417f7
Ruby
QBFreak/NightMAREbot
/sbin/newsbot/plugins/show_news.rb
UTF-8
3,786
2.953125
3
[]
no_license
=begin Contains several methods to display posts in various ways. =end class NewsCommand < Command def display_news news_array news_array = get_news_from news_array if news_array.kind_of? Integer return news_array.map{|n| n.short_display}.join("\n") end def get_news_from index=-1 p_arr = [] if index == -1 ($DATA[:news].size-1).downto(0) do |i| unless $DATA[:news][i].sticky p_arr << $DATA[:news][i] break if p_arr.size == 15 end end return p_arr else index.upto($DATA[:news].size-1) do |i| unless $DATA[:news][i].sticky p_arr << $DATA[:news][i] break if p_arr.size == 15 end end return p_arr.reverse end end def prefix with_stickies = true title_string = 'newsboard_daemon_' + #now get mods! if $DATA[:options][$CALLER][:color] == :off 'mono_' elsif Time.now.month == 12 'christmas_' else '' end + 'title' str = Util::from_daemon(title_string) + "\n" str << Constants::TITLE str << "Sticky threads:" << "\n" << display_news($DATA[:stickies].map{|n| Util::get_post(n.to_s)}.reverse) << "\n" << Constants::DIVIDER if with_stickies and $DATA[:stickies].size > 0 return str end private :display_news, :get_news_from, :prefix end NewsCommand.new do name "Show news" desc "Shows recent news posts" help <<-eof This shows you the last 15 news posts. New news posts have [NEW] in front of them, and the index of posts that are either new or have unread replies is highlighted. eof syntax "+news" match(/^$/) trigger do next NewsMessage.new{|n| n.message = prefix + display_news(-1)} end end NewsCommand.new do name "History" desc "Show older news posts" help <<-eof This command allows you to look back in the news beyond that shown by a simple +news. The post number you give will be the first one in the list - the next 15 will also be displayed. eof syntax "+news hist=<post number>" match(/^hist=(\d+)/) trigger do |match| next NewsMessage.new{|n| n.message = prefix(false) + display_news($1.to_i - 1)} end end NewsCommand.new do name "Show full" desc "Shows posts as a \"tree\"" help <<-eof With this command you may examine posts as a "tree" rather than a plain list. Replies to posts are shown indented below the post itself, with replies to them further indented, and so on. A post path can be included - if so, you will get just that post and its children. Note that if there are over 15 replies to a post they will all be shown, and that they are not shown in reverse order as news posts are normally. eof syntax "+news full [post path]" match(/^full( #{Constants::PATH_TO_POST})?/) trigger do |match| r_string = '' if match[1].nil? r_string = prefix p_arr = get_news_from -1 p_arr.each do |news| news.drill_with_depth do |article, i| r_string << ('%t' * i) << article.short_display << '%r' end end else r_string = prefix(false) p = Util::get_post match[1][1..-1] #remove space next Constants::ERR_NOT_FOUND if p.nil? p.drill_with_depth do |article, i| r_string << ('%t' * i) << article.short_display << '%r' end end next NewsMessage.new{|n| n.message = r_string} end end NewsCommand.new do name "Show unread" desc "Shows the latest 15 news posts with unread content" help <<-eof With this command you may see the last 15 posts that contain unread content. Unread content basically means any posts that you haven't read, or have unread replies. eof syntax "+news unread" match(/^unread/) trigger do arr = [] ($DATA[:news].size - 1).downto(0) do |i| n = $DATA[:news][i] arr << n if n.num_unread_replies(true) > 0 break if arr.size > 14 end next NewsMessage.new{|n| n.message = prefix(false) + display_news(arr)} end end
true
65b557ff508f5d091c91e0da5a4c145c1fec946e
Ruby
s-wigg/algorithms
/lib/selection_sort.rb
UTF-8
779
4.09375
4
[]
no_license
# time complexity is O(n^2) or quadratic def find_smallest(array) smallest = array[0] smallest_index = 0 array.drop(1).each_with_index do |value, index| # print "value: #{value} " # puts "Index: #{index}" next unless value < smallest smallest = value # puts "smallest: #{smallest}" smallest_index = index + 1 # puts "smallest index: #{smallest_index}" end return smallest_index end def selection_sort(array) sorted_array = [] while array.length > 0 index = find_smallest(array) # puts "I'm in the selection sort method!" sorted_array << array.delete_at(index) # print array # puts "\n" # print sorted_array end return sorted_array end # array = [10, 5, 1] # puts selection_sort(array)
true
f410a8ebb3f18fefe426da30449f33466709f087
Ruby
codeship/bitbucket
/lib/bitbucket_rest_api/repos/commits.rb
UTF-8
1,766
2.578125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
# encoding: utf-8 module BitBucket class Repos::Commits < API VALID_KEY_PARAM_NAMES = %w(include exclude pagelen).freeze # Gets the commit information associated with a repository. By default, this # call returns all the commits across all branches, bookmarks, and tags. The # newest commit is first. # # = Parameters # *<tt>include</tt> - The SHA, branch, bookmark, or tag to include, for example, v10 or master. You can repeat the parameter multiple times. # *<tt>exclude</tt> - The SHA, branch, bookmark, or tag to exclude, for example, v10 or master . You can repeat the parameter multiple times. # # = Examples # bitbucket = BitBucket.new # bitbucket.repos.commits.list 'user-name', 'repo-name' # bitbucket.repos.commits.list 'user-name', 'repo-name', 'master' # bitbucket.repos.commits.list 'user-name', 'repo-name' { |key| ... } # bitbucket.repos.commits.list 'user-name', 'repo-name', nil, # "include" => "feature-branch", # "exclude" => "master" # def list(user_name, repo_name, branchortag=nil, params={}) _update_user_repo_params(user_name, repo_name) _validate_user_repo_params(user, repo) unless user? && repo? normalize! params filter! VALID_KEY_PARAM_NAMES, params path = if BitBucket.options[:bitbucket_server] "/1.0/projects/#{user_name}/repos/#{repo_name}/commits" else "/2.0/repositories/#{user}/#{repo.downcase}/commits" end path << "/#{branchortag}" if branchortag response = get_request(path, params) return response unless block_given? response.each { |el| yield el } end alias :all :list end # Repos::Commits end # BitBucket
true
8612abe881173a21427907f97cac789e05b9cadf
Ruby
paradox460/subbot
/plugins/subreddit_management.rb
UTF-8
1,720
2.609375
3
[ "MIT" ]
permissive
require './lib/common_functions' require "active_support/core_ext/array/conversions" class SubredditManagement include Cinch::Plugin include CommonFunctions set :plugin_name, "Subreddit Management" set :help, "Usage: #{CONFIG['prefix']}subreddit (add|del|list) <subreddit>" match /subreddit add ([[:alnum:]]\w{1,21})/, method: :add_subreddit match /subreddit del ([[:alnum:]]\w{1,21})/, method: :del_subreddit match /subreddit list/, method: :list_subreddits def add_subreddit(m, subreddit) admincheck(m) do opcheck(m) do if subreddit =~ Regexp.union(SubbotConstants::BADSUBS) m.reply "Try a real subreddit please" else sr = Database::Subreddit.first_or_create(name: subreddit) c = Database::Channel.first_or_create(name: m.channel.to_s) c.subreddits << sr if c.save m.reply "Added!" else m.reply CONFIG['messages']['failure'] end end end end end def del_subreddit(m, subreddit) admincheck(m) do opcheck(m) do c = Database::Channel.first(name: m.channel.to_s) sr = Database::Subreddit.first(name: subreddit) if Database::Assignment.get(c.id, sr.id).destroy m.reply "Removed!" else m.reply CONFIG['messages']['failure'] end end end end def list_subreddits(m) subs = Database::Channel.first(name: m.channel.to_s).subreddits if subs.empty? m.reply "No subreddits assigned!" else m.safe_reply subs.map { |x| "/r/#{x.name}" }.to_sentence m.safe_reply "Multireddit of subs: http://www.reddit.com/r/#{subs.map(&:name).join('+')}" end end end
true
9064ddd1f667e2b8ead587345bd17d11390b2f45
Ruby
sunlightlabs/tcorps-earmarks
/vendor/gems/rscribd-1.0.1/lib/scribddoc.rb
UTF-8
11,486
3
3
[ "MIT" ]
permissive
require 'uri' module Scribd # A document as shown on the Scribd website. API programs can upload documents # from files or URL's, tag them, and change their settings. An API program can # access any document, but it can only modify documents owned by the logged-in # user. # # To upload a new document to Scribd, you must create a new Document instance, # set the +file+ attribute to the file's path, and then save the document: # # doc = Scribd::Document.new # doc.file = '/path/or/URL/of/file.txt' # doc.save # # You can do this more simply with one line of code: # # doc = Scribd::Document.create :file => '/path/or/URL/of/file.txt' # # If you are uploading a file that does not have an extension (like ".txt"), # you need to specify the +type+ attribute as well: # # doc = Scribd::Document.upload :file => 'CHANGELOG', :type => 'txt' # # Aside from these two attributes, you can set other attributes that affect # how the file is displayed on Scribd. See the API documentation online for a # list of attributes, at # http://www.scribd.com/publisher/api?method_name=docs.search (consult the # "Result explanation" section). # # These attributes can be accessed or changed directly # (<tt>doc.title = 'Title'</tt>). You must save a document after changing its # attributes in order for those changes to take effect. Not all attributes can # be modified; see the API documentation online for details. # # A document can be associated with a Scribd::User via the +owner+ attribute. # This is not always the case, however. Documents retrieved from the find # method will not be associated with their owners. # # The +owner+ attribute is read/write, however, changes made to it only apply # _before_ the document is saved. Once it is saved, the owner is set in stone # and cannot be modified: # # doc = Scribd::Document.new :file => 'test.txt' # doc.user = Scribd::User.signup(:username => 'newuser', :password => 'newpass', :email => '[email protected]') # doc.save #=> Uploads the document as "newuser", regardless of who the Scribd API user is # doc.user = Scribd::API.instance.user #=> raises NotImplementedError class Document < Resource # Creates a new, unsaved document with the given attributes. The document # must be saved before it will appear on the website. def initialize(options={}) super @download_urls = Hash.new if options[:xml] then load_attributes(options[:xml]) @attributes[:owner] = options[:owner] @saved = true @created = true else @attributes = options end end # For document objects that have not been saved for the first time, uploads # the document, sets its attributes, and saves it. Otherwise, updates any # changed attributes and saves it. Returns true if the save completed # successfully. Throws an exception if save fails. # # For first-time saves, you must have specified a +file+ attribute. This can # either be a local path to a file, or an HTTP, HTTPS, or FTP URL. In either # case, the file at that location will be uploaded to create the document. # # If you create a document, specify the +file+ attribute again, and then # save it, Scribd replaces the existing document with the file given, while # keeping all other properties (title, description, etc.) the same, in a # process called _revisioning_. # # This method can throw a +Timeout+ exception if the connection is slow or # inaccessible. A Scribd::ResponseError will be thrown if a remote problem # occurs. A Scribd::PrivilegeError will be thrown if you try to upload a new # revision for a document with no associated user (i.e., one retrieved from # the find method). # # You must specify the +type+ attribute alongside the +file+ attribute if # the file's type cannot be determined from its name. def save if not created? and @attributes[:file].nil? then raise "'file' attribute must be specified for new documents" return false end if created? and @attributes[:file] and (@attributes[:owner].nil? or @attributes[:owner].session_key.nil?) then raise PrivilegeError, "The current API user is not the owner of this document" end # Make a request form fields = @attributes.dup if @attributes[:file] then fields.delete :file ext = @attributes[:file].split('.').last unless @attributes[:file].index('.').nil? fields[:doc_type] = fields.delete(:type) fields[:doc_type] ||= ext fields[:doc_type].downcase! if fields[:doc_type] fields[:rev_id] = fields.delete(:doc_id) end fields[:session_key] = fields.delete(:owner).session_key if fields[:owner] response = nil if @attributes[:file] then uri = nil begin uri = URI.parse @attributes[:file] rescue URI::InvalidURIError uri = nil # Some valid file paths are not valid URI's (but some are) end if uri.kind_of? URI::HTTP or uri.kind_of? URI::HTTPS or uri.kind_of? URI::FTP then fields[:url] = @attributes[:file] response = API.instance.send_request 'docs.uploadFromUrl', fields elsif uri.kind_of? URI::Generic or uri.nil? then File.open(@attributes[:file]) do |file| fields[:file] = file response = API.instance.send_request 'docs.upload', fields end end end fields = @attributes.dup # fields is what we send to the server if response then # Extract our response xml = response.get_elements('/rsp')[0] load_attributes(xml) @created = true end fields.delete :file fields.delete :type fields.delete :access changed_attributes = fields.dup # changed_attributes is what we will stick into @attributes once we update remotely fields[:session_key] = fields[:owner].session_key if fields[:owner] changed_attributes[:owner] ||= API.instance.user fields[:doc_ids] = self.id API.instance.send_request('docs.changeSettings', fields) @attributes.update(changed_attributes) @saved = true return true end # Quickly updates an array of documents with the given attributes. The # documents can have different owners, but all of them must be modifiable. def self.update_all(docs, options) raise ArgumentError, "docs must be an array" unless docs.kind_of? Array raise ArgumentError, "docs must consist of Scribd::Document objects" unless docs.all? { |doc| doc.kind_of? Document } raise ArgumentError, "You can't modify one or more documents" if docs.any? { |doc| doc.owner.nil? } raise ArgumentError, "options must be a hash" unless options.kind_of? Hash docs_by_user = docs.inject(Hash.new { |hash, key| hash[key] = Array.new }) { |hash, doc| hash[doc.owner] << doc; hash } docs_by_user.each { |user, doc_list| API.instance.send_request 'docs.changeSettings', options.merge(:doc_ids => doc_list.collect(&:id).join(','), :session_key => user.session_key) } end # === Finding by query # # This method is called with a scope and a hash of options to documents by # their content. You must at a minimum supply a +query+ option, with a # string that will become the full-text search query. For a list of other # supported options, please see the online API documentation at # http://www.scribd.com/publisher/api?method_name=docs.search # # The scope can be any value given for the +scope+ parameter in the above # website, or <tt>:first</tt> to return the first result only (not an array # of results). # # The +num_results+ option has been aliased as +limit+, and the +num_start+ # option has been aliased as +offset+. # # Documents returned from this method will have their +owner+ attributes set # to nil. # # Scribd::Document.find(:all, :query => 'cats and dogs', :limit => 10) # # === Finding by ID # # Passing in simply a numerical ID loads the document with that ID. You can # pass additional options as defined at # httphttp://www.scribd.com/publisher/api?method_name=docs.getSettings # # Scribd::Document.find(108196) # # For now only documents that belong to the current user can be accessed in # this manner. def self.find(scope, options={}) doc_id = scope if scope.kind_of?(Integer) raise ArgumentError, "You must specify a query or document ID" unless options[:query] or doc_id if doc_id then options[:doc_id] = doc_id response = API.instance.send_request('docs.getSettings', options) return Document.new(:xml => response.elements['/rsp']) else options[:scope] = scope == :first ? 'all' : scope.to_s options[:num_results] = options[:limit] options[:num_start] = options[:offset] response = API.instance.send_request('docs.search', options) documents = [] response.elements['/rsp/result_set'].elements.each do |doc| documents << Document.new(:xml => doc) end return scope == :first ? documents.first : documents end end class << self alias_method :upload, :create end # Returns the conversion status of this document. When a document is # uploaded it must be converted before it can be used. The conversion is # non-blocking; you can query this method to determine whether the document # is ready to be displayed. # # The conversion status is returned as a string. For a full list of # conversion statuses, see the online API documentation at # http://www.scribd.com/publisher/api?method_name=docs.getConversionStatus # # Unlike other properties of a document, this is retrieved from the server # every time it's queried. def conversion_status response = API.instance.send_request('docs.getConversionStatus', :doc_id => self.id) response.elements['/rsp/conversion_status'].text end # Deletes a document. Returns true if successful. def destroy response = API.instance.send_request('docs.delete', :doc_id => self.id) return response.elements['/rsp'].attributes['stat'] == 'ok' end # Returns the +doc_id+ attribute. def id self.doc_id end # Ensures that the +owner+ attribute cannot be set once the document is # saved. def owner=(newuser) #:nodoc: saved? ? raise(NotImplementedError, "Cannot change a document's owner once the document has been saved") : super end # Retrieves a document's download URL. You can provide a format for the # download. Valid formats are listed at # http://www.scribd.com/publisher/api?method_name=docs.getDownloadUrl # # If you do not provide a format, the link will be for the document's # original format. def download_url(format='original') @download_urls[format] ||= begin response = API.instance.send_request('docs.getDownloadUrl', :doc_id => self.id, :doc_type => format) response.elements['/rsp/download_link'].cdatas.first.to_s end end end end
true
2a8aaf88b2ef5c11099544222d190a6233584396
Ruby
nagano564/operationcode_backend
/app/lib/format_data.rb
UTF-8
372
3.40625
3
[ "MIT", "CC-BY-3.0" ]
permissive
class FormatData # Converts a comma-separated string into an array of its contents. # # @param comma_separated_string [String] String of comma-separated values, i.e '80123, 80202' # @return [Array] An array of strings, i.e. ['80123', '80202'] # def self.csv_to_array(comma_separated_string) comma_separated_string.upcase.split(',').map(&:strip) end end
true
e45701342ade8ad441af9488d961737d5e9283a5
Ruby
codegorilla/lang
/builders/IntBuilder.rb
UTF-8
7,561
3.390625
3
[ "MIT" ]
permissive
class IntBuilder def initialize () @Int = TauObject.new($Class, "<class 'Int'>") end def makeRaw (value) TauObject.new(@Int, value) end def make (params) makeRaw(params[0].value) end def bor (params) x = params[0] y = params[1] result = case y.type when @Int then TauObject.new(@Int, x.value | y.value) else TauObject.new($Exception, "Type error: unsupported operand types for |: Int and <other>") end result end def bxor (params) x = params[0] y = params[1] result = case y.type when @Int then TauObject.new(@Int, x.value ^ y.value) else TauObject.new($Exception, "Type error: unsupported operand types for ^: Int and <other>") end result end def band (params) x = params[0] y = params[1] result = case y.type when @Int then TauObject.new(@Int, x.value & y.value) else TauObject.new($Exception, "Type error: unsupported operand types for ^: Int and <other>") end result end def equ (params) x = params[0] y = params[1] result = case y.type when @Int then z = x.value == y.value # return the singletons not a new value if z == true then $true else $false end when $Float then z = x.value == y.value if z == true then $true else $false end else $false end result end def neq (params) x = params[0] y = params[1] result = case y.type when @Int then z = x.value != y.value # return the singletons not a new value if z == true then $true else $false end when $Float then z = x.value != y.value if z == true then $true else $false end else $true end result end def gt (params) x = params[0] y = params[1] result = case y.type when @Int then if x.value > y.value then $true else $false end when $Float then if x.value > y.value then $true else $false end else TauObject.new($Exception, "Type error: unsupported operand types for >: Int and <other>") end result end def lt (params) x = params[0] y = params[1] result = case y.type when @Int then if x.value < y.value then $true else $false end when $Float then if x.value < y.value then $true else $false end else TauObject.new($Exception, "Type error: unsupported operand types for <: Int and <other>") end result end def ge (params) x = params[0] y = params[1] result = case y.type when @Int then if x.value >= y.value then $true else $false end when $Float then if x.value >= y.value then $true else $false end else TauObject.new($Exception, "Type error: unsupported operand types for >=: Int and <other>") end result end def le (params) x = params[0] y = params[1] result = case y.type when @Int then if x.value <= y.value then $true else $false end when $Float then if x.value <= y.value then $true else $false end else TauObject.new($Exception, "Type error: unsupported operand types for <=: Int and <other>") end result end def shl (params) x = params[0] y = params[1] result = case y.type when @Int then TauObject.new(@Int, x.value << y.value) else TauObject.new($Exception, "Type error: unsupported operand types for <<: Int and <other>") end result end def shr (params) x = params[0] y = params[1] result = case y.type when @Int then TauObject.new(@Int, x.value >> y.value) else TauObject.new($Exception, "Type error: unsupported operand types for >>: Int and <other>") end result end def add (params) x = params[0] y = params[1] result = case y.type when @Int then TauObject.new(@Int, x.value + y.value) when $Float then TauObject.new($Float, x.value + y.value) else TauObject.new($Exception, "Type error: unsupported operand types for +: Int and <other>") end result end def sub (params) x = params[0] y = params[1] result = case y.type when @Int then TauObject.new(@Int, x.value - y.value) when $Float then TauObject.new($Float, x.value - y.value) else TauObject.new($Exception, "Type error: unsupported operand types for -: Int and <other>") end result end def mul (params) x = params[0] y = params[1] result = case y.type when @Int then TauObject.new(@Int, x.value * y.value) when $Float then TauObject.new($Float, x.value * y.value) else TauObject.new($Exception, "Type error: unsupported operand types for *: Int and <other>") end result end def div (params) x = params[0] y = params[1] result = case y.type when @Int then TauObject.new(@Int, x.value / y.value) when $Float then TauObject.new($Float, x.value / y.value) else TauObject.new($Exception, "Type error: unsupported operand types for /: Int and <other>") end result end def neg (params) x = params[0] result = TauObject.new(@Int, -x.value) result end def bnot (params) x = params[0] result = TauObject.new(@Int, ~x.value) result end def not (params) # Need to think about truthy vs. falsy values # Do we follow the python/javascript model or the ruby model? result = $false result end def toString (params) x = params[0] result = TauObject.new($String, x.value.to_s) end def classObj () @Int end def build () @Int.setMember('super', $Any) # Perhaps the value should be an array or some kind of 'NativeCode' ruby # object that the interpreter will distinguish at runtime. An array will # work for now. Array is of the form [numParams, code]. makeFun = TauObject.new($Function, [1, method(:make)]) @Int.setMember('make', makeFun) @Int.setMember('bor', TauObject.new($Function, [2, method(:bor)])) @Int.setMember('bxor', TauObject.new($Function, [2, method(:bxor)])) @Int.setMember('band', TauObject.new($Function, [2, method(:band)])) @Int.setMember('equ', TauObject.new($Function, [2, method(:equ)])) @Int.setMember('neq', TauObject.new($Function, [2, method(:neq)])) @Int.setMember('gt', TauObject.new($Function, [2, method(:gt)])) @Int.setMember('lt', TauObject.new($Function, [2, method(:lt)])) @Int.setMember('ge', TauObject.new($Function, [2, method(:ge)])) @Int.setMember('le', TauObject.new($Function, [2, method(:le)])) @Int.setMember('shl', TauObject.new($Function, [2, method(:shl)])) @Int.setMember('shr', TauObject.new($Function, [2, method(:shr)])) @Int.setMember('add', TauObject.new($Function, [2, method(:add)])) @Int.setMember('sub', TauObject.new($Function, [2, method(:sub)])) @Int.setMember('mul', TauObject.new($Function, [2, method(:mul)])) @Int.setMember('div', TauObject.new($Function, [2, method(:div)])) @Int.setMember('neg', TauObject.new($Function, [2, method(:neg)])) @Int.setMember('bnot', TauObject.new($Function, [1, method(:bnot)])) @Int.setMember('not', TauObject.new($Function, [1, method(:not)])) @Int.setMember('toString', TauObject.new($Function, [1, method(:toString)])) end end # class
true
d4166c1cc7e2a36f9d74daa9bfecdf83685a0e54
Ruby
SamiZhang/Phase-0
/week-5/gps2_2.rb
UTF-8
3,925
4.5625
5
[ "MIT" ]
permissive
# Method to create a list # input: string of items separated by spaces (example: "carrots apples cereal pizza") # steps: # Create a method named create_list and it will accept a string as input # Create hash for method create_list with default value for each key equal to 1 # Split string into individual items and add to the hash # String.split(" ") # print the list to the console [can you use one of your other methods here?] # output: Recieve a list of strings and each string will contain a key and a value from the hash def create_list(string) list = Hash.new string.split(" ").each do |item| list[item] = 1 end p list end grocery_list = create_list("carrots apples cereal pizza") # Method to add an item to a list # input: list that created previously, new item, and quantity of new item # steps: # add new item into previous list # output: previous list with new item and it's quantity included def add_item(list, item, qty) list[item] = qty p list end add_item(grocery_list, "bread",3) # p list # Method to remove an item from the list # input: list that created previously, item needed to be removed # steps: remove an item from list # output: previous list with an item removed def remove_item(list, item) list.delete(item) p list end remove_item(grocery_list, "bread") # Method to update the quantity of an item # input: list created previously, item, quantity # steps: replace the item's old quantity with the new quantity # output: previous list with updated item quantity def new_quantity(list, item, qty) list[item] += qty p list end new_quantity(grocery_list, "carrots", 5) # Method to print a list and make it look pretty # input: list # steps: take each item from the list and write it out along with its value # output: nicer looking list with the hash's information def print_out(list) list.each { |a,b| puts "#{a} : #{b}" } end print_out(grocery_list) =begin What did you learn about pseudocode from working on this challenge? I learned that pseudocode are used to write out what you want the method to do and it helps you when creating the method. Pseudocode for Ruby is like wireframe for HTML. What are the tradeoffs of using Arrays and Hashes for this challenge? We can use array when calling the list to add or remove a item and/or quantity within a hash. Hash was used to list a set of items(key) and a quantity was given(value) which was great to create the list for this challenge. What does a method return? A method returns a value accodring to the instructions given to the method. What kind of things can you pass into methods as arguments? You can pass strings, numbers, array, and even methods as arguments. How can you pass information between methods? Instead of just creating a local variable, we can create a method and set it's output to a variable and using it on other methods. What concepts were solidified in this challenge, and what concepts are still confusing? I think I have a much clearer undertanding of how to write a method to make it work a certain way. I know there are many ways to write a single method but the concept of writing it out was difficult for me. This challenge definitely solidfied that concept for me and I need to spend more time looking into Ruby syntax so I can really write a method without any confusions. John, This is something unrelated to this challenge but what would you say is a good way to practice Ruby? As you can see tonight, I really struggled figuring out how to create a method. I realized that I had major problem thinking through how to write the methods whether it's pseudocode or the solution. Also, I want to know when to use (), [], and {}. From this challenge I saw that the brackets were used at different occasion. Does the brackets itself have specific usage or it just depends on what the code is? Thank you for guiding tonight! You helped me a lot. =end
true
bb5a53ee30ed9eb09081309e03ae725d83f1dad1
Ruby
peppetrombetta/webgl
/lib/web_gl/world.rb
UTF-8
1,634
2.75
3
[]
no_license
class WebGL::World class Camera attr_accessor :right, :up, :view, :position, :look_at def changed? orientation_changed? || position || look_at end def orientation_changed? right || up || view end def js_lookat(name) result = "" result.concat "#{name}.setPosition([#{position.join(",")}]);" if (position) result.concat "#{name}.lookAt([#{look_at.join(",")}]);" if look_at result end def js_orient(name) orientation = [view || "#{name}.getView()", up || "#{name}.getUp()", right || "#{name}.getRight()", position || "#{name}.getPosition()"] orientation.reject! { |c| c.nil? } orientation.collect! { |c| c.kind_of?(Array) ? "[#{c.join(",")}]" : c.to_s } "#{name}.orient(#{orientation.join(",")})" end end attr_reader :objects, :camera attr_accessor :scene delegate :<<, :to => :objects def initialize @objects = [] @camera = WebGL::World::Camera.new end def to_js js = "(function(){var world=new World();" if camera.orientation_changed? js.concat "#{camera.js_orient('world.camera')};" elsif camera.changed? js.concat "#{camera.js_lookat('world.camera')};" end if @scene js.concat "world.scene = (#{@scene.to_js});" end objects.each { |obj| js.concat "world.addObject(#{obj.to_js});" } # objects.each { |obj| js.concat obj.to_js("function(obj) { world.addObject(obj); }") } js.concat "return world;" js.concat "})()" js end end
true
8bcee7742351f2dd12d38eb1cffc083b6efad925
Ruby
adamamo17/nfl_app
/spec/models/coach_spec.rb
UTF-8
3,094
2.765625
3
[]
no_license
# == Schema Information # # Table name: coaches # # id :integer not null, primary key # name :string(255) # team :string(255) # created_at :datetime not null # updated_at :datetime not null # password_digest :string(255) # require 'spec_helper' describe Coach do before { @coach = Coach.new(name: "Andrew.Carnegie", team: "Silicon Valley Programmers", password: "footballrules", password_confirmation: "footballrules") } subject { @coach } # allows us to imply @coach is the variable for all tests it { should respond_to(:name) } it { should respond_to(:team) } it { should respond_to(:password_digest) } it { should respond_to(:password) } it { should respond_to(:password_confirmation) } it { should respond_to(:authenticate) } it { should be_valid } describe "when name is not present" do before { @coach.name = " " } it { should_not be_valid } end describe "when team is not present" do before { @coach.team = " " } it { should_not be_valid } end #Name describe "when name is too long" do before { @coach.name = "a" * 51 } it { should_not be_valid } end describe "when name format is invalid" do it "should be invalid" do names = %w[andrew.carnegie Andrew.carnegie andrew.Carnegie "Andrew Carnegie"] names.each do |invalid_name| @coach.name = invalid_name @coach.should_not be_valid end end end describe "when name format is valid" do it "should be valid" do names = %w[Andrew.Carnegie Andrew.Mellon Robert.Mellon] names.each do |valid_name| @coach.name = valid_name @coach.should be_valid end end end describe "when name is already taken" do before do user_with_same_name = @coach.dup user_with_same_name.save end it { should_not be_valid } end #Password describe "when password is not present" do before { @coach.password = @coach.password_confirmation = " " } it { should_not be_valid } end describe "when password doesn't match confirmation" do before { @coach.password_confirmation = "mismatch" } it { should_not be_valid } end describe "when password confirmation is nil" do before { @coach.password_confirmation = nil } it { should_not be_valid } end #Authentication describe "with a password that's too short" do before { @coach.password = @coach.password_confirmation = "a" * 5 } it { should be_invalid } end describe "return value of authenticate method" do before { @coach.save } let(:found_coach) { Coach.find_by_name(@coach.name) } describe "with valid password" do it { should == found_coach.authenticate(@coach.password) } end describe "with invalid password" do let(:coach_for_invalid_password) { found_coach.authenticate("invalid") } it { should_not == coach_for_invalid_password } specify { coach_for_invalid_password.should be_false } end end end
true
909d27dff750bc9bdd869cf5b95c6a9759f65c47
Ruby
J-Michael-Brown/Anagrams-and-Antigrams
/lib/seporite_methods.rb
UTF-8
1,256
3.515625
4
[ "MIT" ]
permissive
require('Grammable') def for_each_grammable(input_word, *statements) # found 'reject(&:empty?)' logic on stack overflow by Matt Greer @https://stackoverflow.com/questions/5878697/how-do-i-remove-blank-elements-from-an-array for_word = input_word.split(/\W/).reject(&:empty?).join check_words = [] statements.each do |statement| words = statement.split(" ").reject(&:empty?) words.each do |word| check_words.push(word.split(/\W/).reject(&:empty?).join) end end results = [] check = Grammable.new(for_word) check_words.each do |check_word| check.change_second(check_word) if !check.words? results.push("not a word") elsif check.anagram? double_check = ["anagram"] if check.palindrome? double_check.push(", also words make palindrome: "+ check.palindrome?.join(" and ")) end results.push(double_check.join) elsif check.antigram? results.push("antigram") elsif check.palindrome? results.push("words make palindrome: "+ check.palindrome?.join(" and ")) else overlap = check.letter_match results.push("'#{for_word}' and '#{check_word}' aren't anagrams but #{overlap.length} letter(s) match: #{overlap.join(", ")}.") end end results end
true
48df426cc6d46279c70289e7981f3dcfa00f9d9e
Ruby
eli-zbth/DL_Fundamentos_Ruby
/02_Ciclos_y_metodos/01_desafios/solo_pares2.rb
UTF-8
158
2.875
3
[]
no_license
tope = ARGV[0].to_i i =1 mostrados=0 res="" while (mostrados<tope) if i%2 ==0 res=res+ " #{i}" mostrados +=1 end i+=1 end res[0]="" print res+"\n"
true
5228e137d3ae41be21ce0bb6c58291277ad63731
Ruby
aman29april/Hatchways-Blog
/app/services/post_sort_transformer.rb
UTF-8
365
2.984375
3
[]
no_license
class PostSortTransformer def initialize(sort_by:, direction:) # default sort by 'id' and direction is asc @sort_by = sort_by || 'id' @is_desc = direction == 'desc' end def transform(data) sort(data) end private def sort(data) response = data.sort_by { |post| post[@sort_by] } @is_desc ? response.reverse : response end end
true
d9333baa800d66518afc2ed5c03c2a84ce41c3ec
Ruby
zitom4/prct08
/spec/matrices_spec.rb
UTF-8
1,918
3.140625
3
[]
no_license
require './lib/matrices.rb' require '/home/alu4101/datos/homes.rala/LPP/prct07/lib/fraccion.rb' describe Matriz do before :each do @M1 = Matriz.new(2,2) @M1[0] = [1,1] @M1[1] = [2,2] @M2 = Matriz.new(2,2) @M2[0] = [1,1] @M2[1] = [2,2] #### PRACTICA #### @F1=Fraccion.new(1,2) @F2=Fraccion.new(1,3) @F3=Fraccion.new(1,4) @F4=Fraccion.new(1,5) @F5=Fraccion.new(2,3) @F6=Fraccion.new(3,4) @F7=Fraccion.new(4,5) @R1=Fraccion.new(1,1) @R2=Fraccion.new(3,5) @R3=Fraccion.new(11,40) @R4=Fraccion.new(49,150) @MP1 = Matriz.new(2,2) @MP1[0]=[@F1,@F2] @MP1[1]=[@F3,@F4] @MP2 = Matriz.new(2,2) @MP2[0]=[@F1,@F5] @MP2[1]=[@F6,@F7] @RESSUM = Matriz.new(2,2) @RESSUM[0]=[@R1,@R1] @RESSUM[1]=[@R1,@R1] @RESMUL = Matriz.new(2,2) @RESMUL[0]=[@F1,@R2] @RESMUL[1]=[@R3,@R4] end # describe " Almacenamiento de variables" do # # it " Almacen de filas " do # @M1.fil # end # # it "Almacen de columnas" do # @M1.col # end # # it " Funciona el to_s" do # @M1.to_s.should eq "1 1 \n 2 2 \n " # end # end # # # #### OPERACIONES ARITMETICAS TESTEADAS #### # describe " Operaciones con matrices" do # # it " Suma de matrices " do # (@M1 + @M2).to_s.should eq "2 2 \n 4 4 \n " # end # # it " Multiplicacion de matrices " do # (@M1 * @M2).to_s.should eq "2 2 \n 8 8 \n " # end # it "Resta de matrices" do # (@M1 - @M2).to_s.should eq "0 0 \n 0 0 \n " # end # end # ##### OPERACIONES PRACTICA ######## describe " Operaciones practica " do it " Suma de matrices " do (@MP1 + @MP2) == @RESSUM end it " Multiplicacion " do (@MP1 * @MP2).to_s.should eq " "# == @RESMUL end end
true
c8e6801601bc3d7cb32c8bcae5fd1b854a4a9b7f
Ruby
usman-tahir/rubyeuler
/neweuler10.rb
UTF-8
254
3.71875
4
[]
no_license
# http://projecteuler.net/problem=10 require 'prime' def sum_of_primes_below(number) accumulator_array =[] Prime.each(number) do |prime| accumulator_array << prime end accumulator_array.inject(:+) end puts sum_of_primes_below(2_000_000)
true
c2591fd048b47ac0f351f8ba5aebafa1e7b3c1c1
Ruby
mikey-roberts/bowling-challenge-ruby
/lib/rules.rb
UTF-8
643
3.046875
3
[]
no_license
module Rules MAXIMUM_FRAMES = 10 MAXIMUM_PINS = 10 MAXIMUM_THROW = 10 # Throw Validation def strike? first_throw == MAXIMUM_PINS end def spare? first_throw + second_throw = MAXIMUM_PINS end def pins_hit? both_throws != 0 end def gutter? both_throws == 0 end def both_throws first_throw + second_throw end # Max validation def single_turn_valid(bowl) bowl <= MAXIMUM_PINS end def both_turns_valid both_throws <= MAXIMUM_PINS end def max_throw MAXIMUM_THROW end def max_frames MAXIMUM_FRAMES end def max_pins MAXIMUM_PINS end end
true
c86955eecdce5661cafd3d4786a565b174b1c9a1
Ruby
stupendousC/dijkstra
/lib/dijkstra.rb
UTF-8
3,247
3.484375
3
[]
no_license
##### I'M LEAVING IN MY PRINT STATEMENTS BC IT HELPS ME REMEMBER WHY I DID WHAT I DID... def dijkstra(adjacency_matrix, start_node) puts "==============\nADJACENCY MATRIX" adjacency_matrix.each do |r| p r end puts "==============\n\n" #int nVertices = adjacencyMatrix[0].length; num_nodes = adjacency_matrix.length # shortest_distances will hold the shortest distances from start_node to i # it starts with infinity as the value shortest_distances = Array.new(num_nodes, Float::INFINITY) immedParent = Array.new(num_nodes, nil) visited = Array.new(num_nodes, false) # set up for the starter node visited[start_node] = true immedParent[start_node] = nil shortest_distances[start_node] = 0 currNode = start_node processCurrNode(adjacency_matrix[currNode], currNode, shortest_distances, immedParent, visited) while keepVisiting(visited) puts "keep visiting!" currNode = getNextToVisit(visited, shortest_distances) if !currNode # ran out of available next neighbors, but we haven't visited almost everyone (only 1 is allowed to be unvisited) yet! break end visited[currNode] = true processCurrNode(adjacency_matrix[currNode], currNode, shortest_distances, immedParent, visited) end puts "GRAND FINALE" puts "\tvisited = #{visited.inspect}" puts "\timmedParent = #{immedParent.inspect}" puts "\tshortestDistances = #{shortest_distances.inspect}\n" answer = { start_node: start_node, parent_list: immedParent, shortest_distances: shortest_distances } return answer end def keepVisiting(visited) return visited.count(false) != 1 end def getNextToVisit(visited, shortest_distances) shortest = Float::INFINITY winner = nil visited.each_with_index do |visitedStatus, i| puts "looking at... visitedStatus=#{visitedStatus} for node #{i}" if visitedStatus == false && shortest_distances[i] < shortest winner = i shortest = shortest_distances[i] end end if winner puts "\nNext up is... node #{winner}, it's distance is #{shortest}\n" return winner else return nil end end def processCurrNode(currNodesDistances, currNode, shortest_distances, immedParent, visited) puts "Processing... #{currNodesDistances.inspect}" currNodesDistances.each_with_index do |distance, destinationNode| puts "looking at #{distance} for nodeIndex #{destinationNode}" if visited[destinationNode] # puts "already visited this node, including self" next elsif distance == 0 # puts "this node is defined as not reachable" next else # puts "is this new distance shorter?" recordedSD = shortest_distances[destinationNode] prevLeg = shortest_distances[currNode] currDistance = distance + prevLeg if currDistance < recordedSD puts "\tfound a shorter distance!" shortest_distances[destinationNode] = currDistance immedParent[destinationNode] = currNode end end end puts "Ended with..." puts "\tvisited = #{visited.inspect}" puts "\timmedParent = #{immedParent.inspect}" puts "\tshortestDistances = #{shortest_distances.inspect}\n" end
true
6998e2f607c5d9d518f4cc8517c3777c329aeaca
Ruby
sebaureta/E6CP2A1
/3 strings/ejercicio2.rb
UTF-8
458
4.125
4
[]
no_license
# Construir un arreglo de los nombres de todos sus compañeros y en base a él: # 1. Imprimir todos los elementos que excedan más de 5 caracteres. # 2. Crear un arreglo nuevo con todos los elementos en minúscula. # 3. Crear un método que devuelva un arreglo con la cantidad de caracteres que tiene cada nombre. mates = %w[Ale Adrian Fabian Enrique Sebastian Fio] mates.each do |i| puts i if i.length > 5 end minus = [] mates.each do |i| i.downcase! minus << i end p minus
true
52d771f5c6f524619cb7805040da319c1ebfba80
Ruby
Napwob/Ruby-Temperature-Converter
/spec/states/second_scale_spec.rb
UTF-8
2,005
2.796875
3
[]
no_license
# frozen_string_literal: true require_relative './../../src/states/read_second_scale' require_relative './../../src/states/read_value' require_relative './../../src/io_adapter' describe States::ReadSecondScale do let(:adapter) { double 'IO_Adapter' } before do allow(IO_Adapter).to receive(:instance).and_return(adapter) allow(adapter).to receive(:write) end describe '#execute' do it 'execute correct sentence' do subject.execute expect(adapter).to have_received(:write).with('Please, enter second convertation scale(C, F, K)') end end describe '#next' do subject { described_class.new(first_scale: 'K').next } before { allow(adapter).to receive(:read).and_return(value) } context 'When the user enter right scale that equal to previous one' do let(:value) { 'K' } it { is_expected.to be_a(States::ReadSecondScale) } it 'execution error' do subject expect(adapter).to have_received(:write).with('Second convertation scale must not be the same as first one "K"') end end context 'When the user enter right scale that equal to previous one but low char' do let(:value) { 'k' } it { is_expected.to be_a(States::ReadSecondScale) } it 'execution error' do subject expect(adapter).to have_received(:write).with('Second convertation scale must not be the same as first one "K"') end end context 'When the user enter right scale' do let(:value) { 'C' } it { is_expected.to be_a(States::ReadValue) } end context 'When the user enter right low char scale' do let(:value) { 'c' } it { is_expected.to be_a(States::ReadValue) } end context 'When the user dont enter scale' do let(:value) { 'U' } it { is_expected.to be_a(States::ReadSecondScale) } it 'execution error' do subject expect(adapter).to have_received(:write).with('U is not conversation scale') end end end end
true
3280c32454c63d9f7ffd47da983b34404ad8848a
Ruby
AlejandroDeheza/TADP-TP
/ruby/lib/prueba.rb
UTF-8
5,759
2.71875
3
[]
no_license
class Prueba def materia :tadp end end #estaba en "ObjetoPersistible" =begin # define metodos y accesors para las clases persistibles def self.included(clase) clase.singleton_class.send(:attr_reader, :atributos_persistibles) clase.singleton_class.send(:attr_accessor, :tabla) end =end # estaba en "ClasePersistible" #def definir_getter(named) # send(:define_method, named) do # obj.instance_variable_set("@#{named.to_s}".to_sym, []) # end #end # estaba en "ORM" <<<<<<<<<<<<< #modulo.class_eval do # def initialize # inicializar_atributos_has_many # super # end #end # Hace lo mismo que arriba #modulo.send(:define_method, :initialize) do # inicializar_has_many # super() #end # Hace lo mismo que arriba #modulo.define_singleton_method(:initialize) do # inicializar_has_many # super() #end # estaba en ORM #modulo.incluye_orm = true # =begin class Module attr_accessor :incluye_orm def modulos_hijos @modulos_hijos ||= [] end def included(modulo) if @incluye_orm ORM::entregar_dependecias(modulo) modulos_hijos.push(modulo) end end end class Class def inherited(clase) if @incluye_orm clase.incluye_orm = true modulos_hijos.push(clase) end end end =end # estaba en AdministradorDeTabla =begin def analizar_ancestros ancestros = [] ancestors.each do |ancestro| break if ancestro == ORM ancestros.push(ancestro) if ancestro.is_a?(EntidadPersistible) end ancestros.delete_at(0) agregar_atributos_de_ancestros(ancestros) if ancestros.size > 0 self end def agregar_atributos_de_ancestros(ancestros) ancestros.reverse! atr_persistibles_original = atributos_persistibles.clone atr_has_many_original = atributos_has_many.clone ancestros.each { |modulo| agregar_atributos_de(modulo.atributos_persistibles, modulo.atributos_has_many) } agregar_atributos_de(atr_persistibles_original, atr_has_many_original) atributos_has_many = self.atributos_has_many.uniq self end def agregar_atributos_de(hash_atributos, atributos_has_many) hash_atributos.each do |nombre, tipo| if atributos_has_many.include?(nombre) has_many(tipo, named: nombre) else has_one(tipo, named: nombre) end end self end =end # estaba en ValidadorAtributos =begin class ValidadorAtributos include Util def initialize(params, tipo) @params = params @tipo_atributo = tipo end def validar(valor, nombre_clase_error) validar_no_blank(valor, nombre_clase_error) if @params[:no_blank] unless valor.nil? validar_tipo(valor, nombre_clase_error) validar_block_validate(valor, nombre_clase_error) if @params[:validate] if @tipo_atributo <= Numeric validar_from(valor, nombre_clase_error) if @params[:from] validar_to(valor, nombre_clase_error) if @params[:to] end end self end def validar_no_blank(valor, nombre_clase_error) if valor.nil? || valor == "" raise NoBlankError.new(nombre_clase_error, @params[:named]) end self end def validar_tipo(valor, nombre_clase_error) if valor.is_a?(InstanciaPersistible) valor.validate! elsif es_tipo_primitivo(@tipo_atributo) && !(valor.class <= @tipo_atributo) || !es_tipo_primitivo(@tipo_atributo) raise TipoDeDatoError.new(nombre_clase_error, @params[:named], @tipo_atributo) end self end def validar_from(valor, nombre_clase_error) if @params[:from] > valor raise FromError.new(nombre_clase_error, @params[:named], @params[:from]) end self end def validar_to(valor, nombre_clase_error) if @params[:to] < valor raise ToError.new(nombre_clase_error, @params[:named], @params[:to]) end self end def validar_block_validate(valor, nombre_clase_error) unless valor.instance_eval(&@params[:validate]) raise BlockError.new(nombre_clase_error, @params[:named], @params[:validate]) end self end end =end #estaba en ValidadorAtributos # =begin class CompositeValidator def initialize(validadores_proc) @validadores = validadores_proc end def call(valor, clase) @validadores.each { |v| v.call(valor, clase) } end end class ValidatorsBuilder extend Util def self.build(tipo_atributo, params) validators = [] validators.push(no_blank(params[:named])) if params[:no_blank] validators.push(validar_tipo(tipo_atributo, params[:named])) validators.push(validar_from(params[:from], params[:named])) if params[:from] validators.push(validar_to(params[:to], params[:named])) if params[:to] validators.push(validar_block_validate(params[:validate], params[:named])) if params[:validate] CompositeValidator.new(validators) end def self.no_blank(nombre_atr) proc { |v, clase| raise NoBlankError.new(clase, nombre_atr) unless !v.nil? && v != "" } end def self.validar_tipo(tipo_atributo, nombre_atr) proc do |v, clase| if v.is_a?(InstanciaPersistible) v.validate! elsif !v.nil? && es_tipo_primitivo(tipo_atributo) && !(v.class <= tipo_atributo) || !v.nil? && !es_tipo_primitivo(tipo_atributo) raise TipoDeDatoError.new(clase, nombre_atr, tipo_atributo) end end end def self.validar_from(from, nombre_atr) proc { |v, clase| raise FromError.new(clase, nombre_atr, from) unless !v.nil? && v.class <= Numeric && from < v } end def self.validar_to(to, nombre_atr) proc { |v, clase| raise ToError.new(clase, nombre_atr, to) unless !v.nil? && v.class <= Numeric && to > v } end def self.validar_block_validate(block, nombre_atr) proc { |v, clase| raise BlockError.new(clase, nombre_atr, block) unless !v.nil? && v.instance_eval(&block)} end end =end #estaba en Excepciones
true
a646b924b31ee8f793997a337d5f461870dd7924
Ruby
Andriamanitra/adventofcode2020
/day02/fun.rb
UTF-8
1,105
3.28125
3
[]
no_license
# Let's try to solve it with ONLY regex! # I'm not happy with using MatchData#captures -method # because it returns an ARRAY(!) which is CLEARLY # NOT REGEX. But this is the best I have come up # with so far... input = ARGF.read def puts(x) STDOUT.puts Time.now.strftime("[%a %H:%M:%S.%L] #{x}") end line = /(\d+)-(\d+) (.):(.+)/ passwords = input.gsub(line, '\4') # Part 1 - This will take literal years to run with full input, # but it works perfectly in theory! # Either comment this part out or run with something like: # $ head -n20 input.txt | ruby fun.rb re = input.gsub(line, '(?:^((?:[^\3]*\3){\1,\2}[^\3]*$)|(?:.*$))') puts "Part 1 (re.length = #{re.length})" valid1 = Regexp.new(re) valid_passwords = passwords.match(valid1).captures - [nil] puts valid_passwords.size # Part 2 - This one is fast (should only take milliseconds) re = input.gsub(line, '(?:^(?=.{\1}\3)(?=.{\2}[^\3])(.*)$|^(?=.{\2}\3)(?=.{\1}[^\3])(.*)$|(?:.*$))') puts "Part 2 (re.length = #{re.length})" valid2 = Regexp.new(re) valid_passwords = passwords.match(valid2).captures - [nil] puts valid_passwords.size
true
a3c63795d9d49bde6785ab1d441569866014f8de
Ruby
thestoneage/isaak
/lib/universe.rb
UTF-8
1,112
3.15625
3
[]
no_license
class Universe attr_reader :width, :height, :things def initialize(width, height, gravity) @things = [] @width = width @height = height @border = true @gravity = gravity end def update @things.each do |thing| if @border bounce(thing) end mutual_gravity(thing) thing.add_force(@gravity * thing.mass) thing.update end end def mutual_gravity(thing) @things.each do |otherthing| if thing != otherthing thing.add_force(otherthing.gravity_force(thing)) end end end def bounce(thing) if thing.loc.x < 0 + thing.radius thing.loc.x = 0 + thing.radius thing.vel.x *= -1 * thing.elastic elsif thing.loc.x > @width - thing.radius thing.loc.x = @width - thing.radius thing.vel.x *= -1 * thing.elastic end if thing.loc.y < 0 + thing.radius thing.loc.y = 0 + thing.radius thing.vel.y *= -1 * thing.elastic elsif thing.loc.y > @height - thing.radius thing.loc.y = @height - thing.radius thing.vel.y *= -1 * thing.elastic end end end
true
56b0d246991725d5800fe534ba9d1ca56a8ac862
Ruby
brady-robinson/ls-rb101
/small_problems/medium2-10.rb
UTF-8
1,149
4.4375
4
[]
no_license
# problem: write a method that employs bubble sort algorithm # data: array # input: array # output: sorted array! # alg: # - this is going to need a nested loop # - initialize a variable that will change when any two integers are swapped # - initialize a count variable # - start a loop # - in the outer loop, before inner loop, break if change variable is 0 # - start inner loop # - break if count equals array size # - compare element count and count plus one # - when result is 1, swap elements # - if swap elements, add one to change variable # - add one to count # - back in outer loop, reset the count to 0 # - return the sorted array def bubble_sort!(array) change_variable = 0 count = 0 loop do loop do break if count >= array.size if (array[count] <=> array[count + 1]) == 1 array[count], array[count + 1] = array[count + 1], array[count] change_variable += 1 end count += 1 end break if change_variable == 0 count = 0 change_variable = 0 end array end array = %w(Sue Pete Alice Tyler Rachel Kim Bonnie) bubble_sort!(array) p array == %w(Alice Bonnie Kim Pete Rachel Sue Tyler)
true
17b1b0216065d26d7470d570b2da9ec32e95c3d0
Ruby
sergii/daily-ruby-tips
/114/struct_block.rb
UTF-8
1,224
4.75
5
[]
no_license
# Ruby inheritance is pretty cool, and today's we look at how sub classing a Struct object # and using the Struct block can return the same result. # A normal struct object doesnt have a very pretty output Park = Struct.new(:location, :capacity) cp = Park.new("Central Park", "1,200,000") puts cp #=> #<struct Park location="Central Park", capacity="1,200,000"> # By creating a method on the Park class # we can make this much prettier Boardwalk = Struct.new(:location, :capacity) class Boardwalk def to_s "#{self.location} can hold #{self.capacity} people." end end vb = Boardwalk.new("Venice Beach", "200,000") puts vb #=> Venice Beach can hold 200,000 people. # We can inherit the Struct and reduce our code class Mall < Struct.new(:location, :capacity) def to_s "#{self.location} can hold #{self.capacity} people." end end moa = Mall.new("Mall of America", "300,000") puts moa #=> Mall of America can hold 300,000 people. # BUT the cool thing about Struct is it takes a block Beach = Struct.new(:location, :capacity) do def to_s "#{self.location} can hold #{self.capacity} people." end end mb = Beach.new("Manhattan Beach", "25,000") puts mb #=> Manhattan Beach can hold 25,000 people.
true
db6495da7f4e6ea2c9a79f6d7f12653a7a21237e
Ruby
aellonk/ttt-3-display_board-example-v-000
/lib/display_board.rb
UTF-8
299
3.265625
3
[]
no_license
# Define a method display_board that prints a 3x3 Tic Tac Toe Board def display_board cell = " " cell_divider = "|" row = cell + cell_divider + cell + cell_divider + cell row_divider = "-----------" puts row puts row_divider puts row puts row_divider puts row end display_board
true
a9e0a37f217c0f281965516b6a2c18301f0f0f3a
Ruby
bentrevor/game-of-life
/run.rb
UTF-8
488
3.140625
3
[]
no_license
require './lib/cells' require './lib/game' n = 120**2 random_grid = Array.new n n.times do |i| random_grid[i] = [0,1].sample end game = Game.new random_grid def show(game) grid = game.cells.grid grid.each_with_index do |cell, index| char = if cell == 0 ' ' else '@' end if index % game.cells.width == 0 char << "\n" end print char end end loop do system 'clear' show(game) game.next_generation end
true
9ab6924cdf6ad6b9c30a82993d03ff75859e1bac
Ruby
rajat-11223/aprroveforme
/spec/support/stripe_helpers.rb
UTF-8
468
2.5625
3
[]
no_license
module StripeHelpers def fill_stripe_element(card, exp, cvc, postal='') card_iframe = all('iframe')[0] within_frame card_iframe do fill_by_char card, find_field('cardnumber') fill_by_char exp, find_field('exp-date') fill_by_char cvc, find_field('cvc') fill_by_char postal, find_field('postal') end end private def fill_by_char(text, field) text.chars.each do |piece| field.send_keys(piece) end end end
true
03218a1ef18dbc79b61b9df8593c9196c7758d2a
Ruby
kbutkus/fibanocci
/Fibonacci.rb
UTF-8
598
3.90625
4
[]
no_license
def iterative_fib(number) array = [] counter = number a = 0 b = 1 c = 0 print "#{a}, " until counter == 0 c = a + b a = b b = c print "#{c}, " counter = counter - 1 end puts end @array = [0,1] def recursive_fib(number) return number if number < 2 @array[number] = recursive_fib(number - 1) + recursive_fib(number - 2) end # n = 35 # puts "#{n}'s fibonacci value is #{recursive_fib(n)}" # puts iterative_fib(n) require 'benchmark' num = 35 Benchmark.bm do |x| x.report("recursive_fib") { recursive_fib(num) } x.report("iterative_fib") { iterative_fib(num) } end
true
442c918a15ae20a506c971e673ee089cd5081a00
Ruby
kcin46/CMSC498JPageRank
/SubredditInfo.rb
UTF-8
206
2.890625
3
[]
no_license
class SubredditInfo attr_accessor "name" , "posts", "posts_map" def initialize(name, posts) @name = name @posts = posts @posts_map = Hash.new () end def add_post(link) @posts << link end end
true
9b64eaefe3c2f63bd38adee57660c2925972a9ff
Ruby
jihao/ruby_scripts_for_fun
/meta_programming/meta/meta_test.rb
UTF-8
1,436
3.046875
3
[]
no_license
#!/usr/bin/env ruby -wKU require 'test/unit' class C def self.metaclass # C.singleton_class class << self;self;end end def self.class_method puts "class_method defined in C.metaclass = #{self.metaclass}" end def metaclass # C.new.singleton_class class << self;self;end end end class MetaTest < Test::Unit::TestCase def test_metaclass puts "C.metaclass = #{C.metaclass}; \r\nC.singleton_class = #{C.singleton_class}" puts "C.new.metaclass = #{C.new.metaclass};\r\nC.new.singleton_class = #{C.new.singleton_class}" puts end def test_metaclass_superclass # puts "C.metaclass = #{C.metaclass}; \r\nC.singleton_class = #{C.singleton_class}" # puts "C.new.metaclass = #{C.new.metaclass};\r\nC.new.singleton_class = #{C.new.singleton_class}" puts "C.new.metaclass.superclass = #{C.new.metaclass.superclass};" puts end def test_method_define C.class_method obj = C.new def obj.object_method puts "object_method in obj.metaclass = #{self.metaclass}" end obj.object_method puts end def test_method2 puts "C.metaclass.instance_methods: " puts C.metaclass.instance_methods false obj = C.new def obj.object_method puts "object_method in obj.metaclass = #{self.metaclass}" end puts "obj(C.new).metaclass.instance_methods: " puts obj.metaclass.instance_methods false puts end end
true
027397c8501a31d17fe45cfdbbc0c68bb3693f76
Ruby
Banzar/rubycode
/rand.rb
UTF-8
106
3.59375
4
[]
no_license
# rand.rb # Randoms in ruby elg = rand(100) puts "I have " + elg.to_s() + " apples in my apple tree!"
true
a4de2fd329e2ecbbaba9217e48d3f70a61bd8805
Ruby
h-shima/rbs
/lib/rbs/json_schema/generator.rb
UTF-8
13,074
2.71875
3
[ "BSD-2-Clause", "Ruby" ]
permissive
require "json" require "uri" require "rbs/json_schema/validation_error" module RBS module JSONSchema class Generator attr_reader :stringify_keys attr_reader :output attr_reader :stdout attr_reader :stderr attr_reader :path_decls attr_reader :generated_schemas # Alias declarations for easier referencing Alias = RBS::AST::Declarations::Alias def initialize(stringify_keys:, output:, stdout:, stderr:) @stringify_keys = stringify_keys @output = output @stdout = stdout @stderr = stderr @path_decls = {} @generated_schemas = {} end # IMPORTANT: Function invoked to generate RBS from JSON schema # Generates RBS from JSON schema after validating options & writes to file/STDOUT def generate(uri) # Validate options received from CLI validate_options() @path_decls[uri.path] ||= RBS::AST::Declarations::Module.new( name: generate_type_name_for_uri(uri, module_name: true), type_params: AST::Declarations::ModuleTypeParams.empty, members: [], self_types: [], annotations: [], location: nil, comment: nil ) generate_rbs(uri, read_from_uri(uri)) end # IMPORTANT: Function used to generate AST alias declarations from a URI & a schema document def generate_rbs(uri, document) # If schema is already generated for a URI, do not re-generate declarations/types if fragment = uri.fragment # return if fragment.empty? # If fragment is empty, implies top level schema which is always generated since it is the starting point of the algorithm if @generated_schemas.dig(uri.path, fragment.empty? ? "#" : fragment) # Check if types have been generated for a particular path & fragment return end else if @generated_schemas.dig(uri.path, "#") # Check if types have been generated for a particular path return end end unless document.is_a?(Hash) raise ValidationError.new(message: "Invalid JSON Schema: #{document}") end @generated_schemas[uri.path] ||= {} if fragment = uri.fragment @generated_schemas[uri.path][fragment.empty? ? "#" : fragment] = true else @generated_schemas[uri.path]["#"] = true end # Parse & generate declarations from remaining schema content decl = Alias.new( name: generate_type_name_for_uri(uri), # Normal type name with no prefix type: translate_type(uri, document), # Obtain type of alias by parsing the schema document annotations: [], location: nil, comment: nil ) # Append the declaration if & only if the declaration has a valid RBS::Type assigned if @path_decls[uri.path] @path_decls[uri.path].members << decl if !decl.type.nil? else @path_decls[uri.path] = RBS::AST::Declarations::Module.new( name: generate_type_name_for_uri(uri, module_name: true), type_params: AST::Declarations::ModuleTypeParams.empty, members: [], self_types: [], annotations: [], location: nil, comment: nil ) @path_decls[uri.path].members << decl if !decl.type.nil? end end def literal_type(literal) # Assign literal type case literal when String, Integer, TrueClass, FalseClass Types::Literal.new(literal: literal, location: nil) when nil Types::Bases::Nil.new(location: nil) else raise ValidationError.new(message: "Unresolved literal found: #{literal}") end end def untyped_type Types::Bases::Any.new(location: nil) end # Parse JSON schema & return the `RBS::Types` to be assigned def translate_type(uri, schema) case when values = schema["enum"] unless values.is_a?(Array) raise ValidationError.new(message: "Invalid JSON Schema: enum: #{values}") end types = values.map { |literal| literal_type(literal) } Types::Union.new(types: types, location: nil) when const = schema["const"] literal_type(const) when schema["type"] == "array" || schema.key?("items") case when schema["items"].is_a?(Array) # tuple types = schema["items"].map { |definition| translate_type(uri, definition) } Types::Tuple.new(types: types, location: nil) when schema["items"].is_a?(Hash) # array elem_type = translate_type(uri, schema["items"]) BuiltinNames::Array.instance_type(elem_type) else BuiltinNames::Array.instance_type(untyped_type) end when schema["type"] == "object" || schema.key?("properties") || schema.key?("additionalProperties") case when properties = schema["properties"] fields = properties.each.with_object({}) do |pair, hash| key, value = pair unless stringify_keys key = key.to_sym end hash[key] = translate_type(uri, value) end Types::Record.new(fields: fields, location: nil) when prop = schema["additionalProperties"] BuiltinNames::Hash.instance_type( BuiltinNames::String.instance_type, translate_type(uri, prop) ) else BuiltinNames::Hash.instance_type( BuiltinNames::String.instance_type, untyped_type ) end when one_of = schema["oneOf"] Types::Union.new( types: one_of.map { |defn| translate_type(uri, defn) }, location: nil ) when all_of = schema["allOf"] Types::Intersection.new( types: all_of.map { |defn| translate_type(uri, defn) }, location: nil ) when ty = schema["type"] case ty when "integer" BuiltinNames::Integer.instance_type when "number" BuiltinNames::Numeric.instance_type when "string" BuiltinNames::String.instance_type when "boolean" Types::Bases::Bool.new(location: nil) when "null" Types::Bases::Nil.new(location: nil) else raise ValidationError.new(message: "Invalid JSON Schema: type: #{ty}") end when ref = schema["$ref"] ref_uri = begin # Parse URI of `$ref` URI.parse(schema["$ref"]) rescue URI::InvalidURIError => _ raise ValidationError.new(message: "Invalid URI encountered in: $ref = #{ref}") end resolved_uri = resolve_uri(uri, ref_uri) # Resolve `$ref` URI with respect to current URI # Generate AST::Declarations::Alias generate_rbs(resolved_uri, read_from_uri(resolved_uri)) # Assign alias type with appropriate namespace Types::Alias.new( name: generate_type_name_for_uri(resolved_uri, namespace: resolved_uri.path != uri.path), location: nil ) else raise ValidationError.new(message: "Invalid JSON Schema: #{schema.keys.join(", ")}") end end # Read contents from a URI def read_from_uri(uri) # Initial value schema = nil dup_uri = uri.dup # Duplicate the URI for processing dup_uri.fragment = nil # Remove fragment for reading from URI case uri.scheme # File (or) Generic implies a local file when "file", nil # Read local file using `File` module schema = File.read(uri.path) # HTTP/HTTPS implies a remote file when "http", "https" # Read remote file using Net::HTTP schema = Net::HTTP.get(dup_uri) # Unsupported URI scheme else raise ValidationError.new(message: "Could not read content from URI: #{uri}") end begin # Obtain schema in RUBY's Hash data structure by parsing file content schema = JSON.parse(schema) rescue JSON::ParserError, TypeError => e # Print error message for invalid JSON content raise ValidationError.new(message: "Invalid JSON content!\n#{e.full_message}") end dup_uri.fragment = uri.fragment # Re-assign fragment # Check if fragment exists for that URI if dup_uri.fragment # If it is an empty fragment, i.e, `#` then return the original schema return schema if dup_uri.fragment.empty? dup_uri.fragment.slice!(0) if dup_uri.fragment.chr == "/" # Remove initial slash to avoid empty entries while splitting dig_arr = dup_uri.fragment.split("/") # Split the fragment string on `/` e.g, #/definitions/member => [definitions, member] # Scan hash for the required key & if found return the corresponding schema document if (json_schema = __skip__ = schema.dig(*dig_arr)) return json_schema # If key not found, raise an error else raise ValidationError.new(message: "Could not find schema defined for: ##{uri.fragment}") end end schema end # Write output using `RBS::Writer` to a particular `IO` def write_output # If an output directory is given, open a file & write to it if output = self.output @path_decls.each do |path, decls| name = snake_case(decls.name.name.to_s.dup) file_path = File.join(output, "#{name}.rbs") File.open(file_path, 'w') do |io| stdout.puts "Writing output to file: #{file_path}" RBS::Writer.new(out: io).write([decls]) end end # If no output directory is given write to STDOUT else RBS::Writer.new(out: stdout).write(@path_decls.values) end end # Utility function to assign type name from URI private def generate_type_name_for_uri(uri, module_name: false, namespace: false) dup_uri = uri.dup # Duplicate URI object for processing path = dup_uri.path.split("/").last or raise # Extract path path.gsub!(/(.json$)?/, '') # Remove JSON file extension if found prefix = camel_case(path) # prefix is used to write module name, hence converted to camel case # Return module_name if module_name return TypeName.new( name: prefix.to_sym, namespace: Namespace.empty ) end name = :t if dup_uri.fragment && !dup_uri.fragment.empty? dup_uri.fragment.slice!(0) if dup_uri.fragment.chr == "/" # Remove initial slash if present in fragment name = dup_uri.fragment.downcase.split("/").join("_") # Build a type alias compatible name end # Return type name for type alias TypeName.new( name: name.to_sym, namespace: namespace ? Namespace.new(path: [prefix.to_sym], absolute: false) : Namespace.empty ) end # Returns type name with prefixes & appropriate namespace private def type_name(name, absolute: nil) TypeName.new( name: name.to_sym, namespace: absolute ? Namespace.root : Namespace.empty ) end # Utility function to resolve two URIs private def resolve_uri(uri, ref_uri) begin # Attempt to merge the two URIs uri + ref_uri rescue URI::BadURIError, ArgumentError => _ # Raise error in case of invalid URI raise ValidationError.new(message: "Could not resolve URI: #{uri} + #{ref_uri}") end end # Utility function to convert a string to snake_case # Implementation derived from ActiveSupport::Inflector#parameterize method private def snake_case(string) string.gsub!(/[^a-z0-9_]+/i, '_') string.gsub!(/_{2,}/, '_') string.gsub!(/^_|_$/i, '') string.downcase! string end # Utility function to convert a string to camel_case # Implementation derived from ActiveSupport::Inflector#camelize method private def camel_case(string) string = snake_case(string).sub(/^[a-z\d]*/) { |match| match.capitalize } string.gsub!(/(.*?)_([a-zA-Z])/) { "#{$1}#{$2.capitalize}" } string end # Validate options given to the CLI private def validate_options if output = self.output path = Pathname(output) # Check if a valid directory exists? raise ValidationError.new(message: "#{output}: Directory not found!") if !path.directory? end end end end end
true
4ed495fb151bafc093987e4e9d8093de5b963680
Ruby
johnvm914/object_oriented_ruby
/inheritance_example.rb
UTF-8
660
3.640625
4
[]
no_license
class Vehicle def initialize @speed = 0 @direction = 'north' end def brake @speed = 0 end def accelerate @speed += 10 end def turn(new_direction) @direction = new_direction end end class Car < Vehicle def initialize super @fuel = "regular" @make = "Fiat" @model = "500" end def honk_horn puts "Beeeeeeep!" end end class Bike < Vehicle def initialize super @gears = 10 @type = "Cross Country" @weight = 50 end def ring_bell puts "Ring ring!" end end bike1 = Bike.new puts bike1.accelerate bike1.ring_bell car1 = Car.new puts car1.accelerate car1.honk_horn
true
9ed4280878a9c75450ad01be61088bfa98a85464
Ruby
henteko/review-and-css-typesetting
/articles/review-ext.rb
UTF-8
2,276
2.578125
3
[ "MIT" ]
permissive
# encoding: utf-8 ReVIEW::Compiler.defblock :imagetalkl, 1..2 ReVIEW::Compiler.defblock :imagetalkr, 1..2 ReVIEW::Compiler.defsingle :mycolumnbegin, 0 ReVIEW::Compiler.defsingle :mycolumnend, 0 ReVIEW::Compiler.defsingle :questionbegin, 0 ReVIEW::Compiler.defsingle :questionend, 0 ReVIEW::Compiler.defsingle :answerbegin, 0 ReVIEW::Compiler.defsingle :answerend, 0 ReVIEW::Compiler.defsingle :pagebreakforce, 0 class ReVIEW::HTMLBuilder def imagetalkl(lines, img_id, metric=nil) body = lines.map{|line| line + "<br />"} puts "<!--吹き出しはじまり-->" puts "<div class=\"balloon_l\">" puts " <div class=\"faceicon_l_bg\">" puts " <div class=\"faceicon_l\">" indepimage('', img_id) puts " </div>" puts " </div>" puts " <div class=\"chatting\">" puts " <div class=\"says_l\">" puts body puts " </div>" puts " </div>" puts "</div>" puts "<!--吹き出し終わり-->" end def imagetalkr(lines, img_id, metric=nil) body = lines.map{|line| line + "<br />"} puts "<!--吹き出しはじまり-->" puts "<div class=\"balloon_r\">" puts " <div class=\"faceicon_r_bg\">" puts " <div class=\"faceicon_r\">" indepimage('', img_id, '', metric) puts " </div>" puts " </div>" puts " <div class=\"chatting\">" puts " <div class=\"says_r\">" puts body puts " </div>" puts " </div>" puts "</div>" puts "<!--吹き出し終わり-->" end def mycolumnbegin puts "<!--コラムはじまり-->" puts "<div class=\"my-column\">" puts "<span class=\"my-column-title\">コラム</span>" end def mycolumnend puts "</div>" puts "<!--コラムおわり-->" end def questionbegin puts "<!--問題はじまり-->" puts "<div class=\"question\">" puts "<span class=\"question-title\">問題</span>" end def questionend puts "</div>" puts "<!--問題おわり-->" end def answerbegin puts "<!--答えはじまり-->" puts "<div class=\"answer\">" puts "<span class=\"answer-title\">答え</span>" end def answerend puts "</div>" puts "<!--答えおわり-->" end def pagebreakforce puts "<div class=\"page-bleak-after\"></div>" end end
true
144bfa88c47d53d08dae278b85e3f6f5f64177c6
Ruby
jmclean-coder/sample_code
/13-apis/db/seeds.rb
UTF-8
783
2.953125
3
[]
no_license
url = "https://pokemon-go1.p.rapidapi.com/pokemon_stats.json" #sent hte request and got the data pokemon_stats = RestClient::Request.execute(method: :get, url: "https://pokemon-go1.p.rapidapi.com/pokemon_stats.json", headers:{ "X-RapidAPI-Host" => "pokemon-go1.p.rapidapi.com", "X-RapidAPI-Key" => ENV["API_KEY"] }) #just need the response body to get our data response_body = pokemon_stats.body #convert to a hash using JSON.parse json_data = JSON.parse(response_body) #get the columnsm that I want. pokemons = json_data.map{ |pokemon| { base_attack: pokemon["base_attack"], pokemon_name: pokemon["pokemon_name"] } } json_data.each do |pokemon| Pokemon.find_or_create_by(pokemon) end binding.pry puts "all seeds are done. woot!"
true
6c9b21981e486899b3bfe7e482adaa49fb986dae
Ruby
andresporras3423/bowling_game
/lib/game.rb
UTF-8
3,453
3.1875
3
[]
no_license
# frozen_string_literal: true require_relative 'player' require_relative 'valid_score' class Game include ValidScore attr_reader :players def initialize(relative_path, request_output) @players = {} error_message = read_file_content(relative_path) if error_message != '' puts error_message return end give_output if request_output end private def give_output output = "Frame 1 2 3 4 5 6 7 8 9 10\n" @players.each_value do |player| if player.global_scores[1] == -1 puts "Incomplete data, #{player.name} hasn't completed its game" return end name = player.name pinfalls = print_player_pinfalls(player) scores = print_player_score(player) output += "#{name}\n" output += "#{pinfalls}\n" output += "#{scores}\n" end puts output end def print_player_pinfalls(player) pinfalls = 'Pinfalls' (0...player.scores.length).each do |i| pinfalls += if player.scores[i].frame < 10 pinfalls_before_frame_ten(player, i) else pinfalls_frame_ten(player, i) end end pinfalls end def pinfalls_before_frame_ten(player, i) if player.scores[i].roll == 1 && @@valid_score[player.scores[i].points] == 10 return ' X' elsif @@valid_score[player.scores[i].points] == 10 return ' X' elsif player.scores[i].roll == 2 && @@valid_score[player.scores[i - 1].points] + @@valid_score[player.scores[i].points] == 10 return ' /' end " #{player.scores[i].points}" end def pinfalls_frame_ten(player, i) if @@valid_score[player.scores[i].points] == 10 return ' X' elsif (player.scores[i].roll == 2 && @@valid_score[player.scores[i - 1].points] < 10 && @@valid_score[player.scores[i - 1].points] + @@valid_score[player.scores[i].points] == 10) || (player.scores[i].roll == 3 && @@valid_score[player.scores[i - 2].points] == 10 && @@valid_score[player.scores[i - 1].points] < 10 && @@valid_score[player.scores[i - 1].points] + @@valid_score[player.scores[i].points] == 10) return ' /' end " #{player.scores[i].points}" end def print_player_score(player) scores = 'Scores' player.global_scores.each do |key, value| scores += if key == 1 " #{value}" else (' ' * (6 - player.global_scores[key - 1].to_s.split('').length)) + value.to_s end end scores end def read_file_content(relative_path) absolute_path = File.join(File.dirname(__FILE__), relative_path) content_file = File.open(absolute_path) files_lines = content_file.read files_lines.each_line do |line| error_message = add_line_content(line) return error_message if error_message != '' end content_file.close '' rescue StandardError => e e end def add_line_content(line) score_data = line.split(' ') return "Every line should contain two values, the player's name and the pinfalls" if score_data.length != 2 player_name = score_data[0] player_score = @@valid_score[score_data[1]] return 'Score should be an integer between 1 and 10' if player_score.nil? @players[player_name] = Player.new(player_name) if @players[player_name].nil? @players[player_name].add_score(score_data[1]) end end
true
399379e5f096f03867e3e22786b8945d38292ad8
Ruby
LeahB8/badges-and-schedules-london-web-career-040119
/conference_badges.rb
UTF-8
636
3.890625
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# Write your code here. speakers = ["Edsger", "Ada", "Charles", "Alan", "Grace", "Linus", "Matz"] def badge_maker(name) return "Hello, my name is #{name}." end def batch_badge_creator(speakers) speakers.map do |speaker| badge_maker(speaker) end end def assign_rooms(speakers) attendee_array = [] speakers.each.with_index(1) do |speaker, index| attendee_array << "Hello, #{speaker}! You'll be assigned to room #{index}!" end attendee_array end def printer(speakers) batch_badge_creator(speakers).each do |badge| puts badge end assign_rooms(speakers).each do |assignment| puts assignment end end
true
abe69d961c9cdab6b265670594b832e6f76cce4e
Ruby
magic8baller/web-071717
/04-oo-review/lib/zoo.rb
UTF-8
2,970
4.21875
4
[]
no_license
class Animal # An animal belongs to a location attr_accessor :species, :location # Remember that the attr_accessors correspond to a name of a column on our table. @@all = [] def self.all @@all end def initialize(species) @species = species self.class.all << self # this line is the same as saying '@@all << self', but using the class method 'self.all' helps us maintain our program if we changed the class variable from @@all to @@animals. If we use the class variable in many places in our program, we'll have to find all of those and change each one. If we use the method, we only need to change the class variable name inside of the method. end end class Location # A location has many animals, has many zookeepers, and has many climates attr_accessor :name @@all = [] def self.all @@all end def initialize(name) @name = name self.class.all << self end def add_animal(animal) animal.location = self end def animals Animal.all.select { |animal | animal.location == self } end end class Climate # A climate has many locations attr_accessor :name @@all = [] def self.all @@all end def initialize(name) @name = name self.class.all << self end def locations # For this example, let's say our Climate instance is called "winter." # To find the locations of a climate, we loop through all of the LocationClimate instances and filter them out: we only want the ones where the climate matches "winter". location_climates = LocationClimate.all.select do |loc_cli| loc_cli.climate == self end # At this point, location_climates is an array of LocationClimate instances, all of which have a climate equal to "winter". # Now, we want to loop through each of these instances and ask it to return its location. # We're able to do this because "location" is a getter method on our LocationClimate instances (in attr_accessor). locations = location_climates.map do |location_climate| location_climate.location end # At this point, locations is an array of locations. These locations we found through the LocationClimate all method, and all corresponded to our climate "winter". locations end end class LocationClimate #LocationClimate belongs to a location and belongs to a climate. attr_accessor :location, :climate @@all = [] def self.all @@all end def initialize(location, climate) @location = location @climate = climate self.class.all << self end end class Zookeeper # A Zookeeper belongs to a location. attr_accessor :name, :location @@all = [] def self.all @@all end def initialize(name, location) @name = name @location = location self.class.all << self end def animals binding.pry # You can use pry in your program to find out what's happening inside of your methods. self.location.animal end end
true
680c3185244ed89e9d256f21d7b6b99383b6dec2
Ruby
burakkocak884/reverse-each-word-ruby-cartoon-collections-000
/reverse_each_word.rb
UTF-8
355
3.21875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def reverse_each_word(array) new_array = array.split(" ") reversed_array = new_array.each do |word| word.reverse! end reverse_each_word = reversed_array.join(" ") end def reverse_each_word(array) array1 = array.split(" ") reversed_array1 = array1.collect do |word| word.reverse! end reverse_each_word = reversed_array1.join(" ") end
true
449259fcf79b06cb27488795cd6535c1c09af6ca
Ruby
stan761/kanzapanoid
/lib/fader.rb
UTF-8
361
3.46875
3
[]
no_license
class Fader attr_accessor :value, :target, :time, :elapsed def initialize(value=0.0) @value = value @target = @value @time = 0.0 @elapsed = 0.0 end def to(target, time) @target = target @time = time @elapsed = 0.0 end def update if @target != @value @value -= (@value - @target) / (@time - @elapsed) @elapsed += 1 end end end
true
b7179f7f03b78d40e2d58ff82b538cf6a538332f
Ruby
jackzones/client_server_application
/server_application/lib/server/tcp_logger_server.rb
UTF-8
1,498
3.015625
3
[]
no_license
class TCPLoggerServer def initialize(hostname=nil, port=nil, log_file_name=nil) @host = hostname || 'localhost' @port = port || 20000 file_name = log_file_name || 'server.log' @log_file_path = File.join('server_log', file_name) Thread.abort_on_exception = true end # Create TCPServer and accept all incoming connections def server_start begin require "socket" server = TCPServer.new(@host, @port) return if server.nil? puts "Server started.\nListening at port: #{@port}\nLog file: #{@log_file_path}" trap("INT") { stopping() } # Main sever loop loop do # Spawn a thread and accept connection Thread.new(server.accept) do |conn| puts "Connection #{conn} accepted." write_to_log("[#{Time.now.to_s}] ") while line = conn.gets puts "Recieved: #{line.chop}\n" write_to_log(line.chop) end end end rescue => exception puts "ERROR: #{exception.inspect}" end end # Just be informative def stopping puts "\nInterrupt signal recieved.\nStopping server." exit 0 end # Stop server on ctrl+c def server_stop Process.kill 'INT', 0 end # Append text to the log file def write_to_log(text) File.open(@log_file_path, 'a') do |file| # threadsafe write file.flock(File::LOCK_EX) file.puts text file.flush file.flock(File::LOCK_UN) end end end
true
af9538213aba84cc35a5369039cd45fcc9f49d23
Ruby
lamagnotti/codewars
/high_and_low.rb
UTF-8
468
4.34375
4
[]
no_license
# In this little assignment you are given a string of space separated numbers, # and have to return the highest and lowest number. def high_and_low(numbers) new_array = [] new_string = numbers.split new_string.each do |n| new_array << n.to_i end max_string = new_array.max min_string = new_array.min "#{max_string} #{min_string}" end p high_and_low("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6") # => ("542 -214") p high_and_low("1 2 3 4 5") # => ("5 1")
true
f5dd0b6ab5a268522255d94974d05aae5fad1c34
Ruby
murraymel/air
/rspec_test/dog_spec.rb
UTF-8
115
2.59375
3
[]
no_license
describe 'A Dog' do it 'wags tail when you petted' do d = Dog.new d.pet.should eq('wags tail') end end
true
f565d086cf463d429c46fb895a8f368758eb0a40
Ruby
tcd/coolkit
/lib/coolkit/wip/core_ext/titleize.rb
UTF-8
545
3.625
4
[ "MIT" ]
permissive
module Coolkit # Returns a copy of a string with the first letter of each word capitalized. # @return [String] def titleize() return self.split(" ") .map(&:capitalize!) .join(" ") end # @return [String] def titleize2(string) words = self.split(" ") skips = ["and", "of", "the", "in", "to", "over", "an", "a"] words.each do |word| if word == words[0] || !skips.include?(word) element.capitalize! end end answer = array.join(" ") return answer end end
true
55387b9ffde9fad03f1383bf780da063a518c068
Ruby
Themitchell/follower-maze
/lib/follower_maze/user_store.rb
UTF-8
1,478
2.90625
3
[]
no_license
require 'singleton' module FollowerMaze class UserStore @store = {} class NotFoundError < StandardError; end class << self def add user @store[user.id] = user Logger.debug "UserStore: Created user with id: #{user.id}" if user user end def create_or_update id, connection if user = find(id) user.connection = connection user else user = User.new id, connection add(user) user end end def find id user = @store[id.to_i] return nil unless user Logger.debug "UserStore: Found user with id: #{user.id}" user end def find! id user = find id raise NotFoundError.new unless user user end def find_by_connection connection user = @store.values.find { |user| user.connection.fileno == connection.fileno } return nil unless user Logger.debug "UserStore: Found user with id: #{user.id}" user end def all users = @store.values Logger.debug "UserStore: Fetched #{users.size} users from store" users end def destroy user @store.delete user.id Logger.debug "UserStore: Destroyed user with id: #{user.id}" return nil end def destroy_all @store = {} Logger.debug "UserStore: Destroyed everything!!!!!!" end end end end
true
89f32dc44c403bfe294702df14a1fe55cd9c3ec1
Ruby
SebastianWikander/Korean-Manual
/spec/verb_spec.rb
UTF-8
2,786
2.90625
3
[]
no_license
#!/bin/env ruby # encoding: utf-8 require 'verb' describe Verb do it "should conjugate the verb 가다" do verb = Verb.new("가다") verb.present.stem.should eq("가") verb.present.plain.should eq("간다") verb.present.informal.should eq("가") verb.present.polite.should eq("가요") verb.present.formal.should eq("갑니다") verb.past.plain.should eq("갔다") verb.past.informal.should eq("갔어") verb.past.polite.should eq("갔어요") verb.past.formal.should eq("갔습니다") verb.future.plain.should eq("가겠다") verb.future.informal.should eq("가겠어") verb.future.polite.should eq("가겠어요") verb.future.formal.should eq("가겠습니다") end it "should conjugate the verb 하다" do verb = Verb.new("하다") verb.present.stem.should eq("하") verb.present.plain.should eq("한다") verb.present.informal.should eq("해") verb.present.polite.should eq("해요") verb.present.formal.should eq("합니다") verb.past.plain.should eq("했다") verb.past.informal.should eq("했어") verb.past.polite.should eq("했어요") verb.past.formal.should eq("했습니다") verb.future.plain.should eq("하겠다") verb.future.informal.should eq("하겠어") verb.future.polite.should eq("하겠어요") verb.future.formal.should eq("하겠습니다") end it "should conjugate the verb 마시다" do verb = Verb.new("마시다") verb.present.stem.should eq("마시") verb.present.plain.should eq("마신다") verb.present.informal.should eq("마셔") verb.present.polite.should eq("마셔요") verb.present.formal.should eq("마십니다") verb.past.plain.should eq("마셨다") verb.past.informal.should eq("마셨어") verb.past.polite.should eq("마셨어요") verb.past.formal.should eq("마셨습니다") verb.future.plain.should eq("마시겠다") verb.future.informal.should eq("마시겠어") verb.future.polite.should eq("마시겠어요") verb.future.formal.should eq("마시겠습니다") end it "should conjugate the verb 주다" do verb = Verb.new("주다") verb.present.stem.should eq("주") verb.present.plain.should eq("준다") verb.present.informal.should eq("주어") verb.present.polite.should eq("주어요") verb.present.formal.should eq("줍니다") verb.past.plain.should eq("주었다") verb.past.informal.should eq("주었어") verb.past.polite.should eq("주었어요") verb.past.formal.should eq("주었습니다") verb.future.plain.should eq("주겠다") verb.future.informal.should eq("주겠어") verb.future.polite.should eq("주겠어요") verb.future.formal.should eq("주겠습니다") end end
true
ecd21e6a30a8cceb74aba45e5426308cb7033a9a
Ruby
dhopz/oystercard
/spec/oystercard_spec.rb
UTF-8
2,337
3.078125
3
[]
no_license
require 'oystercard' describe OysterCard do let(:oystercard) { OysterCard.new } let(:station) { double :station } it 'get my balance' do expect(subject.balance).to eq 0 end it 'adds money to my balance' do subject.add_funds(10) expect(subject.balance).to eq 10 end it 'raises an error if :balance > 90' do oystercard.add_funds(OysterCard::LIMIT) expect { oystercard.add_funds(1) }.to raise_error "Card balance cannot exceed #{OysterCard::LIMIT}" end it 'is initially not in a journey' do expect(subject).not_to be_in_journey end it 'can touch in' do subject.add_funds(10) subject.touch_in(station) expect(subject).to be_in_journey end it 'checks the balance before #touch_in' do expect { subject.touch_in(station) }.to raise_error "Balance must be greater than 1" end it 'records the departing station' do subject.add_funds(10) subject.touch_in(station) expect(subject.entry_station).to eq station end describe 'stations' do let(:entry_station) { double :station } let(:exit_station) { double :station } let(:journeys){ {entry_station: entry_station, exit_station: exit_station} } it '#touch_out deducts money from card' do subject.add_funds(10) expect { subject.touch_out(exit_station) }.to change{ subject.balance }.by(-OysterCard::MINIMUM_CHARGE) end it 'can touch out' do subject.add_funds(10) subject.touch_in(entry_station) subject.touch_out(exit_station) expect(subject).not_to be_in_journey end it 'stores a journey' do subject.add_funds(10) subject.touch_in(entry_station) subject.touch_out(exit_station) expect(subject.journeys).to include({entry_station: entry_station, exit_station: exit_station}) end it 'stores a journey hash' do subject.add_funds(10) subject.touch_in(entry_station) subject.touch_out(exit_station) expect(subject.journeys).to include journeys end end end
true
6a96fff2d747c31cf439bf913252592703aa25a7
Ruby
suncoast-devs/cohort-xii
/week-08/day-01-intro-to-ruby/helloworld.rb
UTF-8
3,214
4.625
5
[]
no_license
# let name = 'Gavin' name = "Gavin" # console.log(name) puts(name) score = 42 puts(score) # message = `${name}, your score is ${score}` message = "#{name}, your score is #{score}" puts(message) # Array literals, just like in JavaScript # scores = [100, 42, 60, 12, 0, 99 ] scores = [100, 42, 60, 12, 0, 99] # Prints the array as a string, but one element per line puts(scores) # Programmer's print, gives us a programmer friendly output p(scores) # Programmer print a string shows the quotes p(message) # Adding things to an array # JavaScript: scores.push(98) scores.push(98) p(scores) scores << 75 p(scores) # Parenthesis in many places are optional p scores puts name # JavaScript # # const hello = () => { # console.log('hello!') #} def hello puts "hello!" end # JavaScript # # Calls the method # hello() # # Refers to the method itself, does not call it # # hello hello # JavaScript # const greet = name => { # console.log(`Hello ${name}`) # } # greet('Gavin') # greet('Gavin") # greet(name) def greet(name) puts "Hello #{name}" end greet("Gavin") greet(name) # JavaScript # const doubleNumber = number => { # return number * 2 # } def double_number(number) number * 2 end # JavaScript rule about variables we use once, still appies here puts "Doubling 85 is #{double_number(85)}" puts "Triple 85 is #{85 * 3}" puts "The name is #{name}" # JavaScript # const uppercaseName = name.toUpperCase() uppercase_name = name.upcase puts "The uppercase version is #{uppercase_name}" puts "But, name is still #{name}" # Many methods in Ruby have a _mutating_ version # This makes the value inside of the varible name uppercase name.upcase! puts "Now, if we look at name we get #{name}" # JavaScript # const isEven = number => { # return number % 2 === 0 # } def even?(number) number % 2 == 0 end if even?(4) puts "Yup, it is even" end if !even?(5) puts "Yup, it is odd" end # unless is like a backwards if, only do the part when the condition is FALSE unless even?(5) puts "Uh huh, it is odd" end def red?(color) color == "red" end # These two are the same car = "blue" if !red?(car) puts "Nope, not red" end unless red?(car) puts "Nope, not red" end # How many things in an array p scores p scores.length p scores.size p scores.count # Loops! index = 0 while index < scores.length # Do work here score = scores[index] puts "The number at index #{index} is #{score}" index += 1 end # Print a banner for the user puts "What is your name?" # GET a STRING (gets) from the user # CHOMP off the newline # put the result in the variable name name = gets.chomp # Names is a blank array names = [] # Append name to the 'names' array # Alternatively: names.push(name) names << name # Programmer print what is in name if name == "Toni" puts "*" * 40 puts "\n" * 5 puts "hello, Toni!\nYou can play the game!" end until name.empty? puts "Give me another name" name = gets.chomp unless name.empty? names << name puts "Thanks #{name}" end end puts "You gave me #{names.count} names" puts "They are:" # JavaScript # names.forEach(name => { # console.log(name) # }) names.each do |name| puts "> #{name}" end #
true
53912853706f2be40428735c002d28d734b7b60d
Ruby
nyc-sea-lions-2015/Jester
/db/seeds.rb
UTF-8
3,312
2.671875
3
[]
no_license
["bcheng90", "danasselin", "ebutler90", "gellieb", "hoathenguyen85", "kevalwell", "laurennicoleroth", "maxrater", "mbouzi", "notika314", "notryanb", "phanendar", "rimmesbe", "sabron13", "samguergen", "steppinlo", "suprfrye", "tracyteague", "queerviolet", "linkblaine"].each do |user| User.create(name: user, password: "123", created_at: "#{rand(2010..2014)}-#{rand(1..12)}-#{rand(1..28)} 03:14:15") end users = User.all users.each do |user| 5.times do Joke.create(line1: Faker::Hacker.say_something_smart, user_id: user.id, created_at: "#{rand(2010..2014)}-#{rand(1..12)}-#{rand(1..28)} 03:14:15") end 10.times do Comment.create(message: Faker::Hacker.say_something_smart, user_id: user.id, joke_id: rand(1..100), created_at: "#{rand(2010..2014)}-#{rand(1..12)}-#{rand(1..28)} 03:14:15") end end Joke.create(line1: "Why am I making jokes during my assessment/solo challenge?", line2: "Because I'm probably not gonna be listening to the joke during annoucements. Coding brain.", user_id: 1) Joke.create(line1: "My grandpa has the heart of a lion, and a lifetime ban from the zoo.", user_id: 2) Joke.create(line1: "Could you please call me a taxi?", line2: "You're a taxi.", user_id: 3) Joke.create(line1: "How does a train eat?", line2: "It goes chew chew", user_id: 4) Joke.create(line1: "What's Forest Gumps password?", line2: "HoaneForestHoane", line2: "then it hit me.", user_id: 5) Joke.create(line1: "I think I want a job cleaning mirrors. It's just something I could really see myself doing.", user_id: 6) Joke.create(line1: "Im really good friends with 25 letters of the alphabet... I don't know y", user_id: 7) Joke.create(line1: "Two fish are in a tank. One is driving and the other one is operating the gun.", user_id: 8) Joke.create(line1: "What did Hoa say when everyone was trying to talk to him with his headphones in?", line2: "Hoa-t?", user_id: 9) Joke.create(line1: "Why does Snoop Dogg always carry an umbrella?", line2: "Fo' Drizzle..... or in case of a Lil' Wayne.", user_id: 10) Joke.create(line1: "If you ever get cold, just stand in a corner for a bit.", line2: "They're usually around 90 degrees.", user_id: 11) Joke.create(line1: "There were two muffins in an oven. One says 'man it's hot in here' The other gasps! 'Oh my god! A talking muffin!'", user_id: 12) Joke.create(line1: "A magician was driving down the road when he turned into a driveway.", user_id: 13) Joke.create(line1: "Why aren't there any knock knock jokes about freedom?", line2: "Because freedom rings", user_id: 14) Joke.create(line1: "I went to a zoo the other day. It was completely empty, except for a single dog. It was a Shih Tzu.", user_id: 15) Joke.create(line1: "How many DBC students does it take to switch a lightbulb?", line2: "Two students pairing, one coach helping, and finger snaps ready when it's installed.", user_id: 16) Joke.create(line1: "What happened to the cow that jumped over the barbed wire fence?", line2: "Udder destruction", user_id: 17) Joke.create(line1: "How many 'Hoa's does it take to switch a lightbulb?", line2: "Hoane.", user_id: 18) Joke.create(line1: "My grandpa has the heart of a lion, and a lifetime ban from the zoo.", user_id: 19) Joke.create(line1: "So this guy comes into a bar... No wait, a horse.", line2: "So this guy comes into a horse", user_id: 20)
true
ca9b9383e2fe10d7fc891059301a39e6548dac82
Ruby
gniquil/sudoku_validator
/spec/lib/sudoku_validator_spec.rb
UTF-8
6,119
3.078125
3
[]
no_license
require 'spec_helper' require 'yaml' describe SudokuValidator do def create_validator(file_path=fixture_path('valid_complete.sudoku')) SudokuValidator.new(file_path) end describe '#valid_array?' do it 'returns false if there are repeats excluding "."' do validator = create_validator expect(validator.valid_array?(["1", "2", "3"])).to be_true expect(validator.valid_array?(["1", "2", "3", "3"])).to be_false expect(validator.valid_array?(["1", "2", ".", "."])).to be_true end end describe '#complete_array?' do it 'returns false if the number elements have count of 9 excluding "."' do validator = create_validator expect(validator.complete_array?(["1", "2", ".", "."])).to be_false expect(validator.complete_array?(["1", "2", "3", "4", "5", "6", "7", "8", "."])).to be_false expect(validator.complete_array?(["1", "2", "3", "4", "5", "6", "7", "8", "8"])).to be_true end end describe '#array_ok?' do it 'calls valid_array? if :invalid is given and returns the opposite' do validator = create_validator some_array = [1,2,3] expect(validator).to receive(:valid_array?).with(some_array).once.and_return(false) expect(validator.array_is?(:invalid, some_array)).to be_true expect(validator).to receive(:valid_array?).with(some_array).once.and_return(true) expect(validator.array_is?(:invalid, some_array)).to be_false end it 'calls complete_array? if :incomplete is given and returns the opposite' do validator = create_validator some_array = [1,2,3] expect(validator).to receive(:complete_array?).with(some_array).once.and_return(false) expect(validator.array_is?(:incomplete, some_array)).to be_true expect(validator).to receive(:complete_array?).with(some_array).once.and_return(true) expect(validator.array_is?(:incomplete, some_array)).to be_false end end describe '#initialize' do it 'takes a filepath and stores the grid' do reader = SudokuReader.new reader.read(fixture_path('valid_incomplete.sudoku')) validator = SudokuValidator.new fixture_path('valid_incomplete.sudoku') expect(validator.grid).to eq reader.grid end end describe '#row' do it 'retrieves a row as an array' do validator = SudokuValidator.new fixture_path('valid_incomplete.sudoku') expect(validator.row(1)).to eq ["8", "5", ".", ".", ".", "2", "4", ".", "."] expect(validator.row(5)).to eq ["3", ".", "5", ".", ".", ".", "9", ".", "."] end end describe '#column' do it 'retrieves a column as an array' do validator = SudokuValidator.new fixture_path('valid_incomplete.sudoku') expect(validator.column(2)).to eq ["5", "2", ".", ".", ".", "4", ".", "1", "."] expect(validator.column(4)).to eq [".", ".", ".", "1", ".", ".", ".", ".", "."] end end describe '#subgrid' do # subgrid is laid out as below # 1 2 3 <- grid_column_index # 1 - 3 4 - 6 7 - 9 # 1 . . . | . . . | . . . # 1 | . 1 . | . 2 . | . 3 . # 3 . . . | . . . | . . . # +-----+-------+-----+ # 4 . . . | . . . | . . . # 2 | . 4 . | . 5 . | . 6 . # 6 . . . | . . . | . . . # +-----+-------+-----+ # 7 . . . | . . . | . . . # 3 | . 7 . | . 8 . | . 9 . # 9 . . . | . . . | . . . # # ^ # grid_row_index # it 'retrieves a subgrid as an array' do validator = create_validator('valid_incomplete.sudoku') expect(validator.subgrid(3)).to eq ["4", ".", ".", ".", ".", "9", ".", ".", "."] expect(validator.subgrid(7)).to eq [".", ".", ".", ".", "1", "7", ".", ".", "."] end end describe '#validate!' do it 'runs finds and logs all the errors' do validator = create_validator('invalid_incomplete.sudoku') validator.validate! expect(validator.errors[:invalid][:row]).to eq [] expect(validator.errors[:invalid][:column]).to eq [2, 5] expect(validator.errors[:invalid][:subgrid]).to eq [] expect(validator.errors[:incomplete][:row]).to eq [1, 2, 3, 4, 5, 6, 7, 8, 9] expect(validator.errors[:incomplete][:column]).to eq [1, 2, 3, 4, 5, 6, 7, 8, 9] expect(validator.errors[:incomplete][:subgrid]).to eq [1, 2, 3, 4, 5, 6, 7, 8, 9] end end describe '#error_messages' do it 'ouputs the correct error messages' do validator = create_validator('invalid_incomplete.sudoku') validator.validate! expect(validator.error_messages(:invalid)).to eq [ "invalid columns: 2, 5" ] expect(validator.error_messages(:incomplete)).to eq [ "incomplete columns: 1, 2, 3, 4, 5, 6, 7, 8, 9", "incomplete rows: 1, 2, 3, 4, 5, 6, 7, 8, 9", "incomplete subgrids: 1, 2, 3, 4, 5, 6, 7, 8, 9" ] end end describe '#valid?' do it 'validates all 3 array checks' do validator = create_validator('valid_complete.sudoku') validator.validate! expect(validator.valid?).to be_true validator = create_validator('valid_incomplete.sudoku') validator.validate! expect(validator.valid?).to be_true validator = create_validator('invalid_complete.sudoku') validator.validate! expect(validator.valid?).to be_false validator = create_validator('invalid_incomplete.sudoku') validator.validate! expect(validator.valid?).to be_false end end describe '#complete?' do it 'validates all 3 array checks' do validator = create_validator('valid_complete.sudoku') validator.validate! expect(validator.complete?).to be_true validator = create_validator('valid_incomplete.sudoku') validator.validate! expect(validator.complete?).to be_false validator = create_validator('invalid_incomplete.sudoku') validator.validate! expect(validator.complete?).to be_false validator = create_validator('invalid_complete.sudoku') validator.validate! expect(validator.complete?).to be_true end end end
true
95933282eaee278b3b5efc1b7751782f992a509c
Ruby
eliav-lavi/specs-workshop
/lib/first/person.rb
UTF-8
342
3.59375
4
[]
no_license
class Person attr_reader :first_name, :last_name, :education_level def initialize(first_name, last_name, education_level = 0) @first_name = first_name @last_name = last_name @education_level = education_level end def full_name "#{@first_name} #{@last_name}" end def educate! @education_level += 1 end end
true
7622f2cf30dda853946595376ddad05da0e50b36
Ruby
marshall405/sinatra-mvc-lab-atx01-seng-ft-042020
/models/piglatinizer.rb
UTF-8
888
3.5625
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class PigLatinizer def piglatinize(words) words_arr = words.split(" ") latin_text = words_arr.map do |word| latinize_word(word) end latin_text.join(" ") end def latinize_word(word) if !word[0].downcase.scan(/[aeoui]/).empty? return word + 'way' else word_arr = word.split("") removed_letters = [] count = word.length count.times do |i| if word[i].downcase.scan(/[bcdfghjklmnpqrstvwxyz]/).empty? break else removed_letters << word_arr.shift end end if removed_letters.empty? return word + "ay" else return (word_arr + removed_letters).join("") + "ay" end end end end
true
bac70b0e23a60d95f787c66530b2f008e8c7f4d9
Ruby
GetTheFlightOut/Weather-API
/app/services/weather_service.rb
UTF-8
467
2.734375
3
[]
no_license
class WeatherService def self.conn Faraday.new(url: 'http://api.openweathermap.org') do |req| req.params['appid'] = ENV['WEATHER_API_KEY'] end end def self.weather_search(params) response = conn.get('/data/2.5/onecall') do |req| req.params['lat'] = params[:lat] req.params['lon'] = params[:lon] end parse_data(response) end def self.parse_data(response) JSON.parse(response.body, symbolize_names: true) end end
true
f5424847481d4037a76842b441828bd2c7c5a10c
Ruby
ttillotson/TipTopTomes
/app/models/user.rb
UTF-8
2,693
2.578125
3
[]
no_license
# == Schema Information # # Table name: users # # id :integer not null, primary key # username :string not null # email :string not null # password_digest :string not null # session_token :string not null # created_at :datetime not null # updated_at :datetime not null # class User < ApplicationRecord validates :username, :email, :session_token, presence: true validates :username, :email, uniqueness: true validates :password, length: { minimum: 6, allow_nil: true } after_initialize :ensure_session_token after_create :build_shelves attr_accessor :read_shelf, :reading_shelf, :will_read_shelf has_many :reviews, class_name: :Review, foreign_key: :author_id, dependent: :destroy has_many :shelves, class_name: :Bookshelf, foreign_key: :user_id, dependent: :destroy has_many :memberships, through: :shelves has_many :books, through: :shelves attr_reader :password def default_shelves self.shelves.limit(3) end def default_books self.shelves.includes(:memberships).limit(3).map do |shelf| shelf.memberships end end def default_memberships shelf_memberships = self.shelves.includes(:memberships).limit(3).map do |shelf| shelf.memberships end shelf_memberships.flatten end def default_membership(book_id) # shelf_book = self.shelves # .includes(:memberships) # .limit(3) # .find(book_id: book_id) # return shelf_book # shelf_book = self.books.select{ |book| book.id == bookId }[0] # u.shelf_ids.include?(shelf_book.shelf_id) ? shelf_book : null member = default_memberships.select{ |membership| membership.book_id == book_id }[0] member ? member : false end # FRONT END AUTH def self.find_by_credentials(email, password) user = User.find_by(email: email) (user&.valid_password?(password) ? user : nil) end def valid_password?(password) BCrypt::Password.new(self.password_digest).is_password?(password) end def reset_token! self.session_token = SecureRandom.urlsafe_base64(16) self.save! self.session_token end def password=(password) @password = password self.password_digest = BCrypt::Password.create(password) end private def ensure_session_token self.session_token ||= SecureRandom.urlsafe_base64(16) end def build_shelves @read_shelf = Bookshelf.create!(user_id: self.id, name: "Read") @reading_shelf = Bookshelf.create!(user_id: self.id, name: "Want to Read") @will_read_shelf = Bookshelf.create!(user_id: self.id, name: "Currently Reading") end end
true
47cfbc45182394bfb7e0c443ab10fbfe1d0c7d87
Ruby
benlavon/twgr
/chapter7/to_a.rb
UTF-8
350
3.796875
4
[]
no_license
# Nice way of making an array (1..5).to_a Computer = Struct.new(:os, :manufacturer) laptop1 = Computer.new("linux", "Lenovo") laptop2 = Computer.new("os x", "Apple") puts [laptop1, laptop2].map { |laptop| laptop.to_a } def combine_names(first_name, last_name) first_name + " " + last_name end names = ["David", "Black"] puts combine_names(*names)
true
82590fe8a45683677825cdb6f17bbc8fc6ed53e6
Ruby
Vratislav/saltpack-ruby
/lib/saltpack/armor.rb
UTF-8
10,397
3.265625
3
[ "MIT" ]
permissive
module Saltpack class << self B64_ALPHAPBET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' B62_ALPHAPBET = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' B85_ALPHAPBET = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstu' here = File.dirname(__FILE__) props_file = File.join(here, 'unicode', 'DerivedNormalizationProps.txt') categories_file = File.join(here, 'unicode', 'UnicodeData.txt') def get_alphabet(args) alphabet = B62_ALPHAPBET if args[:alphabet] alphabet = args[:alphabet] elsif args[:base64] alphabet = B64_ALPHAPBET elsif args[:base85] alphabet = B85_ALPHAPBET elsif args[:twitter] fail('Twitter alphabet is not supported yet') end alphabet end def get_bytes_in(args) if args[:bytes_in] != nil puts "String encoding of input is #{args[:bytes_in].encoding} " #we probably do not need to use .encode(). # String in ruby is already in UTF8 return args[:bytes_in].bytes end STDIN.read end def get_block_size(args) block_size = 32 if args[:block] block_size = args[:block].to_i elsif args[:base64] block_size = 3 elsif args[:base85] block_size = 4 elsif args[:twitter] block_size = 351 end block_size end def chunk_iterable(bytes, block_size) fail('Block size must be greater than 0') if block_size <= 0 chunks = [] i = 0 while i < bytes.length chunk = bytes[i..i+block_size-1] #puts "Putted chunk #{chunk}" chunks << chunk i = i + block_size end chunks end def max_bytes_size(alphabet_size, chars_size) ### # The most bytes we can represent satisfies this: # 256 ^ bytes_size <= alphabet_size ^ chars_size # Take the log_2 of both sides: # 8 * bytes_size <= log_2(alphabet_size) * chars_size # Solve for the maximum bytes_size: return (Math.log2(alphabet_size) / 8.0 * chars_size.to_f).floor end def min_chars_size(alphabet_size, bytes_size) ### # The most bytes we can represent satisfies this: # 256 ^ bytes_size <= alphabet_size ^ chars_size # Take the log_2 of both sides: # 8 * bytes_size <= log_2(alphabet_size) * chars_size # Solve for the minimum chars_size: return (8*bytes_size/Math.log2(alphabet_size)).ceil end def extra_bits(alphabet_size, chars_size, bytes_size) #In order to be compatible with Base64, when we write a partial block, we #need to shift as far left as we can. Figure out how many whole extra bits #the encoding space has relative to the bytes coming in.''' total_bits = (Math.log2(alphabet_size)*chars_size).floor total_bits - 8*bytes_size end def encode_block(bytes_block, alphabet, shift=false) # Figure out how wide the chars block needs to be, and how many extra bits # we have. #puts("bytes_block #{bytes_block}") chars_size = min_chars_size(alphabet.length, bytes_block.length) puts "Chars size during encoding #{chars_size}" #puts "alphabet #{alphabet}" #puts 'chars size:' #puts chars_size extra = extra_bits(alphabet.length, chars_size, bytes_block.length) # Convert the bytes into an integer, big-endian. # See: http://www.rubydoc.info/stdlib/core/Array:pack #puts 'bytes block:' #puts bytes_block bytes_int = bytes_to_bigendian_int(bytes_block) #puts 'bytes int:' #puts bytes_int if shift #bytes_int <<= extra bytes_int = bytes_int << extra end # Convert the result into our base places = [] for place in (1..chars_size) reminder = bytes_int%alphabet.length places.insert(0, reminder) #Floor division bytes_int = bytes_int / alphabet.length.to_i end #puts "Places array:#{places}" places.map { |x| alphabet[x] }.join('') end def chunk_string_ignoring_whitespace(s, size) #Skip over whitespace when assembling chunks fail() if size <= 1 chunks = [] chunk = '' s.each_char do |char| if char == " " next end chunk += char if chunk.length == size chunks << chunk chunk = '' end end if chunk != '' chunks << chunk end chunks end def get_char_index(alphabet, char) #This is the same as alphabet.index(char) but error is raised when char is not found #in the given alphabet index = alphabet.index(char) raise IndexError.new("Could not find #{char} in alphabet #{alphabet}") if index == nil index end def decode_block(chars_block, alphabet, shift=false) # Figure out how many bytes we have, and how many extra bits they'll have # been shifted by. bytes_size = max_bytes_size(alphabet.length, chars_block.length) expected_char_size = min_chars_size(alphabet.length, bytes_size) puts "Decoding block #{chars_block}, bytes_size #{bytes_size}" if chars_block.length != expected_char_size fail("illegal chars size #{chars_block.length}, expected #{expected_char_size}") end extra = extra_bits(alphabet.length, chars_block.length, bytes_size) #Convert the chars to an integer. bytes_int = get_char_index(alphabet, chars_block[0]) chars_block[1..chars_block.length-1].each_char { |c| bytes_int *= alphabet.length bytes_int += get_char_index(alphabet, c) } if shift bytes_int = bytes_int >> extra end #Convert the result to bytes, big_endian bytes = bigendian_int_to_bytes(bytes_int, bytes_size) #puts "Bytes #{bytes}" bytes end def armor(input_bytes, alphabet=B62_ALPHAPBET, block_size=32, raw=false, shift=false, message_type='MESSAGE') chunks = chunk_iterable(input_bytes, block_size) output = '' chunks.each do |chunk| output += encode_block(chunk, alphabet, shift) end if raw return chunk_iterable(output, 43).join(' ') end #puts "output: #{output}" words = chunk_iterable(output, 15) sentences = chunk_iterable(words, 200) joined = sentences.map { |sentence| sentence.join(' ') }.join('\n') header = "BEGIN SALTPACK #{message_type}. " footer = ". END SALTPACK #{message_type}." header + joined + footer end def dearmor(input_chars, alphabet=B62_ALPHAPBET, char_block_size=43, raw=false, shift=false) puts "Input in armor #{input_chars}" unless raw #Find the substring between the first periods first_period = input_chars.index('.') if first_period == nil STDERR.puts 'No period found in input.' exit(1) end second_period = input_chars.index('.', first_period+1) if second_period == nil STDERR.puts 'No second period found in input.' exit(1) end input_chars = input_chars[first_period+1..second_period-1] end puts "Dearmoring #{input_chars}" chunks = chunk_string_ignoring_whitespace(input_chars, char_block_size) output = [] chunks.each do |chunk| output << decode_block(chunk, alphabet, shift=shift) end output end def bytes_to_bigendian_int(bytes) result = 0 base = (bytes.count-1) * 8 #puts bytes bytes.each do |byte| result = result | ((byte) << base) #puts "result: #{result} base: #{base}" base = base - 8 end result end def bigendian_int_to_bytes(int, bytes_count) bytes = [] (0..bytes_count-1).reverse_each do |i| base = i*8 byte = (int >> base) int = int - (byte << base) bytes << byte #puts "base is #{base}, byte #{byte}" end bytes end def efficient_chars_sizes(alphabet_size, chars_size_upper_bound) out = [] max_efficiency = 0 (1..chars_size_upper_bound).each do |chars_size| bytes_size = max_bytes_size(alphabet_size, chars_size) efficiency = bytes_size / chars_size.to_f # This check also excludes sizes too small to encode a single byte if efficiency > max_efficiency out << {chars_size: chars_size, bytes_size: bytes_size, efficiency: efficiency} max_efficiency = efficiency end end out end def print_efficient_chars_sizes(alphabet_size, chars_size_upper_bound) puts "efficient block sizes for alphabet size #{alphabet_size}" efficiencies = efficient_chars_sizes(alphabet_size, chars_size_upper_bound) efficiencies.each do |e| bytes = e[:bytes_size].to_s.rjust 2 chars = e[:chars_size].to_s.rjust 2 percentage = (e[:efficiency]*100).round(2).to_s.rjust 2 puts "#{bytes} bytes: #{chars} chars (#{percentage}%)" end end def do_efficient(args) if args[:max_size] == nil upper_bound = 50 else upper_bound = args[:max_size].to_i end alphabet_size = args[:alphabet_size].to_i print_efficient_chars_sizes(alphabet_size, upper_bound) end def do_armor(args) alphabet = get_alphabet(args) bytes_input = get_bytes_in(args) shift = args[:shift] != nil raw = args[:raw] != nil block_size = get_block_size(args) armored = armor(bytes_input, alphabet, block_size, raw, shift) puts armored end def do_dearmor(args) alphabet = get_alphavet(args) chars_in = get_chars_in(args) shift = args[:shift] != nil raw = args[:raw] != nil char_block_size = min_chars_size(alphabet.length, get_block_size(args)) dearmored = dearmor(chars_in, alphabet, char_block_size, raw, shift) STDOUT.write dearmored end end end #puts "Should be #{24929}" #puts Saltpack.bigendian_int_to_bytes(Saltpack.bytes_to_bigendian_int([90,255]),2) #puts "Heh #{'aaa'.unpack("s*")}" #puts Saltpack.armor('ahoj'.bytes) #puts Saltpack.dearmor('BEGIN SALTPACK MESSAGE. 1mb4yQ. END SALTPACK MESSAGE.') Saltpack.do_efficient({alphabet_size: 62})
true
2e7922fdba749a9239c6abe6a82e751c7c779d4e
Ruby
alu0100603453/prct07
/spec/racional_spec.rb
UTF-8
3,207
2.96875
3
[]
no_license
require "racional.rb" describe Fraccion do before :each do @f1 = Fraccion.new(1,2) #<<<<<<< HEAD @f22 = Fraccion.new(2,3) @f2 = Fraccion.new(25,5) @f3 = Fraccion.new(5,15) @f4 = Fraccion.new(5,15) @f5 = Fraccion.new(1,3) @f6 = Fraccion.new(7,5) @f7 = Fraccion.new(-1,2) end describe "# Almacenamiento de valores" do it "Se almacena correctamente el numerador NUM" do @f1.n.should eq(1) end it "Se almacena correctamente el demoninador DEN" do @f1.d.should eq(2) end end #====== describe "#Devolver numerador y denomiador"do it "Se devuelve correctamente el numerador" do @f1.num.should eq(1) end it "Se devuelve correctamente el denominador" do @f1.denom.should eq(2) end end describe "# Metodo coma flotante" do it "Se muestra correctamente la division" do @f1.float.should eq("0.5") end end describe "#abs - Valor absoluto" do it "Se realiza correctamente el abs"do @f7.fabs.should eq("1 / 2") #>>>>>>> origin/test_alderete end end describe "# Minima expresion: " do it "La Fraccion queda reducida en su forma Minima" do f2 = Fraccion.new(4,8) f2.simply f2.n.should eq(1) f2.d.should eq(2) end end describe "# Operaciones aritmeticas" do it "la SUMA se realiza correctamente" do f = @f2 + @f3 f.n.should eq(16) f.d.should eq(3) end it "la RESTA se realiza correctamente" do f = @f2 - @f3 f.n.should eq(14) f.d.should eq(3) end it "el PRODUCTO se realiza correctamente" do f = @f2 * @f3 f.n.should eq(5) f.d.should eq(3) end it "el COCIENTE se realiza correctamente" do f = @f2 / @f3 f.n.should eq(15) f.d.should eq(1) end end describe "# Operaciones de comparacion" do it "las Fracciones son iguales" do check = false if(@f4 == @f3) check = true end check.should eq(true) end it "Fraccion1 < Fraccion2" do check = false if(@f1 < @f3) check = true end check.should eq(false) end it "Fraccion1 > Fraccion2" do check = false if(@f1 > @f3) check = true end check.should eq(true) end it "Fraccion1 <= Fraccion2" do check = false if(@f1 <= @f3) check = true end check.should eq(false) end it "Fraccion1 >= Fraccion2" do check = false if(@f4 >= @f3) check = true end check.should eq(true) end end describe "# De impropia a mixta" do it "f = k+f'" do result = @f6.imp_to_mix result.should eq("1 + 2/5") end end describe "# Reciproco de una Fraccion" do it "calculamos el Reciproco de una Fraccion" do f2 = @f6.recip f2.n.should eq(5) f2.d.should eq(7) end end describe "#Fraccion opuesta" do it "fraccion opuesta correcta" do [email protected] f.n.should eq(-1) f.d.should eq(2) end end describe "#Espectativa conjunto de operaciones(Modificacion en clase)" do it "Igualacion de producto correctamente" do check=false if((@f2*@f3)==(@f2*@f3)) check = true end check.should eq(true) end it "Producto con valor absoluto" do f=(@f7*@f1).fabs f.should eq("1 / 4") end it "Funcion modulo" do if((@f1% @f22) != 0) f=(@f1.op*@f22).fabs end f.should eq("1 / 3") end end end
true
9756e8dbe51daa2aebe2c90844b15de556898c9a
Ruby
BlookHo/TreeFams
/app/models/concerns/similars_exclusions.rb
UTF-8
4,999
2.53125
3
[]
no_license
module SimilarsExclusions extend ActiveSupport::Concern # in User model module ClassMethods ###################################################################### # МЕТОДЫ ПРОВЕРКИ УСЛОВИЯ ИСКЛЮЧЕНИЯ ПОХОЖЕСТИ ###################################################################### # Метод определения факта исключения похожести двух профилей. # Независимо от мощноти общности их кругов # На основе проверки существования отношений исключения похожести # в необщих частях 2-х кругов. def check_similars_exclusions(data_for_check) logger.info "*** check_similars_exclusions ***" # ": data_for_check: #{data_for_check}" uncommon_hash_a, uncommon_hash_b = get_uncommons(data_for_check[:a_profile_circle], data_for_check[:b_profile_circle], data_for_check[:common_hash]) inter_relations = common_of_uncommons(uncommon_hash_a, uncommon_hash_b) sim_exlude_relations = [ "Отец", "Мама", "Дед-о", "Дед-м", "Бабка-о","Бабка-м", "Брат", "Сестра", "Муж", "Жена", "Сын", "Дочь", "Внук-о", "Внук-м", "Внучка-о", "Внучка-м" ] # todo: поместить и брать массив exclude_relations из таблицы WeafamSettings unsimilar_sign = check_relations_exclusion(inter_relations, sim_exlude_relations) logger.info "*** unsimilar_sign: #{unsimilar_sign}, Uncommon relations: #{inter_relations}" return unsimilar_sign, inter_relations end # get_uncommons # Получение не общих частей кругов профилей а и б def get_uncommons(a_profile_circle, b_profile_circle, common_hash) uncommon_hash_a = unintersection(a_profile_circle, common_hash) uncommon_hash_b = unintersection(b_profile_circle, common_hash) #logger.info "*** In get_uncommons : uncommon_hash_a: #{uncommon_hash_a}" #logger.info "*** In get_uncommons : uncommon_hash_b: #{uncommon_hash_b}" return uncommon_hash_a, uncommon_hash_b end # get_commons_of_uncommons relations # Получение пересечения (общей части) не общих частей кругов профилей а и б def common_of_uncommons(uncommon_hash_a, uncommon_hash_b) relations_a = uncommon_hash_a.keys relations_b = uncommon_hash_b.keys # inter_relations = relations_a & relations_b relations_a & relations_b # return inter_relations #logger.info "*** In common_of_uncommons : inter_relations: #{inter_relations}" # inter_relations end # check relations exclusion # Установка значения признака в завис-ти от того, существуют ли среди пересечения inter_relations необщих частей кругов # двух профилей а и б какие-либо из отношений, входящие в массив Отношений-Исключений = exlude_relations. # Если существует, значит среди пересечения необщих частей кругов есть отношения Отец, Мать, Дед, Бабка. # Наличие таких отношений, которые тем не менее не совпали по именам, говорит о том, что эти 2 профиля - # разные люди. Следовательно, нет необходимости далее вычислять мощность общности общей части. def check_relations_exclusion(inter_relations, exlude_relations) unsimilar_sign = true # Исх.знач-е - сначала считаем похожими inter_relations.each do |relation| unsimilar_sign = false if exlude_relations.include?(relation) # Значит - точно непохожие # logger.info "*** In check_rels_ each 1: relation: #{relation}, exlude_relations.include?(relation) = #{exlude_relations.include?(relation)}, exlude_relations = #{exlude_relations} " # logger.info "*** In check_relations_exclusion 2: unsimilar_sign: #{unsimilar_sign}" end unsimilar_sign # передача значения признака (true/false) end # todo: перенести этот метод в Operational - для нескольких моделей # пересечение 2-х хэшей, у которых - значения = массивы def unintersection(first, other) result = {} first.reject { |k, v| (other.include?(k)) }.each do |k, v| # intersect = other[k] & v result.merge!({k => v}) #if !intersect.blank? end result end end end
true
a889078addee630c1b8578f515548bf0a358a5c4
Ruby
mayankagnihotri7/movie_listing_ruby
/spec/flicks/playlist_spec.rb
UTF-8
882
2.734375
3
[]
no_license
require "flicks/playlist" require "flicks/playlist_module" module Flicks describe PlayList do before do @playlist = PlayList.new("Max") end context "change the rank based on the number dice rolls" do before do @inital_rank = 10 @movie = Movie.new("goonies", @inital_rank) @playlist.add_movie(@movie) end it "gives movie a thumbs up if the number rolled if high" do PlaylistModule.stub(:roll_dice).and_return(5) @playlist.play_movie(3) end it "does not change the movie rank if the number rolled is medium" do PlaylistModule.stub(:roll_dice).and_return(3) @playlist.play_movie(3) end it "gives movie a thumbs down if the number rolled is low" do PlaylistModule.stub(:roll_dice).and_return(1) @playlist.play_movie(3) end end end end
true
f0abc283fcb46514783002584572b2a3d8784b02
Ruby
metricfu/metric_fu
/lib/metric_fu/data_structures/location.rb
UTF-8
3,535
2.921875
3
[ "MIT" ]
permissive
module MetricFu class Location include Comparable attr_accessor :file_path, :file_name, :line_number, :class_name, :method_name, :simple_method_name, :hash, :hash_key def self.get(file_path, class_name, method_name) location = new(file_path, class_name, method_name) @@locations ||= {} @@locations.fetch(location.hash_key) do @@locations[location.hash_key] = location location.finalize location end end def initialize(file_path, class_name, method_name) @file_path = file_path @file_name, @line_number = file_path.to_s.split(/:/) @class_name = class_name @method_name = method_name @simple_method_name = @method_name.to_s.sub(@class_name.to_s, "") @hash_key = to_key @hash = @hash_key.hash end def to_hash hash = { "class_name" => class_name, "method_name" => method_name, "file_path" => file_path, "file_name" => file_name, "line_number" => line_number, "hash_key" => hash_key, } if method_name.to_s.size > 0 hash = hash.merge("simple_method_name" => simple_method_name) else hash end end # defining :eql? and :hash to use Location as a hash key def eql?(other) @hash == other.hash end def <=>(other) hash <=> other.hash end # Generates the @hash key def to_key [@file_path, @class_name, @method_name].inspect end def self.for(class_or_method_name) class_or_method_name = strip_modules(class_or_method_name) if class_or_method_name begin match = class_or_method_name.match(/(.*)((\.|\#|\:\:[a-z])(.+))/) rescue => error # new error during port to metric_fu occasionally a unintialized # MatchData object shows up here. Not expected. mf_debug "ERROR on getting location for #{class_or_method_name} #{error.inspect}" match = nil end # reek reports the method with :: not # on modules like # module ApplicationHelper \n def signed_in?, convert it so it records correctly # but classes have to start with a capital letter... HACK for REEK bug, reported underlying issue to REEK if match class_name = strip_modules(match[1]) method_name = class_or_method_name.gsub(/\:\:/, "#") else class_name = strip_modules(class_or_method_name) method_name = nil end else class_name = nil method_name = nil end get(nil, class_name, method_name) end def finalize @file_path &&= @file_path.clone @file_name &&= @file_name.clone @line_number &&= @line_number.clone @class_name &&= @class_name.clone @method_name &&= @method_name.clone freeze # we cache a lot of method call results, so we want location to be immutable end private def self.strip_modules(class_or_method_name) # reek reports the method with :: not # on modules like # module ApplicationHelper \n def signed_in?, convert it so it records correctly # but classes have to start with a capital letter... HACK for REEK bug, reported underlying issue to REEK if class_or_method_name =~ /\:\:[A-Z]/ class_or_method_name.split("::").last else class_or_method_name end end end end
true
37cacf803f118b71f064bdd1587f8f0c4e632627
Ruby
ahwkim/bewd_homework
/class_3_4_homework/99_bottles.rb
UTF-8
533
4
4
[]
no_license
puts "Welcome to 99 Bottles of Beer on the Wall" number = 99 while number >= 2 puts "#{number} bottles of beer on the wall, #{number} bottles of beer. Take one down and pass it around, #{number - 1} bottles of beer on the wall." number = number - 1 end puts "1 bottle of beer on the wall, 1 bottle of beer. Take one down and pass it around, no more bottles of beer on the wall. No more bottles of beer on the wall, no more bottles of beer. Go to the store and buy some more, 99 bottles of beer on the wall."
true
30ac20569dc75ca6a171dab4b379283574af54b9
Ruby
madx/termki
/spec/page_spec.rb
UTF-8
3,283
2.734375
3
[]
no_license
describe TermKi::Page do MockRevision = Struct.new(:checksum, :contents, :timestamp) class MockRevision; def bind(page) end end describe 'initialization' do it 'initializes with a name' do page = TermKi::Page.new('page') page.name.should == 'page' page.history.should.be.kind_of Array page.history.should.be.empty end it 'has name and history read-only attributes' do page = TermKi::Page.new('page') [:name, :history].each do |meth| page.should.respond_to meth page.should.not.respond_to "#{meth}=" end end it 'fails if the name does not match [a-zA-Z0-9_:-]' do [ lambda { TermKi::Page.new('pass') }, lambda { TermKi::Page.new('p4ss') }, lambda { TermKi::Page.new('p-a_ss') }, lambda { TermKi::Page.new('PASS') }, lambda { TermKi::Page.new('pas:s') }, ].each { |l| l.should.not.raise } [ lambda { TermKi::Page.new('pa+ss') }, lambda { TermKi::Page.new('(fail)') }, lambda { TermKi::Page.new('"fail"') }, lambda { TermKi::Page.new('\'fail') }, lambda { TermKi::Page.new('$fail') }, lambda { TermKi::Page.new('fa il') }, lambda { TermKi::Page.new('#fail') } ].each { |l| l.should.raise } end end before do @page = TermKi::Page.new('page') @rev = MockRevision.new('abcd', "Contents", Time.now) end describe '#update(rev)' do it 'adds a revision' do @page.update @rev @page.history.should.include @rev @page.history.first.should == @rev end it 'should not duplicate entries' do 2.times { @page.update(@rev) } @page.history.size.should == 1 @page.history.map {|r| r.checksum }.should.include @rev.checksum end it 'is aliased as <<' do lambda { @page << @rev }.should.not.raise end end describe '#latest()' do it 'returns the latest revision' do 4.times do |i| @latest = MockRevision.new("rev#{i}", "Contents #{i}", Time.now + i*10) @page.update @latest end @page.latest.checksum.should == @latest.checksum end it 'returns nil if there are no history' do @page.latest.should.be.nil end end describe '#revision(checksum)' do before do @page << TermKi::Revision.new("contents") @cksm = @page.history.first.checksum end it 'fails if checksum is not a portion of SHA2' do lambda { @page.revision('void') }.should.raise RuntimeError, 'not a portion of SHA2' end it 'returns the given revision' do @page.revision(@cksm).checksum.should == @cksm end it 'accepts short checksums' do @page.revision(@cksm[0..2]).checksum.should == @cksm end it 'raises an error if the checksum is ambiguous' do checksum = @cksm[0..60] + 'BAD' @page.update MockRevision.new(checksum, "Contents", Time.now) lambda { @page.revision(@cksm[0..2]) }.should.raise RuntimeError, "ambiguous revision #{@cksm[0..2]}" end it 'returns nil if there is no such revision' do @page.revision(@cksm.next).should.be.nil end it 'is aliased as []' do @page[@cksm].should == @page.revision(@cksm) end end end
true
1323cbdd6ef6a7647cf0d28b224681f24f6bbc97
Ruby
Alexander-Andrade/weblog_stat
/src/validators/file_missing_validator.rb
UTF-8
337
2.609375
3
[]
no_license
# frozen_string_literal: true require_relative '../models/result' class FileMissingValidator def initialize(filename) @filename = filename end def validate return Result.success if filename && File.exist?(filename) Result.failure(filename, 'file parameter is missing') end private attr_reader :filename end
true
c445a148052c2de607b5a6f9a853088ee36880ed
Ruby
sebatapiaoviedo/desafio_arreglos
/promedio2.rb
UTF-8
261
3.3125
3
[]
no_license
def promedio (grades, grades1) sum_array = grades + grades1 ratings = 0 all_grades = sum_array.count sum_array.each do |grades| ratings += (grades/all_grades.to_f) end ratings end print promedio([1000, 800, 250], [300, 500,2500])
true
cb98fdfc2546a7b9410a1a1a0f24a75c6644ad7e
Ruby
bahelms/time_tracker
/spec/support/mocks/tasks_decorator_mock.rb
UTF-8
368
2.734375
3
[]
no_license
class TasksDecoratorMock attr_reader :user def initialize(user) @user = user end def tasks tasks = [] 5.times { tasks << Task.new(task_params(Time.current)) } 2.times { tasks << Task.new(task_params(2.weeks.ago)) } tasks end private def task_params(time) { user_id: user.id, duration: 10000, updated_at: time } end end
true
77d05e494b139aa2697ab7d997de7036bf615d61
Ruby
lukei8ii/mtg_online
/app/models/game.rb
UTF-8
1,357
2.921875
3
[]
no_license
class Game include Wisper::Publisher attr_accessor :players attr_accessor :stack attr_accessor :turns def initialize(players) throw "A game needs at least 2 players" unless players.count > 1 @players = players @stack = [] @turns = [] @players.each do |player| player.get_ready self end broadcast(:new_game) next_part! end def current_turn @turns.first end def current_part current_turn.current_part end def next_part! if !current_turn || current_turn.is_last_part? next_turn! else current_turn.next_part! end current_part end def next_turn! if @turns.count > 1 @turns.shift @turns << Turn.new(self, next_player) unless @turns.any? else @turns << Turn.new(self, @players.sample) unless current_turn end current_turn end def current_player current_turn.owner end def next_player player_index = @players.index(current_player) player_index = player_index >= @players.count ? 0 : player_index + 1 @players[player_index] end def self.test deck1 = Deck.with_cards.find(rand(1..5)) deck2 = Deck.with_cards.find(rand(1..5)) player1 = User.first player2 = User.second player1.choose_deck deck1 player2.choose_deck deck2 self.new [player1, player2] end end
true
784193e915f61af04024d8e98741c1bbf36dd033
Ruby
tfielder/RPN-Calculator
/RPN_test.rb
UTF-8
4,985
3.03125
3
[]
no_license
gem 'minitest', '~> 5.2' require 'minitest/autorun' require 'minitest/pride' require_relative 'RPN_class' class RPNTest < Minitest::Test def setup @rpn = RPN.new end def test_creates_new_class assert @rpn end def test_it_has_empty_stack assert_equal [], @rpn.stack end def test_it_validates_input_is_zero input1 = @rpn.input_zero?("0") input2 = @rpn.input_zero?(0) input3 = @rpn.input_zero?("+") input4 = @rpn.input_zero?("zero") assert_equal true, input1 assert_equal false, input2 assert_equal false, input3 assert_equal false, input4 end def test_it_validates_input_is_operator input1 = @rpn.input_operator?("+") input2 = @rpn.input_operator?("-") input3 = @rpn.input_operator?("/") input4 = @rpn.input_operator?("*") input5 = @rpn.input_operator?("%") input6 = @rpn.input_operator?("add") input7 = @rpn.input_operator?("1") assert_equal true, input1 assert_equal true, input2 assert_equal true, input3 assert_equal true, input4 assert_equal false, input5 assert_equal false, input6 assert_equal false, input7 end def test_it_validates_input_is_number input1 = @rpn.input_number?("1") input2 = @rpn.input_number?("-1") input3 = @rpn.input_number?("5.9") input4 = @rpn.input_number?("-5.9") input5 = @rpn.input_number?(123) input6 = @rpn.input_number?("one") input7 = @rpn.input_number?("0") input8 = @rpn.input_number?("+") assert_equal true, input1 assert_equal true, input2 assert_equal true, input3 assert_equal true, input4 assert_equal true, input5 assert_equal false, input6 assert_equal false, input7 assert_equal false, input8 end def test_it_validates_input input1 = @rpn.valid_input?("0") input2 = @rpn.valid_input?("+") input3 = @rpn.valid_input?("-") input4 = @rpn.valid_input?("/") input5 = @rpn.valid_input?("*") input6 = @rpn.valid_input?("1") input7 = @rpn.valid_input?("1.1") input8 = @rpn.valid_input?("-1") input9 = @rpn.valid_input?("-1") input10 = @rpn.valid_input?("-1") input11 = @rpn.valid_input?("-1") input12 = @rpn.valid_input?("-1") input13 = @rpn.valid_input?("yes") input14 = @rpn.valid_input?("%@*i") assert_equal true, input1 assert_equal true, input2 assert_equal true, input3 assert_equal true, input4 assert_equal true, input5 assert_equal true, input6 assert_equal true, input7 assert_equal true, input8 assert_equal true, input9 assert_equal true, input10 assert_equal true, input11 assert_equal true, input12 assert_equal false, input13 assert_equal false, input14 end def test_it_adds_to_the_stack assert_equal 0, @rpn.stack.count @rpn.add_to_stack("0") assert_equal 1, @rpn.stack.count @rpn.add_to_stack("-10.1") assert_equal 2, @rpn.stack.count @rpn.add_to_stack("holy_cow") assert_equal 2, @rpn.stack.count end def test_it_has_enough_operands assert_equal false, @rpn.enough_operands? @rpn.add_to_stack("0") assert_equal false, @rpn.enough_operands? @rpn.add_to_stack("1") assert_equal true, @rpn.enough_operands? end def test_it_asks_division_by_zero @rpn.add_to_stack("0") @rpn.add_to_stack("1") case1 = @rpn.division_by_zero?("/") case2 = @rpn.division_by_zero?("+") assert_equal false, case1 assert_equal false, case2 @rpn.add_to_stack("0") case3 = @rpn.division_by_zero?("/") case4 = @rpn.division_by_zero?("+") assert_equal true, case3 assert_equal false, case4 end def test_valid_calculation @rpn.add_to_stack("0") case1 = @rpn.valid_calculation?("+") case2 = @rpn.valid_calculation?("/") assert_equal false, case1 assert_equal false, case2 @rpn.add_to_stack("1") case3 = @rpn.valid_calculation?("/") assert_equal true, case3 @rpn.add_to_stack("0") case4 = @rpn.valid_calculation?("/") assert_equal false, case4 end def test_determine_calculation @rpn.add_to_stack("2") @rpn.add_to_stack("2") @rpn.determine_calculation("+") assert_equal 4, @rpn.stack[-2] assert_equal 2, @rpn.stack[-1] @rpn.add_to_stack("2") @rpn.add_to_stack("2") @rpn.determine_calculation("-") assert_equal 0, @rpn.stack[-2] assert_equal 2, @rpn.stack[-1] @rpn.add_to_stack("3") @rpn.add_to_stack("3") @rpn.determine_calculation("*") assert_equal 9, @rpn.stack[-2] assert_equal 3, @rpn.stack[-1] @rpn.add_to_stack("9") @rpn.add_to_stack("3") @rpn.determine_calculation("/") assert_equal 3, @rpn.stack[-2] assert_equal 3, @rpn.stack[-1] end def test_it_updates_stack @rpn.add_to_stack("9") @rpn.add_to_stack("3") assert_equal 9, @rpn.stack[-2] assert_equal 3, @rpn.stack[-1] @rpn.update_stack assert_equal 1, @rpn.stack.count assert_equal 9, @rpn.stack[-1] end end
true
94f73b2e81752e66b79be206397672704c6f5ebd
Ruby
mkrahu/launchschool-courses
/101_programming_foundations/02_small_programs/finding_greatest.rb
UTF-8
398
3.765625
4
[]
no_license
def finding_greatest(numbers) max_number = nil return nil if !numbers.is_a? Array || numbers.empty? numbers.each do |num| next unless num.is_a? Integer max_number ||= num max_number = num if num > max_number end max_number end puts finding_greatest([1, 10, 25, 4, 12, -3]) puts finding_greatest([]) == nil puts finding_greatest(nil) == nil puts finding_greatest(0) == nil
true
3afd9d209bfac22f96a623ee2caaf0b2433f3125
Ruby
petertseng/adventofcode-rb-2016
/08_2fa.rb
UTF-8
878
2.96875
3
[ "Apache-2.0" ]
permissive
WIDTH = begin arg = ARGV.find { |x| x.start_with?('-w') } arg ? Integer(ARGV.delete(arg)[2..-1]) : 50 end HEIGHT = 6 screen = Array.new(HEIGHT) { Array.new(WIDTH, false) } ARGF.each_line { |l| words = l.split case words[0] when 'rect' cols, rows = words[1].split(?x).map(&method(:Integer)) rows.times { |r| cols.times { |c| screen[r][c] = true } } when 'rotate' idx = Integer(words[2][/\d+/]) amt = -Integer(words[4][/\d+/]) case words[1] when 'row' screen[idx].rotate!(amt) when 'column' rotated = screen.map { |row| row[idx] }.rotate(amt) screen.zip(rotated) { |row, pixel| row[idx] = pixel } else raise "Rotate #{words[1]} unknown" end else raise "Operation #{words[0]} unknown" end } puts screen.sum { |row| row.count(true) } screen.each { |r| puts r.map { |cell| cell ? ?# : ' ' }.join }
true
73fc4734c475e78e2e1e856a125f3af52bdc87ca
Ruby
lonelyelk/advent-of-code
/2019/21/lib.rb
UTF-8
2,942
3.203125
3
[]
no_license
class Intcode attr_reader :prg, :index def initialize(prog: , input: []) @input = input @prg = prog.dup @index = 0 @halt = false @output = [] @relative_base = 0 end def halt? @halt end def input(data) @input.push(data) end def bulk_input(arr) @input += arr end def output @output.shift end def flush_output re = @output @output = [] re end def compute_continue while !halt? do code = @prg[@index] % 100 modes = [100, 1000, 10000].map { |pos| @prg[@index] / pos % 10 } case code when 1 @prg[address(@index+3, modes[2])] = param(@index+1, modes[0]) + param(@index+2, modes[1]) @index += 4 when 2 @prg[address(@index+3, modes[2])] = param(@index+1, modes[0]) * param(@index+2, modes[1]) @index += 4 when 3 data = @input.shift return if data.nil? @prg[address(@index+1, modes[0])] = data @index += 2 when 4 @output.push(param(@index+1, modes[0])) @index += 2 when 5 if param(@index+1, modes[0]) != 0 @index = param(@index+2, modes[1]) else @index += 3 end when 6 if param(@index+1, modes[0]) == 0 @index = param(@index+2, modes[1]) else @index += 3 end when 7 if param(@index+1, modes[0]) < param(@index+2, modes[1]) @prg[address(@index+3, modes[2])] = 1 else @prg[address(@index+3, modes[2])] = 0 end @index += 4 when 8 if param(@index+1, modes[0]) == param(@index+2, modes[1]) @prg[address(@index+3, modes[2])] = 1 else @prg[address(@index+3, modes[2])] = 0 end @index += 4 when 9 @relative_base += param(@index+1, modes[0]) @index += 2 when 99 @halt = true else raise "ERROR" end end end def param(index, mode) value = @prg[index] || 0 case mode when 0 @prg[value] || 0 when 1 value when 2 @prg[value + @relative_base] || 0 else raise "ERROR" end end def address(index, mode) value = @prg[index] || 0 case mode when 0 value when 2 value + @relative_base else raise "ERROR" end end end def walk(prog, script) intcode = Intcode.new(prog: prog, input: (script + "WALK\n").chars.map(&:ord)) intcode.compute_continue if intcode.halt? print_output(intcode.flush_output) else raise "ERROR" end end def run(prog, script) intcode = Intcode.new(prog: prog, input: (script + "RUN\n").chars.map(&:ord)) intcode.compute_continue if intcode.halt? print_output(intcode.flush_output) else raise "ERROR" end end def print_output(out) out.each do |c| if c <= 255 print c.chr else puts c end end end
true
a236cb24b3e9579d9168d021d118f76038c57ee2
Ruby
tom025/factory-toys
/spec/factory_toys/parser_spec.rb
UTF-8
3,959
3.15625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require 'spec_helper' #implemented here to get tests to pass as in Rails Environment and not ruby core?? class String def blank? self.nil? or self == '' end end describe FactoryToys::Parser do context 'on initialization' do it 'returns straight text in the under :base' do parser = FactoryToys::Parser.new('hello="hello there"') parser.elements.should == {:base => '@hello="hello there"'} end it 'returns straight text in the under :base with multiple lines' do parser = FactoryToys::Parser.new("hello='hello there'\ngoodbye='bye bye'") parser.elements.should == {:base => "@hello='hello there'\n@goodbye='bye bye'"} end it 'does not break hashs' do parser = FactoryToys::Parser.new("hello_hash = {\n:hello='hello there',\n:goodbye='bye bye'}") parser.elements.should == {:base => "@hello_hash = {\n:hello='hello there',\n:goodbye='bye bye'}"} end context 'extracting from multi-line comment' do it 'create element for named after variable' do run_factory[:other_string].should_not == nil end it 'removes excess white space' do run_factory[:other_string].should == "@other_string = <<-TestData\n" + "value=test\n" + "TestData" end it "returns unextracted data" do run_factory[:base].should == "@test='testing'\n@greeting='Hello Again'" end it "does not remove blank lines" do run_factory("\n\ndate='Dont look at me??'")[:base].should == "@test='testing'\n@greeting='Hello Again'\n\n\n@date='Dont look at me??'" end it "when named variables only" do string = <<-Data other_string = <<-TestData value=test TestData Data parser = FactoryToys::Parser.new(string) parser.elements[:base].should == '' parser.elements[:other_string].should == "@other_string = <<-TestData\n" + "value=test\n" + "TestData" end def run_factory(additional_text='') string = <<-Data test='testing' other_string = <<-TestData value=test TestData greeting='Hello Again' Data parser = FactoryToys::Parser.new(string + additional_text) parser.elements end end context 'with inline data sharing' do it 'supports unline use of existing elements' do string = <<-Data string_one = <<-Str1 This is the test Str1 string_two = <<-Str2 This is an inline test << string_one Str2 Data parser = FactoryToys::Parser.new(string) parser.elements[:base].should == '' parser.elements[:string_one].should == "@string_one = <<-Str1\n" + "This is the test\n" + "Str1" parser.elements[:string_two].should == "@string_two = <<-Str2\n" + "This is an inline test\n" + "This is the test\n" + "Str2" end it 'supports inline use of multi-line existing elements' do string = <<-Data string_one = <<-Str1 This is the test And so is this Str1 string_two = <<-Str2 This is an inline test << string_one Str2 Data parser = FactoryToys::Parser.new(string) parser.elements[:base].should == '' parser.elements[:string_two].should == "@string_two = <<-Str2\n" + "This is an inline test\n" + "This is the test\n" + "And so is this\n" + "Str2" end it 'when invalid inline element raises an error' do string = <<-Data string_one = <<-Str1 This is the test Str1 string_two = <<-Str2 This is an inline test << string_error Str2 Data lambda{ FactoryToys::Parser.new(string) }.should raise_error FactoryToys::UnknownInlineError, "string_error" end end end end
true
cbd729f2eb6963d7847cd1862bf51bc016bbcddb
Ruby
alu0100454741/Equipo-DJ-prct08
/spec/matrix_spec.rb
UTF-8
528
3.0625
3
[]
no_license
require 'matrix_main.rb' require 'rspec' describe "Conjunto de expectativas" do before :each do @matrix1 = Matrix.new("9 3 2\n4 6 7") @matrix2 = Matrix.new("3 5 7\n8 9 3") end it "La matriz se muestra correctamente" do @matrix1.show.should eq("[[9, 3, 2], [4, 6, 7]]") end it "Comprobando el acceso de un dato de la matriz mediante indice" do @matrix1[0,0].should == 9 end it "Asignando un valor a una posicion de la matriz" do @matrix2[0,0] = 10 @matrix2[0,0].should == 10 end end
true
4dc9c2da5b115071cb941110e915020d84b23f4a
Ruby
enspiral/playhouse
/lib/playhouse/context.rb
UTF-8
2,575
2.875
3
[ "MIT" ]
permissive
require 'active_support/core_ext/string/inflections' require 'playhouse/part' require 'playhouse/validation/actors_validator' module Playhouse class Context class << self def parts @actor_definitions ||= [] end def actor(name, options = {}) raise InvalidActorKeyError.new(self.class.name, name) unless name.is_a?(Symbol) parts << Part.new(name, options) define_method name do @actors[name] end end def part_for(name) raise InvalidActorKeyError.new(self.class.name, name) unless name.is_a?(Symbol) parts.detect {|definition| definition.name == name} end def method_name context_name_parts.join('').underscore.to_sym end def http_method(method=:post) @http_methods ||= [] if method.is_a?(Array) @http_methods.concat method else @http_methods << method end end def http_methods return [:get] if @http_methods.nil? @http_methods.uniq end private def context_name_parts name.split('::')[1..-1].reverse end end def initialize(actors = {}) store_expected_actors(actors) end def inherit_actors_from(parent) parent.send(:actors).each do |name, actor| if actors[name].nil? && self.class.part_for(name) store_actor name, actor end end end def call validate_actors cast_actors perform end def perform raise NotImplementedError.new("Context #{self.class.name} needs to override the perform method") end protected def validator ActorsValidator.new end private def validate_actors validator.validate_actors(self.class.parts, @actors) end def store_expected_actors(actors) @actors = {} actors.each do |name, actor| store_actor name, actor end end def store_actor(name, actor) part = self.class.part_for(name) if part @actors[name] = actor else raise UnknownActorKeyError.new(self.class.name, name) end end def cast_actors @actors.each do |name, actor| part = self.class.part_for(name) @actors[name] = part.cast(actor) end end def actors @actors end def actors_except(*exceptions) actors.reject do |key, value| exceptions.include?(key) end end end end
true
e9cba3d168e80f2de9b6adbfe016d51608564b52
Ruby
a-woodworth/ls_projects
/lesson_5_advanced_collections/exercise_10.rb
UTF-8
602
4.25
4
[]
no_license
# Given the following data structure and without modifying the original array, use the map method # to return a new array identical in structure to the original but where the value of each integer # is incremented by 1. # [{a: 1}, {b: 2, c: 3}, {d: 4, e: 5, f: 6}] original = [{a: 1}, {b: 2, c: 3}, {d: 4, e: 5, f: 6}] new_array = original.map do |hsh| incremented_hash = {} hsh.each do |key, value| incremented_hash[key] = value + 1 end incremented_hash end p original p new_array # [{:a=>1}, {:b=>2, :c=>3}, {:d=>4, :e=>5, :f=>6}] # [{:a=>2}, {:b=>3, :c=>4}, {:d=>5, :e=>6, :f=>7}]
true
8051289bc07831a9f1d7b572eb5ff6b1ed3c6f51
Ruby
ethanrowe/rivet
/lib/rivet/utils.rb
UTF-8
1,883
2.640625
3
[ "Apache-2.0" ]
permissive
module Rivet module Utils AUTOSCALE_DIR = "autoscale" def self.die(level = 'fatal',message) Rivet::Log.write(level,message) exit end def self.ensure_minimum_setup if Dir.exists?(AUTOSCALE_DIR) true else Rivet::Log.info("Creating #{AUTOSCALE_DIR}") Dir.mkdir(AUTOSCALE_DIR) end end # This returns the merged definition given a group def self.get_definition(group) defaults = consume_defaults group_def = load_definition(group) if defaults && group_def group_def = defaults.deep_merge(group_def) end group_def ? group_def : false end # Gobbles up the defaults file from YML, returns the hash or false if empty def self.consume_defaults(autoscale_dir = AUTOSCALE_DIR) defaults_file = File.join(autoscale_dir,"defaults.yml") if File.exists?(defaults_file) parsed = begin Rivet::Log.debug("Consuming defaults from #{defaults_file}") YAML.load(File.open(defaults_file)) rescue ArgumentError => e Rivet::Log.fatal("Could not parse YAML from #{defaults_file}: #{e.message}") end parsed else false end end # This loads the given definition from it's YML file, returns the hash or # false if empty def self.load_definition(name) definition_dir = File.join(AUTOSCALE_DIR,name) conf_file = File.join(definition_dir,"conf.yml") if Dir.exists?(definition_dir) && File.exists?(conf_file) Rivet::Log.debug("Loading definition for #{name} from #{conf_file}") parsed = begin YAML.load(File.open(conf_file)) rescue Rivet::Log.fatal("Could not parse YAML from #{conf_file}: #{e.message}") end parsed ? parsed : { } else false end end end end
true
20bb2bceb67014247d68e6552b62bd41ad22ecf3
Ruby
Robertfarb/W1D5
/skeleton/lib/knight_path.rb
UTF-8
510
2.96875
3
[]
no_license
require_relative '00_tree_node.rb' class KnightsPathFinder POSSIBLE_MOVES = [[-2, 1], [-2, -1], [2, -1], [2, 1], [1, 2], [1, -2], [-1, 2], [-1, -2]] def initialize(start_position = [0, 0]) @start_position = start_position build_move_tree(start_position) end def new_move_positions(pos) new_moves = [] POSSIBLE_MOVES.each_with_index do |pos, idx| end def find_path(end_position) end def build_move_tree(start_position) end end p tree1 = PolyTreeNode.new('e')
true
40573bbc46e2121b4a76725adae930766454aca9
Ruby
nerdinand/nnfs-ruby
/09_backpropagation/02_combining_everything.rb
UTF-8
2,095
3
3
[]
no_license
require 'numo/narray' require_relative 'layer_dense' require_relative 'activation_relu' require_relative 'activation_softmax_loss_categorical_crossentropy' require_relative '../lib/nnfs' NNFS.init require_relative '../lib/datasets' # Create dataset x, y = SpiralData.create(n_samples: 100, n_classes: 3) # Create Dense layer with 2 input features and 3 output values dense1 = LayerDense.new(n_inputs: 2, n_neurons: 3) # Create ReLU activation (to be used with Dense layer): activation1 = ActivationReLU.new # Create second Dense layer with 3 input features (as we take output # of previous layer here) and 3 output values dense2 = LayerDense.new(n_inputs: 3, n_neurons: 3) # Create Softmax classifier's combined loss and activation loss_activation = ActivationSoftmaxLossCategoricalCrossentropy.new # Make a forward pass of our training data through this layer dense1.forward(x) # Make a forward pass through activation function # it takes the output of first dense layer here activation1.forward(dense1.output) # Make a forward pass through second Dense layer # it takes outputs of activation function of first layer as inputs dense2.forward(activation1.output) # Perform a forward pass through the activation/loss function # takes the output of second dense layer here and returns loss loss = loss_activation.forward(dense2.output, y) # Let's see output of the first few samples: p loss_activation.output[0...5, true] # Print loss value puts "Loss: #{loss}" # Calculate accuracy from output of loss_activation and targets # calculate values along first axis predictions = loss_activation.output.argmax(axis: 1) if y.shape.size == 2 y = y.argmax(axis: 1) end accuracy = Numo::DFloat.cast(predictions.eq(y)).mean # Print accuracy puts "Accuracy: #{accuracy.inspect}" # Backward pass loss_activation.backward(loss_activation.output, y) dense2.backward(loss_activation.dinputs) activation1.backward(dense2.dinputs) dense1.backward(activation1.dinputs) # Print gradients puts dense1.dweights.inspect puts dense1.dbiases.inspect puts dense2.dweights.inspect puts dense2.dbiases.inspect
true
8d40e285dbc4cac4f03feaf0cbcb459a3f8b51ae
Ruby
rachelferretto/WDI_16_HOMEWORK
/Rachel/wk04/1-mon/temp_converter.rb
UTF-8
947
4.1875
4
[]
no_license
require 'pry' puts('enter a start temp') temp = gets.chomp.to_i puts('enter a unit: F, C or K') unit = gets.chomp def convert_temp(temp,unit) if unit == "F" puts("fahrenheit: #{temp}") temp = (temp - 32) / 1.8 puts("#{unit} to celcius: #{temp}") temp = (temp + 459.67) / 1.8 puts("#{unit} to kelvin: #{temp}") elsif unit == "C" puts("celcius: #{temp}") temp = (temp × 1.8) + 32 puts("#{unit} to fahrenheit: #{temp}") temp = temp + 273.15 puts("#{unit} to kelvin: #{temp}") elsif unit == "K" puts("kelvin: #{temp}") temp = temp - 273.15 puts("#{unit} to celcius: #{temp}") temp = (temp × 1.8) - 459.67 puts("#{unit} to fahrenheit: #{temp}") else puts("Invalid unit") end end puts convert_temp(temp,unit) # loop do # convert_temp(temp,unit) # if unit == 'q' # break # end
true
c925e5ed3a9b62f4aa76fe92b58eda7174b40d30
Ruby
Drew242/chisel
/lib/chisel.rb
UTF-8
352
3.203125
3
[]
no_license
require_relative "string_chunker" require_relative "chiseler" class Chisel attr_reader :input, :output def initialize input = File.read(ARGV[0]) html = StringChunker.new(input).html File.write(ARGV[1], html) puts "Converted #{ARGV[0]} (#{input.count("\n")} lines) to #{ARGV[1]} (#{html.count("\n")} lines)" end end Chisel.new
true
c88953859a56a116535d39d03aa44095a25cbe1a
Ruby
Vince331/http_project
/lib/notes.rb
UTF-8
247
2.984375
3
[]
no_license
class Notes def initialize(notes) @notes = notes end def match(matchers) result = @notes matchers.select do |elem| result = result.select do |x| x.upcase.include? elem.upcase end end result end end
true
f7729ad7b45079dcbb1df085ccf66629b52ae29d
Ruby
bloomberg/cobbler-cookbook
/libraries/cobbler_parse.rb
UTF-8
976
2.578125
3
[ "Apache-2.0" ]
permissive
module Cobbler module Parse include Chef::Mixin::ShellOut def cobbler_distro(distro, field) # Parse Cobbler distro report output # Arguments: distro -- the cobbler distro to get data for # field -- the field to return # Acquire Cobbler output like: # Name : centos-6-x86_64 # Architecture : x86_64 # Breed : redhat # [...] distro_chk = Mixlib::ShellOut.new("cobbler distro report --name='#{distro}'") distro_chk.run_command Chef::Application.fatal!("Cobbler failed with:\nStderr: #{distro_chk.stderr.chomp}\nStdout: #{distro_chk.stdout.chomp}\nReturn code: #{distro_chk.exitstatus}") if distro_chk.error? raw_distro_info = distro_chk.stdout raw_field_line = raw_distro_info.each_line.select { |l| l if l.chomp.start_with?(field) } return raw_field_line.first.split(' : ')[1].chomp end end end
true
3d18a7d2400363be359f10922476def1002754b2
Ruby
richpeck/vat-mtd
/lib/hmrc.rb
UTF-8
3,472
2.765625
3
[ "MIT", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
########################################################## ########################################################## ## __ ____ _______ ______ ## ## / / / / |/ / __ \/ ____/ ## ## / /_/ / /|_/ / /_/ / / ## ## / __ / / / / _, _/ /___ ## ## /_/ /_/_/ /_/_/ |_|\____/ ## ## ## ########################################################## ########################################################## ## HMRC API Wrapper ## ## Uses HTTParty to create simple classes to interact ## ########################################################## ########################################################## ## Class ## ## @hrmc = HMRC.new(vtr) ## ## https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/vat-api/1.0#_retrieve-vat-obligations_get_accordion ## class HMRC ## HTTParty ## ## This allows us to wrap the HTTP/API requests in a wrapper, making it object oriented ## include HTTParty base_uri ENV.fetch("HMRC_API_ENDPOINT", "https://test-api.service.hmrc.gov.uk") #################################### #################################### ## Constructor ## ## Allows us to build out the class properly ## ## @hmrc = HMRC.new current_user.vtr def initialize current_user @vrn = current_user.vrn @access = current_user.access_token @query = { "from": "2020-01-01", "to": "2021-01-01" } @headers = { # Authenication # Required to communicate with oAuth 'Accept': 'application/vnd.hmrc.1.0+json', 'Authorization': 'Bearer ' + @access, # Fraud headers # https://developer.service.hmrc.gov.uk/guides/fraud-prevention/connection-method/web-app-via-server/#gov-vendor-product-name 'Gov-Client-Connection-Method': 'WEB_APP_VIA_SERVER', 'Gov-Client-User-IDs': "vat-mtd=#{current_user.id}", 'Gov-Client-Timezone': "UTC#{Time.now.strftime("%:z")}", 'Gov-Vendor-Version': "vat-mtd=1.0.0" } end #################################### #################################### ## Obligations ## ## This pulls down the submitted returns and gives us a periodKey (which we use to pull individual returns) ## ## The aim is to store all returns in a single table ## def obligations self.class.get(url, { headers: @headers, query: @query }) end ## Returns ## ## Allows us to get individual returns from the API def returns(periodKey) self.class.get(url("returns", periodKey), headers: @headers ) end ## Liabilities ## ## Shows money owed to HMRC def returns(periodKey) self.class.get(url("liabilities"), headers: @headers, query: @query ) end #################################### #################################### ## Private ## private # => URL # => Allows us to create class variable for HMRC endpoint etc # => https://test-api.service.hmrc.gov.uk/organisations/vat/{{ vrn }}/liabilities def url endpoint = "obligations", id = nil [ENV.fetch("HMRC_API_ENDPOINT", "https://test-api.service.hmrc.gov.uk"), "organisations/vat", @vrn, endpoint, id].join("/") end #################################### #################################### end ########################################################## ##########################################################
true
4911f0a32a414d92b4a81c93fec91ca8dfcf8750
Ruby
nkrot/rufsl
/lesson.41/person_age_stub.rb
UTF-8
329
4.09375
4
[]
no_license
#!/usr/bin/env ruby class Person attr_accessor :name def initialize name, age @name = name # object variable @age = age end end alice = Person.new "Alice", 10 bob = Person.new "Bob", 11 puts "Alice older than Bob? " + alice.older_than(bob).to_s puts "Bob older than Alice? " + bob.older_than(alice).to_s
true
5deee0894bdaa353b9ae24bebb473837d5b55846
Ruby
Schwad/assignment_rspec_viking
/spec/bow_spec.rb
UTF-8
578
3.140625
3
[]
no_license
# Your code here require 'weapons/bow' describe Bow do let (:b) {Bow.new} describe '#arrows' do it 'initializes with 10 arrows' do expect(b.arrows).to eq(10) end it 'can initialize with other numbers of arrows' do expect(Bow.new(3).arrows).to eq(3) end end describe '#use' do before {b.use} it 'reduces arrow count with use' do expect(b.arrows).to eq(9) end it 'errors if out of errors' do expect do Bow.new(0).use end.to raise_error(RuntimeError) end end end
true
c3d6e7f27d94fe193ee483f55c8833db2ea7ef5e
Ruby
AgarwalConsulting/ruby_training
/examples/10-higer-order-functions/mapper_block.rb
UTF-8
171
3.6875
4
[]
no_license
def mapper(arr, &block) result = [] for el in arr res_el = yield el result << res_el end result end arr = [1, 2, 3, 4, 5] pp mapper(arr) { |el| el + 1 }
true
a3a8c80c8a5de6158476b62152cac4495712b24d
Ruby
bv4791/PizzaShop_m
/app.rb
UTF-8
859
2.734375
3
[ "MIT" ]
permissive
#encoding: utf-8 require 'rubygems' require 'sinatra' require 'sinatra/reloader' require "sinatra/activerecord" set :database, {adapter: "sqlite3", database: "pizzashop.sqlite3"} class Product < ActiveRecord::Base end class Order < ActiveRecord::Base end get '/' do @products = Product.all erb :index end get '/about' do erb :about end post '/place_order' do @order = Order.create params[:order] erb :order_placed end post '/cart' do orders_input = params[:orders] @items = parse_orders_input orders_input @items.each do |item| # id, cnt item[0] = Product.find(item[0]) end erb :cart end def parse_orders_input orders_input s1 = orders_input.split(/,/) arr = [] s1.each do |x| s2 = x.split(/=/) s3 = s2[0].split(/_/) id = s3[1] cnt = s2[1] arr2 = [id, cnt] arr.push arr2 end return arr end
true
53bb7ad4079fdfffb30f381752f5d256288e6a91
Ruby
Loomus/Fuel_Stations
/app/facades/stations_facade.rb
UTF-8
586
2.640625
3
[]
no_license
class StationsFacade def initialize(location) @location = location end def stations conn = Faraday.new(url: "https://developer.nrel.gov") do |f| f.params['api_key'] = ENV['nrel_api_key'] f.params['location'] = @location f.adapter Faraday.default_adapter end response = conn.get("/api/alt-fuel-stations/v1/nearest.json") station_search_data = JSON.parse(response.body, symbolize_names: true)[:fuel_stations] station_search_data.map do |station_data| Station.new(station_data) end end private attr_reader :location end
true
8174834d3a0274b10df9e8c6e3bbc34faadedaf7
Ruby
dianajohnson13/toy-problems
/ruby/twoSum.rb
UTF-8
416
3.921875
4
[]
no_license
# Write a method that takes an array of numbers. If a pair of numbers # in the array sums to zero, return the positions of those two numbers. # If no pair of numbers sums to zero, return `nil`. def two_sum(nums) contents = {} nums.each_with_index do |num, i| if !contents[-num].nil? return [contents[-num], i] elsif contents[num].nil? contents[num] = i end end return nil end
true
c685d4ed8b688c58c1943f2b52766c2cf2b6c1d3
Ruby
ab-thomas/Inject_and_Takeaway
/Takeaway/spec/Takeaway_spec.rb
UTF-8
775
2.9375
3
[]
no_license
require 'Takeaway' describe Takeaway do let(:takeaway) {Takeaway.new} context 'Menu' it 'should have a list of dishes and prices' do expect(takeaway.menu).to eq( [{ dish: "Dim Sum", price: 4.99 }, { dish: "Steamed Rice", price: 2.50 }, { dish: "Blackbean and Ginger chicken", price: 5.95 }, { dish: "Cantonese duck", price: 5.95 }, { dish: "Lettuce Parcel", price: 4.50 }] ) end context 'Calculate Order' it 'should raise an error if the sum of dishes not correct' do expect(takeaway.calc_order("Dim Sum", 2)).to raise_error end it 'should not raise an error if the sum of dishes is correct' do expect(takeaway.calc_order("Dim Sum", 4.99)).to_not raise_error end end
true
a1729c768f6c6ba4dc3023b61a73791652d16228
Ruby
ludwiggj/ruby-pickaxe
/ch03-classes-objects-variables/bookshop/example_books/book_in_stock_4.rb
UTF-8
403
3.671875
4
[]
no_license
class BookInStock4 def initialize(isbn, price) @isbn = isbn @price = Float(price) end def to_s "ISBN: #{@isbn}, price: #{@price}" end # Explicit accessors def isbn @isbn end def price @price end # Short code for setters attr_writer :isbn, :price end b1 = BookInStock4.new("isbn1", 3) puts b1 b1.price = b1.price * 0.75 b1.isbn = "a new isbn code" puts b1
true
7f0c8bef2fcf29b79fd3861f2d7bc2683bcb840c
Ruby
micktaiwan/rubymlib
/manager/SQLIActions.rb
ISO-8859-1
9,104
2.625
3
[]
no_license
# Usage: le fichier emails.txt dans le mme repertoire doit contenir les emails, un par ligne # TODO: # - ecrire le last action id en blanc pour pouvoir gnrer des emails et ne pas les envoyer :) # - pas beau: les dates vides pour les actions closed # - les actions affiches seules sans classement par group doivent faire apparaitre le group dans la ligne require "ftools" require '../MLib/ExcelFile' require 'Manager' # all these constants (path) must be in a file conf.rb # FROM ='C:\\path_to\\Actions-LOS.xls' # WORKINGFILE ='C:\\local_path_to\\Actions-LOS.xls' # BACKUP ='C:\\backup_path\\Actions-LOS.bak.xls' require 'SQLIconf' #... required here ACTIONCELL = 5 ASSIGNEDCELL= 6 STATUSCELL = 1 RELATEDCELL = 0 ENDDATECELL = 8 IDCELL = 0 RESULTSCELL = 7 GROUPCELL = 4 INITTARGETCELL= 2 TARGETCELL = 2 TYPECELL = 3 DAYS = ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'] class Action attr_accessor :action, :assigned, :status, :group, :end_date, :id, :results, :target def initialize end def status_to_text return case @status when 'EC'; 'in progress' when 'open'; 'open ' when 'closed'; 'closed ' when ''; 'open ' else 'unknown status' end end def status_to_html return case @status when 'EC'; '<i>in progress</i>' when 'open'; '<i>open</i>' when 'closed'; '<i>closed</i>' when ''; '<i>open</i>' else '<b>unknown status</b>' end end end class ActionManager def initialize @actions = [] #print 'copy action file from network (y/n) ? ' #if gets.chomp == 'y' begin;File.copy(WORKINGFILE, BACKUP);rescue;end File.copy(FROM, WORKINGFILE) #puts 'Files copied' #end parse(WORKINGFILE) puts 'end' #puts 'File parsed' end def list_actions #@actions.each { |a| # puts a.action # puts a.status_to_text # } @actions.sort_by{|a| [a.status_to_text,a.assigned]}.each { |a| puts "#{a.status_to_text} #{a.assigned}: #{a.action}" if a.status!='closed' } end def prepare_mail_body # read last number last = 0 begin;File.open('./'+LASTFILE).each { |line| last = line.to_i};rescue;end puts "Last email last action id: #{last}" # new actions group = Hash.new([]) str = '' new_last = 0 nb_total = 0 nb_closed = 0 @actions.each { |a| group[a.assigned] += [a] if a.id > last # last action new_last = a.id if a.id > last # some stats nb_total += 1 nb_closed += 1 if a.status == 'closed' } body = "<u><b>New actions since last email</b></u><ul>" group.each { |group_txt,a_arr| str += "<b>#{group_txt}</b><ul>" a_arr.sort_by{|a| a.target=='' ? Date.today : a.target}.each { |a| str += "<b>#{a.group}</b>: (<i>#{a.status_to_html}</i>) #{display_days_to_target(a.target)} #{a.action}<br/>" str += "<ul><b>Progress:</b> #{a.results}</ul>" if a.results != '' } str += "</ul>" } if str == '' body += 'None' else body += str print 'Reset counter ? ' if gets.chomp == 'y' File.new('./'+LASTFILE,'w') << new_last.to_s end end body += "</ul><br/><br/>" # current actions group.clear body += "<u><b>Current actions</b></u><ul>" @actions.each { |a| group[a.group] += [a] } group.each { |group_txt,a_arr| next if 0 == a_arr.inject(0) {|sum, a| sum + ((a.status=='closed')?0:1)} body += "<b>#{group_txt}</b><ul>" a_arr.each {|a| if a.status!='closed' body += "<b>#{a.assigned}</b>: (<i>#{a.status_to_html}</i>) #{display_days_to_target(a.target)} #{a.action}<br/>" body += "<ul><b>Progress:</b> #{a.results}</ul>" if a.results != '' end } body += "</ul>" } body += "</ul><br/><br/>" # action sorted by holder and target date body += "<u><b>Actions by deadline</b></u><ul>" group.clear @actions.each { |a| group[a.assigned] += [a] } group.each { |group_txt,a_arr| next if 0 == a_arr.inject(0) {|sum, a| sum + ((a.status=='closed')?0:1)} body += "<b>#{group_txt}</b><ul>" a_arr.sort_by{|a| a.target=='' ? Date.today : a.target}.each { |a| if a.status!='closed' body += "<b>#{a.group}</b>: (<i>#{a.status_to_html}</i>) #{display_days_to_target(a.target)} #{a.action}<br/>" body += "<ul><b>Progress:</b> #{a.results}</ul>" if a.results != '' end } body += "</ul>" } body += "</ul><br/><br/>" # closed actions group.clear @actions.each { |a| group[a.end_date] += [a] } body += "<b><u>Closed actions of the last 7 days</b></u><ul>" body += "#{nb_closed}/#{nb_total} = <b>#{nb_closed*100/nb_total}%</b> of all actions closed<br/><br/>" if nb_total > 0 i = 1 group.sort.reverse.each { |group_txt,a_arr| break if group_txt < Date.today - 7 next if 0 == a_arr.inject(0) {|sum, a| sum + ((a.status!='closed')?0:1)} body += "<b>#{DAYS[group_txt.wday()]} #{group_txt.mday()}</b><ul>" a_arr.each {|a| if a.status=='closed' body += "<b>#{a.assigned}: (#{a.group})</b> #{a.action}<br/>" body += "<ul><b>Results:</b> #{a.results}</ul>" if a.results != '' end } body += "</ul>" } body += "</ul><br/><br/>" body += "<font size='-1'><i>Cet email est gnr automatiquement depuis le fichier d'actions (voir Starteam: meta/other)<br/>" body end def send_mail outlook = Manager.new msg = outlook.create_email File.open('./SQLIemails.txt').each_line { |line| line = line.chomp next if line == '' or line[0].chr == '#' msg.recipients.add(line) } msg.subject = "Actions "+Date.today.to_s msg.htmlbody = prepare_mail_body msg.recipients.each { |r| r.resolve } msg.save end def parse(file) puts 'Parsing...' excel = ExcelFile.new excel.open(file) excel.select 2 begin i = 2 while(true) i+=1 and next if excel.cells(i,TYPECELL).text.upcase != 'I' i+=1 and next if excel.cells(i,STATUSCELL).text == 'TBC' action = excel.cells(i,ACTIONCELL).text #puts excel.cells(i,ACTIONCELL).ole_methods puts action break if(action == '') a = Action.new a.action = action a.assigned = excel.cells(i,ASSIGNEDCELL).text a.assigned = '---' if a.assigned == '' a.status = excel.cells(i,STATUSCELL).text a.status = 'open' if a.status != 'open' and a.status != 'in progress' and a.status != 'closed' a.group = excel.cells(i,GROUPCELL).text a.group = 'pas class' if a.group == '' date = excel.cells(i,ENDDATECELL).text begin date = Date.parse(date,true); rescue; date = Date.today(); end a.end_date = date # target date = excel.cells(i,TARGETCELL).text date = excel.cells(i,INITTARGETCELL).text if date == '' begin date = Date.parse(date,true); rescue; date = ''; end a.target = date if IDCELL > 0 a.id = excel.cells(i,IDCELL).text.to_i else a.id = @actions.size+1 end a.results = excel.cells(i,RESULTSCELL).text @actions << a i += 1 end ensure excel.close end end def display_days_to_target(d) return '' if d == '' nb = days_diff(d) return '' if nb > 20 return "<b><font color='#888888'>#{nb} days:</font></b> " if nb > 10 return "<b><font color='#FF8800'>#{nb} days:</font></b> " if nb > 0 return "<b><font color='red'>today:</font></b> " if nb == 0 return "<b><font color='red'>#{nb} days:</font></b> " end def days_diff(d) now = Date.today diff = d - now hours, mins, secs, ignore_fractions = Date::day_fraction_to_time(diff) hours / 24 end end am = ActionManager.new #am.list_actions print 'Send mail ? ' if gets.chomp == 'y' am.send_mail end
true
801b93471ecb1815628ee7f5e5249c46c042b9e6
Ruby
metamorph/tomcat_curl
/tomcat_manager_by_curl.rb
UTF-8
2,934
2.90625
3
[]
no_license
#!/usr/bin/env ruby # vim:ai:sw=2:ts=2 # Provides a ruby wrapper for accessing the Tomcat management REST API through Curl. # The reason for using Curl instead of direct net/http access is to allow this library # to be used with Capistrano (or net/ssh). # Interface to create Curl commands agains the Tomcat endpoint. class Curl def initialize(host, port, user, password) @host, @port, @user, @password = host, port, user, password end def command(name, options = {}) base = "curl -s -u #{@user}:#{@password} http://#{@host}:#{@port}/manager/#{name}" unless options.empty? base << "?" + options.map{|k,v| "#{k}=#{v}"}.join('&') end return Command.new(name, base) end # Wraps the command-line for Curl, and the concrete Command class that can handle the output from the command. class Command attr_reader :name, :command_line def initialize(name, command_line) @name, @command_line = name, command_line end def run_local puts "Executing #{@command_line}" return response(`#{@command_line}`) end def response(curl_output) klass = case @name when 'list' ListResponse when 'roles' RolesResponse when 'resources' ResourcesResponse when 'serverinfo' ServerInfoResponse else Response end klass.new(curl_output) end class Response attr_reader :summary, :lines def initialize(curl_output) @summary = curl_output @lines = curl_output.split("\n").map{|l| l.strip} prepare unless fail? end def message @lines.first end def fail? message =~ /^FAIL/ ? true : false end protected def prepare # 'Abstract' method impl. by subclasses. end end class TupleResponse < Response attr_reader :tuples def find_by(key, value) @tuples.select do |tuple| tuple[key] == value end end def prepare @tuples = [] keys = partitions() # Get partitions. if keys @lines[1..-1].each do |line| tuple = line.split(":") hash = {} keys.each do |k| hash[k] = tuple[keys.index(k)] end @tuples << hash end end end def partitions nil # Override in subclasses. end end class ListResponse < TupleResponse def partitions [:path, :status, :sessions, :name] end end class RolesResponse < TupleResponse def partitions [:name, :description] end end class ResourcesResponse < TupleResponse def partitions [:name, :type] end end class ServerInfoResponse < TupleResponse def partitions [:property, :value] end end end end if __FILE__ == $0 require 'pp' command = ARGV.shift options = {} ARGV.map{|pair| pair.split("=", 2)}.each do |k,v| options[k.to_sym] = v end curl = Curl.new('localhost', 8080, 'admin', 'admin') curl_command = curl.command(command, options) response = curl_command.run_local pp response puts "Command Failed: #{response.fail?}" puts "Summary:" puts response.summary end
true
5c79096664c12aefbfefc02bf948a9d8d63086f0
Ruby
IgnesFatuus/Intro_to_Ruby
/Exercises/Small_Problems/Easy_5/ascii.rb
UTF-8
80
3.1875
3
[]
no_license
def ascii_value(string) sum = 0 string.chars { |c| sum += c.ord } sum end
true
ca6c2920b55d3da62df54b07f1bda6300fa3b04c
Ruby
Lewington-pitsos/launch
/170/sinatra/pad.rb
UTF-8
400
2.734375
3
[]
no_license
s = "I had seen little of Holmes lately. My marriage had drifted us away from each other. My own complete happiness, and the home-centred interests which rise up around the man who first finds himself master of his own establishment, were sufficient to absorb all my attention, while Holmes, who loathed every form of society with his whole Bohemian soul" thing = "I had seen" p [1, 2, 4] - [2]
true