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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
a3568298d72bcb6ee2a1fd16ad9cdddbd0256b7f | Ruby | xord/reflexion | /xot/test/test_bit_flag.rb | UTF-8 | 1,963 | 2.90625 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
require_relative 'helper'
class TestBitFlag < Test::Unit::TestCase
include Xot::BitUtil
def flag(*args, &block)
bf = Xot::BitFlag.new(*args, &block)
bf.flag :bit1, bit(1)
bf.flag :bit2, bit(2)
bf.flag :bit3, bit(3)
bf.flag :bit5, bit(5)
bf.flag :all, bit(1, 2, 3, 5)
bf
end
def test_bits2symbols()
assert_equal [], flag.bits2symbols(0)
assert_equal [:bit1], flag.bits2symbols(bit 1)
assert_equal [:bit2], flag.bits2symbols(bit 2)
assert_equal [:bit5], flag.bits2symbols(bit 5)
assert_equal [:bit1, :bit2], flag.bits2symbols(bit 1, 2)
assert_equal [:bit1, :bit5], flag.bits2symbols(bit 1, 5)
assert_equal [:bit3, :bit5], flag.bits2symbols(bit 3, 5)
assert_equal [:bit1, :bit2, :bit3, :bit5], flag.bits2symbols(bit 1, 2, 3, 5)
assert_raise(RuntimeError) {flag.bits2symbols(bit 0)}
assert_raise(RuntimeError) {flag.bits2symbols(bit 4)}
assert_raise(RuntimeError) {flag.bits2symbols(bit 6)}
assert_raise(RuntimeError) {flag.bits2symbols(bit 0, 1)}
end
def test_symbols2bits()
assert_equal bit(1), flag.symbols2bits(:bit1)
assert_equal bit(2), flag.symbols2bits(:bit2)
assert_equal bit(5), flag.symbols2bits(:bit5)
assert_equal bit(1, 2), flag.symbols2bits(:bit1, :bit2)
assert_equal bit(1, 5), flag.symbols2bits(:bit1, :bit5)
assert_equal bit(3, 5), flag.symbols2bits(:bit3, :bit5)
assert_equal bit(1, 2, 3, 5), flag.symbols2bits(:bit1, :bit2, :bit3, :bit5)
assert_equal 0, flag.symbols2bits(:none)
assert_equal 0, flag.symbols2bits(:no)
assert_equal 0, flag.symbols2bits(:none, :no)
assert_raise(RuntimeError) {flag.symbols2bits(:bit0)}
assert_raise(RuntimeError) {flag.symbols2bits(:bit4)}
assert_raise(RuntimeError) {flag.symbols2bits(:bit6)}
assert_raise(RuntimeError) {flag.symbols2bits(:bit0, :bit1)}
assert_raise(RuntimeError) {flag.symbols2bits(nil)}
end
end# TestBitFlag
| true |
2320c6aae9a6c3c1768aecf10102a6b3bb6ab50a | Ruby | CitizenofWorld/WDI_13_HOMEWORK | /Jessica Sole/wk04/3-wed/monkey/monkey.rb | UTF-8 | 335 | 3.890625 | 4 | [] | no_license |
class Monkey
def initialize(name, species)
@name = name
@species = species
@foods_eaten = []
end
def name
return @name
end
def species
return @species
end
def eat(food)
@foods_eaten.push food
end
def introduce
puts "Hi my name is #{@name}. I am a #{@species}. I had #{@foods_eaten} for brunch"
end
end
| true |
c975262e13e6ce1032ed047625014d6bd370de70 | Ruby | cheaphunter/stackskills-dl | /lib/utilities.rb | UTF-8 | 376 | 2.84375 | 3 | [
"MIT"
] | permissive | class Utilities
class << self
def escape_chars(string)
string.tr('(', '-').tr(')', '-').tr(' ', '_').tr("\\", "-").tr("/", "-").tr(":", "-").tr("*", "-").tr("?", "-").tr("<", "-").tr(">", "-").tr("|", "-").tr("\"", "-").tr("&", "and")
end
def mkchdir(dir)
system 'mkdir', '-p', dir
Dir.chdir(dir) do
yield
end
end
end
end | true |
8d56bf311b097a62fe2bf69c28200af96ee832d9 | Ruby | scy0626/kakaobot_maple | /app/controllers/kakao_controller.rb | UTF-8 | 1,322 | 2.515625 | 3 | [] | no_license | class KakaoController < ApplicationController
def keyboard
@msg = {type: "buttons",
buttons: ["소개", "가입문의", "거래"]}
render json: @msg, status: :ok
end
def message
@result = params[:content]
if @result.include? "소개" or @result.include? "순하리"
@msg = {
message: { text: ["안녕하세요 메이플스토리 제니스 서버 [순하리] 길드입니다!.","제니스 대표 길드입니다."].sample},
keyboard: { type: "text"}
}
render json: @msg, status: :ok
elsif
@result.include? "가입문의" or @result.include? "가입"
@msg = {
message: { text: ["인겜닉 '포션좀사쥬' 로 연락주세요","인겜닉 '쁘띠정복자' 로 연락주세요"].sample},
keyboard: { type: "text"}
}
render json: @msg, status: :ok
elsif
@result.include? "거래"
@msg = {
message: { text: "무슨 종류를 거래 하시나요? 1.메소거래를 원하시면 'ㅁㅅ' 2.ㅁㅌ 아이템 거래를 원하시면 'ㅁㅌ' "},
keyboard: { type: "text"}
}
render json: @msg, status: :ok
else
@msg = {
message: { text: "??"},
keyboard: { type: "text"}
}
render json: @msg, status: :ok
end
end
end
| true |
8fed65f5cb655da3726c31d84b72f9149c4426e1 | Ruby | Mattieuga/CodeNow-May2014 | /makeal/colors_bella.rb | UTF-8 | 594 | 3.5 | 4 | [] | no_license | require 'colorize'
require 'win32console'
puts "Codenow".colorize(:blue)
colors_list= [:red, :green, :blue, :yellow, :magenta, :cyan, :white]
#ask user for message
puts "Say Something"
user_message=gets.chomp
#print user message in color
round=0
begin
letters_printed = 0
user_message.each_char do |character|
print character.colorize(colors_list[letters_printed % colors_list.length])
letters_printed=letters_printed +1
end
puts ""
round=round+1
puts round
sleep 0.5
end while round < 5
begin
puts colors_list.sample.to_s.colorize(colors_list.sample)
sleep 0.5
system("cls")
end while true | true |
6a81afb3b8a2c2d2bf538f360674017ef469ab21 | Ruby | vanakenm/tdd-examples | /v3-play/src/game.rb | UTF-8 | 154 | 3.34375 | 3 | [] | no_license | class Game
attr_reader :pieces
def initialize
@pieces = 0
end
def empty?
pieces == 0
end
def play(x, y)
@pieces += 1
end
end
| true |
56068030a9fd15412a427f88a8f6a24ba3f3b1b8 | Ruby | imranariffin/coding-practice | /125/cg_125_easy.rb | UTF-8 | 450 | 3.53125 | 4 | [] | no_license | # @param {String} s
# @return {Boolean}
def is_palindrome(s)
return true if s.empty?
i1 = 0
i2 = s.length - 1
while i1 < i2
if i1 < s.length && !(s[i1] =~ /[A-Za-z0-9]/)
i1 += 1
next
end
if i2 >= 0 && !(s[i2] =~ /[A-Za-z0-9]/)
i2 -= 1
next
end
return false if s[i1].downcase != s[i2].downcase
i1 += 1
i2 -= 1
end
true
end
| true |
d065784f21419d91c3a3ccbbf1133e25cbde8b76 | Ruby | errnox/some-ruby-things | /launchcli/launchcli | UTF-8 | 874 | 3.125 | 3 | [] | no_license | #!/usr/bin/env ruby
class Launchcli
def initialize()
@choices = [];
@commands_file_name = '.launchcli'
@commands_file_location = Dir.home + '/' + @commands_file_name
@options = read_commands_file()
@separator = '-' * 75
end
public
def run()
print("Search: ")
search_string = gets
matches = @options.find_all do |s|
Regexp.new(search_string.strip) =~ s
end
puts
matches.each_with_index { |s, i| puts("#{"%4d" % (i + 1)} #{s}")}
print("\nChose: ")
choice = gets.strip.to_i - 1
command = matches[choice]
puts("\nRun:\n" + command)
puts(@separator)
exec(command)
end
private
def read_commands_file()
@options = File.open(@commands_file_location, 'r').read().split("\n")
end
end
launchcli = Launchcli.new();
begin
launchcli.run();
rescue
puts('Something went wrong.')
end
| true |
f84350031639e3fa9e33ce66869778a3313d0bca | Ruby | DerekYu177/testbed | /ping.rb | UTF-8 | 2,600 | 3.03125 | 3 | [] | no_license | require "descriptive_statistics"
def block_into_small_arrays(input)
arr = []
input.each_line do |line|
arr << line
end
arr
end
def find_time_in_each_line(array)
data_set = []
array.each do |line|
break unless time_without_time = line.match(/time=\d*.\d*/)
time_with_time = time_without_time[0].gsub("time=","")
data_set << time_with_time.to_f
end
data_set
end
def compute_dataset(data)
modified_data = block_into_small_arrays(data)
find_time_in_each_line(modified_data)
end
def print_stats(array)
puts "MIN: #{array.min}"
puts "MAX: #{array.max}"
puts "MEAN #{array.mean}"
puts "MEDIAN: #{array.median}"
puts "ST_DEV: #{array.standard_deviation}"
end
data = "64 bytes from 91.121.23.186: icmp_seq=0 ttl=53 time=90.294 ms
64 bytes from 91.121.23.186: icmp_seq=1 ttl=53 time=89.307 ms
64 bytes from 91.121.23.186: icmp_seq=2 ttl=53 time=90.314 ms
64 bytes from 91.121.23.186: icmp_seq=3 ttl=53 time=89.594 ms
64 bytes from 91.121.23.186: icmp_seq=4 ttl=53 time=87.465 ms
64 bytes from 91.121.23.186: icmp_seq=5 ttl=53 time=89.151 ms
64 bytes from 91.121.23.186: icmp_seq=6 ttl=53 time=89.116 ms
64 bytes from 91.121.23.186: icmp_seq=7 ttl=53 time=161.380 ms
64 bytes from 91.121.23.186: icmp_seq=8 ttl=53 time=89.168 ms
64 bytes from 91.121.23.186: icmp_seq=9 ttl=53 time=87.530 ms
64 bytes from 91.121.23.186: icmp_seq=10 ttl=53 time=89.057 ms
64 bytes from 91.121.23.186: icmp_seq=11 ttl=53 time=89.306 ms
64 bytes from 91.121.23.186: icmp_seq=12 ttl=53 time=88.880 ms
64 bytes from 91.121.23.186: icmp_seq=13 ttl=53 time=88.988 ms
64 bytes from 91.121.23.186: icmp_seq=14 ttl=53 time=89.535 ms
64 bytes from 91.121.23.186: icmp_seq=15 ttl=53 time=89.159 ms
64 bytes from 91.121.23.186: icmp_seq=16 ttl=53 time=89.265 ms
64 bytes from 91.121.23.186: icmp_seq=17 ttl=53 time=242.539 ms
64 bytes from 91.121.23.186: icmp_seq=18 ttl=53 time=90.512 ms
64 bytes from 91.121.23.186: icmp_seq=19 ttl=53 time=86.709 ms
64 bytes from 91.121.23.186: icmp_seq=20 ttl=53 time=89.033 ms
64 bytes from 91.121.23.186: icmp_seq=21 ttl=53 time=89.228 ms
64 bytes from 91.121.23.186: icmp_seq=22 ttl=53 time=89.182 ms
64 bytes from 91.121.23.186: icmp_seq=23 ttl=53 time=89.114 ms
64 bytes from 91.121.23.186: icmp_seq=24 ttl=53 time=89.164 ms
64 bytes from 91.121.23.186: icmp_seq=25 ttl=53 time=89.111 ms
64 bytes from 91.121.23.186: icmp_seq=26 ttl=53 time=87.675 ms
64 bytes from 91.121.23.186: icmp_seq=27 ttl=53 time=89.847 ms
64 bytes from 91.121.23.186: icmp_seq=28 ttl=53 time=89.452 ms
64 bytes from 91.121.23.186: icmp_seq=29 ttl=53 time=88.932 ms
"
print_stats(compute_dataset(data))
| true |
d481501a9f456759851862ae32650bade08e8ee0 | Ruby | akr/webapp | /sample/query.cgi | UTF-8 | 1,195 | 2.53125 | 3 | [
"BSD-3-Clause"
] | permissive | #!/usr/bin/env ruby
require 'webapp'
require 'pathname'
Template = <<'End'
<html>
<head>
<title>query sample</title>
</head>
<body>
<form _attr_action="webapp.make_relative_uri">
Menu:
<select name=menu multiple>
<option selected>mizuyoukan</option>
<option>anmitsu</option>
<option>azukiyose</option>
</select>
<input type=hidden name=form_submitted value=yes>
<input type=submit>
</form>
<hr>
<p>
Since WebApp#validate_html_query validates a query
according to a given form,
impossible query such as <a _attr_href="webapp.make_relative_uri(:query=>{'menu'=>'kusaya'})">kusaya</a> is
ignored because WebApp#validate_html_query raises
WebApp::QueryValidationFailure exception.
</p>
<div _if="q">
<hr>
<table border=1>
<tr><th>name<th>value</tr>
<tr _iter="q.each//key,val">
<td _text=key>key<td _text=val>val</tr>
</table>
</div>
</body>
</html>
End
WebApp {|webapp|
begin
q = webapp.validate_html_query(Template)
rescue WebApp::QueryValidationFailure
q = nil
end
HTree.expand_template(webapp) {Template}
}
| true |
079dca776f6a2ab418c0c817e479568bdd10e7b4 | Ruby | blahutka/terminitor | /lib/terminitor/abstract_capture.rb | UTF-8 | 1,158 | 2.859375 | 3 | [
"MIT"
] | permissive | module Terminitor
# This AbstractCapture defines the basic methods that the Capture class should inherit
class AbstractCapture
# Generates .term file from settings of currently opened terminal windows and tabs
def capture_settings
capture_windows.inject("") do |config, w|
config << generate_object_dsl('window', w) do |dsl|
w[:tabs].each do |t|
dsl << generate_object_dsl('tab', t, 4)
end
end
end
end
# Returns array of settings of currently opened windows,
# [{:options => {:window_option1 => ... }, :tabs => [{:options => {:tab_option1 => ... }}]}]
# Needs to be defined for specific platform
def capture_windows
end
private
# Helper method to generate the .term file
def generate_object_dsl(name, object, ident = 0, &block)
dsl, margin = "", " "*ident
params = object[:options].inject([]) do |params, option|
params << ":#{option[0]} => #{option[1].inspect}"
end.join(", ")
dsl << margin + "#{name} #{params} do\n"
yield(dsl) if block_given?
dsl << margin + "end\n\n"
end
end
end
| true |
6023173450f9dfb643de3dc608dbb85fc6bca750 | Ruby | benedictkohtc/WDI-Project3-WhereWork | /lib/tasks/seed_from_google_places.rake | UTF-8 | 5,445 | 2.59375 | 3 | [] | no_license | # normally, use rails db:seed instead of running this task,
# this task is only for getting new data from Google Places from scratch.
# populates locations from Google Places
# makes random values for some fields
# will get photos and upload them to Cloudinary also,
# so you need valid Cloudinary account data in config/cloudinary.yml
# run "rails add_opening_times" after this task to add opening times to all locations
task seed_from_google_places: :environment do
require 'rubygems'
require 'httparty' # need to gem install
require 'json'
@API_key = ENV['GOOGLE_PLACES_API_KEY']
# for getting 60 locations from Google Places
@nearbysearch_url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/'
@output_type = 'json'
startlat = 1.2984459
startlong = 103.825591
endlat = 1.308294
endlong = 103.847305 # roughly the length of Orchard Roads
# 1.1km north to south
# 2.5km west to east
longstep = 0.002814
latstep = 0.00246
# latitude = 1.3072052
# longitude = 103.831843 # this latlong is 8 Claymore Hill
@radius = '400' # meters, max 50000
@type = 'cafe' # only matches one type per request,
# for getting photo from Google Places Photos
@places_photo_url = 'https://maps.googleapis.com/maps/api/place/photo'
@maxheight = '800'
@maxwidth = '800'
def add_data_to_locations_table(results)
results.each do |result_hash|
if Location.find_by(google_place_id: result_hash['place_id'])
next # skip location if already in table
end
location = Location.new do |l|
l.lat = result_hash['geometry']['location']['lat']
l.lng = result_hash['geometry']['location']['lng']
l.icon = result_hash['icon']
l.name = result_hash['name']
if result_hash['photos'] # saving only reference for first photo
l.google_photo_reference = result_hash['photos'][0]['photo_reference']
photo_args_string = 'key=' + @API_key + \
'&photoreference=' + l.google_photo_reference + \
'&maxheight=' + @maxheight + '&maxwidth=' + @maxwidth
response = HTTParty.get(@places_photo_url + '?' + photo_args_string)
File.open("#{result_hash['place_id']}.jpg", 'wb') do |f|
f.write response.body
end
cloudinary_response = Cloudinary::Uploader.upload("#{result_hash['place_id']}.jpg")
puts "uploading image #{result_hash['place_id']} to cloudinary"
l.cloudinary_link = cloudinary_response['secure_url']
File.delete("#{result_hash['place_id']}.jpg")
end
l.google_place_id = result_hash['place_id']
l.google_rating = result_hash['rating']
l.vicinity = result_hash['vicinity']
# looks like street address but not reliable
l.coffee = rand(2) == 1 ? true : false
l.quiet = rand(2) == 1 ? true : false
l.wifi = rand(2) == 1 ? true : false
l.wifi_name = l.name.squish.downcase.tr(' ', '_')[0..12] + rand(9).to_s + rand(9).to_s if l.wifi
l.wifi_password = ('a'..'z').to_a.sample(8).join if l.wifi
l.aircon = rand(2) == 1 ? true : false
l.total_sockets = rand(2) == 1 ? rand(10) : 0
l.available_sockets = (l.total_sockets / 2).floor
l.total_seats = 20 + rand(30)
l.available_seats = rand(20)
end
location.save
end
end
def add_location(latitude, longitude)
location = latitude.to_s + ',' + longitude.to_s
puts('requesting from Google Places at location ' + location)
args_string = '&key=' + @API_key + '&location=' + location + \
'&radius=' + @radius + '&type=' + @type
puts 'making first HTTP request to Google Places..'
response = HTTParty.get(@nearbysearch_url + @output_type + '?' + args_string)
results_first_twenty = JSON.parse(response.body)['results']
next_page_token = JSON.parse(response.body)['next_page_token']
return if results_first_twenty == nil
return if next_page_token == nil
puts 'adding data for first twenty locations...'
add_data_to_locations_table(results_first_twenty)
puts 'waiting two seconds to let next_page_token become valid...'
sleep(2)
puts 'making second HTTP request (second page)...'
args_string = '&key=' + @API_key + '&pagetoken=' + next_page_token
response = HTTParty.get(@nearbysearch_url + @output_type + '?' + args_string)
results_second_twenty = JSON.parse(response.body)['results']
next_page_token = JSON.parse(response.body)['next_page_token']
return if results_second_twenty == nil
return if next_page_token == nil
puts 'adding data for next twenty locations...'
add_data_to_locations_table(results_second_twenty)
puts 'waiting two seconds to let next_page_token become valid...'
sleep(2)
puts 'making third HTTP request (third page)...'
args_string = '&key=' + @API_key + '&pagetoken=' + next_page_token
response = HTTParty.get(@nearbysearch_url + @output_type + '?' + args_string)
results_third_twenty = JSON.parse(response.body)['results']
return if results_third_twenty == nil
puts 'adding data for next twenty locations...'
add_data_to_locations_table(results_third_twenty)
puts "all done for latlong pair."
end
(startlat..endlat).step(latstep) do |lat|
(startlong..endlong).step(longstep) do |long|
add_location(lat,long)
end
end
end
| true |
3815a950ea0ff84af70afb9028553927170be2ed | Ruby | gemcfadyen/Apprenticeship-RubyRackWebTicTacToe | /lib/ttt_controller.rb | UTF-8 | 1,501 | 2.71875 | 3 | [] | no_license | require 'game_parameters'
require 'player_options'
require 'web_ttt'
require 'board_adapter'
require 'players'
class TTTController
def self.call(env)
route = env['REQUEST_PATH']
request = Rack::Request.new env
if route == '/favicon.ico'
default_success_response
elsif route == '/'
show_player_options
elsif route == '/player_options'
start_game(request, env);
elsif route == '/next_move'
play_move(request)
end
end
private
def self.erb(template)
@player_options = PlayerOptions::all
path = File.expand_path("#{template}", "views")
ERB.new(File.read(path)).result(binding)
end
def self.default_success_response
[200, {}, []]
end
def self.show_player_options
template = erb('player_options.erb')
[200, {}, [template]]
end
def self.start_game(request, env)
chosen_player_type = request.params[GameParameters::PLAYER_TYPE]
env['rack.session'][GameParameters::PLAYER_TYPE] = chosen_player_type
@game_state = WebTTT.new(GameParameters.new(request.params, request.session, BoardAdapter.new), Players.new, GridFormatter.new).play
game_page
end
def self.game_page
template = erb('game.erb')
[200, {}, [template]]
end
def self.play_move(request)
updated_state = WebTTT.new(GameParameters.new(request.params, request.session, BoardAdapter.new), Players.new, GridFormatter.new).play_move
[200, {'Content-Type' => 'json'}, [updated_state.as_json]]
end
end
| true |
d02a9e8454024e86ec63c08988b18f7f7951e318 | Ruby | hwalborn/project-euler-largest-palindrome-product-web-0217 | /lib/oo_largest_palindrome_product.rb | UTF-8 | 334 | 3.25 | 3 | [] | no_license | # Implement your object-oriented solution here!
class LargestPalindromeProduct
def answer
max = 0
(900..999).each do |num_1|
(900...num_1).each do |num_2|
if((num_1 * num_2).to_s.split('') == (num_1 * num_2).to_s.split('').reverse)
max = num_1 * num_2
end
end
end
max
end
end
| true |
82d327165494533eeadc864ad5fa56eee3bf0faf | Ruby | TheJefe/gplan | /lib/printer.rb | UTF-8 | 2,910 | 2.953125 | 3 | [] | no_license | require 'haml'
class Printer
def html stories
$stories = stories
file_path = File.expand_path('../../templates/template.html.haml', __FILE__)
template = File.read(file_path)
engine = Haml::Engine.new(template)
File.write 'releasenotes.html',engine.render
end
def print stories
dependencies = []
# Github stories only
release_notes = "PR:TITLE:ISSUES:MILESTONE\n"
stories.each do |story|
next if Planbox.has_planbox?(story)
dependency = get_dependency(story)
dependencies << "PR ##{story['number']}: " + dependency unless dependency.nil?
line = ""
line += github_pr_info(story) unless story['number'].nil?
release_notes += line + "\n"
end
# Planbox matching stories
if Planbox.has_planbox?(stories)
release_notes += title "Matched Planbox Stories"
release_notes += "ID:STATUS:TITLE:PROJECT_NAME:PROJECT_ALIAS:PR:TITLE\n"
stories.each do |story|
next unless Planbox.has_planbox?(story)
dependency = get_dependency(story)
dependencies << "PR ##{story['number']}: " + dependency unless dependency.nil?
line = ""
line += planbox_info(story)
line += github_pr_info(story) unless story['number'].nil?
end
end
# print dependency blocks
unless dependencies.empty?
release_notes += include_dependencies dependencies
end
puts release_notes
end
def get_dependency(story)
# find dependency based on blocks
unless story['blocks'].nil?
story['blocks'].each do |block|
if block.split("\n")[0].match(/(^(#* *depend(s|ent|ency|encies|encys)))/i)
return block
end
end
end
# find a line starting with 'depends on' in body
if story['body']
dependency = story['body'].match(/^(depend(s|ent)? +on.*)/i)
return dependency[0] if dependency
end
return if story['labels'].nil?
# else find dependency based on labels
if story['labels'].to_s.match /Has Dependency/i
return "has a dependency label"
end
return nil
end
def planbox_info story
"#{story['id']}:#{story['status']}:#{story['name']}:#{story['project_name']}:#{story['project_alias']}"
end
def github_pr_info story
line = ":#{story['number']}:#{story['title']}"
line += github_issue_info(story) if story['linked_issues']
line
end
def github_issue_info story
line = ""
story['linked_issues'].each do |issue|
line += ":ISSUE##{issue['number']}"
line +=":Milestone #{issue['milestone']['title']}" if issue['milestone']
end
line
end
def include_dependencies dependencies
release_notes = title "Dependencies"
dependencies.each do |dependency|
release_notes += dependency
release_notes += "\n"
end
release_notes
end
def title text
"\n---- #{text} ----\n\n"
end
end
| true |
c2b9d9aadcca6d5d18e3efaab9f425046867e75b | Ruby | AliYous/Mini-Jeu-POO | /lib/player.rb | UTF-8 | 2,560 | 3.859375 | 4 | [] | no_license |
#------------------------------------------------------------ CLASS ------------------------------------------------------------
class Player
attr_accessor :name, :life_points
def initialize(name)
@name = name
@life_points = 10
end
#Affiche l'état de pdv actuel du player sur lequel la méthode est appliquée
def show_state
puts "#{@name} a #{@life_points} points de vie"
end
#Réduit les life_points du personnage sur lequel la methode est appellée
def gets_damage(damage_value)
self.life_points -= damage_value
puts "Le joueur #{self.name} à été tué :(" if self.life_points <= 0
end
def attack(attacked_player)
puts "\nle joueur #{self.name} attaque le joueur #{attacked_player.name}"
damage = compute_damage
puts "Il lui inflige #{damage} points de dommage.\n"
attacked_player.gets_damage(damage)
end
#Génère aléatoirement les dégats causés lors d'une attaque
def compute_damage
return rand(1..6)
end
end
#------------------------------------------------------------ CLASS ------------------------------------------------------------
class HumanPlayer < Player
attr_accessor :weapon_level
def initialize(name)
@name = name
@life_points = 100
@weapon_level = 1
end
def show_state
puts "#{@name} a #{@life_points} points de vie et une arme de niveau #{@weapon_level}"
end
def attack(bot_to_attack)
puts "\nle joueur #{@name} attaque le bot #{bot_to_attack.name}"
damage = compute_damage
puts "Il lui inflige #{damage} points de dommage.\n"
bot_to_attack.gets_damage(damage)
end
def compute_damage
rand(1..6) * @weapon_level
end
def search_weapon
found_weapon_level= rand(1..6)
puts "Tu as trouvé une arme de niveau #{found_weapon_level}"
if @weapon_level >= found_weapon_level #Si l'arme actuelle est mieux que l'arme trouvée, on garde l'arme actuelle
puts "Cette arme est naze! C'est mieux que tu gardes la tienne"
elsif @weapon_level < found_weapon_level
@weapon_level = found_weapon_level
puts "OhYeaaaah! Cette arme est mieux que ton arme actuelle, tu la gardes"
end
end
def search_health_pack
random_dice = rand(1..6)
if random_dice == 1
puts "vous n'avez rien trouvé"
elsif random_dice >= 2 && random_dice <= 5
puts "Bravo, tu as trouvé un pack de +50 points de vie !"
@life_points += 50
elsif random_dice == 6
puts "Wooooow, tu as trouvé un pack de +80 points de vie !"
if @life_points > 20
@life_points += (100 - @life_points)
else
@life_points += 80
end
end
end
end | true |
4b0015153be6000a5e06cc75587287f5560e2152 | Ruby | townie/sorting_alogrithims | /merge_sort.rb | UTF-8 | 1,576 | 3.734375 | 4 | [] | no_license | require 'benchmark'
def merge_sort(array)
return array if array.length <= 1
left = array.shift(array.length/2)
right = array
left = merge_sort(left)
right = merge_sort(right)
sorted_list = []
until left.empty? && right.empty?
if left.empty?
sorted_list<<right.shift
elsif right.empty?
sorted_list<<left.shift
elsif left.first < right.first
sorted_list << left.shift
else
sorted_list << right.shift
end
end
return sorted_list
end
def merge_sort_pop(array)
return array if array.length <= 1
left = array.pop(array.length/2)
right = array
left = merge_sort(left)
right = merge_sort(right)
sorted_list = []
until left.empty? && right.empty?
if left.empty?
sorted_list<<right.shift
elsif right.empty?
sorted_list<<left.shift
elsif left.last < right.last
sorted_list << left.pop
else
sorted_list << right.pop
end
end
return sorted_list
end
def create_rand_array(length_of_array= 230)
stuff =[]
(length_of_array).times do
stuff<< rand(200000000)
end
stuff
end
stuff= create_rand_array(4000000)
puts "Shift sort #{stuff.length}"
use = stuff.dup
puts Benchmark.measure { merge_sort(use)}
use = stuff.dup
puts Benchmark.measure { merge_sort(use)}
use = stuff.dup
puts Benchmark.measure { merge_sort(use)}
use = stuff.dup
puts "Pop sort #{use.length}"
puts Benchmark.measure { merge_sort_pop(use)}
use = stuff.dup
puts Benchmark.measure { merge_sort_pop(use)}
use = stuff.dup
puts Benchmark.measure { merge_sort_pop(use)}
| true |
cc89b5bb9c6470a433dc25656d24e1c8bc76c314 | Ruby | dileep-g/Cord-Cutter | /app/helpers/webparser/parser.rb | UTF-8 | 2,172 | 3.03125 | 3 | [] | no_license | require 'webdrivers'
require 'watir'
require 'nokogiri'
require 'htmlentities'
module WebParser
def WebParser.parse_page(url)
# load all channels from database
channels_in_db = []
Channel.all.each do |channel|
channels_in_db << channel.name.delete(' ').downcase
end
# load page
browser = Watir::Browser.new :firefox, profile: 'default', headless: true
# browser = Watir::Browser.new(:chrome, {:chromeOptions => {:args => ['--headless', '--window-size=1200x600']}})
# browser.goto("https://try.philo.com/")
# browser.goto("https://www.hulu.com/live-tv")
# browser.goto("https://tv.youtube.com/welcome/")
# browser.goto("https://www.fubo.tv/welcome/channels")
browser.goto(url)
sleep 1
puts "Page loaded: %s" % browser.title
document = Nokogiri::HTML(browser.body.html)
html_coder = HTMLEntities.new
html_channel_class = ""
html_channel_attr = ""
document.traverse do |node|
next unless node.is_a?(Nokogiri::XML::Element)
alt = html_coder.decode(node['alt']).delete(' ').downcase
title = html_coder.decode(node['title']).delete(' ').downcase
if channels_in_db.include?(alt)
puts "Class: %s, alt: %s" % [node['class'], node['alt']]
html_channel_class = node['class']
html_channel_attr = 'alt'
break
end
if channels_in_db.include?(title)
puts "Class: %s, title: %s" % [node['class'], node['title']]
html_channel_class = node['class']
html_channel_attr = 'title'
break
end
end
# extract elements with class == <html_channel_class>
channels_in_page = []
document.traverse do |node|
next unless node.is_a?(Nokogiri::XML::Element)
if node['class'] == html_channel_class
channels_in_page << node[html_channel_attr]
end
end
puts channels_in_page
end
end | true |
0d8acd21359d3ba6707c0b8948d4fc94b77fe848 | Ruby | Takhmina175/tic-tac-toe-game | /lib/players.rb | UTF-8 | 228 | 3.0625 | 3 | [
"MIT"
] | permissive | class Player
attr_accessor :curr_player
def self.input_range?(input)
input.negative? || input > 8
end
def self.switch_input(curr_input = 'X')
if curr_input == 'X'
'O'
else
'X'
end
end
end
| true |
abf6e3a52044f62aa68545b3c8d5d768907c431d | Ruby | keeks5456/ruby-enumerables-cartoon-collections-lab-part-2-sfo01-seng-ft-060120 | /cartoon_collections.rb | UTF-8 | 507 | 3.25 | 3 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | require 'pry'
def square_array(array)
array.map do |squared|
squared * squared
end
end
def summon_captain_planet(planeteer_calls)
planeteer_calls.collect{ |calls| "#{calls.capitalize}" + "!"}
end
def long_planeteer_calls(planeteer_calls)
planeteer_calls.any? do |elements|
elements.length > 4
end
end
def find_valid_calls(planeteer_calls)
valid_calls = ["Earth!", "Wind!", "Fire!", "Water!", "Heart!"]
planeteer_calls.find do |valid|
valid_calls.include? valid
# binding.pry
end
end
| true |
24244b16af51d699517ceea002c74125e1f67679 | Ruby | emarquez26/exerciseRuby | /Forkme/e1_rubycalculator.rb | UTF-8 | 2,216 | 4 | 4 | [] | no_license | puts "-------------Bienvenido a la calculadora-------------"
resp="si"
while resp=="si"
def menu
puts "1.- sumar"
puts "2.-restar"
puts "3.-multiplicar"
puts "4.-dividir"
puts "5.-Raiz cuadrada"
puts "6.-Factorial"
puts "7.Exponencia"
puts ""
puts "Digite opcion a escojer para realizar operacion "
end
menu
opcion = gets.chomp.to_i
if opcion==1 || opcion==2 || opcion==3 || opcion==4 || opcion==7
puts "Digite numero 1" ; @num1=gets.chomp.to_i
puts "Digite numero 2" ; @num2=gets.chomp.to_i
def suma
result_sum=@num1 + @num2
return "-> La suma de los numeros #{@num1} y #{@num2} es: #{result_sum}"
end
def resta
result_rest=@num1 - @num2
return "-> La resta de los numeros #{@num1} y #{@num2} es: #{result_rest}"
end
def multipl
result_multipli=@num1 * @num2
return "-> La multiplicacion de los numeros #{@num1} y #{@num2} es: #{result_multipli}"
end
def divic
result_div=@num1 / @num2
return "-> La divicion suma de los numeros #{@num1} y #{@num2} es: #{result_div}"
end
def expon
result_exp= @num1 ** @num2
end
case opcion
when 1
p method(:suma).call
when 2
p method(:resta).call
when 3
p method(:multipl).call
when 4
p method(:divic).call
when 7
p method(:expon).call
end
elsif opcion==5 || opcion==6
case opcion
when 5
def raiz
puts "Digite numero a sacar Raiz cuadrada" ; @numr=gets.chomp.to_i
result_raiz=Math.sqrt(@numr)
end
p method("raiz").call
when 6
puts "Digite numero a sacar Factorial" ; @numf=gets.chomp.to_i
def factorial(n)
if n == 0
1
else
n * factorial(n-1)
end
end
p factorial(@numf.to_i)
end
else
puts "Error opcion no se encuentra disponible vuelva a intentarlo"
end
puts "desea continuar(si/no)"
resp=gets.chomp.to_s
end | true |
ec24c25c1fc477def6be8391a7a6e4fa9c4f84bc | Ruby | igorpertsev/rest_api | /spec/commands/contracts/bulk_import_spec.rb | UTF-8 | 2,917 | 2.53125 | 3 | [] | no_license | require 'rails_helper'
RSpec.describe Contracts::BulkImport do
let(:customer) { create(:customer, password: '123test') }
describe '#call' do
subject { described_class.call(customer.id.to_s, params) }
context 'valid parameters' do
let(:params) do
[
{
price: Faker::Number.number(digits: 5),
start_date: Faker::Time.between(from: 10.days.ago, to: 10.days.since),
end_date: Faker::Time.between(from: 10.days.ago, to: 10.days.since),
expiry_date: Faker::Time.between(from: 10.days.ago, to: 30.days.since)
}, {
price: Faker::Number.number(digits: 2),
start_date: Faker::Time.between(from: 10.days.ago, to: 10.days.since),
end_date: Faker::Time.between(from: 10.days.ago, to: 10.days.since),
expiry_date: Faker::Time.between(from: 10.days.ago, to: 30.days.since)
}
]
end
it 'is successful' do
expect(subject.success?).to be_truthy
end
it 'creates new contracts' do
expect { subject }.to change { Contract.count }.by(2)
end
it 'returns amount of imported contracts' do
expect(subject.result).to eq(2)
end
it 'creates contracts with valid attributes' do
subject
params.each do |contracts_data|
expect(::Contract.where(contracts_data).count).to eq(1)
end
end
end
context 'invalid parameters' do
let(:params) do
[
{
price: -5,
start_date: Faker::Time.between(from: 10.days.ago, to: 10.days.since),
end_date: Faker::Time.between(from: 10.days.ago, to: 10.days.since),
expiry_date: Faker::Time.between(from: 10.days.ago, to: 30.days.since)
}, {
price: Faker::Number.number(digits: 2),
start_date: Faker::Time.between(from: 10.days.ago, to: 10.days.since),
end_date: Faker::Time.between(from: 10.days.ago, to: 10.days.since),
expiry_date: Faker::Time.between(from: 10.days.ago, to: 30.days.since)
}
]
end
it 'is not successful' do
expect(subject.success?).to be_falsey
end
it 'creates only valid contracts' do
expect { subject }.to change { Contract.count }.by(1)
end
it 'returns amount of imported contracts' do
expect(subject.result).to eq(1)
end
it 'imports contracts with correct data' do
subject
contracts_data = params.last
expect(::Contract.where(contracts_data).count).to eq(1)
end
it 'returns errors for contracts' do
reason = "#{params.first.to_s} Price must be greater than or equal to 0"
expect(subject.errors.full_messages.count).to eq(1)
expect(subject.errors.full_messages.first).to eq(reason)
end
end
end
end
| true |
c4cf781ce60d6edcf0e1d8b7d123b25a46511a41 | Ruby | JoeQuattrone/j_travel | /app/models/hotel.rb | UTF-8 | 2,490 | 2.765625 | 3 | [] | no_license | require 'nokogiri'
require 'open-uri'
require 'rest-client'
require 'net/http'
require 'json'
class Hotel < ApplicationRecord
has_many :users, through: :visits
has_many :visits
validates :name, uniqueness: true, presence: true
validates :address, presence: true
validates :image_url, presence: true
validates :price, presence: true
validates :city, presence: true
def self.query_by_city(city)
where(city: city)
end
def self.query_by_price(max_price)
where(price: (0)..max_price.to_i)
end
def self.get_data(city)
doc = Nokogiri::HTML(open("https://www.hotels.com/search.do?q-destination=#{city}"))
doc.css(".hotel-wrap").first(15).each do |hotel|
hotel_name = hotel.css(".p-name").css("a").text.strip
img_url = hotel.css(".u-photo").first.values.last.split(/'/)[1] rescue img_url ="https://via.placeholder.com/250x140"
hotel_price = hotel.css(".price").css("ins").text.gsub(/\D/, '')
if hotel_price.empty?
hotel_price = hotel.css(".price").text.gsub(/\D/, '')
end
hotel_address = hotel.css(".contact").text
Hotel.create(name: hotel_name, image_url: img_url, price: hotel_price, address: hotel_address, city: city)
end
end
def self.get_data2(city)
uri = URI('https://api.proxycrawl.com')
uri.query = URI.encode_www_form({
token: 'ySdaNYV4217OA4IhAPXhVQ',
user_agent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/11.1.1 Safari/605.1.15',
url: "https://www.hotels.com/search.do?q-destination=#{city}
"})
res = Net::HTTP.get_response(uri)
doc = Nokogiri::HTML(res.body)
body = doc.css("body")
body.css(".main-inner").css(".hotel-wrap").first(15).each do |hotel|
hotel_name = hotel.css(".p-name").css("a").text.strip
img_url = hotel.css(".u-photo").first.values.last.split(/'/)[1] rescue img_url ="https://via.placeholder.com/250x140"
hotel_price = hotel.css(".price").css("ins").text.gsub(/\D/, '')
#convert RUB to USD
if hotel_price.empty?
if hotel.css(".price").text.match?(/RUB/)
hotel_price = (hotel.css(".price").text.gsub(/\D/, '').to_f * (0.015)).to_s
else
hotel_price = hotel.css(".price").text.gsub(/\D/, '')
end
end
hotel_address = hotel.css(".contact").text
Hotel.create(name: hotel_name, image_url: img_url, price: hotel_price, address: hotel_address, city: city)
end
end
end
| true |
4e0ed001e2f5453af330049ef422d2eb5cab39a0 | Ruby | thnukid/facebook_data_analyzer | /classes/analyzeables/analyzeable.rb | UTF-8 | 2,178 | 3.015625 | 3 | [] | no_license | class Analyzeable
def self.parse
raise "needs to be implemented by concrete class"
end
GROUP_BY = [].freeze
COUNT_BY = [].freeze
def initialize(threads_supported: nil, processes_supported: nil, parallel: false)
# Grouped by is weird and needs a hash for each GROUP_BY, hash for each unique group, and hash for attributes
@grouped_by = Hash.new do |by_group, key|
by_group[key] = Hash.new do |group_name, attribute|
group_name[attribute] = Hash.new(nil)
end
end
@counted_by = Hash.new { |hash, key| hash[key] = Hash.new(0) }
# Thread/Process limit for Parallel processing
@threads_supported = parallel && !threads_supported ? 10 : threads_supported || 0
@processes_supported = parallel && !processes_supported ? 5 : processes_supported || 0
end
def analyze
raise "needs to be implemented by concrete class"
end
def export(package:)
raise "needs to be implemented by concrete class"
end
private
def group(analyzeable:, aggregate_hash: @grouped_by)
self.class::GROUP_BY.each do |attribute|
grouping_method = "group_by_#{attribute}".to_sym
if analyzeable.respond_to?(grouping_method)
grouped_analyzeable = analyzeable.send(grouping_method)
grouped_analyzeable.each do |group, group_attributes|
group_attributes.each do |group_attribute_key, group_attribute_value|
current_grouping = aggregate_hash[attribute][group][group_attribute_key]
if current_grouping.nil?
aggregate_hash[attribute][group][group_attribute_key] = group_attribute_value
else
aggregate_hash[attribute][group][group_attribute_key] += group_attribute_value
end
end
end
end
end
end
def count(analyzeable:, aggregate_hash: @counted_by)
self.class::COUNT_BY.each do |attribute|
counting_method = "count_by_#{attribute}".to_sym
if analyzeable.respond_to?(counting_method)
countables = analyzeable.send(counting_method)
countables.each do |countable|
aggregate_hash[attribute][countable] += 1
end
end
end
end
end | true |
65d5d0c9420ccd177e599e2c61ce6ad9d0276dff | Ruby | Mizar999/Game-of-Life---Gosu | /test/test_rect.rb | UTF-8 | 1,709 | 3.046875 | 3 | [] | no_license | file = "../lib/rect.rb"
begin
require_relative file
rescue NotMethodError
require file
end
require "test/unit"
class TestRect < Test::Unit::TestCase
def setup
@rect = Rect.new
end
def test_initialize
assert_not_nil(@rect)
end
def test_width_and_height
assert_width_and_height(0, 0)
set_width_and_height(20, 30)
assert_width_and_height(20, 30)
end
def test_rect_coordinates
assert_coordinates(0, 0)
set_coordinates(150, 75)
assert_coordinates(150, 75)
end
def test_rect_color
assert_equal(0xff000000, @rect.color)
@rect.color = 0xff00ff00
assert_equal(0xff00ff00, @rect.color)
end
def test_rect_z_order
assert_equal(0, @rect.z_order)
@rect.z_order = 2
assert_equal(2, @rect.z_order)
end
def test_constructor_parameters
@rect = Rect.new(:x => 20, :y => 45, :width => 60, :height => 36, :color => 0xff00ffff, :z_order => 1)
assert_coordinates(20, 45)
assert_width_and_height(60, 36)
assert_equal(0xff00ffff, @rect.color)
assert_equal(1, @rect.z_order)
end
def test_top_left_bottom_right
set_coordinates(30, 45)
set_width_and_height(20, 15)
assert_equal(45, @rect.top)
assert_equal(30, @rect.left)
assert_equal(60, @rect.bottom)
assert_equal(50, @rect.right)
end
private
def set_width_and_height(width, height)
@rect.width = width
@rect.height = height
end
def set_coordinates(x, y)
@rect.x = x
@rect.y = y
end
def assert_width_and_height(width, height)
assert_equal(width, @rect.width)
assert_equal(height, @rect.height)
end
def assert_coordinates(x, y)
assert_equal(x, @rect.x)
assert_equal(y, @rect.y)
end
end
| true |
794d9dc9d4b9b1ab756ec1199ec2fac8f0fd8d64 | Ruby | cyberarm/battleship | /lib/ship.rb | UTF-8 | 2,426 | 2.9375 | 3 | [] | no_license | module Battleship
class Ship
include CyberarmEngine::Common
attr_accessor :angle, :position, :grid_position
def initialize(options = {})
puts self.class
@options = options
@angle = options[:angle]
@angle ||= 0
@position = options[:position]
@position ||= CyberarmEngine::Vector.new
@color = options[:color]
@color ||= Gosu::Color::GREEN
@scale = 1.0
@grid_position = nil
end
def width
image.width * @scale
end
def height
image.height * @scale
end
def draw_in_grid(grid)
return unless @grid_position
@position.x = grid.x + ((@grid_position.x + 1) * grid.cell_size)
@position.y = grid.y + ((@grid_position.y + 1) * grid.cell_size)
case @angle
when 90
@position.x += grid.cell_size
draw_without_rotation_midpoint_offset(grid)
when 270
@position.y += image.width * @scale
draw_without_rotation_midpoint_offset(grid)
else
draw_detached(grid.cell_size)
end
end
def draw_without_rotation_midpoint_offset(grid)
Gosu.rotate(@angle, @position.x, @position.y) do
@scale = grid.cell_size / 16.0
image.draw(@position.x, @position.y, 2, @scale, @scale, @color)
end
end
def draw_detached(cell_size)
Gosu.rotate(@angle, @position.x + image.width / 2 * @scale, @position.y + image.height / 2 * @scale) do
@scale = cell_size / 16.0
image.draw(@position.x, @position.y, 2, @scale, @scale, @color)
end
end
end
class AircraftCarrier < Ship
def length
5
end
def image
get_image("#{GAME_ROOT_PATH}/assets/sprites/aircraft_carrier.png", retro: true)
end
end
class BattleShip < Ship
def length
4
end
def image
get_image("#{GAME_ROOT_PATH}/assets/sprites/battleship.png", retro: true)
end
end
class Cruiser < Ship
def length
3
end
def image
get_image("#{GAME_ROOT_PATH}/assets/sprites/cruiser.png", retro: true)
end
end
class Submarine < Ship
def length
3
end
def image
get_image("#{GAME_ROOT_PATH}/assets/sprites/submarine.png", retro: true)
end
end
class PatrolBoat < Ship
def length
2
end
def image
get_image("#{GAME_ROOT_PATH}/assets/sprites/patrol_boat.png", retro: true)
end
end
end
| true |
bcb399cc497c9d4b14b65143c8f511ce01ce9732 | Ruby | cowalla/GoalsApp | /app/models/user.rb | UTF-8 | 813 | 2.515625 | 3 | [] | no_license | class User < ActiveRecord::Base
attr_accessible :username, :password
before_validation :reset_session_token
validates :username, :password_digest, :session_token, :presence => true
has_many :goals
has_many :cheers
def self.find_by_credentials(username, password)
user = User.find_by_username(username)
return user if user && user.is_password?(password)
nil
end
def generate_session_token
SecureRandom::urlsafe_base64(16)
end
def is_password?(pass)
BCrypt::Password.new(self.password_digest).is_password?(pass)
end
def password=(pass)
self.password_digest = BCrypt::Password.create(pass)
end
def reset_session_token
self.session_token = generate_session_token
end
def reset_session_token!
reset_session_token
self.save!
end
end
| true |
97196b96f207304056814ec0face2c8a315c7e82 | Ruby | kevincai79/phase-0-tracks | /ruby/shout.rb | UTF-8 | 915 | 4.125 | 4 | [] | no_license | =begin
module Shout
def self.yell_angrily(words)
words + "!!!" + " :("
end
def self.yelling_happily(words)
words + "! " + words + "! " + words + "!"
end
end
puts Shout.yell_angrily('No')
puts Shout.yelling_happily('Hurray')
=end
module Shout
def yell_angrily(words)
words + "!!!" + " :("
end
def yelling_happily(words)
words + "! " + words + "! " + words + "!"
end
end
class Student
include Shout
def study
"Studys hard at the libriary."
end
end
class Actor
include Shout
def act(character)
"Playing #{character} role."
end
end
student = Student.new
puts "Student class mixin:"
puts student.yell_angrily("NO")
puts student.yelling_happily("Yay")
puts student.study
puts "--------------------------------------"
puts "Actor class mixin:"
actor = Actor.new
puts actor.yell_angrily("Damn")
puts actor.yelling_happily("Hurray")
puts actor.act("doctor")
| true |
2fff963881cca1947f6e4500b8e7a2360061e375 | Ruby | elizabethcsw/oystercard_challenge | /spec/journeylog_spec.rb | UTF-8 | 2,174 | 2.703125 | 3 | [] | no_license | require 'journeylog'
# require 'journey'
describe JourneyLog do
let(:station1) { double :station1 }
let(:station2) { double :station2 }
let(:journey) { double :journey }
let(:journey_c) { double :journey_c }
subject { described_class.new(journey_c) }
before do
allow(journey).to receive(:in).and_return(station1)
allow(journey_c).to receive(:new).and_return(journey)
end
context '#start' do
it 'starts a journey' do
subject.start(station1)
expect(subject.journeys.last.in).to eq station1
end
end
context '#current_journey' do
before do
subject.start(station1)
end
it 'knows my current incomplete journey' do
allow(journey).to receive(:complete?).and_return(false)
expect(subject.current_journey).to eq journey
end
end
context '#finish' do
before do
allow(journey).to receive(:out=).with(station2).and_return(station2)
allow(journey).to receive(:out).and_return(station2)
end
it 'applies an exit station to the most recent journey' do
allow(journey).to receive(:complete?).and_return(false)
subject.start(station1)
subject.finish(station2)
expect(subject.journeys.last.out).to eq station2
end
end
context '#journeys' do
it 'is empty when initialized' do
expect(subject.journeys).to be_empty
end
it 'shows a logged journey' do
allow(journey).to receive(:out=).and_return(station2)
allow(journey).to receive(:out).and_return(station2)
allow(journey).to receive(:complete?).and_return(false)
subject.start(station1)
subject.finish(station2)
expect(subject.journeys).to include(journey)
end
end
context '#latest_journey' do
it 'shows nothing by default' do
expect(subject.latest_journey).to be_nil
end
it 'shows the latest journey' do
allow(journey).to receive(:complete?).and_return(true)
allow(journey).to receive(:out).and_return(station2)
allow(journey).to receive(:out=).and_return(station2)
subject.start(station1)
subject.finish(station2)
expect(subject.latest_journey).to eq(journey)
end
end
end
| true |
80e449664c642821b0e092875c3041a63ba01c5e | Ruby | alishersadikov/jungle-beat | /lib/linked_list.rb | UTF-8 | 2,970 | 3.546875 | 4 | [] | no_license | class LinkedList
attr_reader :head, :valid, :valid_beats
def initialize
@head = nil
@valid_beats = %w| blop boop bop dah dee deep ding ditt doo doom doop dop hoo la na oom plop shi shu suu tee woo |
@valid = false
end
def valid?(sound)
if @valid_beats.include?(sound)
@valid = true
else
@valid = false
end
end
def append(sound)
if valid?(sound)
if @head == nil
@head = Node.new(sound)
@head.data
else
current_node = @head
while current_node.next_node != nil
current_node = current_node.next_node
end
current_node.next_node = Node.new(sound)
current_node.next_node.data
end
else
"Beat not valid!"
end
end
def prepend(sound)
if valid?(sound)
if @head == nil
@head = Node.new(sound)
@head.data
else
current_node = Node.new(sound)
current_node.next_node = @head
@head = current_node
end
current_node.data
else
"Beat not valid!"
end
end
def insert(index, sound)
if valid?(sound)
node_counter = 0
current_node = @head
while node_counter != index - 1
current_node = current_node.next_node
node_counter += 1
end
new_node = Node.new(sound)
previous_node = current_node
current_node = current_node.next_node
new_node.next_node = current_node
previous_node.next_node = new_node
new_node.data
else
"Beat not valid!"
end
end
def find(index, quantity)
current_node = @head
output = ""
index.times do
current_node = current_node.next_node
end
quantity.times do
output << current_node.data + " "
current_node = current_node.next_node
end
output.chop
end
def includes?(sound)
current_node = @head
is_it_here = false
until current_node.next_node == nil
if current_node.data == sound
is_it_here = true
end
current_node = current_node.next_node
end
is_it_here
end
def pop(quantity = 1)
removed = ""
quantity.times do
current_node = @head
while current_node.next_node.next_node != nil
current_node = current_node.next_node
end
removed << current_node.next_node.data + " "
current_node.next_node = nil
end
removed.split.reverse.join(" ")
end
def count
if @head == nil
"No data!"
else
node_counter = 1
current_node = @head
while current_node.next_node != nil
node_counter += 1
current_node = current_node.next_node
end
node_counter
end
end
def to_string
current_node = @head
all_sounds = ""
while current_node.next_node != nil
all_sounds << current_node.data + " "
current_node = current_node.next_node
end
all_sounds << current_node.data
all_sounds
end
end
| true |
38b79c73b9d033b6595c07201e811f12bf8d8464 | Ruby | theyworkforyou/shineyoureye-sinatra | /lib/factory/person.rb | UTF-8 | 847 | 2.53125 | 3 | [] | no_license | # frozen_string_literal: true
require_relative '../ep/person'
require_relative '../membership_csv/person'
module Factory
class Person
def initialize(mapit:, baseurl:, identifier_scheme:)
@mapit = mapit
@baseurl = baseurl
@identifier_scheme = identifier_scheme
end
def build_ep_person(person, term)
EP::Person.new(
person: person,
term: term,
mapit: mapit,
baseurl: baseurl,
identifier_scheme: identifier_scheme
)
end
def build_csv_person(person, legislature_slug)
MembershipCSV::Person.new(
person: person,
legislature_slug: legislature_slug,
mapit: mapit,
baseurl: baseurl,
identifier_scheme: identifier_scheme
)
end
private
attr_reader :mapit, :baseurl, :identifier_scheme
end
end
| true |
9e8a5a49bf92253ff5b0c97b03bef69ba51b3446 | Ruby | chef/mixlib-versioning | /spec/support/shared_examples/behaviors/sortable.rb | UTF-8 | 1,292 | 2.53125 | 3 | [
"Apache-2.0"
] | permissive | #
# Author:: Seth Chisamore (<schisamo@chef.io>)
# Copyright:: Copyright (c) 2013-2018 Chef Software, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
shared_examples "sortable" do
let(:unsorted_versions) do
unsorted_version_strings.map { |v| described_class.new(v) }
end
let(:sorted_versions) do
sorted_version_strings.map { |v| described_class.new(v) }
end
it "responds to <=>" do
expect(described_class).to respond_to(:<=>)
end
it "sorts all properly" do
expect(unsorted_versions.sort).to eq sorted_versions
end
it "finds the min" do
expect(unsorted_versions.min).to eq described_class.new(min)
end
it "finds the max" do
expect(unsorted_versions.max).to eq described_class.new(max)
end
end # shared_examples
| true |
eff6ded72ec990688690b3664fa2b41ed6c791c9 | Ruby | shoma07/sqlite3_extend_function | /lib/sqlite3_extend_function/functions/mod.rb | UTF-8 | 586 | 2.6875 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
module SQLite3ExtendFunction
module Functions
# SQLite3ExtendFunction::Functions::Mod
module Mod
class << self
# @param [Integer, Float] y
# @param [Integer, Float] x
# @return [Integer]
# @raise [SQLite3::SQLException]
def call(y, x = nil)
Integer(Float(y).modulo(Float(x)))
rescue ArgumentError
raise SQLite3::SQLException,
'Could not choose a best candidate function. You might need to add explicit type casts.'
end
end
end
end
end
| true |
4d24806d712c2ae0ad2b8f0aaaafacf7cb184ecd | Ruby | aastronautss/full-stack-preparatory-notes-and-exercises | /100/1_introduction_to_programming/1_the_basics/1.rb | UTF-8 | 52 | 2.828125 | 3 | [] | no_license | first = "Tyler "
last = "Guillen"
puts first + last
| true |
e59d48756087c83b4f705dbd749eef9f56a68ce5 | Ruby | mrfinch/rb_server_client | /processes/server.rb | UTF-8 | 1,885 | 3.15625 | 3 | [] | no_license | # TODO: on close of connection send user disconnected
require 'socket'
require 'pry'
@clients = []
server = TCPServer.new('localhost', 2000)
def listen server
loop {
client = server.accept
puts "Client accepted at #{Time.now}"
thr = Thread.new(client) do
username = nil
client.puts 'Enter yr username:'
puts @clients
while true
username = client.gets.chomp
puts "#{username} trying to connect"
@clients.each do |clnt|
if clnt[:nickname] == username
client.puts "Choose another nickname"
username = nil
break
end
end
break if username
end
puts "#{username} connected to chat"
client.puts "You are connected. Happy Chatting"
client_info = { client: client, nickname: username }
send_notification_to_rest_clients("#{username} connected to chat window.", client_info)
send_list_of_users_available_to_chat_to_client(client)
@clients << client_info
listen_to_messages_from_client(client_info)
end
}
end
def listen_to_messages_from_client client_info
loop {
msg = client_info[:client].gets.chomp
if msg
send_message_to_rest_clients(msg, client_info)
end
}
end
def send_message_to_rest_clients msg, client_info
@clients.each do |clnt|
next if clnt[:nickname] == client_info[:nickname]
clnt[:client].puts "From #{client_info[:nickname]}: #{msg}"
end
end
def send_notification_to_rest_clients msg, client_info
@clients.each do |clnt|
next if clnt[:nickname] == client_info[:nickname]
clnt[:client].puts "#{msg}"
end
end
def send_list_of_users_available_to_chat_to_client client
client.puts "List of people available for chat:"
@clients.each.with_index do |clnt, index|
client.puts "#{index + 1}. #{clnt[:nickname]}"
end
end
listen(server)
| true |
7a8c5b02b3c45a536419b64b27679a2194e9fa38 | Ruby | choroba/perlweeklychallenge-club | /challenge-213/roger-bell-west/ruby/ch-1.rb | UTF-8 | 467 | 3.34375 | 3 | [] | no_license | #! /usr/bin/ruby
require 'test/unit'
def funsort(l0)
l = l0.sort
a = []
b = []
l.each do |k|
if k % 2 == 0 then
a.push(k)
else
b.push(k)
end
end
a.concat(b)
return a
end
class TestFunsort < Test::Unit::TestCase
def test_ex1
assert_equal([2, 4, 6, 1, 3, 5], funsort([1, 2, 3, 4, 5, 6]))
end
def test_ex2
assert_equal([2, 1], funsort([1, 2]))
end
def test_ex3
assert_equal([1], funsort([1]))
end
end
| true |
6262bee4f11f81481c2a0111d3ea20162ec6bca2 | Ruby | coolbuc123/inHome | /kbutils/crawling/infomax.rb | UTF-8 | 2,653 | 2.578125 | 3 | [] | no_license | =begin
a = [1, 3, 5]
File.open('www', 'w'){ |f1|
f1.puts 'asdasd'
f1.puts '1111111111'
f1.puts a
}
=end
require 'watir'
#add1 = 'https://news.einfomax.co.kr/news/articleView.html?idxno=4073883'
browser1 = Watir::Browser.new :firefox
#browser1.goto add1
#next_page1 = browser1.div(id: 'article-view-content-div').text
#browser1.driver.manage.timeouts.implicit_wait = 3
#p next_page1
#exit
#browser1 = Selenium::WebDriver::Firefox::Profile.new
add1 = 'https://news.einfomax.co.kr/news/articleList.html?sc_area=A&view_type=sm&sc_word=%EC%84%9C%ED%99%98-%EB%A7%88%EA%B0%90'
browser1.goto add1
browser1.driver.manage.timeouts.implicit_wait = 10
#d = browser1.div(class: 'clearfix')
#bb = browser1.element(:xpath => "//a[@class='line-height-3-2x']")
#browser1.elements(:xpath => "//p[@class='list-summary']").each{ |x|
# p x.a.attribute_value('href')
#p x.div.text
#}
def get_pages(browser1)
adds, dates = [], []
browser1.elements(:xpath => "//p[@class='list-summary']").each{ |x|
adds << x.a.attribute_value('href')
}
browser1.elements(:xpath => "//div[@class='list-dated']").each{ |x|
dates << x.text[-16..-7]
}
return adds, dates
end
#pages = []
#browser1.elements(:xpath => "//a[@class='line-height-3-2x']").each{ |x|
# pages << x.attribute_value('href')
#}
#p bb.htmls
#p bb[:href]
#p browser1.links.map(&:href)
#pages = '123456789'.split('')
#pages << "10"
#pages.each{ |x|
# browser1.link(text: x).click
#}
#(2..3).each{ |x|
#browser1.i(class: 'fa fa-angle-right fa-fw').click
#browser1.element(:xpath => "//i[@class='fa fa-angle-right fa-fw']").click
#page1 = next_page1.attribute_value('href')
#p page1
#browser1.goto page1
t_adds, t_dates = [], []
(1..68).each{ |x|
if x % 10 != 1
browser1.link(text: x.to_s).click
browser1.driver.manage.timeouts.implicit_wait = 10
end
p x
adds, dates = get_pages(browser1)
t_adds += adds
t_dates += dates
File.open('address.txt', 'a'){ |f1|
f1.puts adds
}
File.open('dates.txt', 'a'){ |f1|
f1.puts dates
}
if x % 10 == 0
next_page1 = browser1.element(:xpath => "//li[@class='pagination-next']").a
add3 = next_page1.attribute_value('href')
browser1.goto add3
browser1.driver.manage.timeouts.implicit_wait = 10
p [' next', x]
end
}
browser1.close
#element(:xpath => "//a[@href='line-height-3-2x']").each{ |x|
# pages << x.attribute_value('href')
#}
#browser1.link(text: '2').click
#p d.text
#p d
#p d.text_field
#p d.html
#p d.htmls
#p '-----------'
#p d.link
#p d.links
#p d.innertext
#Watir::Browser.new :phantomjs
#class 'list-titles'
# division class 'clearfix'
# page
# li
| true |
b15a7972182ed978b8884d4f439e1af2c8d9d9d5 | Ruby | pawelduda/codeeval-ruby-solutions | /moderate/76.rb | UTF-8 | 679 | 3.703125 | 4 | [] | no_license | # https://www.codeeval.com/browse/76/
def parse_input(input)
input = input.split(',')
{
original: input[0],
rotated: input[1]
}
end
class String
def is_rotation_of?(another_string)
original_length = self.length - 1
doubled_self = self * 2
(0..original_length).each do |rotation|
return 'True' if doubled_self[rotation..(rotation + original_length)] == another_string
end
'False'
end
end
File.open(ARGV[0]).each_line do |line|
input = parse_input(line.strip)
puts input[:original].is_rotation_of?(input[:rotated])
end
# tests
# p 'Hello'.is_rotation_of?('lloHe') == 'True'
# p 'Basefont'.is_rotation_of?('tBasefon') == 'True'
| true |
911d23645638f7f99e8433355468455554ea5011 | Ruby | MasonHolland/module_3_test | /spec/requests/api/v1/item_records_spec.rb | UTF-8 | 3,593 | 2.71875 | 3 | [] | no_license | require 'rails_helper'
# When I send a GET request to `/api/v1/items`
# I receive a 200 JSON response containing all items
# And each item has an id, name, description, and image_url but not the created_at or updated_at
RSpec.describe "items requests" do
it "index returns all items" do
item_1 = Item.create(name: "Green Pan", description: "A non stick great pan", image_url: "google.com")
item_2 = Item.create(name: "Brown Pan", description: "A non stick great pan", image_url: "google.com")
item_3 = Item.create(name: "Red Pan", description: "A non stick great pan", image_url: "google.com")
get "/api/v1/items"
expect(response.status).to eq(200)
items = JSON.parse(response.body)
expect(items.count).to eq(3)
expect(items.first).to have_key("id")
expect(items.first["id"]).to eq(item_1.id)
expect(items.first).to have_key("name")
expect(items.first["name"]).to eq(item_1.name)
expect(items.first).to have_key("description")
expect(items.first["description"]).to eq(item_1.description)
expect(items.first).to have_key("image_url")
expect(items.first["image_url"]).to eq(item_1.image_url)
expect(items.first).to_not have_key("created_at")
expect(items.first).to_not have_key("updated_at")
end
# When I send a GET request to `/api/v1/items/1`
# I receive a 200 JSON response containing the id, name, description, and image_url but not the created_at or updated_at
it "show returns a single item" do
item_1 = Item.create(name: "Green Pan", description: "A non stick great pan", image_url: "google.com")
get "/api/v1/items/1"
expect(response.status).to eq(200)
item = JSON.parse(response.body)
expect(item).to have_key("id")
expect(item["id"]).to eq(item_1.id)
expect(item).to have_key("name")
expect(item["name"]).to eq(item_1.name)
expect(item).to have_key("description")
expect(item["description"]).to eq(item_1.description)
expect(item).to have_key("image_url")
expect(item["image_url"]).to eq(item_1.image_url)
expect(item).to_not have_key("created_at")
expect(item).to_not have_key("updated_at")
end
# When I send a DELETE request to `/api/v1/items/1`
# I receive a 204 JSON response if the record is successfully deleted
it "delete is success" do
item = Item.create(name: "Green Pan", description: "A non stick great pan", image_url: "google.com")
delete "/api/v1/items/1"
expect(response.status).to eq(204)
expect(Item.count).to eq(0)
end
# When I send a POST request to `/api/v1/items` with a name, description, and image_url
# I receive a 201 JSON response if the record is successfully created
# And I receive a JSON response containing the id, name, description, and image_url but not the created_at or updated_at
it "post creates a new item" do
item_1 = {name: "Green Pan", description: "A non stick great pan", image_url: "google.com"}
post "/api/v1/items?name=#{item_1[:name]}&description=#{item_1[:description]}&image_url=#{item_1[:image_url]}"
expect(response.status).to eq(201)
new_item = JSON.parse(response.body)
expect(new_item).to have_key("id")
expect(new_item).to have_key("name")
expect(new_item["name"]).to eq(item_1[:name])
expect(new_item).to have_key("description")
expect(new_item["description"]).to eq(item_1[:description])
expect(new_item).to have_key("image_url")
expect(new_item["image_url"]).to eq(item_1[:image_url])
expect(new_item).to_not have_key("created_at")
expect(new_item).to_not have_key("updated_at")
end
end
| true |
7f6036454c90a492eaa9c0f00c7eb60674f93374 | Ruby | NorCalDavid/AppleIIeTeam_SudokuChallenge | /sudoku_solver_pseudocode.rb | UTF-8 | 840 | 3.328125 | 3 | [
"MIT"
] | permissive | # Input: String of numbers and underscores representing sudoku board.n (incomplete board)
# Output: String of numbers complete with no underscores. (filled board)
# RCG - Row, Column, Grid
# Steps:
# Initial Pass
# P-Code:
# 0. Create Classes: Cell, (Board, Row, Column, Grid)
# 1. Populate 3D array with the input String
# 2. Have each cell check its RCG in order
# 3. Have cell eliminate any numbers in its RCG
# 4. The remaining numbers are the cells list of possible values
# 5. If there is only one possible value, record the value.
# 6. Move on to the next cell.
# User Stories:
# 1. Cell check row for all values in row
# 2. Cell check column for all values in column
# 3. Cell check grid for all values in grid
# 4. Cell collect its possible remaining values (eliminate any values checked from US 1-3)
| true |
29b23dc66c35723f5c3f776e438bc4d859732647 | Ruby | di-stars/suseviclient | /vnc.rb | UTF-8 | 1,240 | 2.578125 | 3 | [] | no_license | #!/usr/bin/env ruby
#This is optional addon to suseviclient.sh.
#It enables us to pass keystrokes to VM and automate custom scenarios
#To use it you have to install ruby-vnc:
#gem install ruby-vnc
require 'rubygems'
require 'net/vnc'
if ARGV[0] == nil or ARGV[0] == '--help'
puts "Usage:
./vnc.rb <server> <port> <password> <string_to_pass_to_server>"
exit
end
server, port, password, string = ARGV
port=port[2,3]
#keystrokes = "netsetup=dhcp autoyast=http://users.suse.cz/~ytsarev/tiny.xml".chars.to_a
keystrokes = string.chars.to_a
vnccode = "vnc.type '"
counter = 0
for character in keystrokes
if "#{character}" == ":"
vnccode += "'
vnc.key_down :shift
vnc.key_down ':'
vnc.key_up :shift
sleep 1
vnc.type '"
elsif character == "~"
vnccode += "'
vnc.key_down :shift
vnc.key_down '`'
vnc.key_up :shift
sleep 1
vnc.type '"
else
vnccode += "#{character}"
end
counter+=1
if (counter % 13) == 0
vnccode += "'
sleep 1
vnc.type '"
end
if counter == keystrokes.length
vnccode += "'"
end
end
#puts vnccode
Net::VNC.open "#{server}:#{port}", :shared => false, :password => password do |vnc|
vnc.key_press :down
eval(vnccode)
vnc.key_press :return
end
| true |
6ea4e296a36249f2f4e481e7b15c494711e0eb0a | Ruby | kawakami-o3/PLC | /scm2asm/tests-1.9.2.rb | UTF-8 | 3,013 | 3.046875 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env ruby
require "./bootstrap"
run_all "vectors", {
'(vector? (make-vector 0))' => "#t",
'(vector-length (make-vector 12))' => "12\n",
'(vector? (cons 1 2))' => "#f\n",
'(vector? 1287)' => "#f\n",
'(vector? ())' => "#f\n",
'(vector? #t)' => "#f\n",
'(vector? #f)' => "#f\n",
'(pair? (make-vector 12))' => "#f\n",
'(null? (make-vector 12))' => "#f\n",
'(boolean? (make-vector 12))' => "#f\n",
'(make-vector 0)' => "#()\n",
'(let ([v (make-vector 2)])
(vector-set! v 0 #t)
(vector-set! v 1 #f)
v)' => "#(#t #f)\n",
'(let ([v (make-vector 2)])
(vector-set! v 0 v)
(vector-set! v 1 v)
(eq? (vector-ref v 0) (vector-ref v 1)))' => "#t\n",
'(let ([v (make-vector 1)] [y (cons 1 2)])
(vector-set! v 0 y)
(cons y (eq? y (vector-ref v 0))))' => "((1 . 2) . #t)\n",
'(let ([v0 (make-vector 2)])
(let ([v1 (make-vector 2)])
(vector-set! v0 0 100)
(vector-set! v0 1 200)
(vector-set! v1 0 300)
(vector-set! v1 1 400)
(cons v0 v1)))' => "(#(100 200) . #(300 400))\n",
'(let ([v0 (make-vector 3)])
(let ([v1 (make-vector 3)])
(vector-set! v0 0 100)
(vector-set! v0 1 200)
(vector-set! v0 2 150)
(vector-set! v1 0 300)
(vector-set! v1 1 400)
(vector-set! v1 2 350)
(cons v0 v1)))' => "(#(100 200 150) . #(300 400 350))\n",
'(let ([n 2])
(let ([v0 (make-vector n)])
(let ([v1 (make-vector n)])
(vector-set! v0 0 100)
(vector-set! v0 1 200)
(vector-set! v1 0 300)
(vector-set! v1 1 400)
(cons v0 v1))))' => "(#(100 200) . #(300 400))\n",
'(let ([n 3])
(let ([v0 (make-vector n)])
(let ([v1 (make-vector (vector-length v0))])
(vector-set! v0 (- (vector-length v0) 3) 100)
(vector-set! v0 (- (vector-length v1) 2) 200)
(vector-set! v0 (- (vector-length v0) 1) 150)
(vector-set! v1 (- (vector-length v1) 3) 300)
(vector-set! v1 (- (vector-length v0) 2) 400)
(vector-set! v1 (- (vector-length v1) 1) 350)
(cons v0 v1))))' => "(#(100 200 150) . #(300 400 350))\n",
'(let ([n 1])
(vector-set! (make-vector n) (sub1 n) (* n n))
n)' => "1\n",
'(let ([n 1])
(let ([v (make-vector 1)])
(vector-set! v (sub1 n) n)
(vector-ref v (sub1 n))))' => "1\n",
'(let ([v0 (make-vector 1)])
(vector-set! v0 0 1)
(let ([v1 (make-vector 1)])
(vector-set! v1 0 13)
(vector-set! (if (vector? v0) v0 v1)
(sub1 (vector-length (if (vector? v0) v0 v1)))
(add1 (vector-ref
(if (vector? v0) v0 v1)
(sub1 (vector-length (if (vector? v0) v0 v1))))))
(cons v0 v1)))' => "(#(2) . #(13))\n",
}
run_all "more vectors", {
'(letrec ([f (lambda (v i)
(if (>= i 0)
(begin (vector-set! v i i) (f v (sub1 i)))
v))])
(let ((v (make-vector 100)))
(vector-length (f v 100))))' => "100\n"
}
| true |
807e90c295082d6eb8a318ff9436a73c8a5e3ab6 | Ruby | theand/our-boxen | /.bundle/ruby/2.0.0/gems/puppet-lint-0.3.2/lib/puppet-lint/plugins/check_strings.rb | UTF-8 | 3,035 | 2.65625 | 3 | [
"MIT"
] | permissive | class PuppetLint::Plugins::CheckStrings < PuppetLint::CheckPlugin
# Public: Check the manifest tokens for any double quoted strings that don't
# contain any variables or common escape characters and record a warning for
# each instance found.
#
# Returns nothing.
check 'double_quoted_strings' do
tokens.select { |r|
r.type == :STRING
}.each { |r|
r.value.gsub!(' '*r.column, "\n")
}.select { |r|
r.value[/(\t|\\t|\n|\\n)/].nil?
}.each do |token|
notify :warning, {
:message => 'double quoted string containing no variables',
:linenumber => token.line,
:column => token.column,
}
end
end
# Public: Check the manifest tokens for double quoted strings that contain
# a single variable only and record a warning for each instance found.
#
# Returns nothing.
check 'only_variable_string' do
tokens.each_index do |token_idx|
token = tokens[token_idx]
if token.type == :DQPRE and token.value == ''
if {:VARIABLE => true, :UNENC_VARIABLE => true}.include? tokens[token_idx + 1].type
if tokens[token_idx + 2].type == :DQPOST
if tokens[token_idx + 2].value == ''
notify :warning, {
:message => 'string containing only a variable',
:linenumber => tokens[token_idx + 1].line,
:column => tokens[token_idx + 1].column,
}
end
end
end
end
end
end
# Public: Check the manifest tokens for any variables in a string that have
# not been enclosed by braces ({}) and record a warning for each instance
# found.
#
# Returns nothing.
check 'variables_not_enclosed' do
tokens.select { |r|
r.type == :UNENC_VARIABLE
}.each do |token|
notify :warning, {
:message => 'variable not enclosed in {}',
:linenumber => token.line,
:column => token.column,
}
end
end
# Public: Check the manifest tokens for any single quoted strings containing
# a enclosed variable and record an error for each instance found.
#
# Returns nothing.
check 'single_quote_string_with_variables' do
tokens.select { |r|
r.type == :SSTRING && r.value.include?('${')
}.each do |token|
notify :error, {
:message => 'single quoted string containing a variable found',
:linenumber => token.line,
:column => token.column,
}
end
end
# Public: Check the manifest tokens for any double or single quoted strings
# containing only a boolean value and record a warning for each instance
# found.
#
# Returns nothing.
check 'quoted_booleans' do
tokens.select { |r|
{:STRING => true, :SSTRING => true}.include?(r.type) && %w{true false}.include?(r.value)
}.each do |token|
notify :warning, {
:message => 'quoted boolean value found',
:linenumber => token.line,
:column => token.column,
}
end
end
end
| true |
15aeb7a004cb994c8151ff71006eec0d60618c80 | Ruby | The-Speck/W2D4-Big-O | /windowed_range.rb | UTF-8 | 528 | 3.484375 | 3 | [] | no_license |
def windowed_max_range(arr, window_size)
current_max = arr.first
(0...arr.length - window_size+1).each do |idx|
value = arr[idx, window_size].minmax.inject(:-).abs
current_max = (value > current_max ? value : current_max)
end
current_max
end
p windowed_max_range([1, 0, 2, 5, 4, 8], 2) #== 4 # 4, 8
p windowed_max_range([1, 0, 2, 5, 4, 8], 3) #== 5 # 0, 2, 5
p windowed_max_range([1, 0, 2, 5, 4, 8], 4) #== 6 # 2, 5, 4, 8
p windowed_max_range([1, 3, 2, 5, 4, 8], 5) #== 6 # 3, 2, 5, 4, 8
def my_queue
end
| true |
5c63fac5750286455c832bcf8a4fa6d3176637fd | Ruby | teckjon/bloccit | /app/helpers/posts_helper.rb | UTF-8 | 350 | 2.53125 | 3 | [] | no_license | module PostsHelper
def user_is_authorized_for_post?(post)
current_user && (current_user == post.user || current_user.admin?)
end
def render_censored_title(post)
output = post.title
if post.id % 5 == 0
output = "<strong>#{post.censored_title}</strong>"
end
output.html_safe
end
end
| true |
e743adfb2babddbd30b99b01e7e06627b78d5f1d | Ruby | ztbrown/photographer_scheduler | /app/models/entities/mimic.rb | UTF-8 | 311 | 2.640625 | 3 | [] | no_license | module Entities
# Include in ActiveRecord models to mimic Biz models.
module Mimic
def data
self
end
def entity?
false
end
def ==(other)
if other.respond_to?(:entity?) && other.entity?
self == other.data
else
super
end
end
end
end
| true |
a186a3f5d195302462a86c6b1485d69d06ea3f0b | Ruby | tbilous/task_JetThoughts | /lib/assignment/justifier.rb | UTF-8 | 2,166 | 3.203125 | 3 | [] | no_license | require 'ostruct'
module Assignment
module Justifier
extend self
@@KNOWN_VERSIONS_REGEX = /v[12]/
@@SPACES_REGEX = /\s+/
def justify(input_str, n, version = 'v1')
raise_if_argument_error(input_str, n, version)
version == 'v1' ? justify_v1(input_str, n) : justify_v2(input_str, n)
end
private
def justify_v1(input_str, n)
input_str.scan(/.{1,#{n}}\b|.{1,#{n}}/).each(&:strip!).join("\n")
end
def justify_v2(input_str, n)
input_words = input_str.split(@@SPACES_REGEX)
state = initial_state(input_words.shift)
res = input_words.each_with_object(state) do |current_word, state|
current_word_len = current_word.length
if current_word_len > n
chunks = current_word.chars.each_slice(n).to_a.map(&:join)
current_word = chunks.pop
state.out.push(state.buffer.join(' '))
state.out += chunks
state.buffer = [current_word]
state.current_line_len = current_word.length
else
if state.current_line_len + current_word_len + state.buffer.count <= n
state.current_line_len += current_word_len
state.buffer.push(current_word)
else
state.out.push(state.buffer.join(' '))
state.buffer = [current_word]
state.current_line_len = current_word.length
end
end
state.last_seen = current_word
end
tail = res.buffer.join(' ')
res.out.push(tail).join("\n")
end
def initial_state(first_word)
OpenStruct.new(
out: [],
current_line_len: 0,
buffer: [first_word],
last_seen: first_word
)
end
def raise_if_argument_error(input_str, n, version)
unless input_str.respond_to?(:chars)
raise ArgumentError, "input should respond to chars, got #{input_str.inspect}"
end
raise ArgumentError, "n should be an Integer, got #{n.inspect}" unless n.is_a?(Integer)
unless version.is_a?(String) && version.match(@@KNOWN_VERSIONS_REGEX)
raise ArgumentError, "version should be 'v1' or 'v2'"
end
end
end
end
| true |
468900cb9d6bad033335bca2abebc055b2a80631 | Ruby | wilsonokibe/BasicRuby | /highlight_search_result/lib/string.rb | UTF-8 | 222 | 2.875 | 3 | [] | no_license | class String
def highlight_match(search_word)
counter = 0
pattern = /(#{search_word})+/i
gsub!(pattern) do |match|
counter += 1
match = "(#{match})"
end
return counter, self
end
end
| true |
d80205138d6bfbf35a9701f2f62bc00294b07115 | Ruby | justindelatorre/rb_101 | /small_problems/easy_9/easy_9_7.rb | UTF-8 | 809 | 4.59375 | 5 | [] | no_license | =begin
Write a method that takes a first name, a space, and a last name passed as a
single String argument, and returns a string that contains the last name, a
comma, a space, and the first name.
Inputs:
- string
Outputs:
- string
Requirements:
- output string must follow format of "#{last_name}, #{first_name}"
Clarifications:
- How do we handle non-string, empty, or nil arguments?
Abstraction:
- Split argument string into a target array
- Use string interpolation and array element referencing to return a string in
the format "#{arr[1]}, #{arr[0]}"
Examples:
swap_name('Joe Roberts') == 'Roberts, Joe'
=end
def swap_name(str)
arr = str.split
"#{arr[1]}, #{arr[0]}"
end
p swap_name('Joe Roberts') == 'Roberts, Joe'
=begin
Alternate solution:
def swap_name(name)
name.split(' ').reverse.join(', ')
end
=end
| true |
c06d99a75956352c6c631fa38775e258bce14240 | Ruby | danowar2k/unicode_utils | /test/test_unicode_6_0_0.rb | UTF-8 | 1,403 | 2.640625 | 3 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | # encoding: utf-8
require "test/unit"
require "unicode_utils"
# Tests behaviour in Unicode 6.0.0 that wasn't in the previously
# supported standard. That means each one of these assertions fails
# with UnicodeUtils 1.0.0.
class TestUnicode_6_0_0 < Test::Unit::TestCase
def test_char_name
assert_equal "CYRILLIC CAPITAL LETTER PE WITH DESCENDER",
UnicodeUtils.char_name("\u{524}")
assert_equal "SAMARITAN LETTER QUF",
UnicodeUtils.char_name("\u{812}")
assert_equal "TIBETAN SUBJOINED SIGN INVERTED MCHU CAN",
UnicodeUtils.char_name("\u{F8F}")
assert_equal "CANADIAN SYLLABICS TLHWE",
UnicodeUtils.char_name("\u{18E8}")
assert_equal "EGYPTIAN HIEROGLYPH F040",
UnicodeUtils.char_name("\u{1312B}")
assert_equal "STEAMING BOWL",
UnicodeUtils.char_name("\u{1F35C}")
assert_equal "HANGUL JUNGSEONG ARAEA-A",
UnicodeUtils.char_name("\u{d7c5}")
assert_equal "CJK UNIFIED IDEOGRAPH-2A700",
UnicodeUtils.char_name("\u{2a700}")
assert_equal "CJK UNIFIED IDEOGRAPH-2B81D",
UnicodeUtils.char_name("\u{2b81d}")
end
def test_grep
assert_equal [0x1F35C], UnicodeUtils.grep(/Steaming Bowl/).map(&:ord)
end
def test_simple_upcase
assert_equal "\u{2c7e}", UnicodeUtils.simple_upcase("\u{23f}")
end
def test_simple_downcase
assert_equal "\u{23f}", UnicodeUtils.simple_downcase("\u{2c7e}")
end
end
| true |
4187aa563a4f8ea3e1da5196822afc8083c16d60 | Ruby | markthomas93/negabaro.github.io | /_posts/backend/ruby_on_rails/rails/loop/each_with_index/1.ruby | UTF-8 | 109 | 3.203125 | 3 | [
"MIT"
] | permissive | array = ["sana", "dahyun", "jihyo"]
array.each_with_index do |element, index|
p "#{index}:#{element}"
end | true |
23008288ee5c20398c070170edd570b7bff62b91 | Ruby | riderjensen/sideProjects | /Ruby/zenRuby.rb | UTF-8 | 1,083 | 4.59375 | 5 | [] | no_license | #different ways to write if statement
puts "I'm not writing code!" unless true
#different way to write if statement with an else
print true ? "true" : "false"
#shortened switch statment
puts "Hello there!"
greeting = gets.chomp
case greeting
when "English" then puts "Hello!"
when "French" then puts "Bonjour!"
when "German" then puts "Guten Tag!"
when "Finnish" then puts "Haloo!"
else puts "I don't know that language!"
end
#conditional assignment to assign a value only if the variable has not been assigned yet
favorite_book ||= "Cat's Cradle"
puts favorite_book
#implicit return: function returns the last value it calculates
def multiple_of_three(n)
n % 3 == 0 ? "True" : "False"
end
#respond_to? checks to see if you can do an operation on a thing
age = 26
age.respond_to?(:next)
caption = "A giraffe surrounded by "
caption << "weezards!"
#SAME AS
caption = "A giraffe surrounded by "
caption += "weezards!"
alphabet = ["a", "b", "c"]
alphabet << "d"
#SAME AS
alphabet = ["a", "b", "c"]
alphabet.push("d") | true |
1d7c200ee18cbb41781e4e21ff9b40c01d8873c2 | Ruby | nktaushanov/rucomasy | /spec/core/executors/runnable_spec.rb | UTF-8 | 2,337 | 2.515625 | 3 | [] | no_license | require 'fileutils'
require './core/rucomasy'
require './spec/rspec/compilation_helper'
module Rucomasy
RSpec.configure do |c|
c.include CompilationHelper
end
describe Runnable do
def random_subdir(dir = File.dirname(__FILE__))
File.join dir, random_dirname
end
before(:each) do
@first_dirname = random_subdir
@second_dirname = random_subdir
@source_folder = random_dirname
source_folder_path = File.join(@first_dirname, @source_folder)
FileUtils.mkdir_p source_folder_path
Dir.chdir(source_folder_path) { FileUtils.touch (1..3).map(&:to_s) }
end
after(:each) do
FileUtils.rm_r @first_dirname if File.exists? @first_dirname
FileUtils.rm_r @second_dirname if File.exists? @second_dirname
end
let(:first_dir_source) { File.join @first_dirname, @source_folder }
let(:second_dir_source) { File.join @second_dirname, @source_folder }
it 'moves runnable\'s directory' do
runnable = Runnable.new "", first_dir_source
runnable.fullpath.should eq first_dir_source
exists?(first_dir_source).should be true
(1..3).each do |file|
exists?(File.join first_dir_source, file.to_s).should be true
end
runnable.move_to @second_dirname
runnable.fullpath.should eq second_dir_source
exists?(first_dir_source).should be false
exists?(second_dir_source).should be true
(1..3).each do |file|
exists?(File.join first_dir_source, file.to_s).should be false
exists?(File.join second_dir_source, file.to_s).should be true
end
end
it 'copies runnable\'s directory' do
first_runnable = Runnable.new "", first_dir_source
first_runnable.fullpath.should eq first_dir_source
exists?(@first_dirname).should be true
(1..3).each do |file|
exists?(File.join first_dir_source, file.to_s).should be true
end
second_runnable = first_runnable.copy_to @second_dirname
second_runnable.fullpath.should eq second_dir_source
exists?(first_dir_source).should be true
exists?(second_dir_source).should be true
(1..3).each do |file|
exists?(File.join first_dir_source, file.to_s).should be true
exists?(File.join second_dir_source, file.to_s).should be true
end
end
end
end | true |
ea2f91ea11f5f0762ea1e78e489aad6811d44f43 | Ruby | jtahstu/iCode | /Ruby/Test/begin.rb | UTF-8 | 619 | 3.609375 | 4 | [] | no_license | #!/usr/bin/ruby
puts "This is main Ruby Program"
END {
puts "Terminating Ruby Program"
}
BEGIN {
puts "Initializing Ruby Program"
}
#指数算术
puts 2**(1/4)#1与4的商为0,然后2的0次方为1
puts 16**(1/4.0)#1与4.0的商为0.25(四分之一),然后开四次方根
#!/usr/bin/ruby -w
puts 'escape using "\\"';
puts 'That\'s right';
#您可以使用序列 #{ expr } 替换任意 Ruby 表达式的值为一个字符串。在这里,expr 可以是任意的 Ruby 表达式。
puts "Multiplication Value : #{24*60*60}";
name="Ruby"
puts name
puts "#{name+",ok"}" | true |
840414fd7041d57423153fd0fb2f6cad0c2aefb3 | Ruby | tjroeder/craft_time_2110 | /lib/person.rb | UTF-8 | 486 | 3.203125 | 3 | [] | no_license | class Person
attr_reader :name, :interests, :supplies
def initialize(info)
@name = info[:name]
@interests = info[:interests]
@supplies = {}
end
def add_supply(name, quantity)
@supplies[name] ||= 0
@supplies[name] += quantity
end
def can_build?(craft)
craft.supplies_required.each_pair do |supply, quantity|
return false unless @supplies.include?(supply.to_s)
return false if quantity > @supplies[supply.to_s]
end
true
end
end | true |
ce478e41ee18bde3702e3ba8463194bbbadb005c | Ruby | ishikota/PokerServer | /spec/poker_engine/seats_spec.rb | UTF-8 | 1,661 | 2.671875 | 3 | [] | no_license | require 'rails_helper'
RSpec.describe Seats do
let(:seats) { Seats.new }
let(:player) { double("player") }
describe "#sit_down" do
it "should set player" do
seats.sitdown(player)
expect(seats.players).to include(player)
end
end
describe "#size" do
it "should return the number of players who sit on" do
expect { seats.sitdown(player) }.to change { seats.size }.by 1
end
end
describe "count method" do
let(:player2) { double("player2") }
before {
seats.sitdown(player)
seats.sitdown(player2)
allow(player).to receive(:active?).and_return(true)
}
describe "#count_active_player" do
context "when player 2 is active" do
before { allow(player2).to receive(:active?).and_return(true) }
it { expect(seats.count_active_player).to eq 2 }
end
context "when player 2 is not active" do
before { allow(player2).to receive(:active?).and_return(false) }
it { expect(seats.count_active_player).to eq 1 }
end
end
describe "#count_ask_wait_players" do
let(:player3) { double("player3") }
def set_pay_status(target, status)
allow(target).to receive_message_chain('pay_info.status').and_return status
end
before {
seats.sitdown(player3)
set_pay_status(player , PokerPlayer::PayInfo::PAY_TILL_END)
set_pay_status(player2, PokerPlayer::PayInfo::FOLDED)
set_pay_status(player3, PokerPlayer::PayInfo::ALLIN)
}
it "should include only PAY_TILL_END player" do
expect(seats.count_ask_wait_players).to eq 1
end
end
end
end
| true |
76daad774cc99242ed628c637d7618bb6f73dce9 | Ruby | juanarbol/ruby | /vectores.rb | UTF-8 | 384 | 3.46875 | 3 | [] | no_license | puts "Digite el tamanho de los vectores"
n = gets.chomp.to_i
vector1 = []
vector2 = []
for j in(0 ...n)
puts "LLenando vector1 indice #{j}"
vector1[j] = gets.chomp.to_f
end
for j in(0 ...n)
puts "LLenando vector2 indice #{j}"
vector2[j] = gets.chomp.to_f
end
c1 = vector1.reduce(:+)
c2 = vector2.reduce(:+)
puts "La suma de los vectores es #{c = [c1+c2]}" | true |
71f42098c94c55b9ae17812afdb5b337eb069193 | Ruby | imathis/wordrush | /app/models/turn.rb | UTF-8 | 1,298 | 2.828125 | 3 | [] | no_license | class Turn < ApplicationRecord
belongs_to :round
belongs_to :player
belongs_to :game
has_many :plays, dependent: :destroy
has_many :words, through: :plays
# length in seconds (add a couple of seconds to account for load time)
def time_limit
62
end
def new?
plays.empty?
end
def time_elapsed
Time.now - plays.first.created_at
end
def ms_remaining
(1000 * time_remaining).ceil
end
def seconds_remaining
t = (time_remaining).ceil
t <= 0 ? 0 : t
end
def time_remaining
time_limit - time_elapsed
end
def finished?
next_word.nil? || !plays.empty? && time_remaining <= 0
end
def next_word
(game.words - played_words).shuffle.first
end
def finish
plays.last.finish(false)
end
def played_words
complete = round.plays.complete.order(:duration)
complete.empty? ? [] : complete.map(&:word)
end
def finish_word(complete=nil)
if p = plays.last
p.finish(0 < time_remaining)
end
end
def current_word
plays.last.word
end
def words_remaining
round.words_remaining
end
def score
plays.complete.map(&:score)
end
def play_word
finish_word
if w = next_word
plays.create(round: round, player: player, word: w, index: plays.size)
end
end
end
| true |
bc2d6c7c2e06557c3d27d1cc8b31ab1fcc5e1aa1 | Ruby | drproteus/chess | /pieces/vector_sum.rb | UTF-8 | 132 | 3.375 | 3 | [] | no_license | def vector_sum(vectors)
result = [0,0]
vectors.each do |vec|
result[0] += vec[0]
result[1] += vec[1]
end
result
end | true |
626d1f53002ac96321fa8f5577d881b60df185e1 | Ruby | mdippery/usaidwat | /lib/usaidwat/client.rb | UTF-8 | 1,549 | 2.546875 | 3 | [
"MIT"
] | permissive | require 'usaidwat/service'
require 'usaidwat/ext/time'
module USaidWat
module Client
class ReachabilityError < RuntimeError
def initialize(msg = nil)
super(msg || 'Reddit unreachable')
end
end
class NoSuchUserError < StandardError; end
class BaseRedditor
attr_reader :username
def initialize(username)
@username = username
end
def comments
user.comments(100)
rescue NoMethodError
raise NoSuchUserError, username
rescue RuntimeError
raise ReachabilityError
end
def link_karma
about.link_karma
end
def comment_karma
about.comment_karma
end
def created_at
about.created_utc
end
def age
(Time.now - created_at).ago
end
def to_s
"#{username}"
end
def posts
user.posts
rescue NoMethodError
raise NoSuchUserError, username
rescue RuntimeError
raise ReachabilityError
end
private
def user
@service.user(username)
end
def about
user.about
rescue NoMethodError
raise NoSuchUserError, username
end
end
class Redditor < BaseRedditor
def initialize(username)
@service = USaidWat::Service::RedditService.new
super
end
end
class TestRedditor < BaseRedditor
def initialize(username)
@service = USaidWat::Service::MockService.new
super
end
end
end
end
| true |
bd71745deec3370de93820895ed92350614ca3e0 | Ruby | alwikah/oop-food-delivery | /app/controllers/employees_controller.rb | UTF-8 | 301 | 2.546875 | 3 | [] | no_license | class EmployeesController
attr_reader :employees_repository, :view
def initialize(view)
@view = view
@employees_repository = EmployeesRepository.new
end
def index
employees = employees_repository.all
employees.each do |employee|
view.display employee
end
end
end
| true |
f46ad0bfce98292f780e030dc9bed8a27bca25e6 | Ruby | enowmbi/algorithms | /first_recurring_character.rb | UTF-8 | 178 | 3.5 | 4 | [] | no_license | def first_recurring_character(arr)
char_hash = {}
arr.each do |char|
if char_hash.has_key?(char)
return char
else
char_hash[char] = 1
end
end
end
| true |
aa808f3619c09fad4c367d0c3a37d37a41124cd3 | Ruby | interfirm/rails-tutorial-2020 | /app/helpers/datetime_helper.rb | UTF-8 | 412 | 2.53125 | 3 | [] | no_license | module DatetimeHelper
def message_datetime(datetime:)
logger.debug(datetime)
today = DateTime.now.beginning_of_day
if today <= datetime
datetime.strftime('%R')
elsif today.yesterday <= datetime
datetime.strftime('昨日 %R')
elsif today.beginning_of_year <= datetime
datetime.strftime('%m月 %d日')
else
datetime.strftime('%Y年 %m月 %d日')
end
end
end | true |
dc4360e59b90769afd4e83ae674fcf63f77de3a2 | Ruby | ajshemi/oo-meowing-cat-dumbo-web-111819 | /lib/meowing_cat.rb | UTF-8 | 103 | 3.09375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | ## code your solution here.
require 'pry'
class Cat
attr_accessor :name
def meow
puts "meow!"
end
end | true |
5339d9c5affe0ae1a1ad67370cae724d1bc8836b | Ruby | drumovski/Coder_Academy_Term_1_and_2 | /week6/strict.rb | UTF-8 | 1,377 | 4.15625 | 4 | [] | no_license | # Is it in the array strict mode
# Arrays can store all different data types.
# These arrays can get quite large and it can get
# quite difficult to keep track of what is in them.
# Sometimes, we want extra flexibility in an array search,
# and want control over casing.
# Create a function that will take a string,
# an array, an additional argument called **strict**,
# and will return whether or not that string exists in the array.
# The additional argument, strict, is a boolean argument.
# * If strict is true, in_array_strict? should care about LEtTeR cASinG
# * If strict is false, in_array_strict? should not care about LEtTeR cASinG and should return true for any match
# Create Test::Unit tests in 27_in_array_strict_test.rb
# Examples:
# in_array_strict?("HeLLo", ["hi", "howdy", "Hello"], true) => false
# in_array_strict?("HeLLo", ["hi", "howdy", "Hello"], false) => true
## Optional
# Try completing this challenge without using any array
# helper methods, except for .each
def in_array_strict? (string, arr, strict)
if strict
arr.each do |s|
if string == s
return true
else
return false
end
end
else
arr.each do |s|
if string.downcase == s.downcase
return true
end
end
return false
end
end
| true |
5f8277de31f6694019f8861b7ecd68fe3c419c96 | Ruby | jfeng702/JS-Exercises | /cracking/arraystring/one_away.rb | UTF-8 | 638 | 3.9375 | 4 | [] | no_license | # pale, ple => true
# pales, pale => true
# pale, bake => false
def one_away(str1, str2)
return false if str1.length - str2.length > 1
i = 0
j = 0
one_fail = false
while i < str1.length || j < str2.length
if str1[i] == str2[j]
i += 1
j += 1
elsif str1[i] != str2[j]
return false if one_fail
one_fail = true
if str1.length < str2.length
j += 1
elsif str1.length > str2.length
i += 1
else
i += 1
j += 1
end
end
end
true
end
p one_away('pale', 'ple')
p one_away('pales', 'pale')
p one_away('pale', 'bale')
p one_away('pale', 'bake')
| true |
cb71ed27b7699a563931c3d27d9a27c001665a17 | Ruby | iangrubb/oo-cash-register-nyc-web-062419 | /lib/cash_register.rb | UTF-8 | 910 | 3.46875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive |
class CashRegister
def initialize(discount = 0)
@total = 0
@discount = discount
@items = []
@transactions = []
end
attr_accessor :discount
attr_accessor :total
def items
@items
end
def add_item(title, price, quantity=1)
@total += price.to_f * quantity
(0...quantity).each do
@items << title
end
@transactions << [title, price, quantity]
end
def apply_discount
if @discount == 0
"There is no discount to apply."
else
@total *= ((100.0 - @discount.to_f)/100.0).round(2)
"After the discount, the total comes to $#{@total.to_i}."
end
end
def void_last_transaction
last = @transactions.pop
@total -= last[1] * last[2]
(0...last[2]).each do
@items.pop
end
end
end | true |
b6ef3b9a42be0351a67fea06a503df7144e01d34 | Ruby | EricRicketts/LaunchSchoolPrepAndSupplements | /IntroductionToRegularExpressions/character-class-shortcuts/exercises.rb | UTF-8 | 1,637 | 3.328125 | 3 | [] | no_license | require 'minitest/autorun'
require 'minitest/pride'
require 'byebug'
class Exercises < Minitest::Test
def test_exercise_one
str = "reds and blues" + "\n" + "the lazy cat sleeps"
my_regex = /\s\w{3}\s/
assert_equal(3, str.scan(my_regex).length)
end
def test_exercise_two
str = "Doc in a big red box.\nHup! 2 3 4"
my_regex1 = /\s...\s/
first_result = str.scan(my_regex1)
expected = [" big ", " 2 3 "]
assert_equal(expected, first_result)
# so why does this match work the way it does?
# the first match is \sbig\s, but \sred\s
# does not match because the opening \s for red
# was the closing \s for big. This is important
# to note because the trailing \s for big was
# consumed by the regex engine to make the match
# for \sbig\s, thus the trailing \s is not
# available for any other match sequence so red
# does not get the benefit of a preceeding \s.
# On the second line
# \s2 3\s matches because the . can be any character
# including a space. It does not match box because
# box is followed by a period. It does not match
# Hup! because Hup is followed by a !. Doc is not
# matched because it is not preceeded by whitespace
end
def test_exercise_three
str = "Hello 4567 bye CDEF - cdef" + "\n" +
"0x1234 0x5678 0xABCD" + "\n" + "1F8A done"
my_regex = /\s\h{4}\s/
assert_equal(4, str.scan(my_regex).length)
end
def test_exercise_four
str = "The red d0g chases the b1ack cat." + "\n" +
"a_b c_d"
my_regex = /[a-zA-Z]{3}/
assert_equal(7, str.scan(my_regex).length)
end
end | true |
29ac79f9bf1f2e57cffb921b8ab46f327262b626 | Ruby | dan-f/coop-site | /lib/tasks/coop.rake | UTF-8 | 970 | 2.71875 | 3 | [] | no_license | namespace :coop do
desc "Populate database with list of coops"
task create_coops: :environment do
coops = ["Brown Bag", "Fairchild", "Harkness", "Keep", "Old Barrows", "Pyle", "Tank", "Third World"]
coops.each do |coopName|
coop = Coop.new({ name: coopName })
if coop.save
puts "Co-op #{coop.name} (id: #{coop.id}) successfully created."
else
puts "Error: coop #{coop.name} not saved in database"
end
end
end
desc "delete the coops (prevent duplicates)"
task delete_coops: :environment do
coops = ["Brown Bag", "Fairchild", "Harkness", "Keep", "Old Barrows", "Pyle", "Tank", "Third World"]
coops.each do |coopName|
coopRet = Coop.where({ name: coopName })
coopRet.each do |coop|
if coop.destroy
puts "Co-op #{coop.name} (id: #{coop.id}) successfully destroyed."
else
puts "Error: coop #{coop.name} not deleted"
end
end
end
end
end
| true |
cee0df0adb8e69cb3c21b73067c009a50a3ec750 | Ruby | esumbar/passphrase | /spec/passphrase/passphrase_spec.rb | UTF-8 | 4,268 | 3.171875 | 3 | [
"MIT"
] | permissive | require "passphrase"
module Passphrase
RSpec.shared_examples "Passphrase object" do
it "responds to attribute reader method passphrase()" do
expect(@passphrase).to respond_to(:passphrase)
end
it "responds to attribute reader method number_of_words()" do
expect(@passphrase).to respond_to(:number_of_words).with(0).arguments
end
it "responds to the generate() method with zero arguments" do
expect(@passphrase).to respond_to(:generate).with(0).arguments
end
it "responds to predicate method using_random_org?()" do
expect(@passphrase).to respond_to(:using_random_org?)
end
it "responds to the to_s() method" do
expect(@passphrase).to respond_to(:to_s)
end
it "responds to the inspect() method with zero arguments" do
expect(@passphrase).to respond_to(:inspect).with(0).arguments
end
it "does not respond to the word_origins() method (private)" do
expect(@passphrase).not_to respond_to(:word_origins)
end
end
RSpec.describe Passphrase, "for generating passphrase objects" do
it "yields itself during instantiation" do
expect { |b| Passphrase.new(&b) }.to yield_with_args(Passphrase)
end
# Dependence on RANDOM.ORG only affects the DicewareRandom class.
# Therefore, only need to thoroughly test the case where RANDOM.ORG is not used.
context "initialized to use RANDOM.ORG" do
it "the predicate method should confirm it is using RANDOM.ORG" do
passphrase = Passphrase.new(use_random_org: true)
expect(passphrase).to be_using_random_org
end
end
context "initialized with default options" do
before do
@passphrase = Passphrase.new
end
it "returns a passphrase of type PassphraseString" do
expect(@passphrase.passphrase).to be_an_instance_of(PassphraseString)
end
it "returns a passphrase with the default number of words" do
number_of_words = @passphrase.passphrase.split.length
expect(number_of_words).to eq(Default.options[:number_of_words])
end
it "should not be using RANDOM.ORG" do
expect(@passphrase).not_to be_using_random_org
end
include_examples "Passphrase object"
end
context "initialized to generate a passphrase with 1 word" do
before do
@passphrase = Passphrase.new(number_of_words: 1)
end
it "returns a passphrase of type PassphraseString" do
expect(@passphrase.passphrase).to be_an_instance_of(PassphraseString)
end
it "returns a passphrase with one word" do
number_of_words = @passphrase.passphrase.split.length
expect(number_of_words).to eq(1)
end
it "should not be using RANDOM.ORG" do
expect(@passphrase).not_to be_using_random_org
end
include_examples "Passphrase object"
context "after executing the generate() method" do
before do
dwr = [["language"], ["11111"], ["passphrase"]]
allow(DicewareMethod).to receive(:run).and_return(dwr)
@result = @passphrase.generate
end
it "returns itself" do
expect(@result).to equal(@passphrase)
end
it "returns a passphrase of type PassphraseString" do
expect(@result.passphrase).to be_an_instance_of(PassphraseString)
end
it "contains a passphrase with one word" do
number_of_words = @result.passphrase.split.length
expect(number_of_words).to eq(1)
end
it "contains the passphrase string" do
expect(@result.passphrase).to eq("passphrase")
end
it "returns the passphrase when printed" do
sio = StringIO.new("")
$stdout = sio
expect { puts @result }.to change { sio.string.chomp }
.from("").to(@result.passphrase)
end
it "can be inspected" do
expect(@result.inspect).to match(
passphrase: "passphrase",
number_of_words: 1,
use_random_org: false,
word_origins: { "passphrase" => {
language: "language",
die_rolls: "11111"
}
}
)
end
end
end
end
end
| true |
cb235fd325c9e0fbb10eaf23b210d4a6455b37ce | Ruby | matadon/postinius | /lib/postinius/mime_type.rb | UTF-8 | 1,209 | 2.796875 | 3 | [
"Apache-2.0"
] | permissive | module Postinius
class MimeType
include_class javax.mail.internet.ContentType
#
# Utility constructor; hands back the object if it's an address,
# builds a new one if not. Helps us avoid needless object
# churn.
#
def self.create_from(type)
return(type) if address.is_a?(self)
return(self.new(type))
end
def initialize(type = nil)
if(type.is_a?(ContentType))
@type = type
elsif(type.is_a?(self.class))
@type = type.to_java
elsif(type.nil? or type.empty?)
@type = ContentType.new
else
@type = ContentType.new(type)
end
end
def empty?
@type.getBaseType == 'null/null'
end
def charset=(charset)
@type.setParameter('charset', charset)
end
def charset
@type.getParameter('charset')
end
def base
@type.getBaseType
end
def primary
@type.getPrimaryType
end
def subtype=(type)
@type.setSubType(type)
end
def subtype
@type.getSubType
end
def to_java
@type
end
def to_s
@type.to_string
end
def eql?(other)
if(other.is_a?(self.class))
@type.match(other.to_java)
else
@type.match(other)
end
end
def ==(other)
eql?(other)
end
end
end
| true |
59545ece66c13dc0a70c1cc21f6786be737380a6 | Ruby | UladKonop/TEST_TASK_Lunar_dinner | /table.rb | UTF-8 | 457 | 2.984375 | 3 | [] | no_license | # frozen_string_literal: true
require_relative('instance_counter')
class Table
include InstanceCounter
attr_reader :id, :history, :people
def initialize(seats_amount)
@id = register_instance
@seats_amount = seats_amount
@history = []
@people = []
end
def people=(person)
@people << person
end
def full?
@people.size.eql?(@seats_amount)
end
def clear
@history << @people.clone
@people.clear
end
end
| true |
e5d05b60a3b66966d2e8baccc23534ffcf076f3d | Ruby | kanderson38/dynamic-programming | /lib/max_subarray.rb | UTF-8 | 350 | 3.359375 | 3 | [
"MIT"
] | permissive |
# Time Complexity: O(n) where n is the number of items in the array
# Space Complexity: O(1)
def max_sub_array(nums)
return 0 if nums == nil
return nil if nums.length == 0
max_sum = nums[0]
sum = 0
nums.length.times do |i|
sum = [nums[i], sum + nums[i]].max
if sum > max_sum
max_sum = sum
end
end
return max_sum
end
| true |
c35cc423f4b44fcad4b7c16b7334f9bde6fdea95 | Ruby | PlasticLizard/wonkavision | /lib/wonkavision/plugins/analytics/cellset.rb | UTF-8 | 4,116 | 2.671875 | 3 | [
"MIT"
] | permissive | require "set"
module Wonkavision
module Analytics
class CellSet
attr_reader :axes, :query, :cells, :totals, :aggregation
def initialize(aggregation,query,tuples)
@axes = []
@query = query
@aggregation = aggregation
@cells = {}
@measure_names = Set.new
dimension_members = process_tuples(tuples)
start_index = 0
query.axes.each do |axis_dimensions|
@axes << Axis.new(self,axis_dimensions,dimension_members,start_index)
start_index += axis_dimensions.length
end
calculate_totals
end
def columns; axes[0]; end
def rows; axes[1]; end
def pages; axex[2]; end
def chapters; axes[3]; end
def sections; axes[4]; end
def measure_names
@measure_names.to_a
end
def selected_measures
@query.selected_measures
end
def inspect
@cells.inspect
end
def to_s
@cells.to_s
end
def [](*coordinates)
coordinates.flatten!
key = coordinates.map{ |c|c.nil? ? nil : c.to_s }
@cells[key] || Cell.new(self,key,[],{})
end
def length
@cells.length
end
private
def calculate_totals(include_subtotals=false)
cells.keys.each do |cell_key|
measure_data = cells[cell_key].measure_data
append_to_subtotals(measure_data,cell_key)
@totals ? @totals.aggregate(measure_data) : @totals = Cell.new(self,
[],
[],
measure_data)
end
end
def append_to_subtotals(measure_data, cell_key)
dims = []
axes.each do |axis|
axis.dimensions.each_with_index do |dimension, idx|
dims << dimension.name
sub_key = cell_key[0..dims.length-1]
append_to_cell(dims.dup, measure_data, sub_key) if
dims.length < cell_key.length #otherwise the leaf and already in the set
#For axes > 0, subtotals must be padded with nil for all prior axes members
if (axis.start_index > 0)
axis_dims = dims[axis.start_index..axis.start_index + idx]
axis_sub_key = Array.new(axis.start_index) +
cell_key[axis.start_index..axis.start_index + idx]
append_to_cell(axis_dims, measure_data, axis_sub_key)
end
end
end
end
def process_tuples(tuples)
dims = {}
tuples.each do |record|
next unless query.matches_filter?(aggregation, record)
update_cell( query.selected_dimensions, record )
record["dimension_names"].each_with_index do |dim_name,idx|
dim = dims[dim_name] ||= {}
dim_key = record["dimension_keys"][idx]
dim[dim_key] ||= record["dimensions"][dim_name]
end
end
dims
end
def key_for(dims,record)
key = []
dims.each_with_index do |dim_name, idx|
dim_name = dim_name.to_s
dim_ordinal = record["dimension_names"].index(dim_name)
key << record["dimension_keys"][dim_ordinal].to_s
end
key
end
def update_cell(dimensions,record)
cell_key ||= key_for(dimensions,record)
measure_data = record["measures"]
@measure_names += measure_data.keys if measure_data
append_to_cell(dimensions, measure_data, cell_key)
end
def append_to_cell(dimensions, measure_data, cell_key)
cell = cells[cell_key]
cell ? cell.aggregate(measure_data) : cells[cell_key] = Cell.new(self,
cell_key,
dimensions,
measure_data)
end
end
end
end
| true |
1f79fce8b3910b35f4453ecb6e90c77c8ee3f91f | Ruby | shterev/Core-Ruby-1 | /week0/1-standard-types/solution.rb | UTF-8 | 1,450 | 4.03125 | 4 | [
"MIT"
] | permissive |
def histogram(string)
hash = {}
string.each_char { |s| hash[s] = hash.key?(s) ? hash[s] + 1 : 1 }
hash
end
def prime?(n)
(1..n - 1).each { |i| return false if i % n == 0 }
true
end
def ordinal(n)
case n = n.to_s
when n.end_with?('1') then "#{n}st"
when n.end_with?('11') then "#{n}th"
when n.end_with?('2') then "#{n}nd"
when n.end_with?('3') then "#{n}rd"
else "#{n}th"
end
end
def palindrome?(object)
true if object.to_s == object.to_s.reverse
end
def anagram?(word, other)
return false if word.length != other.length
word.each_char do |s|
return false unless other.include? s
end
true
end
def remove_prefix(string, prefix)
string.split(prefix).last
end
def remove_suffix(string, suffix)
string.split(suffix).first
end
def digits(n)
array = []
n.to_s.each_char do |s|
array << s.to_i
end
array
end
def fizzbuzz(range)
array = []
range.each do |i|
case
when i % 3 == 0 && i % 5 == 0 then array << :fizz_buzz
when i % 3 == 0 then array << :fizz
when i % 5 == 0 then array << :buzz
else array << i
end
end
array
end
def count(array)
hash = {}
array.each { |a| hash[a] = hash.key?(a) ? hash[a] + 1 : 1 }
hash
end
def count_words(*sentences)
hash = {}
string = ''
sentences.each { |a| string += a }
string = string.downcase.gsub(/[,.]/, ' ').split(' ')
string.each { |s| hash[s] = hash.key?(s) ? hash[s] + 1 : 1 }
hash
end
| true |
ce5ac6578f93818c5c16a2b2c4389b67f8d3a131 | Ruby | rueki/Ruby | /flow_control/ex2.rb | UTF-8 | 185 | 3.921875 | 4 | [] | no_license | def change_caps(letters)
if letters.length > 10
puts letters.upcase
else
puts letters
end
end
puts "What would you like to say?"
answer = gets.chomp
change_caps(answer) | true |
127d0ec6c7cd793a3857df00ad5ac47408c9ebb4 | Ruby | zhangst23/tutorial | /Ruby/IntroToRuby/Ruby 学习笔记.rb | UTF-8 | 8,436 | 4.09375 | 4 | [] | no_license | Ruby 学习笔记.rb
1. 在 Ruby 中定义类
class Customer
end
# Ruby 提供了四种类型的变量:
# 局部变量:局部变量是在方法中定义的变量。局部变量在方法外是不可用的。在后续的章节中,您将看到有关方法的更多细节。局部变量以小写字母或 _ 开始。
# 实例变量:实例变量可以跨任何特定的实例或对象中的方法使用。这意味着,实例变量可以从对象到对象的改变。实例变量在变量名之前放置符号(@)。
# 类变量:类变量可以跨不同的对象使用。类变量属于类,且是类的一个属性。类变量在变量名之前放置符号(@@)。
# 全局变量:类变量不能跨类使用。如果您想要有一个可以跨类使用的变量,您需要定义全局变量。全局变量总是以美元符号($)开始。
2.在 Ruby 中使用 new 方法创建对象
cust1 = Customer. new
3.下面的实例将创建类 Sample 的一个对象,并调用 hello 方法:
class Sample
def hello
puts "Hello Ruby!"
end
end
#使用上面的类来创建对象
object = Sample. new
object.hello
4.Ruby 类案例
# 下面将创建一个名为 Customer 的 Ruby 类,声明两个方法:
# display_details:该方法用于显示客户的详细信息。
# total_no_of_customers:该方法用于显示在系统中创建的客户总数量。
class Customer
@@no_of_customers=0
def initialize(id,name,addr)
@cust_id=id
@cust_name=name
@cust_addr=addr
end
def display_details()
puts "Customer id #@cust_id"
puts "Customer name #@cust_name"
puts "Customer address #@cust_addr"
end
def total_no_of_customers()
@@no_of_customers += 1
puts "Total number of customers: #@@no_of_customers"
end
end
# 创建对象
cust1=Customer.new("1","John","Wisdom Apartments,Ludhiya")
cust2=Customer.new("2","Poul","New Empire road,Khandala")
# 调用方法
cust1.display_details()
cust1.total_no_of_customers()
cust2.display_details()
cust2.total_no_of_customers()
5.Ruby 循环
5.1 while循环
while conditional [do]
code
end
5.3 while 修饰符
code while condition
或者
begin
code
end while condition
# 实例
$i = 0
$num = 5
begin
puts("在循环语句中 i = #$i" )
$i += 1
end while $i < $num
6 Ruby until 语句
until conditional [do]
code
end
6.1 Ruby until 修饰符
语法
code until conditional
或者
begin
code
end until conditional
7.Ruby for 语句
for variable [, variable ...] in expression [do]
code
end
# 实例
fro i in 0..5
puts "局部变量的值为 #{i}"
end
7.1
for...in 循环几乎是完全等价于:
(expression).each do |variable[, variable...]| code end
但是,for 循环不会为局部变量创建一个新的作用域。
语法中 do 可以省略不写。但若要在一行内写出 for 式,则必须以 do 隔开条件式或程式区块。
实例
#!/usr/bin/ruby
# -*- coding: UTF-8 -*-
(0..5).each do |i|
puts "局部变量的值为 #{i}"
end
8. Ruby break 语句
9. Ruby next 语句
10. Ruby redo 语句
重新开始最内部循环的该次迭代,不检查循环条件。如果在块内调用,则重新开始 yield 或 call。
实例
#!/usr/bin/ruby
# -*- coding: UTF-8 -*-
for i in 0..5
if i < 2 then
puts "局部变量的值为 #{i}"
redo
end
end
11
如果 retry 出现在 begin 表达式的 rescue 子句中,则从 begin 主体的开头重新开始。
如果 retry 出现在迭代内、块内或者 for 表达式的主体内,则重新开始迭代调用。迭代的参数会重新评估。
for i in 1..5
retry if i > 2
puts "局部变量的值为 #{i}"
end
12
module Trig
PI = 3.1415926
def Trig.sin(x)
# ..
end
def Trig.cos(x)
# ..
end
end
13
require 'trig.rb'
require 'moral'
14
include modulename
15
class Sample
include A
include B
def s1
end
end
15 迭代器
15.1 each
collection.each do |variable|
code
end
#
ary = [1,2,3,4,5]
ary.each do |i|
puts i
end
15.2 Ruby collect 迭代器
#
a = [1,2,3,4,5]
b = Array.new
b = a.collect( |x|x )
puts b
16 File
File.new方法
# 您可以使用 File.new 方法创建一个 File 对象用于读取、写入或者读写,读写权限取决于 mode 参数。最后,您可以使用 File.close 方法来关闭该文件。
语法
aFile = File.new("filename","mode")
#...处理文件
aFile.close
File.open方法
# 您可以使用 File.open 方法创建一个新的 file 对象,并把该 file 对象赋值给文件。但是,File.open 和 File.new 方法之间有一点不同。不同点是 File.open 方法可与块关联,而 File.new 方法不能。
File.open("filename","mode") do |aFile|
# ... process the file
end
读取和写入文件
sysread 方法
# 您可以使用方法 sysread 来读取文件的内容。当使用方法 sysread 时,您可以使用任意一种模式打开文件。例如:
# 下面是输入文本文件:
This is a simple text file for testing purpose.
# 现在让我们尝试读取这个文件:
aFile = File.new("input.txt","r")
if aFile
content = aFile.sysread(20)
puts content
else
puts "Unable to open file!"
end
#################### 实践过程中遇到的ruby问题 ###################
1. ruby的collect或者map
ids = @pages.collect { |p| p.id }.join(',')
# ids类似: 23,32,53,64,155
# 取出所有符合条件的 id
# 说明:
~ each——连续访问集合的所有元素
~ collect—-从集合中获得各个元素传递给block,block返回的结果生成新的集合。
~ map——-同collect。
~ inject——遍历集合中的各个元素,将各个元素累积成返回一个值。
# 例子:
def debug(arr)
puts '--------'
puts arr
end
h = [1,2,3,4,5]
h1 = h
h1.each{|v|puts sprintf('values is:%s',v)}
h2 = h.collect{|x| [x,x*2]}
debug h2
h3 = h.map{|x| x*3 }
debug h3
h4 = h.inject{|sum,item| sum+item}
debug h4
结果:
values is:1
values is:2
values is:3
values is:4
values is:5
--------
####
当你需要从数据库中查找某一列数据时,通常会有下面三种做法:
User.select(:id).collect(&:id)
User.select(:id).map(&:id)
User.pluck(:id)
很显然前两种中的map与collect其实应该被归结为同一种方式,因为map实际上是collect方法的别名。并且,
这种方式其实是通过select方法,获取一个User对象数组,之后通过对每个对象循环调用id方法,最后返回一个包含
符合条件的id数组。
而对于第三种pluck方法,则不用,其并不会对User对象模型进行操纵,而是直接使用SQL语句对数据库进行查询
并直接返回包含id的结果数组。
这两者的区别用一句话表示就是「pluck返回的是直接结果数据,select返回的则是结果模型」,二者的差异导致的
直接结果就是pluck的执行效率要相比select更高一些,
2. update(id, attributes)
update会调用模型的validation方法,只有当所有validation条件验证通过,才能被保存到数据库中,否则会返回错误,错误信息存储到对象的errors中。
Model.update(1,:language => “ruby”,:framework => “rails”)
Model.update([1,2],[{:language => “ruby”,:framework => “rails”},{:ide => “aptana”}])
2.1 update_all(updates)
调用update_all更新数据,不会触发模型的回调方法和validation方法,并且所有的修改都会在一条SQL语句中执行。
# Update all customers with the given attributes
Customer.update_all wants_email: true
# Update all books with 'Rails' in their title
Book.where('title LIKE ?', '%Rails%').update_all(author: 'David')
# Update all books that match conditions, but limit it to 5 ordered by date
Book.where('title LIKE ?', '%Rails%').order(:created_at).limit(5).update_all(author: 'David')
2.2 update_attribute(name, value)
用来更新记录中的某一字段。特别适合用来更新类似boolean类型,计数一类的字段。它也会触发validation方法,不过仍然会触发回调方法。
obj = Model.find_by_id(params[:id])
obj.update_attribute :language, “php”
2.3 update_attributes
update_attribute方法的升级版,可以同时更新一条记录的多个字段,与update_attribute一样不会触发validation方法。
attributes = {:name => “xyz”, :age => 20}
obj = Model.find_by_id(params[:id])
obj.update_attributes(attributes)
更多的细节,大家可以去参阅Rails API文档。 :)
| true |
25c0082d912a0f82381e71710edc0faf80c0b15b | Ruby | aamannai/Semester4_IS | /phase2.6/app/models/curriculum.rb | UTF-8 | 941 | 2.5625 | 3 | [] | no_license | class Curriculum < ApplicationRecord
#Relationships
has_many :camps
#Required
validates_presence_of :name
validates_presence_of :min_rating
validates_presence_of :max_rating
#Format
validates :name, format: { with: /\A[a-zA-Z]+\z/}
validates :min_rating, numericality: {:only_integer => true}
validates :max_rating, numericality: {:only_integer => true}
#validates :description, format: { with: /\A[a-zA-Z]+\z/}
#Range
validates :min_rating, numericality: { greater_than: -1 }
validates :max_rating, numericality: { less_than: 3001 }
#Unique
validates :name, uniqueness: {case_sensitive: false}
#Scopes
scope :active, -> { where(active: true) }
scope :inactive, -> { where(active: false) }
scope :alphabetical, -> { order('name') }
scope :for_rating, ->(rating) { where('min_rating > ? and max_rating < ?',rating,rating) }
end
| true |
03544a21768b9058934a203b1288f7caf84eb582 | Ruby | andyxhadji/monsterfinder | /app/models/profile_builder.rb | UTF-8 | 315 | 2.703125 | 3 | [] | no_license | class ProfileBuilder
attr_accessor :user
attr_accessor :spots
def initialize(user, spots)
self.user = user
self.spots = spots
end
def render
{
user: user,
monsters: MonsterBuilder.new(spots).render,
totalVotes: spots.map(&:total_vote_count).inject(0, &:+)
}
end
end
| true |
f94c040048b7b200aded24334356aa04ea10f95f | Ruby | mamaadee/phase4 | /app/models/credit_card_type.rb | UTF-8 | 212 | 3.125 | 3 | [] | no_license | class CreditCardType
#getter
attr_reader :name, :pattern
#initializer
def initialize(name, pattern)
@name, @pattern = name, pattern
end
def match(number)
number.to_s.match(pattern)
end
end | true |
140bd1beaaf5e21b4895f1799444088c56222b1a | Ruby | urbantumbleweed/urbantumbleweed | /w01/d04/Alexandra_Shook/temperature.rb | UTF-8 | 1,060 | 5.375 | 5 | [] | no_license | # ### Celsius Temperature Converter
# - Create a new file called temperature.rb
# - Write `convert_to_fahrenheit` and `convert_to_kelvin` methods that will each take a temperature in Celsius as a parameter and return the converted temperature.
# - Once you have these methods written, a program that does the following:
# - The user should be asked to enter a temperature in Celsius
# - The user should be asked to enter if they want to convert the temperature to Fahrenheit or Kelvin
# - After these have been entered, the user should be told what the converted temperature is
def convert_to_fahrenheit(temp_c)
temp_f = (temp_c * 1.8) + 32
return temp_f
end
def convert_to_kelvin(temp_c)
temp_k = temp_c + 273.15
return temp_k
end
puts "Enter a temperature in Celsius:"
temp = gets.chomp.to_i
puts "Do you want to convert to (F)ahrenheit or (K)elvin?"
convert_temp = gets.chomp.downcase
if convert_temp == "f"
result = convert_to_fahrenheit(temp)
else
result = convert_to_kelvin(temp)
end
puts "The converted temperature is #{result}."
| true |
75f1f0756858ab90358a72aa3a444cad00aa1f8f | Ruby | thewmking/adv-ruby-building-blocks | /lib/bubble-sort.rb | UTF-8 | 822 | 4.53125 | 5 | [] | no_license | #for each element in the list, compare it and the element directly to its right.
#if out of order, swap elements. repeat.
def bubble_sort(array)
n = array.length - 1
loop do
swapped = false
(n).times do |i|
if array[i] > array[i+1]
array[i], array[i+1] = array[i+1], array[i]
swapped = true
end
end
break if not swapped
end
puts array
end
bubble_sort([9,2,1,3,5,6,7])
def bubble_sort_by(array)
n = array.length - 1
loop do
swapped = false
(n).times do |i|
if yield(array[i], array[i+1]) > 0
array[i], array[i+1] = array[i+1], array[i]
swapped = true
end
end
break if not swapped
end
puts array
end
bubble_sort_by(["hi", "hello", "hey"]) do |left, right|
left.length - right.length
end
| true |
0c548b69f769f12ec3d8de8a4a8d0573b7887f58 | Ruby | DmytroVasin/urlify | /test/urlify_test.rb | UTF-8 | 1,744 | 2.90625 | 3 | [
"BSD-3-Clause"
] | permissive | #!/usr/bin/env ruby
# encoding: UTF-8
lib = File.expand_path('../../lib/', __FILE__)
$:.unshift lib unless $:.include?(lib)
require 'test/unit'
require 'urlify'
class String
include URLify
end
class URLifyTest < Test::Unit::TestCase
def setup
@philosopher = "Søren Kierkegaard"
@biography = "Boyd: The Fighter Pilot Who Changed the Art of War"
end
def test_subtitle_stripping
assert_equal("Boyd", URLify.strip_subtitle(@biography))
end
def test_mixin_subtitle_stripping
assert_equal("Boyd", @biography.strip_subtitle)
end
def test_ulmaut_deaccentuation
assert_equal("Ae", URLify.deaccentuate("Ä"))
assert_equal("Oe", URLify.deaccentuate("Ö"))
assert_equal("Ue", URLify.deaccentuate("Ü"))
assert_equal("ae", URLify.deaccentuate("ä"))
assert_equal("oe", URLify.deaccentuate("ö"))
assert_equal("ue", URLify.deaccentuate("ü"))
end
def test_deaccentuation
assert_equal("Soeren Kierkegaard", URLify.deaccentuate(@philosopher))
assert_equal("Karl Weierstrass", URLify.deaccentuate("Karl Weierstraß"))
assert_equal("Tomek Bartoszynski", URLify.deaccentuate("Tomek Bartoszyński"))
assert_equal("Jozef Maria Bochenski", URLify.deaccentuate("Józef Maria Bocheński"))
assert_equal("Jerzy Los", URLify.deaccentuate("Jerzy Łoś"))
assert_equal("Jan Lukasiewicz", URLify.deaccentuate("Jan Łukasiewicz"))
assert_equal("Chaim Perelman", URLify.deaccentuate("Chaïm Perelman"))
end
def test_mixin_deaccentuation
assert_equal("Soeren Kierkegaard", @philosopher.deaccentuate)
end
def test_urlification
assert_equal("soeren_kierkegaard", URLify.urlify(@philosopher))
assert_equal("boyd", URLify.urlify(@biography))
end
def test_mixin_urlification
assert_equal("soeren_kierkegaard", @philosopher.urlify)
assert_equal("boyd", @biography.urlify)
end
end
| true |
ed24466608b138b16be9a4d0e478d15bd24ed762 | Ruby | crisweber/corpus-processor | /lib/corpus-processor/processor.rb | UTF-8 | 893 | 3.34375 | 3 | [
"MIT"
] | permissive | # The entry point for processing corpus.
#
# @example Simple use with default configuration.
# CorpusProcessor::Processor.new.process('<P>Some text</P>')
# # => "Some\tO\ntext\tO\n.\tO\n""
class CorpusProcessor::Processor
# @param categories [Hash] the categories extracted with {Categories}.
# @param parser [#parse] the parser for original corpus.
# @param generator [#generate] the generator that computes tokens into
# the tranformed corpus.
def initialize(
categories: CorpusProcessor::Categories.default,
parser: CorpusProcessor::Parsers::Lampada.new(categories),
generator: CorpusProcessor::Generators::StanfordNer.new(categories))
@parser = parser
@generator = generator
end
# Perform the processing of corpus.
#
# @return [String] the converted corpus.
def process corpus
@generator.generate @parser.parse(corpus)
end
end
| true |
e9326e4c2bbb1ae226bcfa02cab6a42dff6af60d | Ruby | jleo3/agile_software_development | /refactoring/lib/generate_primes_v1.rb | UTF-8 | 1,714 | 4.34375 | 4 | [] | no_license | # This class gneerates prime numbers up to a user-specified
# maximum. The algorithm used is the Sieve of Eratosthenes.
# <p>
# Eratosthenes of Cyrene, b. c. 276 BC, Cyrene, Libya --
# d. c. 194, Alexandria. The first man to calculate the
# circumference of the Earth. Also known for working on
# calendars with leap years, he ran the library at Alexandria.
# <p>
# The algorithm is quite simple. Given an array of integers
# starting at 2. Cross out all multiples of 2. Find the next
# uncrossed integer, and cross out all of its multiples.
# Repeat until you have passed the square root of the maximum
# value.
#
# @author Robert C. Martin
# @version 9 Dec 1999 rcm
class GeneratePrimes
def self.generate_primes(max_value)
if max_value >= 2 # the only valid case
# declarations
s = max_value + 1 # size of array
f = Array.new(s) { true } #initialize array to true
# get rid of known non-primes
f[0] = f[1] = false
# sieve
i = 2
while(i < (Math.sqrt(s) + 1))
if f[i] # if i is uncrossed, cross its multiples
j = 2 * i
while j < s
f[j] = false # multiple is not prime
j = j + i
end
end
i = i + 1
end
# how many primes are there?
count = 0
i = 0
while i < s
if f[i]
count = count + 1
end
i = i + 1
end
primes = Array.new(count)
# move the primes into the result
i = 0
j = 0
while i < s
if f[i]
primes[j] = i
j = j + 1
end
i = i + 1
end
return primes # return the primes
else
return []
end
end
end
| true |
c23bdd1c56d84ee9269240ae0b43d3e884d71ab2 | Ruby | najwa/RubyLearning | /Week 3/Exercises/ex06_deaf_grandma.rb | UTF-8 | 918 | 4.28125 | 4 | [] | no_license | # Write a Deaf Grandma program. Whatever you say to grandma (whatever you type in), she should respond with HUH?! SPEAK UP, SONNY!, unless you shout it (type in all capitals). If you shout, she can hear you (or at least she thinks so) and yells back, NO, NOT SINCE 1938! To make your program really believable, have grandma shout a different year each time; maybe any year at random between 1930 and 1950. You can't stop talking to grandma until you shout BYE.
years = (1930...1951).to_a
puts "Grandma: Sonny I've missed ya! Come talk to me!"
printf "You: "
words_to_grandma = gets.chomp
while words_to_grandma != 'BYE'
case words_to_grandma
when words_to_grandma == words_to_grandma.upcase
puts "Grandma: NO, NOT SINCE #{years[rand(years.size)]}!"
else
puts "Grandma: HUH? SPEAK UP, SONNY!"
end
printf "You: "
words_to_grandma = gets.chomp
end
puts 'Grandma: BYE SONNY!'
| true |
85f61b76d850b27313467c2b1bad97a18f9e6dcc | Ruby | Dmitry-White/HackerRank | /30 Days of Code/Ruby/day_2.rb | UTF-8 | 692 | 3.78125 | 4 | [
"MIT"
] | permissive | =begin
Created on Sun Jul 11 15:04:17 2017
@author: Dmitry White
=end
=begin
TODO: Given the meal price (base cost of a meal),
tip percent (the percentage of the meal price being added as tip),
and tax percent (the percentage of the meal price being added as tax) for a meal,
find and print the meal's total cost.
=end
def get_total_cost_of_meal()
meal_cost = gets.to_f
tip_percent = gets.to_i
tax_percent = gets.to_i
tip = meal_cost * (tip_percent.to_f/100)
tax = meal_cost * (tax_percent.to_f/100)
total_cost = (meal_cost + tip + tax).round.to_i
return total_cost
end
print("The total meal cost is ", get_total_cost_of_meal(), " dollars.") | true |
9570f7b885fdeee47c42e17b23490664d85ab514 | Ruby | isaacagutey/flix | /spec/models/video_spec.rb | UTF-8 | 2,402 | 2.71875 | 3 | [] | no_license | require 'spec_helper'
describe Video do
it "saves itself" do
video = Video.create(title:"New Video", description:"some description")
expect(Video.first.id).to eql(video.id)
end
it { should have_many(:categories) }
it { should validate_presence_of(:title) }
it { should validate_presence_of(:description) }
describe "search_by_title" do
it "returns an empty array when there's no match" do
iceage = Video.create(title:"Ice Age", description:"some description")
avengers = Video.create(title:"Avengers", description:"some description")
expect(Video.search_by_title("lion")).to eq([])
end
it "returns all matching objects of the search params" do
iceage = Video.create(title:"Ice Age", description:"some description")
avengers = Video.create(title:"Avengers", description:"some description")
expect(Video.search_by_title("Ice Age")).to eq([iceage])
end
it "returns possbile matching objects of partial search title" do
iceage = Video.create(title:"Ice Age", description:"some description")
avengers = Video.create(title:"Avengers", description:"some description")
expect(Video.search_by_title("venger")).to eq([avengers])
end
it "returns all matches ordered by created_at" do
iceage = Video.create(title:"Ice Ave", description:"some description", created_at:1.day.ago)
avengers = Video.create(title:"Avengers", description:"some description")
expect(Video.search_by_title("Ave")).to eq([avengers, iceage])
end
it "returns an empty array when search param is empty" do
iceage = Video.create(title:"Ice Age", description:"some description")
avengers = Video.create(title:"Avengers", description:"some description")
expect(Video.search_by_title("")).to eq([])
end
end
# describe "#recent videos" do
# it "returns the first 6 most recent videos" do
# iceage = Video.create(title:"Ice Age", description:"some description", created_at:1.day.ago)
# avengers = Video.create(title:"Avengers", description:"some description", created_at: 2.days.ago)
# lion = Video.create(title:"Lion King", description:"some description")
# robin = Video.create(title:"Meet The Robinsons", description:"some description", created_at: 3.days.ago)
# expect(Video.recent_videos).to eq([lion, iceage, avengers])
# end
# end
end | true |
3561b6747f863a690524b7e7a0cde4e7d170993e | Ruby | jamesmacaulay/comp4106 | /code/a1/decision_tree.rb | UTF-8 | 1,091 | 2.546875 | 3 | [] | no_license | $LOAD_PATH.unshift File.dirname(__FILE__)
require 'rubygems'
require 'active_support'
require 'tree'
require 'lib/math_ext'
require 'lib/tree_ext'
module DecisionTree
def self.subset(set, attribute, attribute_value)
set.select {|example| example[attribute] == attribute_value}
end
def self.probability(set, attribute, attribute_value)
subset(set, attribute, attribute_value).size.to_f / set.size.to_f
end
def self.entropy(set, decision_attribute)
decision_attribute.values.sum do |v|
probability = probability(set, decision_attribute, v)
probability.zero? ? 0.0 : -(probability * Math.log2(probability))
end
end
def self.info(attribute, set, decision_attribute)
attribute.values.sum do |v|
probability(set, attribute, v) * entropy(subset(set, attribute, v), decision_attribute)
end
end
def self.gain(set, attribute, decision_attribute)
entropy(set, decision_attribute) - info(attribute, set, decision_attribute)
end
end
require 'decision_tree/attribute'
require 'decision_tree/data_set'
require 'decision_tree/base' | true |
a802abc1526098c0de8277890e3e11395c3206f9 | Ruby | team-ramrod/treva | /leros/asm/sim/leros_sim.rb | UTF-8 | 5,352 | 3.15625 | 3 | [] | no_license | #!/usr/bin/env ruby
require 'readline'
$NUM_REGISTERS = 1000
$print_steps = false
if ARGV.length > 0
$print_steps = true
end
class Treva
attr_accessor :pc, :registers
def initialize file, io = nil
@accu = 0
@io = io
@registers = Array.new($NUM_REGISTERS, 0)
@pc = 0
@app = Array.new
@labels = Hash.new
@breakpoints = Array.new
File.open(file, 'r') do |f|
while line = f.gets
line.slice!(line.index('#')..-1) unless line.index('#').nil?
line.slice!(line.index("//")..-1) unless line.index("//").nil?
line.strip!
if line.index(':')
@labels[line[0..-2]] = @app.length
else
@app.push(line)
end unless line.empty?
end
end
@LENGTH = @app.size
end
def step args
if @pc >= @LENGTH
puts "program end"
return
end
chunks = @app[@pc].split
@pc += 1
case chunks.size
when 1 #nop
send chunks[0].to_sym
when 2
send chunks[0].to_sym, chunks[1]
else
send chunks[0].to_sym, chunks[1..-1]
end
end
def help bad_command
puts "unknown command" if bad_command == true
puts "commands are:
(h)elp
(p)rint_source
(s)tep
(b)reakpoint lineno
(c)ontinue
(i)nspect register
(d)ump up_to
(a)ccumulator_print
(q)uit"
end
def print_source args
@app.each_with_index do |val, i|
puts "%d: %s" %[i,val]
end
end
def toggle_breakpoint lineno
lineno = lineno[0].to_i
index = @breakpoints.index lineno
if index == nil
@breakpoints.push lineno
else
@breakpoints.delete_at index
end
end
def continue args
begin
step nil
end while !(@breakpoints.include? @pc or @pc >= @LENGTH)
end
def inspect register
puts @registers[register[0].to_i]
end
def accumulator args
puts @accu
end
def dump range
max_reg = range[0].to_i
@registers[0..max_reg].each_with_index do |val, i|
puts "reg %d = %d" % [i,val]
end
puts "accumulator = %d" % @accu
end
def run
last = ["help", 0]
dict = Hash.new
dict['a'] = :accumulator
dict['s'] = :step
dict['h'] = :help
dict['b'] = :toggle_breakpoint
dict['c'] = :continue
dict['i'] = :inspect
dict['d'] = :dump
dict['p'] = :print_source
while line = Readline.readline('> ', true)
tokens = line.split
tokens = last if tokens.empty?
command = tokens[0][0].chr
break if command == 'q'
if dict.has_key? command
send(dict[command], tokens[1..-1])
else
help true
end
last = tokens
end
end
def run_old
5000.times do |i|
if @pc < @app.size
puts "%d: %s" % [@pc, @app[@pc]] if $print_steps
step
if $print_steps
@registers.each_with_index do |val, i|
puts "register %d = %d" % [i, val] unless val == 0
end
puts "accu = %d" % @accu
puts
end
#fail if @accu == nil
end
end
end
def get_value arg
val =
if arg.index('r') != nil
@registers[arg[1..-1].to_i]
else
arg.to_i
end
fail if val == nil
val
end
def get_address register
register[1..-1].to_i
end
def load arg
if arg.kind_of?(Array)
@accu = @registers[get_value(arg[0]) + (arg[1][1..-1]).to_i]
else
if arg.index('<').nil?
@accu = get_value arg
else
@accu = @labels[arg[1..-1]]
end
end
end
def store arg
if arg.kind_of?(Array)
@registers[get_value(arg[0]) + (arg[1][1..-1]).to_i] = @accu
else
@registers[get_address arg] = @accu
end
end
def add arg
@accu += get_value arg
end
def sub arg
@accu -= get_value arg
end
def shr
@accu /= 2
end
def and arg
@accu = @accu.to_i & (get_value arg).to_i
end
def mult arg
@accu *= get_value arg
end
def loadh arg
if arg.index('>')
@accu = @labels[arg[1..-1]]
else
@accue = arg.to_i << 8
end
end
def jal arg
@registers[get_address arg] = @pc
@pc = @accu
end
def brnz arg
@pc = @labels[arg] if @accu != 0
end
def brz arg
@pc = @labels[arg] unless @accu != 0
end
def branch arg
@pc = @labels[arg]
end
def in args
temp =
@accu = @io.in(args[0], args[1])
end
def out arg
@io.out @accu, arg[0], arg[1]
end
def nop
#do nothing
end
end
| true |
ee8625fb207dacd0cbd8b2dc1be0c97712cb0c09 | Ruby | TakehiroKatayama/RubyStart | /Chapter2/two.rb | UTF-8 | 109 | 3.1875 | 3 | [] | no_license |
coffee = 400
espresso = 100
puts "コーヒー:#{coffee}円"
puts "合計:#{coffee + espresso * 2}円"
| true |
451dd3a85fa710793408dffcb43a72a581d2b7ae | Ruby | ChenLiZhan/sight_advisor | /lib/comment_combine.rb | UTF-8 | 619 | 3.015625 | 3 | [] | no_license | require 'csv'
arr_of_arrs = CSV.read("sight.csv")
arr_of_arrs.shift
adjust_ary = arr_of_arrs.map do |ele|
ele[1].gsub!(/[“”]/,'')
[ele[0],"#{ele[1]}。#{ele[2]}"]
end
place_ary = arr_of_arrs.map do |e|
e[0]
end.uniq
h = Hash.new
place_ary.each do |place|
h[place] = ''
end
h.each do |key, value|
selected_ary = adjust_ary.select { |arr| arr[0] == key }
selected_ary.each do |s|
s[1].gsub!(/[\"\s]/, '')
h[key] << s[1]
end
end
CSV.open("sight_modified.csv", "wb") do |csv|
csv << ['sight', 'comment']
h.each do |key, value|
csv << [key, value]
end
end
| true |
83246ca7b5f8623dd7214030b3bc201086bcb93a | Ruby | narissa-hajratalli/coding-challenges | /ruby_practice/oop-ruby.rb | UTF-8 | 1,341 | 4.34375 | 4 | [] | no_license | # Reference: https://www.youtube.com/watch?v=n_lvik2UYZg&list=PLY6oTPmKnKbZp8Kh6jS5A6j-6H2kGY12e&index=9&t=0s
# Class is just a way that we construct an object in OOP
#creating the definition of a dog
class Dog
#### CLASS VARIABLES ####
@@totalDogs = 0 #These are specific to the class
#### CONSTRUCTOR - always the initialize function ###
def initialize(name)
#Defining instance variables
#To access these variables outside of the class, we need to define getters and setters
@name = name #Takes what we put into the name parameter
@legs = 4
@ears = 2
@tail = true
@@totalDogs += 1
end
##### METHODS #####
#getter - read
def legs
@legs
end
#setters - write
def set_legs(value)
@legs = value
end
def name
@name
end
#Class function -- this will return total dogs
def Dog.total
@@totalDogs
end
def Dog.stuff(my_arg)
puts my_arg
end
end
# Inheritance
class Small_Dog < Dog
stuff :a_thing
# We are just passing symbols in new methods that were pre-defined in the parent class
end
Dog1 = Small_Dog.new("Spot") #Creates a new object (aka an instance) called 'Spot'. It's data type will be Dog.
Dog2 = Small_Dog.new("Fluffy")
Dog2.set_legs(3) #Changes the amount of legs
# We can make multiple dogs
puts Dog1.name
puts Dog2.name
puts Dog.total
| true |
33c92ddfebb4ef392a90fe6c3c79cd8551d60989 | Ruby | chtompkins026/prime-ruby-online-web-sp-000 | /prime.rb | UTF-8 | 85 | 3.171875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def prime?(num)
return false if num < 2
(2...num).none? {|i| num % i ==0}
end
| true |
8ba30748882ba910e8c88708e92be4783895fd44 | Ruby | shogo-tksk/at_coder | /abc148/a.rb | UTF-8 | 46 | 2.84375 | 3 | [] | no_license | puts (%w(1 2 3) - [gets.chomp, gets.chomp])[0] | true |
ad6483cf1bb856f7df30d91c032f1b6bba937afd | Ruby | LMulvey/RubyMathGame | /player.rb | UTF-8 | 221 | 2.828125 | 3 | [] | no_license | module MathGame
class Player
attr_accessor :name
attr_accessor :lives
def initialize(params = {})
@name = params.fetch(:name, false)
@lives = 3
end
end
end
| true |
5a92c969c462389eb9d5cc37d3a7da0b1146a9c2 | Ruby | cjohansen/juicer | /lib/juicer/command/install.rb | UTF-8 | 1,750 | 2.828125 | 3 | [
"MIT"
] | permissive | require "juicer/command/util"
require "cmdparse"
require "pathname"
module Juicer
module Command
# Installs a third party library so Juicer can use it.
#
class Install < CmdParse::Command
include Juicer::Command::Util
# Initializes command
#
def initialize(io = nil)
super('install', false, true)
@io = io || Logger.new(STDOUT)
@version = nil
@path = Juicer.home
self.short_desc = "Install a third party library"
self.description = <<-EOF
Installs a third party used by Juicer. Downloads necessary binaries and licenses
into Juicer installation directory, usually ~/.juicer
EOF
self.options = CmdParse::OptionParserWrapper.new do |opt|
opt.on('-v', '--version [VERSION]', 'Specify version of library to install') { |version| @version = version }
end
end
# Execute command
#
def execute(*args)
args.flatten!
if args.length == 0
raise ArgumentError.new('Please provide a library to install')
end
args.each do |lib|
installer = Juicer::Install.get(lib).new(@path)
path = File.join(installer.install_dir, installer.path)
version = version(installer)
if installer.installed?(version)
@io.info "#{installer.name} #{version} is already installed in #{path}"
break
end
installer.install(version)
@io.info "Successfully installed #{lib.camel_case} #{version} in #{path}" if installer.installed?(version)
end
end
# Returns which version to install
#
def version(installer)
@version ||= installer.latest
end
end
end
end
| true |
8f0fc8677358f86b4a21e600f0fd9ca9c10c23b5 | Ruby | kickaha2019/twine | /Element.rb | UTF-8 | 2,124 | 2.953125 | 3 | [] | no_license | =begin
Element.rb
Base class definitions
=end
class Element
attr_reader :parent, :file, :lineno, :debug
def initialize( parent, indent, file, lineno)
@parent = parent
@indent = indent
@file = file
@lineno = lineno
@debug = false
end
def add_after( indent, args, file, lineno)
@parent.add_after( indent, args, file, lineno)
end
def add_before( indent, args, file, lineno)
@parent.add_before( indent, args, file, lineno)
end
def add_choice( indent, args, file, lineno)
@parent.add_choice( indent, args, file, lineno)
end
def add_choice_separator( indent, args, file, lineno)
@parent.add_choice_separator( indent, args, file, lineno)
end
def add_debug( indent, args, file, lineno)
if args != ''
error( 'Debug has no parameters', file, lineno)
end
@debug = true
self
end
def add_dialogue( indent, args, file, lineno)
@parent.add_dialogue( indent, args, file, lineno)
end
def add_goto( indent, args, file, lineno)
@parent.add_goto( indent, args, file, lineno)
end
def add_prompt( indent, args, file, lineno)
@parent.add_prompt( indent, args, file, lineno)
end
def add_response( indent, args, file, lineno)
@parent.add_response( indent, args, file, lineno)
end
def add_result( indent, args, file, lineno)
@parent.add_result( indent, args, file, lineno)
end
def add_scene( indent, args, file, lineno)
@parent.add_scene( indent, args, file, lineno)
end
def add_set( indent, args, file, lineno)
@parent.add_set( indent, args, file, lineno)
end
def add_text( indent, args, file, lineno)
@parent.add_text( indent, args, file, lineno)
end
def error( msg, file=@file, lineno=@lineno)
@parent.error( msg, file, lineno)
end
def indent
@indent
end
def inspect
"#{self.class.name}(#{@file}:#{@lineno})"
end
def textual?
false
end
def add_world( indent, args, file, lineno)
@parent.add_world( indent, args, file, lineno)
end
end
| true |
0887631a0cb6a6fc3651db572c350f7d9075d1d3 | Ruby | madleech/console | /lib/console.rb | UTF-8 | 3,610 | 2.546875 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
#
# Copyright, 2019, by Samuel G. D. Williams. <http://www.codeotaku.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
require_relative 'console/logger'
require_relative 'console/resolver'
require_relative 'console/terminal/logger'
module Console
class << self
attr_accessor :logger
# Set the default log level based on `$DEBUG` and `$VERBOSE`.
# You can also specify CONSOLE_LEVEL=debug or CONSOLE_LEVEL=info in environment.
# https://mislav.net/2011/06/ruby-verbose-mode/ has more details about how it all fits together.
def default_log_level(env = ENV)
if level = (env['CONSOLE_LEVEL'] || env['CONSOLE_LOG_LEVEL'])
Logger::LEVELS[level.to_sym] || Logger.warn
elsif $DEBUG
Logger::DEBUG
elsif $VERBOSE.nil?
Logger::WARN
else
Logger::INFO
end
end
# You can change the log level for different classes using CONSOLE_<LEVEL> env vars.
#
# e.g. `CONSOLE_WARN=Acorn,Banana CONSOLE_DEBUG=Cat` will set the log level for Acorn and Banana to warn and Cat to
# debug. This overrides the default log level.
#
# @param logger [Logger] A logger instance to set the logging levels on.
# @param env [Hash] Environment to read levels from.
#
# @return [nil] if there were no custom logging levels specified in the environment.
# @return [Resolver] if there were custom logging levels, then the created resolver is returned.
def default_resolver(logger, env = ENV)
# find all CONSOLE_<LEVEL> variables from environment
levels = Logger::LEVELS
.map { |label, level| [level, env["CONSOLE_#{label.to_s.upcase}"]&.split(',')] }
.to_h
.compact
# if we have any levels, then create a class resolver, and each time a class is resolved, set the log level for
# that class to the specified level
if levels.any?
resolver = Resolver.new
levels.each do |level, names|
resolver.bind(names) do |klass|
logger.enable(klass, level)
end
end
return resolver
end
end
# Controls verbose output using `$VERBOSE`.
def verbose?
!$VERBOSE.nil?
end
def build(output, verbose: self.verbose?, level: self.default_log_level)
terminal = Terminal::Logger.new(output, verbose: verbose)
logger = Logger.new(terminal, verbose: verbose, level: level)
return logger
end
end
# Create the logger instance:
@logger = self.build($stderr)
@resolver = self.default_resolver(@logger)
def logger= logger
@logger = logger
end
def logger
@logger || Console.logger
end
def self.extended(klass)
klass.instance_variable_set(:@logger, nil)
end
end
| true |
d2095dfded1bd8d043a85aa380f02a7963562744 | Ruby | mariaclrd/ruby-nos | /spec/ruby_nos/list_spec.rb | UTF-8 | 1,485 | 2.671875 | 3 | [
"MIT"
] | permissive | require "spec_helper"
describe RubyNos::List do
subject{List.new}
let(:element) {double("element", uuid: "12345")}
before do
subject.add(element)
end
describe "#add" do
it "adds an element to the list" do
expect(subject.list.count).to eq(1)
expect(subject.list.first).to eq({element.uuid => element})
end
end
describe "#update" do
let(:element_two) {double("another_element", uuid: "12345", some_other_thing: "something")}
it "updates an element on the list that has the same uuid" do
subject.update(element.uuid, element_two)
expect(subject.list.count).to eq 1
expect(subject.list.first[element_two.uuid].some_other_thing).to eq "something"
end
end
describe "#eliminate" do
it "eliminates an element from the list" do
subject.eliminate(element.uuid)
expect(subject.list.count).to eq 0
end
end
describe "#info_for" do
it "returns the information on the list for an element" do
info = subject.info_for(element.uuid)
expect(info.uuid).to eq("12345")
end
end
describe "#list_of_keys" do
it "returns the list of keys in the list" do
expect(subject.list_of_keys).to eq(["12345"])
end
end
describe "#is_on_the_list?" do
it "returns true if the element exists and folder if it does not exist" do
expect(subject.is_on_the_list?(element.uuid)).to eq(true)
expect(subject.is_on_the_list?("some_uuid")).to eq(false)
end
end
end | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.