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
edb192574ae0c8e9dc698550e864b7ffe5d22e11
Ruby
befool-inc/swaffle
/lib/swaffle/yaml.rb
UTF-8
6,891
2.765625
3
[]
no_license
require "json" require "yaml" require "erb" module Swaffle module Yaml def self.read_yaml_file(file_path) YAML.safe_load(ERB.new(::IO.read(file_path)).result) end def self.load_file_with_ref(path, root) hash = read_yaml_file(path) resolved_hash = load_ref_with_file(hash, path, root) # 200 みたいな int の key を string にしたい JSON.parse(resolved_hash.to_json) end # file が対象の $ref を置き換える # # $ref: ./UserApp.yml # # これ以上複雑化するようであればリファクタリングする def self.load_ref_with_file(node, path, root) case node when Hash if node.key?("$ref") && !node["$ref"].start_with?("#/") target_file = resolve_file_path(node["$ref"], path, root) load_file_with_ref(target_file, root) elsif node.key?("$merge") && !node["$merge"].start_with?("#/") target_file = resolve_file_path(node["$merge"], path, root) hash = load_file_with_ref(target_file, root) if node.count > 1 remains = node.to_a.reject { |k, _| k == "$merge" } remain_hash = remains.map { |k, v| [k, load_ref_with_file(v, path, root)] }.to_h hash = hash.deep_merge(remain_hash) end hash else node.map { |k, v| [k, load_ref_with_file(v, path, root)] }.to_h end when Array node.map { |e| load_ref_with_file(e, path, root) } else node end end # JSON path が対象の $ref を置き換える # # $ref: '#/definitions/User' def self.load_ref_with_path(node, root, resolve_ref) case node when Hash if node.key?("$ref") && node["$ref"].start_with?("#/") load_ref_with_path_for_ref(node, root, resolve_ref) elsif node.key?("$merge") && node["$merge"].start_with?("#/") load_ref_with_path_for_merge(node, root, resolve_ref) else node.map { |k, v| [k, load_ref_with_path(v, root, resolve_ref)] }.to_h end when Array node.map { |e| load_ref_with_path(e, root, resolve_ref) } else node end end def self.load_ref_with_path_for_ref(node, root, resolve_ref) if resolve_ref path = node["$ref"].sub(%r{^#/}, "").split("/") definition = dig_definition(root, path) hash = load_ref_with_path(definition, root, resolve_ref) if node.count > 1 remain = node.to_a.reject { |k, _| k == "$ref" }.to_h hash = hash.deep_merge(remain) end hash else node end end def self.load_ref_with_path_for_merge(node, root, resolve_ref) path = node["$merge"].sub(%r{^#/}, "").split("/") definition = dig_definition(root, path) hash = load_ref_with_path(definition, root, resolve_ref) if node.count > 1 remains = node.to_a.reject { |k, _| k == "$merge" } remain_hash = remains.map { |k, v| [k, load_ref_with_path(v, root, resolve_ref)] }.to_h hash = hash.deep_merge(remain_hash) end hash end # definition内に存在する $merge や $ref を展開してdefinitionを取得する def self.dig_definition(root, paths) definition = nil node = root paths.each do |path| node = node[path] raise "no such definition. #{paths.join("/")}" unless node if node.key?("$ref") && node["$ref"].start_with?("#/") node = dig_definition(root, node["$ref"].sub(%r{^#/}, "").split("/")) elsif node.key?("$merge") && node["$merge"].start_with?("#/") hash = dig_definition(root, node["$merge"].sub(%r{^#/}, "").split("/")) if node.count > 1 remains = node.to_a.reject { |k, _| k == "$merge" }.to_h hash = hash.deep_merge(remains) end node = hash end definition = node end definition end # ファイルパスを解決する # # - ./foo/bar/zoo: 相対パス: パース中のファイルを起点にパス解決する # - ~/foo/bar/zoo: 絶対パス: ルートファイルを起点にパス解決する def self.resolve_file_path(ref, path, root) if ref.start_with?("~/") File.expand_path(ref.gsub(/^~/, "."), root) else File.expand_path(ref, File.dirname(path)) end end # デフォルトでrequiredとし、オプショナルなカラムはプロパティにoptional: trueをつけて指定するようにする def self.convert_default_required(node) case node when Hash # type: object かつ、propertiesが存在し、required指定が存在しない場合、 # プロパティにoptional: trueがなければrequiredとして扱う。 if node["type"] == "object" && !node.key?("required") && node["properties"] required_keys = [] node["properties"].each do |k, v| required_keys << k unless v["optional"] end node["required"] = required_keys end Hash[node.map { |k, v| [k, convert_default_required(v)] }] when Array node.map { |e| convert_default_required(e) } else node end end # パスのところでsummaryが省略されている場合はdescriptionから補完 def self.convert_paths_summary(node) case node when Hash node["summary"] = node["description"] || "" if node.key?("operationId") && !node.key?("summary") Hash[node.map { |k, v| [k, convert_paths_summary(v)] }] when Array node.map { |e| convert_default_required(e) } else node end end # resolve_mode # :never # 何も解決しない # :file # $ref(file) のみ解決する # :all # $ref(file), $ref(JSON path) の両方を解決する def self.load(path, resolve_mode) hash = case resolve_mode when :never # Hash 化して tmp = JSON.parse(YAML.load_file(path).to_json) # $merge(JSON path) のみ解決する load_ref_with_path(tmp, tmp, false) when :file # $ref(file) を解決しながら一度 Hash 化する tmp = load_file_with_ref(path, File.dirname(path)) # $merge(JSON path) のみ解決する load_ref_with_path(tmp, tmp, false) when :all # $ref(file) を解決しながら一度 Hash 化する tmp = load_file_with_ref(path, File.dirname(path)) # $ref(JSON path), $merge(JSON path) を解決する load_ref_with_path(tmp, tmp, true) end convert_default_required(hash) convert_paths_summary(hash) end end end
true
228c8f9df4c91b153c493fe6a5ebb9a81ebe1b11
Ruby
AKnopf/edu_draw
/examples/areas.rb
UTF-8
386
3.046875
3
[ "MIT" ]
permissive
require "edu_draw" sheet = EduDraw::Sheet.new(x: 150, y: 150) pen = sheet.new_pen(x: 52, y: 10) # Every move in the fill-block will create a filled a shape pen.fill do 5.times do pen.move 40 pen.turn_right 36 end end #Every move out of the fill block just draws a line # Those 10 moves result in a half-filled decagon 5.times do pen.move 40 pen.turn_right 36 end sheet.show
true
9ec4eefe94e84f99d965b3df672a57c2c231d1e5
Ruby
paulfitz/coopy-ruby
/lib/coopy/csv.rb
UTF-8
4,113
2.78125
3
[ "MIT" ]
permissive
#!/bin/env ruby # encoding: utf-8 module Coopy class Csv def initialize @cursor = 0 @row_ended = false end protected attr_accessor :cursor attr_accessor :row_ended attr_accessor :has_structure public def render_table(t) result = "" w = t.get_width h = t.get_height txt = "" v = t.get_cell_view begin _g = 0 while(_g < h) y = _g _g+=1 begin _g1 = 0 while(_g1 < w) x = _g1 _g1+=1 txt += "," if x > 0 txt += self.render_cell(v,t.get_cell(x,y)) end end txt += "\r\n" end end return txt end def render_cell(v,d) return "NULL" if d == nil return "NULL" if v.equals(d,nil) str = v.to_s(d) delim = "," need_quote = false begin _g1 = 0 _g = str.length while(_g1 < _g) i = _g1 _g1+=1 ch = str[i] if ch == "\"" || ch == "'" || ch == delim || ch == "\r" || ch == "\n" || ch == "\t" || ch == " " need_quote = true break end end end result = "" result += "\"" if need_quote line_buf = "" begin _g1 = 0 _g = str.length while(_g1 < _g) i = _g1 _g1+=1 ch = str[i] result += "\"" if ch == "\"" if ch != "\r" && ch != "\n" if line_buf.length > 0 result += line_buf line_buf = "" end result += ch else line_buf += ch end end end result += "\"" if need_quote return result end def parse_table(txt) @cursor = 0 @row_ended = false @has_structure = true result = Array.new row = Array.new while(@cursor < txt.length) cell = self.parse_cell(txt) row.push(cell) if @row_ended result.push(row) row = Array.new end @cursor+=1 end return result end def parse_cell(txt) return nil if txt == nil @row_ended = false first_non_underscore = txt.length last_processed = 0 quoting = false quote = 0 result = "" start = @cursor begin _g1 = @cursor _g = txt.length while(_g1 < _g) i = _g1 _g1+=1 ch = txt[i].ord last_processed = i first_non_underscore = i if ch != 95 && i < first_non_underscore if @has_structure if !quoting break if ch == 44 if ch == 13 || ch == 10 ch2 = txt[i + 1].ord if ch2 != nil if ch2 != ch last_processed+=1 if ch2 == 13 || ch2 == 10 end end @row_ended = true break end if ch == 34 || ch == 39 if i == @cursor quoting = true quote = ch result += [ch].pack("U") if i != start next elsif ch == quote quoting = true end end result += [ch].pack("U") next end if ch == quote quoting = false next end end result += [ch].pack("U") end end @cursor = last_processed if quote == 0 return nil if result == "NULL" if first_non_underscore > start del = first_non_underscore - start return result[1..-1] if result[del..-1] == "NULL" end end return result end def parse_single_cell(txt) @cursor = 0 @row_ended = false @has_structure = false return self.parse_cell(txt) end end end
true
008f19bc5655e0111f43198c87377018e2b22759
Ruby
icvlahovic/the-bachelor-todo-web-012918
/lib/bachelor.rb
UTF-8
1,208
3.484375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def get_first_name_of_season_winner(data, season) data[season].map do |contestant_hash| if contestant_hash["status"].downcase == "winner" return contestant_hash["name"].split.first end end end def get_contestant_name(data, occupation) data.map do |season, contestants| contestants.map do |contestant_hash| if contestant_hash["occupation"] == occupation return contestant_hash["name"] end end end end def count_contestants_by_hometown(data, hometown) total = 0 data.map do |season, contestants| contestants.map do |contestant_hash| if contestant_hash["hometown"] == hometown total += 1 end end end total end def get_occupation(data, hometown) data.each do |season, contestants| contestants.each do |contestant_hash| if contestant_hash["hometown"] == hometown return contestant_hash["occupation"] end end end end def get_average_age_for_season(data, season) season_age_total = 0 number_of_contestants = 0 data[season].each do |contestants| season_age_total += (contestants["age"]).to_f number_of_contestants += 1 end (season_age_total / number_of_contestants).round end
true
6e7cfd8f08e43de3ef2258b2a45650f37334ba5a
Ruby
mozartdminor/HackerRank
/Algorithms/Implementation/angryProfessor.rb
UTF-8
336
3.359375
3
[]
no_license
#https://www.hackerrank.com/challenges/angry-professor cases = gets.to_i for i in 1..cases nk = gets.split(" ") n = nk[0].to_i k = nk[1].to_i arrivals = gets.split(" ") ontime = 0 for j in 1..n if arrivals[j-1].to_i <= 0 ontime += 1 end end if ontime >= k puts("NO") else puts("YES") end end
true
5f0f502048ac0233b41fa507cbcfc5d174933866
Ruby
ged/graphics
/examples/tank.rb
UTF-8
2,967
2.6875
3
[ "MIT" ]
permissive
#!/usr/bin/ruby -w require "graphics" D2R = Math::PI / 180.0 class Tank < Graphics::Body ACCELERATE = 0.25 DECELERATE = 0.125 ROTATION = 2 TICK_ENERGY = 5 SHOT_ENERGY = 100 BULLET_SPEED = 9.0 MAX_SPEED = 4.0 MAX_ROTATION = 360 MAX_ENERGY = 100 attr_accessor :t attr_accessor :e def initialize w super self.x = w.w / 2 self.y = w.h / 2 self.e = 0 self.t = Turret.new self end def update self.e += TICK_ENERGY t.update x, y move limit clip end def limit self.e = MAX_ENERGY if e > MAX_ENERGY if m > MAX_SPEED then self.m = MAX_SPEED elsif m < 0 then self.m = 0 end end def fire if e >= SHOT_ENERGY then self.e -= SHOT_ENERGY t.fire end end class View def self.draw w, b w.blit w.body_img, b.x, b.y, b.a Turret::View.draw w, b.t end end def turn_right; turn(-ROTATION); aim_right; end def turn_left; turn ROTATION; aim_left; end def aim_right; self.t.turn(-ROTATION); end def aim_left; self.t.turn ROTATION; end def accelerate; self.m += ACCELERATE; self.t.m = m; end def decelerate; self.m -= DECELERATE; self.t.m = m; end end class Turret < Graphics::Body def initialize tank self.w = tank.w self.x = tank.x self.y = tank.y self.a = tank.a self.m = tank.m end def fire b = Bullet.new w, x, y, a, m b.move_by a, 15 end def update x, y self.x = x self.y = y end class View def self.draw w, b w.blit w.turret_img, b.x, b.y, b.a end end end class Bullet < Graphics::Body def initialize w, x, y, a, m self.w = w self.x = x self.y = y self.a = a self.m = m + 5 w.bullets << self w.bullet_snd.play end def update move w.bullets.delete self if clip end class View def self.draw w, b w.rect b.x, b.y, 2, 2, :white w.debug "%.2f", b.m end end end class TargetSimulation < Graphics::Simulation attr_accessor :tank, :bullets attr_accessor :body_img attr_accessor :turret_img attr_accessor :bullet_snd def initialize super 640, 640, 16, "Target Practice" self.tank = Tank.new self self.bullets = [] open_mixer 8 register_body tank register_bodies bullets self.body_img = image "resources/images/body.png" self.turret_img = image "resources/images/turret.png" self.bullet_snd = audio "resources/sounds/bullet.wav" end def initialize_keys super add_key_handler(:RIGHT) { tank.turn_right } add_key_handler(:LEFT) { tank.turn_left } add_key_handler(:UP) { tank.accelerate } add_key_handler(:DOWN) { tank.decelerate } add_key_handler(:SEMICOLON) { tank.aim_left } add_key_handler(:Q, :remove){ tank.aim_right } add_key_handler(:SPACE) { tank.fire } end def draw n super fps n end end TargetSimulation.new.run
true
82712dd78df498bca228c1ce2b6b0e47368d460e
Ruby
Invoca/process_settings
/spec/lib/process_settings/targeted_settings_spec.rb
UTF-8
4,181
2.59375
3
[ "MIT" ]
permissive
# frozen_string_literal: true require 'spec_helper' require 'logger' require 'process_settings/targeted_settings' describe ProcessSettings::TargetedSettings do TARGETED_SETTINGS = [{ 'filename' => 'honeypot.yml', 'target' => true, 'settings' => { 'honeypot' => { 'promo_number' => '+18005554321' } } }, { 'meta' => { 'version' => 17, 'END' => true } }].freeze describe "#initialize" do it "requires version:" do expected_message = if RUBY_VERSION < '2.7' /missing keyword: version/ else /missing keyword: :version/ end expect do described_class.new([]) end.to raise_error(ArgumentError, expected_message) end it "requires non-empty version:" do expect do described_class.new([], version: nil) end.to raise_error(ArgumentError, /version must not be empty/) end end describe "[]" do it "allows hash key access to settings" do target_and_settings = described_class.from_array(TARGETED_SETTINGS) result = target_and_settings.targeted_settings_array.first.settings.json_doc.mine('honeypot', 'promo_number') expect(result).to eq('+18005554321') end end context "with file in tmp" do let(:tmp_file_path) { Tempfile.new(['combined_process_settings', '.yml'], File.expand_path('../../../tmp', __dir__)).path } before do File.write(tmp_file_path, TARGETED_SETTINGS.to_yaml) end after do FileUtils.rm_f(tmp_file_path) end describe ".from_file" do it "reads from yaml file" do targeted_settings = described_class.from_file(tmp_file_path) expect(targeted_settings.targeted_settings_array.size).to eq(1) expect(targeted_settings.targeted_settings_array.first.settings.json_doc.keys.first).to eq('honeypot') expect(targeted_settings.version).to eq(17) end it "infers version from END" do targeted_settings = described_class.from_file(tmp_file_path) expect(targeted_settings.targeted_settings_array.size).to eq(1) expect(targeted_settings.version).to eq(17) end it "infers version from END faster with only_meta: true" do targeted_settings = described_class.from_file(tmp_file_path, only_meta: true) expect(targeted_settings.targeted_settings_array.size).to eq(0) expect(targeted_settings.version).to eq(17) end end end describe ".from_array" do it "delegates" do target_and_settings = described_class.from_array(TARGETED_SETTINGS) target = target_and_settings.targeted_settings_array.first.target expect(target.json_doc).to eq(true) expect(target).to be_kind_of(ProcessSettings::Target) settings = target_and_settings.targeted_settings_array.first.settings expect(settings.json_doc).to eq('honeypot' => { 'promo_number' => '+18005554321' }) expect(settings).to be_kind_of(ProcessSettings::Settings) end it "confirms meta: is at end" do expect do described_class.from_array(TARGETED_SETTINGS.reverse) end.to raise_error(ArgumentError, /got \{"filename"=>"honeypot.yml",/) end it "requires meta: at end" do expect do described_class.from_array(TARGETED_SETTINGS[0, 1]) end.to raise_error(ArgumentError, /Missing meta:/) end it "requires END: true at end of meta: section" do expect do described_class.from_array(TARGETED_SETTINGS[0, 1] + [ { 'meta' => { 'END' => true, 'version' => 42 } }]) end.to raise_error(ArgumentError, /END: true must be at end of file/) end it "infers version from meta" do targeted_settings = described_class.from_array(TARGETED_SETTINGS) expect(targeted_settings.targeted_settings_array.size).to eq(1) expect(targeted_settings.version).to eq(17) end it "infers version from meta faster with only_meta: true" do targeted_settings = described_class.from_array(TARGETED_SETTINGS, only_meta: true) expect(targeted_settings.targeted_settings_array.size).to eq(0) expect(targeted_settings.version).to eq(17) end end end
true
80f16872932a2e5394ee8a3b46dcb4a2ab49cba0
Ruby
nanma80/euler_project
/p001_025/p004/main.rb
UTF-8
370
3.640625
4
[]
no_license
MAX = 999 MIN = 900 def is_palindrome?(number) number.to_s.reverse == number.to_s end max_palindrome = 0 MAX.downto(MIN) do |i| MAX.downto(MIN) do |j| n = i * j if n > max_palindrome && is_palindrome?(n) max_palindrome = n end end end puts max_palindrome # 906609 # puts is_palindrome?(9) # puts is_palindrome?(91) # puts is_palindrome?(945)
true
0b927af7224f45f25bc207bcfeb22079655dbebd
Ruby
VijayaArun/e-commerce_web_app
/lib/spree/core/importer/custom_product_importer.rb
UTF-8
4,789
2.765625
3
[]
no_license
# require 'find' # images = [] # Find.find("/home/pooja/Documents/shree sarees" &&"*.jpg" || "*.png") do |path| # images << path if path = ~ /.*\.jpg$/ # # Dir["*.jpg","*.png"] # # Dir.foreach("/documents/shree sarees/*") do |image| # # next if image == # # require file # end # image_file_paths = Find.find('/home/pooja/Documents/shree sarees/cotton/201 bp').select { |p| /.*\.jpg$/ || /.*\.png$/ =~ p } # for identifier in image_file_paths # if image_file_paths.identifier[-7,3].to_i.kind_of?Integer # end # end # folder = '/home/pooja/Documents/shree sarees' # Dir.glob("#{folder}/**/*.jpg") # Dir.foreach("/home/pooja/Documents/shree sarees/cotton/201 bp") do |file| # if file.split(/\W+/).last == "jpg" || file.split(/\W+/).last == "png" # if file[-7,3].to_i.kind_of?Integer # puts file[-7,3] # else # puts "error" # end # end # end # Dir.chdir("/home/pooja/Documents/shree sarees") # Dir.glob(File.join("**","*.jpg")) || Dir.glob(File.join("**","*.png")) # Dir.chdir("/home/pooja/Documents/shree sarees") { Dir.glob("**/*").map {|path| File.expand_path(path) } } # for files in Dir['**/*.*'] # if files[-7,3].to_i.kind_of?Integer # puts files[-7,3] # else # puts "error" # end # end # Dir['**/*.*'].each do |file| # if file.split(/\W+/).last == "jpg" || file.split(/\W+/).last == "png" # if file[-7,3].to_i.kind_of?Integer # puts file[-7,3] # else # puts "error" # end # end # end # require 'find' # Find.find('./') do |f| p f end # #Jpg and png files # Find.find('./') do |file| # file = Dir.glob(File.join("**","*.jpg")) << Dir.glob(File.join("**","*.png")) # p file.split(/\s+|\b/) # end # # Displays Folder names # condition = Dir["*.jpg","*.png"] # Dir.glob(File.join("**", condition)) # condition = Dir["*.jpg","*.png"] # f = Dir.glob(File.join("**", condition)) # Dir.glob(File.join(f, condition)) # Find.find('./') do |file| # file_type = [] # file_type = File.extname(file) # if file_type == ".jpg" || file_type == ".png" # puts File.basename(file,file_type) # else # puts "not jpg or png" # end # end # files = File.join("**", "*.jpg" , "**" , "*.png") # Dir.glob(files) # Find.find('./') do |file| # file_type = [] # file_type = File.extname(file) # if file_type == ".jpg" || file_type == ".png" # fname = File.basename(file,file_type).split(/\W+/) # if fname[-3,3].to_i.kind_of?Integer # puts fname[-3,3] # else # puts "alphabets" # end # end # end #Gives last 3 chars of all jpg and png files for product name. def get_product_name Dir['**/*.{jpg,png}'].each do |file| fname = File.basename(file.to_s , '.*').split(/\W+/) fname = fname.pop fname.split(",").map {|x| x.to_i } puts fname.last(3) end end #Gives all folder names def get_taxanomies unique_folder_names =[] Dir.glob("**/").each do |folder| folder_name = folder.split('/').second if folder_name != nil folder_name = folder_name.gsub(/[^0-9A-Za-z]/, '').gsub(/[^\d]/, '') unique_folder_names << folder_name end end p unique_folder_names.uniq end #Gives all categories def get_categories Dir.glob("**").each do |folder| p folder end end # #Reading prices from excel sheet # require 'spreadsheet' # workbook = Spreadsheet.open '/home/pooja/Documents/ADI PRICE LIST 01-05-16.xls' # workbook.worksheets.each do |sheet| # sheet.each do |row| # puts "#{sheet.name} --> #{row[0]} - #{row[1]} - #{row[2]}" # end # end #Reading prices from csv file # require "CSV" # CSV.foreach("/home/pooja/Documents/ADI PRICE LIST 01-05-16.csv") do |row| # puts "#{row}" # end # require "CSV" # filename = 'data.csv' # sum = 0 # CSV.foreach("/home/pooja/Documents/ADI PRICE LIST 01-05-16.csv") do |row| # sum += row[2].to_i # end # puts sum # arr_of_arrs = CSV.read("/home/pooja/Documents/ADI PRICE LIST 01-05-16.csv") # require 'csv' # data = Array.new # CSV.foreach("/home/pooja/Documents/ADI PRICE LIST 01-05-16.csv") do |row| # data << row.to_hash # end # p data # CSV.open("/home/pooja/Documents/ADI PRICE LIST 01-05-16.csv", skip_blanks: true).reject { |row| row.all?(&:nil?) } # CSV.readlines("/home/pooja/Documents/ADI PRICE LIST 01-05-16.csv", skip_blanks: true).reject { |row| row.all?(&:nil?) } # CSV.open("/home/pooja/Documents/ADI PRICE LIST 01-05-16.csv", skip_blanks: true, headers: true).reject { |row| row.to_hash.values.all?(&:nil?) } # ‘*’ – matches all files and directories in the current path # ‘**’ – matches all files and directories in the current path # ‘**/’ – matches all directories recursively in the current path # ‘**/*’ – matches all files and directories recursively in the current path
true
8319679b2b5f72c31916210c581944941933a3bc
Ruby
MichaelDevenport/chromotype_test
/lib/geo_lookup.rb
UTF-8
2,780
3.03125
3
[ "MIT" ]
permissive
require 'nominatim' require 'geonames_api' class GeoLookup include CacheSupport attr_reader :lat, :lng # See http://en.wikipedia.org/wiki/Decimal_degrees#Accuracy # 4 digits gives us ~10m resolution, 3 digits gives us ~100m resolution. # Given that most aGPS have ~50m resolution, and we want some cache hits, we # default to 3. def initialize(lat, lng) @lat = lat.to_f.round(3) @lng = lng.to_f.round(3) end def path # longest wins paths.sort_by(&:size).last end def paths # No one has ever taken a photo at exactly 0, 0. return [] if [lat, lng] == [0, 0] paths = [place_path, osm_city_path].compact # Only use the state path if we're desperate: paths << state_path if paths.empty? self.class.uniq_paths(paths) end # uniq_paths(nil, [a,b,c], [a,b,c,d], [e,f,g]) = [a,b,c,d], [e,f,g] def self.uniq_paths(arrays) a = arrays.compact.uniq.map { |ea| ea.compact_blanks } a.select { |i| a.except(i).none? { |j| j.size > i.size && j.first(i.size) == i } } end def place with_cache(:place) do # Is there a POI that's <= 250m away? GeoNamesAPI::Place.find(lat: lat, lng: lng, radius: 0.25) end end def place_id place.try(:geoname_id) end def place_path if place osm_city_path_and_place(place.name) || geo_to_path end end def admin_name2 gn_city_path[2] if gn_city_path end def neighbourhood_path with_cache(:neighbourhood) do begin # .25km away n = GeoNamesAPI::Neighbourhood.find(lat: lat, lng: lng, radius: 0.25) if n %w{countryCode adminName1 adminName2 city name}.map do |ea| n.neighbourhood[ea] end end rescue GeoNamesAPI::NoResultFound # no big whoop end end end def osm_city_path with_cache(:osm_city) do place = Nominatim.reverse(lat, lng).address_details(true).fetch a = place.try(:address) if a [a.country_code.upcase, a.state, a.county, a.city, a.town, a.village, a.suburb].compact_blanks end end end def osm_city_path_and_place(place_name) if osm_city_path if osm_city_path.last != place_name osm_city_path + [place_name] else osm_city_path end end end def state_path with_cache(:state_path) do state = GeoNamesAPI::CountrySubdivision.find(lat: lat, lng: lng, radius: 1) [state.country_code.upcase, state.admin_name1] if state end end def with_cache(method, &block) cached_with_long_ttl("#{method}_#{lat}_#{lng}", &block) end def geo_to_path(geo = place) return nil if geo.nil? [geo.country_code.upcase, geo.admin_name1, geo.admin_name2, geo.admin_name3, geo.admin_name4, geo.name] end end
true
faf11d9acdcf31d78d3e6701b4d5dd8f81f4e914
Ruby
dinhhientran/code-utility
/lib/hash_beautifiers/hash_beautifier.rb
UTF-8
2,264
3.484375
3
[]
no_license
class HashBeautifier COMMA = ',' COLON = ':' LEFT_BRACKET = '[' RIGHT_BRACKET = ']' LEFT_BRACE = '{' RIGHT_BRACE = '}' DEFAULT_INDENT = 2 DEFAULT_VALUE_ALIGNED = true def initialize(hash = nil) @hash = hash end def setHash(hash) @hash = hash end def self.getBeautifierInstance(language) case language when 'php' PhpHashBeautifier.new when 'ruby' RubyHashBeautifier.new when 'javascript' JsHashBeautifier.new when 'python' PythonHashBeautifier.new when 'perl' PerlHashBeautifier.new when 'groovy' GroovyHashBeautifier.new end end def setIndent(noOfSpaces) @indent = noOfSpaces.to_i end def setValueAligned(value) @valueAligned = value end def beautify raise ArgumentError.new("Hash should not be null") if @hash.nil? _beautify(@hash, @indent || self.class::DEFAULT_INDENT, true) end private def _beautify(hash, indent, isRoot = false, isHashItem = false) if hash.is_a? Hash longestKey = hash.keys.map { |key| key.to_s.length }.max hash = hash.map do |key, value| key = "#{whiteSpaces(indent + (!isRoot ? indent() : 0))}#{key.to_s}#{valueAligned ? whiteSpaces(longestKey - key.to_s.length) : ' '}#{self.class::COLON}" if value.is_a? String "#{key} #{value}" else "#{key} #{_beautify(value, indent + indent(), false, true)}" end end "#{!isRoot && !isHashItem ? whiteSpaces(indent) : ''}#{self.class::LEFT_BRACE}\n#{hash.join("#{self.class::COMMA}\n")}\n#{!isRoot ? whiteSpaces(indent) : ''}#{self.class::RIGHT_BRACE}" elsif hash.is_a? Array array = hash.map { |item| _beautify(item, indent)} "#{!isRoot && !isHashItem ? whiteSpaces(indent) : ''}#{self.class::LEFT_BRACKET}\n#{array.join("#{self.class::COMMA}\n")}\n#{!isRoot ? whiteSpaces(indent - indent()) : ''}#{self.class::RIGHT_BRACKET}" else "#{!isRoot ? whiteSpaces(indent) : ''}#{hash}" end end def whiteSpaces(n) Array.new(n).map{|w| " "}.join end def indent @indent || self.class::DEFAULT_INDENT end def valueAligned !@valueAligned.nil? ? @valueAligned : self.class::DEFAULT_VALUE_ALIGNED end end
true
a988d9b75d6d8f38bebb2421434eb90e8eac3989
Ruby
cgoodmac/ruby
/labs/stoq/user.rb
UTF-8
249
3.546875
4
[]
no_license
class User attr_accessor :name, :pw, :cash, :stocks def initialize(name, pw, cash) @name = name @pw = pw @cash = cash @stocks = [] # creates an empty array of stocks when each user object is created end def to_s "#{name}" end end
true
45f94a98e8bc0996a102c257ef959e58a46084e4
Ruby
thepoppingone/rubytwodistinctnumssumstoarangeofvalues
/iReader.rb
UTF-8
1,518
3.890625
4
[]
no_license
# This file uses the n factorial way (brute force method) and it only manages to # pass the first two test files: test1.txt test2.txt # beginning_time = Time.now # import the ruby `set` for removing duplicate values require 'set' # Declare a new set and add all the numbers read from the file to form a # list of unique numbers iSet = Set.new() IO.foreach("cases/test2.txt") do |x| iSet.add x.to_i end # Defined a function that iterates through the Set until the Set is completely empty def run_each(iSet) while !iSet.empty? yield(iSet, true) iSet.delete(iSet.first) end end # Declare a new set to store all the unique values of y found fSet = Set.new() # Run the method, inserting a block of a constantly updated Set run_each(iSet) do |fresh_set, check| # Declare an Enumerator from the set e = fresh_set.each # Enumerate the set and save the first element to variable `a` a = e.next # Run a loop for it to check the sum of the first element and the following elements whether they # satisfiy the condition -10000 < y < 10000 while check begin b = e.next y = a+b # Add the found y into the Set fSet.add(y) if y.between?(-10000,10000) rescue StopIteration check = false end end end # Output the final set's length as the number of y found puts fSet.length #end_time = Time.now #puts "Time elapsed #{(end_time - beginning_time)*1000} milliseconds"
true
fe05558b296aa527c418afa83c69812a7aacfe37
Ruby
nktaushanov/rucomasy
/spec/core/tasks/expr_spec.rb
UTF-8
3,306
3.203125
3
[]
no_license
require './core/rucomasy' require 'treetop' Treetop.load './core/tasks/grammer' module Rucomasy describe Expr do def parse(input) ArithmeticParser.new.parse(input).to_sexp end def evaluate(expression, hash = {}) Expr.build(parse(expression)).evaluate(hash) end it "evaluates variables" do evaluate('x', x: 1).should eq 1 evaluate('t', x: 1, t: 4).should eq 4 expect { evaluate('t', x: 1) }.to raise_error(ArgumentError) expect { evaluate('t') }.to raise_error(ArgumentError) end it "evaluates numbers" do evaluate('1231').should eq 1231 evaluate('0').should eq 0 evaluate('-23.07').should eq -23.07 evaluate('-0').should eq 0 end it "evaluates sine" do evaluate('(sin 0)').should eq 0.0 evaluate('(sin 123)').should eq Math.sin(123) evaluate("(sin #{Math.asin(0.3)})").should eq Math.sin(Math.asin(0.3)) end it "evaluates cosine" do evaluate('(cos 0)').should eq 1.0 evaluate('(cos 123)').should eq Math.cos(123) evaluate("(cos #{Math.acos(0.33)})").should eq Math.cos(Math.acos(0.33)) end it "evaluates negation" do evaluate('(- 1231)').should eq -1231 evaluate('(- x)', x: 3.0).should eq -3.0 end it "evaluates addition" do evaluate('(+ 1 2)').should eq 3 evaluate('(+ 13.0 2.0)').should eq 15.0 evaluate('(+ x 2.0)', x: 7.0).should eq 9.0 end it "evaluates substraction" do evaluate('(- 1 2)').should eq -1 evaluate('(- 13.0 2.0)').should eq 11.0 evaluate('(- x 2.0)', x: 7.0).should eq 5.0 end it "evaluates multiplication" do evaluate('(* 1 2)').should eq 2 evaluate('(* 8 2)').should eq 16 evaluate('(* 13.0 2.0)').should eq 26.0 evaluate('(* x 2.0)', x: 7.0).should eq 14.0 end it "evaluates division" do evaluate('(/ 1 2)').should eq 0 evaluate('(/ 8 2)').should eq 4 evaluate('(/ 13.0 2.0)').should eq 6.5 evaluate('(/ x 2.0)', x: 7.0).should eq 3.5 end it "evaluates maximum" do evaluate('(max 74 9)').should eq 74 evaluate('(max 9 74)').should eq 74 evaluate('(max 9 -74)').should eq 9 evaluate('(max -80 -74)').should eq -74 evaluate('(max 8 8)').should eq 8 evaluate('(max 1.5 2.0)').should eq 2.0 evaluate('(max 1.5 -2.0)').should eq 1.5 evaluate('(max x -21)', x: -10).should eq -10 evaluate('(max x -21)', x: -22).should eq -21 end it "evaluates minimum" do evaluate('(min 74 9)').should eq 9 evaluate('(min 9 74)').should eq 9 evaluate('(min 9 -74)').should eq -74 evaluate('(min -80 -74)').should eq -80 evaluate('(min 8 8)').should eq 8 evaluate('(min 1.5 2.0)').should eq 1.5 evaluate('(min 1.5 -2.0)').should eq -2.0 evaluate('(min x -10)', x: -21).should eq -21 evaluate('(min x -10)', x: -8).should eq -10 end it "evaluates nasted expressions" do evaluate('(max (abs -123) (min x (- 13 1)))', x: 13).should eq 123 evaluate('(/ (max x (* 12 15)) (abs -123))', x: -1213).should eq (12*15)/123 evaluate('(max (- (abs -123)) (min 13 (- 13 1)))').should eq 12 evaluate('(sin (abs (- x)))', x: 0.5).should eq Math.sin(0.5) end end end
true
5f8bcd11f4cc5751967b9137502a3acb2efc5923
Ruby
patbrennan/ltp-exercises
/ch8.rb
UTF-8
226
3.640625
4
[]
no_license
#return sorted array when user hits enter words = [] puts "Enter your words" input = gets.chomp.to_s.downcase until input == "" words.push input input = gets.chomp.to_s.downcase end if input == "" puts words.sort end
true
1a57459a8627aca07c816e4b0dff91fb5f356503
Ruby
Itamarzil/bootcamp
/Rails/Ex1/app/models/my_model.rb
UTF-8
215
2.859375
3
[]
no_license
class MyModel < ApplicationRecord def inc firstNumRecord = MyModel.find(1) firstNumRecord.num = firstNumRecord.num + 1 firstNumRecord.save puts "done increasing num." end end
true
3987ac9176e1c8e8af5c9076c5375d587f940a2e
Ruby
Park9eon/learn-ruby
/number.rb
UTF-8
157
3.203125
3
[]
no_license
=begin Ruby Numbers Usual operators: + addition - subtraction * muliplication / divistion =end puts 1 + 2 puts 2 * 3 puts 3 / 2 puts 10 - 11 puts 1.5 / 2.6
true
c3d22e3bc07470d34e661c0f667da9613c3a3814
Ruby
alex-phillips/clouddrive
/lib/clouddrive/commands/remove_command.rb
UTF-8
754
2.71875
3
[ "MIT" ]
permissive
module CloudDrive class RemoveCommand < Command parameter "remote_path", "Remote path of node to move to trash" option ["-i", "--id"], :flag, "Designate remote node by ID" def execute @offline = false init if id? node = Node.load_by_id(remote_path) unless node error("No node exists with ID '#{remote_path}'") end else node = Node.load_by_path(remote_path) unless node error("No node exists at path '#{remote_path}'") end end result = node.trash if result[:success] info("Successfully trashed '#{remote_path}'") else error("Failed to trash node: #{result[:data].to_json}") end end end end
true
8378874f8c7f929bd880d90a270925c3fb001ad6
Ruby
allenscheng/daily_exercises
/recursion.rb
UTF-8
320
3.296875
3
[]
no_license
# @total = 0 # def sum_num(num) # if num <= 1000 # @total += num # sum_num(num+1) # end # return @total # end # p sum_num(1) def sum_num(num, ar) sum_ar = ar if num === 1000 return sum_ar end if num <= 1000 sum_ar += num p sum_ar sum_num(num + 1, sum_ar) end end p sum_num(0,0)
true
a26c1cdc1deefa69887b3bbc69a2fa2ef40afa3c
Ruby
gennyallcroft/bookmarks
/week_2_morning_projects/flip_coin.rb
UTF-8
423
3.40625
3
[]
no_license
class Coin end class CountScore count = 0 def flip(coin) random_number = RandomNumber.new if random_number.random == 0 count += 1 'You flipped a head. The number of heads you have flipped is' + count elsif random_number.random == 1 'You flipped a tails. The number of heads you have flipped is' + count end count end end class RandomNumber def random rand(1) end end
true
a16d23b56f8e9a5561bc7328a22003b0b8623121
Ruby
kylemccurley/RB101_Programming_Foundations
/Lesson4_Ruby_Collections/loops1/loop_on_command.rb
UTF-8
160
3.3125
3
[]
no_license
loop do puts 'Should I stop looping?' answer = gets.chomp break if answer.downcase == 'yes' puts "Please enter 'yes' if you would like to stop looping." end
true
d7d83cde59b32641bbb9d2224a910ba352028fba
Ruby
justinkizer/a-A-HW
/W2D1/skeleton/lib/simon.rb
UTF-8
1,862
3.75
4
[]
no_license
class Simon COLORS = %w(red blue green yellow) attr_accessor :sequence_length, :game_over, :seq def initialize(sequence_length = 1) @sequence_length = sequence_length @game_over = false @seq = [] @answer_seq = [] end def play puts "\nWelcome to Simon!" until @game_over take_turn end game_over_message reset_game end def take_turn show_sequence require_sequence round_success_message @sequence_length += 1 @answer_seq = [] end def clear_display system("clear") end def show_sequence sleep(2) add_random_color @seq.each do |color| clear_display puts "\nWatch the color sequence closely!\n\n" sleep(1) puts color.capitalize sleep(1) end end def require_sequence until @answer_seq.length == @seq.length clear_display puts "\nPlease input the next color! (e.g. \"Red\", \"Blue\", \"Green\", or \"Yellow\")\n\n" color_selection = gets.chomp.downcase unless COLORS.include?(color_selection) raise RuntimeError.new("Invalid input") end check_answer(color_selection) end rescue clear_display puts "\nSorry, but that input was not valid!" sleep(2) retry end def check_answer(answer) @answer_seq << answer current = @answer_seq.length - 1 if @answer_seq[current] != @seq[current] @game_over = true @answer_seq = @seq end end def add_random_color color = COLORS.sample @seq << color end def round_success_message clear_display puts "\nGreat job! Next Round!" end def game_over_message clear_display puts "\nGAME OVER, man, GAME OVER!\n\n" end def reset_game @sequence_length = 1 @seq = [] @game_over = false end end if __FILE__ == $PROGRAM_NAME Simon.new.play end
true
895d04542c9a4529ff5914afd9da0f5b93f83db1
Ruby
yonigoldberg/games-of-thrones-board-game
/app/models/deck.rb
UTF-8
988
2.578125
3
[]
no_license
class Deck < ActiveRecord::Base attr_accessible :views, :cards_order, :deck_type_id, :last_viewed_at, :last_viewed_by, :game belongs_to :game serialize :cards_order validates_presence_of :game, :deck_type_id after_save :populate_card_order def peek(peeked_by) unless (self.cards_order.blank?) card = self.cards.find {|x| x.id == self.cards_order.first} update_attributes(:last_viewed_by => peeked_by, :last_viewed_at => DateTime.now, :views => (self.views + 1)) card end end def cards Card.where({:deck_type_id => self.deck_type_id}).all end def place_top_card_at_the_buttom update_attributes(:cards_order => cards_order.rotate) end private def populate_card_order if (!self.cards.blank? && cards_order.blank?) card_ids = Array.new self.cards.each do |card| card_ids << card.id end card_ids = card_ids.shuffle update_attributes(:cards_order => card_ids) end end end
true
052e070d68fc8f1755a4a12c01bb2b2f58806e86
Ruby
brez/red-vector
/lib/redadapter.rb
UTF-8
1,809
2.671875
3
[ "MIT" ]
permissive
#strategy pattern adapter - needs to be delgator #will support other adapters eventually #the adapter code will likely change a lot when we introduce support for say, #redis which supports more complex data structures than pstore class Redadapter include Redpstore #this should be configurable def initialize() connect end def token_frequency(document_id, frequency) payload = get_document(document_id) if document_exists?(document_id) payload ||= {} payload[:token_frequency] = frequency put_document(document_id, payload) end def token(token) put_token(token, {:token => token, :total_frequency => 0, :number_of_postings => 0}) unless token_exists?(token) get_token(token) end def idf(token, idf) payload = get_token(token) raise Redexception::NotAValidTokenException unless payload payload[:idf] = idf put_token(token, payload) end def number_of_postings(token) payload = get_token(token) raise Redexception::NotAValidTokenException unless payload payload[:number_of_postings] end def total_frequency(token) payload = get_token(token) raise Redexception::NotAValidTokenException unless payload payload[:total_frequency] end def posting(token_payload, document_id, posting_frequency) put_token(token_payload[:token], token_payload) document_id_with_frequency = {document_id => posting_frequency} if posting_exists?(token_payload[:token]) document_id_with_frequency.merge!(get_postings_for(token_payload[:token])) end put_posting(token_payload[:token], document_id, { :token => token_payload[:token], :document_id_with_frequency => document_id_with_frequency }) end def all_tokens get_all_tokens end def postings_for(token) get_postings_for(token) end end
true
89db9c105a2bc4ba362b0c5f468f056609c63fcb
Ruby
RiptideWallace/Two-O-Player-Game
/games.rb
UTF-8
1,942
3.59375
4
[]
no_license
module MathGame class Games # When a game begins two new players are created # and pushed to the players array # Current player starts at zero def initialize @players = [] @players.push(Players.new) @players.push(Players.new) @current_player = 0 end def start_game pp "Welcome to our two player math game" # Initially does a loop to determine whose turn # it is while also determining which question # to ask loop do puts "Player #{@current_player}" questions = MathGame::Question_Answer.new.question? pp questions[0] answer = gets.to_i # The following are actions that happen with # specific outcomes # This code causes the current player to # lose a life if they get a question wrong if(answer != questions[1]) @players[@current_player].lives_lost pp "==============NEXT QUESTION=============" # After that answer is determined # this code is used to determine which # player goes next if @current_player == @players.length - 1 @current_player = 0 else @current_player = 1 end # This code is the action that is taken # if an answer is correct else pp "CORRECT!" pp "==============NEXT QUESTION=============" if @current_player == @players.length - 1 @current_player = 0 else @current_player = 1 end end # Now and action is taken on the end game # method if end_game? pp "PLAYER #{@current_player} HAS WON" pp "==============GAME OVER==============" break end end end # How a game is determined to be over def end_game? @players.any? {|player| player.lives == 0 } end end end
true
e70268429111e303d78b32bcc57540f94c27381b
Ruby
AlexStupakov/sea_battle
/lib/ship.rb
UTF-8
192
2.765625
3
[]
no_license
# frozen_string_literal: true class Ship attr_accessor :x_position, :y_position def initialize(x_position, y_position) @x_position = x_position @y_position = y_position end end
true
acf8ed8829b55c2e90e985707e7530a3ccea331a
Ruby
kashiftufail/sunsspot_search
/lib/foo.rb
UTF-8
111
2.796875
3
[]
no_license
module Foo def my_function(x, y) puts (x+y).inspect+"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@" end end
true
b5fbcea5f3ff136a919148cb610527eab9edc970
Ruby
AugustinBoju/mini_jeu_POO
/lib/player.rb
UTF-8
1,896
3.71875
4
[]
no_license
class Player attr_accessor :name, :life_points def initialize(name) @name = name @life_points = 10 end def show_state puts "#{@name} à #{life_points} points de vie" end def gets_damage(dgt) @life_points = @life_points - dgt if @life_points <= 0 puts "le joueur #{@name} a été tué !" end end def attacks(victim) puts "#{@name} attaque #{victim.name}" dmg = compute_damage puts "il lui inflige #{dmg} points de dommages" victim.gets_damage(dmg) end def compute_damage return rand(1..6) end end class HumanPlayer < Player attr_accessor :weapon_level def initialize(name) @name = name @weapon_level = 1 @life_points = 100 end def show_state puts "#{@name} à #{life_points} points de vie et une arme de niveau #{weapon_level}" end def search_weapon new_weapon = rand(1..6) puts "Tu as trouvé une arme de niveau #{new_weapon}" if new_weapon > @weapon_level puts "Youhou ! elle est meilleure que ton arme actuelle : tu la prends." @weapon_level = new_weapon else puts "M@*#$... elle n'est pas mieux que ton arme actuelle..." end end def compute_damage rand(1..6) * @weapon_level end def search_health_pack find = rand(1..6) if find == 1 puts "Tu n'as rien trouvé... " elsif find >= 2 && find <= 5 if @life_points > 50 @life_points = 100 else @life_points = @life_points + 50 end puts "Bravo, tu as trouvé un pack de +50 points de vie !" puts "Tu as maintenant #{@life_points} points de vie" elsif find == 6 if @life_points > 20 @life_points = 100 else @life_points = @life_points + 80 end puts "Waow, tu as trouvé un pack de +80 points de vie !" puts "Tu as maintenant #{@life_points} points de vie" end end end
true
8143e7f3e3c2f3c75d0ac5c88f3371a3610d888c
Ruby
newscorp-ghfb/rspec-sidekiq
/spec/rspec/sidekiq/matchers/be_a_delayed_job_spec.rb
UTF-8
671
2.5625
3
[ "MIT" ]
permissive
require "spec_helper" describe 'delay call' do describe '.delayed_a_job_for' do class FooClass def bar(str) str end end it 'returns true if the method given has been delayed' do FooClass.delay.bar('hello!') expect('bar').to be_a_delayed_job expect('bar2').to_not be_a_delayed_job expect('ba').to_not be_a_delayed_job expect('foobar').to_not be_a_delayed_job end it 'validates the delay time' do FooClass.delay_for(3600).bar('hello!') expect('bar').to be_a_delayed_job(3600) expect('bar').to be_a_delayed_job expect('bar').to_not be_a_delayed_job(7200) end end end
true
66db4dc247d4cfffe2c5d111659bab8ca5ff3e1a
Ruby
Carrison57/Coin-Changer
/test_coin_changer.rb
UTF-8
535
2.6875
3
[]
no_license
require "minitest/autorun" require_relative "coin_changer.rb" class Test_Coin_Changer < Minitest::Test def test_13_returns_1_dime_3_pennies assert_equal({:quarter => 0, :dime => 1, :nickel => 0, :penny => 3}, coin_changer(13)) end def test_1027_returns_41_quarters_2_pennies assert_equal({:quarter => 41, :dime => 0, :nickel => 0, :penny => 2}, coin_changer(1027)) end def test_6400_returns__dimes_3_pennies assert_equal({:quarter => 256, :dime => 0, :nickel => 0, :penny => 0}, coin_changer(6400)) end end
true
51948cc0b627d33637bd828cd78d388e3266a215
Ruby
deanpcmad/RackspaceCloudDNS
/lib/rackspace_cloud_dns/record.rb
UTF-8
1,298
2.625
3
[ "MIT" ]
permissive
module RackspaceCloudDns class Record # List all records for a domain def self.all(domain_id) RackspaceCloudDns::Request.request("domains/#{domain_id}/records", :get) end # Search though all records for a domain def self.search(domain_id, name, type=nil, data=nil) RackspaceCloudDns::Request.request("domains/#{domain_id}/records?name=#{name}&type=#{type}&data=#{data}", :get) end # Show a specified record for a domain def self.show(domain_id, record_id) RackspaceCloudDns::Request.request("domains/#{domain_id}/records/#{record_id}", :get) end # Create a record on a domain def self.create(domain_id, name, type, data, priority=nil) options = {:records => [:name => name, :type => type, :data => data, :priority => priority]} RackspaceCloudDns::Request.request("domains/#{domain_id}/records", :post, options) end # Edit a record for a domain def self.edit(domain_id, record_id, name, data, priority=nil) options = {:name => name, :data => data, :priority => priority} RackspaceCloudDns::Request.request("domains/#{domain_id}/records/#{record_id}", :put, options) end # Destroy a record def self.destroy(domain_id, record_id) RackspaceCloudDns::Request.request("domains/#{domain_id}/records/#{record_id}", :delete) end end end
true
098e558c23c8f6b5b00ec7f6974a9b59b920be7b
Ruby
adamwyeth/blackjack
/player.rb
UTF-8
682
3.78125
4
[]
no_license
require_relative 'hand.rb' #Container for player hands and chip counts class Player attr_reader :name, :chips, :bet attr_accessor :hand def initialize(name, chips) @name = name @chips = chips end def make_bet(bet_amt) raise "Insufficient chips for bet" if bet_amt > @chips @chips -= bet_amt @bet = bet_amt end def push() @chips += @bet end #Pay out 3:2 on blackjack #Pay out double on double def win(blackjack, double) bet_multiplier = blackjack ? 2.5 : (double ? 4 : 2) chips_won = (@bet * bet_multiplier).to_i @chips += chips_won chips_won end def to_s "#{@name} has #{chips} chips" end end
true
4d1f5d8bd61d1a63813639624a5244e8837ddd7a
Ruby
aclarkk/terminalTwtter
/update.rb
UTF-8
431
2.609375
3
[]
no_license
require_relative "config" client = Twitter::REST::Client.new do |config| config.consumer_key = $consumer_key config.consumer_secret = $consumer_secret config.access_token = $access_token config.access_token_secret = $access_token_secret end # get new tweet from a bash argument newTweet = ARGV[0] puts "tweeting '#{newTweet}' now. " # client.update("#{newTweet} -- "); puts "all done, goodbye." exit
true
4d7ce37544a4c2b08add0ecb3e67114ebcb3b4a6
Ruby
jonathan-c/alfred
/app/models/meal_status.rb
UTF-8
962
2.765625
3
[]
no_license
class MealStatus < ActiveRecord::Base attr_accessible :meal_id, :status_id after_create :subtract_remaining_nutrients after_destroy :re_add_remaining_nutrients belongs_to :meal belongs_to :status def subtract_remaining_nutrients calories = [] protein = [] carbs = [] self.status.meals.each do |meal| calories<<meal.calories protein<<meal.protein carbs<<meal.carbs end status.remaining_calories=(self.status.user.req_daily_calories)-(calories.inject(:+)) status.remaining_protein=(self.status.user.req_daily_protein)-(protein.inject(:+)) status.remaining_carbs=(self.status.user.req_daily_carbs)-(carbs.inject(:+)) status.save end def re_add_remaining_nutrients calories = meal.calories protein = meal.protein carbs = meal.carbs status.remaining_calories+=calories status.remaining_protein+=protein status.remaining_carbs+=carbs status.save end end
true
a7225bfb909c74d44569307e86abcda319a586fd
Ruby
lilbyrne/kwk-l1-intro-to-loops-two-step-lab-kwk-students-l1-bal-061818
/two_step_and_repeat.rb
UTF-8
827
3.625
4
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
def first_steps loop do puts "Right foot back" sleep (0.5) puts "Left foot back" sleep (0.5) puts "Right foot back" sleep (0.5) puts "Stop" sleep (0.5) break end end first_steps def a_few_more_steps loop do puts "Right foot steps right and back" sleep (0.5) puts "Left foot crosses over right" sleep (0.5) puts "Right foot steps right" sleep (0.5) if steps >8 break end end a_few_more_steps def how_many_steps? steps = 0 until steps == 30 steps += 1 puts steps if steps%2 == 0 puts "Left" else puts "right" end sleep (0.5) if steps >10 break end how_many_steps? def break_dance # Write a solution that uses the same code as how_many_steps?, but breaks the # loop if steps is equal to 6 end
true
5ab9d83955982fbfe69422a755db87843b39a260
Ruby
eabrawer/learn_ruby2
/timer.rb
UTF-8
70
2.546875
3
[]
no_license
class Timer def initialize(seconds=0) @seconds = seconds end end
true
ea4a0f83f3d335e8efe60f301947c689d0daf8db
Ruby
imendi/assisted_workflow
/lib/assisted_workflow/addons/pivotal.rb
UTF-8
3,054
2.515625
3
[ "MIT" ]
permissive
require "assisted_workflow/exceptions" require "assisted_workflow/addons/base" require "tracker_api" # wrapper class to pivotal api client module AssistedWorkflow::Addons class PivotalStory < SimpleDelegator def initialize(story) super end def owners_str url = "/projects/#{project_id}/stories/#{id}/owners" client.get(url).body.map{|owner| owner["name"]}.join(", ") end end class Pivotal < Base required_options :fullname, :token, :project_id def initialize(output, options = {}) super @client = TrackerApi::Client.new(token: options["token"]) begin @project = @client.project(options["project_id"]) rescue raise AssistedWorkflow::Error, "pivotal project #{options["project_id"]} not found." end @fullname = options["fullname"] @username = options["username"] end def find_story(story_id) if story_id.to_i > 0 log "loading story ##{story_id}" PivotalStory.new(@project.story(story_id)) end end def start_story(story, options = {}) log "starting story ##{story.id}" options.delete(:estimate) if options[:estimate].nil? update_story!(story, options.merge(:current_state => "started")) owner_ids = story.owner_ids if owner_ids.empty? || !owner_ids.include?(@client.me.id) log "assigning story ##{story.id}" update_story!(story, :owner_ids => owner_ids.dup << @client.me.id) end end def finish_story(story, options = {}) log "finishing story ##{story.id}" saved = update_story! story, :current_state => finished_state(story) if saved && options[:note] add_comment_to_story(story, options[:note]) end end def pending_stories(options = {}) log "loading pending stories" states = ["unstarted"] states << "started" if options[:include_started] filter_str = "state:#{states.join(',')} owned_by:#{@client.me.id}" stories = @project.stories(:filter => filter_str, :limit => 5) stories.map do |story| PivotalStory.new(story) end end def valid? !@project.nil? end private def add_comment_to_story(story, text) url = "/projects/#{story.project_id}/stories/#{story.id}/comments" @client.post(url, params: {:text => text}) rescue TrackerApi::Error => e body = e.response[:body] msg = body["possible_fix"] || body["general_problem"] raise AssistedWorkflow::Error, msg end def finished_state(story) if story.story_type == "chore" "accepted" else "finished" end end def update_story!(story, attributes) if story begin story.attributes = attributes story.save rescue TrackerApi::Error => e body = e.response[:body] msg = body["possible_fix"] || body["general_problem"] raise AssistedWorkflow::Error, msg end true end end end end
true
b9bc39777e10cb3dfc9e40204a01368a6b0ff857
Ruby
neosaurrrus/triangle-classification-online-web-sp-000
/lib/triangle.rb
UTF-8
712
3.53125
4
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
class Triangle def initialize(a,b,c) @a = a @b = b @c = c @triangle_lengths = [@a,@b, @c] end def kind # raise an error of triangle is invalid if @a <= 0 || @b <= 0 || @c <= 0 raise TriangleError end @triangle_lengths = @triangle_lengths.sort if @triangle_lengths[0] + @triangle_lengths[1] <= @triangle_lengths[2] raise TriangleError end @a = @triangle_lengths[0] @b = @triangle_lengths[1] @c = @triangle_lengths[2] if @a == @b && @a == @c return :equilateral elsif @a != @b && @a != @c && @b != @c return :scalene else return :isosceles end end class TriangleError < StandardError end end
true
dc5cccd0575028c951bebbfbbf8676df83e932c7
Ruby
MikeAlvarado/Mate
/src/constants/operators.rb
UTF-8
1,733
3.578125
4
[]
no_license
# Operators # Constants of operators used for identifying the operators # specified in the quadruples module Operators EQUAL = 0 NOT_EQUAL = 1 LESS_EQUAL = 2 GREATER_EQUAL = 3 LESS = 4 GREATER = 5 AND = 6 OR = 7 MOD = 8 MULTIPLY = 9 DIVIDE = 10 ADD = 11 SUBTRACT = 12 NOT = 13 ASSIGN = 14 end # Operator Class # A class for the operator so that we can print errors nicely and # easily identify the value of the operator class Operator include Operators attr_reader :id def initialize(id) @id = id end def to_s case @id when EQUAL '==' when NOT_EQUAL '!=' when LESS_EQUAL '<=' when GREATER_EQUAL '>=' when LESS '<' when GREATER '>' when AND '&&' when OR '||' when MOD '%' when MULTIPLY '*' when DIVIDE '/' when ADD '+' when SUBTRACT '-' when ASSIGN '=' when NOT '!' end end def equal? @id == EQUAL end def not_equal? @id == NOT_EQUAL end def less_equal? @id == LESS_EQUAL end def greater_equal? @id == GREATER_EQUAL end def less? @id == LESS end def greater? @id == GREATER end def or? @id == OR end def and? @id == AND end def mod? @id == MOD end def multiply? @id == MULTIPLY end def divide? @id == DIVIDE end def add? @id == ADD end def subtract? @id == SUBTRACT end def assign? @id == ASSIGN end def not? @id == NOT end end
true
ef18c1b58c1dda95816b66a775e45c842ed34ba9
Ruby
grzesiek/git_compound
/lib/git_compound/component/version/tag.rb
UTF-8
509
2.640625
3
[ "MIT" ]
permissive
module GitCompound class Component module Version # Component version as tag # class Tag < VersionStrategy def initialize(repository, tag) @repository = repository @tag = tag end def ref @tag end def sha @repository.tags[@tag] end def reachable? @repository.tags.key?(@tag) end def to_s "tag: #{@tag}" end end end end end
true
09ffb1190c513d5f8a97f8ecb7d50dcc3e239acc
Ruby
Stephanie041996/Capstone_linters_project
/lib/style_linter.rb
UTF-8
2,079
3.140625
3
[ "MIT" ]
permissive
require 'colorize' module StyleLinter def comment_check(line, number) return unless line.include?('/*') @errors << "#{'WARNING'.yellow} :Comments have been detected on the line number #{number} please remove all comments\n" end def space_check(line, number) return unless line =~ /\A\w/ && !line.start_with?(' ') @errors << "#{'ERROR'.red} :Two empty spaces needed on line number #{number}\n " end def px_check(line, number) return unless line.include?('px') @errors << "#{'WARNING'.yellow} :Use REM or EM for measurement units instead of px on line number #{number}\n" end def start_space_check(line, number) @errors << "#{'ERROR'.red} :Remove empty space at start of line number #{number}\n " if line.start_with?(' ') && (line.include?('.') || line.include?('}')) end def colon_space_check(line, number) return unless line.include?(':') sec = line.split(':')[1] @errors << "#{'ERROR'.red} :Add a Space after the colon on the line number #{number}\n" if sec[0] != ' ' end def bracket_check(line, number) stripped = line.delete("\n") return unless line.include?('{') && !stripped.end_with?('{') @errors << "#{'ERROR'.red} :Line number #{number} should end with { please put any text or closing } on a seperate line\n" end def bracket_check_end(line, number) stripped = line.delete("\n") return unless line.include?('}') && !stripped.end_with?('}') @errors << "#{'ERROR'.red} :Line number #{number} should end with }\n" end def empty_space_check(line, number) stripped = line.delete("\n") @errors << "#{'ERROR'.red} :Tailing spaces have been detected on the line number #{number}\n" if stripped.end_with?(' ') end def ending_check(line, number) if line.include?(':') && !line.include?(';') @errors << "#{'WARNING'.yellow} :No closing ; detected on the line number #{number}\n" elsif line.include?(';') && !line.include?(':') @errors << "#{'WARNING'.yellow} :Missing : detected on the line number #{number}\n" end end end
true
9aad3224c3c5d2ca26e26596689b5d33f43440cf
Ruby
jitendra1989/sent_buddy_beers
/lib/tweet.rb
UTF-8
2,475
3.171875
3
[]
no_license
#require "rubygems" #require "active_support/core_ext" #require "test/unit" class Tweet class Invalid < Exception; end attr_accessor :text, :user, :quantity, :drink, :memo def initialize(text) self.text = text self.parse raise Invalid if [user, quantity, drink].any?(&:blank?) end def drink=(drink) @drink = drink.to_s.gsub(/#buddybeer/, "").strip.presence || "beer" end def quantity=(quantity) @quantity = (quantity.to_s.gsub(/a/, "").strip.presence || 1).to_i end def drink=(drink) @drink = drink.to_s.gsub(/#buddybeer/, "").strip.presence || "beer" end def memo=(memo) @memo = memo.to_s.gsub(/#buddybeers?/, "").strip end protected def parse self.text =~ /io \@(\w+)\s*(|a|\d+) (#buddybeer|beer)s?( for )?((.*)#buddybeers?|(.*))/i self.user, self.quantity, self.drink, self.memo = $1, $2, $3, $5 end end if $0 == __FILE__ class TweetTest < Test::Unit::TestCase def setup @tweet = Tweet.new("IO @matid a beer for writing me a regex to parse this tweet #buddybeer") end def test_user assert_equal "matid", @tweet.user end def test_drink assert_equal "beer", @tweet.drink end def test_quantity assert_equal 1, @tweet.quantity end def test_memo assert_equal "writing me a regex to parse this tweet", @tweet.memo end def test_users_with_dashes tweet = Tweet.new("IO @user_with_dashes a beer for writing me a regex to parse this tweet #buddybeers") assert_equal "user_with_dashes", tweet.user end def test_numeric_quantity tweet = Tweet.new("IO @user 2 beers for a favour #buddybeer") assert_equal 2, tweet.quantity end def test_default_quantity tweet = Tweet.new("IO @user beer for a favour #buddybeer") assert_equal 1, tweet.quantity end def test_inline_hashtag tweet = Tweet.new("IO @user #buddybeer for a favour") assert_equal "beer", tweet.drink assert_equal "a favour", tweet.memo end def test_no_memo tweet = Tweet.new("IO @user a beer #buddybeer") assert_equal "beer", tweet.drink assert tweet.memo.blank? end def test_no_memo_with_inline_hashtag tweet = Tweet.new("IO @user #buddybeer") assert_equal "beer", tweet.drink assert tweet.memo.blank? end def test_raising_exceptions_on_incorrect_tweets assert_raise(Tweet::Invalid){ Tweet.new("WTF?") } end end end
true
7fb8b077d3eadfef85b370336049b63c78ef82fc
Ruby
Gurmal/ArenaMasters
/app/models/gladiator.rb
UTF-8
1,820
2.6875
3
[ "MIT" ]
permissive
#require 'Dice' -- auto included by Rails #loglevel legacy from ruby still used some but logger is replacing slowly $loglevel = 1 class Gladiator < ApplicationRecord belongs_to :team has_many :fight_items has_many :fights, through: :fight_items before_create :setstats def setStyle(fightStyle) self.fightStyle = fightStyle self.save end def getStyleName FightStyle.find(fightStyle).name end def setName(name) self.name = name self.save end def to_s "Name:#{self.name} Str:#{self.str} Con:#{self.con} Dex:#{self.dex} Wnd:#{self.wounds} Rep:#{self.reputation} Val:#{self.value} Style:#{self.fightStyle} Spd:#{self.spd}" end def hp _hp = (10 + self.con) - self.wounds end def setFirstFight self.firstfight = Time.new self.save end def addWound self.wounds += 1 self.save end def killMe self.death = Time.new self.save end def rollInitiative _initiative = rand(20)+1 _initiative += 2 if self.spd.to_i >18 logger.debug "coming through rollInitiative id:#{self.id} init:#{_initiative}" return _initiative end private def setstats statdie = Dice.new(6,3) _str = statdie.roll self.str = _str _dex = statdie.roll self.dex = _dex self.spd = statdie.roll _con = statdie.roll self.con = _con self.chr = statdie.roll self.intl = statdie.roll # @value = @str + @dex + @spd + @con + @chr + @intl if _dex > 18 self.hitmod = 2 else self.hitmod = 0 end if _str > 18 self.strmod = 2 else self.strmod = 0 end self.birth = Time.new #self.firstfight = '1/1/2001' #self.death = '1/1/2001' self.fightStyle = rand(5)+1 self.wounds = 0 self.reputation = 0 self.exp = 0 end end
true
14c794fb455500b6c2f36f0a6201e7a56463fdb6
Ruby
srawlins/msieve
/lib/msieve.rb
UTF-8
857
2.5625
3
[]
no_license
# Thank you, Nokogiri require 'rbconfig' ENV['PATH'] = [File.expand_path( File.join(File.dirname(__FILE__), "..", "ext") ), ENV['PATH']].compact.join(';') if RbConfig::CONFIG['host_os'] =~ /(mswin|mingw|mingw32)/i require File.dirname(__FILE__) + '/../ext/msieve' class Msieve def self.clear_log(log_name = "msieve.log") if File.exist? log_name File.delete log_name end puts "Cleared! (but not really)." end def prime? if factors return (factors.size == 1 and factors[0].factor_type != :composite) else raise "Cannot test for primality. "+inspect+" has not been factored (use Msieve#factor!)." end end end begin; GMP::Z module GMP; class Z def factor Msieve.new(to_i).factor! end def prime? Msieve.new(to_i).factor!.size == 1 end end; end rescue NameError end
true
5aa23454923e39e48821d298d0d0ff91fc2da180
Ruby
JustinData/GA-WDI-Work
/w03/d03/Paris/load_data.rb
UTF-8
582
3.109375
3
[]
no_license
require 'pg' # bring the data into memory # create an array to format the data to put into the table. db_conn = PG.connect( dbname: "sandbox" ) file = File.new("data.txt", "a+") file.each do |line| player_array = line.split(",") query = "INSERT INTO players " query += "(name,age,team,games,points) VALUES" query += "(" query += "'#{player_array[0].gsub("'", "")}', #{player_array[1]}," query += "'#{player_array[2]}', #{player_array[3]}," query += "#{player_array[4]}" query += ");" # this does the actual inserting db_conn.exec( query ) end db_conn.close file.close
true
8d91feafdc9fca656a6a189aae18373bf3adab9b
Ruby
technohippy/red-grape
/test/test_on_the_nature_of_pipes.rb
UTF-8
3,010
2.859375
3
[ "MIT" ]
permissive
require 'test/unit' require 'red_grape' # test the patterns shown in: http://markorodriguez.com/2011/08/03/on-the-nature-of-pipes/ class OnTheNatureOfPipesTest < Test::Unit::TestCase def setup @graph = RedGrape.load_graph 'data/graph-example-1.xml' end def test_basic assert_equal '1', @graph.v(1)[].id assert_equal %w(2 3 4), @graph.v(1).out[].map(&:id).sort assert_equal %w(josh lop vadas), @graph.v(1).out.name[].sort paths = @graph.v(1).out.name.paths[] assert_equal 3, paths.size assert_equal [4, 4, 4], paths.map(&:size) assert_equal %w[V Out Property(name) Path], @graph.v(1).out.name.paths.to_a end def test_filter assert_equal %w(2 4), @graph.v(1).out('knows')[].map(&:id).sort assert_equal %w(2), @graph.v(1).out('knows').filter{it.age < 30}[].map(&:id).sort assert_equal %w(vadas), @graph.v(1).out('knows').filter{it.age < 30}.name[].sort assert_equal [5], @graph.v(1).out('knows').filter{it.age < 30}.name.transform{it.size}[].sort assert_equal %w[V Out(knows) Filter Property(name) Transform], @graph.v(1).out('knows').filter{it.age < 30}.name.transform{it.size}.to_a end def test_side_effect assert_equal 'marko', @graph.v(1).side_effect{@x = it}[].name assert_equal %w(3), @graph.v(1).side_effect{@x = it}.out('created')[].map(&:id).sort assert_equal %w(1 4 6), @graph.v(1).side_effect{@x = it}.out('created').in('created')[].map(&:id).sort assert_equal %w(4 6), @graph.v(1).side_effect{@x = it}.out('created').in('created').filter{it != @x}[].map(&:id).sort assert_equal %w(V SideEffect Out(created) In(created) Filter), @graph.v(1).side_effect{@x = it}.out('created').in('created').filter{it != @x}.to_a end def test_if_then_else #assert_equal ['vadas', ['ripple', 'lop']], assert_equal ['vadas', 'ripple', 'lop'], @graph.v(1).out('knows').if_then_else(_{it.age < 30}, _{it.name}, _{it.out('created').name})[].to_a end def test_back assert_equal %w(josh vadas), @graph.v(1).out('knows').name[].to_a.sort assert_equal %w(vadas), @graph.v(1).out('knows').name.filter{it[0] == 'v'}[].to_a assert_equal %w(2), @graph.v(1).out('knows').name.filter{it[0] == 'v'}.back(2)[].to_a.map(&:id) assert_equal %w(V Out(knows) Property(name) Filter Back), @graph.v(1).out('knows').name.filter{it[0] == 'v'}.back(2).to_a assert_equal %w(2), @graph.v(1).out('knows').as('here').name.filter{it[0] == 'v'}.back('here')[].to_a.map(&:id) end def test_loop assert_equal %w(3 5), @graph.v(1).out.out[].to_a.map(&:id).sort assert_equal %w(3 5), @graph.v(1).out.loop(1){loops < 3}[].to_a.map(&:id).sort assert_equal %w(lop ripple), @graph.v(1).out.loop(1){loops < 3}.name[].sort assert_equal %w(V Out Loop Property(name)), @graph.v(1).out.loop(1){loops < 3}.name.to_a end end
true
3ff4a59423f7598e1e94c0e68570c8805aedaf93
Ruby
msoanes/convent
/lib/relation.rb
UTF-8
1,734
2.921875
3
[]
no_license
require_relative 'queriable' class Relation def self.dup_hash(hsh) result = {} hsh.each do |key, val| result[gen_dup(key)] = gen_dup(val) end result end def self.gen_dup(item) if item.is_a?(Hash) dup_hash(item) else item.dup end rescue item end def initialize(class_name, query_hash = nil) @class_name = class_name @query_hash = query_hash || { select: nil, from: class_model.table_name, where: nil, join: nil, limit: nil, offset: nil } end def method_missing(name, *args, &blk) [].methods.include?(name) ? results.send(name, *args, &blk) : super end def selects(*params) deep_dup.selects!(*params) end def selects!(*params) @query_hash[:select] = params self end def joins(*assocs) deep_dup.joins!(*assocs) end def joins!(*assocs) @query_hash[:join] ||= [] @query_hash[:join] += assocs self end def where(params) deep_dup.where!(params) end def where!(params) @query_hash[:where] ||= {} params.each do |column, value| @query_hash[:where][column] = value end self end def limit(num) deep_dup.limit!(num) end def limit!(num) @query_hash[:limit] = num self end def offset(num) deep_dup.offset!(num) end def offset!(num) @query_hash[:offset] = num self end private include Queriable def class_model @class_name.constantize end def results @results ||= execute_query end def execute_query class_model.parse_all(DBConnection.execute(build_query, params)) end def deep_dup Relation.new(@class_name, self.class.dup_hash(@query_hash)) end end
true
adb40aaf7943c4812bf77b640a24b947d0c8a5c3
Ruby
makiichikawa/ruby-practices
/08.ls_object/test/ls_short_format_test.rb
UTF-8
1,194
2.59375
3
[]
no_license
# frozen_string_literal: true require 'date' require 'minitest/autorun' require_relative '../lib/ls_short_format' require_relative '../lib/ls_directory' class LsShortFormatTest < Minitest::Test def setup system('mkdir ~/test') system('touch ~/test/.test.txt') system('touch ~/test/test.txt') @directory = LsDirectory.new('~/test') end def test_execute output = <<~TEXT test.txt#{' '} TEXT options = { a: false, r: false } ls = LsShortFormat.new(@directory, options) assert_equal output, ls.execute end def test_execute_a_option output = <<~TEXT .#{' '} ..#{' '} .test.txt#{' '} test.txt#{' '} TEXT options = { a: true, r: false, l: false } ls = LsShortFormat.new(@directory, options) assert_equal output, ls.execute end def test_execute_r_option output = <<~TEXT test.txt#{' '} .test.txt#{' '} ..#{' '} .#{' '} TEXT options = { a: true, r: true, l: false } ls = LsShortFormat.new(@directory, options) assert_equal output, ls.execute end def teardown system('rm -R ~/test') end end
true
6f17d1e4822097ae6ccf072a681d3ce2383b7a7a
Ruby
Eagerlearn/backend_mod_1_prework
/section2/exercises/methods.rb
UTF-8
2,710
4.96875
5
[]
no_license
# In the below exercises, write code that achieves # the desired result. To check your work, run this # file by entering the following command in your terminal: # `ruby section2/exercises/methods.rb` # Example: Write a method that when called will print your name: def print_name p "Severus Snape" end print_name # Write a method that takes a name as an argument and prints it: # defines function telling it to print arguments without needing to unpack def print_name(name) # prints to demonstrate that the argument works puts "#{name}" # end code block end # calls function assigns value to argument print_name("Albus Dumbledore") # Write a method that takes in 2 numbers as arguments and prints # their sum. Then call your method three times with different arguments passed in: # defines function telling it to print arguments without needing to unpack def add(a, b) # prints to demonstrate that the argument works puts "ADDING #{a} + #{b}" # returns the value of add function return a + b # end code block end # calls function assigns value to argument first_call = add(10, 5) puts "#{first_call}" # calls function assigns value to argument second_call = add(20, 15) puts "#{second_call}" # calls function assigns value to argument third_call = add(30, 25) puts "#{third_call}" puts "That appears to add up" # Write a method that takes in two strings as arguments and prints # a concatenation of those two strings. Example: The arguments could be # (man, woman) and the end result might output: "When Harry Met Sally". # Then call your method three times with different arguments passed in. def sports(city, team) puts "The #{city} #{team} are my favorites" end first_city = "Philadelphia" first_team = "Eagles" sports(first_city, first_team) second_city = "Philadelphia" second_team = "Sixers" sports(second_city, second_team) third_city = "Philadelphia" third_team = "Phillies" sports(third_city, third_team) #------------------- # PART 3: Naming is Hard #------------------- # Naming is notoriously hard in programming. It is a skill to name a variable or function concisely enough that it is reasonable to type, but descriptive enough that others can infer the meaning. # Look at the code you wrote for the previous YOU DO🎈 - what did you name the function, and why? I named it sports because of the focus on how I would use the arguments to identify the cities and teams I like. # What did you name each parameter, and why? This ties to the last question. I named the parameters based on the ease to call them in order. # EXPLAIN: I wanted to make sure that as I was writing the code my focus was on coding correctly and to minimize effort trying to recall/use the correct one.
true
6e8a8fde58ed9a0740579a7e3757620571c3629b
Ruby
jwirjo/disclosure-backend-static
/process.rb
UTF-8
5,050
2.59375
3
[]
no_license
require_relative './environment.rb' require 'fileutils' require 'open-uri' def build_file(filename, &block) filename = File.expand_path('../build', __FILE__) + filename FileUtils.mkdir_p(filename) unless File.exist?(filename) File.open(File.join(filename, 'index.json'), 'w', &block) end # first, create OfficeElection records for all the offices to assign them IDs OaklandCandidate.select(:Office, :election_name).order(:Office, :election_name).distinct.each do |office| OfficeElection .where(name: office.Office, election_name: office.election_name) .first_or_create end # second, process the contribution data # load calculators dynamically, assume each one defines a class given by its # filename. E.g. calculators/foo_calculator.rb would define "FooCalculator" Dir.glob('calculators/*').each do |calculator_file| basename = File.basename(calculator_file.chomp('.rb')) class_name = ActiveSupport::Inflector.classify(basename) begin calculator_class = class_name.constantize calculator_class .new( candidates: OaklandCandidate.all, ballot_measures: OaklandReferendum.all, committees: OaklandCommittee.all ) .fetch rescue NameError => ex if ex.message =~ /uninitialized constant #{class_name}/ $stderr.puts "ERROR: Undefined constant #{class_name}, expected it to be "\ "defined in #{calculator_file}" puts ex.message exit 1 else raise end end end # third, write everything out to the build files OAKLAND_LOCALITY_ID = 2 ELECTIONS = [ { id: 1, date: '2016-11-08', election_name: 'oakland-2016', is_current: true }, { id: 2, date: '2018-11-06', election_name: 'oakland-2018' }, { id: 3, date: '2018-11-06', election_name: 'berkeley-2018' }, ] build_file('/locality/search') do |f| f.puts JSON.pretty_generate([{ name: 'Oakland', type: 'city', id: OAKLAND_LOCALITY_ID }]) end build_file("/locality/#{OAKLAND_LOCALITY_ID}") do |f| f.puts JSON.pretty_generate([{ name: 'Oakland', type: 'city', id: OAKLAND_LOCALITY_ID }]) end ELECTIONS.each do |election| candidates = OfficeElection.where(election_name: election[:election_name]) referendums = OaklandReferendum.where(election_name: election[:election_name]) files = [ "/ballot/#{election[:id]}", ("/locality/#{OAKLAND_LOCALITY_ID}/current_ballot" if election[:is_current]) ].compact files.each do |filename| build_file(filename) do |f| f.puts({ id: 1, ballot_items: ( candidates.map(&:as_json) + referendums.map(&:as_json) ), date: election[:date], locality_id: OAKLAND_LOCALITY_ID, }.to_json) end end end OfficeElection.find_each do |office_election| build_file("/office_election/#{office_election.id}") do |f| f.puts JSON.pretty_generate(office_election.as_json.merge(ballot_id: 1)) end end OaklandCandidate.includes(:office_election, :calculations).find_each do |candidate| %W[ /candidate/#{candidate.id} ].each do |candidate_filename| build_file(candidate_filename) do |f| # # To add a field to one of these endpoints, add it to the '#as_json' # method in models/oakland_candidate.rb # f.puts candidate.to_json end end end OaklandCommittee.includes(:calculations).find_each do |committee| build_file("/committee/#{committee['Filer_ID']}") do |f| f.puts committee.to_json end build_file("/committee/#{committee['Filer_ID']}/contributions") do |f| f.puts JSON.pretty_generate(committee.calculation(:contribution_list) || []) end build_file("/committee/#{committee['Filer_ID']}/opposing") do |f| f.puts JSON.pretty_generate(committee.calculation(:opposition_list) || []) end end OaklandReferendum.find_each do |referendum| build_file("/referendum/#{referendum.id}") do |f| f.puts JSON.pretty_generate(referendum.as_json.merge(ballot_id: 1)) end build_file("/referendum/#{referendum.id}/supporting") do |f| f.puts JSON.pretty_generate(referendum.as_json.merge( supporting_organizations: referendum.calculation(:supporting_organizations) || [], total_contributions: referendum.calculation(:supporting_total) || [], contributions_by_region: referendum.calculation(:supporting_locales) || [], contributions_by_type: referendum.calculation(:supporting_type) || [], )) end build_file("/referendum/#{referendum.id}/opposing") do |f| f.puts JSON.pretty_generate(referendum.as_json.merge( opposing_organizations: referendum.calculation(:opposing_organizations) || [], total_contributions: referendum.calculation(:opposing_total) || [], contributions_by_region: referendum.calculation(:opposing_locales) || [], contributions_by_type: referendum.calculation(:opposing_type) || [], )) end end build_file('/stats') do |f| f.puts JSON.pretty_generate( date_processed: TZInfo::Timezone.get('America/Los_Angeles').now.to_date, ) end
true
c9b9cd8669324824bd012d8cd36aafe2dd8ab656
Ruby
akasata/gulp-opal
/test/ruby/hoge_class.rb
UTF-8
203
3.84375
4
[ "MIT" ]
permissive
class HogeClass attr_accessor :text def initialize(text) @text = text end def print_text puts @text end end hoge = HogeClass.new('Hello Opal World!') hoge.print_text
true
194ac2e0e8c1d589d26c08e68086129b4bb96bee
Ruby
DaniG2k/RubyCrawler
/lib/ruby_crawler/spider.rb
UTF-8
2,506
2.765625
3
[]
no_license
module RubyCrawler class Spider def initialize @stored = [] @frontier = [] @assets = {} end def stored @stored end def assets @assets end def start_crawl if RubyCrawler.configuration.polite? parser = RubyCrawler::RobotsParser.new parser.parse_robots_txt end RubyCrawler.configuration.start_urls.each do |url| @frontier << url end until @frontier.empty? url = @frontier.shift @stored << url puts "Stored: #{url}\n" parse_page(url) end end def parse_page(url) begin html_doc = ::Nokogiri::HTML(open(url)) # Disregard the page if it includes a meta robots tag with a # noindex directive. if RubyCrawler.configuration.polite? && html_doc.xpath('//meta[@name="robots"]/@content').map(&:value).any? {|elt| elt.include?('noindex')} puts "Noindex meta-tag detected. Removing #{url}" # Remove last url. @stored.pop else # Gather static assets in the @assets hash. @assets[url] = { :css => html_doc.css('link[rel=stylesheet]').map {|css| URI.join(url, css['href']).to_s }, :images => html_doc.xpath("//img/@src").map {|img| URI.join(url, img).to_s }, :javascript => html_doc.css('script').map {|js| src = js['src']; src.to_s unless src.nil?}.compact } links = html_doc.xpath('//a[@href]').map do |link| url = URI.join(url, link['href']).to_s if is_relative?(url) || matches_include_exclude_rules url end end links.compact.each do |link| if !@frontier.include?(link) && !@stored.include?(link) @frontier << link end end end rescue URI::InvalidURIError => e puts "Invalid url: #{url}\n#{e}" rescue StandardError => e puts e.message end end def matches_include_exclude_rules matches_include_patterns?(url) && !matches_exclude_patterns?(url) end def is_relative?(url) !(url =~ /^\//).nil? end def matches_include_patterns?(url) RubyCrawler.configuration.include_patterns.any? do |pat| !(url =~ pat).nil? end end def matches_exclude_patterns?(url) RubyCrawler.configuration.exclude_patterns.any? do |pat| !(url =~ pat).nil? end end end end
true
56e320e1fcda8c52c75460c5d51a64583b0e19fd
Ruby
egogo/battle_pets
/service_wrappers/test/contest_service_wrapper_test.rb
UTF-8
2,670
2.609375
3
[]
no_license
require File.expand_path '../test_helper.rb', __FILE__ describe "ContestServiceWrapper" do let(:described_class) { ContestServiceWrapper } let(:instance) { described_class.new } let(:contest_json) { { id: 42, title: 'Contest #42', type: 'wit', first_pet_id: 5, second_pet_id: 12, winner_id: 5, started_at: '2016-08-02T18:25:43.511Z', finished_at: '2016-08-02T18:26:13.511Z' } } describe '#get' do describe 'when context exists' do before do stub_request(:get, "http://localhost:5000/api/v1/contests/42.json").to_return(status: 200, body: contest_json.to_json ) end it 'returns an instance of ContestServiceWrapper::Contest with all properties assigned' do result = instance.get(42) result.must_be_instance_of(ContestServiceWrapper::Contest) result.id.must_equal 42 result.title.must_equal 'Contest #42' result.type.must_equal 'wit' result.first_pet_id.must_equal 5 result.second_pet_id.must_equal 12 result.winner_id.must_equal 5 result.started_at.must_equal Time.parse('2016-08-02T18:25:43.511Z') result.finished_at.must_equal Time.parse('2016-08-02T18:26:13.511Z') end end describe 'when contest does not exists' do before do stub_request(:get, "http://localhost:5000/api/v1/contests/42.json").to_return(status: 404, body: '' ) end it 'raises an error' do err = -> { instance.get(42) }.must_raise ContestServiceWrapper::InvalidContestError err.message.must_equal 'Contest with ID#42 does not exist.' end end describe 'when service is down' do before do stub_request(:get, "http://localhost:5000/api/v1/contests/42.json").to_return(status: 500, body: '' ) end it 'raises an error' do err = -> { instance.get(42) }.must_raise ContestServiceWrapper::ServiceNotAvailableError err.message.must_equal 'Contest service at url: http://localhost:5000 is not available at this time.' end end end describe 'ContestServiceWrapper::Contest' do let(:contest) { instance.get(42) } before do stub_request(:get, "http://localhost:5000/api/v1/contests/42.json").to_return(status: 200, body: contest_json.merge(winner_id: nil).to_json ) stub_request(:put, "http://localhost:5000/api/v1/contests/42.json").with(body: {"token"=>"service_token", "winner_id"=>"123"}).to_return(status: 204, body: "") end describe '#set_winner' do it 'sends winner id to the service' do contest.set_winner(123) end end end end
true
725c293059d8ee3b1ad549c4fc8927e310c2bbff
Ruby
Ricky199X/ttt-with-ai-project-online-web-pt-041519
/lib/players/computer.rb
UTF-8
319
2.828125
3
[]
no_license
module Players class Players::Computer < Player def move(board) board.cells.each_with_index do |cell, index| if cell == " " position = index + 1 return position.to_s end end end end end
true
1d5c82ebfd68fb453bc51db55926749e75024b1c
Ruby
wrld3d/transitland-datastore
/app/services/gtfs_stop_time_service.rb
UTF-8
5,423
2.765625
3
[ "MIT" ]
permissive
class GTFSStopTimeService def self.debug(msg) log(msg) end def self.clean_stop_times(stop_times) # Sort by stop_sequence stop_times.sort_by! { |st| st.stop_sequence } # If we only have 1 time, assume it is both arrival and departure stop_times.each do |st| (st.arrival_time = st.departure_time) if st.arrival_time.nil? (st.departure_time = st.arrival_time) if st.departure_time.nil? end # Ensure time is positive current = stop_times.first.arrival_time stop_times.each do |st| s = st.arrival_time fail Exception.new('cannot go backwards in time') if s && s < current current = s if s s = st.departure_time fail Exception.new('cannot go backwards in time') if s && s < current current = s if s end # These two values are required by spec fail Exception.new('missing first departure time') if stop_times.first.departure_time.nil? fail Exception.new('missing last arrival time') if stop_times.last.arrival_time.nil? return stop_times end def self.interpolate_stop_times(stop_times, shape_id) stop_times = clean_stop_times(stop_times) # Return early if possible gaps = interpolate_find_gaps(stop_times) return stop_times if gaps.size == 0 # Measure stops along line trip_pattern = stop_times.map(&:stop_id) # First pass: line interpolation distances = get_shape_stop_distances(trip_pattern, shape_id) gaps.each do |gap| o, c = gap interpolate_gap_distance(stop_times[o..c], distances) end # Second pass: distance interpolation gaps = interpolate_find_gaps(stop_times) gaps.each do |gap| o, c = gap interpolate_gap_linear(stop_times[o..c]) end return stop_times end def self.get_shape_stop_distances(trip_pattern, shape_id) # Calculate line percent from closest point to stop distances = {} s = 'gtfs_stops.id, ST_LineLocatePoint(shapes.geometry::geometry, ST_ClosestPoint(shapes.geometry::geometry, gtfs_stops.geometry::geometry)) AS line_s' g = GTFSStop.select(s) # Create shape if necessary # if shape_id g = g.joins('INNER JOIN gtfs_shapes AS shapes ON true') # else # shape_id = 0 # g = g.joins("INNER JOIN (SELECT 0 as id, ST_MakeLine(geometry) AS geometry FROM (SELECT geometry FROM gtfs_stops INNER JOIN (SELECT unnest,ordinality FROM unnest( ARRAY[#{trip_pattern.join(',')}] ) WITH ORDINALITY) as unnest ON gtfs_stops.id = unnest ORDER BY ordinality) as q) AS shapes ON true") # end # Filter g = g.where('shapes.id': shape_id, id: trip_pattern) # Run g.each do |row| distances[row.id] = row.line_s end return distances end def self.interpolate_find_gaps(stop_times) gaps = [] o, c = nil, nil stop_times.each_with_index do |st, i| # close an open gap # puts "i: #{i} st: #{st.stop_sequence} stop: #{st.stop_id} arrival_time: #{st.arrival_time} departure_time: #{st.departure_time}" if o && st.arrival_time gaps << [o, i] if (i-o > 1) o = nil end # open a new gap if o.nil? && st.departure_time o = i end end return gaps end def self.interpolate_gap_distance(stop_times, distances) # debug("trip: #{stop_times.first.trip_id} interpolate_gap_distance: #{stop_times.first.stop_sequence} -> #{stop_times.last.stop_sequence}") # open and close times o_time = stop_times.first.departure_time c_time = stop_times.last.arrival_time # open and close distances o_distance = distances[stop_times.first.stop_id] c_distance = distances[stop_times.last.stop_id] # check that we can interpolate reasonably p_distance = o_distance stop_times.each do |st| i_distance = distances[st.stop_id] return unless i_distance return if i_distance < p_distance # cannot backtrack return if i_distance > c_distance # cannot exceed end p_distance = i_distance end # interpolate on distance # debug("\tlength: #{c_distance - o_distance} duration: #{c_time - o_time}") # debug("\to_distance: #{o_distance} o_time: #{o_time}") stop_times[1...-1].each do |st| i_distance = distances[st.stop_id] pct = (i_distance - o_distance) / (c_distance - o_distance) i_time = (c_time - o_time) * pct + o_time # debug("\ti_distance: #{i_distance} pct: #{pct} i_time: #{i_time}") st.arrival_time = i_time st.departure_time = i_time st.interpolated = 1 end # debug("\tc_distance: #{c_distance} c_time: #{c_time}") return true end def self.interpolate_gap_linear(stop_times) # debug("trip: #{stop_times.first.trip_id} interpolate_gap_linear: #{stop_times.first.stop_sequence} -> #{stop_times.last.stop_sequence}") # open and close times o_time = stop_times.first.departure_time c_time = stop_times.last.arrival_time # interpolate on time p_time = o_time # debug("\tduration: #{c_time - o_time}") # debug("\ti: 0 o_time: #{o_time}") stop_times[1...-1].each_with_index do |st,i| pct = pct = (i+1) / (stop_times.size.to_f-1) i_time = (c_time - o_time) * pct + o_time # debug("\ti: #{i+1} pct: #{pct} i_time: #{i_time} ") st.arrival_time = i_time st.departure_time = i_time st.interpolated = 2 end # debug("\ti: #{stop_times.size-1} c_time: #{c_time}") end end
true
dfb0a9a8187db715dd41453208e6442d1bea4bad
Ruby
chinshr/merchant_sidekick
/lib/merchant_sidekick/money.rb
UTF-8
2,040
3.078125
3
[ "MIT" ]
permissive
module MerchantSidekick # Extensions to the money gem. module Money # Used to define a composed field that plays well with +merchant_sidekick+. Fore example, use the money # class method to define a price attribute for product instances. A money object is composed of +cents+ # and +currency+ fields in the database. # # @param [Symbol] name Lets you define the name of the attribute # @option options [Symbol] :cents Sets the column name to use as cents amount, default "cents". # @option options [Symbol] :currency Sets the column name to use as currency, default "currency". # # @example # class Product < ActiveRecord::Base # money :price, :cents => "price_cents", :currency => "price_currency" # end # # @product = Product.new :price_cents => 1050, :price_currency => "USD" # @product.price.format # => "$10.50" def money(name, options = {}) options = {:cents => "#{name}_cents".to_sym}.merge(options) mapping = [[options[:cents].to_s, 'cents']] mapping << ([options[:currency].to_s, 'currency_as_string']) if options[:currency] composed_of name, :class_name => "::Money", :mapping => mapping, :constructor => Proc.new {|cents, currency| ::Money.new(cents || 0, currency || ::Money.default_currency)}, :converter => Proc.new {|value| value.respond_to?(:to_money) ? value.to_money : raise(ArgumentError, "Can't convert #{value.class} to Money")} if options[:currency] class_eval(<<-END, __FILE__, __LINE__+1) def currency ::Money::Currency.wrap(self[:#{options[:currency]}]) end def currency_as_string self[:#{options[:currency]}] end END else class_eval(<<-END, __FILE__, __LINE__+1) def currency ::Money.default_currency end def currency_as_string ::Money.default_currency.to_s end END end end end end
true
d15af102b0eede7d7b3cc7039c14784f01f44401
Ruby
grantneufeld/solidifier
/lib/solidifier/url_tool.rb
UTF-8
2,713
3.21875
3
[ "MIT" ]
permissive
module Solidifier # URL utility methods. class UrlTool attr_reader :path attr_reader :source_url attr_reader :path_args def initialize(params={}) @path = params[:path] # strip any args from the source url match = params[:source_url].match /\A([^#\?]+)/ @source_url = match[1] # split the path into the part without args, and the args (if any) match = @path.match /\A([^#\?]*)([#\?].*)?\z/ @path_noargs = match[1] @path_args = match[2].to_s end # Convert a given path to the full url, based on a source url. # E.g., path: '/d/e', source_url: 'http://a.b/c.html' converts to 'http://a.b/d/e' # path: 'e/f', source_url: 'http://a.b/c/d.html' converts to 'http://a.b/c/e/f' # path: '/d/e', source_url: 'http://a.b/c.html' converts to 'http://a.b/d/e' def full_url if path.match /\A\// flatten_root_relative elsif path.match /\A[a-z0-9]+:/ path # it’s already a full url else flatten_subpath_relative end end # Strip away any “?” arguments or “#” anchors. def full_url_no_args url = full_url match = url.match /\A([^#\?]+)[#\?]/ if match match[1] else url end end # Is this url a sub-url of the given parent url? def contained_in?(parent_url) full_url.match /\A#{parent_url}/ end #protected # Merge the path (which must be relative to the root) with the root url. def flatten_root_relative source_root_url + path[1..-1] # strip the leading “/” from the path end # Merge the path (which is assumed to be relative to the source url’s directory) with the directory url. def flatten_subpath_relative source_root_url_noslash + resolved_path + path_args end # The root url of the source url. def source_root_url match = source_url.match /\A([^:\/]+:[\/]*[^\/]+)/ match[1] + '/' end # The root url of the source url. def source_root_url_noslash match = source_url.match /\A([^:\/]+:[\/]*[^\/]+)/ match[1] end # The result of merging the path and the source url’s path. # Will handle “../” directory reversal. def resolved_path File.absolute_path path_noargs, source_directory_path end # The path part of the source url. # E.g., “http://a.b/c/d.html” would return “/c/” def source_directory_path match = source_url.match /\A[^:]+:\/*[^\/]*(\/.*\/?)[^\/]*\z/ match = match[1].match /\A(.*\/)[^\/]*\z/ match[1] end def path_noargs match = path.match /\A([^#\?]*)([#\?].*)?\z/ match[1] end end end
true
3d8a744856abce6dc23cd224dddf79f7fcda57c5
Ruby
lstemp1234/data-engineering
/app/models/import.rb
UTF-8
1,100
2.90625
3
[]
no_license
class Import < ActiveRecord::Base validates_presence_of :purchaser_name validates_presence_of :item_description validates_presence_of :item_price validates_presence_of :purchase_count validates_presence_of :merchant_address validates_presence_of :merchant_name validates_numericality_of :item_price, greater_than_or_equal_to: 0.0 validates_numericality_of :purchase_count, greater_than_or_equal_to: 1 def self.import_data(data) gross_revenue = 0.0 Import.transaction do data.each do |row| record = { purchaser_name: row['purchaser name'], item_description: row['item description'], item_price: row['item price'].to_f, purchase_count: row['purchase count'].to_i, merchant_address: row['merchant address'], merchant_name: row['merchant name'] } raise 'Invalid import data' if record[:purchaser_name].blank? Import.create(record) gross_revenue += record[:item_price] * record[:purchase_count] end end return gross_revenue end end
true
cce3bef0670f257c2d6499bfbc5be79f382a0e48
Ruby
Gibheer/dm-mapper
/spec/integration/arel/basic_spec.rb
UTF-8
1,206
2.515625
3
[]
no_license
require 'spec_helper_integration' describe "Using Arel engine" do include_context 'Models and Mappers' before(:all) do setup_db insert_user 1, 'John', 18 insert_user 2, 'Jane', 21 insert_user 3, 'Piotr', 29 user_mapper end let(:user_mapper) { DM_ENV.build(user_model, :postgres) do relation_name :users map :id, Integer, :key => true, :coercion_method => :to_integer map :name, String, :to => :username map :age, Integer, :coercion_method => :to_integer end } it "returns all users ordered by name" do users = DM_ENV[user_model].order(:name).all users.should have(3).items user1, user2, user3 = users user1.id.should be(2) user1.name.should eql('Jane') user1.age.should be(21) user2.id.should be(1) user2.name.should eql('John') user2.age.should be(18) user3.id.should be(3) user3.name.should eql('Piotr') user3.age.should be(29) end it "returns all users with given limit and offset" do users = DM_ENV[user_model].limit(1).offset(2).all users.should have(1).items user = users.first user.name.should eql('Piotr') user.age.should be(29) end end
true
8d6a07f3d6ac4688794fefe003324697eedd4e02
Ruby
JanaVPetrova/hashie
/spec/hashie/mash_spec.rb
UTF-8
977
2.875
3
[ "MIT" ]
permissive
require 'spec_helper' describe Hashie::Mash do before(:each) do @mash = Hashie::Mash.new end it "should return false if .key? is missing" do expect(@mash.name?).to eq false end it "should check if key exists" do @mash.name = "john" expect(@mash.name?).to eq true end it "should return nil if .key is missing" do expect(@mash.name).to eq nil end it "should return value if key is known" do @mash.name = "john" expect(@mash.name).to eq "john" end it "should add pair key-value" do @mash.key = "value" expect(@mash.key("value")).to eq "value" end it "should print self" do @mash.name = "john" @mash.fruit = "apple" expect(@mash.inspect).to eq @mash end it "should create second level mash" do @mash.author! expect(@mash.author).to be_a_kind_of Hashie::Mash end it "should inspect second level mash" do @mash.author! expect(@mash.author.inspect).to eq @mash.author end end
true
7912abbb06823f67a21708b9595a3b1d135064aa
Ruby
meseker/sketch
/lib/geometry/dsl/polyline.rb
UTF-8
3,108
3.78125
4
[ "BSD-3-Clause" ]
permissive
module Geometry module DSL =begin rdoc When you want to draw things that are made of lots and lots of lines, this is how you do it. == Requirements This module is intended to be included into a Class, and that Class must provide some infrastructure. It must provide a push method for pushing new elements, a first method that returns the first vertex in the {Polyline}, and a last method that returns the last vertex. == Usage begin start_at [0,0] move_y 1 # Go up 1 unit right 1 down 1 left 1 # Close the box close # Unnecessary in this case end =end module Polyline BuildError = Class.new(StandardError) # Close the {Polyline} with a {Line}, if it isn't already closed def close move_to(first) unless closed? end # @return [Bool] True if the {Polyline} is closed, otherwise false def closed? first == last end # Draw a line to the given {Point} # @param [Point] The {Point} to draw a line to def move_to(point) push Point[point] end # Move the specified distance along the X axis # @param [Number] distance The distance to move def move_x(distance) push (last || PointZero) + Point[distance, 0] end # Move the specified distance along the Y axis # @param [Number] distance The distance to move def move_y(distance) push (last || PointZero) + Point[0, distance] end # Specify a starting point. Can't be specified twice, and only required if no other entities have been added. # #param [Point] point The starting point def start_at(point) raise BuildError, "Can't specify a start point more than once" if first push Point[point] end # @group Relative Movement # Move the specified distance along the +Y axis # @param [Number] distance The distance to move in the +Y direction def up(distance) move_y distance end # Move the specified distance along the -Y axis # @param [Number] distance The distance to move in the -Y direction def down(distance) move_y -distance end # Move the specified distance along the -X axis # @param [Number] distance The distance to move in the -X direction def left(distance) move_x -distance end # Move the specified distance along the +X axis # @param [Number] distance The distance to move in the +X direction def right(distance) move_x distance end # Draw a vertical line to the given y-coordinate while preserving the # x-coordinate of the previous {Point} # @param y [Number] the y-coordinate to move to def vertical_to(y) push Point[last.x, y] end alias :down_to :vertical_to alias :up_to :vertical_to # Draw a horizontal line to the given x-coordinate while preserving the # y-coordinate of the previous {Point} # @param x [Number] the x-coordinate to move to def horizontal_to(x) push [x, last.y] end alias :left_to :horizontal_to alias :right_to :horizontal_to # @endgroup end end end
true
a48e85f5a7bbe7aaa52bc17f73369c6551d9cc46
Ruby
cielavenir/procon
/aizu/tyama_aizuALDS1~15A.rb
UTF-8
77
2.671875
3
[ "0BSD" ]
permissive
#!/usr/bin/ruby r=gets.to_i;k=0 [25,10,5,1].each{|e|d,r=r.divmod e;k+=d} p k
true
3c61a771b2f8a410647843387701a370a1408be2
Ruby
jamesward/pubnub-api
/ruby/examples/subscribe_example.rb
UTF-8
1,142
2.8125
3
[ "MIT" ]
permissive
## ----------------------------------- ## PubNub Ruby API Subscribe Example ## ----------------------------------- ## including required libraries require 'rubygems' require 'pubnub' ## declaring publish_key, subscribe_key, secret_key, cipher_key, ssl flag publish_key = 'demo' subscribe_key = 'demo' secret_key = 'demo' cipher_key = 'demo' ssl_on = false channel = 'hello_world' ## Print usage if missing info. if !subscribe_key puts(' Get API Keys at http://www.pubnub.com/account ============== EXAMPLE USAGE: ============== ruby subscribe-example.rb PUBLISH-KEY SUBSCRIBE-KEY SSL-ON ruby subscribe-example.rb demo demo true ') exit() end ## Create Pubnub Client API (INITIALIZATION) puts('Initializing new Pubnub state') pubnub = Pubnub.new(publish_key,subscribe_key,secret_key,cipher_key,ssl_on) ## Listen for Messages (SUBSCRIBE) puts('Listening for new messages with subscribe() Function') puts('Press CTRL+C to quit.') pubnub.subscribe({ 'channel' => channel, 'callback' => lambda do |message| puts(message) ## print message return true ## keep listening? end })
true
4795b31ac4ccdaec4ef9b78f6f14feb8e8f0c6e8
Ruby
rhythm29/Geektrust_War
/lengaburu.rb
UTF-8
417
2.609375
3
[]
no_license
require './battle_resource' module Main class Lengaburu @horse = Main::BattleResource.new($HORSE_POWER, 100) @elephant = Main::BattleResource.new($ELEPHANT_POWER, 50) @armoured_tank = Main::BattleResource.new($ARMOURED_TANK_POWER, 10) @sling_gun = Main::BattleResource.new($SLING_GUN_POWER, 5) class << self attr_accessor :horse, :elephant, :armoured_tank, :sling_gun end end end
true
6b2e2c3ccd7d50929c81a9ab8a6e3f93a474265a
Ruby
thenora/recursive-dynamic-programming
/lib/fibonacci.rb
UTF-8
1,082
4.3125
4
[ "MIT" ]
permissive
# Improved Fibonacci ## Improved Fibonacci # Earlier you saw how an array could be used to store Fibonacci numbers resulting in a time-complexity reduction from O(2<sup>n</sup>) to O(n). Now we will take this a set further, because to find a given Fibonacci number, you only need to find the previous two numbers. # Reminder: # Fib(0) = 0 # Fib(1) = 1 # Fib(n) = Fib(n-2) + Fib(n-1), for all n >= 2 # Restrictions: # - You cannot use a loop, use recursion. # - Your solution should be O(n) space complexity, due to the call stack. # Recursive Solution from class # Time Complexity - O(2^n) # Space Complexity - O(n) # Hint, you may want a recursive helper method def fibonacci(n) if n < 0 raise ArgumentError.new "n must be greater than or equal to 0." end return n if n == 0 || n == 1 return fib_helper([0, 1], 2, n) end def fib_helper(solutions, current, n) if current == n return solutions[n - 1] + solutions[n-2] end solutions << solutions[current - 1] + solutions[current -2] return fib_helper(solutions, current + 1, n) end
true
f84f63928c02dbeae88b3bf698116915dbe56a68
Ruby
camilledelbos/copilot_v0
/test/models/travel_calculator_test.rb
UTF-8
2,791
2.828125
3
[]
no_license
require 'test_helper' class TravelCalculatorTest < ActiveSupport::TestCase attr_reader :katherine, :kingston, :trinidad, :vanadzor def setup travel = FactoryGirl.create(:travel) @katherine = FactoryGirl.create(:stage, :katherine, travel: travel, stage_position: 0, departure_date: DateTime.new(2014,1,23)) @kingston = FactoryGirl.create(:stage, :kingston, travel: travel, stage_position: 1, duration: 20) @trinidad = FactoryGirl.create(:stage, :trinidad, travel: travel, stage_position: 2, duration: 35) @vanadzor = FactoryGirl.create(:stage, :vanadzor, travel: travel, stage_position: 3, duration: 40) end #je souhaite connaitre la saison de chaque station #je souhaite connaitre le chemin optimal (distance) de manière à ce que je bénéficie du meilleur climat à chaque station # => je reste plus ou moins longtemps dans chaque station donc selon l'ordre de visite, le climat dans chacun de ces stations ne sera pas le même def test_recette_chemin_optimal assert_equal [katherine, vanadzor, kingston, trinidad], better_path(katherine, [katherine, trinidad, vanadzor, kingston]) end def test_juste_1_depart assert_equal [katherine], better_path(katherine, [katherine]) end def test_1_depart_1_destination assert_equal [katherine, kingston], better_path(katherine, [katherine, kingston]) end def test_1_depart_2_destinations assert_equal [katherine, trinidad, kingston], better_path(katherine, [katherine, kingston, trinidad]) end def _test_1_depart_2_destinations_sunway_mois_janvier FactoryGirl.create(:climate, main_city: 'kingston', month: '1', notation: 5) FactoryGirl.create(:climate, main_city: 'katherine', month: '1', notation: 4) FactoryGirl.create(:climate, main_city: 'trinidad', month: '1', notation: 3) assert_equal [katherine, kingston, trinidad], sunway(katherine, [katherine, trinidad, kingston]) end def test_1_calculer_les_enddates_fonction_de_la_position_et_de_la_durée FactoryGirl.create(:climate, main_city: 'kingston') FactoryGirl.create(:climate, main_city: 'katherine') FactoryGirl.create(:climate, main_city: 'trinidad') assert_equal ["Wed, 30 Jul 2014", "Mon, 08 Sep 2014", "Sun, 28 Sep 2014", "Sun, 02 Nov 2014"], climateway["Wed, 30 Jul 2014", "Mon, 08 Sep 2014", "Sun, 02 Nov 2014", "Sun, 28 Sep 2014"] #calculer les dates fonction de la durée et de l'ordre end def _test_nearest_neighbours FactoryGirl.create(:climate, main_city: 'kingston') FactoryGirl.create(:climate, main_city: 'katherine') FactoryGirl.create(:climate, main_city: 'trinidad') FactoryGirl.create(:climate, main_city: 'vanadzor') assert_equal [katherine, kingston, trinidad], nearest_neighbours(katherine, [katherine, trinidad, kingston]) end end
true
72c665f3bb586c1856efe44757ce5790eec1c446
Ruby
JBFowler/Launch_School_Prep_Course
/ch1.rb
UTF-8
1,791
4.375
4
[]
no_license
# Answers to Ch1 (Basics of Ruby) def prompt(msg) puts "=> #{msg}" gets end def question(num) prompt("Answer to question #{num}: ") end def factorial(num) total = num * (num - 1) num = num - 2 loop do if num > 1 total = total * num num -= 1 else prompt(total) break end end end def question1 question(1) prompt("Joe " + "Fowler.") end def question2 question(2) number = 1234 prompt("Our number is #{number}.") thousands = number/1000 hundreds = number%1000/100 tens = number%100/10 ones = number%10 prompt("The thousands number is #{thousands}.") prompt("The hundreds number is #{hundreds}.") prompt("The tens number is #{tens}.") prompt("The ones number is #{ones}.") end def question3 question(3) movies = { :gladiator => "2000", :toy_story_3 => "2012", :inside_out => "2015", :interstellar => "2014" } movies.each { |key, value| prompt("Year of #{key.to_s.split('_').map(&:capitalize).join(" ")}: #{value}") } end def question4 question(4) dates = ["2000", "2012", "2015", "2014"] dates.each { |date| prompt(date) } end def question5 question(5) prompt("5 Factorial is: ") factorial(5) prompt("6 Factorial is: ") factorial(6) prompt("7 Factorial is: ") factorial(7) prompt("8 Factorial is: ") factorial(8) end def question6 question(6) prompt("The square of 3.21 is: ") prompt("#{3.21*3.21}") prompt("The square of 11.2 is: ") prompt("#{11.2*11.2}") prompt("The square of 6.89 is: ") prompt("#{6.89*6.89}") end def question7 question(7) prompt("The following error message tells me that a closing parenthesis was used instead of a closing bracket on line 2 of an irb console.") end question1 question2 question3 question4 question5 question6 question7
true
eaf490bf7942a55110607e8a1bfc8d493a679415
Ruby
kgknight/rubyFizzBuzz
/FizzBuzz.rb
UTF-8
398
3.453125
3
[]
no_license
class FizzBuzz def rex(start=1,finish=100,a=3,b=5,atext="Fizz",btext="Buzz") if start % (a * b) == 0 puts "#{atext}#{btext}" elsif start % a == 0 puts atext elsif start % b == 0 puts btext elsif puts start end if(start < finish) self.rex(start+1,finish,a,b,atext,btext) end end end if __FILE__ == $0 FizzBuzz.new.rex(1,100) end
true
14be70f9831c20ff4feadb8d3a84a786986d298a
Ruby
PaaS-TA/Service-release
/paasta-mysql-release/src/cf-mysql-broker/spec/models/database_spec.rb
UTF-8
4,205
2.5625
3
[ "Apache-2.0" ]
permissive
require 'spec_helper' describe Database do let(:db_name) { 'database_name' } describe '.create' do after { connection.execute("DROP DATABASE `#{db_name}`") } it 'creates a new database' do Database.create(db_name) expect(connection.select("SELECT COUNT(*) FROM information_schema.SCHEMATA WHERE schema_name='#{db_name}'").rows.first.first).to eq(1) end context 'when the database already exists' do before do Database.create(db_name) end it 'avoids collisions with existing databases' do expect { Database.create(db_name) }.to_not change { connection.select("SHOW DATABASES LIKE '#{db_name}'").count }.from(1) end end end describe '.drop' do context 'when the database exists' do before { connection.execute("CREATE DATABASE `#{db_name}`") } it 'drops the database' do expect { Database.drop(db_name) }.to change { connection.select("SHOW DATABASES LIKE '#{db_name}'").count }.from(1).to(0) end end context 'when the database does not exist' do it 'does not raise an error' do expect { Database.drop('unknown_database') }.to_not raise_error end end end describe '.exists?' do context 'when the database exists' do before { connection.execute("CREATE DATABASE `#{db_name}`") } after { connection.execute("DROP DATABASE `#{db_name}`") } it 'returns true' do expect(Database.exists?(db_name)).to eq(true) end end context 'when the database does not exist' do it 'returns false' do expect(Database.exists?(db_name)).to eq(false) end end end describe '.usage' do let(:mb_string) { 'a' * 1024 * 1024 } before { Database.create(db_name) } after { Database.drop(db_name) } it 'returns the data usage of the db in megabytes' do connection.execute("CREATE TABLE #{db_name}.mytable (id MEDIUMINT, data LONGTEXT)") connection.execute("INSERT INTO #{db_name}.mytable (id, data) VALUES (1, '#{mb_string}')") connection.execute("INSERT INTO #{db_name}.mytable (id, data) VALUES (2, '#{mb_string}')") connection.execute("INSERT INTO #{db_name}.mytable (id, data) VALUES (3, '#{mb_string}')") connection.execute("INSERT INTO #{db_name}.mytable (id, data) VALUES (4, '#{mb_string}')") expect(Database.usage(db_name)).to eq 4 end end describe '.with_reconnect' do before do allow(Kernel).to receive(:sleep) reconnect_count = 0 allow(ActiveRecord::Base.connection).to receive(:reconnect!) do reconnect_count += 1 if reconnect_count == 1 raise Mysql2::Error.new("fake") else allow(ActiveRecord::Base.connection).to receive(:active?).and_return(true) end end @foo = double('bob') allow(@foo).to receive(:bar).and_raise(ActiveRecord::ActiveRecordError) end it 'attempts to reconnect every 3 seconds if the connection becomes inactive' do allow(ActiveRecord::Base.connection).to receive(:active?).and_return(false) Database.with_reconnect do @foo.bar end expect(@foo).to have_received(:bar) expect(ActiveRecord::Base.connection).to have_received(:reconnect!).twice expect(Kernel).to have_received(:sleep).with(3.seconds) end it 'stops trying to reconnect eventually, in case there is an unrecoverable error' do allow(ActiveRecord::Base.connection).to receive(:active?).and_return(false) allow(ActiveRecord::Base.connection).to receive(:reconnect!).and_raise(Mysql2::Error.new("fake")) expect { Database.with_reconnect do @foo.bar end }.to raise_error(Mysql2::Error) end it 'does not reconnect if there was an error but the connection is active' do allow(ActiveRecord::Base.connection).to receive(:active?).and_return(true) expect { Database.with_reconnect do @foo.bar end }.to raise_error(ActiveRecord::ActiveRecordError) expect(@foo).to have_received(:bar) end end end
true
2224b524ad73d468c97500d37c0a185bac38ec2d
Ruby
joliewrites/edabit
/Ruby/easy/frames.rb
UTF-8
59
2.6875
3
[]
no_license
def frames(minutes, fps) return minutes * (fps * 60) end
true
20cfb31c13cf71272d345f2d93c759813d28024d
Ruby
ravraw/Ruby_2_player_math_game
/Player.rb
UTF-8
120
2.90625
3
[]
no_license
# Player class class Player attr_accessor :name,:lives def initialize(name) @name = name @lives = 3 end end
true
8ddc24b9abe6519766430ae6e7cf09e322970963
Ruby
glenegbert/Event-Reporter
/lib/command_processor.rb
UTF-8
1,985
3.078125
3
[]
no_license
require 'repository_manager' require 'entry' class CommandProcessor attr_accessor :repository_manager # def initialize(repository_manager = RepositoryManager.load_entries) def initialize(repository_manager = RepositoryManager.new) @repository_manager = repository_manager end def queue_print puts headers repository_manager.queue.map { |entry| entry_format(entry)} end def headers "LAST NAME".ljust(24, " ") + "FIRST NAME".ljust(24, " ") + "EMAIL".ljust(40, " ") + "ZIPCODE".ljust(12, " ") + "CITY".ljust(35, " ") + "STATE".ljust(20, " ") + "ADDRESS".ljust(36, " ") + "PHONE".ljust(18, " ") end def queue_print_by(field) puts headers repository_manager.queue.sort_by {|entry| entry.send(field)}.map{|entry| entry_format(entry)} end def entry_format(entry) "#{entry.last_name}".ljust(24, " ")+ "#{entry.first_name}".ljust(24, " ")+ "#{entry.email_address}".ljust(40, " ")+ "#{entry.zipcode}".ljust(12, " ")+ "#{entry.city}".ljust(35, " ")+ "#{entry.state}".ljust(20, " ")+ "#{entry.street}".ljust(36, " ")+ "#{entry.homephone}".ljust(18," ") end def save_format(entry) "#{entry.reg_date}," + "#{entry.last_name}," + "#{entry.first_name}," + "#{entry.email_address}," + "#{entry.homephone}," + "#{entry.street}," + "#{entry.city}," + "#{entry.state}," + "#{entry.zipcode}" end def queue_count repository_manager.queue.length end def queue_save_to(to_file="saved_data.csv") file_path = File.join('./test/data', to_file) File.open(file_path, "w") do |file| file.puts " ,RegDate,first_Name,last_Name,Email_Address,HomePhone,Street,City,State,Zipcode" @repository_manager.queue.each { |entry| file.puts save_format(entry) } # file.puts @repository_manager.queue.each{|entry| puts entry_format(entry)} end end def queue_clear repository_manager.queue = [] end end #refactor #split out some classes #
true
075d586912c72024b66d1d33a8f738089f3596d5
Ruby
adriencouture/learn_ruby
/03_simon_says/simon_says.rb
UTF-8
504
4.15625
4
[]
no_license
def shout(word) word.upcase end def echo(word) word end def repeat(word, n = 2) array = [] n.times do array.push(word) end array.join(" ") end def start_of_word(word, number_of_characters) word[0, number_of_characters] end def first_word(first_word) array = first_word.split array[0] end def titleize(string) array = string.split array[0].capitalize! array.each do |word| word.capitalize! unless word == "and" || word == "the" || word == "over" end array.join(" ") end
true
1f7b3607790e9c6ccda7348edd4cf70e21b41b04
Ruby
bibstha/projecteuler
/3.rb
UTF-8
317
3.15625
3
[]
no_license
require 'awesome_print' require 'prime' # largest prime factor of 600851475143 def exec num = 600851475143 num = 1234567890123456789012345678901234567890 Prime.each do |prime| puts "#{prime}\t#{num}" num /= prime while (num % prime).zero? if num <= 1 return prime end end end puts exec
true
a6ece7b3ce993e30cb08ed59e054ba62f05e252a
Ruby
gaohongwei/rails_topics
/params.rb
UTF-8
1,109
3.34375
3
[]
no_license
The params in a controller looks like a Hash, but it's actually an instance of ActionController::Parameters, which provides several methods such as require and permit. The require method ensures that a specific parameter is present, otherwise the require method throws an error It returns an instance of ActionController::Parameters for the key passed into require. The permit method returns a copy of the parameters object, returning only the permitted keys and values. When creating a new ActiveRecord model, only the permitted attributes are passed into the model. It looks a lot like the whitelisting that was formerly included in ActiveRecord models, but it makes more sense for it to be in the controller. Permit returns another hash that contains only the permitted key AND (this is critical) will respond with true to the permitted? method. By default, an instance of the ActionController::Parameters class will return false for permitted? Responding true to permitted? means the parameter object can be used in mass assignment; else the app will throw a ForbiddenAttributes error.
true
201801f35068bea780d8d16a5a1cecfbd66823fd
Ruby
conorpreston13/vinyl_tracker_backend
/app/controllers/vinyls_controller.rb
UTF-8
1,500
2.5625
3
[]
no_license
class VinylsController < ApplicationController # ------------------index allows you to pull up all of the vinyl in the collection def index @vinyls = Vinyl.all render json: @vinyls end # ------------------show allows you to pick out 1 specific vinyl to show by id def show @vinyl = Vinyl.find(params[:id]) render json: @vinyl end # ------------------create allows you to create a new entry def create @vinyl = Vinyl.new(vinyl_params) if @vinyl.save render json: @vinyl, status: 201 else render json: @vinyl.errors, status: 422 end end # ------------------these are strong params for the entries def vinyl_params params.require(:vinyl).permit(:artist, :album, :release_year) end # ------------------update allows you to update an entry def update @vinyl = Vinyl.find(params[:id]).update(vinyl_params) render json: 'Entry has been successfully updated!' end # ------------------destroy....well, destroys the entry. def destroy @vinyl = Vinyl.find(params[:id]) if @vinyl.destroy render json: @vinyl, status: 200 else render json: { errors: 'Could Not Delete Successfully' }, status: 400 end end # ------------------private makes these methods specific to this controller private end
true
d389ed6139980d6bedab1fa85794b635e47694c8
Ruby
dalzinho/Codeclan-Work
/w2/day_4/lab/specs/agent_spec.rb
UTF-8
265
2.625
3
[]
no_license
require 'minitest/autorun' require 'minitest/rg' require_relative '../Agent' class AgentTest < MiniTest::Test def setup @agent = Agent.new("james", "bond") end def test_can_shay_name assert_equal("The name's Bond, James Bond.", @agent.talk) end end
true
35499162b77cb7c1a325fa938d29ba3da8eb6c3d
Ruby
RomanADavis/challenges
/advent/2015/day14/solutions/part2.rb
UTF-8
2,311
3.953125
4
[]
no_license
# --- Part Two --- # # Seeing how reindeer move in bursts, Santa decides he's not pleased with the # old scoring system. # # Instead, at the end of each second, he awards one point to the reindeer # currently in the lead. (If there are multiple reindeer tied for the lead, they # each get one point.) He keeps the traditional 2503 second time limit, of # course, as doing otherwise would be entirely ridiculous. # # Given the example reindeer from above, after the first second, Dancer is in # the lead and gets one point. He stays in the lead until several seconds into # Comet's second burst: after the 140th second, Comet pulls into the lead and # gets his first point. Of course, since Dancer had been in the lead for the 139 # seconds before that, he has accumulated 139 points by the 140th second. # # After the 1000th second, Dancer has accumulated 689 points, while poor Comet, # our old champion, only has 312. So, with the new scoring system, Dancer would # win (if the race ended at 1000 seconds). # # Again given the descriptions of each reindeer (in your puzzle input), after # exactly 2503 seconds, how many points does the winning reindeer have? class Reindeer attr_accessor :name, :speed, :fly_time, :fly_time_left, :rest_time, :rest_time_left, :distance, :points def initialize(description) description = description.split self.name = description[0] self.speed = description[3].to_i self.fly_time = self.fly_time_left = description[6].to_i self.rest_time, self.rest_time_left = description[-2].to_i, 0 self.distance = self.points = 0 end def go self.fly_time_left.zero? ? rest : fly end def fly self.fly_time_left -= 1 self.distance += self.speed self.rest_time_left = self.rest_time if self.fly_time_left.zero? end def rest self.rest_time_left -= 1 self.fly_time_left = self.fly_time if self.rest_time_left.zero? end end contestants = File.readlines("./input/reindeer.txt") contestants.map! { |reindeer| Reindeer.new(reindeer) } seconds = 2503 seconds.times do contestants.each {|reindeer| reindeer.go } contestants.max_by {|reindeer| reindeer.distance}.points += 1 end puts contestants.max_by {|reindeer| reindeer.points }.points
true
df9e413dd76aff68f80b5d3ac9bd54d4c828755d
Ruby
RumaniKafle/ITSC3155_SPRING2019_800991130
/RubyBasics2/lib/rubybasics2.rb
UTF-8
405
3.65625
4
[]
no_license
# Strings and Regular Expressions # Part I def hello(name) # YOUR CODE HERE "Hello, " + name end # Part II def starts_with_consonant? s # YOUR CODE HERE if (s[0] =~/[bcdfghjklmnprstvwxyz]+/i) return true else return false end end # Part III def binary_multiple_of_4? s # YOUR CODE HERE if s =~ /^[0-1]+$/ return s.to_i(2) % 4 == 0 else return false end end
true
942528897ff67d0b25be8eea90ff30e56e5bbd43
Ruby
solipsis/trainingMontage
/deck.rb
UTF-8
656
3.34375
3
[]
no_license
class Deck attr_accessor :cards STRAIGHT_1 = 15 STRAIGHT_2 = 10 STRAIGHT_3 = 5 RIGHT = 10 LEFT = 10 def initialize() @cards = Array.new() # todo fix straight1_img = nil straight2_img = nil right_img = nil left_img = nil STRAIGHT_1.times do puts "adding card" cards.push(Card.new(:straight1, straight1_img)) end STRAIGHT_2.times do cards.push(Card.new(:straight2, straight2_img)) end RIGHT.times do cards.push(Card.new(:right, right_img)) end LEFT.times do cards.push(Card.new(:left, left_img)) end puts "deck initialized" @cards.shuffle! end def dealCard() return @cards.pop end end
true
d305b4a6ccf5d083e6596bc1aab7d8af835e4b88
Ruby
Marlon-Poddalgoda/ICS4U-Unit2-10-Ruby
/Bike.rb
UTF-8
825
3.65625
4
[]
no_license
#!/usr/bin/env ruby ## # This class file holds the Bike class. # # @author Marlon Poddalgoda # @version 1.0 # @since 2021-05-28 # frozen_string_literal: true load "Vehicle.rb" # This class makes a bike using the vehicle class class Bike < Vehicle # Uses the constructor from the vehicle class # getters # gets number of passengers def get_passengers @num_of_passengers end # gets number of wheels def get_wheels @num_of_wheels = 2 return @num_of_wheels end # Methods # calculates the cadence for a 24" wheel def calc_cadence # formula to calculate rpm of a wheel @cadence = (get_speed / 12 * 2) @cadence_int = @cadence.to_i return @cadence_int end # ring bell method def ring_bell puts "Ding!" end end
true
9af531bd9c7d0eaa69124b20e39cb2a362146509
Ruby
daniel-certa-1228/Ruby-Enumerators-and-Enumerables
/enumerator.rb
UTF-8
504
3.515625
4
[]
no_license
enum = ['apple', 'bear', 'cactus'].each puts enum #<Enumerator:0x00007fb96686b768> puts enum.size #3 puts enum.next#apple puts enum.next#bear puts enum.peek#cactus peek looks at the next one but doesn't move the counter puts enum.next#cactus enum.rewind puts enum.next puts "#{enum.next_values}"#["bear"] enum.each_with_index { |num, i| puts "#{i}. #{num}"} # 0. apple # 1. bear # 2. cactus enum.with_index(1) { |num, i| puts "Offset #{i}. #{num}"} # Offset 1. apple # Offset 2. bear # Offset 3. cactus
true
1047e6bf4733b7cb0a54d166f94c8d2f46f79e21
Ruby
AntoineDelarchand/Morpion
/lib/app/game.rb
UTF-8
634
3.6875
4
[]
no_license
# frozen_string_literal: true require 'pry' require_relative 'player' require_relative 'board' class Game def p1 puts 'Player 1: Enter your first name:' print '>' name = gets.chomp.to_s player1 = Player.new(name) end def p2 puts 'Player 2: Enter your first name:' print '>' name = gets.chomp.to_s player2 = Player.new(name) end def greet(p1, p2) puts "Welcome #{p1.name} and #{p2.name} to the Morpion!" end def show_table #display morpion board1 = Board.new board1.table end def perform greet(p1, p2) show_table end end game1 = Game.new game1.perform
true
64d9187fcae25ef9ab1858fb9d39fdb4e4aad1fa
Ruby
scokop/rubyprograms
/3week/exercise_8.rb
UTF-8
303
3.90625
4
[]
no_license
def fizzbuzz 1.upto(100) do |number| fizz_buzz_output = "" if number % 3 == 0 then fizz_buzz_output << "Fizz" end if number % 5 == 0 then fizz_buzz_output << "Buzz" end if fizz_buzz_output.empty? puts number else puts fizz_buzz_output end end end fizzbuzz
true
183ea2b92a7b9199b69c3dd6c2603ce997413df4
Ruby
ThundaHorse/contacts_app
/contact_client.rb
UTF-8
958
3.5
4
[]
no_license
require 'http' system "clear" puts "Sup yo" puts "" puts "Options" puts " [1] Display a single contact" puts " [2] Display all contacts" puts "What you wanna do" user_option = gets.chomp if user_option == "1" response = HTTP.get('http://localhost:3000/api/contacts_url') contact_hash = response.parse puts "#{contact_hash["first_name"]} #{contact_hash["last_name"]}" puts "=" * 60 puts "Email: #{contact_hash["email"]}" puts "Phone: #{contact_hash["phone_number"]}" elsif user_option == "2" response = HTTP.get('http://localhost3000/api/all_contacts_url') contacts_array = response.parse puts "All" # puts "¯\_(ツ)_/¯" puts "" contacts_array.each do |contact_hash| puts "#{contact_hash["first_name"]} #{contact_hash["last_name"]}" puts "=" * 60 puts "Email: #{contact_hash["email"]}" puts "Phone: #{contact_hash["phone_number"]}" puts "" puts "-" * 60 puts "" end end
true
4780e188b2154ddbbfcb24f2daf0a183355fea6e
Ruby
learn-co-curriculum/testing-truth
/things_that_are_true_in_ruby.rb
UTF-8
275
3.296875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require_relative 'true.rb' puts "Did you know that true is " + true?(true).to_s #=> true puts "Did you know that false is " + true?(false).to_s #=> false puts "Did you know that 0 is " + true?(0).to_s #=> true puts "Did you know that \"\" is " + true?("").to_s #=> true
true
d70d29220266485d659dcf253f872a9226b1a2d7
Ruby
TomK32/Unstack
/unstack/Smiley.rb
UTF-8
351
2.703125
3
[]
no_license
# # Smiley.rb # unstack # # Created by Thomas R. Koll on 02.04.11. # Copyright 2011 Ananasblau.com. All rights reserved. # class Smiley < Block def initialize c = NSColor.yellowColor n = nil self.shape = [ [n, c, c, c, n], [c, n, n, n, c], [n, n, c, n, n], [n, c, n, c, n] ] end def alpha 1.0 end end
true
5a06c725bd76dd9a92424e45fec1669e17684e71
Ruby
YuichiYagisawa/CodeWars
/digital_root.rb
UTF-8
217
3.34375
3
[]
no_license
def digital_root(n) a = n.to_s.split("").map(&:to_i).sum if a >= 10 a.to_s.split("").map(&:to_i).sum else return a end end #ans # def digital_root(n) # n < 10 ? n : digital_root(n.digits.sum) # end
true
15083565f13e3ed9befaff81652894e93d34067a
Ruby
krestenkrab/hotruby
/modules/vm-shared/rb/test/basic/Regexp.rb
UTF-8
17,417
2.59375
3
[ "Apache-2.0", "BSD-3-Clause" ]
permissive
require 'test/unit/testcase' require 'test/unit/testresult' #require 'test/unit' class RegexpTest < Test::Unit::TestCase def test_simple assert_match(['bcd'], /bcd/, 'abcde') end def test_constructors assert_match(['bcd'], Regexp.new('bcd'), 'abcde') assert_match(['bcd'], Regexp.new('bcd', Regexp::MULTILINE), 'abcde') assert_match(['bcd'], Regexp.new('bcd', Regexp::MULTILINE, 'n'), 'abcde') assert_match(['bcd'], Regexp.compile('bcd'), 'abcde') assert_match(['bcd'], Regexp.compile('bcd', Regexp::MULTILINE), 'abcde') assert_match(['bcd'], Regexp.compile('bcd', Regexp::MULTILINE, 'n'), 'abcde') end def test_specialchars assert_match(['%&'], /%&/, '!@%&-_=+') end def test_escape assert_equal 'abc', Regexp.escape('abc') #TODO Escapes do not work in HotRuby strings #assert_equal 'a\\\\c', Regexp.escape('a\\c') assert_equal 'a\(c', Regexp.escape('a(c') assert_equal 'a\[c', Regexp.escape('a[c') assert_equal 'a\]c', Regexp.escape('a]c') assert_equal 'a\{c', Regexp.escape('a{c') assert_equal 'a\}c', Regexp.escape('a}c') assert_equal 'a\|c', Regexp.escape('a|c') assert_equal 'a\.c', Regexp.escape('a.c') assert_equal 'a\$c', Regexp.escape('a$c') assert_equal 'a\^c', Regexp.escape('a^c') assert_equal 'a\+c', Regexp.escape('a+c') assert_equal 'a\?c', Regexp.escape('a?c') assert_equal 'a\*c', Regexp.escape('a*c') assert_equal 'a\-c', Regexp.escape('a-c') assert_equal 'a&c', Regexp.escape('a&c') assert_equal 'a/c', Regexp.escape('a/c') assert_equal 'a:c', Regexp.escape('a:c') end def test_quote assert_equal 'abc', Regexp.quote('abc') #TODO Escapes do not work in HotRuby strings #assert_equal 'a\\\\c', Regexp.quote('a\\c') assert_equal 'a\(c', Regexp.quote('a(c') end def test_too_many_ending_parentheses # TODO assert_raise(RegexpError) { Regexp.new('ab(cd))ef') } # TODO assert_raise(SyntaxError) do # eval "assert_match(['abcd)ef', 'cd'], /ab(cd))ef/, '12abcd)ef34')" #end end def test_group assert_match(['abcdef', 'cd'], /ab(cd)ef/, '12abcdef34') assert_match(['abcdefghij', 'cd', 'gh'], /ab(cd)ef(gh)ij/, '12abcdefghij34') assert_match(['abcd', 'bc', 'c'], /a(b(c))d/, '12abcd34') assert_match(['abd', 'b', nil], /a(b(c)?)d/, '12abd34') assert_match(['ad', nil, nil], /a(b(c)?)?d/, '12ad34') end def test_alternation assert_match(['abc', 'b'], /a(b|3)c/, '12abc45') assert_match(['a3c', '3'], /a(b|3)c/, '12a3c45') assert_match(['abc'], /abc|a3c/, '12abc45') assert_match(['a3c'], /abc|a3c/, '12a3c45') end def test_zero_or_more assert_match(['ac'], /ab*c/, 'ac') assert_match(['abc'], /ab*c/, 'abc') assert_match(['abbc'], /ab*c/, 'abbc') end def test_optional assert_match(['ac'], /ab?c/, 'ac') assert_match(['abc'], /ab?c/, 'abc') assert_no_match(/ab?c/, 'abbc') end def test_one_or_more assert_no_match(/ab+c/, 'ac') assert_match(['abc'], /ab+c/, 'abc') assert_match(['abbc'], /ab+c/, 'abbc') end def test_repetition_min_max_specified assert_no_match(/ab{2,4}c/, 'abc') assert_match(['abbc'], /ab{2,4}c/, 'abbc') assert_match(['abbbbc'], /ab{2,4}c/, 'abbbbc') assert_no_match(/ab{2,4}c/, 'abbbbbc') # If any whitespace is included, it never matches assert_no_match(/ab{2 ,4}c/, 'abbc') assert_no_match(/ab{ 2,4}c/, 'abbc') assert_no_match(/ab{2, 4}c/, 'abbc') assert_no_match(/ab{2,4 }c/, 'abbc') end def test_repetition_exact assert_no_match(/ab{2}c/, 'abc') assert_match(['abbc'], /ab{2}c/, 'abbc') assert_no_match(/ab{2}c/, 'abbbc') # If any whitespace is included, it never matches assert_no_match(/ab{ 2}c/, 'abbc') assert_no_match(/ab{2 }c/, 'abbc') end def test_repetition_minimum assert_no_match(/ab{2,}c/, 'abc') assert_match(['abbc'], /ab{2,}c/, 'abbc') assert_match(['abbbbc'], /ab{2,}c/, 'abbbbc') # If any whitespace is included, it never matches assert_no_match(/ab{ 2,}c/, 'abbc') assert_no_match(/ab{2 ,}c/, 'abbc') assert_no_match(/ab{2, }c/, 'abbc') end def test_backreference assert_no_match(/a(b)\1c/, 'abc') assert_match(['abbc', 'b'], /a(b)\1c/, 'abbc') assert_match(['ab&c', 'b'], /a(b)\&c/, 'ab&c') assert_match(['ab`c', 'b'], /a(b)\`c/, 'ab`c') assert_match(["ab'c", 'b'], /a(b)\'c/, "ab'c") assert_match(['ab+c', 'b'], /a(b)\+c/, 'ab+c') end def test_predefined_character_classes # \d, \D assert_match(['a3b'], /a\db/, '12a3b45') assert_no_match(/a\Db/, '12a3b45') assert_match(['a b'], /a\Db/, '12a b45') # \s, S assert_match(['a b'], /a\sb/, '12a b45') assert_no_match(/a\Sb/, '12a b45') assert_match(['a3b'], /a\Sb/, '12a3b45') # \w, \W assert_match(['abc'], /a\wc/, '12abc45') assert_no_match(/a\Wc/, '12abc45') assert_no_match(/a\Wc/, '12a3c45') assert_match(['a c'], /a\Wc/, '12a c45') assert_match(['abc'], /a.c/, '12abc45') assert_no_match(/a.c/, "12a\nc45") end def test_character_classes assert_match(['a3c'], /a[3b]c/, '12a3c45') assert_match(['abc'], /a[3b]c/, '12abc45') assert_match(['abc'], /a[b-f]c/, '12abc45') assert_match(['aec'], /a[b-f]c/, '12aec45') assert_match(['a-c'], /a[-a-c]c/, '12a-c45') assert_match(['abc'], /a[-a-c]c/, '12abc45') assert_match(['a-c'], /a[-----a-c]c/, '12a-c45') assert_match(['a-c'], /a[a-c-]c/, '12a-c45') # TODO assert_raise(SyntaxError) do # eval("assert_match(['a-c'], /a[a--c]c/, '12a-c45')") #end assert_match(['a]c'], /a[ab\]]c/, '12a]c45') assert_no_match(/a[ab\]]c/, '12a\c45') # Inverse classes assert_match(['a3c'], /a[^bc]c/, '12a3c45') assert_no_match(/a[^bc]c/, '12abc45') assert_match(['a3c'], /a[^^^^^bc]c/, '12a3c45') assert_no_match(/a[^^^^^bc]c/, '12a^c45') assert_no_match(/a[^-bc]c/, '12a-c45') # Escapes assert_match(['a3c'], /a[a-c\d]c/, '12a3c45') assert_no_match(/a[a-c\d]c/, '12aec45') # TODO assert_raise(SyntaxError) do # eval("assert_match(['aFc'] /a[a-c\F]c/, '12aFc45')") #end assert_match(['a-c'], /a[a-c\-]c/, '12a-c45') assert_match(['a.c'], /a[abc\.]c/, '12a.c45') assert_match(['a.c'], /a[abc.]c/, '12a.c45') # TODO assert_match(['a\\c'], /a[ab\\c]c/, '12a\\c45') assert_match(['abc'], /a[ab\d]c/, '12abc45') assert_no_match(/a[ab\d]c/, '12adc45') assert_match(['abc'], /a[^\[\]]c/, '12abc45') # POSIX character classes assert_match(['a3c'], /a[b[:digit:]]c/, '12a3c45') assert_match(['abc'], /a[b[:digit:]]c/, '12abc45') assert_match(['abc'], /a[[:alnum:]]c/, '12abc45') assert_match(['a3c'], /a[[:alnum:]]c/, '12a3c45') assert_match(['abc'], /a[[:alpha:]]c/, '12abc45') assert_match(['a c'], /a[[:blank:]]c/, '12a c45') assert_match(["a\nc"], /a[[:cntrl:]]c/, "12a\nc45") assert_match(['a.c'], /a[[:graph:]]c/, "12a.c45") assert_match(['abc'], /a[[:lower:]]c/, "12abc45") assert_match(['abc'], /a[[:print:]]c/, "12abc45") assert_match(['a.c'], /a[[:punct:]]c/, "12a.c45") assert_match(['a c'], /a[[:space:]]c/, "12a c45") assert_match(['aBc'], /a[[:upper:]]c/, "12aBc45") assert_match(['aFc'], /a[[:xdigit:]]c/, "12aFc45") # TODO assert_raise(SyntaxError) do # eval("assert_no_match(/a[b[:digits:]]c/, '12abc45')") #end end def test_anchors # ^ assert_no_match(/^abc/, '12abc34') assert_match(['abc'], /^abc/, 'abc34') assert_no_match(/a^bc/, '12abc34') # $ assert_no_match(/abc$/, '12abc34') assert_match(['abc'], /abc$/, '12abc') assert_no_match(/ab$c/, '12abc34') # \A assert_no_match(/\Aabc/, '12abc34') assert_match(['abc'], /\Aabc/, 'abc34') assert_no_match(/a\Abc/, '12abc34') # \z assert_no_match(/abc\z/, '12abc34') assert_match(['abc'], /abc\z/, '12abc') assert_no_match(/ab\zc/, '12abc34') assert_no_match(/abc\z/, "12abc\n") # \Z assert_no_match(/abc\Z/, '12abc34') assert_match(['abc'], /abc\Z/, '12abc') assert_no_match(/ab\Zc/, '12abc34') assert_match(['abc'], /abc\Z/, "12abc\n") # \b assert_match(['cd'], /\bcd/, 'ab cd') assert_no_match(/\bcd/, 'abcd') assert_match(['ab'], /ab\b/, 'ab cd') assert_no_match(/ab\b/, 'abcd') # \B assert_no_match(/ab\B/, 'ab cd') assert_match(['ab'], /ab\B/, 'abcd') assert_no_match(/\Bcd/, 'ab cd') assert_match(['cd'], /\Bcd/, 'abcd') # \G # TODO: Test with repetitive matches... assert_no_match(/\Gabc/, '12abc34') assert_match(['abc'], /\Gabc/, 'abc34') assert_no_match(/a\Gbc/, '12abc34') end def test_extensions # Comment assert_match(['abc'], /a(?# my comment )bc/, 'abc') assert_match(['abc'], /a(?#my comment)bc/, 'abc') assert_match(['abc'], /a(?# my comment \)bc/, 'abc') assert_match(['abc'], /a(?# my comment ()bc/, 'abc') # Group without backreference assert_match(['abc', 'a', 'c'], /(a)(?:b)(c)/, '12abc34') # Zero-width positive lookahead assert_match(['a'], /[a-z]+(?=,)/, '12a,c34') assert_no_match(/[a-z]+(?=,)/, '12ac34') # Zero-width negative lookahead assert_match(['a'], /a(?!c)/, '12abc34') assert_no_match(/a(?!b)/, '12abc34') # Independent regular expression assert_match(['abbc'], /a(?>b*)c/, '12abbc45') assert_match(['abbc', 'b'], /a(?>(b)*)c/, '12abbc45') # Unknown extension # TODO assert_raise(RegexpError) { Regexp.new('a(?<b*)c') } end def test_options assert_equal 1, Regexp::IGNORECASE assert_equal 2, Regexp::EXTENDED assert_equal 4, Regexp::MULTILINE # Ignorecase assert_no_match(Regexp.new('abc', 0), '12aBc45') assert_match(['aBc'], Regexp.new('abc', Regexp::IGNORECASE), '12aBc45') assert_match(['aBc'], /abc/i, '12aBc45') assert_match(['abcaBc'], /abc(?i)abc/, '12abcaBc45') assert_match(['abcaBc'], /abc(?i:abc)/, '12abcaBc45') assert_no_match(/abc(?i)abc(?-i)abc/, '12abcaBcaBc45') assert_no_match(Regexp.new('abc(?-i)abc', Regexp::IGNORECASE), '12aBcaBc45') # casefold? assert !(Regexp.new('abc', 0).casefold?) assert Regexp.new('abc', Regexp::IGNORECASE).casefold? # Extended s = "\n a #comment\n #Another comment\n bc\n" assert_match(['abc'], Regexp.new(s, Regexp::EXTENDED), '12abc45') assert_match(['abc'], /a #A comment # Another comment bc/x, '12abc45') t = "\n a #A comment\n (?-x) # Another comment\n bc\n" assert_no_match(Regexp.new(t, Regexp::EXTENDED), '12abc45') # Multiline assert_no_match(/12a\nc45/, 'a.b') assert_match(['abc'], /^abc/, "12\nabc45") assert_match(['abc'], /^abc/m, "12\nabc45") assert_match(['abc'], Regexp.new('^abc', Regexp::MULTILINE), "12\nabc45") assert_match(["abca\nc"], /abc(?m)a\nc/, "12abca\nc45") assert_match(['abc'], /abc$/, "12abc\n45") assert_match(['abc'], /abc$/m, "12abc\n45") assert_match(['abc'], Regexp.new('abc$', Regexp::MULTILINE), "12abc\n45") assert_match(['abcabc'], /abc(?m)abc$/, "12abcabc\n45") assert_no_match(/a.c/, "12a\nc45") assert_match(["a\nc"], /a.c/m, "12a\nc45") assert_match(["a\nc"], Regexp.new('a.c', Regexp::MULTILINE), "12a\nc45") assert_match(["abca\nc"], /a.c(?m)a.c/, "12abca\nc45") assert_no_match(/a.c(?-m)a.c/m, "12a\nca\nc45") assert_no_match(Regexp.new('a.c(?-m)a.c', Regexp::MULTILINE), "12a\nca\nc45") # Total confusion of option switching assert_no_match(/(?i)a(?i-i)bc/, '12aBc45') assert_no_match(/a(?i-i)bc/, '12aBc45') #assert_raise(RegexpError) { Regexp.new('b(?ih)c') } end def test_equals assert !(/abd/ == /abc/), 1 assert /abd/ != /abc/, 2 assert /abc/ == /abc/, 3 assert /abc/ == Regexp.new('abc'), 4 assert Regexp.new('abc') == /abc/, 5 assert !(/abc/ == /abc/x), 6 assert /abc/ != /abc/x, 7 assert !(/abc/ == /abc/i), 8 assert /abc/ != /abc/i, 9 assert /abc/ != 'abc' end def test_case_equality assert /abc/ === '12abc45' assert !(/abd/ === '12abc45') case '12abc45' when /abd/: res = 1 when /abc/: res = 2 when /abe/: res = 3 else res = 4 end assert_equal 2, res end def test_eqtilde assert '12abc45' =~ /abc/ assert !('12abd45' =~ /abc/) end def test_to_s assert_equal '(?-mix:abc)', /abc/.to_s assert_equal '(?mix:abc)', Regexp.new('abc', Regexp::MULTILINE | Regexp::IGNORECASE | Regexp::EXTENDED).to_s end def test_inspect assert_equal '/ab/', /ab/.inspect assert_equal '/ab/mx', Regexp.new('ab', Regexp::MULTILINE | Regexp::EXTENDED).inspect assert_equal '/ab/mix', Regexp.new('ab', Regexp::MULTILINE | Regexp::IGNORECASE | Regexp::EXTENDED).inspect end def test_match_constant $_ = '12abc45' assert ~ /abc/ assert !(~ /abd/) end def test_union assert_equal '(?!)', Regexp.union().source assert_equal 'abc', Regexp.union('abc').source assert_equal 'a\(c', Regexp.union('a(c').source assert_equal 'abc', Regexp.union(/abc/).source assert_equal 'abc|def', Regexp.union('abc', 'def').source assert_equal 'abc|def|ghi', Regexp.union('abc', 'def', 'ghi').source assert_equal '(?-mix:abc)|(?-mix:def)', Regexp.union(/abc/, /def/).source assert_equal '(?-mix:abc)|(?-mix:def)|(?-mix:ghi)', Regexp.union(/abc/, /def/, /ghi/).source assert_equal 'abc|(?-mix:def)', Regexp.union('abc', /def/).source end def test_globals 'abcdefghijklmnopqr' =~ /(c)(d)(e)(f)(g)(h)(i)(j)(k)(l)(m)(n)(o)(p)/ match = $~ assert_equal 'cdefghijklmnop', $& assert_equal 'cdefghijklmnop', match[0] 'abcdefghijklmnopqr' =~ /(c)(d)(e)(f)(g)(h)(i)(j)(k)(l)(m)(n)(o)(p)/ assert_equal 'ab', $` 'abcdefghijklmnopqr' =~ /(c)(d)(e)(f)(g)(h)(i)(j)(k)(l)(m)(n)(o)(p)/ assert_equal 'qr', $' 'abcdefghijklmnopqr' =~ /(c)(d)(e)(f)(g)(h)(i)(j)(k)(l)(m)(n)(o)(p)/ assert_equal 'c', $1 'abcdefghijklmnopqr' =~ /(c)(d)(e)(f)(g)(h)(i)(j)(k)(l)(m)(n)(o)(p)/ assert_equal 'd', $2 'abcdefghijklmnopqr' =~ /(c)(d)(e)(f)(g)(h)(i)(j)(k)(l)(m)(n)(o)(p)/ assert_equal 'l', $10 'abcdefghijklmnopqr' =~ /(c)(d)(e)(f)(g)(h)(i)(j)(k)(l)(m)(n)(o)(p)/ assert_equal 'p', $14 'abcdefghijklmnopqr' =~ /(c)(d)(e)(f)(g)(h)(i)(j)(k)(l)(m)(n)(o)(p)/ /(a)(b)(c)/.match('12abc45') match = $~ assert_equal 'abc', $& assert_equal 'abc', match[0] /(a)(b)(c)/.match('12abc45') assert_equal '12', $` /(a)(b)(c)/.match('12abc45') assert_equal '45', $' /(a)(b)(c)/.match('12abc45') assert_equal 'a', $1 /(a)(b)(c)/.match('12abc45') assert_equal nil, $14 /abc/.match('hello') match = $~ assert_equal nil, $& assert_equal nil, match /abc/.match('hello') assert_equal nil, $` /abc/.match('hello') assert_equal nil, $' /abc/.match('hello') assert_equal nil, $1 end def test_last_match 'abcdefghijklmnopqr' =~ /(c)(d)(e)(f)(g)(h)(i)(j)(k)(l)(m)(n)(o)(p)/ last_match = Regexp.last_match last_match_zero = Regexp.last_match 0 last_match_one = Regexp.last_match 1 assert_equal 'cdefghijklmnop', last_match[0] assert_equal 'cdefghijklmnop', last_match_zero assert_equal('c', last_match_one) /abc/.match('hello') last_match = Regexp.last_match last_match_zero = Regexp.last_match 0 last_match_one = Regexp.last_match 1 assert_equal nil, last_match assert_equal nil, last_match_zero assert_equal nil, last_match_one end private def assert_match(result, regexp, input) match = regexp.match(input).to_a if (match != result) p "No match #{regexp}: Expected #{result}, was #{match}" end assert_equal result, regexp.match(input).to_a end end def do_test(name) p name tc = RegexpTest.new(name) tr = Test::Unit::TestResult.new tc.run(tr) do |event,name| #p "test:#{event} #{name}" end p tr.to_s end do_test "test_simple" do_test "test_constructors" do_test "test_specialchars" do_test "test_escape" do_test "test_quote" do_test "test_too_many_ending_parentheses" do_test "test_group" do_test "test_alternation" do_test "test_zero_or_more" do_test "test_optional" do_test "test_one_or_more" do_test "test_repetition_min_max_specified" do_test "test_repetition_exact" do_test "test_repetition_minimum" do_test "test_backreference" do_test "test_predefined_character_classes" do_test "test_character_classes" do_test "test_anchors" do_test "test_extensions" do_test "test_options" do_test "test_equals" do_test "test_case_equality" do_test "test_eqtilde" do_test "test_to_s" do_test "test_inspect" do_test "test_match_constant" do_test "test_union" do_test "test_globals" do_test "test_last_match"
true
09cfa41103ed831b6d38fc00a6fdfa4b9695a9b2
Ruby
mmanousos/ruby-small-problems
/small_problems/easy8/seven_double_char_pt1.rb
UTF-8
1,695
4.75
5
[]
no_license
=begin *assignment* Double Char (Part 1) Write a method that takes a string, and returns a new string in which every character is doubled. Examples: repeater('Hello') == "HHeelllloo" repeater("Good job!") == "GGoooodd jjoobb!!" repeater('') == '' *problem* input: string output: string with each character doubled access each character of the string and put 2 copies of it into an array, join the array and return it. #each_with_object ? could this be done by concatenating to a string (without the array)? empty string returns an empty string (0 * 2 = 0!). *examples / test cases * see above *data structures* string to array to string *algorithm* BEGIN declare a method that takes a single string as an argument SET arr = [] empty array to hold working values SET counter = 0 WHILE arr.size < string.size * 2 SET char = each character of the string (start with arr[counter]) arr << arr[counter] * 2 increment counter += 1 PRINT arr.join END =end def repeater(str) str.chars.each_with_object([]) { |char, arr| arr << char * 2 }.join end def repeater(str) doubled_str = '' counter = 0 while counter < str.size doubled_str.concat(str[counter] * 2) counter += 1 end doubled_str end def repeater(str) doubled_str = '' str.each_char { |char| doubled_str.concat(char * 2) } doubled_str end # Course Solution - nearly identical to my third solution only using shovel # operator in place of String#concat method def repeater(string) result = '' string.each_char do |char| result << char << char end result end p repeater('Hello') == "HHeelllloo" p repeater("Good job!") == "GGoooodd jjoobb!!" p repeater('') == ''
true
9ca8f872146b1bef487f8db9dd0380b409d21d75
Ruby
NiestrojMateusz/Launch-School-101
/lesson_3/Hard_1.rb
UTF-8
4,844
4.46875
4
[]
no_license
#Question 1 #What do you expect to happen when the greeting variable is referenced in the last line of the code below? if false greeting = “hello world” end greeting # Solution 1 # greeting is nil here, and no "undefined method or local variable" exception is thrown. Typically, when you reference an uninitialized variable, Ruby will raise an exception, stating that it’s undefined. However, when you initialize a local variable within an if block, even if that if block doesn’t get executed, the local variable is initialized to nil. ################################################################################ # Question 2 # What is the result of the last line in the code below? greetings = { a: 'hi' } informal_greeting = greetings[:a] informal_greeting << ' there' puts informal_greeting # => "hi there" puts greetings # Solution 2 # The output is {:a=>"hi there"}. The reason is because informal_greeting is a reference to the original object. The line informal_greeting << ' there' was using the String#<< method, which modifies the object that called it. This means that the original object was changed, thereby impacting the value in greetings. If instead of modifying the original object, we wanted to only modify informal_greeting but not greetings, there are a couple of options: # we could initialize informal_greeting with a reference to a new object containing the same value by informal_greeting = greetings[:a].clone. # we can use string concatenation, informal_greeting = informal_greeting + ' there', which returns a new String object instead of modifying the original object. #============================================================================= # Question 4 # A UUID is a type of identifier often used as a way to uniquely identify items...which may not all be created by the same system. That is, without any form of synchronization, two or more separate computer systems can create new items and label them with a UUID with no significant chance of stepping on each other's toes. # It accomplishes this feat through massive randomization. The number of possible UUID values is approximately 3.4 X 10E38. # Each UUID consists of 32 hexadecimal characters, and is typically broken into 5 sections like this 8-4-4-4-12 and represented as a string. # It looks like this: "f65c57f6-a6aa-17a8-faa1-a67f2dc9fa91" # Write a method that returns one UUID when called with no parameters. def make_uuid sections = [8, 4, 4, 4, 12] uuid = '' sections.each do |section| section.times do uuid += rand(16).to_s(16) end uuid += "-" unless section >= 12 end uuid end make_uuid #alternative def uuid_maker_alt strings_container = [8, 4, 4, 4, 12].map do |num| Array.new(num) { rand(16).to_s(16) }.join end strings_container.join('-') end #alternative 2 def uuid [8, 4, 4, 4, 12].map { |n| Array.new(n) { rand(16).to_s(16) }.join }.join('-') end #========================================================================== # Question 5 # Ben was tasked to write a simple ruby method to determine if an input string is an IP address representing dot-separated numbers. e.g. "10.4.5.11". He is not familiar with regular expressions. Alyssa supplied Ben with a method called is_an_ip_number? that determines if a string is a valid ip address number and asked Ben to use it. def dot_separated_ip_address?(input_string) dot_separated_words = input_string.split(".") while dot_separated_words.size > 0 do word = dot_separated_words.pop break unless is_an_ip_number?(word) end return true end # Alyssa reviewed Ben's code and says "It's a good start, but you missed a few things. You're not returning a false condition, and you're not handling the case that there are more or fewer than 4 components to the IP address (e.g. "4.5.5" or "1.2.3.4.5" should be invalid)." # Help Ben fix his code. # Solution 5 # There are several ways to fix this. To determine if there are exactly 4 dot-separated "words" in the string, you can simply add a check for dot_separated_words.size after splitting the string. # The other error in Ben's code is that instead of returning false upon encountering a non-numeric component, he used break to break out of the while loop. Once he breaks, control falls through to the return true statement. He can fix this by performing return false instead of break. def dot_separated_ip_address?(input_string) dot_separated_words = input_string.split(".") return false unless dot_separated_words.size == 4 while dot_separated_words.size > 0 do word = dot_separated_words.pop return false unless is_an_ip_number?(word) end true end # Note: Ben's original return true on the last line of the method can be shortened to just true. This is because Ruby returns the result of the last evaluated expression.
true
52a7a48bdd1a9f49e23feec84ef70ee0f2a13569
Ruby
DavidHuarino/codeSignal_interviewPractice
/Dynamic_Programming_Advanced/maximalSquare.rb
UTF-8
717
3.0625
3
[]
no_license
def maximalSquare(matrix) return 0 if matrix.empty? def findMaxSquare(x, y, matrix, memo) return 0 if x >= matrix.size or y >= matrix[0].size return memo[[x, y]] if memo.key?([x, y]) if matrix[x][y] == '0' memo[[x, y]] = 0 else memo[[x, y]] = 1 + ([findMaxSquare(x + 1, y, matrix, memo), findMaxSquare(x, y + 1, matrix, memo), findMaxSquare(x + 1, y + 1, matrix, memo)].min) end memo[[x, y]] end memo = Hash.new maxGlobal = 0 (0...matrix.size).each do |i| (0...matrix[i].size).each do |j| maxGlobal = [maxGlobal, findMaxSquare(i, j, matrix, memo)].max end end maxGlobal * maxGlobal end
true
bf511c4eb99b47bd60d32187a5ae51927f2f90aa
Ruby
ychubachi/romaji_table
/lib/romaji_table/c生成器.rb
UTF-8
7,935
2.9375
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby # -*- coding: utf-8 -*- require_relative 'c鍵盤' require_relative 'c五十音' require_relative 'c変換表' require 'singleton' module RomajiTable Qwerty = C鍵盤::Qwerty Dvorak = C鍵盤::Dvorak # ローマ字変換表生成器 class C生成器 include Singleton # 鍵盤にある母音の順番を左からの番号で指定 attr :鍵盤母音順 # 生成された変換表の配列 attr :変換表配列, true # {RomajiTable::C五十音}の実体への参照 attr :五十音 # {RomajiTable::C鍵盤}の実体への参照 attr :鍵盤 # nilへのエイリアス C省略 = nil def initialize @五十音 = C五十音.new @鍵盤 = C鍵盤.new @変換表 = C変換表.new(@鍵盤) @変換表配列 = [] @二重母音 = nil # 01234 04321 # aiueo -> aoeui @鍵盤母音順 = [0, 4, 3, 2, 1] end def 鍵盤登録(鍵盤) @鍵盤.登録 鍵盤 end def 鍵盤母音順(母音順) @鍵盤母音順 = 母音順 end def 直音行 @五十音.直音行.dup end def 拗音行 @五十音.拗音行.dup end def 開拗音行 @五十音.開拗音行.dup end def 合拗音行 @五十音.合拗音行.dup end def 行拗音化(行, 列, 拗音) @五十音.拗音(行, 列, 拗音) end # 文字(または記号)を登録する # # @param [String] 文字 登録する文字 # @param [Array] 確定鍵 確定する鍵の位置の配列 # @return [Array] 変換表配列 def 単文字登録(文字, 確定鍵) if 文字.is_a?(String) == false raise '文字は文字列で指定してください' end if 確定鍵.is_a?(Array) == false raise '確定鍵は配列で指定してください' end ローマ字 = '' 確定鍵.each do |位置| ローマ字 += @鍵盤[位置[:左右]][位置[:段]][位置[:番号]] end 変換表作成(ローマ字, 文字) end # 子音と母音の位置を指定する. # # @param [String, Array<String>, Symbol] かな 打鍵順序に対応づけるひらがなである. # 「かな」がStringのときは1文字毎に,Arrayの場合は要素毎に変換規則を生成する. # またSynbolの場合,{C五十音#表}の行を表す. # @param [Hash] 開始鍵 子音の位置を指定するHash.位置の内容を省略することはできない. # @param [Array, Hash] 確定鍵 母音の位置を指定するArrayもしくはHash. # Hashの場合,内部で{#母音位置正規化}する. # また,省略した(nil)場合,鍵盤にある母音の位置になる. # いずれの場合も,必ず「かな」と同じ長さになるようにすること. # @return [Array] ローマ字変換列 # @todo 中間鍵を配列でも渡せるようにする def 変換(文字, 追加文字: '', 開始鍵: nil, 中間鍵: nil, 確定鍵: nil, 次開始鍵: nil) # # Uncomment a floowing line when you need. # IceNine.deep_freeze([文字, 追加文字, 開始鍵, 中間鍵, 確定鍵]) 文字配列 = 文字正規化(文字) 中間鍵配列 = 中間鍵正規化(中間鍵) 確定鍵配列 = 確定鍵正規化(確定鍵) if 開始鍵 && 開始鍵.is_a?(Hash) == false raise '開始鍵は連想配列で指定,または,省略してください' end if 文字配列.length != 確定鍵配列.length raise '文字は確定鍵と同じ文字数で指定してください' end 中間鍵配列 = 段省略(中間鍵配列, 開始鍵) 確定鍵配列 = 段省略(確定鍵配列, 開始鍵) 打鍵順 = [] 開始鍵 and 打鍵順 += [開始鍵] 中間鍵配列 and 打鍵順 += 中間鍵配列 結果 = [] [文字配列, 確定鍵配列].transpose.each do | (文字i, 確定鍵i) | 結果 << @変換表.追加(文字i + 追加文字, 打鍵順 + [確定鍵i], 次開始鍵: 次開始鍵) end 結果 end def 文字生成(行配列, 母音, 拗音化: nil, &block) if 行配列.is_a?(Array) == false raise '行は配列で指定してください' end 元母音, @二重母音 = @二重母音, 母音 結果 = [] 行配列.each do |行| 行x = if 拗音化 行拗音化(行, 拗音化[0], 拗音化[1]) else 行 end 文字 = 二重母音(行x) yield 文字, 行 if block 結果 << [文字, 行] end @二重母音 = 元母音 結果 end def 二重母音登録(二重母音) @二重母音 = 二重母音 end def 二重母音(行) if @二重母音 == nil raise '二重母音が登録されてません' end case 行 when Symbol 行 = @五十音.表[行] end 結果 = [] @二重母音.each do |二重母音| 列 = @五十音.表[:あ行].index(二重母音[0]) if 列 == C省略 raise "「#{二重母音[0]}」はあ行の文字ではありません" end 結果 << "#{行[列]}#{二重母音[1]}" end 結果 end def 変換表出力 @変換表.出力 # @変換表配列.each do |ローマ字, かな| # puts "#{ローマ字}\t#{かな}" # end end def 変換表消去 @変換表.消去 end def 五十音合成(対象行, 列: nil, 行: nil) @五十音.合成(対象行, 列: 列, 行: 行) end def シフト(位置) C鍵盤.シフト(位置) end private def 変換表作成(ローマ字, かな) @変換表配列 << [ローマ字, かな] [ローマ字, かな] end # 指定に基づき,「かな」の配列を得る操作 # # @param かな [Array, String, Symbol] # かな('かきくけこ',['きゃ', 'きゅ', 'きょ'], :さ行)など. # 配列の場合は,そのまま返す. # 文字列の場合は,1文字ごとの配列にする. # @return [Array] かなの配列 def 文字正規化(文字) case 文字 when Array 文字 when String 文字.split("") when Symbol @五十音.表[文字] else raise '文字はシンボル,文字列,配列で指定してください' end end def 中間鍵正規化(中間鍵) case 中間鍵 when Array Marshal.load(Marshal.dump(中間鍵)) when Hash [中間鍵.dup] when nil [] else raise '中間鍵は連想配列または配列で指定,または,省略してください' end end def 確定鍵正規化(確定鍵) case 確定鍵 when Array Marshal.load(Marshal.dump(確定鍵)) when Hash case when 確定鍵[:番号] || 確定鍵[:範囲外] [確定鍵] else if @鍵盤母音順 else raise '確定鍵の番号を省略する場合は鍵盤母音順を設定してください' end 結果 = [] for 番号 in 0..4 x = 確定鍵.dup x[:番号] = @鍵盤母音順[番号] 結果 << x end 結果 end when nil @鍵盤.母音 else raise '確定鍵は連想配列または配列で指定,または,省略してください' end end def 段省略(鍵配列, 参照鍵) 鍵配列.each do |鍵i| if 鍵i[:範囲外] == nil && 鍵i[:段] == C省略 鍵i[:段] = 参照鍵[:段] end end end end end
true
59b1ee09caa0f4ad0460beb7d0364ebd1375f5dd
Ruby
SeneddCymru/e-petitions
/app/jobs/fetch_members_job.rb
UTF-8
3,994
2.515625
3
[ "LicenseRef-scancode-proprietary-license", "MIT" ]
permissive
require 'faraday' class FetchMembersJob < ApplicationJob HOST = "https://business.senedd.wales" TIMEOUT = 5 ENDPOINTS = { "en-GB": "/mgwebservice.asmx/GetCouncillorsByWard", "cy-GB": "/mgwebservicew.asmx/GetCouncillorsByWard" } WARDS = "/councillorsbyward/wards/ward" CONSTITUENCY = ".//wardtitle" REGION = ".//districttitle" MEMBERS = ".//councillor" MEMBER_ID = ".//councillorid" MEMBER_NAME = ".//fullusername" PARTY = ".//politicalpartytitle" rescue_from StandardError do |exception| Appsignal.send_exception exception end before_perform do @translated_members = load_translated_members end def perform Member.transaction do Member.update_all(region_id: nil, constituency_id: nil) @translated_members.each do |id, attributes| retried = false begin Member.for(id) { |member| member.update!(attributes) } rescue ActiveRecord::RecordNotUnique => e if retried raise e else retried = true retry end end end end end private def load_translated_members {}.tap do |hash| members(:"en-GB").each do |member| hash[member[:id]] = {}.tap do |row| row[:name_en] = member[:name] row[:party_en] = member[:party] row[:constituency_id] = member[:constituency_id] row[:region_id] = member [:region_id] end end members(:"cy-GB").each do |member| hash.fetch(member[:id]).tap do |row| row[:name_cy] = member[:name] row[:party_cy] = member[:party] end end end end def members(locale) I18n.with_locale(locale) { load_members } end def constituency_maps @constituency_maps ||= {} end def constituency_map constituency_maps[I18n.locale] ||= normalize_map(Constituency.pluck(:name, :id)) end def region_maps @region_maps ||= {} end def region_map region_maps[I18n.locale] ||= normalize_map(Region.pluck(:name, :id)) end def load_members response = fetch_members if response.success? parse(response.body) else [] end rescue Faraday::Error => e Appsignal.send_exception(e) return [] end def parse(body) xml = Nokogiri::XML(body) parse_wards(body).inject([]) do |members, node| if constituency_member?(node) members << parse_constituency(node) else members += parse_regions(node) end members end end def parse_wards(body) Nokogiri::XML(body).xpath(WARDS) end def constituency_member?(node) node.at_xpath(CONSTITUENCY).text.strip != "No Ward" end def parse_constituency(node) id = Integer(node.at_xpath(MEMBER_ID).text) name = node.at_xpath(MEMBER_NAME).text.strip party = node.at_xpath(PARTY).text.strip constituency_name = node.at_xpath(CONSTITUENCY).text.strip constituency_id = constituency_map.fetch(constituency_name.parameterize) { id: id, name: name, party: party, constituency_id: constituency_id } end def parse_regions(node) node.xpath(MEMBERS).map do |member| id = Integer(member.at_xpath(MEMBER_ID).text) name = member.at_xpath(MEMBER_NAME).text.strip party = member.at_xpath(PARTY).text.strip region_name = member.at_xpath(REGION).text.strip region_id = region_map.fetch(region_name.parameterize) { id: id, name: name, party: party, region_id: region_id } end end def faraday Faraday.new(HOST) do |f| f.response :follow_redirects f.response :raise_error f.adapter :net_http_persistent end end def fetch_members faraday.get(endpoint) do |request| request.options[:timeout] = TIMEOUT request.options[:open_timeout] = TIMEOUT end end def endpoint ENDPOINTS[I18n.locale] end def normalize_map(mappings) mappings.map { |key, id| [key.parameterize, id] }.to_h end end
true
b384b26c1656416ecb47ad7371358cda8bf271d3
Ruby
romaimperator/SPUploader
/SPUploader/Generator.rb
UTF-8
572
3.390625
3
[ "BSD-2-Clause" ]
permissive
# The base class for all values stored for tags # # To use just subclass and overload the method 'value'. For an example, refer # to the SSVGenerator class that is included. class Generator def initialize(value) @value = value end # Returns the value stored in @value. Can be overloaded to provide any # arbitrary value for the tag in the page provided the function returns a # string. def value return @value end # Just in case, appends the passed value to the stored value. def append_value(value) @value += value end end
true
f3fa5a9efc64ca9a82d3ff821e63e7ec444b3c38
Ruby
blacktm/tello
/lib/tello/cli/server.rb
UTF-8
1,263
3.15625
3
[ "MIT" ]
permissive
# A simple UDP server require 'tello/colorize' require 'socket' PORT = 8889 server = UDPSocket.new server.bind('localhost', PORT) puts "Starting Tello test server...".bold, "Listening on udp://localhost:#{PORT}" bye = false while (not bye) do msg, addr = server.recvfrom(100) puts "#{"==>".green} Received: \"#{msg}\", from #{addr[3]}:#{addr[1]}" case msg when 'speed?' #=> 1-100 cm/s res = "#{rand(1..100).to_f}\r\n" when 'battery?' #=> 0-100 % res = "#{rand(0..100)}\r\n" when 'time?' #=> time res = "#{rand(0..100)}s\r\n" when 'height?' #=> 0-3000 cm res = "#{rand(0..3000)}dm\r\n" when 'temp?' #=> 0-90 °C res = "83~86C\r\n" when 'attitude?' #=> pitch roll yaw res = "pitch:-8;roll:3;yaw:2;\r\n" when 'baro?' #=> m res = "-80.791573\r\n" when 'acceleration?' #=> x y z res = "agx:-138.00;agy:-51.00;agz:-989.00;\r\n" when 'tof?' #=> 30-1000 cm res = "#{rand(30..1000)}mm\r\n" when 'wifi?' #=> snr res = "90\r\n" when 'bye!' res = 'good bye!' bye = true else #=> 'ok' or 'error' res = 'ok' end bytes = server.send(res.to_s, 0, addr[3], addr[1]) puts "#{"<==".blue} Sent: #{res.inspect}, #{bytes} bytes" end server.close
true
67b221ebbff00b0a14881f56ae5142a9b10b16ab
Ruby
jatla/RubyWinter2014
/week2/homework/simon_says.rb
UTF-8
424
3.21875
3
[ "Apache-2.0" ]
permissive
module SimonSays def echo(str) str end def shout(str) str.upcase end def repeat(*args) str = nil count = 2 if (!args[0].nil?) str = args[0] end if (!args[1].nil?) count = args[1] end repeatedStr = String.new(str) while (count > 1) do count = count - 1 repeatedStr.concat(" ".concat(str)) end repeatedStr end def start_of_word(str, count) str[0...count] end def first_word(str) str.split[0] end end
true
78c331fd98431298af2c115109e34e04baf36ae7
Ruby
ruxandrafed/contacts-list
/contact.rb
UTF-8
1,176
3.421875
3
[]
no_license
require 'csv' require 'pry' class Contact attr_accessor :name, :email def initialize(name, email) @name = name @email = email end def to_s "Name: #{@name}, Email: #{email}" end class << self # Initializes a contact and adds it to the list of contacts def create(name, email, phone_numbers) @name = name @email = email @phone_numbers = phone_numbers.to_a ContactDatabase.write([@name, @email, @phone_numbers]) end # Finds and returns contacts that contain the term in the first name, last name or email def find(term) matches = ContactDatabase.read.select {|entry| entry.to_s.include? (term)} end # Return the list of contacts, as is def all ContactDatabase.read end # Shows a contact based on ID def show(id) matches = ContactDatabase.read.select {|entry| entry[0] == id.to_s} end # Checks if an entry with the same email address already exits in the database def contact_exists?(email) same_email_matches = ContactDatabase.read.select {|entry| entry[2].include?(email)} same_email_matches.empty? ? false : true end end end
true
9d2eaf364e773a84fc17e464072e255f3889d36e
Ruby
mattmccray/gumdrop
/lib/gumdrop/cli/external.rb
UTF-8
1,710
2.796875
3
[ "MIT" ]
permissive
require 'fileutils' require 'thor' module Gumdrop::CLI class External < Thor include Thor::Actions def self.source_root File.expand_path('../../../..', __FILE__) end desc 'new [NAME]', 'Create new gumdrop project' method_option :template, aliases:'-t', desc:'Template to start from', required:true, default:'default' def new(name) template= options[:template] || 'default' if File.directory? gem_template_path(template) say "New site from template: #{template} (gem)" directory(gem_template_path(template), name) elsif File.directory? home_template_path(template) say "New site from template: #{template} (local)" directory(home_template_path(template), name) else say "Unknown template!!\n" say "Please select from one of the following:\n\n" self.templates return end # path= File.expand_path(name) # puts `cd #{path} && bundle install` end desc 'templates', 'List templates' def templates say "Gem templates:" Dir[ gem_template_path ].each do |name| say " - #{File.basename name}" if File.directory?(name) end say "Local templates:" Dir[ home_template_path ].each do |name| say " - #{File.basename name}" if File.directory?(name) end end desc "version", "Displays Gumdrop version" def version say "Gumdrop v#{ Gumdrop::VERSION }" end private def gem_template_path(template='*') self.class.source_root / 'templates' / template end def home_template_path(template='*') File.expand_path "~" / '.gumdrop' / 'templates' / template end end end
true
bd24055c664a9b836799a4cd2c4a74173048803f
Ruby
Felipeishon/rails-dev-box
/curso68/TESTMIO.rb
UTF-8
183
3.453125
3
[ "MIT" ]
permissive
def reemplazo(x) x.each_with_index do |elemento, indice| if elemento < 0 x.delete(x[indice]) end end puts x.to_s end reemplazo([1, 5, 10, -2])
true