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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
dec97e691be75c1d9c2da92f5318262704e85351
|
Ruby
|
cornixxx/lesson2
|
/genie.rb
|
UTF-8
| 1,529
| 3.71875
| 4
|
[] |
no_license
|
class Genie
attr_accessor :health, :mood, :hunger, :asleep, :obedience, :magic
def initialize(name)
@name = name
@health = 20
@mood = 10
@hunger = 10
@asleep = false
@obedience = 20
@magic = 20
end
def make_wish
puts "You ask #{@name} to make one of your wishes come true."
if @magic >= 5
puts "#{@name} claps his hands and gives you the desired"
else
puts "#{@name} doesn't have enough magic and shruggs his shoulders"
end
time_period
@magic -= 5
@obedience -= 3
end
def let_fly
puts "You let #{@name} to fly in the clouds and he smiles thankfully"
time_period
@obedience += 2
@mood += 3
end
def feed
puts "You feed #{@name} with nectar, he really admires it"
time_period
@magic += 5
@hunger -= 5
end
def scold
puts "You scold #{@name} because you have a bad mood"
time_period
puts 'You shold be more patient to your pet!'
@obedience -= 5
@mood -= 5
@health -= 5
end
def put_to_bed
puts "You puts #{@name} to bed"
@asleep = true
time_period
@asleep = false
@magic = 20
puts "#{@name} opens his eyes and is full of energy"
end
def read_book
puts "You read a fairy-tale for #{@name}"
time_period
@obedience += 3
end
private
def time_period
@magic += 5
@hunger += 3
run_away if @obedience <= 0 || @health <= 0
end
def run_away
puts "#{@name} cannot bear your rude treating and fly away"
exit
end
end
| true
|
31abc50eceaa2b5371f8503d68f1fc1d4c3ed5e0
|
Ruby
|
kmeyerhofer/Programming_and_Back-end_Development
|
/120_object_oriented_programming/lesson_4/easy_2/question_10.rb
|
UTF-8
| 673
| 3.203125
| 3
|
[] |
no_license
|
# easier to pass information around the program
# more concise code
# more customization
# less code duplication (DRY)
# Creating objects allows programmers to think more abstractly about the code they are writing.
# Objects are represented by nouns so are easier to conceptualize.
# It allows us to only expose functionality to the parts of code that need it, meaning namespace issues are much harder to come across.
# It allows us to easily give functionality to different parts of an application without duplication.
# We can build applications faster as we can reuse pre-written code.
# As the software becomes more complex this complexity can be more easily managed.
| true
|
7eb22a02a2131de7fa3f0eb1b8581a6dec2c2147
|
Ruby
|
adrienfort/BonVoyage
|
/db/seeds.rb
|
UTF-8
| 8,556
| 2.734375
| 3
|
[] |
no_license
|
require 'faker'
require 'open-uri'
puts "Building a huge seed ..."
puts " - Destroying actual data ..."
puts " destroying explorers and all their dependecies"
Explorer.destroy_all
puts " destroying artists and all their dependencies"
Artist.destroy_all
puts " DONE"
puts " - Creating presentation explorer ..."
adrien = Explorer.new(email: "adrien@gmail.com",
password: "azerty",
first_name: "Adrien",
last_name: "Fort",
nickname: "ad12")
adrien.save!
puts " DONE"
puts " - Creating presentation artist ..."
juca = Artist.new(email: "juca@gmail.com", password: "azerty", name: "Juca")
juca.save!
puts " DONE"
puts " - Creating presentation album ..."
puts " creating album n°1"
album = Album.new(meaning: Faker::Quote.famous_last_words,
name: Faker::Music.album,
artist: juca)
file = URI.open("https://picsum.photos/id/1002/200")
album.photo.attach(io: file, filename: "album_photo.jpg")
album.save!
puts " DONE"
puts " - Creating presentation musics ..."
puts " creating music n°1"
file = open("#{Rails.root.to_s}/app/assets/audios/default-audio.mp3")
music = Music.new(name: "Why is there a way", album: album)
music.audio_file.attach(io: file, filename: "default-audio-music-name", content_type: "audio/mpeg")
music.save!
puts " creating music n°2"
file = open("#{Rails.root.to_s}/app/assets/audios/default-audio.mp3")
music = Music.new(name: "Job done", album: album)
music.audio_file.attach(io: file, filename: "default-audio-music-name", content_type: "audio/mpeg")
music.save!
puts " creating music n°3"
file = open("#{Rails.root.to_s}/app/assets/audios/default-audio.mp3")
music = Music.new(name: "Bill it", album: album)
music.audio_file.attach(io: file, filename: "default-audio-music-name", content_type: "audio/mpeg")
music.save!
puts " creating music n°4"
file = open("#{Rails.root.to_s}/app/assets/audios/default-audio.mp3")
music = Music.new(name: "Arai", album: album)
music.audio_file.attach(io: file, filename: "default-audio-music-name", content_type: "audio/mpeg")
music.save!
puts " creating music n°5"
file = open("#{Rails.root.to_s}/app/assets/audios/default-audio.mp3")
music = Music.new(name: "Just you and me", album: album)
music.audio_file.attach(io: file, filename: "default-audio-music-name", content_type: "audio/mpeg")
music.save!
puts " DONE"
puts " - Creating presentation plays ..."
album.musics.each do |music|
nb = rand(1..20)
1.upto(nb) do |i|
puts " creating play n°#{i} for music #{music.id}"
date = Faker::Date.between(from: 10.days.ago, to: Date.today)
play = Play.new(music: music)
play.created_at = date
play.save!
end
end
puts " DONE"
# puts " - Creating presentation fan_artists"
# puts " - creating fan_artist n°1"
# fan_artist = FanArtist.new(explorer: adrien, artist: Artist.all.first)
# fan_artist.save!
# puts " - creating fan_artist n°2"
# fan_artist = FanArtist.new(explorer: adrien, artist: Artist.all.last)
# fan_artist.save!
# puts " - creating fan_artist n°3"
# fan_artist = FanArtist.new(explorer: adrien, artist: juca)
# fan_artist.save!
# puts " DONE"
# puts " - Creating presentation fan_albums"
# puts " creating fan_album n°1"
# fan_album = FanAlbum.new(explorer: adrien, album: Album.all.first)
# fan_album.save!
# puts " creating fan_album n°2"
# fan_album = FanAlbum.new(explorer: adrien, album: Album.all.last)
# fan_album.save!
# puts " creating fan_album n°3"
# fan_album = FanAlbum.new(explorer: adrien, album: album)
# fan_album.save!
# puts " DONE"
# puts " - Creating presentation fan_musics"
# puts " creating fan_music n°1"
# fan_music = FanMusic.new(explorer: adrien, music: Music.all[0])
# fan_music.save!
# puts " creating fan_music n°2"
# fan_music = FanMusic.new(explorer: adrien, music: Music.all[6])
# fan_music.save!
# puts " creating fan_music n°3"
# fan_music = FanMusic.new(explorer: adrien, music: Music.all[7])
# fan_music.save!
# puts " creating fan_music n°4"
# fan_music = FanMusic.new(explorer: adrien, music: Music.all[8])
# fan_music.save!
# puts " creating fan_music n°5"
# fan_music = FanMusic.new(explorer: adrien, music: Music.all[9])
# fan_music.save!
# puts " creating fan_music n°6"
# fan_music = FanMusic.new(explorer: adrien, music: Music.all[9])
# fan_music.save!
# puts " DONE"
puts " - Creating 25 explorers ..."
1.upto(25) do |i|
puts " creating explorer n°#{i}"
explorer = Explorer.new(email: Faker::Internet.unique.email,
password: "azerty",
first_name: Faker::Name.first_name,
last_name: Faker::Name.last_name,
nickname: Faker::FunnyName.unique.name)
explorer.save!
end
puts " DONE"
puts " - Creating 15 artists ..."
1.upto(15) do |i|
puts " creating artist n°#{i}"
artist = Artist.new(email: Faker::Internet.unique.email,
password: "azerty",
name: Faker::Artist.unique.name)
artist.save!
end
puts " DONE"
puts " - Creating fan_artists ..."
Explorer.all.each do |explorer|
Artist.all.each do |artist|
bool = Faker::Boolean.boolean(true_ratio: 0.3)
if (bool == true)
puts " creating fan_artist between explorer #{explorer.id} and artist #{artist.id}"
fan_artist = FanArtist.new(explorer: explorer, artist: artist)
fan_artist.save!
end
end
end
puts " DONE"
puts " - Creating 1 album per artist ..."
Artist.all.each_with_index do |artist, index|
puts " creating album n°#{index}"
album = Album.new(meaning: Faker::Quote.jack_handey,
name: Faker::Music.album,
artist: artist)
file = URI.open("https://picsum.photos/200")
album.photo.attach(io: file, filename: "album_photo.jpg")
album.save!
end
puts " DONE"
puts " - Creating fan_albums ..."
Explorer.all.each do |explorer|
Album.all.each do |album|
bool = Faker::Boolean.boolean(true_ratio: 0.3)
if (bool == true)
puts " creating fan_album between explorer #{explorer.id} and album #{album.id}"
fan_album = FanAlbum.new(explorer: explorer, album: album)
fan_album.save!
end
end
end
puts " DONE"
puts " - Creating 1 music per albums ..."
Album.all.each_with_index do |album, index|
puts " creating music n°#{index}"
file = open("#{Rails.root.to_s}/app/assets/audios/default-audio.mp3")
music = Music.new(name: Faker::Music::Phish.song, album: album)
music.audio_file.attach(io: file, filename: "default-audio-music-name", content_type: "audio/mpeg")
music.save!
end
puts " DONE"
puts " - Creating fan_musics ..."
Explorer.all.each do |explorer|
Music.all.each do |music|
bool = Faker::Boolean.boolean(true_ratio: 0.3)
if (bool == true)
puts " creating fan_music between explorer #{explorer.id} and music #{music.id}"
fan_music = FanMusic.new(explorer: explorer, music: music)
fan_music.save!
end
end
end
puts " DONE"
puts " - Creating plays"
Music.all.each do |music|
nb = rand(1..30)
1.upto(nb) do |i|
puts " creating play n°#{i} for music #{music.id}"
date = Faker::Date.between(from: 10.days.ago, to: Date.today)
play = Play.new(music: music)
play.created_at = date
play.save!
end
end
puts " DONE"
puts " - Creating presentation playlist ..."
playlist = Playlist.new(name: "Killing me softly", explorer: adrien)
file = open("#{Rails.root.to_s}/app/assets/images/default-playlist-picture.jpg")
playlist.photo.attach(io: file, filename: 'default-playlist-picture.png', content_type: 'image/jpg')
playlist.save!
puts " DONE"
puts " - Creating presentation playlist_musics ..."
puts " creating playlist_music n°1"
playlist_music = PlaylistMusic.new(playlist: playlist, music: Music.all[5])
playlist_music.save!
puts " creating playlist_music n°2"
playlist_music = PlaylistMusic.new(playlist: playlist, music: Music.all[10])
playlist_music.save!
puts " creating playlist_music n°3"
playlist_music = PlaylistMusic.new(playlist: playlist, music: Music.all[20])
playlist_music.save!
puts " creating playlist_music n°4"
playlist_music = PlaylistMusic.new(playlist: playlist, music: Music.all[1])
playlist_music.save!
puts " creating playlist_music n°5"
playlist_music = PlaylistMusic.new(playlist: playlist, music: Music.all[12])
playlist_music.save!
puts " DONE"
Faker::UniqueGenerator.clear
puts "FINISHED !"
| true
|
f4bd2d205c726a8c02dfe558a243b59a5631d0ef
|
Ruby
|
nagachandrakn/Ruby-Fu
|
/countdown3.rb
|
UTF-8
| 98
| 3.265625
| 3
|
[] |
no_license
|
#countdown3.rb
x= gets.chomp.to_i
for i in 1..x do
puts x
x-=1
end
puts "Done!"
| true
|
53a3b95da9f414a86f11e963d7b6d6479a4f7ce9
|
Ruby
|
Bl00d-Kirito/HSK-Cremisi_Portals_Demo
|
/Scripts/106 - PField_Time.rb
|
UTF-8
| 9,981
| 2.8125
| 3
|
[] |
no_license
|
################################################################################
# * Day and night system
################################################################################
def pbGetTimeNow
return Time.now
end
module PBDayNight
HourlyTones=[
Tone.new(-142.5,-142.5,-22.5,68), # Midnight
Tone.new(-135.5,-135.5,-24, 68),
Tone.new(-127.5,-127.5,-25.5,68),
Tone.new(-127.5,-127.5,-25.5,68),
Tone.new(-119, -96.3, -45.3,45.3),
Tone.new(-51, -73.7, -73.7,22.7),
Tone.new(17, -51, -102, 0), # 6AM
Tone.new(14.2, -42.5, -85, 0),
Tone.new(11.3, -34, -68, 0),
Tone.new(8.5, -25.5, -51, 0),
Tone.new(5.7, -17, -34, 0),
Tone.new(2.8, -8.5, -17, 0),
Tone.new(0, 0, 0, 0), # Noon
Tone.new(0, 0, 0, 0),
Tone.new(0, 0, 0, 0),
Tone.new(0, 0, 0, 0),
Tone.new(-3, -7, -2, 0),
Tone.new(-10, -18, -5, 0),
Tone.new(-36, -75, -13, 0), # 6PM
Tone.new(-72, -136, -34, 3),
Tone.new(-88.5, -133, -31, 34),
Tone.new(-108.5,-129, -28, 68),
Tone.new(-127.5,-127.5,-25.5,68),
Tone.new(-142.5,-142.5,-22.5,68)
]
@cachedTone=nil
@dayNightToneLastUpdate=nil
# Returns true if it's day.
def self.isDay?(time)
return (time.hour>=6 && time.hour<20)
end
# Returns true if it's night.
def self.isNight?(time)
return (time.hour>=20 || time.hour<6)
end
# Returns true if it's morning.
def self.isMorning?(time)
return (time.hour>=6 && time.hour<12)
end
# Returns true if it's the afternoon.
def self.isAfternoon?(time)
return (time.hour>=12 && time.hour<20)
end
# Returns true if it's the evening.
def self.isEvening?(time)
return (time.hour>=17 && time.hour<20)
end
# Gets a number representing the amount of daylight (0=full night, 255=full day).
def self.getShade
time=pbGetDayNightMinutes
time=(24*60)-time if time>(12*60)
shade=255*time/(12*60)
end
# Gets a Tone object representing a suggested shading
# tone for the current time of day.
def self.getTone()
return Tone.new(0,0,0) if !ENABLESHADING
if !@cachedTone
@cachedTone=Tone.new(0,0,0)
end
if !@dayNightToneLastUpdate || @dayNightToneLastUpdate!=Graphics.frame_count
@cachedTone=getToneInternal()
@dayNightToneLastUpdate=Graphics.frame_count
end
return @cachedTone
end
def self.pbGetDayNightMinutes
now=pbGetTimeNow # Get the current in-game time
return (now.hour*60)+now.min
end
private
# Internal function
def self.getToneInternal()
# Calculates the tone for the current frame, used for day/night effects
realMinutes=pbGetDayNightMinutes
hour=realMinutes/60
minute=realMinutes%60
tone=PBDayNight::HourlyTones[hour]
nexthourtone=PBDayNight::HourlyTones[(hour+1)%24]
# Calculate current tint according to current and next hour's tint and
# depending on current minute
return Tone.new(
((nexthourtone.red-tone.red)*minute/60.0)+tone.red,
((nexthourtone.green-tone.green)*minute/60.0)+tone.green,
((nexthourtone.blue-tone.blue)*minute/60.0)+tone.blue,
((nexthourtone.gray-tone.gray)*minute/60.0)+tone.gray
)
end
end
def pbDayNightTint(object)
if !$scene.is_a?(Scene_Map)
return
else
if ENABLESHADING && $game_map && pbGetMetadata($game_map.map_id,MetadataOutdoor)
tone=PBDayNight.getTone()
object.tone.set(tone.red,tone.green,tone.blue,tone.gray)
else
object.tone.set(0,0,0,0)
end
end
end
################################################################################
# * Zodiac and day/month checks
################################################################################
# Calculates the phase of the moon.
# 0 - New Moon
# 1 - Waxing Crescent
# 2 - First Quarter
# 3 - Waxing Gibbous
# 4 - Full Moon
# 5 - Waning Gibbous
# 6 - Last Quarter
# 7 - Waning Crescent
def moonphase(time) # in UTC
transitions=[
1.8456618033125,
5.5369854099375,
9.2283090165625,
12.9196326231875,
16.6109562298125,
20.3022798364375,
23.9936034430625,
27.6849270496875]
yy=time.year-((12-time.mon)/10.0).floor
j=(365.25*(4712+yy)).floor + (((time.mon+9)%12)*30.6+0.5).floor + time.day+59
j-=(((yy/100.0)+49).floor*0.75).floor-38 if j>2299160
j+=(((time.hour*60)+time.min*60)+time.sec)/86400.0
v=(j-2451550.1)/29.530588853
v=((v-v.floor)+(v<0 ? 1 : 0))
ag=v*29.53
for i in 0...transitions.length
return i if ag<=transitions[i]
end
return 0
end
#=======================================================================================
# New Birthsigns
#
# If you want to modify the date ranges for each Birthsign:
#-The first number on each line corresponds to the month that Birthsign begins.
#-The second number on each line corresponds to the day of the given month that the Birthsign begins.
#-The third number on each line corresponds to the month that the Birthsign ends.
#-The fourth number on each line corresponds to the day of the given month that the Birthsign ends.
#
#If you change the date ranges for any of the Birthsigns, make sure to reflect these changes in the
#Birthsign Page text in PScreen_Summary
#=======================================================================================
def zodiac(month,day)
time=[
1,1,1,31, # The Apprentice
2,1,2,28, # The Companion
3,1,3,31, # The Beacon
4,1,4,30, # The Savage
5,1,5,31, # The Prodigy
6,1,6,30, # The Martyr
7,1,7,31, # The Maiden
8,1,8,31, # The Gladiator
9,1,9,30, # The Voyager
10,1,10,31, # The Thief
11,1,11,30, # The Glutton
12,1,12,31 # The Wishmaker
]
for i in 0...12
return i if month==time[i*4] && day>=time[i*4+1]
return i if month==time[i*4+2] && day<=time[i*4+2]
end
return 0
end
#=======================================
# Returns the opposite of the given zodiac sign.
# 0 is Aries, 11 is Pisces.
def zodiacOpposite(sign)
return (sign+6)%12
end
# 0 is Aries, 11 is Pisces.
def zodiacPartners(sign)
return [(sign+4)%12,(sign+8)%12]
end
# 0 is Aries, 11 is Pisces.
def zodiacComplements(sign)
return [(sign+1)%12,(sign+11)%12]
end
#===============================================================================
# Birthsigns - Names & Descriptions
#
#If you choose to change the names of 'The Beacon', 'The Martyr', or 'The Voyager', you will also
#need to change the text in PScreen_Party & PScreen_Summary to match your new names.
#
#If you choose to change the names of any of the other Birthsigns, you will need to change the
#text in PScreen_EggHatching & PScreen_Summary to match your new names.
#
#If you choose to change the description text for any of the Birthsigns, your next text may no
#longer fit on the page and may require new positioning in PScreen_Summary, and may
#also need changes to the 'summaryzboarder' graphic.
#===============================================================================
def zodiacValue(sign)
return (sign)%12
end
def pbGetZodiacName(sign)
return [_INTL(""),
_INTL("'The Apprentice'"),
_INTL("'The Companion'"),
_INTL("'The Beacon'"),
_INTL("'The Savage'"),
_INTL("'The Prodigy'"),
_INTL("'The Martyr'"),
_INTL("'The Maiden'"),
_INTL("'The Gladiator'"),
_INTL("'The Voyager'"),
_INTL("'The Thief'"),
_INTL("'The Glutton'"),
_INTL("'The Wishmaker'")][sign]
end
def pbGetZodiacDesc(sign)
return [_INTL(""),
_INTL("The Pokémon is born cured of Pokérus."),
_INTL("The Pokémon is born with max happiness."),
_INTL("The Pokémon can use Flash without the move."),
_INTL("The Pokémon has max IV's in offense & Speed, but 0 HP."),
_INTL("The Pokémon is born with its Hidden Ability."),
_INTL("The Pokémon can use Soft-Boiled without the move."),
_INTL("The Pokémon is always born female, if able."),
_INTL("The Pokémon is born with 100 EV's in Atk & Sp.Atk."),
_INTL("The Pokémon can use Teleport without the move."),
_INTL("The Pokémon is born with max EV's in Speed."),
_INTL("The Pokémon has max IV's in defenses & HP, but 0 Speed."),
_INTL("The Pokémon is always born shiny.")][sign]
end
#===============================================================================
def pbIsWeekday(wdayVariable,*arg)
timenow=pbGetTimeNow
wday=timenow.wday
ret=false
for wd in arg
ret=true if wd==wday
end
if wdayVariable>0
$game_variables[wdayVariable]=[
_INTL("Sunday"),
_INTL("Monday"),
_INTL("Tuesday"),
_INTL("Wednesday"),
_INTL("Thursday"),
_INTL("Friday"),
_INTL("Saturday")
][wday]
$game_map.need_refresh = true if $game_map
end
return ret
end
def pbIsMonth(wdayVariable,*arg)
timenow=pbGetTimeNow
wday=timenow.mon
ret=false
for wd in arg
ret=true if wd==wday
end
if wdayVariable>0
$game_variables[wdayVariable]=[
_INTL("January"),
_INTL("February"),
_INTL("March"),
_INTL("April"),
_INTL("May"),
_INTL("June"),
_INTL("July"),
_INTL("August"),
_INTL("September"),
_INTL("October"),
_INTL("November"),
_INTL("December")
][wday-1]
$game_map.need_refresh = true if $game_map
end
return ret
end
def pbGetAbbrevMonthName(month)
return [_INTL(""),
_INTL("Jan."),
_INTL("Feb."),
_INTL("Mar."),
_INTL("Apr."),
_INTL("May"),
_INTL("Jun."),
_INTL("Jul."),
_INTL("Aug."),
_INTL("Sep."),
_INTL("Oct."),
_INTL("Nov."),
_INTL("Dec.")][month]
end
| true
|
75157d9146bb936bab748524df2fc8ccdf9a3c4e
|
Ruby
|
wied03/ansible-ruby
|
/lib/ansible/ruby/modules/generated/identity/keycloak/keycloak_clienttemplate.rb
|
UTF-8
| 3,248
| 2.515625
| 3
|
[
"BSD-2-Clause"
] |
permissive
|
# frozen_string_literal: true
# See LICENSE.txt at root of repository
# GENERATED FILE - DO NOT EDIT!!
require 'ansible/ruby/modules/base'
module Ansible
module Ruby
module Modules
# This module allows the administration of Keycloak client templates via the Keycloak REST API. It requires access to the REST API via OpenID Connect; the user connecting and the client being used must have the requisite access rights. In a default Keycloak installation, admin-cli and an admin user would work, as would a separate client definition with the scope tailored to your needs and a user having the expected roles.
# The names of module options are snake_cased versions of the camelCase ones found in the Keycloak API and its documentation at U(http://www.keycloak.org/docs-api/3.3/rest-api/)
# The Keycloak API does not always enforce for only sensible settings to be used -- you can set SAML-specific settings on an OpenID Connect client for instance and vice versa. Be careful. If you do not specify a setting, usually a sensible default is chosen.
class Keycloak_clienttemplate < Base
# @return [:present, :absent, nil] State of the client template,On C(present), the client template will be created (or updated if it exists already).,On C(absent), the client template will be removed if it exists
attribute :state
validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>"%{value} needs to be :present, :absent"}, allow_nil: true
# @return [String, nil] Id of client template to be worked on. This is usually a UUID.
attribute :id
validates :id, type: String
# @return [String, nil] Realm this client template is found in.
attribute :realm
validates :realm, type: String
# @return [String, nil] Name of the client template
attribute :name
validates :name, type: String
# @return [Object, nil] Description of the client template in Keycloak
attribute :description
# @return [:"openid-connect", :saml, nil] Type of client template (either C(openid-connect) or C(saml).
attribute :protocol
validates :protocol, expression_inclusion: {:in=>[:"openid-connect", :saml], :message=>"%{value} needs to be :\"openid-connect\", :saml"}, allow_nil: true
# @return [Boolean, nil] Is the "Full Scope Allowed" feature set for this client template or not. This is 'fullScopeAllowed' in the Keycloak REST API.
attribute :full_scope_allowed
validates :full_scope_allowed, expression_inclusion: {:in=>[true, false], :message=>"%{value} needs to be true, false"}, allow_nil: true
# @return [Array<Hash>, Hash, nil] a list of dicts defining protocol mappers for this client template. This is 'protocolMappers' in the Keycloak REST API.
attribute :protocol_mappers
validates :protocol_mappers, type: TypeGeneric.new(Hash)
# @return [Object, nil] A dict of further attributes for this client template. This can contain various configuration settings, though in the default installation of Keycloak as of 3.4, none are documented or known, so this is usually empty.
attribute :attributes
end
end
end
end
| true
|
b6cb7cc4fc0f87173048617a308499c1a318da25
|
Ruby
|
Vizzuality/cw-ndc-tracking
|
/app/models/static/target.rb
|
UTF-8
| 996
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
module Static
class Target
include ActiveModel::Model
include ActiveModel::Serialization
attr_reader :title, :summary, :slug, :order, :indicators
# @param target_config [Hash]
# @option target_config :categories [Array<Hash>]
def initialize(target_config)
@title = target_config[:title]
@summary = target_config[:summary]
@slug = target_config[:slug]
@order = target_config[:order]
@indicators = target_config[:indicators].
map.with_index do |indicator_config, idx|
Static::Indicator.new(
indicator_config.symbolize_keys.merge(order: idx)
)
end
end
def attributes
{'title' => nil, 'summary' => nil, 'slug' => nil}
end
# @param slug [String]
def find_indicator_by_slug(slug)
indicators.find do |indicator|
indicator.slug == slug
end
end
def to_hash
serializable_hash(methods: [:title, :summary, :slug, :order])
end
end
end
| true
|
bd3050ea454b4458b48e484c8feff39f62ec3ed1
|
Ruby
|
jakeheft/whether_sweater
|
/app/services/images_service.rb
|
UTF-8
| 411
| 2.546875
| 3
|
[] |
no_license
|
class ImagesService
def self.fetch_image(location)
conn = Faraday.new('https://api.unsplash.com') do |f|
f.headers['Accept-Version'] = 'v1'
f.headers['Authorization'] = ENV['UNSPLASH_API_KEY']
end
response = conn.get('/search/photos') do |req|
req.params[:query] = "location: #{location}"
end
parsed_json = JSON.parse(response.body, symbolize_names: true)
parsed_json[:results][0]
end
end
| true
|
e1ad867ab8938c58af27fb41f9af3743ea7efeaa
|
Ruby
|
Reinoptland/week-1-codaisseur
|
/day4/dish.rb
|
UTF-8
| 242
| 3.265625
| 3
|
[] |
no_license
|
class Dish
def initialize(dish_name, ingredients, price)
@name = dish_name
@ingredients = ingredients
@price = price
end
def name
@name
end
def ingredients
@ingredients
end
def price
@price
end
end
| true
|
fffa01e43845aae170285602eaa0b15b51f839c0
|
Ruby
|
StefansM/treecode
|
/TreeCode2/examples/3d-plasma-freq/parse_particles.rb
|
UTF-8
| 1,433
| 3.1875
| 3
|
[] |
no_license
|
#!/usr/bin/env ruby
require 'pp'
require 'optparse'
require 'matrix'
class Options
attr_accessor :dimensions, :timestep, :file
def initialize
@dimensions = 3
@timestep = 0
@file = nil
end
def self.parse
return_opts = Options.new
#Parse optional arguments
opts = OptionParser.new do |opts|
opts.banner = "Usage: #{$0} coord_file [OPTIONS]\n\t\"coord_file\" must be a csv file, every column a component of a particle's velocity or position."
opts.on("-t", "--timetsep TIMESTEP", "Timestep at which to use results."){|t|
return_opts.timestep = t.to_i
}
opts.on("-d", "--dimensions DIMS", "Number of dimensions we are working.."){|d|
return_opts.dimensions = d.to_i
}
opts.on_tail("-h", "--help", "This help text."){|h|
puts opts
exit
}
end
opts.parse!(ARGV)
#Now, if we have more than one arg, failboat.
#The remaining arg should be the database file
if ARGV.length != 1
STDERR.puts opts
exit 1
end
return_opts.file = ARGV[0]
return return_opts
end
end
def get_coords(opts)
coords = []
File.open(opts.file, "r") do |f|
opts.timestep.times {f.readline}
cols = f.readline.split("\t")
coord = []
cols.each_with_index{|c,i|
coord << c.to_f
if (i+1) % opts.dimensions == 0
v = Vector.elements(coord)
if block_given?
coords << v if yield(v)
else
coords << v
end
coord = []
end
}
end
return coords
end
| true
|
8b7a21de1a167cea2044509cc6b93cdf99ffbfeb
|
Ruby
|
nicmlu/cartoon-collections-online-web-pt-100719
|
/cartoon_collections.rb
|
UTF-8
| 1,038
| 3.734375
| 4
|
[
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
def roll_call_dwarves(dwarf_names)
# print each name and index using puts
dwarf_names.each.with_index(1) do |name, index|
puts "#{index} #{name}"
end
end
def summon_captain_planet(planeteer_calls)
planeteer_calls.map do |call|
call.capitalize!
"#{call}!"
end
end
def long_planeteer_calls(long_calls)
# evaluate whether any are longer than 4 characters
# return true or false
long_calls.any? {|call| call.length > 4}
end
# def find_the_cheese(arr)
# # look through each string
# # return the first string that is a cheese with detect or find
# # the array below is here to help
# cheese_types = ["cheddar", "gouda", "camembert"]
# if cheese_types.all? do |element| arr.include?(element)
# return element
# end
# end
# end
def find_the_cheese(arr)
# look through each string
# return the first string that is a cheese with include?
# the array below is here to help
cheese_types = ["cheddar", "gouda", "camembert"]
arr.find do |type|
cheese_types.include?(type)
end
end
| true
|
293453bbc189228a1d4f3134398d34cf2c0d8b77
|
Ruby
|
wolframkriesing/tic-tac-toe
|
/specs/winner_spec.rb
|
UTF-8
| 2,653
| 3.25
| 3
|
[] |
no_license
|
require_relative "boards"
require_relative "_helper"
require_relative "_input_double"
require_relative "../lib/player"
require "minitest/autorun"
class NoWinner < MiniTest::Unit::TestCase
def test_empty_board_has_no_winner
assert_equal Boards.empty_board.find_winner, nil
end
# rows
def test_top_row_won_by_player1
assert_equal Boards.top_row_won_by_player1.find_winner, Boards.player1
end
def test_middle_row_won_by_player1
assert_equal Boards.middle_row_won_by_player1.find_winner, Boards.player1
end
def test_bottom_row_won_by_player1
assert_equal Boards.bottom_row_won_by_player1.find_winner, Boards.player1
end
# columns
def test_left_column_won
winner = Boards.left_column_won_by(Boards.player1).find_winner
assert_equal winner, Boards.player1
end
def test_middle_column_won
winner = Boards.middle_column_won_by(Boards.player1).find_winner
assert_equal winner, Boards.player1
end
def test_right_column_won
winner = Boards.right_column_won_by(Boards.player1).find_winner
assert_equal winner, Boards.player1
end
# diagonals
def test_diagonal_from_right_top_won_by_player2
winner = Boards.diagonal_from_right_top_won_by_player2.find_winner
assert_equal winner, Boards.player2
end
def test_diagonal_from_left_top_won_by_player1
winner = Boards.diagonal_from_left_top_won_by_player1.find_winner
assert_equal winner, Boards.player1
end
end
class BoardWithTwoRows < MiniTest::Unit::TestCase
def play(player1, player2)
TestHelper.winner_for_board(Board.new(2), player1, player2)
end
def test_first_player_wins_with_filled_row
player1 = HumanPlayer.new("1", MyInput.new("12"))
player2 = HumanPlayer.new("2", MyInput.new("3"))
assert_equal play(player1, player2), player1
end
def test_first_player_wins_with_filled_column
player1 = HumanPlayer.new("1", MyInput.new("13"))
player2 = HumanPlayer.new("2", MyInput.new("2"))
assert_equal play(player1, player2), player1
end
def test_first_player_wins_with_filled_diagonal
player1 = HumanPlayer.new("1", MyInput.new("14"))
player2 = HumanPlayer.new("2", MyInput.new("2"))
assert_equal play(player1, player2), player1
end
end
class BoardWithFourRows < MiniTest::Unit::TestCase
def play(player1, player2)
TestHelper.winner_for_board(Board.new(4), player1, player2)
end
def test_diagonal_wins
player1 = HumanPlayer.new("1", MyInput.new(["1", "6", "11", "16"]))
player2 = HumanPlayer.new("2", MyInput.new("234"))
assert_equal play(player1, player2), player1
end
end
| true
|
59e31994a04136c3061af84df7f73590fbb8c2c3
|
Ruby
|
DPNT-Sourcecode/CHK-kxrb01
|
/lib/solutions/CHK/checkout.rb
|
UTF-8
| 6,165
| 3.140625
| 3
|
[
"Apache-2.0"
] |
permissive
|
# noinspection RubyUnusedLocalVariable
class Checkout
ITEMS = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' ]
PRICES = [{item: 'A', count: 1, price: 50}, {item: 'B', count: 1, price: 30},
{item: 'C', count: 1, price: 20}, {item: 'D', count: 1, price: 15},
{item: 'E', count: 1, price: 40}, {item: 'F', count: 1, price: 10},
{item: 'G', count: 1, price: 20}, {item: 'H', count: 1, price: 10},
{item: 'I', count: 1, price: 35}, {item: 'J', count: 1, price: 60},
{item: 'K', count: 1, price: 70}, {item: 'L', count: 1, price: 90},
{item: 'M', count: 1, price: 15}, {item: 'N', count: 1, price: 40},
{item: 'O', count: 1, price: 10}, {item: 'P', count: 1, price: 50},
{item: 'Q', count: 1, price: 30}, {item: 'R', count: 1, price: 50},
{item: 'S', count: 1, price: 20}, {item: 'T', count: 1, price: 20},
{item: 'U', count: 1, price: 40}, {item: 'V', count: 1, price: 50},
{item: 'W', count: 1, price: 20}, {item: 'X', count: 1, price: 17},
{item: 'Y', count: 1, price: 20}, {item: 'Z', count: 1, price: 21},
]
MULTIBUY_OFFERS = [{item: 'A', count: 3, offer_price: 130},
{item: 'B', count: 2, offer_price: 45},
{item: 'A', count: 5, offer_price: 200},
{item: 'F', count: 3, offer_price: 20},
{item: 'H', count: 5, offer_price: 45},
{item: 'H', count: 10, offer_price: 80},
{item: 'K', count: 2, offer_price: 120},
{item: 'P', count: 5, offer_price: 200},
{item: 'Q', count: 3, offer_price: 80},
{item: 'U', count: 4, offer_price: 120},
{item: 'V', count: 2, offer_price: 90},
{item: 'V', count: 3, offer_price: 130}
]
COMBO_OFFERS = [{item: 'E', count: 2, free_item: 'B'},
{item: 'N', count: 3, free_item: 'M'},
{item: 'R', count: 3, free_item: 'Q'}
]
GROUP_DISCOUNT_OFFER = {items: ['S', 'T', 'X', 'Y', 'Z'], count: 3, offer_price: 45}
def checkout(skus)
@skus = skus
@total_price = 0
skus.split("").uniq.each do |item|
return -1 if !ITEMS.include? item
end
structure_basket()
apply_group_discounts()
apply_combo_offers()
apply_multibuy_offers()
apply_normal_price()
return @total_price
end
def structure_basket
@basket = []
sku_array = @skus.split("")
sku_array.uniq.each do |item|
basket_item = {:item => item, :count => sku_array.count(item)}
@basket << basket_item
end
end
def apply_multibuy_offers
@basket.each do |basket_item|
MULTIBUY_OFFERS.sort_by{|an_offer| an_offer[:count]}.reverse.each do |offer|
if offer[:item] == basket_item[:item]
number_of_offers = 0
if basket_item[:count] >= offer[:count]
number_of_offers = basket_item[:count] / offer[:count]
@total_price += (offer[:offer_price] * number_of_offers)
basket_item[:count] -= (offer[:count] * number_of_offers)
end
end
end
end
end
def apply_normal_price
@basket.each do |basket_item|
PRICES.each do |item_detail|
if item_detail[:item] == basket_item[:item]
@total_price += (item_detail[:price] * basket_item[:count])
end
end
end
end
def apply_combo_offers
@basket.each do |basket_item|
COMBO_OFFERS.each do |item_detail|
if item_detail[:item] == basket_item[:item]
number_of_possible_combo_offers = 0
if basket_item[:count] >= item_detail[:count]
number_of_possible_combo_offers = basket_item[:count] / item_detail[:count]
free_item = @basket.select {|element| element[:item] == item_detail[:free_item]}.first
if free_item != nil
#reduce the quantity of the free item in the basket
if free_item[:count] >= number_of_possible_combo_offers
free_item[:count] -= number_of_possible_combo_offers
elsif free_item[:count] > 0
free_item[:count] = 0
end
end
end
end
end
end
end
def apply_group_discounts
number_of_group_discount_items = 0
discount_basket_items = []
@basket.each do |basket_item|
if GROUP_DISCOUNT_OFFER[:items].include? basket_item[:item]
number_of_group_discount_items += basket_item[:count]
basket_item_price = 0
PRICES.each do |item_detail|
if item_detail[:item] == basket_item[:item]
basket_item_price = item_detail[:price]
end
end
discount_basket_items << {item: basket_item[:item],
count: basket_item[:count], price: basket_item_price}
end
end
if number_of_group_discount_items >= GROUP_DISCOUNT_OFFER[:count]
number_of_group_discount_offers = number_of_group_discount_items / GROUP_DISCOUNT_OFFER[:count]
@total_price += (GROUP_DISCOUNT_OFFER[:offer_price] * number_of_group_discount_offers)
total_qty_to_reduce = number_of_group_discount_offers * GROUP_DISCOUNT_OFFER[:count]
sorted_discount_basket_items = discount_basket_items.sort_by{|a_discount_item| a_discount_item[:price]}.reverse
sorted_discount_basket_items.each do |sorted_basket_item|
if total_qty_to_reduce > 0
if sorted_basket_item[:count] >= total_qty_to_reduce
sorted_basket_item[:count] -= total_qty_to_reduce
total_qty_to_reduce = 0
else
total_qty_to_reduce -= sorted_basket_item[:count]
sorted_basket_item[:count] = 0
end
end
end
sorted_discount_basket_items.each do |discount_item|
@basket.select{|element| element[:item] == discount_item[:item]}.first[:count] = discount_item[:count]
end
end
end
end
| true
|
313203a80649de920e3acaa550629d02f9ace559
|
Ruby
|
urbanadventurer/huginn
|
/app/models/agents/adioso_agent.rb
|
UTF-8
| 2,445
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
module Agents
class AdiosoAgent < Agent
cannot_receive_events!
default_schedule "every_1d"
description <<-MD
The Adioso Agent will tell you the minimum airline prices between a pair of cities, and within a certain period of time.
The currency is USD. Please make sure that the difference between `start_date` and `end_date` is less than 150 days. You will need to contact [Adioso](http://adioso.com/)
for a `username` and `password`.
MD
event_description <<-MD
If flights are present then events look like:
{
"cost": 75.23,
"date": "June 25, 2013",
"route": "New York to Chicago"
}
otherwise
{
"nonetodest": "No flights found to the specified destination"
}
MD
def default_options
{
'start_date' => Date.today.httpdate[0..15],
'end_date' => Date.today.plus_with_duration(100).httpdate[0..15],
'from' => "New York",
'to' => "Chicago",
'username' => "xx",
'password' => "xx",
'expected_update_period_in_days' => "1"
}
end
def working?
event_created_within?(options['expected_update_period_in_days']) && !recent_error_logs?
end
def validate_options
unless %w[start_date end_date from to username password expected_update_period_in_days].all? { |field| options[field].present? }
errors.add(:base, "All fields are required")
end
end
def date_to_unix_epoch(date)
date.to_time.to_i
end
def check
auth_options = {:basic_auth => {:username =>interpolated[:username], :password=>interpolated['password']}}
parse_response = HTTParty.get "http://api.adioso.com/v2/search/parse?q=#{URI.encode(interpolated['from'])}+to+#{URI.encode(interpolated['to'])}", auth_options
fare_request = parse_response["search_url"].gsub /(end=)(\d*)([^\d]*)(\d*)/, "\\1#{date_to_unix_epoch(interpolated['end_date'])}\\3#{date_to_unix_epoch(interpolated['start_date'])}"
fare = HTTParty.get fare_request, auth_options
if fare["warnings"]
create_event :payload => fare["warnings"]
else
event = fare["results"].min {|a,b| a["cost"] <=> b["cost"]}
event["date"] = Time.at(event["date"]).to_date.httpdate[0..15]
event["route"] = "#{interpolated['from']} to #{interpolated['to']}"
create_event :payload => event
end
end
end
end
| true
|
64a1cbb598a1196040cea94e6ef222a62d095039
|
Ruby
|
picatz/command_lion
|
/lib/command_lion/app.rb
|
UTF-8
| 10,552
| 2.921875
| 3
|
[
"MIT"
] |
permissive
|
module CommandLion
class App < Base
def self.default_help(app)
flagz = []
app.commands.each do |_, cmd|
if cmd.options?
cmd.options.each do |_, opt|
if opt.flags?
if opt.flags.long?
flagz << opt.flags.short + opt.flags.long
else
flagz << opt.flags.short
end
elsif opt.index?
flagz << opt.index.to_s if opt.index?
end
end
end
if cmd.flags?
if cmd.flags.long?
flagz << cmd.flags.short + cmd.flags.long
else
flagz << cmd.flags.short
end
elsif cmd.index?
flagz << cmd.index.to_s if cmd.index?
else
raise "No flags or index was given!"
end
end
max_flag = flagz.map(&:length).max + 4
max_desc = app.commands.values.map(&:description).select{|d| d unless d.nil? }.map(&:length).max
puts app.name
if app.version?
puts
puts "VERSION"
puts app.version
puts unless app.description?
end
if app.description?
puts
puts "DESCRIPTION"
puts app.description
puts
end
if app.usage?
puts
puts "USAGE"
puts usage
puts
end
puts unless app.version? || app.description? || app.usage?
puts "COMMANDS"
app.commands.values.select { |cmd| cmd unless cmd.is_a? CommandLion::Option }.each do |command|
if command.flags?
short = command.flags.long? ? command.flags.short + ", " : command.flags.short
short_long = "#{short}#{command.flags.long}".ljust(max_flag)
else
short_long = "#{command.index.to_s}".ljust(max_flag)
end
puts "#{short_long} #{command.description}"
if command.options?
command.options.each do |_, option|
if option.flags?
short = option.flags.long? ? option.flags.short + ", " : option.flags.short
short_long = " " + "#{short}#{option.flags.long}".ljust(max_flag - 2)
else
short_long = " " + "#{option.index.to_s}".ljust(max_flag - 2)
end
puts "#{short_long} #{option.description}"
end
end
puts
end
end
# The run method will run a given block of code using the
# Commmand Lion DSL.
def self.run(&block)
# Initialize an instance of an App object.
app = new
# Evaluate the block of code within the context of that App object.
app.instance_eval(&block)
# Parse the application logic out.
app.parse
# Sometimes a command-line application is run without being given any arguments.
if ARGV.empty?
# Default to a help menu.
if cmd = app.commands[:help]
cmd.before.call if cmd.before?
cmd.action.call if cmd.action?
cmd.after.call if cmd.after?
exit 0
else
# Use the default help menu for the application unless that's been
# explictly removed by the author for whatever reason.
default_help(app) unless app.default_help_menu_removed?
end
else
app.commands.each do |_, cmd|
next unless cmd.given?
cmd.options.each do |_, opt|
next unless opt.given?
opt.before.call if opt.before?
opt.action.call if opt.action?
opt.after.call if opt.after?
end if cmd.options?
cmd.before.call if cmd.before?
cmd.action.call if cmd.action?
cmd.after.call if cmd.after?
end
end
end
# Check if there has been an indexed help command.
def help?
return true if @commands[:help]
false
end
# Explicitly remove the default help menu from the application.
def remove_default_help_menu
@remove_default_help_menu = true
end
# Check if the default help menu for the application has been explicitly removed.
def default_help_menu_removed?
@remove_default_help_menu || false
end
# Simple attributes for the application. Mostly just metadata to help
# provide some context to the application.
#
# * `name` is the name people would refernce your application to in conversation.
# * `usage` is a simple, optional custom string to provide further context for the app.
# * `description` allows you to describe what your application does and why it exists.
# * `version` allows you to do simple version control for your app.
simple_attrs :name, :usage, :description, :version, :help
# An application usually has multiple commands.
#
# == Example
# app = CommandLion::App.build
# # meta information
#
# command :example1 do
# # more code
# end
#
# command :example2 do
# # more code
# end
# end
#
# app.commands.map(&:name)
# # => [:example1, :example2]
def command(index, &block)
if index.is_a? Command
cmd = index
else
cmd = Command.new
cmd.index= index
cmd.instance_eval(&block)
end
@commands = {} unless @commands
@flags = [] unless @flags
if cmd.flags?
@flags << cmd.flags.short if cmd.flags.short?
@flags << cmd.flags.long if cmd.flags.long?
elsif cmd.index # just use index
@flags << cmd.index.to_s
else
raise "No index or flags were given to use this command."
end
if cmd.options?
cmd.options.each do |_, option|
if option.flags?
@flags << option.flags.short if option.flags.short?
@flags << option.flags.long if option.flags.long?
else # just use index
@flags << option.index.to_s
end
@commands[option.index] = option
end
end
@commands[cmd.index] = cmd
cmd
end
def ctrl_c(&block)
trap("SIGINT") { block.call }
end
def help(&block)
command :help, &block
end
# Plugin a command that's probably been built outside of the application's run or build block.
# This is helpful for sharing or reusing commands in applications.
# @param command [Command]
def plugin(command)
command(command)
end
# Direct access to the various flags an application has. Helpfulp for debugging.
def flags
@flags
end
# Direct access to the various commands an application has. Helpful for debugging.
def commands
@commands.reject { |_, v| v.is_a? CommandLion::Option }
end
# Parse arguments off of ARGV.
#
# @TODO Re-visit this.
def parse
@commands.each do |_, cmd|
if cmd.flags?
# or for the || seems to not do what I want it to do...
next unless argv_index = ARGV.index(cmd.flags.short) || ARGV.index(cmd.flags.long)
else
next unless argv_index = ARGV.index(cmd.index.to_s)
end
cmd.given = true unless argv_index.nil?
if cmd.type.nil?
yield cmd if block_given?
else
if parsed = parse_cmd(cmd, flags)
cmd.arguments = parsed || cmd.default
yield cmd if block_given?
elsif cmd.default
cmd.arguments = cmd.default
yield cmd if block_given?
end
end
end
end
# Parse a given command with its given flags.
# @TODO Re-visit this.
def parse_cmd(cmd, flags)
if cmd.flags?
args = Raw.arguments_to(cmd.flags.short, flags)
if args.nil? || args.empty?
args = Raw.arguments_to(cmd.flags.long, flags)
end
else
args = Raw.arguments_to(cmd.index.to_s, flags)
end
unless cmd.type.to_s =~ /stdin/
return nil if args.nil?
end
case cmd.type
when :stdin
args = STDIN.gets.strip
when :stdin_stream
args = STDIN
when :stdin_string
args = STDIN.gets.strip
when :stdin_strings
args = []
while arg = STDIN.gets
next if arg.nil?
arg = arg.strip
args << arg
end
args
when :stdin_integer
args = STDIN.gets.strip.to_i
when :stdin_integers
args = []
while arg = STDIN.gets
next if arg.nil?
arg = arg.strip
parse = arg.to_i
if parse.to_s == arg
args << parse
end
end
args
when :stdin_bool
args = STDIN.gets.strip.downcase == "true"
when :single, :string
args = args.first
when :strings, :multi
if cmd.delimiter?
if args.count > 1
args = args.first.split(cmd.delimiter)
else
args = args.map { |arg| arg.split(cmd.delimiter) }.flatten
end
end
args
when :integer
args = args.first.to_i
when :integers
if cmd.delimiter?
if args.count > 1
args = args.join
args = args.select { |arg| arg if arg.include?(cmd.delimiter) }
args = args.map { |arg| arg.split(cmd.delimiter) }.flatten
else
args = args.map { |arg| arg.split(cmd.delimiter) }.flatten
end
end
args = args.map(&:to_i)
when :bool, :bools
if cmd.delimiter?
if args.count > 1
args = args.join
args = args.select { |arg| arg if arg.include?(cmd.delimiter) }
args = args.map { |arg| arg.split(cmd.delimiter) }.flatten
else
args = args.map { |arg| arg.split(cmd.delimiter) }.flatten
end
end
args = args.map { |arg| arg == "true" }
end
rescue => e# this is dangerous
puts e
nil
end
def run!
parse do |cmd|
next unless cmd.given?
cmd.options.each do |_, opt|
next unless opt.given?
opt.before.call if opt.before?
opt.action.call if opt.action?
opt.after.call if opt.after?
end if cmd.options?
cmd.before.call if cmd.before?
cmd.action.call if cmd.action?
cmd.after.call if cmd.after?
end
end
# Run the application if the file is the main file being run.
# It's almost kind of narcisitc, if you think about it.
if __FILE__== $0
run!
end
end
end
| true
|
d8c1410d1227853bd681cc169c88de522fb26cfa
|
Ruby
|
tokihiro000/AhoCorasick
|
/strutil.rb
|
UTF-8
| 1,358
| 3.390625
| 3
|
[] |
no_license
|
require 'set'
def GetExistStr count, file_name
search_str_list = []
File.open(file_name) do |file|
file.each_line do |str|
str.chomp!
search_str_list << str
if search_str_list.length >= count
break
end
end
end
return search_str_list
end
def GetRandomStr count, str_length
str_map = {}
short_length = str_length / 2
more_short_length = str_length / 3
while str_map.length < count
str = (0...str_length).map{ ('A'..'Z').to_a[rand(26)] }.join
str_map[str] = 0
tmp_str_list1 = str.scan(/.{1,#{more_short_length}}/)
tmp_str_list1.each do |tmp_str|
str_map[tmp_str] = 0
end
tmp_str_list2 = str.scan(/.{1,#{short_length}}/)
tmp_str_list2.each do |tmp_str|
str_map[tmp_str] = 0
end
end
str_list = str_map.keys
(str_list.length - count).times do |i|
str_list.shift
end
return str_list
end
def GetStrSet const_str
str = const_str.dup
set = Set.new
length = str.length - 1
while str.length > 0
length = str.length
length.times do |i|
str.scan(/.{1,#{i + 1}}/).each do |s|
set.add s
end
end
str[0] = ''
end
return set
end
if $0 == __FILE__
set = GetStrSet "abcdefghijklmn"
list = set.to_a
list.sort!
list.each do |str|
puts str
end
str_list = GetRandomStr 100, 12
p str_list
end
| true
|
9cc9ec58496e547264b931052042cef5b4126093
|
Ruby
|
jthoenes/ips
|
/ips/src/main/ruby/lib/ext/assert_ext.rb
|
UTF-8
| 1,235
| 3.421875
| 3
|
[
"Apache-2.0"
] |
permissive
|
#
# Exension of the ruby base class +Object+ for enabling checking for assertions.
#
class Object
# Basic assertion expecting the block passed to yield +true+, otherwise
# an assertion error is raised.
def assert
unless yield
# Cleaning the stack-trace from all assert methods, so it appears
# the exception was directly raised by the assert statement (like in java)
stack_trace = caller.reject{|c| c =~ /__FILE__/}
raise StandardError, "Assertion failed!", stack_trace
end
end
#
# Check that all arguments are probabilites i.e. the are numbers between 0.0
# and 1.0
def assert_probability *args
assert_floatable(*args)
args.each do |var|
assert do
var >= 0.0 &&
var <= 1.0
end
end
end
# Checks that all arguments are float or can be converted to a float.
def assert_floatable *args
args.each do |var|
assert do
var.not_nil? && var.is_a?(Numeric)
end
end
end
# Checks that all arguments are symbols.
def assert_symbol *args
args.each{|a| assert{a.is_a?(Symbol)}}
end
# Checks that all arguments are a Proc object or +nil+.
def assert_proc_or_nil *args
args.each{|a| assert{a.nil? || a.is_a?(Proc)}}
end
end
| true
|
9ec0f438df5a236615cdb96a87b27726931f3ae0
|
Ruby
|
hopsoft/model_definition_tester
|
/lib/model_definition_tester.rb
|
UTF-8
| 9,187
| 3.046875
| 3
|
[
"MIT"
] |
permissive
|
class Test::Unit::TestCase
IGNORE_PATTERN = /^(id|created_at|created_on|updated_at|updated_on|created_by|updated_by)$/i
# This method provides a powerful yet simple way to test model definitions. It
# verifies that the expected columns are supported, and that certain column
# properties are enforced... such as validations.
#
# There are 2 steps to using this method effectively.
#
# 1. Create the column meta data that will drive the test. _This is
# accomplished by creating a constant by the name of Columns in your test
# class like so:_
#
# <code>
# Columns = {
# :my_column => {:required => true, :default => "some value" :valid => ["value a", "123"], :invalid => ["a", "12"] },
# :another_column => :def_only
# }
# </code>
#
# Each value should be a symbol of :def_only or a Hash.
# The column name should be used as the main key for the outer Hash.
# If the value is a Hash, the Hash should contain all the column's meta information to be tested.
# If the value is :def_only, we only verify that the model has defined the column... nothing else.
#
# The supported keys are:
# * required - Boolean
# * default - The expected default value.
# * valid - An Array of valid values.
# * invalid - An Array of invalid values.
#
# 2. Create a test that invokes this method like so: <code> def
# test_my_model_definition run_model_tests(MyModel.new, Columns) end </code>
#
# A complete sample test case would look like something like this:
#
# <code>
# class MyModelTest < ActiveSupport::TestCase
# Columns = {
# :my_column => {:required => true, :default => "some value" :valid => ["value a", "123"], :invalid => ["a", "12"] }
# }
#
# def test_my_model_definition
# run_model_tests(MyModel.new, Columns)
# end
# end
# </code>
def run_model_tests(obj, columns)
class_name = obj.class.name
tested_column_names = []
columns.each do |name, value|
tested_column_names << name.to_s
assert obj.respond_to?(name.to_sym), "The #{class_name} model doesn't support the '#{name}' field"
next if value == :def_only
# verify default values
val = eval "obj.#{name}"
if value[:default].blank?
assert val.blank?, "#{class_name}.#{name} has a value when it should be 'blank'" unless value[:default].blank?
else
assert_not_nil val, "The #{class_name}.#{name} field doesn't have a default value"
assert_equal val, value[:default], "Invalid default value for #{class_name}.#{name}"
end
# verify required values
if value[:required]
eval "obj.#{name} = nil"
obj.valid?
expected_error_exists = get_columns_with_errors(obj).include?(name)
unless expected_error_exists
n = name.to_s
expected_error_exists = get_columns_with_errors(obj).include?(n[0..-4].to_sym) if n =~ /_id$/i
end
assert expected_error_exists,
"#{class_name}.#{name} is required but passed validations with a nil value"
end
# verify valid values
if value[:valid]
value[:valid].each do |val|
# verify that assignment works as expected
eval "obj.#{name} = val"
actual = eval "obj.#{name}"
print_val = val.nil? ? "nil" : val.to_s
print_actual = actual.nil? ? "nil" : actual.to_s
assert_equal val, actual,
"#{class_name}.#{name} field value assignment is incorrect!\nexpected: #{print_val}\nactual: #{print_actual}"
# verify that no errors exist after assignment
obj.valid?
assert_equal false, get_columns_with_errors(obj).include?(name),
"#{class_name} ##{obj.id} '#{name}' field has errors when it shouldn't! assigned value: #{print_val}\n#{obj.errors[name]}"
end
end
# verify invalid values
if value[:invalid]
value[:invalid].each do |val|
if val.is_a?(Array)
msg = val[1]
val = val[0]
end
print_val = val.nil? ? "nil" : val.to_s
# verify the field has errors after assignment
eval "obj.#{name} = val"
obj.valid?
assert get_columns_with_errors(obj).include?(name),
"#{class_name}.#{name} field should have errors! assigned value: #{print_val}"
# test the error message
if msg
m = "The expected error message for #{class_name}.#{name} is not present"
assert_not_nil obj.errors[name], m
assert obj.errors[name].include?(msg), m
end
end
end
end
# verify that the model does not define columns that haven't been tested
obj.class.columns.each do |column|
name = column.name
next if name.to_s =~ IGNORE_PATTERN
assert tested_column_names.include?(name), "The #{class_name} is missing a model test for the '#{name}' column"
end
end
# This method provides a powerful yet simple way to test model relationships,
# simply pass a model instance and the relationship meta data that should be tested.
#
# The relationship meta data looks like this:
# Relations = {
# :belongs_to => [:software]
# }
#
# This method will also test to ensure that the model doesn't define any
# relationships not tested. You can turn this off by passing false for "fail_untested".
#
# Note: we may need to add more options for non-standard relationships.
def run_relationship_tests(obj, relations, fail_untested=true)
klass = obj.class
tested_relationships = []
relations.each do |macro, names|
next if macro == :suppress_loopback
names = [names] unless names.is_a?(Array)
names.each do |name|
tested_relationships << name
reflection = klass.reflections[name]
# test definitions
msg = "#{klass.name} is missing the #{macro} relationship to #{name}"
assert_not_nil reflection, msg
assert reflection.macro == macro, msg
# check foreign key existence
if macro == :belongs_to
# verify the foreign key has been setup as an attribute on the model
fk_name = reflection.options[:foreign_key] || reflection.association_foreign_key
assert obj.respond_to?(fk_name),
"#{klass.name} is missing the '#{fk_name}' field which maps to #{name}"
# verify the parent table maps back to me
parent_klass = eval reflection.class_name
parent_reflection_tables = []
parent_klass.reflections.each {|k,v| parent_reflection_tables << v.table_name }
assert parent_reflection_tables.include?(klass.table_name),
"#{parent_klass.name} is missing a relationship that points to #{klass.table_name}"
end
if relations[:suppress_loopback].nil? || !(relations[:suppress_loopback].include?(name))
# test child relations back to me
# testing here and not recursively so a single test doesn't spawn a system wide check
if macro == :has_many || macro == :has_one
child_attr_name = klass.table_name.downcase.singularize.to_sym
child_klass = eval(reflection.options[:class_name] || reflection.table_name.classify)
child_reflection = child_klass.reflections[child_attr_name]
# test relationship definitions back to me
msg = "#{child_klass.name} is missing the belongs_to relationship to #{child_attr_name}"
assert_not_nil child_reflection, msg
assert child_reflection.macro == :belongs_to, msg
# test child foreign key field that maps back to me
child_obj = child_klass.new
assert child_obj.respond_to?(reflection.primary_key_name),
"#{child_klass.name} is missing the '#{reflection.primary_key_name}' field which maps to #{child_attr_name}"
elsif macro == :has_and_belongs_to_many
# test that my child also has me as child
child_attr_name = klass.table_name.downcase.to_sym
child_klass = eval(reflection.options[:class_name] || reflection.table_name.classify)
child_reflection = child_klass.reflections[child_attr_name]
# test relationship definitions back to me
msg = "#{child_klass.name} is missing the has_and_belongs_to_many relationship to #{child_attr_name}"
assert_not_nil child_reflection, msg
assert child_reflection.macro == :has_and_belongs_to_many, msg
end
end
end
end
# verify that the model does not define relationships that haven't been tested
if fail_untested
klass.reflections.each do |name, value|
assert tested_relationships.include?(name),
"#{klass.name} is missing a relationship test for: #{value.macro} #{name}"
end
end
end
private
# Returns an array of symbols.
# one symbol (column name) for each column that contains errors.
def get_columns_with_errors(model_instance)
list = model_instance.errors.map {|e| e[0].to_sym}
end
end
| true
|
11ad8973125138f131a1184cbc02cc052824c4c3
|
Ruby
|
theod07/project-euler
|
/problem_2.rb
|
UTF-8
| 776
| 4.34375
| 4
|
[] |
no_license
|
# Project Euler
# Problem 2 - Even Fibonacci numbers
# Each new term in the Fibonacci sequence is generated
# by adding the previous two terms. By starting with 1
# and 2, the first 10 terms will be:
# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
# By considering the terms in the Fibonacci sequence
# whose values do not exceed four million, find the sum
# of the even-valued terms.
fibonacci = [1,2,3,5,8,13,21,34,55,89]
while fibonacci[-1] <= 4000000
fibonacci << fibonacci[-1] + fibonacci[-2]
end
puts "fibonacci.length : #{fibonacci.length}"
even_fibonacci = []
for num in fibonacci
if num % 2 == 0
even_fibonacci << num
end
end
puts "even_fibonacci : #{even_fibonacci}"
even_sum = even_fibonacci.inject(0) {|sum, num| sum + num}
puts "even_sum : #{even_sum}"
| true
|
95a563306826fc746a1ab9fdc84032618f035ebd
|
Ruby
|
leonimanuel/js-rails-as-api-pokemon-teams-project-online-web-sp-000
|
/pokemon-teams-backend/app/services/pokemon_serializer.rb
|
UTF-8
| 207
| 2.546875
| 3
|
[
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
class PokemonSerializer
def initialize(pokemon_object)
@pokemon = pokemon_object
end
def to_serialized_json
options = {
except: [:updated_at, :created_at]
}
@pokemon.to_json(options)
end
end
| true
|
4a32ad5495c1255f5cbce1f227864240144a3c90
|
Ruby
|
mib32/tennis-rails
|
/app/models/wallet.rb
|
UTF-8
| 960
| 2.703125
| 3
|
[] |
no_license
|
class Wallet < ActiveRecord::Base
belongs_to :user
has_many :deposits, dependent: :destroy
has_many :deposit_requests, dependent: :destroy
has_many :withdrawals, dependent: :destroy
has_many :withdrawal_requests, dependent: :destroy
def deposit_with_tax_deduction! amount
deposit! amount - tax_for(amount)
deduct_tax(amount)
end
def deposit! amount
deposits.create! amount: amount
end
def withdraw! amount
if can_spend? amount
withdrawals.create! amount: amount
else
raise "Недостаточно средств"
end
end
def total
deposits.sum(:amount) - withdrawals.sum(:amount) + deposit_requests.success.sum(:amount) - withdrawal_requests.success.sum(:amount)
end
def can_spend? amount
total - amount >= 0
end
def tax_for(amount)
amount.to_f * Option.current.tax / 100
end
private
def deduct_tax(amount)
AdminWallet.find.deposit! tax_for(amount)
end
end
| true
|
75d2d678c22f68e64851029fe1794f05b4964fa3
|
Ruby
|
queer1/imsg
|
/lib/imsg.rb
|
UTF-8
| 2,188
| 3.359375
| 3
|
[
"MIT"
] |
permissive
|
#!/usr/bin/env ruby
require "imsg/version"
require 'appscript'
module ImsgHandler
CHAT_DISPLAY_LIMIT = 12
class Chat
attr_accessor :chat_number, :updated, :participants
def initialize(chat_number, updated, participants)
self.chat_number = chat_number
self.updated = updated
self.participants = participants
end
def to_s
"#{chat_number} - #{participants.map(&:name).join(", ")}"
end
def self.fetch_all
ascript_chats.map.with_index(1){ |chat, i| from_ascript_chat(chat, i) }
end
def self.ascript_chats
Appscript.app("Messages").chats.get()
end
def self.from_ascript_chat(chat, chat_number)
new(chat_number, chat.updated.get(), participants_from_ascript_chat(chat))
end
def self.participants_from_ascript_chat(chat)
chat.participants.get().map do |participant|
Participant.from_ascript_participant(participant)
end
end
end
class Participant
attr_accessor :name
def initialize(name)
self.name = name
end
def self.from_ascript_participant(ascript_participant)
self.new(ascript_participant.name.get())
end
end
def self.display_chats(chats)
sort_by_updated(chats).first(CHAT_DISPLAY_LIMIT).map(&:to_s).join("\n")
end
def self.sort_by_updated(chats)
chats.sort{ |a, b| b.updated <=> a.updated }
end
# Check if a String is a integer number
def self.is_i str
!!(str =~ /^[-+]?[0-9]+$/)
end
# Calls Applescript in order to trigger an iMessage message to a buddy
# The buddy parameter accepts a String with either a chat number or a Buddy name
def self.sendMessage message, buddy
if is_i buddy
puts "Sending \'#{message}\' to chat number #{buddy}"
`osascript -e 'tell application "Messages" to send \"#{message}\" to item #{buddy.to_i} of text chats'`
else
puts "Sending \'#{message}\' to buddy \'#{buddy}\'"
`osascript -e 'tell application "Messages" to send \"#{message}\" to buddy \"#{buddy}\"'`
end
end
# Shows the chat list along with their participants
def self.showChatList
chats = Chat.fetch_all
puts "\nWho would you like to send your message to?"
puts "(You can choose a number or type a buddy name/email)\n\n"
puts display_chats(chats)
end
end
| true
|
df1ca8ff97ad6a90006a919ea3e3e73dd1f9397f
|
Ruby
|
ilocp/incident-locator
|
/app/behaviours/format_coordinates.rb
|
UTF-8
| 266
| 2.671875
| 3
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
#
# Defines common location callbacks for models
#
module FormatCoordinates
def round_coordinates
# round lat/lng to 7 decimal digits (cm precision)
self.latitude = self.latitude.round(7)
self.longitude = self.longitude.round(7)
end
end
| true
|
aa58360002f803ac728a73e252f78bd57ea45ed5
|
Ruby
|
djspinmonkey/testify
|
/samples/summary.rb
|
UTF-8
| 406
| 2.75
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
# Output a summary of the test results after they've all been run.
#
class Summary
include Testify::Middleware
aka :summary
def call( env )
results = @app.call(env)
summary = Hash.new(0)
results.each { |res| summary[res.status] += 1 }
puts "Ran #{results.size} tests in all"
summary.each { |status, count| puts "#{count} tests with status #{status}" }
results
end
end
| true
|
2d639011b3a33ba30d2db3604d95841d9fa9a07c
|
Ruby
|
PlushNinja/stellar
|
/app/models/transfer.rb
|
UTF-8
| 6,157
| 2.59375
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
class Transfer < ApplicationRecord
resourcify
include Authority::Abilities
include Trackable
#---
belongs_to :store
# Transfers happen from source to destination, either of which may be nil
# for a one-sided transfer (from purchases/orders).
belongs_to :source, class_name: 'Inventory', optional: true
belongs_to :destination, class_name: 'Inventory', optional: true
# If a shipment is associated, this transfer is for its stock changes.
belongs_to :shipment, optional: true
# This association has an extension to merge a new transfer item with
# an existing similar item, because the item needs to be built first
# to include a product id needed for find_or_initialize_by
has_many :transfer_items, dependent: :destroy do
def merge(new_item)
find_or_initialize_by(
product: new_item.product,
lot_code: new_item.lot_code,
expires_at: new_item.expires_at
).tap do |item|
item.amount += new_item.amount
end
end
end
default_scope { order(created_at: :desc) }
scope :complete, -> { where.not(completed_at: nil) }
scope :manual, -> { where(shipment_id: nil) }
#---
validates :destination_id, exclusion: {
in: -> (transfer) { [transfer.source_id] },
message: :same_as_source
}
#---
def complete?
completed_at.present?
end
def incomplete?
!complete?
end
# Completes the transfer by creating inventory entries corresponding to
# the changes made to the source and destination inventories by the
# transfer items.
def complete!
now = Time.current
transaction do
transfer_items.each do |item|
source.present? && source.destock!(item, now, self)
destination.present? && destination.restock!(item, now, self)
end
update completed_at: now
end
end
# Transfer is considered feasible only if all its items can be
# transferred, given current stock levels. Immediately returns
# true if the source is nil -- denoting an external source -- or
# if the source uses a stock gateway, which will not be queried.
def feasible?
return true if source.nil? || source.enable_gateway?
transfer_items.each do |item|
return false unless item.feasible?
end
true
end
# Loads the given order items into the transfer. To keep track of
# inventory during the load, matching inventory items are preloaded
# and updated by each #load_item! call.
def load!(order_items)
transaction do
products = order_items.map(&:product)
stock = source.inventory_items.for(products)
order_items.each do |order_item|
load_item!(order_item, stock)
end
end
end
# Creates a new transfer item based on given order item, specifying the
# product, lot code, and amount, if not overridden by arguments.
def create_item_from(order_item, lot_code = nil, expires_at = nil, amount = nil)
transfer_items.create!(
order_item: order_item,
product: order_item.product,
lot_code: lot_code || order_item.lot_code,
expires_at: expires_at,
amount: amount || order_item.waiting
)
end
# Duplicates given existing transfer items into this transfer,
# useful for creating return transfers.
def duplicate_items_from(items)
transaction do
items.each do |item|
transfer_items << item.dup
end
end
end
def appearance
if incomplete?
return 'danger text-danger' unless feasible?
'warning text-warning'
end
end
def icon
if incomplete?
return 'warning' unless feasible?
'cog'
end
end
def to_s
"%s %s ➡ %s" % [note, source, destination]
end
private
# Loads a single order item from given stock into the transfer
# as one or more transfer items. Updates the stock accordingly.
# Attempts several strategies until one returns true to denote
# the item has been loaded or the item is left (partially) unloaded.
def load_item!(order_item, stock)
if !order_item.product.tracked_stock? || source.enable_gateway?
load_item_from_infinite_stock(order_item) && return
end
stock_items = stock.select { |item| item.product == order_item.product }
return false if stock_items.none?
if order_item.lot_code.present?
load_item_by_lot_code(order_item, stock_items)
else
load_item_from_stock(order_item, stock_items)
end
end
# Loading from infinite stock always succeeds. Order number is
# used as lot code for the transfer item.
def load_item_from_infinite_stock(order_item)
create_item_from(order_item, order_item.order.number)
true
end
# Loading an item by lot code selects an inventory item by code,
# and only loads the item if a match is found.
def load_item_by_lot_code(order_item, stock_items)
item = stock_items.find { |item| order_item.lot_code == item.code }
# If the order item has a serial number, try lot code part only.
if item.nil? && order_item.lot_code['-']
lot_code_part = order_item.lot_code.split('-').first
item = stock_items.find { |item| lot_code_part == item.code }
end
# If a match was found, load the item and return. If a partial
# match set a lot code part above, use that, or provide nil
# to use the code on the order item.
if item.present?
item.reserved += order_item.amount
return create_item_from(order_item, lot_code_part, item.expires_at)
end
false # Failed to load the item.
end
# Default strategy: loads the order item from given stock items.
def load_item_from_stock(order_item, stock_items)
amount = order_item.waiting
stock_items.each do |item|
all = item.available
next if all <= 0
if amount <= all
# This inventory item satisfies the amount, we're done.
item.reserved += amount
return create_item_from(order_item, item.code, item.expires_at, amount)
else
# Load all of this item and continue with the remaining amount.
item.reserved += all
create_item_from(order_item, item.code, item.expires_at, all)
amount -= all
end
end
end
end
| true
|
05f0100b010d1c32ab9f2d9ef626bdc8d8c4a046
|
Ruby
|
itggot-hannes-skoog/standard-biblioteket
|
/lib/min_of_three.rb
|
UTF-8
| 440
| 4.5
| 4
|
[] |
no_license
|
# Public: Takes three numbers and outputs smallest of the three.
#
# num1 - First number.
# num2 - Second number.
# num3 - Third number.
#
# Examples
#
# min_of_three(7,12,2)
# # => 2
#
# Returns smallest of three numbers.
def min_of_three(num1, num2, num3)
if num1 < num2
if num1 < num3
return num1
end
else
if num2 < num3
return num2
end
end
return num3
end
| true
|
d891433596496e631e4bb97e37e81a7017afa780
|
Ruby
|
sansuaza/RubyUdemy
|
/section8/Spaceship_Operator.rb
|
UTF-8
| 175
| 2.796875
| 3
|
[] |
no_license
|
# Se comparan dos elementos si l la der es mayor, retorna -1
# de lo contrario 1, si son iguales 0
# Con arreglos los compara todos
4 <=> 5
=> -1
4 <=> 3
=> 1
4 <=> 4
=> 0
| true
|
20dc871f6bea6130cfdd2c1c75ef586f4cd07ce5
|
Ruby
|
sf-wdi-22-23/23-homework
|
/BreanaMarie/breana-zombies.rb
|
UTF-8
| 2,252
| 2.671875
| 3
|
[] |
no_license
|
Level 1
#Find
$ Zombie.find(1)
#<Zombie id: 1, name: "Ashley", graveyard: "Glen Haven Memorial Cemetery">
Successfully found Zombie where ID = 1.
#Crete
$ Bill = Zombie.create
#FindII
$ Zombie.last
#<Zombie id: 3, name: "Katie", graveyard: "My Father's Basement">
Found the last Zombie!
#Query
#<ActiveRecord::Relation [#<Zombie id: 2, name: "Ashley", graveyard: "Glen Haven Memorial Cemetery">, #<Zombie id: 1, name: "Bob", graveyard: "Chapel Hill Cemetery">, #<Zombie id: 3, name: "Katie", graveyard: "My Father's Basement">]>
Found all Zombies ordered by their names.
#Update
$ Zombie.find(3).update(graveyard: 'Benny Hills Memorial')
true
Successfully updated Zombie 3s graveyard
#Destroy
$ Zombie.find(3).destroy
#<Zombie id: 3, name: "Katie", graveyard: "My Father's Basement">
Destroyed Zombie 3.
Level 2
#Create Model
class Zombie < ActiveRecord::Base
end
#ValidationsI
class Zombie < ActiveRecord::Base
# insert validation here
validates_presence_of :name
end
#ValidationsII
class Zombie < ActiveRecord::Base
# insert validation here
validates_uniqueness_of :name
end
#VAlidationsIII
class Zombie < ActiveRecord::Base
# insert validation here
validates :name,
uniqueness:true,
presence:true
end
#Belongs to
class Weapon < ActiveRecord::Base
belongs_to :zombie
end
#Relationship Find$ Zombie.find(1).weapons
$ Zombie.find(1).weapons
#<ActiveRecord::Associations::CollectionProxy [#<Weapon id: 1, name: "Hammer", strength: 1, zombie_id: 1>]>
Successfully found all of Ashleys weapons.
Level 3
# Views Simple
<h1><%= zombie.name %></h1>
<p>
<%= zombie.graveyard %>
</p>
# Linking
<p>
<%= link_to zombie.name, zombie %>
</p>
# Each Blocks
<ul>
<% zombies.each do |zombie| %>
<li>
<%= zombie.name %>
</li>
<% end %>
</ul>
# If
<ul>
<% zombies.each do |zombie| %>
<li>
if(zombie.tweet.length >= tweet
<%= zombie.name %>
<%if zombie.tweets.size > 1 %>SMART ZOMBIE<% end %>
</li>
<% end %>
</ul>
# Linking in Blocks
<% zombies = Zombie.all %>
<ul>
<% zombies.each do |zombie| %>
<li>
<%= link_to zombie.name, edit_zombie_path(zombie) %>
</li>
<% end %>
</ul>
Level 4
# Show Action
# Respond To
# Controller Create Action
# Controller Before Action
| true
|
c664a9604a559e90237f097a65751dda9c95a5f0
|
Ruby
|
djlazz3/hyperledger-fabric-sdk
|
/lib/fabric_ca/error.rb
|
UTF-8
| 291
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
module FabricCA
class Error < StandardError
attr_reader :response, :full_message
def initialize(message, response)
super message
@response = Hashie::Mash.new JSON.parse(response.body)
@full_message = @response.errors.map(&:message).join(', ')
end
end
end
| true
|
0512d145e35d90c9f6c0254aa0b6f5ae40f31971
|
Ruby
|
LincolnWilliam/curso_ruby
|
/modulo1/loops/each.rb
|
UTF-8
| 429
| 3.78125
| 4
|
[] |
no_license
|
#Sintaxe each # cada
#itera ranges
(1..5).each do |i|
puts "o valor de i é: #{i}"
end
#itera arrays
["banana", "maçã", "mamão"].each do |fruta|
puts "a fruta é #{fruta}"
end
#itera hashes
{a: "banana", b: "maçã", c: "mamao"}.each do |fruta|
puts "a fruta é #{fruta.last}"
end
####
nome = ["marcos", "rogerio", "hugo"]
nome.each do |users|
puts"#{users.capitalize}"
end
| true
|
62772b3bf95b4ce1a70f2b46388811e4e5f2f58e
|
Ruby
|
IciredAtenllado/sample_app
|
/app/helpers/application_helper.rb
|
UTF-8
| 361
| 2.625
| 3
|
[
"MIT",
"Beerware",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
module ApplicationHelper
# Returns the full title on a per-page basis. # Documentation comment
def full_title(page_title = '') # Method def, optional arg
base_title = "Ruby on Rails Tutorial Sample App" # Variable assignment
if page_title.empty? # Boolean test
base_title # Implicit return
else
page_title + " | " + base_title # String concatenation
end
end
end
| true
|
7769a8fc84cafd46a3db414136b25390b3483480
|
Ruby
|
MagneticRegulus/120_exercises
|
/basics_4/2_choose_right_method.rb
|
UTF-8
| 573
| 3.40625
| 3
|
[] |
no_license
|
# Add the appropriate accessor methods to the following code.
class Person
attr_writer :name, :phone_number
attr_reader :name
end
person1 = Person.new
person1.name = 'Jessica'
person1.phone_number = '0123456789'
puts person1.name
# OR
class Person
attr_accessor :name, :phone_number
end
person1 = Person.new
person1.name = 'Jessica'
person1.phone_number = '0123456789'
puts person1.name
# OR
class Person
attr_accessor :name
attr_writer :phone_number
end
person1 = Person.new
person1.name = 'Jessica'
person1.phone_number = '0123456789'
puts person1.name
| true
|
6b3e68b1e04865e2e4c17dac28fb2e1c4be34f46
|
Ruby
|
princesspretzel/euler
|
/ruby/10.rb
|
UTF-8
| 229
| 3.4375
| 3
|
[] |
no_license
|
# The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
# Find the sum of all the primes below two million.
require 'prime'
sum = 0
(1..2000000).step(2) do |x|
if Prime.prime?(x)
sum += x
end
end
sum+2
# 142913828922
| true
|
b420f9ec6ee42f8f75f45890d03e533c499baa0d
|
Ruby
|
jaimeiniesta/DroidTimeLapse
|
/droidtimelapse.rb
|
UTF-8
| 1,322
| 3.375
| 3
|
[
"MIT"
] |
permissive
|
##########################################################################
# DroidTimeLapse
# A tiny little script to take photos from android on a specified interval
##########################################################################
# Define dirs and constants
APP_DIR = File.expand_path File.dirname(__FILE__)
SETUP_WAIT = 10
# Ask user for instructions
# Welcome screen
puts "### DroidTimeLapse ###\n"
# Number of seconds to wait after each picture
puts "How many seconds should I wait after each photo?"
WAIT = gets.chomp.to_i
# Number of pictures to be taken in total
puts "How many pictures should we take in total?"
NUM_PICTURES = gets.chomp.to_i
# Require and initialize Android API
require "android"
DROID = Android.new
# Give time to position the camera
puts "Please position your camera."
puts "Photo capturing will begin in #{SETUP_WAIT} seconds"
sleep SETUP_WAIT
# Loop and take pictures
album_name = Time.now.strftime('%Y/%m/%d/%H_%M')
counter = 0
NUM_PICTURES.times do
puts "Taking picture #{counter += 1}..."
snapshot_path = File.join APP_DIR, "droidtimelapse/albums/#{album_name}/#{Time.now.strftime('%Y%m%d_%H%M%S')}.jpg"
DROID.cameraCapturePicture snapshot_path
puts "#{NUM_PICTURES - counter} pictures remaining. Sleeping #{WAIT} seconds..."
sleep WAIT
end
puts "Finished!"
| true
|
82700913fa29038ef0ed899f158e9425ce1cdf00
|
Ruby
|
siwS/bowling-game-tdd-kata
|
/spec/game_spec.rb
|
UTF-8
| 1,390
| 3.09375
| 3
|
[] |
no_license
|
require_relative "../lib/game"
describe Game do
describe "#roll" do
it "responds to #roll" do
game = Game.new
expect(game).to respond_to(:roll)
end
end
describe "#score" do
it "responds to #roll" do
game = Game.new
expect(game).to respond_to(:score)
end
it "all misses score a zero" do
game = Game.new
20.times do
game.roll(0)
end
expect(game.score).to eq(0)
end
it "all ones score 20" do
game = Game.new
20.times do
game.roll(1)
end
expect(game.score).to eq(20)
end
it "A spare in the first frame, followed by three pins, followed by all misses scores 16." do
game = Game.new
game.roll(5)
game.roll(5)
game.roll(3)
17.times do
game.roll(0)
end
expect(game.score).to eq(16)
end
it "A strike in the first frame, followed by three and then four pins, followed by all misses, scores 24." do
game = Game.new
game.roll(10)
game.roll(3)
game.roll(4)
17.times do
game.roll(0)
end
expect(game.score).to eq(24)
end
it "A perfect game (12 strikes) scores 300." do
game = Game.new
game.roll(10)
game.roll(3)
game.roll(4)
17.times do
game.roll(0)
end
expect(game.score).to eq(24)
end
end
end
| true
|
ac90ba44eab6935872fe1e65c9007888662d80da
|
Ruby
|
KP09/logbook-api
|
/db/seeds.rb
|
UTF-8
| 551
| 2.734375
| 3
|
[] |
no_license
|
puts "Destroying previous passages"
Passage.destroy_all
puts "Seeding new passages..."
10.times do
Passage.create!({
departure_port: "Some departure port",
arrival_port: "Some arrival port",
departure_date: Date.today-100,
arrival_date: Date.today-90,
description: "A really awesome passage. We left from here and arrived there. The weather was rough.",
miles: 150,
hours: 20,
night_hours: 10,
role: "Crew",
overnight: true,
tidal: true,
ocean_passage: true
})
end
puts "Finished seeding passages"
| true
|
23a7a375600501d0c4cd1c1dee57080f2fd96e3e
|
Ruby
|
ziobrando/da_beat
|
/test/clock/clock_spec.rb
|
UTF-8
| 797
| 2.53125
| 3
|
[] |
no_license
|
$:.unshift File.join(File.dirname(__FILE__), "../..", "lib")
require "rspec"
require "clock/clock"
describe "Tick" do
it "should tick at a given interval" do
end
it "should accept listeners" do
clock = Clock.new 20,5
listener = MockListener.new
clock.add_listener listener
clock.start
listener.count.should == 4
end
it "should accept multiple listeners" do
clock = Clock.new 50,5
listener_a = MockListener.new
listener_b = MockListener.new
clock.add_listener listener_a
clock.add_listener listener_b
clock.start
listener_a.count.should == 10
listener_b.count.should == 10
end
end
class MockListener
attr_reader :count
def initialize
@count = 0
end
def tick time
@count+=1
end
#include ClockListener
end
| true
|
67ef3dd8a877a183eb990de70107341ab5c9b77b
|
Ruby
|
toshimaru/jekyll-toc
|
/test/parser/test_invalid_options.rb
|
UTF-8
| 883
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
require 'test_helper'
class TestInvalidOptions < Minitest::Test
BASE_HTML = '<h1>h1</h1>'
EXPECTED_HTML = <<~HTML.chomp
<ul id="toc" class="section-nav">
<li class="toc-entry toc-h1"><a href="#h1">h1</a></li>
</ul>
HTML
def test_option_is_nil
parser = Jekyll::TableOfContents::Parser.new(BASE_HTML, nil)
assert_equal(EXPECTED_HTML, parser.build_toc)
end
def test_option_is_epmty_string
parser = Jekyll::TableOfContents::Parser.new(BASE_HTML, '')
assert_equal(EXPECTED_HTML, parser.build_toc)
end
def test_option_is_string
parser = Jekyll::TableOfContents::Parser.new(BASE_HTML, 'string')
assert_equal(EXPECTED_HTML, parser.build_toc)
end
def test_option_is_array
parser = Jekyll::TableOfContents::Parser.new(BASE_HTML, [])
assert_equal(EXPECTED_HTML, parser.build_toc)
end
end
| true
|
65301dc2e9eeb2ea5728942f4b1bcdba85eb3007
|
Ruby
|
anette87/bringing-it-all-together-onl01-seng-ft-050420
|
/lib/dog.rb
|
UTF-8
| 2,585
| 3.390625
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
class Dog
attr_accessor :name, :breed, :id
def initialize(keyvalues_hash)
@id = keyvalues_hash[:id]
@name = keyvalues_hash[:name]
@breed = keyvalues_hash[:breed]
end
def self.create_table
sql = <<-SQL
CREATE TABLE IF NOT EXISTS dogs(
id INTEGAR PRIMARY KEY,
name TEXT,
breed, TEXT
)
SQL
DB[:conn].execute(sql)
end
def self.drop_table
DB[:conn].execute("DROP TABLE IF EXISTS dogs")
end
def save
sql = <<-SQL
INSERT INTO dogs(name,breed) VALUES (?, ?)
SQL
DB[:conn].execute(sql, self.name, self.breed)
@id = DB[:conn].execute("SELECT last_insert_rowid() FROM dogs")[0][0]
self #returns an instance of the dog class
end
def self.create(keyvalues_hash)
dog = Dog.new(keyvalues_hash)
dog.save
dog
end
def self.new_from_db(row)
new_dog_hash = {}
new_dog_hash[:id] = row[0]
new_dog_hash[:name] = row[1]
new_dog_hash[:breed] = row[2]
new_dog = self.new(new_dog_hash)
new_dog
end
def self.find_by_id(id)
sql = <<-SQL
SELECT * FROM dogs WHERE id = ?
SQL
dog = DB[:conn].execute(sql,id)
new_dog_hash = {}
new_dog_hash[:id] = dog[0][0]
new_dog_hash[:name] = dog[0][1]
new_dog_hash[:breed] = dog[0][2]
new_dog = self.new(new_dog_hash)
new_dog
end
def self.find_or_create_by(name:, breed:)
dog = DB[:conn].execute("SELECT * FROM dogs WHERE name = ? AND breed = ?", name, breed)
if !dog.empty?
dog_data = dog[0],
dog_data_hash = {}
dog_data_hash[:id] = dog_data[0][0]
dog_data_hash[:name] = dog_data[0][1]
dog_data_hash[:breed] = dog_data[0][2]
dog = Dog.new(dog_data_hash)
else
dog = self.create(name:name, breed:breed)
end
dog
end
def self.find_by_name(name)
sql = "SELECT * FROM dogs WHERE name = ?"
result = DB[:conn].execute(sql,name)[0]
dog_data_hash = {}
dog_data_hash[:id] = result[0]
dog_data_hash[:name] = result[1]
dog_data_hash[:breed] = result[2]
dog = Dog.new(dog_data_hash)
dog
end
def update
sql = "UPDATE dogs SET name = ?, breed = ? WHERE id = ?"
DB[:conn].execute(sql, self.name, self.breed, self.id)
end
end
| true
|
84829f0f804157cd737bccc43091fe39e796aaaa
|
Ruby
|
newtonry/interview-street
|
/fraud-prevention.rb
|
UTF-8
| 1,856
| 3.265625
| 3
|
[] |
no_license
|
def fraud_checker
deals = {}
frauds = []
num_input = gets.chomp.to_i
num_input.times do
inp = gets.chomp.split(',')
deal_id = inp[1]
entry = {}
entry[:ord_id] = inp[0]
entry[:email] = process_email(inp[2])
entry[:full_address] = full_add(inp[3], inp[4], inp[5], inp[6])
entry[:credit_card] = inp[7]
deals[deal_id] = deals[deal_id] || []
deals[deal_id] << entry
end
deals.each do |deal_id, orders|
frauds = frauds.concat(check_dups(orders))
end
frauds.uniq.sort.join(',')
end
def check_dups(orders)
frauds = []
orders.sort_by! {|order| order[:full_address] }
orders[0..-2].each_with_index do |order, i|
if order[:full_address] == orders[i+1][:full_address] && order[:credit_card] != orders[i+1][:credit_card]
frauds << order[:ord_id].to_i << orders[i+1][:ord_id].to_i
end
end
orders.sort_by! {|order| order[:email]}
orders[0..-2].each_with_index do |order, i|
if order[:email] == orders[i+1][:email] && order[:credit_card] != orders[i+1][:credit_card]
frauds << order[:ord_id].to_i << orders[i+1][:ord_id].to_i
end
end
frauds
end
def process_email(email)
new_email = email.downcase.gsub('.', '').split("@").map do |segment|
segment[0..((segment.index('+') || 0) - 1)]
end.join('@')
end
def full_add(address, city, state, zip)
full_add = [process_add(address), city, process_state(state), process_zip(zip)].join(',').downcase
end
def process_add(address)
abbrevs = {'St.' => 'Street', 'Rd.' => 'Road'}
abbrevs.each do |k, v|
address.gsub!(k, v)
end
address
end
def process_state(state)
abbrevs = {'Illinois' => 'IL', 'California' => 'CA', 'New York' => 'NY'}
abbrevs.each do |k, v|
state.gsub!(k, v)
end
state
end
def process_zip(zip)
zip[0..((zip.index('-') || 0) - 1)]
end
puts fraud_checker
| true
|
4e11a4a0f3006b10292dc2cacb5ad68661c3106d
|
Ruby
|
tommoor/filecop
|
/lib/filecop/runner.rb
|
UTF-8
| 576
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
module Filecop
class Runner
def initialize(paths)
@paths = paths
end
def run
# load banned patterns from config file
patterns = JSON.parse File.read(File.join(File.dirname(__FILE__), '..', 'patterns.json'))
rules = patterns.map { |o| Rule.new(o) }
output = []
@paths.each do |file|
rules.each do |rule|
if rule.matches?(file)
output << {
file: file,
rule: rule
}
break
end
end
end
output
end
end
end
| true
|
0325102813962b762dbb41c74d1e8ef996ea9268
|
Ruby
|
zoebisch/artist-song-modules-v-000
|
/lib/concerns/memorable.rb
|
UTF-8
| 283
| 2.625
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
module Memorable
module ClassMethods
def reset_all
self.all.clear
end
def count
self.all.count
end
end
module InstanceMethods #Did it both ways, here and in paramable
def to_param
self.name.downcase.gsub(' ', '-')
end
end
end
| true
|
622e77b2f44bd529171a71520dda5d7ea5a70ab0
|
Ruby
|
AdelineAdy/Exos_Ruby
|
/exo_17.rb
|
UTF-8
| 253
| 3.734375
| 4
|
[] |
no_license
|
puts "Quel est votre age?"
print ">"
age = gets.chomp.to_i
year = 2020 - age
minage = 0
while (year <= 2020)
if age / 2 == minage
puts "Il y a #{2020 - year} ans, tu avais la moitié de l'âge que tu as aujourd'hui."
end
minage += 1
year += 1
end
| true
|
c02468457f7c9bf283675c63374e6a4bf5504d4d
|
Ruby
|
jasoncorum/ga_bewd
|
/Students/Andrew_Doepping/secret_number.rb
|
UTF-8
| 1,051
| 4.03125
| 4
|
[] |
no_license
|
secret_number = rand(11)
def intro
puts "So, who wants to challenge Camacho to a game of Secret Number?"
player_name = gets.chomp
puts "Woah #{player_name} ! You're about to play mental ninjitzu!"
puts "Let's layout the rules. I gots myself a number, and you need to figure out what it is in three tries."
puts "I'll be nice and tell you if you are over, under, or right on the money."
puts "I'll be even tell you it's between one and ten. LET'S GO!"
end
def number_of_guesses_left(secret_number)
3.downto(1) do |count|
if count == 1
puts "You have #{count} guess left"
else
puts "You have #{count} guesses left"
end
puts "Guess Sucker!"
guess = gets.chomp.to_i
looper(guess, secret_number)
end
puts "The secret number is " +secret_number.to_s+ " son!"
end
def looper(guess, secret_number)
high_low = guess <=> secret_number
if high_low == 1
puts "Too high!"
elsif
high_low == 0
puts 'Oh you\'re a magician!'
abort
else
puts "Too low!"
end
end
intro()
number_of_guesses_left(secret_number)
| true
|
a852b2d0f134ede582d60c20e896b242eb6e927d
|
Ruby
|
alvaritog/openlocs_app
|
/db/seeds.rb
|
UTF-8
| 1,310
| 2.5625
| 3
|
[] |
no_license
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
user = CreateAdminService.new.call
puts 'CREATED ADMIN USER: ' << user.email
# Environment variables (ENV['...']) can be set in the file .env file.
# SEED TEST LOCATIONS
locations = CreateTestLocationsService.new.call
locations.each do |loc|
OpeningRule.weekdays.each do |weekday_name, weekday_value|
opening_type = [:a,:b,:c,:d].sample
case opening_type
when :a
loc.opening_rules.create! weekday: weekday_name, start_time: "08:00", end_time: "12:00"
loc.opening_rules.create! weekday: weekday_name, start_time: "16:00", end_time: "18:00"
when :b
loc.opening_rules.create! weekday: weekday_name, start_time: "00:00", end_time: "23:59"
when :c
loc.opening_rules.create! weekday: weekday_name, start_time: "08:00", end_time: "20:00"
when :d
end
end
end
puts "LOCATIONS:"
puts locations.as_json(include: {opening_rules: {only: [:weekday,:start_time,:end_time]}}).pretty_inspect
| true
|
72ba02bd08d4e8857d2a1ba15af8b874873c13b9
|
Ruby
|
jimmy2/launchschool_intro_to_programming
|
/hashes/exercise_02.rb
|
UTF-8
| 346
| 2.875
| 3
|
[] |
no_license
|
hash_01 = { shawshank_redemption: 9.2, the_godfather: 9.2, the_dark_knight: 9.0, twelve_angry_men: 8.9 }
hash_02 = { shindlers_list: 8.9, pulp_fiction: 8.9, lotr: 8.9, fight_club: 8.8 }
hash_01.merge(hash_02)
puts "Using merge"
puts hash_01
puts hash_02
hash_01.merge!(hash_02)
# mutates the caller
puts "Using merge!"
puts hash_01
puts hash_02
| true
|
ddf8cd7cbe4493c188f771d3f801f4a30b576c22
|
Ruby
|
abishekaditya/RubyProjects
|
/pry
|
UTF-8
| 82
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
#!/usr/bin/env ruby
require 'pry'
a = 50
binding.pry
if a > 20
puts a - 50
end
| true
|
aa5027dd3788ef6d06b436a7365940d3e3a3cbe5
|
Ruby
|
marcwright/WDI_ATL_1_Instructors
|
/REPO - London/0_Homeworks/sinatra__calcit/calcit_sinatra/main.rb
|
UTF-8
| 2,277
| 2.765625
| 3
|
[] |
no_license
|
require 'sinatra'
require 'sinatra/reloader' if development?
require 'pry-byebug'
get '/' do
erb :home
end
get '/simple' do
@first = params[:first].to_f
@second = params[:second].to_f
@operator = params[:operator].to_s
@result = case @operator
when '+' then
@first + @second
when '-' then
@first - @second
when '*' then
@first * @second
when '/' then
@first / @second
end
erb :simple
end
get '/advanced' do
@type = params[:type].to_s
@first = params[:first].to_f
@second = params[:second].to_f
@square = params[:square].to_f
if @type == 'sqrt' then
@result = Math.sqrt(@square)
elsif @type == 'power' then
@result = @first ** @second
end
erb :advanced
end
get '/mortgage' do
if params[:loan]
loan = params[:loan].to_i
rate = params[:rate].to_f/100
months = params[:months].to_i*12
interest = (1+rate/12)**(12/12)-1
capital = (1-(1/(1+interest))**months)/interest
@result = (loan/capital).round(2)
end
erb :mortgage
end
get '/bmi' do
if params[:height]
@operation = params[:operation].to_s
@height = params[:height].to_f
@weight = params[:weight].to_f
@result = ((@weight/(@height * @height))).round(2)
if @operation == 'i'
@result = (@result*703)
end
end
erb :bmi
end
get '/trip' do
if params[:distance]
@distance = params[:distance].to_f
@mpg = params[:mpg].to_f
@cost = params[:cost].to_f
@speed = params[:speed].to_f
if @speed > 60
@mpg = @mpg - ((@speed - 60)*2)
end
@time_driving = @distance / @speed
@result = ((@cost/@mpg)*@distance).round(2)
end
erb :trip
end
get '/death' do
if params[:age]
@age = params[:age].to_f
@result = (81 - @age)*365.25*24*60*60
end
erb :death
end
post '/navigate' do
goto = case
when params[:destination].downcase.include?('ortgag')
:mortgage
when params[:destination].downcase.include?('bmi')
:bmi
when params[:destination].downcase.include?('trip')
:trip
when params[:destination].downcase.include?('death')
:death
when params[:destination].downcase.include?('simp')
:simple
when params[:destination].downcase.include?('adva')
:advanced
else
:home
end
erb goto
end
| true
|
51c8f40d9590af0796fba4bc6e84e38dc2bdaa4d
|
Ruby
|
kukushkin/mimi
|
/lib/mimi/cli/template/spec/support/envvars.rb
|
UTF-8
| 371
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
require 'dotenv'
# Runs block with ENV variables loaded from specified file,
# restores original ENV variables after.
#
# @example
# with_env_vars('.env.test') do
# application.config.load
# end
#
def with_env_vars(filename = nil, &_block)
original_env_vars = ENV.to_hash
Dotenv.load(filename) if filename
yield
ensure
ENV.replace(original_env_vars)
end
| true
|
050d84cb16ad0d5b0f028d5c03da648064624be1
|
Ruby
|
JonathanSR/flashcards
|
/test/card_test.rb
|
UTF-8
| 574
| 3
| 3
|
[] |
no_license
|
require 'minitest/autorun'
require 'minitest/pride'
require './lib/card'
require 'pry'
class CardTest < Minitest::Test
def test_does_card_exist
card = Card.new("What is the capital of Alaska?", "Juneau")
assert_equal Card, card.class
end
def test_does_card_have_a_question
card = Card.new("What is the capital of Alaska?", "Juneau")
assert_equal "What is the capital of Alaska?", card.question
end
def test_does_card_have_answer
card = Card.new("What is the capital of Alaska?", "Juneau")
assert_equal "Juneau", card.answer
end
end
| true
|
31c626432f6972b2ef3f9049621e314496b84ddc
|
Ruby
|
MichaelSchwar3/AoC
|
/day1/part1.rb
|
UTF-8
| 114
| 3.265625
| 3
|
[] |
no_license
|
f = File.new("input.txt")
arr = []
f.each_line do |num|
n = num.chomp.to_i
arr << n
end
p arr.reduce(:+)
| true
|
331ef5afa8c629daaa13faae4b72dcb62a101f97
|
Ruby
|
kumaranvpl/rbnd-udacitask-part2
|
/lib/listable.rb
|
UTF-8
| 632
| 2.921875
| 3
|
[] |
no_license
|
module Listable
def format_description(description)
"#{description}".ljust(25)
end
def format_priority(priority)
value = " ⇧".colorize(:red) if priority == "high"
value = " ⇨".colorize(:yellow) if priority == "medium"
value = " ⇩".colorize(:green) if priority == "low"
value = "" if !priority
return value
end
def format_date(date1, date2 = nil)
if date2 == nil
date1 ? date1.strftime("%D") : "No due date"
else
dates = date1.strftime("%D") if date1
dates << " -- " + date2.strftime("%D") if date2
dates = "N/A" if !dates
return dates
end
end
end
| true
|
2c1259cda1065f9427ec0078033adb1323e9a807
|
Ruby
|
yusukeyamane/vending-machine
|
/VendingMachine.rb
|
UTF-8
| 1,284
| 3.671875
| 4
|
[] |
no_license
|
class Beverage
@@tax = 0.1
attr_reader :name, :price
def initialize(args)
@name = args.fetch(:name, 'サイダー')
@price = args.fetch(:price, 120)
end
def price
@price + (@price * @@tax).floor
end
end
class VendingMachine
def initialize(products)
@products = products
end
def transaction
display_anounce
product = take_order
serve_item(product)
end
def display_anounce
puts '購入したい商品を以下から選んで、金額を入力してください'
@products.each_with_index do |product, i|
puts "[#{i}] 商品名:#{product.name} 税込み価格:#{product.price}円"
end
end
def take_order
product = @products[gets.to_i]
puts "#{product}が選択されました"
product
end
def serve_item(product)
# 適正金額が受け取れるまで繰り返す。
while true do
payment = gets.to_i
charge = calc_change(payment, product.price)
if charge >= 0
break
else
puts "入力金額が不足しています。金額を再入力してください。"
end
end
puts "お釣りは#{charge}円です。ご利用ありがとうございました。"
end
def calc_change(payment, price)
payment - price
end
end
| true
|
5baa6e24892c9ec6f3787048e58ad4a79e26a220
|
Ruby
|
scpike/rails-units
|
/lib/rails_units/unit_definitions.rb
|
UTF-8
| 13,712
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
class Unit < Numeric
UNIT_DEFINITIONS = {
# prefixes
'<googol>' => [%w{googol}, 1e100, :prefix],
'<kibi>' => [%w{Ki Kibi kibi}, 2**10, :prefix],
'<mebi>' => [%w{Mi Mebi mebi}, 2**20, :prefix],
'<gibi>' => [%w{Gi Gibi gibi}, 2**30, :prefix],
'<tebi>' => [%w{Ti Tebi tebi}, 2**40, :prefix],
'<pebi>' => [%w{Pi Pebi pebi}, 2**50, :prefix],
'<exi>' => [%w{Ei Exi exi}, 2**60, :prefix],
'<zebi>' => [%w{Zi Zebi zebi}, 2**70, :prefix],
'<yebi>' => [%w{Yi Yebi yebi}, 2**80, :prefix],
'<yotta>' => [%w{Y Yotta yotta}, 1e24, :prefix],
'<zetta>' => [%w{Z Zetta zetta}, 1e21, :prefix],
'<exa>' => [%w{E Exa exa}, 1e18, :prefix],
'<peta>' => [%w{P Peta peta}, 1e15, :prefix],
'<tera>' => [%w{T Tera tera}, 1e12, :prefix],
'<giga>' => [%w{G Giga giga}, 1e9, :prefix],
'<mega>' => [%w{M Mega mega}, 1e6, :prefix],
'<kilo>' => [%w{k kilo}, 1e3, :prefix],
'<hecto>' => [%w{h Hecto hecto}, 1e2, :prefix],
'<deca>' => [%w{da Deca deca deka}, 1e1, :prefix],
'<deci>' => [%w{d Deci deci}, Rational(1,1e1), :prefix],
'<centi>' => [%w{c Centi centi}, Rational(1,1e2), :prefix],
'<milli>' => [%w{m Milli milli}, Rational(1,1e3), :prefix],
'<micro>' => [%w{u Micro micro}, Rational(1,1e6), :prefix],
'<nano>' => [%w{n Nano nano}, Rational(1,1e9), :prefix],
'<pico>' => [%w{p Pico pico}, Rational(1,1e12), :prefix],
'<femto>' => [%w{f Femto femto}, Rational(1,1e15), :prefix],
'<atto>' => [%w{a Atto atto}, Rational(1,1e18), :prefix],
'<zepto>' => [%w{z Zepto zepto}, Rational(1,1e21), :prefix],
'<yocto>' => [%w{y Yocto yocto}, Rational(1,1e24), :prefix],
'<1>' => [%w{1},1,:prefix],
# length units
'<meter>' => [%w{m meter meters metre metres}, 1, :length, %w{<meter>} ],
'<inch>' => [%w{in inch inches "}, Rational(254,10_000), :length, %w{<meter>}],
'<foot>' => [%w{ft foot feet '}, Rational(3048,10_000), :length, %w{<meter>}],
'<yard>' => [%w{yd yard yards}, 0.9144, :length, %w{<meter>}],
'<mile>' => [%w{mi mile miles}, 1609.344, :length, %w{<meter>}],
'<naut-mile>' => [%w{nmi}, 1852, :length, %w{<meter>}],
'<league>'=> [%w{league leagues}, 4828, :length, %w{<meter>}],
'<furlong>'=> [%w{furlong furlongs}, 201.2, :length, %w{<meter>}],
'<rod>' => [%w{rd rod rods}, 5.029, :length, %w{<meter>}],
'<mil>' => [%w{mil mils}, 0.0000254, :length, %w{<meter>}],
'<angstrom>' =>[%w{ang angstrom angstroms}, Rational(1,1e10), :length, %w{<meter>}],
'<fathom>' => [%w{fathom fathoms}, 1.829, :length, %w{<meter>}],
'<redshift>' => [%w{z red-shift}, 1.302773e26, :length, %w{<meter>}],
'<AU>' => [%w{AU astronomical-unit}, 149597900000, :length, %w{<meter>}],
'<light-second>'=>[%w{ls light-second}, 299792500, :length, %w{<meter>}],
'<light-minute>'=>[%w{lmin light-minute}, 17987550000, :length, %w{<meter>}],
'<light-year>' => [%w{ly light-year}, 9460528000000000, :length, %w{<meter>}],
'<parsec>' => [%w{pc parsec parsecs}, 30856780000000000, :length, %w{<meter>}],
#mass
'<kilogram>' => [%w{kg kilogram kilograms}, 1, :mass, %w{<kilogram>}],
'<AMU>' => [%w{u AMU amu}, 6.0221415e26, :mass, %w{<kilogram>}],
'<dalton>' => [%w{Da Dalton Daltons dalton daltons}, 6.0221415e26, :mass, %w{<kilogram>}],
'<slug>' => [%w{slug slugs}, 14.5939029, :mass, %w{<kilogram>}],
'<short-ton>' => [%w{tn ton}, 907.18474, :mass, %w{<kilogram>}],
'<metric-ton>'=>[%w{tonne}, 1000, :mass, %w{<kilogram>}],
'<carat>' => [%w{ct carat carats}, 0.0002, :mass, %w{<kilogram>}],
'<pound>' => [%w{lbs lb pound pounds #}, Rational(8171193714040401,18014398509481984), :mass, %w{<kilogram>}],
'<ounce>' => [%w{oz ounce ounces}, Rational(8171193714040401,288230376151711744), :mass, %w{<kilogram>}],
'<gram>' => [%w{g gram grams gramme grammes},Rational(1,1e3),:mass, %w{<kilogram>}],
#area
'<hectare>'=>[%w{hectare}, 10000, :area, %w{<meter> <meter>}],
'<acre>'=>[%w(acre acres), 4046.85642, :area, %w{<meter> <meter>}],
'<sqft>'=>[%w(sqft), 1, :area, %w{<feet> <feet>}],
#volume
'<liter>' => [%w{l L liter liters litre litres}, Rational(1,1e3), :volume, %w{<meter> <meter> <meter>}],
'<gallon>'=> [%w{gal gallon gallons}, 0.0037854118, :volume, %w{<meter> <meter> <meter>}],
'<quart>'=> [%w{qt quart quarts}, 0.00094635295, :volume, %w{<meter> <meter> <meter>}],
'<pint>'=> [%w{pt pint pints}, 0.000473176475, :volume, %w{<meter> <meter> <meter>}],
'<cup>'=> [%w{cu cup cups}, 0.000236588238, :volume, %w{<meter> <meter> <meter>}],
'<fluid-ounce>'=> [%w{floz fluid-ounce}, 2.95735297e-5, :volume, %w{<meter> <meter> <meter>}],
'<tablespoon>'=> [%w{tbs tablespoon tablespoons}, 1.47867648e-5, :volume, %w{<meter> <meter> <meter>}],
'<teaspoon>'=> [%w{tsp teaspoon teaspoons}, 4.92892161e-6, :volume, %w{<meter> <meter> <meter>}],
#speed
'<kph>' => [%w{kph}, 0.277777778, :speed, %w{<meter>}, %w{<second>}],
'<mph>' => [%w{mph}, 0.44704, :speed, %w{<meter>}, %w{<second>}],
'<knot>' => [%w{kt kn kts knot knots}, 0.514444444, :speed, %w{<meter>}, %w{<second>}],
'<fps>' => [%w{fps}, 0.3048, :speed, %w{<meter>}, %w{<second>}],
#acceleration
'<gee>' => [%w{gee}, 9.80655, :acceleration, %w{<meter>}, %w{<second> <second>}],
#temperature_difference
'<kelvin>' => [%w{degK kelvin}, 1, :temperature, %w{<kelvin>}],
'<celsius>' => [%w{degC celsius celsius centigrade}, 1, :temperature, %w{<kelvin>}],
'<fahrenheit>' => [%w{degF fahrenheit}, Rational(1,1.8), :temperature, %w{<kelvin>}],
'<rankine>' => [%w{degR rankine}, Rational(1,1.8), :temperature, %w{<kelvin>}],
'<temp-K>' => [%w{tempK}, 1, :temperature, %w{<temp-K>}],
'<temp-C>' => [%w{tempC}, 1, :temperature, %w{<temp-K>}],
'<temp-F>' => [%w{tempF}, Rational(1,1.8), :temperature, %w{<temp-K>}],
'<temp-R>' => [%w{tempR}, Rational(1,1.8), :temperature, %w{<temp-K>}],
#time
'<second>'=> [%w{s sec second seconds}, 1, :time, %w{<second>}],
'<minute>'=> [%w{min minute minutes}, 60, :time, %w{<second>}],
'<hour>'=> [%w{h hr hrs hour hours}, 3600, :time, %w{<second>}],
'<day>'=> [%w{d day days}, 3600*24, :time, %w{<second>}],
'<week>'=> [%w{wk week weeks}, 7*3600*24, :time, %w{<second>}],
'<fortnight>'=> [%w{fortnight fortnights}, 1209600, :time, %W{<second>}],
'<year>'=> [%w{y yr year years annum}, 31556926, :time, %w{<second>}],
'<decade>'=>[%w{decade decades}, 315569260, :time, %w{<second>}],
'<century>'=>[%w{century centuries}, 3155692600, :time, %w{<second>}],
#pressure
'<pascal>' => [%w{Pa pascal Pascal}, 1, :pressure, %w{<kilogram>},%w{<meter> <second> <second>}],
'<mmHg>' => [%w{mmHg}, 133.322368,:pressure, %w{<kilogram>},%w{<meter> <second> <second>}],
'<inHg>' => [%w{inHg}, 3386.3881472,:pressure, %w{<kilogram>},%w{<meter> <second> <second>}],
'<torr>' => [%w{torr}, 133.322368,:pressure, %w{<kilogram>},%w{<meter> <second> <second>}],
'<bar>' => [%w{bar}, 100000,:pressure, %w{<kilogram>},%w{<meter> <second> <second>}],
'<atm>' => [%w{atm ATM atmosphere atmospheres}, 101325,:pressure, %w{<kilogram>},%w{<meter> <second> <second>}],
'<psi>' => [%w{psi}, 6894.76,:pressure, %w{<kilogram>},%w{<meter> <second> <second>}],
'<cmh2o>' => [%w{cmH2O}, 98.0638,:pressure, %w{<kilogram>},%w{<meter> <second> <second>}],
'<inh2o>' => [%w{inH2O}, 249.082052,:pressure, %w{<kilogram>},%w{<meter> <second> <second>}],
#viscosity
'<poise>' => [%w{P poise}, Rational(1,10), :viscosity, %w{<kilogram>},%w{<meter> <second>} ],
'<stokes>' => [%w{St stokes}, Rational(1,1e4), :viscosity, %w{<meter> <meter>}, %w{<second>}],
#substance
'<mole>' => [%w{mol mole}, 1, :substance, %w{<mole>}],
#concentration
'<molar>' => [%w{M molar}, 1000, :concentration, %w{<mole>}, %w{<meter> <meter> <meter>}],
'<wtpercent>' => [%w{wt% wtpercent}, 10, :concentration, %w{<kilogram>}, %w{<meter> <meter> <meter>}],
#activity
'<katal>' => [%w{kat katal Katal}, 1, :activity, %w{<mole>}, %w{<second>}],
'<unit>' => [%w{U enzUnit}, 16.667e-16, :activity, %w{<mole>}, %w{<second>}],
#capacitance
'<farad>' => [%w{F farad Farad}, 1, :capacitance, %w{<farad>}],
#charge
'<coulomb>' => [%w{C coulomb Coulomb}, 1, :charge, %w{<ampere> <second>}],
#current
'<ampere>' => [%w{A Ampere ampere amp amps}, 1, :current, %w{<ampere>}],
#conductance
'<siemens>' => [%w{S Siemens siemens}, 1, :resistance, %w{<second> <second> <second> <ampere> <ampere>}, %w{<kilogram> <meter> <meter>}],
#inductance
'<henry>' => [%w{H Henry henry}, 1, :inductance, %w{<meter> <meter> <kilogram>}, %w{<second> <second> <ampere> <ampere>}],
#potential
'<volt>' => [%w{V Volt volt volts}, 1, :potential, %w{<meter> <meter> <kilogram>}, %w{<second> <second> <second> <ampere>}],
#resistance
'<ohm>' => [%w{Ohm ohm}, 1, :resistance, %w{<meter> <meter> <kilogram>},%w{<second> <second> <second> <ampere> <ampere>}],
#magnetism
'<weber>' => [%w{Wb weber webers}, 1, :magnetism, %w{<meter> <meter> <kilogram>}, %w{<second> <second> <ampere>}],
'<tesla>' => [%w{T tesla teslas}, 1, :magnetism, %w{<kilogram>}, %w{<second> <second> <ampere>}],
'<gauss>' => [%w{G gauss}, Rational(1,1e4), :magnetism, %w{<kilogram>}, %w{<second> <second> <ampere>}],
'<maxwell>' => [%w{Mx maxwell maxwells}, Rational(1,1e8), :magnetism, %w{<meter> <meter> <kilogram>}, %w{<second> <second> <ampere>}],
'<oersted>' => [%w{Oe oersted oersteds}, 250.0/Math::PI, :magnetism, %w{<ampere>}, %w{<meter>}],
#energy
'<joule>' => [%w{J joule Joule joules}, 1, :energy, %w{<meter> <meter> <kilogram>}, %w{<second> <second>}],
'<erg>' => [%w{erg ergs}, Rational(1,1e7), :energy, %w{<meter> <meter> <kilogram>}, %w{<second> <second>}],
'<btu>' => [%w{BTU btu BTUs}, 1055.056, :energy, %w{<meter> <meter> <kilogram>}, %w{<second> <second>}],
'<calorie>' => [%w{cal calorie calories}, 4.18400, :energy,%w{<meter> <meter> <kilogram>}, %w{<second> <second>}],
'<Calorie>' => [%w{Cal Calorie Calories}, 4184.00, :energy,%w{<meter> <meter> <kilogram>}, %w{<second> <second>}],
'<therm-US>' => [%w{th therm therms Therm}, 105480400, :energy,%w{<meter> <meter> <kilogram>}, %w{<second> <second>}],
#force
'<newton>' => [%w{N Newton newton}, 1, :force, %w{<kilogram> <meter>}, %w{<second> <second>}],
'<dyne>' => [%w{dyn dyne}, Rational(1,1e5), :force, %w{<kilogram> <meter>}, %w{<second> <second>}],
'<pound-force>' => [%w{lbf pound-force}, 4.448222, :force, %w{<kilogram> <meter>}, %w{<second> <second>}],
#frequency
'<hertz>' => [%w{Hz hertz Hertz}, 1, :frequency, %w{<1>}, %{<second>}],
#angle
'<radian>' =>[%w{rad radian radian radians}, 1, :angle, %w{<radian>}],
'<degree>' =>[%w{deg degree degrees}, Math::PI / 180.0, :angle, %w{<radian>}],
'<grad>' =>[%w{grad gradian grads}, Math::PI / 200.0, :angle, %w{<radian>}],
'<steradian>' => [%w{sr steradian steradians}, 1, :solid_angle, %w{<steradian>}],
#rotation
'<rotation>' => [%w{rotation}, 2.0*Math::PI, :angle, %w{<radian>}],
'<rpm>' =>[%w{rpm}, 2.0*Math::PI / 60.0, :angular_velocity, %w{<radian>}, %w{<second>}],
#memory
'<byte>' =>[%w{B byte}, 1, :memory, %w{<byte>}],
'<bit>' =>[%w{b bit}, 0.125, :memory, %w{<byte>}],
#currency
'<dollar>'=>[%w{USD dollar}, 1, :currency, %w{<dollar>}],
'<cents>' =>[%w{cents}, Rational(1,100), :currency, %w{<dollar>}],
#luminosity
'<candela>' => [%w{cd candela}, 1, :luminosity, %w{<candela>}],
'<lumen>' => [%w{lm lumen}, 1, :luminous_power, %w{<candela> <steradian>}],
'<lux>' =>[%w{lux}, 1, :illuminance, %w{<candela> <steradian>}, %w{<meter> <meter>}],
#power
'<watt>' => [%w{W watt watts}, 1, :power, %w{<kilogram> <meter> <meter>}, %w{<second> <second> <second>}],
'<horsepower>' => [%w{hp horsepower}, 745.699872, :power, %w{<kilogram> <meter> <meter>}, %w{<second> <second> <second>}],
#radiation
'<gray>' => [%w{Gy gray grays}, 1, :radiation, %w{<meter> <meter>}, %w{<second> <second>}],
'<roentgen>' => [%w{R roentgen}, 0.009330, :radiation, %w{<meter> <meter>}, %w{<second> <second>}],
'<sievert>' => [%w{Sv sievert sieverts}, 1, :radiation, %w{<meter> <meter>}, %w{<second> <second>}],
'<becquerel>' => [%w{Bq bequerel bequerels}, 1, :radiation, %w{<1>},%w{<second>}],
'<curie>' => [%w{Ci curie curies}, 3.7e10, :radiation, %w{<1>},%w{<second>}],
# rate
'<cpm>' => [%w{cpm}, Rational(1,60), :rate, %w{<count>},%w{<second>}],
'<dpm>' => [%w{dpm}, Rational(1,60), :rate, %w{<count>},%w{<second>}],
'<bpm>' => [%w{bpm}, Rational(1,60), :rate, %w{<count>},%w{<second>}],
#resolution / typography
'<dot>' => [%w{dot dots}, 1, :resolution, %w{<each>}],
'<pixel>' => [%w{pixel px}, 1, :resolution, %w{<each>}],
'<ppi>' => [%w{ppi}, 1, :resolution, %w{<pixel>}, %w{<inch>}],
'<dpi>' => [%w{dpi}, 1, :typography, %w{<dot>}, %w{<inch>}],
'<pica>' => [%w{pica}, 0.00423333333 , :typography, %w{<meter>}],
'<point>' => [%w{point pt}, 0.000352777778, :typography, %w{<meter>}],
#other
'<cell>' => [%w{cells cell}, 1, :counting, %w{<each>}],
'<each>' => [%w{each}, 1, :counting, %w{<each>}],
'<count>' => [%w{count}, 1, :counting, %w{<each>}],
'<base-pair>' => [%w{bp}, 1, :counting, %w{<each>}],
'<nucleotide>' => [%w{nt}, 1, :counting, %w{<each>}],
'<molecule>' => [%w{molecule molecules}, 1, :counting, %w{<1>}],
'<dozen>' => [%w{doz dz dozen},12,:prefix_only, %w{<each>}],
'<percent>'=> [%w{% percent}, Rational(1,100), :prefix_only, %w{<1>}],
'<ppm>' => [%w{ppm},Rational(1,1e6),:prefix_only, %w{<1>}],
'<ppt>' => [%w{ppt},Rational(1,1e9),:prefix_only, %w{<1>}],
'<gross>' => [%w{gr gross},144, :prefix_only, %w{<dozen> <dozen>}],
'<decibel>' => [%w{dB decibel decibels}, 1, :logarithmic, %w{<decibel>}]
} # doc
end
| true
|
e380b52056bcc77fe53a85ad663f1fc22604fb86
|
Ruby
|
sunrick/tiy-homework
|
/tic-tac-toe/test.rb
|
UTF-8
| 1,768
| 3.234375
| 3
|
[] |
no_license
|
require 'minitest/autorun'
require './game'
require './computer'
require './human'
require './board'
require './validation'
require './format'
include Validation
include Format
class GameTest < MiniTest::Test
def test_can_make_game
game = Game.new(Human.new("Rick"),Computer.new("John"),[3,3])
assert_instance_of Game, game
end
def test_human_player_can_move
game = Game.new(Human.new("Rick"),Computer.new("John"),[3,3])
assert game.choose_move
end
def test_computer_player_can_move
game = Game.new(Computer.new("Rick"),Computer.new("John"),[3,3])
assert game.choose_move
end
end
class BoardTest < MiniTest::Test
def test_can_make_a_board
board = Board.new(3,3)
assert_instance_of Board, board
end
def test_can_update_board
board = Board.new(4,3)
player_letter = "X"
player_input = 5
board.update(player_input, player_letter)
assert board.board[4] == "X"
end
def test_can_get_valid_moves_left_on_board
board = Board.new(5,110)
board.update(5,"X")
available_moves = board.valid_moves
refute available_moves.include?(5)
end
end
class ComputerTest < MiniTest::Test
def test_computer_can_choose_move
computer = Computer.new("John")
assert computer.get_move([1, 2, 3, 4, 'x', 'x', 'x', 8, 9])
end
def test_computer_cannot_choose_move
computer = Computer.new("John")
refute computer.get_move([])
end
end
class HumanTest < MiniTest::Test
def can_create_human
human = Human.new("Sup")
assert_instance_of Human, human
human = Human.new
refute_instance_of Human, human
end
def test_human_can_choose_move
human = Human.new("John")
assert human.get_move([1, 2, 3, 4, 4, 5, 6, 8, 9])
end
end
| true
|
107e88fd17d45cffd4b1d37e738e9c5dd7b0c7fa
|
Ruby
|
himynameisjonas/timber-ruby
|
/lib/timber/util/hash.rb
|
UTF-8
| 880
| 3.0625
| 3
|
[
"ISC"
] |
permissive
|
module Timber
module Util
# @private
module Hash
SANITIZED_VALUE = '[sanitized]'.freeze
extend self
# Deeply reduces a hash into a new hash, passing the current key, value,
# and accumulated map up to that point. This allows the caller to
# conditionally rebuild the hash.
def deep_reduce(hash, &block)
new_hash = {}
hash.each do |k, v|
v = if v.is_a?(::Hash)
deep_reduce(v, &block)
else
v
end
block.call(k, v, new_hash)
end
new_hash
end
def sanitize(hash, keys_to_sanitize)
hash.each_with_object({}) do |(k, v), h|
k = k.to_s.downcase
if keys_to_sanitize.include?(k)
h[k] = SANITIZED_VALUE
else
h[k] = v
end
end
end
end
end
end
| true
|
e9f764b5a98b86f3a627f41ef0dca185313c8d2f
|
Ruby
|
tolsen/rubydav
|
/lib/rubydav/auth_world.rb
|
UTF-8
| 5,497
| 2.75
| 3
|
[] |
no_license
|
# $Id$
# $URL$
require 'bsearch'
require 'uri'
module RubyDav
# represents a set of protection spaces for a request object
class AuthWorld
def initialize
@spaces = []
end
def get_auth url, client_opts
l = @spaces.bsearch_lower_boundary { |x| x.prefix <=> url }
# skip the one found if it's not the same authority
l -= 1 unless l < @spaces.length && self.class.equal_authority?(url, @spaces[l].prefix)
digest_auth = basic_auth = nil
@spaces[0..l].reverse.each do |s|
# if we're now looking at a non-matching authority, then we've passed
# all matching authorities
return nil unless self.class.equal_authority? url, s.prefix
if self.class.prefix? s.prefix, url
digest_auth = s.get_auth :digest, client_opts if digest_auth.nil?
# prefer digest authentication
return digest_auth if digest_auth && !client_opts[:force_basic_auth]
basic_auth = s.get_auth :basic, client_opts if basic_auth.nil?
return basic_auth if basic_auth && client_opts[:force_basic_auth]
end
end
return basic_auth if basic_auth
return nil
end
def add_auth auth, url, client_opts
raise "malformed url: #{url}" unless
url =~ /^https?:\/\/[^\/]/
url = self.class.ensure_trailing_slash_if_no_hierarchy(url)
self.send "add_auth_#{auth.scheme.to_s}".to_sym, auth, url, client_opts
end
private
# url's without any path must end with trailing slash
# e.g. http://example.com is not ok
def add_auth_basic auth, url, client_opts
l = @spaces.bsearch_lower_boundary { |x| x.prefix <=> url }
space = nil
if l < @spaces.length && self.class.prefix?(@spaces[l].prefix, url)
space = @spaces[l]
else
prefix = url.sub /[^\/]+$/, '' # chop off until last slash
space = AuthSpace.new prefix
@spaces.insert l, space
end
space.update_auth auth, client_opts
end
# url's without any path must end with trailing slash
# e.g. http://example.com is not ok
def add_auth_digest auth, url, client_opts
uri = URI.parse url
abs_domains = if auth.domain.nil? || auth.domain.empty?
[ /^https?:\/\/[^\/]+\//.match(url)[0] ]
else
auth.domain.map do |d|
domain_uri = URI.parse d
d = URI.join(url, d).to_s if domain_uri.relative?
d
end
end
abs_domains.each do |domain|
l = @spaces.bsearch_lower_boundary { |x| x.prefix <=> domain }
space = l < @spaces.length ? @spaces[l] : nil
if space.nil? || space.prefix != domain
space = AuthSpace.new domain
@spaces.insert l, space
end
space.update_auth auth, client_opts
end
end
class << self
def prefix? url1, url2
u1, u2 = url1, ensure_trailing_slash_if_no_hierarchy(url2)
return false if u1.length > u2.length
return true if u1 == u2
# it is a prefix if u1 matches the beginning of u2 and
# u1 ends with a slash or the character in u2 after
# matching u1 is a slash
return true if
u2[0..(u1.length - 1)] == u1 &&
(u1[-1].chr == '/' || u2[u1.length].chr == '/')
return false
end
def ensure_trailing_slash_if_no_hierarchy url
url.sub(/(https?:\/\/[^\/]+)$/, '\1/')
end
def equal_authority? url1, url2
uri1, uri2 = URI.parse(url1), URI.parse(url2)
uri1.scheme == uri2.scheme &&
uri1.host == uri2.host &&
uri1.port == uri2.port
end
end
end
# represents a protection space
class AuthSpace
include Comparable
# URI prefix
# Must be an absolute URI
attr_reader :prefix
def initialize prefix
@prefix = prefix
@auth_tables = {
:digest => AuthTable.new,
:basic => AuthTable.new
}
end
def update_auth auth, client_opts
# sanity check. This should be checked before we get here
client_realm = client_opts[:realm]
raise ArgumentError, "Internal error: realms do not match" if
!client_realm.nil? && client_realm != auth.realm
@auth_tables[auth.scheme][client_opts] = auth
end
def get_auth scheme, client_opts
return @auth_tables[scheme][client_opts]
end
def <=> other
self.prefix <=> other.prefix
end
end
class AuthTable
@@auth_keys = [:username, :password, :basic_creds,
:digest_a1, :realm, :digest_session]
def [] opts
auth = @tbl[extract_auth_values(opts)]
return auth unless
auth.nil? && opts.include?(:digest_session) && !File.zero?(opts[:digest_session])
auth = DigestAuth.load opts[:digest_session]
auth.username = opts[:username]
auth.password = opts[:password]
auth.h_a1 = opts[:digest_a1]
auth
rescue Errno::ENOENT
nil
end
def []= opts, auth
@tbl[extract_auth_values(opts)] = auth
auth.dump_sans_creds opts[:digest_session] if opts.include? :digest_session
end
def initialize
@tbl = {}
end
private
def extract_auth_values opts
opts.values_at *@@auth_keys
end
end
end
| true
|
72e3348403ea8802e0e89e0d03a8156134d9dd33
|
Ruby
|
b09/project_dashboard
|
/models/project.rb
|
UTF-8
| 1,745
| 3.09375
| 3
|
[] |
no_license
|
require_relative('../db/sql_runner')
class Project
attr_reader :id
attr_accessor :name, :budget, :start_date, :type, :description
def initialize(options)
@id = options['id'].to_i if options['id']
@name = options['name']
@budget = options['budget'].to_i
@type = options['type']
@start_date = options['start_date']
@description = options['description']
end
def save
sql = "
INSERT INTO projects (name, budget, start_date, type, description)
VALUES ($1, $2, $3, $4, $5) RETURNING id"
values = [@name, @budget, @start_date, @type, @description]
pg_hash = SqlRunner.run(sql, values)
@id = pg_hash.first['id'].to_i
end
def self.all
sql = "
SELECT * FROM projects
"
result = SqlRunner.run(sql)
return result.map { |project| Project.new(project) }
end
def self.delete(id)
sql = " DELETE FROM projects WHERE id = $1 "
values = [id]
SqlRunner.run(sql, values)
end
def self.delete_all
sql = " DELETE FROM projects"
SqlRunner.run(sql)
end
def self.find(id)
sql = " SELECT * FROM projects WHERE id = $1"
values = [id]
result = SqlRunner.run(sql, values)
return Project.new(result.first)
end
def update()
sql = "
UPDATE projects SET (name, budget, start_date, type, description) =
($1, $2, $3, $4, $5) WHERE id = $6
"
values = [@name, @budget, @start_date, @type, @description, @id]
SqlRunner.run(sql, values)
end
def members
sql = "SELECT * FROM members INNER JOIN projectteams ON
projectteams.member_id = members.id WHERE projectteams.project_id = $1;"
values = [@id]
results = SqlRunner.run(sql, values)
return results.map { |member| Member.new(member) }
end
end
| true
|
cce8620540a30956e3058f6d6c5c7323dfbd986d
|
Ruby
|
dcoleman21/BattleShip
|
/lib/game.rb
|
UTF-8
| 5,116
| 3.65625
| 4
|
[] |
no_license
|
require './lib/ship'
require './lib/cell'
require './lib/turn'
require './lib/player'
require './lib/board'
require "pry"
class Game
attr_reader :computer_player,
:human_player,
:computer_ships_sunk,
:human_ships_sunk
def initialize(computer, human)
@computer_player = computer
@human_player = human
@computer_ships_sunk = 0
@human_ships_sunk = 0
@computer_board = @computer_player.board
@human_board = @human_player.board
end
def start
system "clear"
puts "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n" +
" ____ _ _____ _____ _ _____ ____ _ _ ___ ____\n" +
" | __ ) / ||_ _|_ _| | | ____/ ___|| | | |_ _| _ \n" +
" | _ / _| | | | | | | | _| ___ | |_| || || |_) |\n" +
" | |_) / __| | | | | | |___| |___ ___) | _ || || __/\n" +
" |____/_/ | |_| |_| |_____|_____|____/|_| |_|___|_|\n" +
"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
puts ""
puts "Welcome to BATTLESHIP."
sleep(0.8)
puts "Enter p to play. Enter q to quit."
input = gets.chomp
if input == 'p'
computer_place_ships
system "clear"
puts "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n" +
" ____ _ _____ _____ _ _____ ____ _ _ ___ ____\n" +
" | __ ) / ||_ _|_ _| | | ____/ ___|| | | |_ _| _ \n" +
" | _ / _| | | | | | | | _| ___ | |_| || || |_) |\n" +
" | |_) / __| | | | | | |___| |___ ___) | _ || || __/\n" +
" |____/_/ | |_| |_| |_____|_____|____/|_| |_|___|_|\n" +
"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
puts ""
puts "I have laid out my ships on the grid."
sleep(0.8)
puts "You now need to lay out your two ships."
sleep(0.8)
puts "The Cruiser is three units long and the Submarine is two units long."
puts ""
sleep(0.8)
puts "#{@computer_board.render}" +
"Enter the squares for the Cruiser (3 spaces):"
human_set_up_cruiser
puts "#{@human_board.render(true)}" +
"Enter the squares for the Submarine (2 spaces):"
human_set_up_submarine
new_turn
puts "Game Over!"
end
end
def human_set_up_cruiser
cruiser = Ship.new("Cruiser", 3)
loop do
input = gets.chomp
cruiser_coords = input.split(",")
cruiser_coords = cruiser_coords.map do |coordinate|
coordinate.strip()
end
if @human_board.valid_placement?(cruiser, cruiser_coords)
@human_board.place(cruiser, cruiser_coords)
break
end
puts "Those are invalid coordinates. Please try again:"
end
end
def human_set_up_submarine
submarine = Ship.new("Submarine", 2)
loop do
input = gets.chomp
submarine_coords = input.split(",")
submarine_coords = submarine_coords.map do |coordinate|
coordinate.strip()
end
if @human_board.valid_placement?(submarine, submarine_coords)
@human_board.place(submarine, submarine_coords)
break
end
puts "Those are invalid coordinates. Please try again:"
end
end
def new_turn
system 'clear'
turn = Turn.new(computer_player, human_player)
turn.computer_shot
sleep(0.8)
puts "=============COMPUTER BOARD============="
puts "#{@computer_board.render}"
puts "==============PLAYER BOARD=============="
puts "#{@human_board.render(true)}"
puts "Enter coordinate to fire upon"
player_input = gets.chomp
turn.human_shot(player_input)
sleep(0.8)
if @computer_player.has_lost?
puts "=============COMPUTER BOARD============="
puts "#{@computer_board.render}"
puts "==============PLAYER BOARD=============="
puts "#{@human_board.render(true)}"
p "You won!"
sleep(5.0)
self.start
elsif @human_player.has_lost?
puts "=============COMPUTER BOARD============="
puts "#{@computer_board.render}"
puts "==============PLAYER BOARD=============="
puts "#{@human_board.render(true)}"
p "Computer won!"
sleep(5.0)
self.start
else
new_turn
end
end
def computer_place_ships
computer_cruiser = Ship.new("Cruiser", 3)
computer_submarine = Ship.new("Submarine", 2)
loop do
cruiser_coords = []
until cruiser_coords.length == computer_cruiser.length do
cruiser_coords << @computer_board.cells.keys.sample
end
if @computer_board.valid_placement?(computer_cruiser, cruiser_coords)
@computer_board.place(computer_cruiser, cruiser_coords)
break
end
end
loop do
submarine_coords = []
until submarine_coords.length == computer_submarine.length do
submarine_coords << @computer_board.cells.keys.sample
end
if @computer_board.valid_placement?(computer_submarine, submarine_coords)
@computer_board.place(computer_submarine, submarine_coords)
break
end
end
end
end
| true
|
330b047e829de1cd9b5161987d60b1f4f5c967ae
|
Ruby
|
dnnnn-yu/session_old
|
/app/models/concerns/master.rb
|
UTF-8
| 1,339
| 2.71875
| 3
|
[] |
no_license
|
module Master
PREFECTURES = {
北海道: 1, 青森県: 2, 岩手県: 3, 宮城県: 4, 秋田県: 5, 山形県: 6, 福島県: 7,
茨城県: 8, 栃木県: 9, 群馬県: 10, 埼玉県: 11, 千葉県: 12, 東京都: 13, 神奈川県: 14,
新潟県: 15, 富山県: 16, 石川県: 17, 福井県: 18, 山梨県: 19, 長野県: 20,
岐阜県: 21, 静岡県: 22, 愛知県: 23, 三重県: 24,
滋賀県: 25, 京都府: 26, 大阪府: 27, 兵庫県: 28, 奈良県: 29, 和歌山県: 30,
鳥取県: 31, 島根県: 32, 岡山県: 33, 広島県: 34, 山口県: 35,
徳島県: 36, 香川県: 37, 愛媛県: 38, 高知県: 39,
福岡県: 40, 佐賀県: 41, 長崎県: 42, 熊本県: 43, 大分県: 44, 宮崎県: 45, 鹿児島県: 46, 沖縄県: 47
}
REGION = {
北海道: [1],
東北地方: [2, 3, 4, 5, 6, 7],
関東地方: [8, 9, 10, 11, 12, 13, 14],
中部地方: [15, 16, 17, 18, 19, 20, 21, 22, 23],
近畿地方: [24, 25, 26, 27, 28, 29, 30],
中国地方: [31, 32, 33, 34, 35],
四国地方: [36, 37, 38, 39],
九州地方: [40, 41, 42, 43, 44, 45, 46],
沖縄: [47]
}
def belongs_region(pref_number)
REGION.each do |region_name, pref_numbers|
{ region_name: region_name, pref_numbers: pref_numbers } if pref_numbers.include?(pref_number)
end
end
end
| true
|
adb43ef47ef707cf33b75ccea6288ca3540c9b8b
|
Ruby
|
ccallebs/Moon-Critter
|
/lib/map.rb
|
UTF-8
| 924
| 3.234375
| 3
|
[] |
no_license
|
require 'gosu'
require './lib/map_tile'
class Map
attr_accessor :window, :tiles
def initialize(window)
@window = window
@char_map = []
populate_world_map
build_tiles
end
def draw
horizontal_tiles = 800 / 50
vertical_tiles = 800 / 50
horizontal_tiles.times do |x|
vertical_tiles.times do |y|
if @tiles[x][y].nil?
MapTile.new(@window, @char_map[x][y], x * 50, y * 50).draw
else
@tiles[x][y].draw
end
end
end
end
private
def populate_world_map
text = File.open("./assets/small_farm.dat").read
line_counter = 0
char_counter = 0
text.each_line do |line|
@char_map.push []
line.each_char do |char|
@char_map[line_counter].push char
end
line_counter += 1
end
end
def build_tiles
@tiles = Array.new(@char_map.length, Array.new(@char_map[0].length))
end
end
| true
|
a127e96b5f40b8bd45b0c089a81a63c37022ec47
|
Ruby
|
Skeyelab/enoCards
|
/db/seeds.rb
|
UTF-8
| 7,081
| 2.78125
| 3
|
[] |
no_license
|
EnoCard.create!([
{text: "Abandon normal instruments"},
{text: "Accept advice"},
{text: "Accretion"},
{text: "A line has two sides"},
{text: "Allow an easement (an easement is the abandonment of a stricture)"},
{text: "Are there sections? Consider transitions"},
{text: "Ask people to work against their better judgement"},
{text: "Ask your body"},
{text: "Assemble some of the instruments in a group and treat the group"},
{text: "Balance the consistency principle with the inconsistency principle"},
{text: "Be dirty"},
{text: "Breathe more deeply"},
{text: "Bridges -build -burn"},
{text: "Cascades"},
{text: "Change instrument roles"},
{text: "Change nothing and continue with immaculate consistency"},
{text: "Children's voices -speaking -singing"},
{text: "Cluster analysis"},
{text: "Consider different fading systems"},
{text: "Consult other sources -promising -unpromising"},
{text: "Convert a melodic element into a rhythmic element"},
{text: "Courage!"},
{text: "Cut a vital connection"},
{text: "Decorate, decorate"},
{text: "Define an area as `safe' and use it as an anchor"},
{text: "Destroy -nothing -the most important thing"},
{text: "Discard an axiom"},
{text: "Disconnect from desire"},
{text: "Discover the recipes you are using and abandon them"},
{text: "Distorting time"},
{text: "Do nothing for as long as possible"},
{text: "Don't be afraid of things because they're easy to do"},
{text: "Don't be frightened of cliches"},
{text: "Don't be frightened to display your talents"},
{text: "Don't break the silence"},
{text: "Don't stress one thing more than another"},
{text: "Do something boring"},
{text: "Do the washing up"},
{text: "Do the words need changing?"},
{text: "Do we need holes?"},
{text: "Emphasize differences"},
{text: "Emphasize repetitions"},
{text: "Emphasize the flaws"},
{text: "Faced with a choice, do both (given by Dieter Rot)"},
{text: "Feedback recordings into an acoustic situation"},
{text: "Fill every beat with something"},
{text: "Get your neck massaged"},
{text: "Ghost echoes"},
{text: "Give the game away"},
{text: "Give way to your worst impulse"},
{text: "Go slowly all the way round the outside"},
{text: "Honor thy error as a hidden intention"},
{text: "How would you have done it?"},
{text: "Humanize something free of error"},
{text: "Imagine the music as a moving chain or caterpillar"},
{text: "Imagine the music as a set of disconnected events"},
{text: "Infinitesimal gradations"},
{text: "Intentions -credibility of -nobility of -humility of"},
{text: "Into the impossible"},
{text: "Is it finished?"},
{text: "Is there something missing?"},
{text: "Is the tuning appropriate?"},
{text: "Just carry on"},
{text: "Left channel, right channel, centre channel"},
{text: "Listen in total darkness, or in a very large room, very quietly"},
{text: "Listen to the quiet voice"},
{text: "Look at a very small object, look at its centre"},
{text: "Look at the order in which you do things"},
{text: "Look closely at the most embarrassing details and amplify them"},
{text: "Lowest common denominator check -single beat -single note -single"},
{text: "riff"},
{text: "Make a blank valuable by putting it in an exquisite frame"},
{text: "Make an exhaustive list of everything you might do and do the last"},
{text: "thing on the list"},
{text: "Make a sudden, destructive unpredictable action; incorporate"},
{text: "Mechanicalize something idiosyncratic"},
{text: "Mute and continue"},
{text: "Only one element of each kind"},
{text: "(Organic) machinery"},
{text: "Overtly resist change"},
{text: "Put in earplugs"},
{text: "Remember those quiet evenings"},
{text: "Remove ambiguities and convert to specifics"},
{text: "Remove specifics and convert to ambiguities"},
{text: "Repetition is a form of change"},
{text: "Reverse"},
{text: "Short circuit (example: a man eating peas with the idea that they will"},
{text: "improve his virility shovels them straight into his lap)"},
{text: "Shut the door and listen from outside"},
{text: "Simple subtraction"},
{text: "Spectrum analysis"},
{text: "Take a break"},
{text: "Take away the elements in order of apparent non-importance"},
{text: "Tape your mouth (given by Ritva Saarikko)"},
{text: "The inconsistency principle"},
{text: "The tape is now the music"},
{text: "Think of the radio"},
{text: "Tidy up"},
{text: "Trust in the you of now"},
{text: "Turn it upside down"},
{text: "Twist the spine"},
{text: "Use an old idea"},
{text: "Use an unacceptable color"},
{text: "Use fewer notes"},
{text: "Use filters"},
{text: "Use `unqualified' people"},
{text: "Water"},
{text: "What are you really thinking about just now? Incorporate"},
{text: "What is the reality of the situation?"},
{text: "What mistakes did you make last time?"},
{text: "What would your closest friend do?"},
{text: "What wouldn't you do?"},
{text: "Work at a different speed"},
{text: "You are an engineer"},
{text: "You can only make one dot at a time"},
{text: "You don't have to be ashamed of using your own ideas"}
])
| true
|
ef31864d341fe7258b67351cb1d7479cbd6f857b
|
Ruby
|
trouni/batch-303
|
/reboot/instacart/instacart_2_with_qty.rb
|
UTF-8
| 1,421
| 3.921875
| 4
|
[] |
no_license
|
# 1. Decide where to ask for qty
# 2. Ask for the qty to the user using qty = gets.chomp and store it
# 3. Store the item & qty in the hash: cart[item] = qty
# 4. Display the details of the bill
store = {
kiwi: 390,
banana: 100,
grapefruit: 1590,
grapes: 50
}
# cart = []
cart = {} # key: item, value: qty
puts "=" * 30
puts " WELCOME TO GAVIN'S LAIR "
puts "=" * 30
puts "Here are the items we have in store today:"
store.each do |item, price|
puts "#{item.capitalize} - ¥#{price}"
end
puts "=" * 30
selected_item = "start"
until selected_item.empty?
puts "Which item do you want? (Press Enter to checkout)"
selected_item = gets.chomp
if store.key?(selected_item.to_sym)
puts "How many of #{selected_item} do you want?"
selected_qty = gets.chomp.to_i
if cart[selected_item]
cart[selected_item] += selected_qty
else
cart[selected_item] = selected_qty
end
elsif selected_item.empty?
break
else
puts "Sorry, we don't have #{selected_item} in our store. Please pick another product."
end
# same as cart.push(selected_item)
end
puts "=" * 30
puts "Thank you for shopping at Gavin's lair."
puts "You ordered:"
cart_total = 0
cart.each do |item, qty|
item_price = store[item.to_sym]
subtotal = qty * item_price
cart_total += subtotal
puts "#{item.capitalize}: #{qty} x ¥#{item_price} = #{subtotal}"
end
puts "Your total is ¥#{cart_total}"
| true
|
4d41162bc94c63650830eea01556b1dabb84e801
|
Ruby
|
SylviaChoong/calculator
|
/calculator.rb
|
UTF-8
| 2,282
| 4.65625
| 5
|
[] |
no_license
|
require "byebug"
# Building a working calculator with functions +, -, *, /
# Print a string to ask for user first input number
# Print a list to ask user if he wants to add, substract, multiply, divide or equalize the equation
# IF user adds, ask for an input number and puts added number
# ELSIF user substracts, ask for an input number and puts substracted number
# ELSIF user multiply, ask for an input number and puts multiplied number
# ELSE user divides, ask for an input number and puts divided number
# Print the list again after each actions
puts "-------***** Calculator *****-------"
print "*****------- Input a number: "
# check if input is an Integer
num = Integer(gets) rescue false
if num != false
loop do
puts "-------***** What do you want to do with the number, " + num.to_s + "? *****-------"
puts "-------***** Add (+) *****-------"
puts "-------***** Substract (-) *****-------"
puts "-------***** Multiply (*) *****-------"
puts "-------***** Divide (/) *****-------"
puts "-------***** End (e) *****-------"
print "-------***** Enter (+) or (-) or (*) or (/): "
choice = gets.chomp
if choice == "+"
print "*****------- Input a number: "
num1 = Integer(gets) rescue false
num += num1
elsif choice == "-"
print "*****------- Input a number: "
num1 = Integer(gets) rescue false
num -= num1
elsif choice == "*"
print "*****------- Input a number: "
num1 = Integer(gets) rescue false
num *= num1
elsif choice == "/"
print "*****------- Input a number: "
num1 = Integer(gets) rescue false
num /= num1.to_f
elsif choice != ("+" || "-" || "*" || "/")
puts "-------***** Error! Input unknown *****-------"
end
print "\n"
puts "-------***** ************ *****-------"
puts "-------***** ************ *****-------"
puts "-------***** ************ *****-------"
print "\n"
puts "-------***** Current total number is: " + num.to_s + " *****-------"
print "\n"
puts "-------***** ************ *****-------"
puts "-------***** ************ *****-------"
puts "-------***** ************ *****-------"
print "\n"
break if choice == "e" || ((choice != "+" && choice != "-" && choice != "*" && choice != "/" ))
end
else
puts "-------***** Error! Input not a number! *****-------"
end
| true
|
e465981172c393a212c94c889e34ed58ac8b3554
|
Ruby
|
CristianCurteanu/proz-scrapper
|
/lib/proz/parser.rb
|
UTF-8
| 1,531
| 2.625
| 3
|
[] |
no_license
|
# frozen_string_literal: true
require 'open-uri'
require 'nokogiri'
module Proz
class Parser
extend ModelAttribute
attribute :source
attribute :first_name
attribute :last_name
attribute :country
attribute :native_language
attribute :target_language
def initialize(url)
self.source = url
@document = Nokogiri::HTML open(url)
end
def extract
attributes.except(:source).each_key do |attribute|
write_attribute(attribute, send(attribute))
end
self
end
private
def full_name
@full_name ||= @document.css('td[valign="top"] strong').text
end
def first_name
@first_name ||= full_name.split(' ').first
end
def last_name
@last_name ||= unless full_name.split(' ').last.eql? first_name
full_name.split(' ').last
end
end
def native_language
@native_language ||= @document.css('tr > td > div.pd_bot').text.split.last[0..-2]
rescue NoMethodError
nil
end
def target_language
@target_language ||= @document.css('#lang_full > .mouseoverText').
each_with_object([]) { |v, a| a << v.text.split(' to ') }.
flatten.uniq - [native_language]
end
def country
@country ||= if @document.css('td[valign="top"] > div').length.eql?(17)
@document.css('td[valign="top"] > div')[5].children.first.text.split.last
end
end
end
end
| true
|
a9c946e4d089f165014de23001b10ac401814882
|
Ruby
|
surfacedamage/pairing-config
|
/Rakefile
|
UTF-8
| 1,699
| 2.921875
| 3
|
[
"MIT"
] |
permissive
|
require 'rubygems'
require 'rake'
desc "attempt to symlink all dot files from the current user's home directory"
task :symlink do
symlink(:skip => '.gitconfig')
end
namespace :symlink do
desc "symlink all dot files (including .gitconfig) from the current user's home directory"
task :pairing do
symlink
end
end
def symlink(options = {})
files = Dir.glob('.*') - ['.git', '.gitmodules', '.', '..'] - [options[:skip]]
files.each do |file|
case
when file_identical?(file) then skip_identical_file(file)
when replace_all_files? then link_file(file)
when file_missing?(file) then link_file(file)
else prompt_to_link_file(file)
end
end
end
# FILE CHECKS
def file_exists?(file)
File.exists?("#{ENV['HOME']}/#{file}")
end
def file_missing?(file)
!file_exists?(file)
end
def file_identical?(file)
File.identical? file, File.join(ENV['HOME'], "#{file}")
end
def replace_all_files?
@replace_all == true
end
# FILE ACTIONS
def prompt_to_link_file(file)
print "overwrite? ~/#{file} [ynaq] "
case $stdin.gets.chomp
when 'y' then replace_file(file)
when 'a' then replace_all(file)
when 'q' then exit
else skip_file(file)
end
end
def link_file(file)
puts " => symlinking #{file}"
directory = File.dirname(__FILE__)
sh("ln -s #{File.join(directory, file)} #{ENV['HOME']}/#{file}")
end
def replace_file(file)
sh "rm -rf #{ENV['HOME']}/#{file}"
link_file(file)
end
def replace_all(file)
@replace_all = true
replace_file(file)
end
def skip_file(file)
puts " => skipping ~/#{file}"
end
def skip_identical_file(file)
puts " => skipping identical ~/#{file}"
end
| true
|
c0f802aad0a2a5b37eea3d9a6946d3a40a031cec
|
Ruby
|
Ric-Lavers/slotwars
|
/slotwars/app/models/slot.rb
|
UTF-8
| 619
| 2.75
| 3
|
[] |
no_license
|
class Slot < ApplicationRecord
def initialize
@q = "bb-8.png"
@k = "porg.png"
@a = "bad_guy.png"
@cards = [@q,@k,@a]
@totalscore = 0
end
def spin
result = []
(0..2).each{|card|
result << @cards.sample
}
@result = result
end
def score
if @result == [@a,@a,@a]
return 50
elsif @result == [@k,@k,@k]
return 35
elsif @result == [@q,@q,@q]
return 20
elsif @result.count(@a) == 2
return 5
elsif @result.count(@k) == 2
return 5
elsif @result.count(@q) == 2
return 5
else
return 0
end
end
end
| true
|
ab0de473061f57bb3f8f76d60af255a254bef91f
|
Ruby
|
LHJE/war_or_peace_redux
|
/test/deck_test.rb
|
UTF-8
| 1,516
| 3.328125
| 3
|
[] |
no_license
|
require 'minitest/autorun'
require 'minitest/pride'
require './lib/card'
require './lib/deck'
class DeckTest < Minitest::Test
def setup
@card_1 = Card.new(:diamond, 'Queen', 12)
@card_2 = Card.new(:heart, 'Ace', 14)
@card_3 = Card.new(:spade, 'Three', 3)
@card_4 = Card.new(:club, 'four', 4)
@card_5 = Card.new(:diamond, 'five', 5)
@card_6 = Card.new(:heart, 'six', 6)
@deck = Deck.new([@card_1, @card_2])
end
def test_it_exists
assert_instance_of Deck, @deck
end
def test_it_has_readable_attributes
assert_equal [@card_1, @card_2], @deck.cards
end
def test_rank_of_cards_at
assert_equal 14, @deck.rank_of_card_at(1)
end
def test_high_ranking_cards
deck_2 = Deck.new([@card_1, @card_2, @card_3, @card_4])
assert_equal [@card_1, @card_2], deck_2.high_ranking_cards
end
def test_percent_high_ranking_cards
deck_3 = Deck.new([@card_1, @card_2, @card_3, @card_4, @card_5, @card_6])
assert_equal 33.33, deck_3.percent_high_ranking
end
def test_remove_card
deck_4 = Deck.new([@card_1, @card_2, @card_3, @card_4])
assert_equal [@card_1, @card_2, @card_3, @card_4], deck_4.cards
deck_4.remove_card
assert_equal [@card_2, @card_3, @card_4], deck_4.cards
end
def test_add_card
deck_5 = Deck.new([@card_1, @card_2])
assert_equal [@card_1, @card_2], deck_5.cards
card_7 = Card.new(:spade, 'Seven', 7)
deck_5.add_card(card_7)
assert_equal [@card_1, @card_2, card_7], deck_5.cards
end
end
| true
|
9c316a286c3855bda7f2f204aedb24ee1e59c800
|
Ruby
|
mepiphany/scraper_rails_api_jungle
|
/app/services/scraper.rb
|
UTF-8
| 1,402
| 2.75
| 3
|
[] |
no_license
|
require 'open-uri'
require 'nokogiri'
class Scraper
attr_reader :asin, :doc
include ProductInformationAttr
include CategoryBaseInformationAttr
include CategorySubInformationAttr
def initialize(asin)
@asin = asin
@doc = Nokogiri::HTML(open("https://www.amazon.com/dp/#{asin}"))
end
def create_record
data_entry = product_info_data_entry(doc, asin)
if product_does_not_exist(asin)
product_information = ProductInformation.new(data_entry)
create_base_category(product_information.id) if product_information.save
return product_information.id
else
product_information = ProductInformation.find_by(asin: asin)
product_information.update_attributes(data_entry)
return product_information.id
end
end
def create_base_category(product_info_id)
data_entry = base_category_data_entry(doc, product_info_id)
if category_does_not_exist(product_info_id, 'base')
Category.create(data_entry)
else
category = Category.find_by(product_information_id: product_info_id, category_type: 'base')
category.update_attriutes(data_entry)
end
end
def product_does_not_exist(asin)
ProductInformation.find_by(asin: asin).nil?
end
def category_does_not_exist(product_info_id, category_type)
Category.find_by(product_information_id: product_info_id, category_type: category_type).nil?
end
end
| true
|
ba54dc72262eeff120101877e6476d2fd0b8dfd4
|
Ruby
|
RomanPlyazhnic/practice_parce
|
/app/controllers/main_controller.rb
|
UTF-8
| 1,624
| 2.640625
| 3
|
[] |
no_license
|
require './lib/classes/PageDownloader'
require './lib/classes/Parser'
require './lib/classes/GenresStorage'
require 'kaminari'
class MainController < ApplicationController
helper QueryHelper
def index
@genres = GenresStorage.genres
@animes = anime_selector(@animes, params)
end
def search
@genres = GenresStorage.genres
@animes = anime_selector(@animes, params, true)
render :index
end
def parse
Parser.new.parse
redirect_to :action => "index"
end
private
def anime_selector(animes, params, search = false)
@selected_genres = Hash.new
@genres.each do |genre|
@selected_genres[genre] = params[genre]
end
order = params[:order] == nil ? :rank : params[:order].to_sym
animes = Anime.order(order)
if params[:search_field] != nil
animes = animes.where("lower(name) LIKE lower('%#{params[:search_field]}%')")
end
if !array_selected_genres(@selected_genres).empty?
animes = animes.where("name in (
select animes.name from animes
join animegenres on animes.id = animegenres.anime_id
join genres on animegenres.genre_id = genres.id
where genres.genre in (?)
group by name having count(*) = ?
order by animes.name)",
array_selected_genres(@selected_genres), array_selected_genres(@selected_genres).length)
end
animes = animes.page(params[:page])
end
def array_selected_genres(hash)
array_genres = Array.new
hash.each do |key, value|
array_genres.push(key) if value == "true"
end
return array_genres
end
end
| true
|
05069188d70bf9bedba8a55d2cc0be0ea465876e
|
Ruby
|
Canar/pulseaudio_simple_ffi
|
/lib/pulseaudio_simple_ffi.rb
|
UTF-8
| 2,939
| 2.53125
| 3
|
[] |
no_license
|
#!/usr/bin/env ruby
require 'ffi'
module PulseAudioSimpleFFI
extend FFI::Library
ffi_lib 'pulse-simple'
class IntPtr < FFI::Struct
layout :value, :int
end
enum :sample_format, [
:u8, :alaw, :ulaw,
:s16le, :s16be,
:f32le, :f32be,
:s32le, :s32be,
:s24le, :s24be,
:s2432le, :s2432be,
:max, -1,:invalid
]
enum :stream_direction, [
:nodirection, # invalid direction
:playback, # playback stream
:record, # record stream
:upload # sample upload stream
]
class PulseSampleSpec < FFI::Struct
layout :format, :sample_format,
:rate, :uint32,
:channels, :uint8
end
attach_function :simple_new, :pa_simple_new, [
:string, # server name or NULL for default
:string, # A descriptive name for this client (application name, ...)
:stream_direction, # Open this stream for recording or playback?
:string, # Sink (resp. source) name, or NULL for default
:string, # A descriptive name for this stream (application name, song title, ...)
PulseSampleSpec, # The sample type to use
:pointer, # (UNIMPLEMENTED) The channel map to use, or NULL for default
:pointer, # (UNIMPLEMENTED) Buffering attributes, or NULL for default
IntPtr # A pointer where the error code is stored when the routine returns NULL. It is OK to pass NULL here.
], :pointer # Returns type pa_simple*, intentionally undefined in user API.
attach_function :simple_get_latency, :pa_simple_get_latency, [:pointer,:int], :uint64
attach_function :simple_write, :pa_simple_write, [:pointer,:strptr,:uint64,IntPtr], :int
attach_function :simple_free, :pa_simple_free, [:pointer], :void
class PulseAudioSimpleO
def initialize name,desc,server:nil,device:nil,map:nil,buffer:nil,format: :f32le,rate:44100,channels:2
ps=PulseSampleSpec.new
ps[:format]=format
ps[:rate]=rate
ps[:channels]=channels
@err=IntPtr.new
@err[:value]=0
# "correct form" is commented below, map and buffer unimplemented in active code
#@handle=PulseAudioSimpleFFI.simple_new(server,name,:playback,device,desc,ps,map,buffer,@err)
@handle=PulseAudioSimpleFFI.simple_new(server,name,:playback,device,desc,ps,nil,nil,@err)
throw [@err[:value],'Error in simple_new(), PulseSimpleO.initialize.'] unless 0 == @err[:value]
end
def write buf
@err[:value]=0
PulseAudioSimpleFFI.simple_write @handle,buf,buf.length,@err
throw [@err[:value],'Error in simple_write(), PulseSimpleO.write.'] unless 0 == @err[:value]
end
def free
PulseAudioSimpleFFI.simple_free @handle
@handle=nil
end
def latency
@err[:value]=0
val=PulseAudioSimpleFFI.simple_get_latency @handle,@err
throw [@err[:value],'Error in simple_get_latency(), PulseSimpleO.latency.'] unless 0 == @err[:value]
val
end
alias :close :free
end
end
| true
|
53969eb9d59aa8cabf35d5ff3d8bd2c01f2b3e89
|
Ruby
|
hilben/ffi_rust
|
/test.rb
|
UTF-8
| 405
| 2.546875
| 3
|
[] |
no_license
|
require "ffi"
module Rust
extend FFI::Library
ffi_lib "target/release/test.dll"
ffi_convention :stdcall
attach_function :square, [:int ], :int
end
module Win32
extend FFI::Library
ffi_lib 'user32'
attach_function :messageBox,
:MessageBoxA,[ :pointer, :string, :string, :long ], :int
end
Win32.messageBox(nil, "Hello Windows! Rust calculated: #{Rust.square(100)}", "nice", 0x40)
| true
|
42efb986fd698f0e974ecc7c0244c507bd8ca46e
|
Ruby
|
npl22/dynamic-array
|
/lib/queue_with_max.rb
|
UTF-8
| 1,248
| 3.859375
| 4
|
[] |
no_license
|
require_relative 'ring_buffer'
class QueueWithMax
attr_accessor :store, :maxqueue
def initialize
@store = RingBuffer.new
@maxqueue = RingBuffer.new
end
# Only 2 pushes, so it's constant, not with respect to O(n)
def enqueue(el)
@maxqueue.push(el) if @maxqueue.length.zero?
@store.push(el)
while @maxqueue[0] < el
@maxqueue.pop
break if @maxqueue.length.zero?
end
@maxqueue.push(el)
end
def dequeue
val = @store.shift
@maxqueue.shift if val == @maxqueue[0]
val
end
def max
@maxqueue[0]
end
def length
@store.length
end
end
# Goal, you want to know what the maximum value of the queue at all times
# two instances of a ring buffer, one for the queue, one for the max
# q = QueueWithMax
# q.max --> max in O(1) time instead of arr.max which is O(n) time
# dequeueing is easy, enqueueing can be constant time amortized, once
# you get a new max, pop off all of the numbers less than the max and
# then push it into the maxqueue. This way the max will always be the
# first element and you can look it up in constant time. This is O(1)
# amortized because you only pop in O(n) when you get a new max. Pushes
# with numbers less than the current max are "free"
| true
|
7180f4c910b4ecddce9dfd7bf28c9b51a7f0ebc4
|
Ruby
|
kindrowboat/hexflex
|
/lib/hexflex/glue_template.rb
|
UTF-8
| 1,382
| 2.78125
| 3
|
[
"MIT"
] |
permissive
|
require 'hexflex/base_template'
require 'hexflex/triangle_grid'
require 'hexflex/rvg_template_vectorizer'
require 'hexflex/triangle'
module Hexflex
class GlueTemplate < BaseTemplate
def make_vector
RvgTemplateVectorizer.new(triangle_grid).vectorize
end
private
def triangle_grid
TriangleGrid.new.tap do |grid|
grid.place(blank_triangle, 0, 0)
grid.place(blank_triangle, 0, 9)
grid.place(sides[0].triangles[0], 0, 1)
grid.place(sides[0].triangles[1], 1, 3)
grid.place(sides[0].triangles[2], 1, 4)
grid.place(sides[0].triangles[3], 0, 6)
grid.place(sides[0].triangles[4], 0, 7)
grid.place(sides[0].triangles[5], 1, 9)
grid.place(sides[2].triangles[0], 0, 3)
grid.place(sides[2].triangles[1], 1, 5)
grid.place(sides[2].triangles[2], 1, 6)
grid.place(sides[2].triangles[3], 0, 8)
grid.place(sides[2].triangles[4], 1, 0)
grid.place(sides[2].triangles[5], 0, 2)
grid.place(sides[1].triangles[0], 0, 5)
grid.place(sides[1].triangles[1], 1, 7)
grid.place(sides[1].triangles[2], 1, 8)
grid.place(sides[1].triangles[3], 1, 1)
grid.place(sides[1].triangles[4], 1, 2)
grid.place(sides[1].triangles[5], 0, 4)
end
end
def blank_triangle
Triangle.place_holder
end
end
end
| true
|
f18e1ced43673285a94f1799f0b0d6472bd9c9f4
|
Ruby
|
rachel1032/kwk-l1-say-hello-methods-ruby-kwk-students-l1-bos-070918
|
/say_hello.rb
|
UTF-8
| 278
| 3.96875
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
# Build your say_hello method here
your_name = ("Nimisha")
my_name = ("Rachel")
def say_hello1 (your_name, my_name)
puts "Hello #{your_name}! I'm #{my_name}"
end
say_hello1("Nimisha","Rachel")
def say_hello (name = "Ruby Programmer")
puts "Hello #{name}!"
end
say_hello
| true
|
4366aa2a4738b28f9f8e8740a6e93a7bfcfd472b
|
Ruby
|
rosyatrandom/ruby-code-line-counter
|
/lib/predicates_checker.rb
|
UTF-8
| 503
| 3.03125
| 3
|
[] |
no_license
|
require_relative 'counter'
class PredicatesChecker
def initialize
@checks = {}
end
def []= name, check
@checks[name] = check
end
def check_item item
@checks.transform_values { |check| check.call item }
end
def counts_for items
items
.map { |item| check_item item }
.each_with_object(Counter.new @checks.keys) do |results, counter|
true_values = results.filter { |_, result| result }.keys
counter.increment_for true_values
end
end
end
| true
|
6a794722a00ec4b77a18808b6495024c08545991
|
Ruby
|
dalibor/bitfields
|
/spec/bitfields_spec.rb
|
UTF-8
| 13,317
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
require 'spec_helper'
class User < ActiveRecord::Base
include Bitfields
bitfield :bits, 1 => :seller, 2 => :insane, 4 => :stupid
end
class UserWithBitfieldOptions < ActiveRecord::Base
include Bitfields
bitfield :bits, 1 => :seller, 2 => :insane, 4 => :stupid, :scopes => false
end
class MultiBitUser < ActiveRecord::Base
self.table_name = 'users'
include Bitfields
bitfield :bits, 1 => :seller, 2 => :insane, 4 => :stupid
bitfield :more_bits, 1 => :one, 2 => :two, 4 => :four
end
class UserWithoutScopes < ActiveRecord::Base
self.table_name = 'users'
include Bitfields
bitfield :bits, 1 => :seller, 2 => :insane, 4 => :stupid, :scopes => false
end
class UserWithoutSetBitfield < ActiveRecord::Base
self.table_name = 'users'
include Bitfields
end
class InheritedUser < User
end
class GrandchildInheritedUser < InheritedUser
end
# other children should not disturb the inheritance
class OtherInheritedUser < UserWithoutSetBitfield
self.table_name = 'users'
bitfield :bits, 1 => :seller_inherited
end
class InheritedUserWithoutSetBitfield < UserWithoutSetBitfield
end
class OverwrittenUser < User
bitfield :bits, 1 => :seller_inherited
end
class BitOperatorMode < ActiveRecord::Base
self.table_name = 'users'
include Bitfields
bitfield :bits, 1 => :seller, 2 => :insane, :query_mode => :bit_operator
end
class WithoutThePowerOfTwo < ActiveRecord::Base
self.table_name = 'users'
include Bitfields
bitfield :bits, :seller, :insane, :stupid, :query_mode => :bit_operator
end
class WithoutThePowerOfTwoWithoutOptions < ActiveRecord::Base
self.table_name = 'users'
include Bitfields
bitfield :bits, :seller, :insane
end
class CheckRaise < ActiveRecord::Base
self.table_name = 'users'
include Bitfields
end
class ManyBitsUser < User
self.table_name = 'users'
end
describe Bitfields do
before do
User.delete_all
end
describe :bitfields do
it "parses them correctly" do
User.bitfields.should == {:bits => {:seller => 1, :insane => 2, :stupid => 4}}
end
it "is fast for huge number of bits" do
bits = {}
0.upto(20) do |bit|
bits[2**bit] = "my_bit_#{bit}"
end
Timeout.timeout(0.2) do
ManyBitsUser.class_eval{ bitfield :bits, bits }
end
end
end
describe :bitfield_options do
it "parses them correctly when not set" do
User.bitfield_options.should == {:bits => {}}
end
it "parses them correctly when set" do
UserWithBitfieldOptions.bitfield_options.should == {:bits => {:scopes => false}}
end
end
describe :bitfield_column do
it "raises a nice error when i use a unknown bitfield" do
lambda{
User.bitfield_column(:xxx)
}.should raise_error(RuntimeError, 'Unknown bitfield xxx')
end
end
describe :bitfield_values do
it "contains all bits with values" do
User.new.bitfield_values(:bits).should == {:insane=>false, :stupid=>false, :seller=>false}
User.new(:bits => 15).bitfield_values(:bits).should == {:insane=>true, :stupid=>true, :seller=>true}
end
end
describe 'attribute accessors' do
it "has everything on false by default" do
User.new.seller.should == false
User.new.seller?.should == false
end
it "is true when set to true" do
User.new(:seller => true).seller.should == true
end
it "is true when set to truthy" do
User.new(:seller => 1).seller.should == true
end
it "is false when set to false" do
User.new(:seller => false).seller.should == false
end
it "is false when set to falsy" do
User.new(:seller => 'false').seller.should == false
end
it "stays true when set to true twice" do
u = User.new
u.seller = true
u.seller = true
u.seller.should == true
u.bits.should == 1
end
it "stays false when set to false twice" do
u = User.new(:bits => 3)
u.seller = false
u.seller = false
u.seller.should == false
u.bits.should == 2
end
it "changes the bits when setting to false" do
user = User.new(:bits => 7)
user.seller = false
user.bits.should == 6
end
it "does not get negative when unsetting high bits" do
user = User.new(:seller => true)
user.stupid = false
user.bits.should == 1
end
it "changes the bits when setting to true" do
user = User.new(:bits => 2)
user.seller = true
user.bits.should == 3
end
it "does not get too high when setting high bits" do
user = User.new(:bits => 7)
user.seller = true
user.bits.should == 7
end
it "has _was" do
user = User.new
user.seller_was.should == false
user.seller = true
user.save!
user.seller_was.should == true
end
it "has _changed?" do
user = User.new
user.seller_changed?.should == false
user.seller = true
user.seller_changed?.should == true
user.save!
user.seller_changed?.should == false
end
it "has _change" do
user = User.new
user.seller_change.should == nil
user.seller = true
user.seller_change.should == [false, true]
user.save!
user.seller_change.should == nil
end
it "has _became_true?" do
user = User.new
user.seller_became_true?.should == false
user.seller = true
user.seller_became_true?.should == true
user.save!
user.seller_became_true?.should == false
user.seller = true
user.seller_became_true?.should == false
end
end
describe '#bitfield_changes' do
it "has no changes by defaut" do
User.new.bitfield_changes.should == {}
end
it "records a change when setting" do
u = User.new(:seller => true)
u.changes.should == {'bits' => [0,1]}
u.bitfield_changes.should == {'seller' => [false, true]}
end
end
describe :bitfield_sql do
it "includes true states" do
User.bitfield_sql({:insane => true}, :query_mode => :in_list).should == 'users.bits IN (2,3,6,7)' # 2, 1+2, 2+4, 1+2+4
end
it "includes invalid states" do
User.bitfield_sql({:insane => false}, :query_mode => :in_list).should == 'users.bits IN (0,1,4,5)' # 0, 1, 4, 4+1
end
it "can combine multiple fields" do
User.bitfield_sql({:seller => true, :insane => true}, :query_mode => :in_list).should == 'users.bits IN (3,7)' # 1+2, 1+2+4
end
it "can combine multiple fields with different values" do
User.bitfield_sql({:seller => true, :insane => false}, :query_mode => :in_list).should == 'users.bits IN (1,5)' # 1, 1+4
end
it "combines multiple columns into one sql" do
sql = MultiBitUser.bitfield_sql({:seller => true, :insane => false, :one => true, :four => true}, :query_mode => :in_list)
sql.should == 'users.bits IN (1,5) AND users.more_bits IN (5,7)' # 1, 1+4 AND 1+4, 1+2+4
end
it "produces working sql" do
u1 = MultiBitUser.create!(:seller => true, :one => true)
u2 = MultiBitUser.create!(:seller => true, :one => false)
u3 = MultiBitUser.create!(:seller => false, :one => false)
conditions = MultiBitUser.bitfield_sql({:seller => true, :one => false}, :query_mode => :in_list)
MultiBitUser.where(conditions).should == [u2]
end
describe 'with bit operator mode' do
it "generates bit-operator sql" do
BitOperatorMode.bitfield_sql(:seller => true).should == '(users.bits & 1) = 1'
end
it "generates sql for each bit" do
BitOperatorMode.bitfield_sql(:seller => true, :insane => false).should == '(users.bits & 3) = 1'
end
it "generates working sql" do
u1 = BitOperatorMode.create!(:seller => true, :insane => true)
u2 = BitOperatorMode.create!(:seller => true, :insane => false)
u3 = BitOperatorMode.create!(:seller => false, :insane => false)
conditions = MultiBitUser.bitfield_sql(:seller => true, :insane => false)
BitOperatorMode.where(conditions).should == [u2]
end
end
describe 'without the power of two' do
it 'uses correct bits' do
u = WithoutThePowerOfTwo.create!(:seller => false, :insane => true, :stupid => true)
u.bits.should == 6
end
it 'has all fields' do
u = WithoutThePowerOfTwo.create!(:seller => false, :insane => true)
u.seller.should == false
u.insane.should == true
WithoutThePowerOfTwo.bitfield_options.should == {:bits=>{:query_mode=>:bit_operator}}
end
it "can e built without options" do
u = WithoutThePowerOfTwoWithoutOptions.create!(:seller => false, :insane => true)
u.seller.should == false
u.insane.should == true
WithoutThePowerOfTwoWithoutOptions.bitfield_options.should == {:bits=>{}}
end
end
it "checks that bitfields are unique" do
lambda{
CheckRaise.class_eval do
bitfield :foo, :bar, :baz, :bar
end
}.should raise_error(Bitfields::DuplicateBitNameError)
end
it "checks that bitfields are powers of two" do
lambda{
CheckRaise.class_eval do
bitfield :foo, 1 => :bar, 3 => :baz, 4 => :bar
end
}.should raise_error("3 is not a power of 2 !!")
lambda{
CheckRaise.class_eval do
bitfield :foo, 1 => :bar, -1 => :baz, 4 => :bar
end
}.should raise_error("-1 is not a power of 2 !!")
end
end
describe :set_bitfield_sql do
it "sets a single bit" do
User.set_bitfield_sql(:seller => true).should == 'bits = (bits | 1) - 0'
end
it "unsets a single bit" do
User.set_bitfield_sql(:seller => false).should == 'bits = (bits | 1) - 1'
end
it "sets multiple bits" do
User.set_bitfield_sql(:seller => true, :insane => true).should == 'bits = (bits | 3) - 0'
end
it "unsets multiple bits" do
User.set_bitfield_sql(:seller => false, :insane => false).should == 'bits = (bits | 3) - 3'
end
it "sets and unsets in one command" do
User.set_bitfield_sql(:seller => false, :insane => true).should == 'bits = (bits | 3) - 1'
end
it "sets and unsets for multiple columns in one sql" do
sql = MultiBitUser.set_bitfield_sql(:seller => false, :insane => true, :one => true, :two => false)
sql.should == "bits = (bits | 3) - 1, more_bits = (more_bits | 3) - 2"
end
it "produces working sql" do
u = MultiBitUser.create!(:seller => true, :insane => true, :stupid => false, :one => true, :two => false, :four => false)
sql = MultiBitUser.set_bitfield_sql(:seller => false, :insane => true, :one => true, :two => false)
MultiBitUser.update_all(sql)
u.reload
u.seller.should == false
u.insane.should == true
u.stupid.should == false
u.one.should == true
u.two.should == false
u.four.should == false
end
end
describe 'named scopes' do
before do
@u1 = User.create!(:seller => true, :insane => false)
@u2 = User.create!(:seller => true, :insane => true)
end
it "creates them when nothing was passed" do
User.respond_to?(:seller).should == true
User.respond_to?(:not_seller).should == true
end
it "does not create them when false was passed" do
UserWithoutScopes.respond_to?(:seller).should == false
UserWithoutScopes.respond_to?(:not_seller).should == false
end
it "produces working positive scopes" do
User.insane.seller.to_a.should == [@u2]
end
it "produces working negative scopes" do
User.not_insane.seller.to_a.should == [@u1]
end
end
describe 'overwriting' do
it "does not change base class" do
OverwrittenUser.bitfields[:bits][:seller_inherited].should_not == nil
User.bitfields[:bits][:seller_inherited].should == nil
end
it "has inherited methods" do
User.respond_to?(:seller).should == true
OverwrittenUser.respond_to?(:seller).should == true
end
end
describe 'inheritance' do
it "knows overwritten values and normal" do
User.bitfields.should == {:bits=>{:seller=>1, :insane=>2, :stupid=>4}}
OverwrittenUser.bitfields.should == {:bits=>{:seller_inherited=>1}}
end
it "knows overwritten values when overwriting" do
OverwrittenUser.bitfield_column(:seller_inherited).should == :bits
end
it "does not know old values when overwriting" do
-> {
OverwrittenUser.bitfield_column(:seller)
}.should raise_error(RuntimeError)
end
it "knows inherited values without overwriting" do
InheritedUser.bitfield_column(:seller).should == :bits
end
it "has inherited scopes" do
InheritedUser.should respond_to(:not_seller)
end
it "has inherited methods" do
InheritedUser.new.should respond_to(:seller?)
end
it "knows grandchild inherited values without overwriting" do
GrandchildInheritedUser.bitfield_column(:seller).should == :bits
end
it "inherits no bitfields for a user without bitfields set" do
InheritedUserWithoutSetBitfield.bitfields.should be_nil
end
end
describe "rspec matchers" do
subject { User.new }
it { should have_a_bitfield :seller }
it { should_not have_a_bitfield :pickle_eater }
end
end
| true
|
b72c2cdbed9d7310104cdd64e394c60b577a0491
|
Ruby
|
aliashafi/W4D4
|
/TDD/spec/tdd_prac_spec.rb
|
UTF-8
| 1,048
| 2.890625
| 3
|
[] |
no_license
|
require "tdd_prac"
RSpec.describe Array do
describe "Array#my_uniq" do
subject(:arr) {[1,2,3,3,2]}
subject(:answer) { arr.my_uniq }
it "returns an Array" do
expect(answer).to be_a(Array)
end
it "has no duplicates" do
expect(answer.count(3)).to eq(1)
end
it "should return a new array" do
expect(answer.object_id).not_to eq(arr.object_id)
end
end
describe "Array#two_sum" do
subject(:my_array){[-1,0,2,-2,1]}
it "finds all pairs of positions where the elements sum to zero" do
expect(my_array.two_sum).to eq([[0,4], [2,3]])
end
it "returns an Array" do
expect(my_array).to be_a(Array)
end
end
describe "Array#my_transpose" do
subject(:my_arr) {[[0, 1, 2],[3, 4, 5],[6, 7, 8]]}
it "should transpose the array" do
expect(my_arr.my_transpose).to eq(my_arr.transpose)
end
it "it should return a new array" do
expect(my_arr.my_transpose.object_id).not_to eq(my_arr.object_id)
end
end
end
| true
|
145212972a07f939bc1b9f3ebb2f7365ef266e3d
|
Ruby
|
department-of-veterans-affairs/ruby-bgs
|
/lib/bgs/services/rating_profile.rb
|
UTF-8
| 1,769
| 2.578125
| 3
|
[
"CC0-1.0",
"LicenseRef-scancode-public-domain"
] |
permissive
|
# As a work of the United States Government, this project is in the
# public domain within the United States.
#
# Additionally, we waive copyright and related rights in the work
# worldwide through the CC0 1.0 Universal public domain dedication.
module BGS
# Used for finding information about specific ratings
class RatingInformationService < BGS::Base
def bean_name
"RatingInformationService"
end
def self.service_name
"rating_profile"
end
# Returns issues and disabilities for a specific rating (also known as a rating profile)
def find(participant_id:, profile_date:)
response = request(:read_rating_profile, "veteranId": participant_id, "profileDate": profile_date)
# Purposely avoiding much data processing here to do that in the application layer
response.body[:read_rating_profile_response][:rba_profile]
end
# Returns rating profiles within the date range with rating issues for decisions that were at issue
# response includes backfilled ratings
def find_in_date_range(participant_id:, start_date:, end_date:)
response = request(
:get_all_decns_at_issue_for_date_range,
"veteranID": participant_id,
"startDate": start_date,
"endDate": end_date
)
response.body[:get_all_decns_at_issue_for_date_range_response][:decns_at_issue_for_date_range]
end
# Returns current rating profile by participant_id
def find_current_rating_profile_by_ptcpnt_id(participant_id, include_issues=true)
response = request(:read_current_rating_profile_by_ptcpnt_id, "veteranId": participant_id, "includeIssues": include_issues)
response.body[:read_current_rating_profile_by_ptcpnt_id_response][:rba_profile]
end
end
end
| true
|
0bd5f798042d3180481e99818c95ad1c0a555710
|
Ruby
|
norchow/conversor_monedas
|
/src/conversor.rb
|
UTF-8
| 1,729
| 3.703125
| 4
|
[] |
no_license
|
class MoneyAmount
attr_accessor :amount, :currency
def initialize(amount, currency)
self.amount = amount
self.currency = currency
end
def equals(another_amount)
self.amount == another_amount.amount && self.currency == another_amount.currency
end
def *(coefficient)
@newAmount = MoneyAmount.new(self.amount * coefficient, self.currency)
@newAmount
end
def +(another_amount)
#use the first operator's currency
another_amount_with_correct_currency = another_amount.transform_to(self.currency)
@newAmount = MoneyAmount.new(
self.amount + another_amount_with_correct_currency.amount,
self.currency )
@newAmount
end
def transform_to(currency)
@newAmount = MoneyAmount.new(
self.amount * (self.currency.value / currency.value),
currency)
@newAmount
end
def to_s
"#{self.amount} #{self.currency}"
end
end
class Currency
attr_accessor :denomination, :value
def initialize(denomination, value)
self.denomination = denomination
self.value = value
end
end
class Converter
attr_accessor :currencies
def currencies
@currencies = @currencies || Array.new
end
def add_currency(currency)
self.currencies << currency
end
def convert(amount, currency)
if ((self.currencies.include? amount.currency) and (self.currencies.include? currency))
return amount.transform_to(currency)
else
raise NoCurrencyError.new("These currencies are not supported by this converter")
end
end
end
class NoCurrencyError < RuntimeError
end
| true
|
02f9ea52354eb0a1272b5d931d5fbb474b2917e9
|
Ruby
|
AlexanderCleasby/dice-roll-ruby-online-web-prework
|
/dice_roll.rb
|
UTF-8
| 251
| 3.859375
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
# Create method `roll` that returns a random number between 1 and 6
# Feel free to google "how to generate a random number in ruby"
def roll
# answer using ranges
#rand(6)+1
#answer using arrays
values = [1,2,3,4,5,6]
values[rand(6)]
end
| true
|
6ac4c92852ba5b1c758fb8fbe1d1edda97c51412
|
Ruby
|
meliew/anagram-detector-online-web-pt-051319
|
/lib/anagram.rb
|
UTF-8
| 190
| 3.0625
| 3
|
[
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
class Anagram
attr_accessor :word
def initialize(word)
@word = word
end
def match(words)
words.keep_if do |string| word.split('').sort == string.split('').sort
end
end
end
| true
|
6be9864a261dda8a3d79ee6e869fa349467d0023
|
Ruby
|
yinm/ruby-book-codes
|
/sample-codes/chapter_04/code_4.05.02.rb
|
UTF-8
| 448
| 3.5
| 4
|
[] |
no_license
|
# 不等号を使う場合
def liquid?(temperature)
# 0度以上100度未満であれば液体、と判定したい
0 <= temperature && temperature < 100
end
liquid?(-1) #=> false
liquid?(0) #=> true
liquid?(99) #=> true
liquid?(100) #=> false
# 範囲オブジェクトを使う場合
def liquid?(temperature)
(0...100).include?(temperature)
end
liquid?(-1) #=> false
liquid?(0) #=> true
liquid?(99) #=> true
liquid?(100) #=> false
| true
|
c8213821acf44d52f4dc3f4ed14fe1f49e528d97
|
Ruby
|
teoucsb82/pokemongodb
|
/lib/pokemongodb/pokemon/metapod.rb
|
UTF-8
| 1,294
| 2.703125
| 3
|
[] |
no_license
|
class Pokemongodb
class Pokemon
class Metapod < Pokemon
def self.id
11
end
def self.base_attack
56
end
def self.base_defense
86
end
def self.base_stamina
100
end
def self.buddy_candy_distance
1
end
def self.candy_to_evolve
50
end
def self.capture_rate
0.4
end
def self.cp_gain
7
end
def self.description
"The shell covering this Pokémon's body is as hard as an iron slab. Metapod does not move very much. It stays still because it is preparing its soft innards for evolution inside the hard shell."
end
def self.evolves_into
Pokemongodb::Pokemon::Butterfree
end
def self.flee_rate
0.2
end
def self.height
0.7
end
def self.max_cp
477.92
end
def self.moves
[
Pokemongodb::Move::Tackle,
Pokemongodb::Move::BugBite,
Pokemongodb::Move::Struggle
]
end
def self.name
"metapod"
end
def self.types
[
Pokemongodb::Type::Bug
]
end
def self.weight
9.9
end
end
end
end
| true
|
71bb9817094cee78023e2da50f17149513800295
|
Ruby
|
mendeza428/rockpaperscissors
|
/spec/db_spec.rb
|
UTF-8
| 889
| 2.59375
| 3
|
[] |
no_license
|
require 'spec_helper'
require './lib/rps.rb'
include RPS
describe "db" do
it "exists" do
expect(DB).to be_a(Class)
end
it "returns a db" do
expect(RPS.db).to be_a(DB)
end
it "is a singleton" do
db1 = RPS.db
db2 = RPS.db
expect(db1).to be(db2)
end
describe "users in db" do
let(:data) do
data = {
name: "Taylor",
password: "password"
}
end
describe ".build_user" do
it "returns a User object" do
user = RPS.db.build_user(data)
expect(user).to be_a(User)
expect(user.name).to eq("Taylor")
expect(user.password).to eq("password")
end
end
describe ".create_user" do
it "puts a User in the database" do
user = RPS.db.create_user(data)
expect(user).to be_a(User)
expect(user.id).to be_a(Fixnum)
end
end
end
end
| true
|
c44a73e5fdba830de4c9e707df8da636deb2958c
|
Ruby
|
developersbk/Universal_Code_Snippets
|
/Codes/Ruby/Algorithms/bst.txt
|
UTF-8
| 553
| 3.4375
| 3
|
[] |
no_license
|
module BST
Node = Struct.new(:value, :parent, :left, :right)
# Finds the 'next' node (in-order successor) of a given node in a binary search tree,
# see examples in test/bst_test.rb
def self.find_next(node)
return nil if node.nil?
# find the left most node in the right subtree
if node.right
n = node.right
n = n.left while n.left
return n
end
# otherwise go up until we're on the left side
n = node
p = n.parent
while p && p.left != n
n = p
p = p.parent
end
p
end
end
| true
|
e2fb324db56a52463a5294e31a8cc1e413b5275b
|
Ruby
|
IonatanMocan/Learn-Ruby-the-hard-way
|
/lifetime_left.rb
|
UTF-8
| 965
| 4.125
| 4
|
[] |
no_license
|
puts "You think you have all the time in the world? Ha."
puts "I don't are how old are you, but till what age would you want to live?"
expected_years = $stdin.gets.chomp.to_i
puts "I can tell you how many days and hours you have left till that day"
puts "What is your birth year"
birth_year = $stdin.gets.chomp.to_i
puts "your birth month? number, please"
birth_month = $stdin.gets.chomp.to_i
puts "what day of that month?"
birth_day = $stdin.gets.chomp.to_i
birth = Time.local(birth_year, birth_month, birth_day)
now = Time.new
puts "You have lived #{((now - birth) / 60 / 60 / 24).to_i} days"
puts "You have lived #{((now - birth) / 60 / 60).to_i} hours\n"
puts "If you want to live until #{expected_years} years, you have:"
death = Time.local(birth_year + expected_years, birth_month, birth_day)
days_left = ((death - now) / 60 / 60 / 24).round
hours_left = ((death - now) / 60 / 60).round
puts "#{days_left} days left"
puts "#{hours_left} hours left"
| true
|
1977a40aabc24477efd4b8c313fc646f2577a83c
|
Ruby
|
zulfikar4568/ruby-language
|
/02.strukturKontrol/09.forLoops/main.rb
|
UTF-8
| 123
| 3.28125
| 3
|
[] |
no_license
|
for i in 1..10
# break if i>10
next if i==2
puts i
end
x = 0
loop do
puts x
x+=1
break if x>10
end
| true
|
e32e6a72bdb473401c1f25ec5ad19af0f364784e
|
Ruby
|
thomasbeckett/sparta_stuff
|
/week-8/oop-refresher/shrubs/rhododendron.rb
|
UTF-8
| 328
| 2.953125
| 3
|
[] |
no_license
|
require_relative "../plant.rb"
require_relative "../plant_types/shrubs.rb"
class Rhododendron < Plant
include Shrub
def color
puts "pink"
end
def location
puts "I am found in asia"
end
def height
Size.height
end
def stems
CommonTraits.stems
end
end
steve = Rhododendron.new
steve.height
| true
|
6aad3546f3caaa2cf60ca2f65a03fd2e5352637f
|
Ruby
|
AJDot/Launch_School_Files
|
/120_Object_Oriented_Programming/LS_Book_OOP_in_Ruby/The_Object_Model/exercises.rb
|
UTF-8
| 979
| 4.375
| 4
|
[] |
no_license
|
puts "------------"
puts "Exercise 1"
puts "------------"
# How do we create an object in Ruby? Give an example of the creation of an object.
# ANSWER
# An object is by using the #new method on a class. A class is defined using the 'class' reserved word like a method using 'def'
class House
end
# the object 'my_house' is instantiated by using the #new method of the class #House
my_house = House.new
puts House.ancestors
puts "------------"
puts "Exercise 2"
puts "------------"
# What is a module? What is its purpose? How do we use them with our classes? Create a module for the class you created in exercise 1 and include it properly.
# ANSWER
# A module is a collection of behaviors that can be used by multiple classes. They can give additional functionality to multiple classes without having to upend all code to make the change.
module OpenDoor
def open_door
puts "You opened the door"
end
end
class House
include OpenDoor
end
my_house.open_door
| true
|
da43bfe6c0997ba03d89ea199efe711c8222f838
|
Ruby
|
alto/aasm
|
/spec/unit/simple_example_spec.rb
|
UTF-8
| 1,621
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
require 'spec_helper'
class Payment
include AASM
aasm do
state :initialised, :initial => true
state :filled_out
state :authorised
event :fill_out do
transitions :from => :initialised, :to => :filled_out
end
event :authorise do
transitions :from => :filled_out, :to => :authorised
end
end
end
describe 'state machine' do
let(:payment) {Payment.new}
it 'starts with an initial state' do
payment.aasm_current_state.should == :initialised
# payment.aasm.current_state.should == :initialised # not yet supported
payment.should respond_to(:initialised?)
payment.should be_initialised
end
it 'allows transitions to other states' do
payment.should respond_to(:fill_out)
payment.should respond_to(:fill_out!)
payment.fill_out!
payment.should respond_to(:filled_out?)
payment.should be_filled_out
payment.should respond_to(:authorise)
payment.should respond_to(:authorise!)
payment.authorise
payment.should respond_to(:authorised?)
payment.should be_authorised
end
it 'denies transitions to other states' do
lambda {payment.authorise}.should raise_error(AASM::InvalidTransition)
lambda {payment.authorise!}.should raise_error(AASM::InvalidTransition)
payment.fill_out
lambda {payment.fill_out}.should raise_error(AASM::InvalidTransition)
lambda {payment.fill_out!}.should raise_error(AASM::InvalidTransition)
payment.authorise
lambda {payment.fill_out}.should raise_error(AASM::InvalidTransition)
lambda {payment.fill_out!}.should raise_error(AASM::InvalidTransition)
end
end
| true
|
bb0da92d9bff94e82f21e4eeb00fda8043752c2f
|
Ruby
|
itsolutionscorp/AutoStyle-Clustering
|
/all_data/exercism_data/ruby/roman-numerals/3afc8fcb62434147a7f70089c8e31156.rb
|
UTF-8
| 1,727
| 3.9375
| 4
|
[] |
no_license
|
class Fixnum
def to_roman
roman_numbers = {
1 => 'I',
4 => 'IV',
5 => 'V',
9 => 'IX',
10 => 'X',
40 => 'XL',
50 => 'L',
90 => 'XC',
100 => 'C',
400 => 'CD',
500 => 'D',
900 => 'CM',
1000 => 'M'
}
result = ''
number = self
roman_numbers.reverse_each do |k,v|
while number >= k do
result << v
number -= k
end
end
result
end
end
# class Fixnum
# def to_roman
# number = self.to_s.reverse #reversed since it's easier than iterating backwards
# numeral = logic(number[0].to_i, "I", "V", "IX") #units - sending the numerals for 1, 5, 9
# if number[1]
# tens = logic(number[1].to_i, "X", "L", "XC") #tens - numerals for 10, 50, 90
# numeral.insert(0, tens)
# end
# if number[2]
# hundreds = logic(number[2].to_i, "C", "D", "CM") #hundreds - numerals for 100, 500, 900
# numeral.insert(0, hundreds)
# end
# if number[3]
# thousands = th_logic(number[3].to_i)
# numeral.insert(0, thousands)
# end
# numeral
# end
# def logic (digit, one, five, nine) #same logic for 1-9, 10 - 90 & 100 - 900
# result = ""
# if digit > 4
# if digit == 9
# result << nine
# digit -= 9
# else
# result << five
# digit -= 5
# end
# end
# while digit > 0
# if digit < 4
# result << one
# digit -= 1
# else
# result << one + five
# digit -= 4
# end
# end
# result
# end
# def th_logic (digit)
# result = ""
# while digit > 0
# result << "M"
# digit -= 1
# end
# result
# end
# end
| true
|
d53e0c380fb41ff1e32a94112c0313e91a77ecb2
|
Ruby
|
dgrahn/baregrades
|
/app/models/access.rb
|
UTF-8
| 659
| 2.6875
| 3
|
[] |
no_license
|
# File: access.rb
# Class: Access
# Type: Model
# Author: Dan Grahn, Matt Brooker, Justin Engel
#
# Description:
# This class is a utility model for maintaining connections
# between different models. It tells us which users belong to
# which courses and what roles they have.
# -----------------------------------------------------------
class Access < ActiveRecord::Base
attr_accessible :user_id, :role_id, :course_id
validates :user_id, :presence => true, :numericality => true
validates :role_id, :presence => true, :numericality => true
validates_uniqueness_of :user_id, :scope => [:course_id]
belongs_to :user
belongs_to :role
belongs_to :course
end
| true
|
dab1efd13a89bc26fad5add75edd7418eb5eeb4d
|
Ruby
|
mathias/hackety-hack.com
|
/models/program.rb
|
UTF-8
| 750
| 2.640625
| 3
|
[] |
no_license
|
# The `Program` class represents a program that someone's uploaded. Right now
# we only store the latest version as text, but eventually, I'd love for
# programs to be backed by `git`.
class Program
include MongoMapper::Document
key :creator_username, String
key :title, String
key :slug, String
# this is the source code for the program.
key :code, String
validate_on_create :slug_check
before_save :make_slug
many :comments
timestamps!
private
def slug_check
programs = Program.all(:creator_username => creator_username)
unless programs.detect {|p| p.slug == title.to_slug }.nil?
errors.add(:title, "Title needs to be unique")
end
end
def make_slug
self.slug = self.title.to_slug
end
end
| true
|
cb0bb134d41274a9feef1b0739b61ad5bdefd7b2
|
Ruby
|
mahmoudazaid/rspec_practice
|
/spec/04_Matcher/05_error_exception_matcher_spec.rb
|
UTF-8
| 1,015
| 2.703125
| 3
|
[] |
no_license
|
require 'spec_helper'
require_relative '../unit/string_analyzer/string_analyzer'
describe StringAnalyzer do
before(:example) do
@sa = StringAnalyzer.new
end
it "Error Matchers", :aggregate_failuresdo do
expect { 1/0 }.to raise_error
expect { 1/0 }.to raise_error(ZeroDivisionError)
expect { 1/0 }.to raise_error("divided by 0")
expect { 1/0 }.to raise_error("divided by 0", ZeroDivisionError)
end
it "Exception Matcher" do
expect { 1/0 }.to raise_exception
expect { 1/0 }.to raise_exception(ZeroDivisionError)
expect { 1/0 }.to raise_exception("divided by 0")
expect { 1/0 }.to raise_exception("divided by 0", ZeroDivisionError)
end
it "Error Matchers", :aggregate_failures do
expect { @sa.word('iii') }.to raise_error(ArgumentError)
expect { @sa.word('iii') }.to raise_error("wrong number of arguments (given 1, expected 0)")
expect { @sa.word('iii') }.to raise_error("wrong number of arguments (given 1, expected 0)", ArgumentError)
end
end
| true
|
272994cfeaa0966d6ac3399ffc5448033a4197d5
|
Ruby
|
urnotjessie/regex-lab-v-000
|
/lib/regex_lab.rb
|
UTF-8
| 593
| 3.3125
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def starts_with_a_vowel?(word)
word.match(/\b[aeiouAEIOU]/) != nil
end
def words_starting_with_un_and_ending_with_ing(text)
text.scan(/\bun\w*ing\b/)
end
def words_five_letters_long(text)
text.scan(/\b\w{5}\b/)
end
def first_word_capitalized_and_ends_with_punctuation?(text)
if text.match(/^[A-Z](.)*(.)*[[:punct:]]\z/) != nil
return true
else
return false
end
end
def valid_phone_number?(phone)
if phone.match(/([0-9] *?){10}|(\([0-9]{3}\)(([0-9]{3}-[0-9]{4})|[0-9]{7})\b)/) != nil
return true
else
return false
end
end
| true
|
ed9fab0d219cfa0a69c34ca2559a954bdd096638
|
Ruby
|
weilandia/battleship
|
/lib/battleship/players/computer.rb
|
UTF-8
| 2,691
| 3.203125
| 3
|
[] |
no_license
|
class Battleship::Player::Computer < Battleship::Player
attr_accessor :radar
def take_turn
puts "=============OPPONENT TURN============="
if radar
coordinate = radar[:targets].pop
cell = opponent.board.cells[coordinate] || valid_targets.sample
else
cell = valid_targets.sample
end
attack(cell: cell)
calibrate_radar(cell: cell)
puts "My #{cell.render_attack_result}"
end
private
def calibrate_radar(cell:)
return if cell.empty?
return clear_radar if cell.ship.sunk?
self.radar = { hits: [], targets: [] } if radar.nil?
radar[:hits] << cell
radar[:targets] = get_targets(hits: radar[:hits])
end
def clear_radar
self.radar = nil
end
def get_targets(hits:)
# This is not as smart as it could be -- it can get confused with multuple ships. TO handle this, we'll need to match on hits.length == 1 AND ensure the hits are on the same ship
if hits.length == 1
get_perimeter(cell: hits[0])
else
get_adjacent(cells: hits)
end
end
def get_perimeter(cell:)
row, column = cell.to_ints
perimeter = [[1, 0], [-1, 0], [0, 1], [0, -1]].map do |(shift_x, shift_y)|
[row + shift_y, column + shift_x]
end
perimeter_coordinates = Battleship::Cell.transform_coord_ints(coord_ints: perimeter)
perimeter_coordinates.select do |coordinate|
opponent.board.valid_coordinate?(coordinate: coordinate) && opponent.board.cells[coordinate].safe?
end
end
def get_adjacent(cells:)
coordinates = cells.map(&:to_ints)
if coordinates.map(&:last).uniq.length == 1
increment = coordinates.map(&:first).sort
column = coordinates[0][1]
targets = [[increment[0] - 1, column], [increment[-1] + 1, column]]
else
increment = coordinates.map(&:last).sort
row = coordinates[0][0]
targets = [[row, increment[0] - 1], [row, increment[-1] + 1]]
end
adjacent_coordinates = Battleship::Cell.transform_coord_ints(coord_ints: targets)
adjacent_coordinates.select do |coordinate|
opponent.board.valid_coordinate?(coordinate: coordinate) && opponent.board.cells[coordinate].safe?
end
end
def place_ships
ships.each do |ship|
placement_coordinates = Battleship::RandomShipPlacementFinder.call(ship: ship, board: board)
raise BoardSetupError if placement_coordinates.nil?
board.place_ship(ship: ship, coordinates: placement_coordinates)
end
puts post_setup_message
end
def post_setup_message
"I have laid out my ships on the grid.\n\n"
end
end
| true
|
789a0f96056404f6b82244df69c5dc5b76de6b9c
|
Ruby
|
ralli/testman
|
/spec/models/testsuiterun_spec.rb
|
UTF-8
| 2,118
| 2.515625
| 3
|
[] |
no_license
|
require 'spec_helper'
describe Testsuiterun do
describe "when validating" do
def make_valid_testrun(attributes = {})
project = Project.new
project.stub(Project.make.attributes)
user = User.new
user.stub(User.make(:current_project => project).attributes)
testsuite = Testsuite.new
testsuite.stub(:edited_by => user, :created_by => user, :project => project)
run = Testsuiterun.make({:testsuite => testsuite, :created_by => user, :edited_by => user}.merge(attributes))
end
it "should be valid" do
run = make_valid_testrun
run.should be_valid
end
it "should have a status" do
run = make_valid_testrun(:status => nil)
run.should_not be_valid
end
it "should have a result" do
run = make_valid_testrun(:result => nil)
run.should_not be_valid
end
it "should have a valid status" do
run = make_valid_testrun(:status => 'hase')
run.should_not be_valid
end
it "should have a valid result" do
run = make_valid_testrun(:result => 'hase')
run.should_not be_valid
end
it "should belong to a test suite" do
run = make_valid_testrun(:testsuite => nil)
run.should_not be_valid
end
it "should be created by a user" do
run = make_valid_testrun(:created_by => nil)
run.should_not be_valid
end
it "should be edited by a user" do
run = make_valid_testrun(:edited_by => nil)
run.should_not be_valid
end
end
describe "when stepping" do
it "should update the run even if no testcase run is present" do
run = Testsuiterun.make(:status => 'new', :result => 'unknown')
run.stub(:nextcase => nil)
arg = { :edited_by => 'user', :status => 'ended', :result => 'ok' }
run.should_receive(:update_attributes!).with(arg)
run.step('user', 'ok')
end
it "should not update the run if already ended" do
run = Testsuiterun.make(:status => 'ended', :result => 'ok')
run.nextcase.should be_nil
run.next?.should be_false
run.step?.should be_false
end
end
end
| true
|
a8515d2c292dfdfe00bbead39f28e5153c1e4848
|
Ruby
|
sf-wdi-22-23/modules-23
|
/w10-mean/d4-drills-bst-traversal/rb/binary_tree.rb
|
UTF-8
| 360
| 3.40625
| 3
|
[] |
no_license
|
##
# This class represents a tree
# with _exactly_ _two_ _subtrees_
# (one or both of which may be nil).
class BinaryTree
attr_accessor :key, :left, :right
##
# Creates a new binary tree
# with the root node key specified by key param
# as the @key for the instance
def initialize(key)
@key = key
@left = nil
@right = nil
end
end
| true
|
81db87f8479532ed9ca7ba94053445dbada8fc4b
|
Ruby
|
47colborne/cloud-sesame
|
/lib/cloud_sesame/query/ast/value.rb
|
UTF-8
| 972
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
module CloudSesame
module Query
module AST
class Value < Abstract::Value
TYPES = {
string: StringValue,
numeric: NumericValue,
datetime: DateValue
}
def self.map_type(symbol)
(klass =TYPES[symbol]) ? klass : self
end
def self.parse(value)
return value.parse self if value.kind_of?(RangeValue)
(
range_value?(value) ? RangeValue :
numeric_value?(value) ? NumericValue :
datetime_value?(value) ? DateValue : StringValue
).new(value, self)
end
def self.range_value?(value)
range?(value) || string_range?(value)
end
def self.numeric_value?(value)
numeric?(value) #|| string_numeric?(value)
end
def self.datetime_value?(value)
datetime?(value) || string_datetime?(value) || string_time?(value)
end
end
end
end
end
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.