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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
ae445510394be8ebf007d5979d18f630d998e50e
|
Ruby
|
J-Y/RubyQuiz
|
/ruby_quiz/quiz54_sols/solutions/Interfecus/indexer.rb
|
UTF-8
| 2,179
| 4.09375
| 4
|
[
"MIT"
] |
permissive
|
class Catalogue
def initialize(start_docs=[[]])
#Expects an array of [space-delimited keyword list, object to catalogue] arrays for each initial object
@keywords = Array.new #Array of used keywords. Position is important.
@cat_objects = Array.new #Array of [keyword bitfield, stored object] arrays
start_docs.each do |st_doc|
self.catalogue!(st_doc[0], st_doc[1])
end
end
def each_under_kw(keyword)
#Expects a string keyword. Yields objects using that keyword.
if cindex = @keywords.index(keyword.upcase)
@cat_objects.each do |cat_obj|
yield(cat_obj[1]) unless ((cat_obj[0] & (2 ** cindex)) == 0)
end
end
end
def each
@cat_objects.each {|obj| yield obj[1]}
end
def catalogue!(keyword_list, cat_object)
#Adds a new object to the catalogue. Expects a space-delimited list of keywords and an object to catalogue.
key_bitfield = 0
split_list = keyword_list.upcase.split
unless split_list.empty?
split_list.each do |test_keyword|
cindex = @keywords.index(test_keyword)
if cindex == nil
cindex = @keywords.length
@keywords << test_keyword
end
key_bitfield |= 2 ** cindex
end
@cat_objects << [key_bitfield , cat_object]
end
end
attr_accessor :cat_objects, :keywords
end
# Begin Demonstration
# For this demonstration, the list of keywords itself is the object stored.
# This does not have to be the case, any object can be stored.
doc1 = "The quick brown fox"
doc2 = "Jumped over the brown dog"
doc3 = "Cut him to the quick"
demo = Catalogue.new([[doc1, doc1], [doc2, doc2]]) #Create the
catalogue with 2 objects
demo.catalogue!(doc3, doc3) #Add an object to the catalogue
print "All phrases:\n"
demo.each do |obj|
print obj + "\n"
end
print "\nList of objects with keyword 'the':\n"
demo.each_under_kw('the') do |obj|
print obj + "\n"
end
print "\nList of objects with keyword 'brown':\n"
demo.each_under_kw('brown') do |obj|
print obj + "\n"
end
print "\nList of objects with keyword 'dog':\n"
demo.each_under_kw('dog') do |obj|
print obj + "\n"
end
print "\nList of objects with keyword 'quick':\n"
demo.each_under_kw('quick') do |obj|
print obj + "\n"
end
#End Demonstration
| true
|
193faf532d90e9e502a7fba027411059d5882d6c
|
Ruby
|
J-Y/RubyQuiz
|
/ruby_quiz/quiz120_sols/solutions/Jesse Merriman/state.rb
|
UTF-8
| 5,932
| 3.796875
| 4
|
[
"MIT"
] |
permissive
|
#!/usr/bin/env ruby
# state.rb
# Ruby Quiz 120: Magic Fingers
require 'constants'
require 'outcome'
require 'set'
# Represents one state of the game, which includes how many fingers are on each
# player's hands, and whose turn it is. States can also have parents, and a
# best_outcome can be assigned to them, though this class doesn't do anything
# with that itself. The player's hands are always sorted, since it doesn't
# matter having 3-left and 2-right is equivalent to 2-left and 3-right. When
# comparing states with ==, eql?, or their hashes, only @players and @turn are
# taken into account.
class State
attr_reader :players, :turn, :parent, :best_outcome
attr_writer :best_outcome
# player_1 and player_2 are Arrays of number-of-fingers on each hand.
def initialize(player_1, player_2, turn, parent = nil)
@players = [player_1, player_2]
@turn = turn
@parent = parent
@touch_reachable = @clap_reachable = nil
for player in @players do
State.normalize(player)
end
if end_state?
@best_outcome = (self.winner == Player1 ? Outcome::P1Win : Outcome::P2Win)
else
@best_outcome = Outcome::Unknown
end
self
end
def hand_alive?(player_num, hand_num)
@players[player_num][hand_num] > 0
end
def player_alive?(player_num)
hand_alive?(player_num, Left) or hand_alive?(player_num, Right)
end
# true if at least one player is dead.
def end_state?
not player_alive?(Player1) or not player_alive?(Player2)
end
# Return the winner. This should only be called on end states (otherwise,
# it'll always return Player1).
def winner
player_alive?(Player1) ? Player1 : Player2
end
# Turn the given player's hand into a fist if it has >= FingesPerHand
# fingers up, and sort the hands.
def State.normalize(player)
for hand_num in [Left, Right] do
player[hand_num] = 0 if player[hand_num] >= FingersPerHand
end
player.sort!
end
# Return a nice string representation of a player.
def player_string(player_num)
player = @players[player_num]
'-' * (FingersPerHand-player[Left]) +
'|' * player[Left] +
' ' +
'|' * player[Right] +
'-' * (FingersPerHand-player[Right])
end
# Return a nice string representation of this state (including both player
# strings).
def to_s
s = "1: #{player_string(Player1)}"
s << ' *' if @turn == Player1
s << "\n2: #{player_string(Player2)}"
s << ' *' if @turn == Player2
s
end
# Return a compact string representation.
def to_compact_s
if @turn == Player1
"[#{@players[Player1].join(',')}]* [#{@players[Player2].join(',')}]"
else
"[#{@players[Player1].join(',')}] [#{@players[Player2].join(',')}]*"
end
end
# Equality only tests the players' hands and the turn.
def ==(other)
@players == other.players and @turn == other.turn
end
# Both eql? and hash are defined so that Sets/Hashes of states will only
# differentiate states based on @players and @turn.
def eql?(other); self == other; end
def hash; [@players, @turn].hash; end
# Yield once for each ancestor state, starting from the oldest and ending on
# this state.
def each_ancestor
ancestors = [self]
while not ancestors.last.parent.nil?
ancestors << ancestors.last.parent
end
ancestors.reverse_each { |a| yield a }
end
# Have one player (the toucher) touch the other player (the touchee).
def State.touch(toucher, toucher_hand, touchee, touchee_hand)
touchee[touchee_hand] += toucher[toucher_hand]
end
# Yield each state reachable from this state by a touch move.
def each_touch_reachable_state
if @touch_reachable.nil?
# Set to avoid duplicates.
@touch_reachable = Set[]
player = @players[@turn]
opponent_num = (@turn + 1) % 2
opponent = @players[opponent_num]
for player_hand in [Left, Right] do
for opponent_hand in [Left, Right] do
if hand_alive?(@turn, player_hand) and
hand_alive?(opponent_num, opponent_hand)
op = opponent.clone # because touch modifies it
State.touch(player, player_hand, op, opponent_hand)
if @turn == Player1
@touch_reachable << State.new(player, op, opponent_num, self)
else
@touch_reachable << State.new(op, player, opponent_num, self)
end
end
end
end
end
@touch_reachable.each { |r| yield r }
end
# Yield each state reachable from this state by a clap move.
def each_clap_reachable_state
if @clap_reachable.nil?
# Set to avoid duplicates.
@clap_reachable = Set[]
player = @players[@turn]
opponent_num = (@turn + 1) % 2
opponent = @players[opponent_num]
# Clap rules.
for source_hand in [Left, Right] do
target_hand = (source_hand == Left ? Right : Left)
# The first line is the number that can be removed from the source.
# The second is the number that can be added to the target without
# killing it.
max_transfer = [player[source_hand],
(FingersPerHand - player[target_hand] - 1)].min
(1..max_transfer).each do |i|
# skip transfers that just flip the hands
next if (player[source_hand] - i) == player[target_hand]
p = player.clone
p[source_hand] -= i
p[target_hand] += i
if @turn == Player1
@clap_reachable << State.new(p, opponent.clone, opponent_num, self)
else
@clap_reachable << State.new(opponent.clone, p, opponent_num, self)
end
end
end
end
@clap_reachable.each { |r| yield r }
end
# Yield once for each state reachable from this one.
def each_reachable_state
each_touch_reachable_state { |r| yield r }
each_clap_reachable_state { |r| yield r }
end
end
| true
|
d647db3ed621256a1bf0b263b43546e577b02364
|
Ruby
|
miofmelanezzer22/tyler-git
|
/bin/git-branches-commit-is-in
|
UTF-8
| 521
| 2.53125
| 3
|
[] |
no_license
|
#!/usr/bin/env ruby
# I was able to do git log <sha> for a commit that a saw a notification for
# but it wasn't listed in the log for master and I wanted to know which
# branch it WAS in (if not master)....
# (turned out it was in origin/test, for which I had no tracking local branch,
# so gitk wouldn't even let me jump to it)
# this tool should take a sha, and perhaps recursively look at the commit's parents
# until it reaches a head
# .git/refs/remotes/origin/test
# actually, I ran into it in .git/FETCH_HEAD
| true
|
dc32db475f719d779fb5a7d267c69612d033a4c7
|
Ruby
|
jamesrnelson/enigma
|
/test/offset_calculator_test.rb
|
UTF-8
| 878
| 2.796875
| 3
|
[] |
no_license
|
require 'simplecov'
require 'minitest/autorun'
require 'minitest/pride'
require './lib/offset_calculator'
require './lib/keygen'
require 'Date'
SimpleCov.start
class OffsetCalculatorTest < Minitest::Test
def setup
date = Date.new(2018, 2, 5)
@offset = OffsetCalculator.new(date, 1, 1)
end
def test_offset_calculator_exists
assert_instance_of OffsetCalculator, @offset
end
def test_the_creation_of_today_date
assert_equal 50218, @offset.the_date
end
def test_the_date_is_squared
assert_equal 2521847524, @offset.the_squared_date
end
def test_date_offset_array
assert_equal [7, 5, 2, 4], @offset.the_date_offset
end
def test_the_keys_combine
assert_equal [[11, 7], [11,5], [11, 2], [11,4]], @offset.combined_keys
end
def test_final_rotation_array
assert_equal [18, 16, 13, 15], @offset.final_rotations
end
end
| true
|
955eeab341495a72d0cd13673ad30e582410e049
|
Ruby
|
FKnottenbelt/LS_130
|
/lesson_2_testing/09_more_topics/easy1/01_enumerable_class.rb
|
UTF-8
| 912
| 3.953125
| 4
|
[] |
no_license
|
=begin
Assume we have a Tree class that implements a binary tree.
class Tree
...
end
A binary tree is just one of many forms of collections, such as Arrays,
Hashes, Stacks, Sets, and more. All of these collection classes include
the Enumerable module, which means they have access to an each method,
as well as many other iterative methods such as map, reduce, select, and more.
For this exercise, modify the Tree class to support the methods of Enumerable.
You do not have to actually implement any methods -- just show the methods
that you must provide.
=end
class Tree
include Enumerable
def each; end
def <=>; end
end
=begin
See the paragraph at the top of the documentation for Enumerable, for help.
After including the Enumerable module, the Tree#each and Tree#<=> methods
will provide the underlying functionality necessary for the Enumerable
instance methods to work on Tree objects.
=end
| true
|
afa29151ba6cfc8b7f69748c0c78fc26a47bccd5
|
Ruby
|
Trevorsuter/hipster_food
|
/test/event_test.rb
|
UTF-8
| 1,870
| 3.1875
| 3
|
[] |
no_license
|
require 'minitest/autorun'
require 'minitest/pride'
require 'mocha/minitest'
require 'pry'
require './lib/item'
require './lib/food_truck'
require './lib/event'
class EventTest < MiniTest::Test
def setup
@event = Event.new("South Pearl Street Farmers Market")
@food_truck = FoodTruck.new("Rocky Mountain Pies")
@food_truck2 = FoodTruck.new("Ba-Nom-a-Nom")
@item1 = Item.new({name: 'Peach Pie (Slice)', price: '$3.75'})
@item2 = Item.new({name: 'Apple Pie (Slice)', price: '$2.50'})
@item3 = Item.new({name: "Peach-Raspberry Nice Cream", price: "$5.30"})
@item4 = Item.new({name: "Banana Nice Cream", price: "$4.25"})
@food_truck.stock(@item1, 30)
@food_truck.stock(@item2, 30)
@food_truck2.stock(@item3, 15)
@food_truck2.stock(@item4, 10)
end
def test_it_exists
assert_instance_of Event, @event
assert_equal "South Pearl Street Farmers Market", @event.name
assert_equal [], @event.food_trucks
end
def test_add_food_truck
@event.add_food_truck(@food_truck)
assert_equal [@food_truck], @event.food_trucks
end
def test_food_truck_names
@event.add_food_truck(@food_truck)
assert_equal ["Rocky Mountain Pies"], @event.food_truck_names
end
def test_trucks_that_sell
@event.add_food_truck(@food_truck)
@event.add_food_truck(@food_truck2)
assert_equal [@food_truck], @event.trucks_that_sell(@item1)
assert_equal [@food_truck2], @event.trucks_that_sell(@item3)
end
def test_sorted_item_list
@event.add_food_truck(@food_truck)
@event.add_food_truck(@food_truck2)
assert_equal [@item2.name, @item4.name, @item1.name, @item3.name], @event.sorted_item_list
end
def test_total_inventory
@event.add_food_truck(@food_truck)
@event.add_food_truck(@food_truck2)
assert_equal 4, @event.total_inventory.keys.length
assert_equal 2,
end
end
| true
|
aed9e8cefe736997e9dd9e4fb20b26697050c235
|
Ruby
|
Yamikamisama/PatsRottenTomatoes
|
/app/models/user.rb
|
UTF-8
| 1,318
| 2.5625
| 3
|
[] |
no_license
|
class User < ActiveRecord::Base
has_many :movies
has_many :filters
#CHECK FOR NEW MOVIES EVERY REFRESH
def movies_stale?
Time.new - self.movies.last.updated_at >= 900
end
def fetch_movies!
uri = URI.parse("http://api.rottentomatoes.com/api/public/v1.0/lists/movies/upcoming.json?apikey=vymecugmgctsrxbbbmztpnb9")
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new(uri.request_uri)
response = http.request(request)
if response.code == "200"
@result = JSON.parse(response.body)
end
#THIS IS ULGY REFACTOR LATER
@result["movies"].each do |movie|
if (self.movies.exists?(title: movie["title"]) != true) && (movie["abridged_cast"].length >= 5)
self.movies.create(title: movie["title"],synopsis: movie["synopsis"],mpaa_rating: movie["mpaa_rating"],year: movie["year"],runtime: movie["runtime"],release_date: movie["release_dates"]["theater"],critics_score: movie["ratings"]["critics_score"],audience_score: movie["ratings"]["audience_score"],poster_thumbnail: movie["posters"]["thumbnail"], cast1: movie["abridged_cast"][0]["name"] || nil, cast2: movie["abridged_cast"][1]["name"] || nil, cast3: movie["abridged_cast"][2]["name"] || nil, cast4: movie["abridged_cast"][3]["name"] || nil, cast5: movie["abridged_cast"][4]["name"] || nil)
end
end
end
end
| true
|
9353c2bed677bdb9b3b8d4c9a3182c75bb6e5c81
|
Ruby
|
tomstuart/inference-rules
|
/spec/parser_spec.rb
|
UTF-8
| 1,689
| 2.78125
| 3
|
[] |
no_license
|
require 'support/builder_helpers'
require 'support/parser_helpers'
RSpec.describe do
include BuilderHelpers
include ParserHelpers
def yes
keyword('true')
end
def no
keyword('false')
end
def conditional(condition, consequent, alternative)
sequence(
keyword('if'), condition,
keyword('then'), consequent,
keyword('else'), alternative
)
end
def evaluates(before, after)
sequence(before, keyword('→'), after)
end
describe 'without variables' do
specify { expect(parse('true')).to eq yes }
specify { expect(parse('if false then false else true')).to eq conditional(no, no, yes) }
specify { expect(parse('if (if true then true else false) then false else true')).to eq conditional(conditional(yes, yes, no), no, yes) }
end
describe 'with variables' do
let(:scope) { double }
specify { expect(parse('(if true then $t₂ else $t₃) → $t₂', scope)).to eq evaluates(conditional(yes, variable('t₂', scope), variable('t₃', scope)), variable('t₂', scope)) }
specify { expect(parse('(if false then $t₂ else $t₃) → $t₃', scope)).to eq evaluates(conditional(no, variable('t₂', scope), variable('t₃', scope)), variable('t₃', scope)) }
specify { expect(parse('$t₁ → $t₁′', scope)).to eq evaluates(variable('t₁', scope), variable('t₁′', scope)) }
specify { expect(parse('(if $t₁ then $t₂ else $t₃) → (if $t₁′ then $t₂ else $t₃)', scope)).to eq evaluates(conditional(variable('t₁', scope), variable('t₂', scope), variable('t₃', scope)), conditional(variable('t₁′', scope), variable('t₂', scope), variable('t₃', scope))) }
end
end
| true
|
6716cc8ad2e27d6eb4c3d10cc5413d187b83b80a
|
Ruby
|
SciRuby/daru-io
|
/lib/daru/io/link.rb
|
UTF-8
| 4,604
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
module Daru
class DataFrame
class << self
# Links `Daru::DataFrame` Import / Export methods to corresponding
# `Daru::IO` Importer / Exporter classes. Here is the list of linkages:
#
# #### Importers
#
# | `Daru::DataFrame` method | `Daru::IO::Importers` class |
# | ----------------------------------- | -----------------------------------------|
# | `Daru::DataFrame.from_activerecord` | {Daru::IO::Importers::ActiveRecord#from} |
# | `Daru::DataFrame.read_avro` | {Daru::IO::Importers::Avro#read} |
# | `Daru::DataFrame.read_csv` | {Daru::IO::Importers::CSV#read} |
# | `Daru::DataFrame.read_excel` | {Daru::IO::Importers::Excel#read}, |
# | | {Daru::IO::Importers::Excelx#read} |
# | `Daru::DataFrame.read_html` | {Daru::IO::Importers::HTML#read} |
# | `Daru::DataFrame.from_json` | {Daru::IO::Importers::JSON#from} |
# | `Daru::DataFrame.read_json` | {Daru::IO::Importers::JSON#read} |
# | `Daru::DataFrame.from_mongo` | {Daru::IO::Importers::Mongo#from} |
# | `Daru::DataFrame.read_plaintext` | {Daru::IO::Importers::Plaintext#read} |
# | `Daru::DataFrame.read_rails_log` | {Daru::IO::Importers::RailsLog#read} |
# | `Daru::DataFrame.read_rdata` | {Daru::IO::Importers::RData#read} |
# | `Daru::DataFrame.read_rds` | {Daru::IO::Importers::RDS#read} |
# | `Daru::DataFrame.from_redis` | {Daru::IO::Importers::Redis#from} |
# | `Daru::DataFrame.from_sql` | {Daru::IO::Importers::SQL#from} |
#
# #### Exporters
#
# | `Daru::DataFrame` instance method | `Daru::IO::Exporters` class |
# | --------------------------------- | -----------------------------------|
# | `Daru::DataFrame.to_avro_string` | {Daru::IO::Exporters::Avro#to_s} |
# | `Daru::DataFrame.write_avro` | {Daru::IO::Exporters::Avro#write} |
# | `Daru::DataFrame.to_csv_string` | {Daru::IO::Exporters::CSV#to_s} |
# | `Daru::DataFrame.write_csv` | {Daru::IO::Exporters::CSV#write} |
# | `Daru::DataFrame.to_excel_string` | {Daru::IO::Exporters::Excel#to_s} |
# | `Daru::DataFrame.write_excel` | {Daru::IO::Exporters::Excel#write} |
# | `Daru::DataFrame.to_json` | {Daru::IO::Exporters::JSON#to} |
# | `Daru::DataFrame.to_json_string` | {Daru::IO::Exporters::JSON#to_s} |
# | `Daru::DataFrame.write_json` | {Daru::IO::Exporters::JSON#write} |
# | `Daru::DataFrame.to_rds_string` | {Daru::IO::Exporters::RDS#to_s} |
# | `Daru::DataFrame.write_rds` | {Daru::IO::Exporters::RDS#write} |
# | `Daru::DataFrame.to_sql` | {Daru::IO::Exporters::SQL#to} |
#
# @param function [Symbol] Functon name to be monkey-patched into +Daru::DataFrame+
# @param instance [Class] The Daru-IO class to be linked to monkey-patched function
#
# @return A `Daru::DataFrame` class method in case of Importer, and instance
# variable method in case of Exporter.
def register_io_module(function, instance=nil, &block)
return define_singleton_method(function, &block) if block_given?
case function.to_s
when /\Ato_.*_string\Z/, /\Ato_/, /\Awrite_/ then register_exporter(function, instance)
when /\Afrom_/, /\Aread_/ then register_importer(function, instance)
else raise ArgumentError, 'Invalid function name given to monkey-patch into Daru::DataFrame.'
end
end
private
def register_exporter(function, instance)
define_method(function) do |*args, &io_block|
case function.to_s
when /\Ato_.*_string\Z/ then instance.new(self, *args, &io_block).to_s
when /\Ato_/ then instance.new(self, *args, &io_block).to
when /Awrite_/ then instance.new(self, *args[1..-1], &io_block).write(*args[0])
end
end
end
def register_importer(function, instance)
define_singleton_method(function) do |*args, &io_block|
case function.to_s
when /\Afrom_/ then instance.new.from(*args[0]).call(*args[1..-1], &io_block)
when /\Aread_/ then instance.new.read(*args[0]).call(*args[1..-1], &io_block)
end
end
end
end
end
end
| true
|
c1fb9e2c5656b264b62e70034908869e42f23661
|
Ruby
|
SamBrigham/ruby-oo-object-relationships-my-pets-yale-web-yss-052520
|
/lib/dog.rb
|
UTF-8
| 331
| 3.03125
| 3
|
[
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
require 'pry'
require_relative "owner.rb"
require_relative "cat.rb"
#see cat notes
class Dog
attr_accessor :owner, :mood
attr_reader :name
@@all = []
def initialize(name, owner)
@name = name
@owner = owner
@mood = "nervous" #initiating dog w nervous mood
@@all << self
end
def self.all
@@all
end
end
| true
|
ac6f9c6f4b50462163a3ac2cf6af55e80abe5537
|
Ruby
|
tomoya55/thumbs_up
|
/lib/acts_as_voter.rb
|
UTF-8
| 4,057
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
module ThumbsUp #:nodoc:
module ActsAsVoter #:nodoc:
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def acts_as_voter
# If a voting entity is deleted, keep the votes.
# has_many :votes, :as => :voter, :dependent => :nullify
# Destroy votes when a user is deleted.
has_many :votes, :as => :voter, :dependent => :destroy
include ThumbsUp::ActsAsVoter::InstanceMethods
extend ThumbsUp::ActsAsVoter::SingletonMethods
end
end
# This module contains class methods
module SingletonMethods
end
# This module contains instance methods
module InstanceMethods
VALUES = {
:gold => 3, :silver => 2, :bronze => 1
}
# plusword
def vote_gold(voteable)
self.vote(voteable, { :value => VALUES[:gold], :exclusive => true })
end
def vote_silver(voteable)
self.vote(voteable, { :value => VALUES[:silver], :exclusive => true })
end
def vote_bronze(voteable)
self.vote(voteable, { :value => VALUES[:bronze], :exclusive => true })
end
def vote_gold?(voteable)
vote_with?(voteable, VALUES[:gold])
end
def vote_silver?(voteable)
vote_with?(voteable, VALUES[:silver])
end
def vote_bronze?(voteable)
vote_with?(voteable, VALUES[:bronze])
end
def vote_with?(voteable, value)
0 < Vote.where(:voter_id => self.id,
:voter_type => self.class.name,
:vote => value,
:voteable_id => voteable.id,
:voteable_type => voteable.class.name
).count
end
# Usage user.vote_count(:up) # All +1 votes
# user.vote_count(:down) # All -1 votes
# user.vote_count() # All votes
def vote_count(for_or_against = :all)
return self.votes.size if for_or_against == "all"
self.votes.count(:conditions => {:vote => (for_or_against ? 1 : -1)})
end
def voted_for?(voteable)
voted_which_way?(voteable, :up)
end
def voted_against?(voteable)
voted_which_way?(voteable, :down)
end
def voted_on?(voteable)
voteable.voted_by?(self)
end
def vote_for(voteable)
self.vote(voteable, { :value => :up, :exclusive => false })
end
def vote_against(voteable)
self.vote(voteable, { :value => :down, :exclusive => false })
end
def vote_exclusively_for(voteable)
self.vote(voteable, { :value => :up, :exclusive => true })
end
def vote_exclusively_against(voteable)
self.vote(voteable, { :value => :down, :exclusive => true })
end
def vote(voteable, options = {})
raise ArgumentError "you must specify value in order to vote" unless options[:value]
if options[:exclusive]
self.clear_votes(voteable)
end
value = [:up, :down].include?(options[:value]) ? (options[:value] == :up ? 1 : -1) : options[:value].to_i
Vote.create!(:vote => value, :voteable => voteable, :voter => self).tap do |v|
voteable.reload_vote_counter if !v.new_record? and voteable.respond_to?(:reload_vote_counter)
end
end
def clear_votes(voteable)
Vote.where(
:voter_id => self.id,
:voter_type => self.class.name,
:voteable_id => voteable.id,
:voteable_type => voteable.class.name
).map(&:destroy)
end
def voted_which_way?(voteable, direction)
raise ArgumentError, "expected :up or :down" unless [:up, :down].include?(direction)
sql = direction == :up ? 'vote >= 1' : 'vote <= -1'
0 < Vote.where(
:voter_id => self.id,
:voter_type => self.class.name,
:voteable_id => voteable.id,
:voteable_type => voteable.class.name
).where(sql).count
end
end
end
end
| true
|
77a008aa48c03fdccb6f2c48273870dbc960ee0a
|
Ruby
|
CAHOCA/Carlos206
|
/Anfitrion.rb
|
UTF-8
| 1,198
| 3.828125
| 4
|
[] |
no_license
|
# To change this license header, choose License Headers in Project Properties.
# To change this template file, choose Tools | Templates
# and open the template in the editor.
class Anfitrion
attr_accessor :nombre
def initialize(nombre="Mundo!")
@nombre=nombre
end
###################
def decir_hola
if @nombre.nil?
puts "..."
elsif @nombre.respond_to?("each")
@nombre.each do |nombre|
puts "Hola #{nombre}"
end
else
puts "Hola #{@nombre}!"
end
end
#######################
def decir_adios
if @nombre.nil?
puts "..."
elsif @nombre.respond_to?("each")
@nombre.each do |nombre|
puts "Adios #{@nombre.join(", ")}. Vuelvan pronto"
end
else
puts "Adios #{@nombre}. Vuelva pronto."
end
end
end
if __FILE__ == $0
ma = Anfitrion.new
ma.decir_hola
ma.decir_adios
# Cambiar el nombre a "Diego"
ma.nombre = "Diego"
ma.decir_hola
ma.decir_adios
# Cambiar el nombre a un vector de nombres
ma.nombre = ["Alberto", "Beatriz", "Carlos",
"David", "Ernesto"]
ma.decir_hola
ma.decir_adios
# Cambiarlo a nil
ma.nombre = nil
ma.decir_hola
ma.decir_adios
end
| true
|
4d7a5e3437b580e4cc7c83bd83475cc83ab1e399
|
Ruby
|
itggot-christoffer-polndorfer-oresten/standard-biblioteket
|
/lib/max_of_three.rb
|
UTF-8
| 377
| 4.21875
| 4
|
[] |
no_license
|
# Public: Takes three integers and returns the biggest one
#
# num1 - the first integer
# num2 - the second integer
# num3- the third integer
#
# Examples
#
# max_of_three(2, 100, 1000)
# => 1000
#
# Returns the biggest integer
def max_of_three(num1, num2, num3)
return num1 if num1 > num2 && num1 > num3
return num2 if num2 > num3 && num2 > num1
return num3
end
| true
|
2becdd6bd4d2249e009e359573e3e97358320238
|
Ruby
|
ianburrell/tivo-fetch
|
/split_shows
|
UTF-8
| 975
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
#!/usr/bin/ruby
def split_file(start_time, duration, input, output)
if File.exists?(output) then
puts "skipping #{output}"
return
end
cmd = %Q{ffmpeg -loglevel fatal -ss #{start_time} -t #{duration} -i "#{input}" -vcodec copy -acodec copy "#{output}"}
puts cmd
system(cmd) or raise "#{cmd} failed: #{$?}"
end
duration = ARGV.shift
ARGV.each do |file|
extension = File.extname(file)
parts = File.basename(file, extension).split(' - ')
if parts.length == 3 then
show_title, episode_num, episode_title = parts
elsif parts.length == 2 then
show_title, episode_title = parts
else
puts "could not split #{file}"
next
end
episodes = episode_title.split('; ')
if episodes.length != 2 then
puts "not multiple episodes #{episode_title}"
next
end
split_file("00:00", duration, file, "#{show_title} - #{episodes[0]}#{extension}")
split_file(duration, duration, file, "#{show_title} - #{episodes[1]}#{extension}")
end
| true
|
7c6b35b2d8129387144071415805cc2db91b9114
|
Ruby
|
cerishaw/exchange
|
/app/helpers/exchange_rate.rb
|
UTF-8
| 555
| 2.90625
| 3
|
[] |
no_license
|
module ExchangeRate
def self.at(date, base_currency_code, counter_currency_code)
base_rate = find_conversion_rate_on_date(date, base_currency_code)
counter_rate = find_conversion_rate_on_date(date, counter_currency_code)
counter_rate / base_rate
end
private
def self.find_conversion_rate_on_date(date, currency_code)
ConversionRate.joins('INNER JOIN currencies ON currencies.id = conversion_rates.currency_id')
.where(currencies: {code: currency_code}, date: date)
.first!.rate
end
end
| true
|
ddfca1b0690706f1848ead35204a7df3fe93c6b0
|
Ruby
|
mduffield/giphy
|
/lib/giphy/response.rb
|
UTF-8
| 500
| 2.5625
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
module Giphy
class Response
def self.build(response)
new(response).data
end
def initialize(response)
@response = response
end
def data
raise Giphy::Errors::Unexpected unless response.body
response.body['data'] || raise(Giphy::Errors::API.new(error))
end
private
attr_reader :response
def error
"#{meta['error_type']} #{meta['error_message']}"
end
def meta
@meta ||= response.body.fetch('meta')
end
end
end
| true
|
04649a340e5a63b8b308408ee86eac1e786d68fa
|
Ruby
|
cbituin/ttt-8-turn-v-000
|
/lib/turn.rb
|
UTF-8
| 2,090
| 4.5625
| 5
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
# Before defining #turn, you should define the following methods:
# #display_board
# Should accept a board as an argument and print out the current state of the board for the user.
def display_board(board)
puts " #{board[0]} | #{board[1]} | #{board[2]} "
puts "-----------"
puts " #{board[3]} | #{board[4]} | #{board[5]} "
puts "-----------"
puts " #{board[6]} | #{board[7]} | #{board[8]} "
end
# #valid_move?
# Should accept a board and an index from the user and return true if the index is within the correct range of 0-8 and is currently unoccupied by an X or O token.
def valid_move?(board, index)
if position_taken?(board, index) == true; false
#elsif board[index] == "X" || board[index] == "O"; true
elsif index > 9 || index < 0; false
else; true
end
end
# Hint: While not explicitly required by this lab, you might want to encapsulate the logic to check if a position is occupied in its own method, perhaps #position_taken?
def position_taken?(board, index)
if board[index] == " " || board[index] == "" || board[index] = nil
false
else
true
#board[index] == "X" || board[index] == "O"
end
end
# #move
# This method should accept a board, an index from the user (which was converted from their raw input with input_to_index), and a token to mark that position with (you can give that argument a default value of 'X'––we're not worrying about whose turn it is yet). The method should set the correct index value of that position within the board equal to the token.
def move(board, userinput, character = "X")
board[userinput] = character
display_board(board)
end
def input_to_index(userinput)
userinput = userinput.to_i
userinput - 1
end
def turn(board)
# ask for input
puts "Please enter 1-9:"
# get input
index = gets.strip
# convert input to index
indexNum = input_to_index(index)
# if index is valid
if valid_move?(board, indexNum) == true
true; move(board, indexNum)
else
false; turn(board)
end
end
| true
|
7aee9846c34c1707ce2cab7521d0b900208953e5
|
Ruby
|
corlinus/simple_model_view
|
/spec/simple_model_view/resource_table_builder_spec.rb
|
UTF-8
| 10,070
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
RSpec.describe SimpleModelView::ResourceTableBuilder, type: :helper do
describe '#format' do
let(:test_model) { TestModel.new('Name') }
subject { described_class.new(helper, test_model) }
let(:formatter) { double :formatter_instance, call: nil }
before { allow(SimpleModelView::ValueFormatter).to receive(:new).and_return(formatter) }
it 'autodects type and calls formatter' do
subject.format('string', :string, {})
expect(formatter).to have_received(:call).with('string', :string, {})
end
it 'autodects type and calls formatter with options' do
subject.format('string', :string, foo: :bar)
expect(formatter).to have_received(:call).with('string', :string, foo: :bar)
end
it 'passes given type to formatter' do
subject.format(123, :integer, {})
expect(formatter).to have_received(:call).with(123, :integer, {})
end
it 'passes given type options to formatter' do
subject.format(123, :integer, foo: :bar)
expect(formatter).to have_received(:call).with(123, :integer, foo: :bar)
end
it 'does not call formatter for nil value' do
subject.format(nil, nil, {})
expect(formatter).not_to have_received(:call)
end
end
describe '#row' do
let(:test_object) do
TestObject.new(
'Name',
'Some Name',
1,
{a: :a},
100,
1.98765,
false,
true,
Time.new(2014, 10, 11),
['name', 'surename', nil, 1],
nil,
Date.today - 1,
Date.new(2119, 7, 4),
Date.today,
Time.now
)
end
subject { described_class.new(self, test_object) }
let(:model_class) { double human_attribute_name: 'Name' }
before { allow(test_object).to receive(:class).and_return(model_class) }
it 'renders for id' do
expect(subject.row(:id)).to eq('<tr class="id"><th>Name</th><td>1</td></tr>')
end
it 'renders for string' do
expect(subject.row(:name)).to eq('<tr class="string"><th>Name</th><td>Some Name</td></tr>')
end
it 'renders for collection' do
expect(subject.row(:collection_val, collection: true)).to eq(
'<tr class="collection"><th>Name</th><td><ul>'\
'<li>name</li><li>surename</li><li><span class="empty">empty</span></li><li>1</li>'\
'</ul></td></tr>')
end
it 'renders empty' do
expect(subject.row(:nil_val)).to eq(
'<tr class="object"><th>Name</th><td><span class="empty">empty</span></td></tr>')
end
it 'renders when `title:` option is given' do
expect(subject.row(:name, title: 'Имя')).to eq(
'<tr class="string"><th>Имя</th><td>Some Name</td></tr>')
end
it 'when value is an Integer' do
expect(subject.row(:integer_val)).to eq(
'<tr class="integer"><th>Name</th><td>100</td></tr>')
end
it 'when value is Float' do
expect(subject.row(:float_val)).to eq(
'<tr class="float"><th>Name</th><td>1.98765</td></tr>')
end
it 'when value is a Float and format with a symbol' do
expect(subject.row(:float_val, format: :price)).to eq(
'<tr class="float"><th>Name</th><td>1.99</td></tr>')
end
it 'when value is a Float and format with a string' do
expect(subject.row(:float_val, format: '%.4f')).to eq(
'<tr class="float"><th>Name</th><td>1.9876</td></tr>')
end
it 'when value is "true" and format with :boolean' do
expect(subject.row(:none, format: :boolean)).to eq(
'<tr class="boolean"><th>Name</th><td>Yes</td></tr>')
end
it 'when value is a Time and format with a symbol' do
expect(subject.row(:created_at, format: :long)).to eq(
'<tr class="time"><th>Name</th><td>October 11, 2014 00:00</td></tr>')
end
it 'when value is a Boolean and `as: string` passed' do
expect(subject.row(:none, as: :string)).to eq(
'<tr class="string"><th>Name</th><td>true</td></tr>')
end
it 'renders html with simple_format helper if `as: :html` is passed' do
expect(subject.row(:name, as: :html, class: 'foo')).
to include('<p class="foo">Some Name</p>')
end
it 'when value is a Time with fromat' do
expect(
subject.row(
:created_at,
format: :date_month_year_concise,
)
).to eq('<tr class="time"><th>Name</th><td>11-10-14</td></tr>')
end
it 'when give varior class and options for label and vlue' do
expect(subject.row(:name,
wrapper_html: {class: 'foo'},
label_html: {align: 'foo'},
value_html: {bgcolor: 'red'}
)
).to eq('<tr class="foo string"><th align="foo">Name</th><td bgcolor="red">Some Name</td></tr>')
end
it 'when type_specific_class is on, value is a float and classes in array' do
expect(
subject.row(
:float_val,
type_specific_class: true,
wrapper_html: {class: %w[foo bar]}
)
).to eq('<tr class="foo bar float positive"><th>Name</th><td>1.98765</td></tr>')
end
it 'when type_specific_class on and date in past' do
expect(subject.row(:date_past, type_specific_class: true)).to include(
'date past yesterday')
end
it 'when type_specific_class on, date is future' do
expect(subject.row(:date_future, type_specific_class: true)).to include('date future')
end
it 'when type_specific_class on, date today' do
expect(subject.row(:date_today, type_specific_class: true)).to include('date today')
end
it 'when type_specific_class on add value in custom_class is a proc' do
expect(
subject.row(:float_val,
type_specific_class: true,
custom_class: {
below_100: proc { |x| x < 100 },
above_100: proc { |x| x > 100 },
}
)
).to include('float positive below_100')
end
it 'when type_specific_class on and value in custom_class is a Symbol' do
expect(
subject.row(
:float_val,
custom_class: {
positive: :positive?,
negative: :negative?,
}
)
).to include('float positive')
end
it 'when type_specific_class on and custom class, value is nil' do
expect(
subject.row(
:nil_val,
type_specific_class: true,
custom_class: {
negative: proc { |x| x < 100 },
}
)
).to include('object')
end
it 'when not ActiveRecord object is passed' do
expect(
described_class.new(self, double(:obj, attr: 'value')).row(:attr)
).to eq('<tr class="string"><th>Attr</th><td>value</td></tr>')
end
it 'yields block and passes attr value' do
expect { |b| subject.row(:name, &b) }.to yield_successive_args(test_object.name)
end
it 'renders block' do
expect(subject.row(:name) { |x| helper.content_tag(:i, x) }).
to eq("<tr class=\"string\"><th>Name</th><td><i>#{test_object.name}</i></td></tr>")
end
it 'renders block for nil value' do
expect(subject.row(:nil_val) { |x| helper.content_tag(:i, x) }).
to eq('<tr class="object"><th>Name</th><td><i></i></td></tr>')
end
it 'does not render block with no_blank_block for nil value' do
expect(subject.row(:nil_val, no_blank_block: true) { |x| helper.content_tag(:i, x) }).
to eq('<tr class="object"><th>Name</th><td><span class="empty">empty</span></td></tr>')
end
it 'renders block for collection' do
expect(subject.row(:collection_val) { |x| helper.content_tag(:i, x) }).
to eq('<tr class="collection"><th>Name</th><td><ul><li><i>name</i></li><li><i>surename</i>'\
'</li><li><i></i></li><li><i>1</i></li></ul></td></tr>')
end
it 'yields block for collection if `collection: false` and passes the collection' do
expect { |b| subject.row(:collection_val, collection: false, &b) }.
to yield_successive_args(test_object.collection_val)
end
it 'yields block once for collection if `collection: false` is passed' do
expect { |b| subject.row(:collection_val, collection: false, &b) }.
to yield_control.once
end
it 'renders block one time for collection if `collection: false` is passed' do
expect(subject.row(:collection_val, collection: false) { |x| helper.content_tag(:i, x.inspect) }).
to eq("<tr class=\"object\"><th>Name</th><td><i>#{
helper.send :html_escape, test_object.collection_val.inspect
}</i></td></tr>")
end
context 'when call formatter and receive whith normal value' do
let(:formatter) { double call: nil }
before { allow(SimpleModelView::ValueFormatter).to receive(:new).and_return(formatter) }
it 'when autodetect string' do
subject.row(:name)
expect(formatter).to have_received(:call).with('Some Name', :string, {})
end
it 'when give type' do
subject.row(:none, as: :boolean)
expect(formatter).to have_received(:call).with(true, :boolean, as: :boolean)
end
it 'when autudetect type and give format' do
subject.row(:created_at, format: :long)
expect(formatter).to have_received(:call).
with(Time.new(2014, 10, 11), :time, format: :long)
end
end
end
describe '#actions' do
let(:test_object) { Object.new }
subject { described_class.new(helper, test_object) }
it 'renders actions cell' do
expect(subject.actions).to eq('<tr><th></th><td></td></tr>')
end
it 'renders actions cell with title' do
expect(subject.actions(title: 'Actions')).to eq('<tr><th>Actions</th><td></td></tr>')
end
it 'yeilds once if block given' do
expect { |b| subject.actions(header_html: {class: 'th'}, &b) }.to yield_control.once
end
it 'passes object to block if block given' do
expect { |b| subject.actions(header_html: {class: 'th'}, &b) }.
to yield_with_args(test_object)
end
end
end
| true
|
ebf21ef6cbf293b8c0db086b64598e058132524f
|
Ruby
|
rayning0/rubyquiz
|
/lib/title_case.rb
|
UTF-8
| 232
| 3.453125
| 3
|
[] |
no_license
|
# http://www.codewars.com/kata/5202ef17a402dd033c000009
class TitleCase
def title_case(title, minor_words = '')
title.capitalize.split().map{|a| minor_words.downcase.split().include?(a) ? a : a.capitalize}.join(' ')
end
end
| true
|
4102663d8f679f54b4477ef96aa0a572138b5126
|
Ruby
|
collabnix/dockerlabs
|
/vendor/bundle/ruby/2.6.0/gems/i18n-0.9.5/test/i18n/interpolate_test.rb
|
UTF-8
| 3,920
| 2.6875
| 3
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
require 'test_helper'
# thanks to Masao's String extensions, some tests taken from Masao's tests
# http://github.com/mutoh/gettext/blob/edbbe1fa8238fa12c7f26f2418403015f0270e47/test/test_string.rb
class I18nInterpolateTest < I18n::TestCase
test "String interpolates a hash argument w/ named placeholders" do
assert_equal "Masao Mutoh", I18n.interpolate("%{first} %{last}", :first => 'Masao', :last => 'Mutoh' )
end
test "String interpolates a hash argument w/ named placeholders (reverse order)" do
assert_equal "Mutoh, Masao", I18n.interpolate("%{last}, %{first}", :first => 'Masao', :last => 'Mutoh' )
end
test "String interpolates named placeholders with sprintf syntax" do
assert_equal "10, 43.4", I18n.interpolate("%<integer>d, %<float>.1f", :integer => 10, :float => 43.4)
end
test "String interpolates named placeholders with sprintf syntax, does not recurse" do
assert_equal "%<not_translated>s", I18n.interpolate("%{msg}", :msg => '%<not_translated>s', :not_translated => 'should not happen' )
end
test "String interpolation does not replace anything when no placeholders are given" do
assert_equal "aaa", I18n.interpolate("aaa", :num => 1)
end
test "String interpolation sprintf behaviour equals Ruby 1.9 behaviour" do
assert_equal "1", I18n.interpolate("%<num>d", :num => 1)
assert_equal "0b1", I18n.interpolate("%<num>#b", :num => 1)
assert_equal "foo", I18n.interpolate("%<msg>s", :msg => "foo")
assert_equal "1.000000", I18n.interpolate("%<num>f", :num => 1.0)
assert_equal " 1", I18n.interpolate("%<num>3.0f", :num => 1.0)
assert_equal "100.00", I18n.interpolate("%<num>2.2f", :num => 100.0)
assert_equal "0x64", I18n.interpolate("%<num>#x", :num => 100.0)
assert_raise(ArgumentError) { I18n.interpolate("%<num>,d", :num => 100) }
assert_raise(ArgumentError) { I18n.interpolate("%<num>/d", :num => 100) }
end
test "String interpolation raises an I18n::MissingInterpolationArgument when the string has extra placeholders" do
assert_raise(I18n::MissingInterpolationArgument) do # Ruby 1.9 msg: "key not found"
I18n.interpolate("%{first} %{last}", :first => 'Masao')
end
end
test "String interpolation does not raise when extra values were passed" do
assert_nothing_raised do
assert_equal "Masao Mutoh", I18n.interpolate("%{first} %{last}", :first => 'Masao', :last => 'Mutoh', :salutation => 'Mr.' )
end
end
test "% acts as escape character in String interpolation" do
assert_equal "%{first}", I18n.interpolate("%%{first}", :first => 'Masao')
assert_equal "% 1", I18n.interpolate("%% %<num>d", :num => 1.0)
assert_equal "%{num} %<num>d", I18n.interpolate("%%{num} %%<num>d", :num => 1)
end
def test_sprintf_mix_unformatted_and_formatted_named_placeholders
assert_equal "foo 1.000000", I18n.interpolate("%{name} %<num>f", :name => "foo", :num => 1.0)
end
class RailsSafeBuffer < String
def gsub(*args, &block)
to_str.gsub(*args, &block)
end
end
test "with String subclass that redefined gsub method" do
assert_equal "Hello mars world", I18n.interpolate(RailsSafeBuffer.new("Hello %{planet} world"), :planet => 'mars')
end
end
class I18nMissingInterpolationCustomHandlerTest < I18n::TestCase
def setup
super
@old_handler = I18n.config.missing_interpolation_argument_handler
I18n.config.missing_interpolation_argument_handler = lambda do |key, values, string|
"missing key is #{key}, values are #{values.inspect}, given string is '#{string}'"
end
end
def teardown
I18n.config.missing_interpolation_argument_handler = @old_handler
super
end
test "String interpolation can use custom missing interpolation handler" do
assert_equal %|Masao missing key is last, values are {:first=>"Masao"}, given string is '%{first} %{last}'|,
I18n.interpolate("%{first} %{last}", :first => 'Masao')
end
end
| true
|
b34c6137ffa31139ee843b94c221a3f7db582cb3
|
Ruby
|
dawidof/server_stat
|
/lib/server_statistics.rb
|
UTF-8
| 1,753
| 2.515625
| 3
|
[] |
no_license
|
class ServerStatistics
def self.get
cpu_rvm_count = `ps -ef | grep rben |wc -l`
cpu_count = `ps -ef | wc -l`
uptime = `uptime`
captures = (`uptime`.match /up (?:(?:(\d+) day?.,)?\s*(\d+):(\d+)|(\d+) min)/)
# puts captures.inspect
if captures.nil?
captures = (`uptime`.match /up (?:(?:(\d+) day?.,)?\s*(\d+) min)/)
if captures.nil?
captures = (`uptime`.match /up (?:(?:(\d+) day?.,)?\s*(\d+):(\d+) min)/)
if captures.nil?
captures = (`uptime`.match /up (?:(?:(\d+) day?.,)?\s*(\d+):(\d+))/)
# puts captures.captures.inspect
captures = captures.captures.insert(3, nil)
else
# puts captures.captures.inspect
captures = captures.captures.insert(3, nil)
end
else
# puts captures.inspect
captures = captures.captures.insert(1, nil).insert(3, nil)
end
else
captures = captures.captures
end
elapsed_seconds = captures.zip([86440, 3600, 60, 60]).inject(0) do |total, (x,y)|
total + (x.nil? ? 0 : x.to_i * y)
end
up = Time.now - elapsed_seconds
memory_usage = `free -m | awk '/Mem:/ {total=$2} /Mem:/ {used=$3} END {print used/total*100}'`
swap_to_ram_usage = `free -m | awk '/Mem:/ { total=$2 } /Swap:/ { used=$3 } END { print used/total*100}'`
cpu_usage = uptime.split.last(3).join(' ')
free_hdd = (100 - `df -h | awk '/dev/ {print $5}'`.split("\n")[0].to_i).to_s + '%'
hash = {
cpu_count: cpu_count.chomp,
uptime: up,
cpu_rvm_count: cpu_rvm_count.chomp,
cpu_usage: cpu_usage,
memory_usage: memory_usage.to_f.round(2).to_s,
swap_to_ram_usage: swap_to_ram_usage.to_f.round(2).to_s,
checked: Time.now,
free_disk: free_hdd
}
return hash
end
end
| true
|
38b75cd3174591392a753f016cc81bb69da45f09
|
Ruby
|
mcmillhj/PL0Compiler
|
/SyntaxTree/ParameterListNode.rb
|
UTF-8
| 504
| 2.921875
| 3
|
[] |
no_license
|
class ParameterListNode < Node
attr_reader :param_list
def initialize param_list
super()
@param_list = param_list
end
# todo
def accept visitor
# visit all the parameters
@param_list.each do |param|
param.accept visitor
end
visitor.visit_formal_param_list self
end
def types
@param_list.map{|p| p.get_type}
end
def names
@param_list.map{|p| p.get_name}
end
def to_s
return "ParameterListNode -> #{@param_list}"
end
end
| true
|
dadbf61dabc41aac03fbb3a48de7ff001452df60
|
Ruby
|
dabeeya/phase_0_unit_2
|
/week_4/5_pad_array/my_solution.rb
|
UTF-8
| 1,890
| 4.15625
| 4
|
[] |
no_license
|
# U2.W4: Pad an Array
# Complete each step below according to the challenge directions and
# include it in this file. Also make sure everything that isn't code
# is commented in the file.
# I worked on this challenge [by myself, with: ].
# 1. Pseudocode
# What is the input?
# What is the output? (i.e. What should the code return?)
# What are the steps needed to solve the problem?
#1. see if we need to pad or not
#2. if we don't need to pad, return array
#3. if we do need to pad, and they don't specificy to add anything, add nil until you reach the number pad
# is asking for
# 2. Initial Solution
#extending the arary class
#monkey patching
# 3. Refactored Solution
class Array
def pad(new_length, new_value=nil)
new_array = self.clone
if new_length <= self.length
return new_array
else
push_num = new_length - self.length
push_num.times{|x| new_array.push(new_value)}
return new_array
end
end
def pad!(new_length, new_value=nil)
if new_length <= self.length
return self
else
push_num = new_length - self.length
push_num.times{|x| self.push(new_value)}
return self
end
end
end
# 4. Reflection
# I had a lot of trouble trying to figure out how to begin this challenge. I think my biggest problem was trying to
# figure out how to write the syntax. Also, I had to learn from an instructor/tutor that we would have to extending
# the array class so that out pad method would work.
# After this challenge, I am feeling not that conifdent about the learning compeneticies. I still felt pretty lost
# even when I was being helped tutored.
# It sucked that I wasn't able to to this by myself and that I got stuck on different parts. I didn't enjoy this
# challenge and everything felt tedious.
| true
|
ffb2ff86a32da3089ce2bb83cd809027444dd3c3
|
Ruby
|
tkt989/atcoder
|
/abc147_c.rb
|
UTF-8
| 868
| 2.828125
| 3
|
[
"MIT"
] |
permissive
|
N = gets.chomp.to_i
A = []
N.times do
n = gets.chomp.to_i
a = {}
n.times do
x, y = gets.chomp.split(" ").map(&:to_i)
a[x-1] = y
end
A << a
end
def check(a, liars)
table = {}
a.each do |list|
list.each do |k, v|
if table[k] != nil && table[k] != v then
return nil
end
table[k] = v
end
end
l = []
table.each do |k, v|
l << k if v == 0
end
p l
p liars
if l.sort != liars.sort then
return nil
end
return l.size
end
result = check(A, [])
if result == 0 then
puts N
exit
end
all = (0...N).to_a
(1..N).each do |n|
all.combination(n).each do |flips|
a = A.clone
flips.each do |idx|
a[idx] = a[idx].map{ |k,v| [k, v == 1 ? 0 : 1]}.to_h
end
result = check(a, flips)
if result != nil && result == n then
puts N - n
exit
end
end
end
puts "0"
| true
|
5ecde7a7ccb63a833346f217d6f39f47c902336b
|
Ruby
|
aaecheverria96/oo-cash-register-onl01-seng-pt-072720
|
/lib/cash_register.rb
|
UTF-8
| 655
| 3.09375
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
require 'pry'
class CashRegister
attr_accessor :new, :discount, :total, :items
def initialize(discount = 0)
@total = 0
@discount = discount
@items = []
#items_list << @items
end
def add_item(title,price,quantity = 1)
quantity.times do
items << title
end
@last_total = @total
@total += price * quantity
end
def apply_discount
applied_discount = (100 - @discount) * 0.01
@total = applied_discount * @total
if @discount != 0
return "After the discount, the total comes to $#{@total.to_i}."
else
return "There is no discount to apply."
end
end
def items
@items
end
def void_last_transaction
@total = @last_total
end
end
| true
|
e8f576d8e740032349fe0511de85fefa3beac268
|
Ruby
|
kjkosmatka/makebelieve
|
/lib/makebelieve/network.rb
|
UTF-8
| 2,858
| 2.96875
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
class Network
require 'ostruct'
CONTEXTS = [:variables, :probabilities, :attributes]
attr_reader :vars, :pots, :meta, :graph
def initialize(options={}, &block)
@meta = OpenStruct.new
@graph = Graph.new
@vars = options[:variables].nil? ? [] : optioens[:variables]
@pots = options[:potentials].nil? ? [] : options[:potentials]
self.instance_eval(&block) if block_given?
end
def full_setting_probability(instance)
@pots.inject(1) { |product,pot| product * pot.probability(instance) }
end
def ask(variable_name, options={}, &block)
defaults = {:by => :enumeration, :given => Hash.new}
options = defaults.merge(options)
var = @vars.find_by_name(variable_name)
evidence = block_given? ? instance_eval(&block) : options[:given]
if options[:by] == :enumeration
return ask_enumerate(var, evidence)
elsif options[:by] == :elimination
return Elimination.new(self, variable_name, evidence).infer
elsif options[:by] == :gibbs
g = GibbsInference.new(self, evidence, options)
g.infer
return g.query(variable_name)
end
end
def ask_enumerate(variable, evidence)
# form an array with an entry for each outcome of the query variable
distribution = variable.outcomes.map do |voutcome|
# add this outcome to the evidence
ev = evidence.merge({variable.name => voutcome})
# summing across all instantiations consistent with evidence
sum = 0
Variable::each_instantiation(@vars, :given => ev) do |instance|
sum += full_setting_probability(instance)
end
sum
end
DiscreteDistribution.new distribution.normalized
end
def given(evidence)
evidence
end
def discrete(name, outcomes=[true,false])
@vars << Variable.new(name,outcomes)
end
alias_method :boolean, :discrete
def add_potential(variable_name, options={}, &block)
parents = options[:given]
@graph.node variable_name
@graph.breed parents, variable_name unless parents.nil?
varnames = Array(options[:given]) + Array(variable_name)
vars = varnames.map { |vname| @vars.find_by_name(vname) }
probs = block_given? ? block.call : options[:distribution]
@pots << Potential.new(vars, probs)
end
def variable(symbol)
@vars.find_by_name(symbol)
end
def context(symbol, &block)
@context = symbol.to_sym
instance_eval(&block) if block_given? and CONTEXTS.include?(@context)
@context = nil
end
def method_missing(symbol, *args, &block)
if CONTEXTS.include?(symbol)
context(symbol, &block)
elsif @context == :variables
# pass
elsif @context == :probabilities
add_potential(symbol, *args, &block)
elsif @context == :attributes
@meta.send("#{symbol}=", args[0])
else
raise NoMethodError
end
end
end
| true
|
ac3568d15b626de999d098ef77d399b802212989
|
Ruby
|
camilamaia/algorithms-stanford
|
/course1/week1/sort/merge_sort.rb
|
UTF-8
| 900
| 3.9375
| 4
|
[] |
no_license
|
def merge_sort array
n = array.size
# Array of size 1 or less is always sorted
return array if n <= 1
# Apply "Divide & Conquer" strategy
# 1. Divide
mid = n / 2
part_a = merge_sort array.slice(0, mid)
part_b = merge_sort array.slice(mid, n - mid)
# 2. Conquer
sorted = []
i = 0
j = 0
while i < part_a.size && j < part_b.size
# Take the smallest of the two, and push it on our array
if part_a[i] < part_b[j]
sorted << part_a[i]
i += 1
else part_b[j] < part_a[i]
sorted << part_b[j]
j += 1
end
end
while i < part_a.size
sorted << part_a[i]
i += 1
end
while j < part_b.size
sorted << part_b[j]
j += 1
end
return sorted
end
# array size 8 containing distincs elements between 0..10
input = (0..10).to_a.sort{ rand() - 0.5 }[0..7]
p "Input: #{input}"
output = merge_sort input
p "Output: #{output}"
| true
|
3cbbb89920df2d2c632830e136ed2dcdf4917e52
|
Ruby
|
xord/reflexion
|
/reflex/test/test_window.rb
|
UTF-8
| 3,091
| 2.8125
| 3
|
[
"MIT"
] |
permissive
|
# -*- coding: utf-8 -*-
require_relative 'helper'
class TestWindow < Test::Unit::TestCase
def win(*a, **k, &b)
Reflex::Window.new(*a, **k, &b)
end
def point(*a) Reflex::Point.new(*a) end
def bounds(*a) Reflex::Bounds.new(*a) end
def test_show_hide_hidden()
w = win
assert_equal true, w.hidden
w.show
assert_equal false, w.hidden
w.hide
assert_equal true, w.hidden
w.hide
assert_equal true, w.hidden
w.show
assert_equal true, w.hidden
w.show
assert_equal false, w.hidden
end
def test_coord_conversion()
w = win x: 100, y: 200
assert_equal [400, 300], w.from_screen(500).to_a
assert_equal [600, 700], w. to_screen(500).to_a
end
def test_title()
w = win
assert_equal '', w.title
w.title = 'A'
assert_equal 'A', w.title
end
def test_frame()
w = win
b = w.frame.dup
assert_equal b, w.frame
w.frame = 1; assert_equal [0, 0, 1, 1], w.frame.to_a
w.frame = [1]; assert_equal [0, 0, 1, 1], w.frame.to_a
w.frame = [1, 2]; assert_equal [0, 0, 1, 2], w.frame.to_a
w.frame = [1, 2, 3]; assert_equal [0, 0, 1, 2], w.frame.to_a
w.frame = [1, 2, 3]; assert_equal [0, 0, 0, 1, 2, 0], w.frame.to_a(3)
w.frame = [1, 2, 3, 4]; assert_equal [1, 2, 3, 4], w.frame.to_a
w.frame = [1, 2, 3, 4]; assert_equal [1, 2, 0, 3, 4, 0], w.frame.to_a(3)
w.frame = [1, 2, 3, 4, 5, 6]; assert_equal [1, 2, 4, 5], w.frame.to_a
w.frame = [1, 2, 3, 4, 5, 6]; assert_equal [1, 2, 0, 4, 5, 0], w.frame.to_a(3)
w.frame = point(1); assert_equal [0, 0, 1, 1], w.frame.to_a
w.frame = [point(1)]; assert_equal [0, 0, 1, 1], w.frame.to_a
w.frame = point(1, 2); assert_equal [0, 0, 1, 2], w.frame.to_a
w.frame = [point(1, 2)]; assert_equal [0, 0, 1, 2], w.frame.to_a
w.frame = [point(1, 2), point(3, 4)]; assert_equal [1, 2, 3, 4], w.frame.to_a
w.frame = [point(1, 2), point(3, 4)]; assert_equal [1, 2, 0, 3, 4, 0], w.frame.to_a(3)
w.frame = [point(1, 2, 3), point(4, 5, 6)]; assert_equal [1, 2, 4, 5], w.frame.to_a
w.frame = [point(1, 2, 3), point(4, 5, 6)]; assert_equal [1, 2, 0, 4, 5, 0], w.frame.to_a(3)
w.frame = bounds(1, 2, 3, 4, 5, 6); assert_equal [1, 2, 0, 4, 5, 0], w.frame.to_a(3)
w.frame = [bounds(1, 2, 3, 4, 5, 6)]; assert_equal [1, 2, 0, 4, 5, 0], w.frame.to_a(3)
end
def test_resizable?()
w = win
assert_true w.resizable?
w.resizable = false
assert_false w.resizable?
w.resizable = true
assert_true w.resizable?
w.resizable false
assert_false w.resizable?
w.resizable true
assert_true w.resizable?
end
def test_root()
w = win
assert_not_nil w.root
assert_nil w.root.parent
assert_equal 'ROOT', w.root.name
assert_equal w, w.root.window
end
end# TestWindow
| true
|
c13e19072ff7593fd5d7603c48b715c4844390b9
|
Ruby
|
m4thayus/emoticon-translator-dc-web-051319
|
/lib/translator.rb
|
UTF-8
| 1,000
| 3.28125
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
require 'yaml'
require 'pry'
def load_library(path)
library = YAML.load_file(path)
emoticons = {"get_meaning" => {}, "get_emoticon" => {}}
library.each do |meaning, icons|
emoticons["get_meaning"][icons[1]] = meaning
emoticons["get_emoticon"][icons[0]] = icons[1]
end
emoticons
end
def get_japanese_emoticon(path, emoticon)
translation = nil
library = load_library(path)
library["get_emoticon"].each do |english, japanese|
if emoticon == english
translation = japanese
end
end
!(translation) ? translation = "Sorry, that emoticon was not found" : nil
translation
end
def get_english_meaning(path, emoticon)
translation = nil
library = load_library(path)
library["get_meaning"].each do |japanese, meaning|
if emoticon == japanese
translation = meaning
end
end
!(translation) ? translation = "Sorry, that emoticon was not found" : nil
translation
end
| true
|
e3f186959a8a1050b8b6b638e92a9bb1ba9429e0
|
Ruby
|
jameshughes7/bank_tech_test
|
/spec/account_spec.rb
|
UTF-8
| 1,377
| 2.921875
| 3
|
[] |
no_license
|
require 'account'
describe Account do
subject(:account) { described_class.new(0) }
describe '#initialize' do
it 'should create a new instance of Account class' do
account = Account.new
expect(account).to be_instance_of(Account)
end
it 'should initialize with a default zero balance' do
account = Account.new
expect(account.show_balance).to eq(0)
end
it 'should initialize with a empty transaction array' do
account = Account.new
expect(account.transactions).to eq([])
end
end
describe '#account can receive data' do
it 'should be able to receive a credit' do
account = Account.new
expect(account).to respond_to(:credit).with(1).argument
account.credit(100)
expect(account.show_balance).to eq(100)
end
it 'should be able to receive a debit' do
account = Account.new
expect(account).to respond_to(:debit).with(1).argument
account.debit(100)
expect(account.show_balance).to eq(-100)
end
it 'should be able to receive transaction_records' do
account = Account.new
expect(account).to respond_to(:receive_transactions).with(2).arguments
account.receive_transactions(100, nil)
expect(account.transaction_record).to(be_a(Hash))
expect(account.transactions[0]).to eq(account.transaction_record)
end
end
end
| true
|
a72ab9408c76a34494cabfbc272e29cea456e57d
|
Ruby
|
mje113/newark
|
/test/test_router.rb
|
UTF-8
| 2,986
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
require 'helper'
class TestingApp
include Newark
before do
headers['X-Newark-Version'] = Newark::VERSION
end
before do
if params[:token] && params[:token] == '123456'
redirect_to 'http://example.com' && return
end
end
after do
headers['X-Newark-Done'] = 'true'
end
get '/', params: { user: 'frank' } do
'hello frank'
end
get '/' do
'hello'
end
get(/\/regexp/) do
'regexp'
end
get '/create' do
'whoops'
end
post '/create' do
'created'
end
get '/request_and_response' do
request && response
headers && params
'ok'
end
get '/variables/:a/:b' do
"#{params[:a]}:#{params[:b]}"
end
get '/path_globbing/*rest_of_path' do
params[:rest_of_path]
end
get '/trailing_slash/' do
'trailing_slash'
end
get '/no_trailing_slash' do
'no_trailing_slash'
end
end
class TestRouter < MiniTest::Unit::TestCase
include Rack::Test::Methods
def app
Rack::Lint.new(TestingApp.new)
end
def test_gets_root
get '/'
assert last_response.ok?
assert_equal 'hello', last_response.body
end
def test_gets_root_with_param_constraint
get '/', user: 'frank'
assert last_response.ok?
assert_equal 'hello frank', last_response.body
end
def test_gets_404
get '/not_found'
refute last_response.ok?
assert last_response.not_found?
end
def test_gets_by_regexp
get '/regexp'
assert last_response.ok?
assert_equal 'regexp', last_response.body
end
def test_post
post '/create'
assert last_response.ok?
assert_equal 'created', last_response.body
end
def test_has_access_to_request_and_response
get '/request_and_response'
assert last_response.ok?
assert_equal 'ok', last_response.body
end
def test_before_hook
get '/'
assert_equal Newark::VERSION, last_response.header['X-Newark-Version']
end
def test_before_hook_stops_rendering
skip
get '/', token: '123456'
assert last_response.redirected?
end
def test_after_hook
get '/'
assert_equal 'true', last_response.header['X-Newark-Done']
end
def test_variable_globbing
get '/variables/fu/bar'
assert last_response.ok?
assert_equal 'fu:bar', last_response.body
end
def test_path_globbing
get '/path_globbing/rest/of/path'
assert last_response.ok?
assert_equal 'rest/of/path', last_response.body
end
def test_deals_with_trailing_slashes
get '/trailing_slash/'
assert last_response.ok?
assert_equal 'trailing_slash', last_response.body
get '/trailing_slash'
assert last_response.ok?
assert_equal 'trailing_slash', last_response.body
end
def test_deals_with_no_trailing_slashes
get '/no_trailing_slash/'
assert last_response.ok?
assert_equal 'no_trailing_slash', last_response.body
get '/no_trailing_slash'
assert last_response.ok?
assert_equal 'no_trailing_slash', last_response.body
end
end
| true
|
cbce173cddd929d3733447e515458873443aa952
|
Ruby
|
nmaisonneuve/gsv_downloader
|
/lib/gsv_downloader/image_downloader_parallel.rb
|
UTF-8
| 1,224
| 3.109375
| 3
|
[
"MIT"
] |
permissive
|
require "typhoeus"
require "image_downloader.rb"
# Google Street View Image Downloader
# multi_thread version (get the tiles in a multithread way)
class ImageDownloaderParallel < ImageDownloader
def initialize(tmp_path = "./tmp")
set_tmp_dir(tmp_path)
end
def parallel_download(data)
# process
hydra = Typhoeus::Hydra.new
data.each do | datum|
request = Typhoeus::Request.new(datum[:url])
request.on_complete do |response|
process_response(response, datum[:filename])
end
hydra.queue request
end
hydra.run
data.collect{ |datum| datum[:filename]}
end
def download_tiles(panoID, zoom_level)
# prepare the information for each tile
data = []
filenames = []
get_tiles(zoom_level) do |x, y|
data << {
url: "http://cbk1.google.com/cbk?output=tile&zoom=#{zoom_level}&x=#{x}&y=#{y}&v=4&panoid=#{panoID}",
filename: "#{@tmp_path}/tile-#{panoID}-#{x}-#{y}.jpg"
}
end
parallel_download(data)
data.collect{ |datum| datum[:filename]}
end
def process_response(response, filename)
if response.success?
open(filename, 'wb') do |file|
file.write(response.body)
end
else
raise Exception.new("tile #{filename} not downloaded")
end
end
end
| true
|
8ee06b77dc733aacdfbe0a8a788309f109ae7678
|
Ruby
|
sirsir/PMS-FCT-cms
|
/- svn/PMS/app/models/caption.rb
|
UTF-8
| 1,020
| 2.796875
| 3
|
[] |
no_license
|
class Caption < ActiveRecord::Base
belongs_to :label
belongs_to :language
validates_uniqueness_of :label_id, :scope => [:language_id]
validates_presence_of :label_id
validates_presence_of :name
alias_attribute :description, :name
class << self
# Caption.missing_msg(caption_id, info = nil) -> string
# Get message when caption is missing.
# Caption.missing(0) #=> "<span class='error_message'>Caption with ID=0 is missing!</span>"
# Caption.missing(0, 'Extra info') #=> "<span class='error_message'>Caption with ID=0 (Extra info) is missing!</span>"
def missing_msg(caption_id, info = nil)
"<span class='error_message'>Caption with ID=#{caption_id}#{" (#{info})" if info} is missing!</span>"
end
end # class << self
# caption.descr
# Get caption's description.
# Caption.find(:first, :conditions => {:name => 'Age'}).descr => "Age"
def descr
if self[:name] =~ /#\{.+\}/
eval "\"#{self[:name]}\""
else
self[:name]
end
end
end
| true
|
90286ae9285fdf933bfc60f76951b828d9dae93a
|
Ruby
|
Karunamon/farscrape
|
/main.rb
|
UTF-8
| 3,451
| 2.8125
| 3
|
[] |
no_license
|
require 'mechanize' #Heavy lifting
require 'net/http' #Other shenanigans
require 'logger'
#require 'pry' #debugger
require 'rbconfig' #Need to tell what our host OS is
###CONFIGURATION
$certfile = 'cacert.pem'
#Base64 encode these so anybody over your shoulder can't see your login details
$wf_username = Base64.decode64('')
$wf_password = Base64.decode64('')
######
#Real stuff begins here
#Let's set up the scraper.
farscrape = Mechanize.new
# Work around some really silly Windows breakage
# http://blog.emptyway.com/2009/11/03/proper-way-to-detect-windows-platform-in-ruby/
# http://stackoverflow.com/questions/8567973/why-does-accessing-a-ssl-site-with-mechanize-on-windows-fail-but-on-mac-work
farscrape.agent.http.ca_file = File.expand_path($certfile) if RbConfig::CONFIG['host_os'] =~ /mingw|mswin/
#Turn on logging to stdout
farscrape.log = Logger.new(STDOUT)
farscrape.log.level = Logger::WARN
#Look like every other browser out there
farscrape.user_agent_alias = 'Windows IE 8'
#Here we use the "online account access" page. The front page has a login form too,
#but that is much more likely to change in weird ways in the future. This one is
#stable and simple.
farscrape.log.info('Loading signon page')
page = farscrape.get('https://online.wellsfargo.com/signon?LOB=CONS')
#Grab the login form
login_form = page.form('Signon')
#Fill the fields
login_form.userid = $wf_username
login_form.password = $wf_password
farscrape.log.info('Submitting credentials')
page = farscrape.submit(login_form, login_form.buttons.first)
#Now there's an interstitial page. Let's follow that URL!
redirecturl = page.parser.at('meta[http-equiv="Refresh"]')['content'][/URL=(.+)/, 1]
page = farscrape.get(redirecturl)
#At this point we've got a login cookie, so we're golden.
#Occasionally they'll throw some weird advertisement-esque "thing" here.
#Let's make sure we're on the account page!
until page.title.include? 'Account Summary'
farscrape.log.warn('Could not get account summary. Going to try again.')
reloadcount +=1
raise RuntimeError 'Could not get account summary in 3 tries, bailing out!' if reloadcount > 3
waittime = Random.rand(5..15)
farscrape.log.warn("Waiting #{waittime} seconds to retry")
sleep(waittime)
farscrape.log.warn('Here we go again!')
page = farscrape.get(redirecturl)
end
accountstable = page.parser.xpath('//table[@id="cash"]//tr') #cash contains the table with our account info. let's get all the TRs
#There will be one tr per account, in addition to the header line and the total line.
#Therefore, we don't care about the first or the last tr's on the page
accountsrows = accountstable[1, accountstable.count-1]
accountresults = []
#Generate an array containing account names and balances.
#This is kind of ugly, but it works. We know the first item in each split row
#will be some name for the account. Depending on how many words there are,
#there may be more, but for sanity's sake, we'll just take the first one.
#Usually the last item in each row will be the available balance, but here
#we can't rely on that due to funny characters (like the (R) symbol) messing
#with the formatting. I can think of no reason someone's account name would
#contain a dollar sign with digits, so we'll use that to know we have an amount.
#tl;dr: HTML be crazy.
accountsrows.each { |row| accountresults.push(row.content.split[0]).push(row.content.split.grep(/\$\d/))}
puts accountresults
| true
|
fc6554dc8a4e2ac10c9b4d35edbb34c96e078f9a
|
Ruby
|
h-nagamine09/review
|
/paiza1.rb
|
UTF-8
| 411
| 3.765625
| 4
|
[] |
no_license
|
# Here your code !
# And演算子
number1 = 1
number2 = 2
number3 = rand(1..100)
puts number3
if number3 >= 30 && number2 <= 60
puts "あたり"
else
puts "ハズレ"
end
# 演習問題
# 順位に合わせてメッセージを表示する
number = rand(1..10)
puts "あなたの順位は#{number}位です"
## ここにifを追加する
if number >= 2 && number <= 5
puts 'あと少し!'
end
| true
|
378aa7b609f26eff689c946fbbbfe99df34061fa
|
Ruby
|
Ank13/socrates_prep
|
/count_bw.rb
|
UTF-8
| 352
| 3.953125
| 4
|
[] |
no_license
|
def count_between(array, lower_bound, upper_bound)
array.count{|x| x >= lower_bound && x <= upper_bound}
end
puts count_between([1,2,3], 0, 100) # => 3
puts count_between([-10, 1, 2], 0, 100) # => 2
puts count_between([10, 20, 30], 10, 30) # => 3
puts count_between([], -100, 100) # => 0
puts count_between([0], 0, 0) # => 1
| true
|
126f8208fb104f555469c651fb89b7d06e446d45
|
Ruby
|
mdmccoy/wyncode
|
/voter_sim/status_msgs.rb
|
UTF-8
| 251
| 2.65625
| 3
|
[] |
no_license
|
module Status_msgs
def invalid_input
puts "\nEnter a valid input."
end
def person_added(type)
puts "\n#{type} added to world."
end
def invalid_person
puts "\nInvalid person type."
end
def done
puts "\nDone!"
end
end
| true
|
1e6cb2a54ef4333a89cdef9a300a4d8149d6b84d
|
Ruby
|
turnon/mychart.js.rb
|
/test/x_test.rb
|
UTF-8
| 421
| 2.953125
| 3
|
[
"MIT"
] |
permissive
|
require 'minitest/autorun'
require 'my_chart/x'
class TestX < MiniTest::Unit::TestCase
def test_x_to_xy
xy = @x.group_by {|num| num % 3}
exp = {0 => [3,6,9,12,15,18], 1 => [1,4,7,10,13,16,19], 2 => [2,5,8,11,14,17,20]}
assert_equal exp, xy.value
end
def test_select
gt19 = @x.select {|n| n > 19}
assert_equal [20], gt19.value
end
def setup
@x = MyChart::X.new (1..20).to_a
end
end
| true
|
7ca5156d6598257c25230fa2ccbdc20ec762c9df
|
Ruby
|
gpks/algorythms
|
/binary/solution.rb
|
UTF-8
| 337
| 3.453125
| 3
|
[] |
no_license
|
class Algo
def solution(n)
binary = "%b" % n
solution = 0
current = 0
binary.each_char.with_index do |bin, i|
if bin == '0'
current += 1
else
solution = current if current > solution
break if current > binary[i+1..-1].size
current = 0
end
end
solution
end
end
| true
|
e0830b1daaad410a2a208948c8d33e6a092c7800
|
Ruby
|
rastullahs-lockenpracht/modules
|
/regressiontest/scripts/effecttest.rb
|
UTF-8
| 2,075
| 2.71875
| 3
|
[] |
no_license
|
require 'testcase.rb'
load "effects/astraleregeneration.rb"
load "effects/ausdauernd.rb"
load "effects/paralues.rb"
load "effects/resistentgegenkrankheiten.rb"
load "effects/schnelleheilung.rb"
load "effects/wunde.rb"
class ParaluesAction < Action
def initialize
super("paralues", "Spontan versteinern.");
end
def canDo(go, user, target)
true
end
def doAction(go, user, target)
p "Du wirst versteinert.";
$hero.addEffectWithCheckTime($paralueseffect, 1 * Date::ONE_KAMPFRUNDE);
p "Du solltest dich jetzt eine Weile nicht mehr bewegen können.";
end
end
class ResistenzAction < Action
def initialize
super("resistenz", "Resistenz gegen Krankheiten erweben.");
end
def canDo(go, user, target)
true
end
def doAction(go, user, target)
p "KO normal: "
p $hero.getEigenschaft("KO");
p "Du wirst resistent gegen Krankheiten.";
$hero.addEffect($resistenzeffect);
p "Effekt angewendet.";
p "KO gegen Krankheiten: "
p $hero.getEigenschaft("KO", Effect::MODTAG_KRANKHEIT);
end
end
# Test case for weffects.
class EffectTest < TestCase
def execute()
# Define a pointer to the hero
$h = PartyManager.getSingleton().getActiveCharacter()
# Define a base box to place everything else on.
height = 0.1
min_base = [-2.0, 0.05, -2.0]
max_base = [2.0, height, 2.0]
base = $AM.createBoxPrimitiveActor("EffectTestBase", min_base, max_base,
"alpha_yellow")
base.placeIntoScene(getCenter());
bottich = $GOM.createGameObject("EffectTest");
bottich.addAction(ParaluesAction.new());
bottich.addAction(ResistenzAction.new());
bottich.placeIntoScene();
bottich.setPosition(rel_pos([0.0, height, 0.0]));
$paralueseffect = Paralues.new(10);
$resistenzeffect = ResistentGegenKrankheiten.new();
$SCRIPT.log("EffectTest initialisiert.");
end
end
| true
|
4c65b2cd901b97f3ee92ac4c5164f2623b4e390b
|
Ruby
|
MadBomber/experiments
|
/openai/swagger.rb
|
UTF-8
| 1,575
| 3.265625
| 3
|
[] |
no_license
|
#!/usr/bin/env ruby
require 'boxcars' # Boxcars is a gem that enables you to create new systems with AI composability. Inspired by python langchain.
require 'amazing_print' # Pretty print Ruby objects with proper indentation and colors
require 'tty-progressbar' # A flexible and extensible progress bar for terminal applications.
# Use the Swagger Pet Store server as an example
swagger_url = "https://petstore.swagger.io/v2/swagger.json"
sbox = Boxcars::Swagger.new(swagger_url: swagger_url, context: "API_token: secret-key")
my_pet = "40010473" # FIXME: (outdated) example id for below
prompts = []
prompts << "List the APIs for Pets?"
prompts << "Using the find by status api, how many pets are available?"
prompts << "What is the current store inventory?"
# FIXME: The my_pet ID is outdated so these prompts
# result in a 404 not found http error
#
# prompts << "I was watching pet with id #{my_pet}. Has she sold?"
# prompts << "I was watching pet with id #{my_pet}. What was her name again?"
# Working with a rate limited API
# requests per minute (rpm)
rpm = 3
seconds = (60 / rpm).to_i + 5 # 5 is a fudge factor
prompts.each_with_index do |prompt, inx|
puts
if inx > 0
bar = TTY::ProgressBar.new("waiting to start next request [:bar]", total: seconds)
seconds.times do
sleep(1)
bar.advance # by default increases by 1
end
end
puts
puts "="*prompt.length
puts prompt
puts
result = sbox.run prompt
puts
puts "Result Class: #{result.class}"
puts "Result: #{result}"
end
| true
|
c82039c7ca615c5a5d045473ba5606e1a42b4f4c
|
Ruby
|
Jccrespi/jakebot
|
/jakebot.rb
|
UTF-8
| 4,740
| 2.578125
| 3
|
[] |
no_license
|
require 'cinch'
require 'twitter'
require 'yaml'
require './waaai.rb'
bot_dir = File.expand_path "~/.jakebot"
welcome_messages = {}
responses = {}
phrases = {}
channels = ["#bottest"]
VERSION = '0.2.6'
# Create the storage directory if it doesn't exist
Dir.mkdir(bot_dir) unless File.exists?(bot_dir)
if !(File.exists?("#{bot_dir}/keys") and File.exists?("#{bot_dir}/phrases"))
abort "This bot will not work until files 'phrases' and 'keys' are placed in ~/.jakebot"
end
keys = YAML.load(File.read("#{bot_dir}/keys"))
phrases = YAML.load(File.read("#{bot_dir}/phrases"))
# Load the saved welcome messages, if they exist
if File.exists?("#{bot_dir}/welcome")
welcome_messages = YAML.load_file("#{bot_dir}/welcome")
end
if File.exists? "#{bot_dir}/responses"
responses = YAML.load_file("#{bot_dir}/responses")
end
# Load twitter client
tw_client = Twitter::REST::Client.new do |config|
tw_keys = keys['twitter']
config.consumer_key = tw_keys['consumer_key']
config.consumer_secret = tw_keys['consumer_secret']
config.access_token = tw_keys['access_token']
config.access_token_secret = tw_keys['access_token_secret']
end
# Utility methods
def shorten_any_urls! string
r = /https?:\/\/(.+)/
pieces = string.split(' ')
pieces.each do |piece|
if r =~ piece
string[piece] = Waaai.shorten piece
end
end
return string
end
bot = Cinch::Bot.new do
# Configure the bot
configure do |c|
c.server = "irc.phinugamma.org"
c.channels = channels
c.nick = "jakebot"
c.user = "jakebot"
c.realname = "Jake Mk II Electric Boogaloo"
end
# Register handlers
on :message, /^(hello|hi|yo|hey|greetings|howdy|hola|salutations) jakebot/i do |m| #maybe make a new file for this?
m.reply "#{phrases['greetings'].sample} #{m.user.nick}"
end
on :message, /^!tweet (.+)/i do |m, tw|
tweet = tw_client.update tw
m.reply "#{phrases['affirmatives'].sample} It's been tweeted at #{tweet.url}"
end
on :message, /^!welcome (.+)/i do |m, message|
shorten_any_urls! message
welcome_messages[m.user.nick] = message
m.reply "#{phrases['affirmatives'].sample}"
# Save the messages
IO.write("#{bot_dir}/welcome", YAML.dump(welcome_messages))
end
on :message, /^!kill (.+)/i do |m, victim|
m.reply "Killing #{victim}"
sleep 1
m.reply "pew pew pew"
sleep 0.5
m.reply "#{victim} is dead"
end
on :message, /^!suicide/i do |m|
m.channel.kick(m.user.nick, reason = "suicide")
m.reply "#{m.user} has killed himself"
sleep 0.75
m.reply "R.I.P #{m.user.nick}, you will be missed"
end
on :message, /^!retard/i do |m|
m.reply "im retarded"
end
on :message, /^(.+)$/i do |m, message|
# Save the message or update stats w/e
end
on :join do |m|
# Case of bot joining
if m.user == bot.nick
m.reply "HELLO EVERYONE! I AM JAKEBOT v#{VERSION}"
else
m.channel.op(m.user)
if welcome_messages.key? m.user.nick
m.reply welcome_messages[m.user.nick]
else
m.reply phrases['welcomes'].sample
end
end
end
on :message, /^!respond "(.+)" "(.+)"/i do |m, trigger, response|
trigger.downcase!
if !responses.key? trigger
responses[trigger] = []
end
shorten_any_urls! response
responses[trigger].push response
m.reply "#{phrases['affirmatives'].sample}"
IO.write("#{bot_dir}/responses", YAML.dump(responses))
end
on :message, /^jakebot (.+)/i do |m, message|
message.downcase!
if responses.key? message
m.reply responses[message].sample
end
end
on :message, /^!topic ?add (.+)/i do |m, new_topic|
current_topic = m.channel.topic
shorten_any_urls! new_topic
if current_topic.empty?
m.channel.topic = new_topic
else
m.channel.topic = "#{current_topic} | #{new_topic}"
end
end
on :message, /^!topic ?rem(ove)? (.+)/i do |m, garbage, top|
# Remove an items from the topic
reg = Regexp.new(top, true) # Case insensitive regexp
current_topic = m.channel.topic
topic_segments = current_topic.split(" | ")
topic_segments.each do |t|
if reg =~ t
topic_segments.delete(t)
end
end
new_topic = topic_segments.join(" | ")
if new_topic.eql? current_topic
# If the edited topic and new topic are the same, the
# requested item to delete must not have been found
m.reply "That's not in the topic"
else
m.channel.topic = new_topic
end
end
# Start timers
Timer(3 * 59) { # Every ~3 minutes
if rand < 0.01 # 1% chance
channels.each do |chan| Channel(chan).send(phrases['jakeisms'].sample) end
end
}
end
# Start the bot
bot.start
| true
|
797c56629aeb6de1536852df19298c93421eaa4c
|
Ruby
|
JaimeCrz/Ruby_Exercises
|
/methods.rb
|
UTF-8
| 627
| 4.53125
| 5
|
[] |
no_license
|
# Write a program that prints a greeting
loop do
puts ' Hello! can you please write your name?'
answer = gets.chomp
puts "Hello there, General #{answer} "
break
end
# A- It's 2
# B- Will print "x = 2"
# C- Will print joe as string (p () is another version of print/puts)
# D- Will give the value Four to four
# E- it will print nothing but will be in the same line.
#--- Method not printing.
def scream(word)
word = word + "!!!"
return puts "#{word}" #<--------
end
#-- Method priting now!
# What does the error means?
# The not valid argument given in the method calculate_product.
| true
|
601f99534a9c57231ee81dfdf29700e87cfd1ce5
|
Ruby
|
oguzpol/ruby-tutorial
|
/pop_method.rb
|
UTF-8
| 215
| 3.21875
| 3
|
[] |
no_license
|
arr = [1,2,3,4,5,6,7,8,9,10,11,15]
p arr.length
p arr.pop # deleted last item 15
p arr.length
arr.pop # deleted last item 11
p arr
p last_item = arr.pop
p arr
two_items = arr.pop(2) # last two item
p arr
p two_items
| true
|
a4a86c4b14d5008e6490d791ac108ea5ba2d8df0
|
Ruby
|
ver2point0/ruby-way
|
/1.3-oop-in-ruby/methods-and-attributes/methods-attributes.rb
|
UTF-8
| 1,388
| 3.890625
| 4
|
[] |
no_license
|
# methods can take attributes
puts Time.mktime(2014, "Aug", 24, 16, 0)
# method calls may typically be chained or stacked
puts 3.succ.to_s
print /(x.z).*?(x.z).*?/.match("x1z_1a3_x2z_1b3_").to_a[1..3]
puts "\n#{3+2.succ}"
# do-end block
my_array.each do |x|
x.some_action
end
# brace-delimite block
File.open(filename) { |f| f.some_action }
# methods can take a variable number of arguments
receiver.method(arg1, *more_args)
# an asterisk in a list of formal parameters can "collapse" a sequence of actual parameters into an array
def mymethod(a, b, *c)
print a, b
c.each do |x|
print x
end
end
mymethod(1, 2, 3, 4, 5, 6, 7) # a = 1, b = 2, c = [3, 4, 5, 6, 7]
# named parameters simultaneously set default values and allow arguments to be given in any order because they are explicitly labeled
def name_parameter_method(name: "default", options: {})
options.merge!(name: name)
some_action_with(options)
end
# named parameter with default omitted in method definition, named parameter is required
def other_method(name:, age:)
puts "Person #{name} is aged #{age}."
# It's an error to call this method without specifying
# values for name and age.
end
# singletons: defining a method on a per-object basis
str = "Hello, World!"
str2 = "Goodbye!"
def str.spell
self.split(/./).join("-")
end
str.spell # "H-e-l-l-0-,- - -w-o-r-l-d-!"
str2.spell # error!
| true
|
82246b281047b43b04b9e503c9fa6bbaf7be96c9
|
Ruby
|
rrgayhart/RubytheHardWay
|
/ex45/lib/parse.rb
|
UTF-8
| 347
| 3.203125
| 3
|
[] |
no_license
|
module Parse
def prompt
printf "> "
end
def input_with_index(input)
result = []
input.split.each_with_index{|word, index| result << [word, index]}
result
end
def input_to_array(input)
input.split
end
def unrecognized_command
puts "I don't recognize that command. Try again."
return "error"
end
end
| true
|
fad42595aa9dd37e6bdb90baff8883816aa7ea2c
|
Ruby
|
jasoncomes/CyberSecurity.org
|
/plugins/filters/ifelse.rb
|
UTF-8
| 428
| 2.890625
| 3
|
[] |
no_license
|
# IfElse
# If image exists print primary argument otherwise print secondary argument.
# {{ image | iflese:" has-image", "" }}
module IfElse
def iflese(content, if_content = "", else_content = "")
content = content.to_s
if if_content.empty? and else_content.empty?
return
end
return (!content.nil? and !content.empty?) ? if_content : else_content
end
end
Liquid::Template.register_filter(IfElse)
| true
|
91c5e035c79d2f1e1ecd9c8eb066655c0454cab6
|
Ruby
|
alexlag/railschallenge-city-watch
|
/app/models/responder.rb
|
UTF-8
| 1,340
| 2.578125
| 3
|
[] |
no_license
|
class Responder < ActiveRecord::Base
# To avoid STI from :type column
self.inheritance_column = nil
validates :type, presence: true
validates :name, presence: true, uniqueness: true
validates :capacity, presence: true, inclusion: { in: (1..5) }
belongs_to :emergency
delegate :code, to: :emergency, allow_nil: true, prefix: true
scope :to, ->(type) { where(type: type) }
scope :available, -> { where(emergency_id: nil) }
scope :on_duty, -> { where(on_duty: true) }
scope :available_on_duty, -> { available.on_duty }
# @return [Array] Types in the system
def self.types
uniq.pluck(:type)
end
# @return [Fixnum] Sum of capacities in scope
def self.sum_capacity
pluck(:capacity).reduce(0, :+)
end
# Makes array of metrics for given type
#
# @param [String] type one of types in the system
# @return [Array] Numbers of responders according to specs
def self.capacity_info_for(type)
if type
typed = Responder.to(type)
[typed, typed.available, typed.on_duty, typed.available_on_duty].map(&:sum_capacity)
end
end
# Gathers capacity information for each type in system
#
# @return [Hash] Responder information for each type
def self.capacity_info
types.each_with_object({}) do |type, result|
result[type] = capacity_info_for(type)
end
end
end
| true
|
3e246674a9aee85ff48780c62c9336b44f2dd348
|
Ruby
|
thebravoman/software_engineering_2014
|
/class016/Vanya_Santeva_5_B/task3.rb
|
UTF-8
| 1,198
| 2.59375
| 3
|
[] |
no_license
|
require_relative 'task.rb'
class Task3 < Task
def init_contexts
context1_1 = {
:task_number=>"1",
:length=>"5",
:in_what_order => "ASC",
:format=>"csv",
:format_example=>
"file1.rb,9
file2.rb,11
.....
fileN.rb,N",
:expected=>
"never.rb,11
forget.rb,16
32lines.rb,32
sixtyfivelines.rb,96"
}
context1_2 = {
:task_number=>"2",
:length=>"10",
:in_what_order => "ASC",
:format=>"xml",
:format_example=>
"<results>
<file1.rb>N</file1.rb>
<file2.rb>11</file2.rb>
...
</results>",
:expected=>
"<results>
<never.rb>3</never.rb>
<forget.rb>5</forget.rb>
<32lines.rb>15</32lines.rb>
<sixtyfivelines.rb>30</sixtyfivelines.rb>
</results>"
}
context1_3 = {
:task_number=>"3",
:length=>"6",
:in_what_order => "ASC",
:format=>"json",
:format_example=>
"\"file1.rb\":9,\"file2.rb\":11,......",
:expected=>
"\"never.rb\":6,\"forget.rb\":9,\"32lines.rb\":27,\"sixtyfivelines\":54"
}
[context1_1,context1_2,context1_3]
end
def initialize
super 'task3.eruby'
end
end
| true
|
77a7b2832ed55b2e58f891ad341e4e282061a865
|
Ruby
|
gigi-wolff/challenges
|
/luhn.rb
|
UTF-8
| 661
| 3.78125
| 4
|
[] |
no_license
|
require "pry"
class Luhn
def initialize(number=0)
@number = []
number.to_s.each_char { |c| @number << c.to_i }
end
def addends
arr = @number.reverse!
arr.map!.with_index do |x, i|
if i.even?
x
else
(2 * x > 10 ? 2 * x - 9 : 2 * x)
end
end.reverse!
end
def checksum
addends.reduce(:+)
end
def valid?
checksum.modulo(10) == 0
end
def create(number=0)
number = number * 10
@number = []
number.to_s.each_char { |c| @number << c.to_i }
addends
end
end
=begin
num = 738
luhn = Luhn.new(num)
p "create: #{luhn.create(873_956)}"
puts "is valid? #{luhn.valid?}"
=end
| true
|
598c2c4003148fec12dea152124d0587d95f37cc
|
Ruby
|
itsolutionscorp/AutoStyle-Clustering
|
/all_data/exercism_data/src/380.rb
|
UTF-8
| 150
| 2.984375
| 3
|
[] |
no_license
|
def compute(s1, s2)
l = [s1.length, s2.length].min
s1[0..l-1].each_char.zip(s2[0..l-1].each_char).select { |a,b| a != b }.size
end
| true
|
1edbb09cafa6e2e33dd0d047c8abedb972c25c66
|
Ruby
|
derekgr/leds
|
/leds.rb
|
UTF-8
| 1,585
| 2.96875
| 3
|
[] |
no_license
|
class LedStrip
attr_reader :length, :device
# gamma correction + 7-bit color conversion
# https://gist.github.com/3309494
@@gamma = 256.times.map { |i|
0x80 | ((i.to_f/255.0)**2.5 * 127.0 + 0.5).to_i
}
def initialize(device="/dev/spidev0.0",length=32)
@device = device
@length = length
@dev = File.open(device, "w")
clear!
end
# set pixels to off
def clear!
# r,g,b per pixel + 1 latch byte at the end
@bytes = [@@gamma[0],@@gamma[0],@@gamma[0]]*@length + [0]
end
def reset!
clear!
write!
end
# set pixel at i to [r,g,b]
def []=(offset, v)
r,g,b = v
i = offset*3
# byte order to device is g,r,b
@bytes[i] = @@gamma[g]
@bytes[i+1] = @@gamma[r]
@bytes[i+2] = @@gamma[b]
end
# flush the state of pixels in the buffer to the strip
def write!
@dev = File.open(@device, "w") if (@dev.nil? || @dev.closed?)
@dev.write @bytes.pack("c*")
@dev.flush
end
def close
@dev.close
end
# silly demo, techno party
def chaser(interval=0.03)
i = 0
step = 1
glow = 0
glow_step = 1
while true do
while i >= 0 && i < 32 do
self.clear!
self[i] = [rand(255-glow),rand(255-glow),rand(255-glow)]
self.write!
i = i + step
sleep(interval)
glow += glow_step*rand(10)
if glow > 230
glow = 230
glow_step = -1
end
if glow < 0
glow = 0
glow_step = 1
end
end
# reverse direction
i = i - step
step *= -1
end
end
end
| true
|
4f53bf94b2f5854cef77e7bae44d23b118fdea1a
|
Ruby
|
ElaErl/Fundations
|
/exerc/easy8/10.rb
|
UTF-8
| 259
| 3.3125
| 3
|
[] |
no_license
|
def center_of(string)
string.length.odd? ? string[(string.length)/2] : string[string.length/2 - 1, 2]
end
center_of('I love ruby') == 'e'
center_of('Launch School') == ' '
center_of('Launch') == 'un'
center_of('Launchschool') == 'hs'
center_of('x') == 'x'
| true
|
0b9095ed8dc9194a87223cba2cb452a248b9348f
|
Ruby
|
itsolutionscorp/AutoStyle-Clustering
|
/all_data/exercism_data/ruby/leap/2cb73c60aea64a799f3bf2479d12dab1.rb
|
UTF-8
| 420
| 3.703125
| 4
|
[] |
no_license
|
class Year
class << self
def leap?(year)
@year = year
check_leap_year?
end
def check_leap_year?
divisible_by?(4) && !divisible_by?(100) || leap_century?
end
def divisible_by?(num)
boolean_result( @year % num )
end
def leap_century?
divisible_by?(100) && divisible_by?(400)
end
def boolean_result(result)
result == 0
end
end
end
| true
|
b8dadf86ff4ae4a138d7f04570545bcc1f4deab5
|
Ruby
|
robbytobby/timit
|
/app/models/calendar.rb
|
UTF-8
| 2,544
| 2.921875
| 3
|
[] |
no_license
|
class Calendar
attr_accessor :bookings
attr_accessor :days
attr_accessor :machines
attr_accessor :machine_offset
private :machines=, :days=, :bookings=, :machine_offset=
def initialize(starts = nil, ends = nil, machine_ids = [], machine_offset = 0)
starts ||= Date.today
ends ||= (starts.to_date + 4.weeks)
self.machine_offset = machine_offset.to_i ||= 0
self.bookings = Booking.where("starts_at <= :ends and ends_at >= :starts",
:ends => ends.to_datetime,
:starts => starts.to_datetime).order(:starts_at)
self.days = starts.to_date...ends.to_date
self.machines = machine_ids.any? ? Machine.order(:name).find(machine_ids) : Machine.order(:name)
end
def entries_for(machine_id, date)
bookings.collect{|b| b if b.machine_id == machine_id && b.includes?(date)}.compact
end
def draw_new_booking_first?(machine_id, date)
first = entries_for(machine_id, date).first
return false if first && (first.all_day? || !first.starts_at?(date) || !first.book_before_ok?)
return true
end
def draw_new_booking_after?(booking, date)
return true if booking.ends_at?(date) && booking.book_after_ok?
return false
end
def draw_new_booking_after_mulitday?(booking, date)
return false if draw_booking?(booking,date)
return true if booking.multiday? && !booking.all_day? && booking.ends_at?(date) && booking.book_after_ok?
return false
end
def draw_booking?(booking, date)
booking.starts_at?(date) || date == days.first
end
def number_of_entries(machine_id, date)
n = 0
n += 1 if draw_new_booking_first?(machine_id, date)
entries_for(machine_id, date).each{ |b| n += draw_new_booking_after?(b, date) ? 2 : 1 }
n
end
def max_entries(date)
machines.collect{|m| number_of_entries(m.id, date)}.max
end
def next
days.last
end
def prev
days.first - 4.weeks
end
def not_available_options(machine, day, opts = {})
not_available = {}
starts = ( opts[:after].try(:ends_at) || day.beginning_of_day )
ends = ( opts[:before].try(:starts_at) || Booking.next(machine.id, starts, day.end_of_day).try(:starts_at) || day.end_of_day )
machine.options.each do |opt|
conflicts = opt.available?(starts...ends, return_conflicts = true)
not_available[opt.name] = conflicts if conflicts.any?
not_available[opt.name] = :whole_time if conflicts.any?{|c| c.cover?(starts) && c.cover?(ends - 1.minute)}
end
not_available
end
end
| true
|
29a46eab7cb8e688375c64db08ba3cacaba185b4
|
Ruby
|
mattfaircloth/public-porta-potty
|
/app/models/bathroom.rb
|
UTF-8
| 1,055
| 2.734375
| 3
|
[] |
no_license
|
class Bathroom < ApplicationRecord
has_many :bathroom_locations
has_many :locations, through: :bathroom_locations
has_many :comments
has_many :users, through: :comments
accepts_nested_attributes_for :locations
def cleanest_bathroom
hash = {}
Bathroom.all.map do |bathroom|
hash[bathroom.name] = bathroom.cleanliness
end
a=hash.sort_by {|_key, value| value}.last
"#{a[0]} with a rating of #{a[1]}!"
end
def dirtiest_bathroom
hash = {}
Bathroom.all.map do |bathroom|
hash[bathroom.name] = bathroom.cleanliness
end
a=hash.sort_by {|_key, value| value}.first
"#{a[0]} with a rating of #{a[1]}!"
end
def most_comments
#Look through all of the bathrooms
#Count the number of comments for each bathroom
#Which bathroom has the most comments
hash = {}
Bathroom.all.map do |bathroom|
hash[bathroom.name] = bathroom.comments.count
end
a=hash.sort_by {|_key, value| value}.last
"#{a[0]} has the most comments with #{a[1]}!"
end
end
| true
|
b24b138dbc7071ea2e4af1db87e36967bc1c1844
|
Ruby
|
PritpalSS/Ruby-Projects
|
/Inheritance/operatorOverloading.rb
|
UTF-8
| 2,370
| 4.53125
| 5
|
[] |
no_license
|
# Operator Overloading
class Animal
attr_accessor:name,:trait
def initialize(name, trait)
@name = name
@trait = trait
end
#Operator overloading
def + (other_object)
return Animal.new("#{self.name}#{other_object.name}", "#{self.trait}#{other_object.trait}") # we can access object a by using self keyword
end
end
class Zebra < Animal
end
a = Zebra.new("shreks", "fun")
b = Zebra.new("smart", "youtube")
#puts (a + b).inspect #This is operator overloading, invokes the method def + (other_object). Operator overloading allow us to add two user defined data types like objects
# Operator overloading part 2
# "<", ">", "=" Comparable operators
class MyClass
include Comparable # include statements are used to include Ruby files, here we include Comparable module which is pre-defined module
attr_accessor:myname
def initialize(name)
@myname = name
end
def <=>(other)
self.myname<=>other.myname
end
end
#puts "Shreks"<=>"Singh" #When <=> is encountered then def <=> method is called, and we are comparing the two values in that method
#puts 100 <=> 20
obj = MyClass.new("Apple")
obj2 = MyClass.new("Banana")
#puts obj > obj2
#puts obj < obj2
#puts obj == obj2
#puts obj != obj2
# Operator overloading part 3
# "+", "-", "*", "/", "%", "**" operators
class Tester
attr_accessor:num
def initialize(num)
@num = num
end
def +(other)
return self.num + other.num
end
def *(other)
return self.num * other.num
end
def /(other)
return self.num / other.num
end
def %(other)
return self.num % other.num
end
def **(other)
return self.num ** other.num
end
end
a = Tester.new(5)
b = Tester.new(3)
#puts a + b # when this statement is executed then it will call +(other) function, other gets the value of 3, other is acting as fix number or integer value
#puts a * b
#puts a / b
#puts a % b
#puts a ** b # 5^3, ** = ^ (Exponential)
# Operator overloading part 4
# "[]", "[]=", "<<" Operators using Array
class Tester
attr_accessor:arr
def initialize(*arr)
@arr = arr
end
def [] (x)
return @arr[x]
end
def []=(x, value)
@arr[x] = value
end
def <<(x)
@arr << x
end
end
a = Tester.new(0,1,2,3)
puts a[3]
a << 97
puts a[4]
a[5] = 101
puts a[5]
| true
|
0cf54d8deeacee8358f67e83f9fd63783622f823
|
Ruby
|
TenteMarrero/rbnd-survivr-part1
|
/lib/colorizr.rb
|
UTF-8
| 572
| 3.359375
| 3
|
[] |
no_license
|
class String
@colors = {
red: "31",
green: "32",
yellow: "33",
blue: "34",
pink: "35",
light_blue: "94",
white: "97",
light_grey: "37",
black: "30"
}
def self.colors
@colors.map {|color| color[0]}
end
def self.sample_colors
@colors.each do |color|
puts "This is #{color[0].to_s.send(color[0])}"
end
end
def self.create_colors
@colors.each do |color|
self.send(:define_method, "#{color[0]}") do
"\e[#{color[1]}m" + self + "\e[0m"
end
end
end
end
String.create_colors
| true
|
c3dac5002a08bb4960583e0d4db4dc436810549c
|
Ruby
|
gilesdotcodes/battleships_Team_SAZAS
|
/spec/enemy_spec.rb
|
UTF-8
| 825
| 3.015625
| 3
|
[] |
no_license
|
require 'enemy'
describe Enemy do
let(:enemy){Enemy.new}
let(:player){Player.new("Steve")}
it 'should store a score' do
expect(enemy.score).to eq(0)
end
it 'should set up a new grid when created for us to place ships on' do
expect(enemy.actual_grid.grid[3][5]).to eq('~')
end
it 'should set up a new grid when created for us to show the user on' do
expect(enemy.displayed_grid.grid[3][5]).to eq('~')
end
it 'should place all ships onto the grid' do
enemy.get_ships
enemy.enemy_place_ships
expect(enemy.actual_grid.ship_square_count('~')).to eq(85)
end
it 'should shoot a shot randomly' do
enemy.enemy_shoot(player)
expect(player.player_grid.ship_square_count('~')).to eq(99)
end
it 'should receive a shot' do
expect(enemy.received_shot(2, 4)).to change{actual_grid[2][3]}
end
end
| true
|
060cbcbf0039ad91d0255546788c52acc26617e6
|
Ruby
|
Dujota/Ruby-comprehensive-examples-for-students
|
/GUItools/GTK+/checkButton.rb
|
UTF-8
| 758
| 2.921875
| 3
|
[] |
no_license
|
'''
Zetcode Ruby GTK tutorial
This program roggles the title of the window with
the Gtk::CheckButton widget.
'''
require 'gtk3'
class RubyApp < Gtk::Window
def initialize
super
init_ui
end
def init_ui
fixed = Gtk::Fixed.new
add fixed
cb = Gtk::CheckButton.new "Show title"
cb.set_active true
cb.set_can_focus false
cb.signal_connect("clicked") do |w|
on_clicked w
end
fixed.put cb, 50, 50
set_title "Gkt::CheckButton"
signal_connect "destroy" do
Gtk.main_quit
end
set_default_size 300,200
set_window_position :center
show_all
end
def on_clicked sender
if sender.active?
self.set_title "Gtk::CheckButton"
else
self.set_title ""
end
end
end
#Gtk.init
window = RubyApp.new
Gtk.main
| true
|
33020ad4a307c4ae1b57e7f3e1e40ff9f5c5f000
|
Ruby
|
theseanything/smart-answers
|
/lib/smart_answer/calculators/benefit_cap_calculator_configuration.rb
|
UTF-8
| 2,226
| 2.6875
| 3
|
[
"LicenseRef-scancode-proprietary-license",
"MIT"
] |
permissive
|
module SmartAnswer::Calculators
module BenefitCapCalculatorConfiguration
def self.data
@data ||= begin
filepath = Rails.root.join("config/smart_answers/benefit_cap_data.yml")
YAML.load_file(filepath).with_indifferent_access
end
end
module_function
def benefits
data.fetch(:benefits).with_indifferent_access
end
def exempt_benefits
data.fetch(:exempt_benefits)
end
def weekly_benefit_caps(region = :national)
data.fetch(:weekly_benefit_caps)[region].with_indifferent_access
end
def new_housing_benefit_amount(housing_benefit_amount, total_over_cap)
housing_benefit_amount.to_f - total_over_cap.to_f
end
def new_housing_benefit(amount)
amount = sprintf("%.2f", amount)
if amount < "0.5"
amount = sprintf("%.2f", 0.5)
end
amount
end
def weekly_benefit_cap_descriptions(region = :national)
weekly_benefit_caps(region).each_with_object(HashWithIndifferentAccess.new) do |(key, value), weekly_benefit_cap_description|
weekly_benefit_cap_description[key] = value.fetch(:description)
end
end
def weekly_benefit_cap_amount(family_type, region = :national)
weekly_benefit_caps(region).fetch(family_type)[:amount]
end
def exempted_benefits?(exempted_benefits)
ListValidator.new(exempt_benefits.keys).all_valid?(exempted_benefits)
end
def questions
benefits.each_with_object(HashWithIndifferentAccess.new) do |(key, value), benefits_and_questions|
benefits_and_questions[key] = value.fetch(:question)
end
end
def descriptions
benefits.each_with_object(HashWithIndifferentAccess.new) do |(key, value), benefits_and_descriptions|
benefits_and_descriptions[key] = value.fetch(:description)
end
end
def region(postcode)
london?(postcode) ? :london : :national
end
def london?(postcode)
area(postcode).any? do |result|
result["type"] == "EUR" && result["name"] == "London"
end
end
def area(postcode)
response = GdsApi.imminence.areas_for_postcode(postcode)&.to_hash
OpenStruct.new(response).results || []
end
end
end
| true
|
839af77ea89b851afc5aad09823e4f8d3ddcd6d8
|
Ruby
|
hchiam/learning-rubyOnRails
|
/ruby/moreExamples.rb
|
UTF-8
| 807
| 4.15625
| 4
|
[] |
no_license
|
#!/usr/bin/ruby
# see https://www.tutorialspoint.com/ruby/ruby_quick_guide.htm
print "Hello world!\n" # double quote char -> replaces \n with newline character
print 'Hello world!\n' # single quote char -> DOES NOT replace \n with newline
print "\n"
puts '"puts" prints a new line without needing to type "\n"'
hsh = colors = { "red" => 0xf00, "green" => 0x0f0 } # hash or dictionary
hsh.each do |key, value|
print key, " is ", value, "\n"
end
(1..5).each do |n| # use range 1 to 5 inclusive
puts n
end
# $global_variable
# @@class_variable
# @instance_variable
local_variable = 123.4.to_s + ' hi ' + nil.to_s
puts local_variable
if 1==2
puts "1==2 is true"
elsif 1==1
puts "1==1 is true"
else
puts "I won't print (not this time anyways)"
end
puts "one-liner if statement" if 1==1
| true
|
de5ba30a50b7b9ca8ef3dd23c83319de8caf5e84
|
Ruby
|
yuramax/howitzer_stat
|
/lib/data_cacher.rb
|
UTF-8
| 1,369
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
class DataCacher
HASH_EXAMPLE = [
{
feature: {
name: '...',
description: '...',
path_to_file: '...',
line: 1
},
scenarios: [
{
scenario: {name: '...', line: 10},
steps: [
{ text: '...', line: 11, used: 'yes'},
{ text: '...', line: 12, used: 'no'}
]
}
]
}
]
include Singleton
def initialize
@data = {cucumber: {}, rspec: {}}
@data[:cucumber].default = {}
@data[:rspec].default = {}
@data[:cucumber]['testpage'] = HASH_EXAMPLE
end
def page_cached?(page_class, type=:cucumber)
key = normalize_page_class(page_class)
@data[type].key? key
end
def cached_pages(type=:cucumber)
@data[type].keys
end
def set(page_class, stat, type=:cucumber)
key = normalize_page_class(page_class)
@data[type][key] = stat if key
end
def get(page_class, type=:cucumber)
key = normalize_page_class(page_class)
@data[type][key]
end
private
def normalize_page_class(page_class)
page_class = page_class.to_s
if page_class.empty? || page_class.nil?
nil
else
page_class
end
end
end
module API
def self.data_cacher
@dc ||= DataCacher.instance
end
end
| true
|
a60ed39bc6263d12f1ed375410d1a84b94f2051d
|
Ruby
|
michael-emmi/bam-bam-boogieman
|
/spec/parsing_spec.rb
|
UTF-8
| 1,219
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
# typed: false
require 'bpl/parser.tab'
describe Bpl do
# TODO add more parsing tests
it "can parse basic language features" do
adt = BoogieLanguage.new.parse <<~STRING
var $glob: int;
procedure {:some_attr} some_proc(x: int)
requires true;
ensures true;
modifies $glob;
{
if (*) {
$glob := 0;
} else {
$glob := 1;
}
return;
}
STRING
expect(adt).not_to be nil
expect(adt.any? do |decl|
decl.is_a?(VariableDeclaration) &&
decl.type == Type::Integer &&
decl.names.length == 1 &&
decl.names.any? {|id| id == "$glob"}
end).to be true
expect(adt.any? do |decl|
decl.is_a?(ProcedureDeclaration) &&
decl.names.any? {|id| id == "some_proc"} &&
decl.any? {|a| a.is_a?(Attribute)} &&
decl.any? {|s| s.is_a?(RequiresClause)} &&
decl.any? {|s| s.is_a?(EnsuresClause)} &&
decl.any? {|s| s.is_a?(ModifiesClause)}
end).to be true
expect(adt.any? do |stmt|
stmt.is_a?(IfStatement) &&
stmt.any? {|e| e == Expression::Wildcard} &&
stmt.any? {|s| s.is_a?(AssignStatement)} &&
stmt.else
end).to be true
end
end
| true
|
49b4ddd41d38b82beaa09d3a78f5bca486c1e30b
|
Ruby
|
rkoko/ruby-intro-to-arrays-lab-prework
|
/lib/intro_to_arrays.rb
|
UTF-8
| 515
| 3.671875
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def instantiate_new_array
array = Array.new
return array
end
def array_with_two_elements
["item1", "item2"]
end
def first_element(array)
return array[0]
#also array.first
end
def third_element(array)
return array[2]
end
def last_element(array)
return array[-1]
#also array.last
end
def first_element_with_array_methods(array)
return array.first
end
def last_element_with_array_methods(array)
return array.last
end
def length_of_array(array)
return array.count
end
| true
|
f9938c33c872457b45e91d1d3af49a6c5f0f568d
|
Ruby
|
tomoasleep/vhdl_parser
|
/lib/vhdl_parser/extractor.rb
|
UTF-8
| 1,444
| 3.078125
| 3
|
[] |
no_license
|
module VHDL_Parser
# Helper class with methods that extract a portion of interest from
# a given String.
class Extractor
def self.extract_name(string)
names = string.split(":").map! { |e| e.strip}
names[0].split(/\s*,\s*/)
end
def self.extract_direction(string)
res = string.match(/:\s*(in|out|inout)/)
if res[1]
return res[1]
end
""
end
def self.extract_type(string)
res = string.match(/:\s*(?:in|out|inout)?\s+(\w+)/i)
if res[1]
return res[1]
end
""
end
def self.extract_size(string)
res = string.match(/\((.*?)\s+(downto|to)\s+(.+?)\)/i)
if res
return res
end
""
end
def self.extract_range(string)
res = string.match(/range\s+(.*?)\s+(downto|to)\s+([-a-z0-9_]*)/i)
if res
return res
end
""
end
def self.extract_comment(string)
res = string.match(/--(.*)$/)
if res && res[0]
return res[0]
end
""
end
def self.extract_package_constants(string)
body = string.match(/package\s+(.*)\s+is\s+(.*)\s*end\s*\1;/im)
name = body[1]
constants = body[2]
constants.scan /constant\s+(\w+)\s*:\s*(\w+)\s*:=\s*(.*);/i
end
def self.extract_value(string)
res = string.match /:=\s*([xo"0-9a-z_]*)/i
if res && res[1]
return res[1]
end
""
end
end
end
| true
|
7dc308dedc77d2624bdb8cf91bdd50c1ac451c68
|
Ruby
|
SlamDunc34/day2homework
|
/ruby_functions_practice.rb
|
UTF-8
| 939
| 3.59375
| 4
|
[] |
no_license
|
def return_10
return 10
end
def add(num1, num2)
return num1 + num2
end
def subtract(num1, num2)
return num1 - num2
end
def multiply(num1, num2)
return num1 * num2
end
def divide(num1, num2)
return num1 / num2
end
def length_of_string(test_string)
return test_string.length
end
def join_string(string_1, string_2)
return string_1 + string_2
end
def add_string_as_number(string_1,string_2)
return string_1.to_i+string_2.to_i
end
def number_to_full_month_name(month)
case month
when 1
return "January"
when 3
return "March"
when 9
return "September"
end
end
def number_to_short_month_name(month)
case month
when 1
return "Jan"
when 3
return "Mar"
when 9
return "Sep"
end
end
def volume_of_cube(side)
return side**3
end
def volume_of_sphere(radius)
return (4/3.to_f*Math::PI*(radius**3)).round(1)
end
def fahrenheit_to_celsius(value)
return ((value - 32)*5)/9
end
| true
|
1f29ab6dae9619d7d473e95b2eaaf7ba61da2ef2
|
Ruby
|
eel87/sep-assignments
|
/01-data-structures/06-trees/binary_tree/binary_search_tree.rb
|
UTF-8
| 2,412
| 3.515625
| 4
|
[] |
no_license
|
require_relative 'node'
class BinarySearchTree
def initialize(root)
@root = root
end
def insert(root, node)
if root.rating < node.rating && !root.right
root.right = node
elsif root.rating < node.rating && root.right
insert(root.right, node)
elsif root.rating > node.rating && !root.left
root.left = node
elsif root.rating > node.rating && root.left
insert(root.left, node)
end
end
# Recursive Depth First Search
def find(root, data)
return nil if !root || data === nil
return root if root.title === data
if root.left && root.left.title === data
return root.left
elsif root.right && root.right.title === data
return root.right
elsif find(root.left, data)
return find(root.left, data)
elsif find(root.right, data)
return find(root.right, data)
end
end
def delete(root, data)
return nil if !root || data === nil
if root.title === data
root = root.right
else
node = find(root, data)
node.title = nil
end
end
def printf(children=nil)
return nil if @root.nil?
queue = Queue.new
queue.enq(@root)
while !queue.empty?
value = queue.deq
puts "#{value.title}: #{value.rating}" if !value.title.nil?
# keep moving the levels in tree by pushing left and right nodes of tree in queue
queue.enq(value.left) if value.left
queue.enq(value.right) if value.right
end
end
end
# root = Node.new("The Matrix", 87)
# tree = BinarySearchTree.new(root)
# braveheart = Node.new("Braveheart", 78)
# jedi = Node.new("Star Wars: Return of the Jedi", 80)
# donnie = Node.new("Donnie Darko", 19)
# inception = Node.new("Inception", 86)
# district = Node.new("District 9", 90)
# shawshank = Node.new("The Shawshank Redemption", 91)
# martian = Node.new("The Martian", 92)
# hope = Node.new("Star Wars: A New Hope", 93)
# empire = Node.new("Star Wars: The Empire Strikes Back", 94)
# mad_max_2 = Node.new("Mad Max 2: The Road Warrior", 98)
# pacific_rim = Node.new("Pacific Rim", 72)
# tree.insert(root, hope)
# tree.insert(root, empire)
# tree.insert(root, jedi)
# tree.insert(root, martian)
# tree.insert(root, pacific_rim)
# tree.insert(root, inception)
# tree.insert(root, braveheart)
# tree.insert(root, shawshank)
# tree.insert(root, district)
# tree.insert(root, mad_max_2)
# tree.insert(root, donnie)
# tree.printf
| true
|
d1d4f08cc99848c58e1324b5a603480f34c4c16b
|
Ruby
|
tomdotorg/advent2017
|
/2016/day2.rb
|
UTF-8
| 907
| 3.71875
| 4
|
[] |
no_license
|
SIDE = 3 # how big is the matrix on one side
# up: - width unless <= width
def up(side, num)
return num <= side ? num : num - side
end
# down: + width unless > width ** 2 - width
def down(side, num)
return num > (side ** 2)-side ? num : num + side
end
# left -1 unless % width == 1
def left(side, num)
return num % side == 1 ? num : num - 1
end
# right: +1 unless % width == 0
def right(side, num)
return num % side == 0 ? num : num + 1
end
def move(num, dir)
case dir
when 'U'
return up(SIDE, num)
when 'D'
return down(SIDE, num)
when 'L'
return left(SIDE, num)
when 'R'
return right(SIDE, num)
end
end
def unlock(loc, code)
code.split("").each {|c|
loc = move(loc, c)
}
return loc
end
loc = 5 # starting location
print (loc = unlock(loc, "ULL"))
print (loc = unlock(loc, "RRDDD"))
print (loc = unlock(loc, "LURDL"))
puts (loc = unlock(loc, "UUUUD"))
| true
|
26c4dc5a0d5bfa53ec1390b2672af96b1fd1415a
|
Ruby
|
TIY-ATL-ROR-2015-Jan/lectures
|
/01-05/fancy_fizzbuzz.rb
|
UTF-8
| 257
| 3.78125
| 4
|
[] |
no_license
|
def fizz_buzz (n)
(1..n).each do |i|
x = ''
x += 'Fizz' if i % 3 == 0
x += 'Buzz' if i % 5 == 0
puts(x.empty? ? i : x)
end
end
puts "got arguments: #{ARGV}"
puts "calling fizzbuzz with #{ARGV[0]}"
limit = ARGV[0].to_i
fizz_buzz(limit)
| true
|
dda1a7bf37b648d68a5605f2f5ed41068b400874
|
Ruby
|
felixonmars/cixl
|
/perf/bench8.rb
|
UTF-8
| 188
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
n = 100000
c = Fiber.new {(0..n).each {|i| Fiber.yield(i)}}
t1 = Time.now
(0..n).each {|i| raise 'fail' unless c.resume == i}
t2 = Time.now
delta = (t2 - t1) * 1000
puts "#{delta.to_i}"
| true
|
b151ed4e74e3015a2a0f8c6e0e6def2ec93768d6
|
Ruby
|
no1fushi/procon
|
/2015/look_ch.rb
|
UTF-8
| 8,250
| 2.953125
| 3
|
[] |
no_license
|
# -*- coding: utf-8 -*-
=begin
仕様-
2014の
・敵にブロックfを置く #char
・ブロックを避ける(方向ランダム) #block
・アイテムを取りに行く(ランダム) # item
・アイテム,キャラ斜め判断,(横優先,ランダム) #item,char slanting
・go初期ランダム
・ループを避ける=ランダム
・ターンカウント
・敵保存 #char save
・敵次ターンよける #char flee
・変数出力 #debug 形debug_var(name,var)
・look #look
・looksave
・look敵奥対策 #lookchar
=end
require 'CHaserConnect.rb' # CHaserConnect.rbを読み込む Windows
require 'date'
require 'fileutils'
# サーバに接続
target = CHaserConnect.new("ktch") # この名前を4文字までで変更する
values = Array.new(10) # 書き換えない
#debug
def debug_var(name,var)
$day = Time.now
$output_file = File.open("../../CHaser2012Server/tmp/log/var_output.log","w")
$output_file.write("#{$day} #{name} #{var} \n")
print("#{name} #{var}\n")
end
#variable set
char = Array.new(4, false)
ulook = Array.new(9)
llook = Array.new(9)
rlook = Array.new(9)
dlook = Array.new(9)
go = rand(4)
mode = 0
rand = nil
tarn = 0
ifct = 0
ct = 0
loop do
#----- ここから -----
values = target.getReady
if values[0] == 0
break
end
#loop variable
ifct = tarn
ifct += 1
#look char
if ulook[0] == 1 #up
go = 0
elsif ulook[1] == 1
target.lookUp
tarn += 1
elsif ulook[2] == 1
go = 0
end
if llook[0] == 1 #left
go = 1
elsif llook[3] == 1
target.lookLeft
tarn += 1
elsif llook[6] == 1
go = 1
end
if rlook[2] == 1 #right
go = 3
elsif rlook[5] == 1
target.lookRight
tarn += 1
elsif rlook[8] == 1
go = 3
end
if dlook[6] == 1 #down
go = 2
elsif dlook[7] == 1
target.lookDown
tarn += 1
elsif dlook[8] == 1
go = 2
end
#char save
if values[1] == 1
char[0] = true
tarn = ct
else
char[0] = false
end
if values[3] == 1
char[1] = true
tarn = ct
else
char[1] = false
end
if values[7] == 1
char[2] = true
tarn = ct
else
char[2] = false
end
if values[9] == 1
char[3] = true
tarn = ct
else
char[3] = false
end
#char flee
if ct == ifct
if char[0] == false
rand = rand(2)
if rand == 0
go = 3
if values[6] == 2
go = 2
end
else
go = 2
if values[8] == 2
go = 3
end
end
elsif char[1] == false
rand = rand(2)
if rand == 0
go = 1
if values[4] == 2
go = 2
end
else
go = 2
if values[8] == 2
go = 1
end
end
elsif char[2] == false
rand = rand(2)
if rand == 0
go = 0
if values[2] == 2
go = 3
end
else
go = 3
if values[6] == 2
go = 0
end
end
elsif char[3] == false
rand = rand(2)
if rand == 0
go = 0
if values[2] == 2
go = 1
end
else
go = 1
if values[4] == 2
go = 0
end
end
end
end
#char slanting
if values[1] == 1
rand = rand(2)
if rand == 0
go = 3
if values[6] == 2
go = 2
end
else
go = 2
if values[8] == 2
go = 3
end
end
elsif values[3] == 1
rand = rand(2)
if rand == 0
go = 1
if values[4] == 2
go = 2
end
else
go = 2
if values[8] == 2
go = 1
end
end
elsif values[7] == 1
rand = rand(2)
if rand == 0
go = 0
if values[2] == 2
go = 3
end
else
go = 3
if values[6] == 2
go = 0
end
end
elsif values[9] == 1
rand = rand(2)
if rand == 0
go = 0
if values[2] == 2
go = 1
end
else
go = 1
if values[4] == 2
go = 0
end
end
end
#item slanting
if values[1] == 3
rand = rand(2)
if rand == 0
go = 0
if values[2] == 2
go = 1
end
else
go = 1
if values[4] == 2
go = 0
end
end
elsif values[3] == 3
rand = rand(2)
if rand == 0
go = 0
if values[2] == 2
go = 3
end
else
go = 3
if values[6] == 2
go = 0
end
end
elsif values[7] == 3
rand = rand(2)
if rand == 0
go = 1
if values[4] == 2
go = 2
end
else
go = 2
if values[8] == 2
go = 1
end
end
elsif values[9] == 3
rand = rand(2)
if rand == 0
go = 3
if values[6] == 2
go = 2
end
else
go = 2
if values[8] == 2
go = 3
end
end
end
#block
if go == 0 #Uo
if values[2] == 2
rand = rand(2)
if rand(2) == 0
go = 1
if values[4] == 2
go = 3
if values[6] == 2
go = 2
end
end
else
go = 3
if values[6] == 2
go = 1
if values[4] == 2
go = 2
end
end
end
end
end
if go == 1 #Left
if values[4] == 2
rand = rand(2)
if rand(2) == 0
go = 0
if values[2] ==2
go = 2
if values[8] ==2
go = 3
end
end
else
go = 2
if values[8]
go = 0
if values[2] == 2
go = 3
end
end
end
end
end
if go == 2 #down
if values[8] == 2
rand = rand(2)
if rand(2) == 0
go = 1
if values[4] == 2
go = 3
if values[6] == 2
go = 0
end
end
else
go = 3
if values[6] == 2
go = 1
if values[4] == 2
go = 0
end
end
end
end
end
if go == 3 #right
if values[6] == 2
rand = rand(2)
if rand(2) == 0
go = 0
if values[2] ==2
go = 2
if values[8] ==2
go = 1
end
end
else
go = 2
if values[8]
go = 0
if values[2] == 2
go = 1
end
end
end
end
end
#cher
if values[2] == 1
values = target.putUp
tarn += 1
elsif values[4] == 1
values = target.putLeft
tarn += 1
elsif values[6] == 1
values = target.putRight
tarn += 1
elsif values[8] == 1
values = target.putDown
tarn += 1
end
#item
if values[2] == 3
go = 0
elsif values[4] == 3
go = 1
elsif values[6] == 3
go = 3
elsif values[8] == 3
go = 2
end
if mode == 0
#look
case go
when 0
target.lookUp
ulook[0] = values[1]
ulook[1] = values[2]
ulook[2] = values[3]
ulook[3] = values[4]
ulook[4] = values[5]
ulook[5] = values[6]
ulook[6] = values[7]
ulook[7] = values[8]
ulook[8] = values[9]
tarn += 1
mode = 1
when 1
target.lookLeft
llook[0] = values[1]
llook[1] = values[2]
llook[2] = values[3]
llook[3] = values[4]
llook[4] = values[5]
llook[5] = values[6]
llook[6] = values[7]
llook[7] = values[8]
llook[8] = values[9]
tarn += 1
mode = 1
when 2
target.lookDown
dlook[0] = values[1]
dlook[1] = values[2]
dlook[2] = values[3]
dlook[3] = values[4]
dlook[4] = values[5]
dlook[5] = values[6]
dlook[6] = values[7]
dlook[7] = values[8]
dlook[8] = values[9]
tarn += 1
mode = 1
when 3
target.lookRight
rlook[0] = values[1]
rlook[1] = values[2]
rlook[2] = values[3]
rlook[3] = values[4]
rlook[4] = values[5]
rlook[5] = values[6]
rlook[6] = values[7]
rlook[7] = values[8]
rlook[8] = values[9]
tarn += 1
mode = 1
end
elsif mode == 1
#go
case go
when 0
target.walkUp
tarn += 1
mode = 0
when 1
target.walkLeft
tarn += 1
mode = 0
when 2
target.walkDown
tarn += 1
mode = 0
when 3
target.walkRight
tarn += 1
mode = 0
end
end
if values[0] == 0
break
end
#----- ここまで -----
end
target.close
| true
|
e5ed60290ba4b50de56082783245cb03c6523954
|
Ruby
|
MariaAstakhova/minimax_test
|
/minimax_test/lib/minimax.rb
|
UTF-8
| 1,407
| 3.546875
| 4
|
[] |
no_license
|
class Minimax
attr_accessor :player
WINNING_SETS = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]
].freeze
@player = false
def initialize(board)
@board = board
end
def execute(hash)
puts "running new test"
{score: calculate_score(@board), position: generate_position(@board)}
end
def calculate_score(any_board)
WINNING_SETS.each do |combination|
return -1 if any_board.values_at(*combination).all?('X')
return 1 if any_board.values_at(*combination).all?('O')
end
0
end
def get_empty_spaces(any_board)
any_board.each_index.select{|i| any_board[i] == ''}
end
def generate_position(any_board)
spaces = get_empty_spaces(any_board)
spaces.each do |space|
temp_board = any_board.dup
mark = @player ? 'X' : 'O'
temp_board[space] = mark
output = temp_board
print output
puts ""
if (calculate_score(temp_board) == 1 && !@player) ||
(calculate_score(temp_board) == -1 && @player)
return space
end
@player = !@player
generate_position(temp_board)
end
spaces[0]
end
end
| true
|
67ba27c65abab31eeb45efb6cb746d6e9af1bc48
|
Ruby
|
eserna27/soccer_app
|
/app/application/weeks/week.rb
|
UTF-8
| 1,616
| 2.734375
| 3
|
[] |
no_license
|
require 'active_model'
module Weeks
class Week
include ActiveModel::Model
attr_reader :season, :week_number, :season_name, :season_id, :id, :matches
def initialize(params)
@id = params[:id]
@season = params[:season]
@week_number = params[:week_number]
@season_name = params[:season_name]
@season_id = params[:season_id]
@matches = params[:matches]
end
def self.new_for_form(season_store, team_store)
season = current_season(season_store, team_store)
new({
season_id: season.id,
season_name: season.name,
week_number: ""
})
end
def self.new_from_store(week, store_team)
new({
id: week.id,
week_number: week.week_number,
season_id: week.season.id,
season_name: week.season.name,
matches: converts_in_match(week.matches, store_team)
})
end
def self.show_week_page(week_id, week_store, store_team)
week = new_from_store(find_week(week_id, week_store), store_team)
end
def new_match
Matches.new_for_form(self)
end
def params
{
season_id: season.to_i,
week_number: week_number
}
end
private
def self.current_season(season_store, team_store)
Seasons::Season.current_season(season_store, team_store)
end
def self.find_week(week_id, week_store)
week_store.find_week(week_id)
end
def self.converts_in_match(matches, store_team)
matches.map do |match|
Matches::Match.new_match_from_store(match, store_team)
end
end
end
end
| true
|
b7c390688f00b9eab6549b2a5355e66ba795d932
|
Ruby
|
Dutchmile/ruby-instance-variables-lab-onl01-seng-pt-061520
|
/lib/dog.rb
|
UTF-8
| 157
| 3.15625
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
class Dog
def name=(dog_name)
@this_dogs_name = dog_name
end
def name
@this_dogs_name
end
end
lassie = Dog.new
lassie.name= "Lassie"
lassie.name
| true
|
2703a2db1c98dca8427d194efad226bb39e7c506
|
Ruby
|
uemura-15/memoApp
|
/memo.rb
|
UTF-8
| 1,162
| 3.21875
| 3
|
[] |
no_license
|
require "csv"
#選択肢を出力
while true
puts "1(新規メモ作成),2(メモの編集),3(終了)"
memo_type = gets.chomp
#文字列を取得し、改行をしない
if memo_type == "1"
puts "拡張子を除いたファイル名を入力"
memo_name = gets.chomp
puts "メモ入力の完了後、Ctrl+dを押下してください"
memo = STDIN.read
CSV.open("#{memo_name}.csv", "w") do |test|
test << ["#{memo}"]
end
elsif memo_type == "2"
puts "編集可能なファイルの拡張子を除いたファイル名を入力"
memo_name = gets.chomp
puts "メモ入力の完了後、Ctrl+dを押下してください"
memo = STDIN.read
CSV.open("#{memo_name}.csv", "a") do |test|
test << ["#{memo}"]
end
elsif memo_type == "3"
puts "処理を終了"
exit
else
puts "規定の数字を入力してください"
end
end
| true
|
21de0d3ef79da3b25f0d016574ef5dc88b9c742a
|
Ruby
|
sds/haml-lint
|
/lib/haml_lint/tree/script_node.rb
|
UTF-8
| 730
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
require 'haml_lint/parsed_ruby'
module HamlLint::Tree
# Represents a node which produces output based on Ruby code.
class ScriptNode < Node
# The Ruby script contents parsed into a syntax tree.
#
# @return [ParsedRuby] syntax tree in the form returned by Parser gem
def parsed_script
statement =
if children.empty?
script
else
"#{script}#{@value[:keyword] == 'case' ? ';when 0;end' : ';end'}"
end
HamlLint::ParsedRuby.new(HamlLint::RubyParser.new.parse(statement))
end
# Returns the source for the script following the `-` marker.
#
# @return [String]
def script
@value[:text]
end
end
end
| true
|
f16f540c55e3b56cbb25839b74fcca144548092d
|
Ruby
|
Rohaninfibeam/quintype
|
/BookCab/app/models/assigment.rb
|
UTF-8
| 1,355
| 2.671875
| 3
|
[] |
no_license
|
class Assigment < ApplicationRecord
belongs_to :user
belongs_to :cab
def set_source_location(latitude, longitude)
latitude = latitude.to_f
longitude = longitude.to_f
self.source_lat = latitude
self.source_long = longitude
self.save!
end
def set_dest_location(latitude,longitude)
latitude = latitude.to_f
longitude = longitude.to_f
self.dest_lat = latitude
self.dest_long = longitude
self.save!
end
def get_source_location
[self.source_lat,self.source_long]
end
def get_dest_location
[self.dest_lat,self.dest_long]
end
def start_ride(latitude,longitude)
set_source_location(latitude,longitude)
self.start_time = Time.now
self.save!
end
def end_ride(latitude,longitude)
set_dest_location(latitude,longitude)
self.end_time = Time.now
self.distance = find_distance.present? ? find_distance : nil
self.price = find_total_price.present? ? find_total_price : nil
self.save!
end
def cancel_ride
self.cancelled_time = Time.now
self.save!
end
private
def find_distance
if self.end_time.present?
total_distance(get_dest_location,get_source_location)
else
nil
end
end
def find_total_price
if self.distance.present? && self.start_time.present? && self.end_time.present?
total_time = (self.end_time- self.start_time)/60
total_time*1 + distance*2
else
nil
end
end
end
| true
|
26a9360461eb9d45c1713b5ae5effad593cf4465
|
Ruby
|
mdiasfernandes/ruby
|
/secao_9/setters_and_getters.rb
|
UTF-8
| 1,230
| 4.09375
| 4
|
[] |
no_license
|
#Setters and Getters
##############################GETTERS
class ApiConnector
#Anithing inside here belongs to 'ApiConnector' class
#Attribute Accessors, in terms of JAVA for example, means create a getter and setter method
#The definitions below stands for the attributes (variables) for this class
attr_accessor :title, :description, :url
#method 1
def uncalled_method
puts "Testing class call, but this method won't be called"
end
#method 2
def work_method
puts "Testing class cal, this method will work because will be called"
end
#method 3
def work_math_method(a, b)
c = a + b
puts c
c = a * b
puts c
c = a - b
puts c
c = a / b
puts c
end
end
#The above class doesn't work if won't instantiated, so it's need setters method ...
###############################SETTERS
api = ApiConnector.new
api.url = "http://www.google.com/"
puts api.url
# => http://www.google.com/
#calling work_method
api.work_method
# => Testing class cal, this method will work because will be called
#calling work_math_method passing below argumrnts
api.work_math_method(10,5)
# => 15
# => 50
# => 05
# => 02
| true
|
359252f42402a4dc6f02ac15e54c231ec1200dc5
|
Ruby
|
kachan1208/doubleLinkedList
|
/doubleLinkedList.rb
|
UTF-8
| 1,185
| 3.453125
| 3
|
[] |
no_license
|
load "node.rb"
class List
@firstElement = nil
@lastElement = nil
attr_accessor :lenght
def initialize
@lenght = 0
end
def push(val)
if @lastElement.nil?
buff = Node.new(val)
@firstElement = buff
@lastElement = buff
else
buff = Node.new(val)
buff.id = @lastElement.id + 1
buff.prev = @lastElement # set prev element for node
@lastElement.next = buff # set next element for current node
@lastElement = buff # update last element
end
@lenght += 1
end
def getVal
result = []
buff = @firstElement
loop do
result << buff.val
buff = buff.next
break if buff.nil?
end
return result
end
def getNode(id)
buff = @firstElement
loop do
break if buff.nil? || buff.id == id
buff = buff.next
end
return buff
end
def removeNode(id)
node = self.getNode(id)
unless node.nil?
unless node == @firstElement
node.prev.next = node.next
end
unless node == @lastElement
node.next.prev = node.prev
end
@lenght -= 1;
end
end
end
#TODO: add update first, last element when remove node
| true
|
241cde51f3f9fc0b181bfba383d1c0e2ad9cd3dc
|
Ruby
|
epicodusSummer2014/train_system
|
/spec/train_spec.rb
|
UTF-8
| 1,721
| 2.875
| 3
|
[] |
no_license
|
require 'spec_helper'
describe 'Station' do
describe 'initialize' do
it 'initializes a new station' do
new_station = Station.new({:name => "151st & Gleason"})
expect(new_station).to be_a Station
end
end
describe 'save' do
it 'saves a station' do
new_station = Station.new({:name => "151st & Gleason"})
new_station.save
expect(Station.all).to eq [new_station]
end
end
describe '.all' do
it 'returns all of the stations' do
new_station = Station.new({:name => "151st & Gleason"})
new_station2 = Station.new({:name => "Fischers Landing"})
new_station.save
new_station2.save
expect(Station.all).to eq [new_station, new_station2]
end
end
describe '==' do
it 'compares two stations for equality' do
new_station = Station.new({:name => "151st & Gleason"})
new_station2 = Station.new({:name => "151st & Gleason"})
new_station.save
new_station2.save
expect(new_station.==(new_station2)).to eq true
end
end
describe '.station_list' do
it 'returns all of the stations on a given line' do
new_station = Station.new({:name => "151st & Gleason"})
new_station2 = Station.new({:name => "Fischers Landing"})
new_station.save
new_station2.save
new_line = Line.new({:name => "Portland Express"})
new_line2 = Line.new({:name => "Vancouver Express"})
new_line.save
new_line2.save
new_station.update_train_lines(new_line.name)
new_station.update_train_lines(new_line2.name)
new_station2.update_train_lines(new_line.name)
expect(Station.station_list("Portland Express")).to eq [new_station, new_station2]
end
end
end
| true
|
23a52bfd472d363692c0c2ba6b2d9d2edc460640
|
Ruby
|
zhanna1825/GithubHomework
|
/Lucy.rb
|
UTF-8
| 213
| 3.90625
| 4
|
[] |
no_license
|
puts "Welcome..."
sleep 2
puts "Let's play a game, what is your name?"
users_name = gets.chomp
puts "One second, calculating..."
sleep 3
puts "Great, #{users_name.chars.shuffle.join} is your new name - Goodbye!"
| true
|
c328c44a6f2814ff2796ac82848a3b691d45d7fc
|
Ruby
|
yamshim/StockPortal
|
/lib/clawler/models/foreign_exchange.rb
|
UTF-8
| 4,198
| 2.703125
| 3
|
[] |
no_license
|
# coding: utf-8
module Clawler
module Models
class ForeignExchange < Clawler::Base
extend AllUtils
# include Clawler::Sources
# Initializeは一番最初にスクリプトとして実行する csv化するか、分割化するかなどはまた後で
# sleepを入れる
# エラーバンドリング
# 強化
# 重複データの保存を避ける
# break, next
def self.patrol
foreign_exchange_patroller = self.new(:foreign_exchange, :patrol)
foreign_exchange_patroller.scrape
foreign_exchange_patroller.import
foreign_exchange_patroller.finish
end
def self.build
foreign_exchange_builder = self.new(:foreign_exchange, :build)
foreign_exchange_builder.build
foreign_exchange_builder.finish
end
def set_latest_object(currency_code)
@latest_object = ::ForeignExchange.where(currency_code: currency_code).try(:pluck, :date).try(:sort).try(:last)
end
def each_scrape(currency_code, page)
foreign_exchange_lines = []
foreign_exchanges_info = Clawler::Sources::Yahoo.get_foreign_exchanges_info(csym(:currency, currency_code), page)
return {type: :break, lines: nil} if foreign_exchanges_info.blank?
foreign_exchanges_info.each do |foreign_exchange_info|
foreign_exchange_line = Clawler::Sources::Yahoo.get_foreign_exchange_line(foreign_exchange_info, currency_code)
if @status == :patrol && @latest_object.present?
return {type: :all, lines: foreign_exchange_lines} if @latest_object >= foreign_exchange_line[1]
end
foreign_exchange_lines << foreign_exchange_line
end
return {type: :part, lines: foreign_exchange_lines}
end
def line_import
@lines.group_by{|random_line| random_line[0]}.each do |currency_code, lines|
::ForeignExchange.transaction do
foreign_exchanges = []
last_date = ::ForeignExchange.where(currency_code: currency_code).try(:pluck, :date).try(:sort).try(:last)
foreign_exchanges_info = []
lines.sort_by{|line| line[1]}.reverse.each do |line|
if last_date.present?
break if last_date >= line[1]
end
foreign_exchange_info = {}
foreign_exchange_info[:date] = line[1]
foreign_exchange_info[:opening_price] = line[2]
foreign_exchange_info[:high_price] = line[3]
foreign_exchange_info[:low_price] = line[4]
foreign_exchange_info[:closing_price] = line[5]
foreign_exchange_info[:currency_code] = currency_code
foreign_exchanges << ::ForeignExchange.new(foreign_exchange_info)
end
foreign_exchanges.each(&:save!)
end
end
true
end
def csv_import
currency_codes = cvals(:currency)
currency_codes.each do |currency_code|
::ForeignExchange.transaction do
foreign_exchanges = []
last_date = ::ForeignExchange.where(currency_code: currency_code).try(:pluck, :date).try(:sort).try(:last)
foreign_exchanges_info = []
csv_text = get_csv_text(currency_code)
lines = CSV.parse(csv_text).sort_by{|line| trim_to_date(line[1])}.reverse.uniq
lines.each do |line|
if last_date.present?
break if last_date >= trim_to_date(line[1])
end
foreign_exchange_info = {}
foreign_exchange_info[:date] = trim_to_date(line[1])
foreign_exchange_info[:opening_price] = line[2].to_f
foreign_exchange_info[:high_price] = line[3].to_f
foreign_exchange_info[:low_price] = line[4].to_f
foreign_exchange_info[:closing_price] = line[5].to_f
foreign_exchange_info[:currency_code] = currency_code
foreign_exchanges << ::ForeignExchange.new(foreign_exchange_info)
end
foreign_exchanges.each(&:save!)
end
end
true
end
end
end
end
| true
|
1efdf32c145bd3fe7c64d3496f3bf41bb353be59
|
Ruby
|
unused/sna-workspace
|
/data-management/import.rb
|
UTF-8
| 708
| 2.78125
| 3
|
[
"MIT"
] |
permissive
|
require './application'
def create_tweet_from(json_line)
unless json_line[0] == '{'
json_line = json_line.split('{').last
create_tweet_from json_line if json_line[0] == '{' # second chance
return
end
tweet = JSON.parse json_line
print (Tweet.new(tweet.to_h).save ? '.' : 'x')
rescue Mongo::Error::OperationFailure => err
puts "[ERR] Failed to save tweet: #{err}"
rescue JSON::ParserError => err
puts "[ERR] Failed to parse line... #{String(err).slice(0, 50)}"
end
def import_file(file)
print "\n[INFO] Import file #{file}..."
File.readlines(file).each { |line| create_tweet_from line }
# File.open(file).each_line { |line| create_tweet_from line }
end
import_file ARGV[-1]
| true
|
3e9fa312c2cc49f216a42cf8e58c67f63b7457e5
|
Ruby
|
ippei94da/vasputils
|
/bin/vaspdir
|
UTF-8
| 7,392
| 2.78125
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
#! /usr/bin/env ruby
# coding: utf-8
# Manipulate VaspDir from command line.
require "vasputils"
require 'thor'
INSPECT_DEFAULT_ITEMS = [ :klass_name, :state, :toten, :dir, ]
INSPECT_ALL_ITEMS = [ :kpoints, :encut, :i_step, :e_step, :time, ] + INSPECT_DEFAULT_ITEMS
# for printf option. minus value indicate left shifted printing.
INSPECT_WIDTH = {
:dir => "-20",
:e_step => "3",
:i_step => "3",
:klass_name => "11",
:kpoints => "8",
:encut => "6",
:state => "10",
:time => "15",
:toten => "17",
}
def show_items(hash, tgt_properties)
items = tgt_properties.map do |item|
val = sprintf("%#{INSPECT_WIDTH[item]}s", hash[item])
val
end
separator = " "
puts items.join(separator)
end
def form_time(second)
second = second.to_i
result = ""
result = sprintf("%02d", second % 60)
minute = second / 60
if 0 < minute
result = sprintf("%02d:#{result}", minute % 60)
end
hour = minute / 60
if 0 < hour
result = sprintf("%02d:#{result}", hour % 24)
end
day = hour / 24
if 0 < day
result = sprintf("%dd #{result}", day)
end
return result
end
### Command template
class VaspdirCommand < Thor
desc 'show [options] [dirs]', "show information"
option "finished" , type: :boolean, desc: "Show about finished dir." #"-f",
option "yet" , type: :boolean, desc: "Show about yet dir." #"-y",
option "terminated" , type: :boolean, desc: "Show about terminated dir." #"-t",
option "started" , type: :boolean, desc: "Show about sarted dir." #"-s",
option "dirs_with_matches" , type: :boolean, desc: "Show dir name only." #"-l",
option "all_items" , type: :boolean, desc: "Show all items." #"-a",
option "state" , type: :boolean, desc: "Show STATE." #"-S",
option "toten" , type: :boolean, desc: "Show TOTEN." #"-e",
option "ionic_steps" , type: :boolean, desc: "Show ionic steps as I_S." #"-i",
option "last_update" , type: :boolean, desc: "Show LAST-UPDATE." #"-L",
option "encut" , type: :boolean, desc: "Show ENCUT." #"-c",
option "kpoints" , type: :boolean, desc: "Show KPOINTS." #"-k",
def show(* args)
tgt_properties = []
show_dir_states = []
show_dir_states << :finished if options[:finished]
show_dir_states << :yet if options[:yet]
show_dir_states << :terminated if options[:terminated]
show_dir_states << :started if options[:started]
tgt_properties << :state if options[:state]
tgt_properties << :toten if options[:toten]
tgt_properties << :ionic_steps if options[:ionic_steps]
tgt_properties << :last_update if options[:last_update]
tgt_properties << :encut if options[:encut]
tgt_properties << :kpoints if options[:kpoints]
dirs = args
dirs = ["."] if args.empty?
if options[:all_items]
tgt_properties = INSPECT_ALL_ITEMS
elsif options[:dirs_with_matches]
tgt_properties = [:dir]
elsif tgt_properties == nil || tgt_properties.empty?
tgt_properties = INSPECT_DEFAULT_ITEMS
else
tgt_properties = tgt_properties.push :dir
end
unless options[:dirs_with_matches]
# show title of items.
results = {
:klass_name => "TYPE",
:kpoints => "KPOINTS",
:encut => "ENCUT",
:state => "STATE",
:toten => "TOTEN",
:i_step => "I_S", #I_S is ionic steps
:e_step => "E_S", #E_S is electronic steps
:time => "LAST_UPDATE_AGO",
:dir => "DIR"
}
show_items(results, tgt_properties)
end
dirs.each do |dir|
next unless File.directory? dir
begin
klass_name = "VaspDir"
calc = VaspUtils::VaspDir.new(dir)
state = calc.state
begin
outcar = calc.outcar
toten = sprintf("%9.6f", outcar[:totens][-1].to_f)
i_step = outcar[:ionic_steps]
e_step = outcar[:electronic_steps]
time = form_time(Time.now - calc.latest_modified_time)
kp = calc.kpoints
if kp.scheme == :automatic
k_str = kp.mesh.join("x")
else
k_str = kp.points.size.to_s
end
encut = calc.incar["ENCUT"]
rescue
toten = i_step = e_step = time = k_str = encut = ""
end
rescue VaspUtils::VaspDir::InitializeError
klass_name = "-------"
end
results = {
:klass_name => klass_name,
:kpoints => k_str,
:encut => encut,
:state => state,
:toten => toten,
:i_step => i_step,
:e_step => e_step,
:time => time,
:dir => dir,
}
if show_dir_states.empty?
show_items(results, tgt_properties)
else
if show_dir_states.include? results[:state]
show_items(results, tgt_properties)
end
end
end
end
desc 'execute [dirs]', "Execute vasp"
def execute(* args)
VaspUtils::VaspDir.execute(args)
end
desc 'qsub [options] [dirs]', "Submit queue to grid engine. Empty 'dirs' in argument indicates current directory.' "
option :q_name, desc: "Queue name for '#$ -q', E.g. 'Pd.q'"
option :pe_name, desc: "Parallel environment name for '#$ -pe'"
option :ppn, desc: "Process per node, 2nd argument for'#$ -pe'"
option :ld_library_path, desc: "Environmental variable 'LD_LIBRARY_PATH'"
option :command, desc: "Command"
option :load_group, desc: "Load setting from group in setting file."
option :no_submit, desc: "Write script, but not submit."
option :auto, type: :boolean, desc: "Select low load group and automatic setting."
def qsub(* args)
new_options = Marshal.load(Marshal.dump(options))
new_options[:command] = "#{__FILE__} execute"
#pp args, new_options
#exit
VaspUtils::VaspDir.qsub(args, new_options)
end
desc 'clean [dirs]', "Clean up output files of VASP"
def clean(* args)
targets = args
targets = [ENV['PWD']] if targets.empty?
targets.each do |target_dir|
puts "Directory: #{target_dir}"
begin
vd = VaspUtils::VaspDir.new(target_dir)
rescue VaspUtils::VaspDir::InitializeError
puts " Do nothing due to not VaspDir."
next
end
vd.reset_clean
end
end
desc 'init [dirs]', "Clean up all files except for POSCAR, POTCAR, KOINTS, INCAR"
def init(* args)
targets = args
targets = [ENV['PWD']] if targets.empty?
targets.each do |target_dir|
puts "Directory: #{target_dir}"
begin
vd = VaspUtils::VaspDir.new(target_dir)
rescue VaspUtils::VaspDir::InitializeError
puts " Do nothing due to not VaspDir."
next
end
vd.reset_initialize
end
end
desc 'nelect', 'count NELECT value from POSCR and POTCAR'
def nelect
poscar = VaspUtils::Poscar.load_file('POSCAR')
potcar = VaspUtils::Potcar.load_file('POTCAR')
#pp poscar.elements
#pp potcar.elements
sum = 0
poscar.nums_elements.size.times do |i|
sum += poscar.nums_elements[i] * (potcar.zvals[i].to_i)
end
puts sum
end
end
VaspdirCommand.start(ARGV)
| true
|
f61e704a6d38a7009598f3bde964bbdd6d311638
|
Ruby
|
lulekalabs/luleka-v1
|
/app/controllers/vouchers_controller_base.rb
|
UTF-8
| 1,935
| 2.5625
| 3
|
[] |
no_license
|
# provides controller helpers for voucher related methods in users, partners and voucher controller
module VouchersControllerBase
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
end
protected
# hash key for voucher session id
def voucher_session_param
:voucher_id
end
def voucher_cookie_auth_token
"#{voucher_session_param}_auth_token".to_sym
end
# Accesses the current voucher from the session.
# Future calls avoid the database because nil is not equal to false.
def current_voucher
@current_voucher ||= load_voucher_from_session || load_voucher_from_cookie unless @current_voucher == false
end
# Store the given voucher in the session.
def current_voucher=(new_voucher)
session[voucher_session_param] = new_voucher ? new_voucher.id : nil
@current_voucher = new_voucher || false
end
def load_voucher_from_session
self.current_voucher = Voucher.find_by_id(session[voucher_session_param]) if session[voucher_session_param]
end
def load_voucher_from_cookie
voucher = cookies[voucher_cookie_auth_token] && Voucher.find_by_uuid(cookies[voucher_cookie_auth_token])
if voucher && !voucher.expired? && !voucher.redeemed?
cookies[voucher_cookie_auth_token] = {:value => voucher.uuid, :expires => voucher.expires_at}
self.current_voucher = voucher
end
end
# returns current voucher only if it is a partner membership voucher
# assigns consignee_confirmation to voucher as current user.person,
# since we need to validate if this person, the potential consignee,
# is the consignee if one exists or the potential consignee must not
# be a partner already.
def current_partner_voucher
if (partner_voucher = current_voucher) && current_voucher.is_a?(PartnerMembershipVoucher)
partner_voucher.consignee_confirmation = @person if @person
partner_voucher
end
end
end
| true
|
ba1aa7380de662cd0365d8969546e4a74ef1f8ab
|
Ruby
|
suchprogramming/budget_app
|
/lib/categories.rb
|
UTF-8
| 1,077
| 2.890625
| 3
|
[] |
no_license
|
class Category
attr_reader(:id, :category_name)
define_method(:initialize) do |attributes|
@id = attributes.fetch(:id)
@category_name = attributes.fetch(:category_name)
end
define_method(:==) do |another_category|
self.id() == another_category.id() && self.category_name() == another_category.category_name()
end
define_singleton_method(:all) do
returned_categories = DB.exec("SELECT * FROM categories;")
categories = []
returned_categories.each() do |category_name|
id = category_name.fetch("id").to_i()
category_name = category_name.fetch("expense_type")
categories.push(Category.new({:id => id, :category_name => category_name}))
end
categories
end
define_method(:save) do
result = DB.exec("INSERT INTO categories (expense_type) VALUES ('#{@category_name}') RETURNING id;")
@id = result.first().fetch("id").to_i()
end
define_singleton_method(:find) do |search_id|
Category.all().each() do |category|
if category.id().==(search_id)
return category
end
end
end
end
| true
|
f26c01c71493f9875ef11a02ff1cb24c51ea9cc8
|
Ruby
|
stephan-nordnes-eriksen/ruby_ship
|
/bin/shipyard/darwin_ruby/lib/ruby/2.3.0/rdoc/token_stream.rb
|
UTF-8
| 2,563
| 3.359375
| 3
|
[
"MIT"
] |
permissive
|
# frozen_string_literal: false
##
# A TokenStream is a list of tokens, gathered during the parse of some entity
# (say a method). Entities populate these streams by being registered with the
# lexer. Any class can collect tokens by including TokenStream. From the
# outside, you use such an object by calling the start_collecting_tokens
# method, followed by calls to add_token and pop_token.
module RDoc::TokenStream
##
# Converts +token_stream+ to HTML wrapping various tokens with
# <tt><span></tt> elements. The following tokens types are wrapped in spans
# with the given class names:
#
# TkCONSTANT :: 'ruby-constant'
# TkKW :: 'ruby-keyword'
# TkIVAR :: 'ruby-ivar'
# TkOp :: 'ruby-operator'
# TkId :: 'ruby-identifier'
# TkNode :: 'ruby-node'
# TkCOMMENT :: 'ruby-comment'
# TkREGEXP :: 'ruby-regexp'
# TkSTRING :: 'ruby-string'
# TkVal :: 'ruby-value'
#
# Other token types are not wrapped in spans.
def self.to_html token_stream
token_stream.map do |t|
next unless t
style = case t
when RDoc::RubyToken::TkCONSTANT then 'ruby-constant'
when RDoc::RubyToken::TkKW then 'ruby-keyword'
when RDoc::RubyToken::TkIVAR then 'ruby-ivar'
when RDoc::RubyToken::TkOp then 'ruby-operator'
when RDoc::RubyToken::TkId then 'ruby-identifier'
when RDoc::RubyToken::TkNode then 'ruby-node'
when RDoc::RubyToken::TkCOMMENT then 'ruby-comment'
when RDoc::RubyToken::TkREGEXP then 'ruby-regexp'
when RDoc::RubyToken::TkSTRING then 'ruby-string'
when RDoc::RubyToken::TkVal then 'ruby-value'
end
text = CGI.escapeHTML t.text
if style then
"<span class=\"#{style}\">#{text}</span>"
else
text
end
end.join
end
##
# Adds +tokens+ to the collected tokens
def add_tokens(*tokens)
tokens.flatten.each { |token| @token_stream << token }
end
alias add_token add_tokens
##
# Starts collecting tokens
def collect_tokens
@token_stream = []
end
alias start_collecting_tokens collect_tokens
##
# Remove the last token from the collected tokens
def pop_token
@token_stream.pop
end
##
# Current token stream
def token_stream
@token_stream
end
##
# Returns a string representation of the token stream
def tokens_to_s
token_stream.compact.map { |token| token.text }.join ''
end
end
| true
|
a43574432e036b4bd32965b607e7a9ff7ec77ff3
|
Ruby
|
boblail/recipes
|
/app/helpers/ingredient_helper.rb
|
UTF-8
| 211
| 2.65625
| 3
|
[] |
no_license
|
module IngredientHelper
def formatted_amount(ingredient)
amount = ingredient.amount
amount = amount.join("-") if amount.respond_to? :join
"#{amount} #{ingredient.unit.to_s.pluralize}"
end
end
| true
|
a53806b3e930219304a23f1831eede9ea918ca18
|
Ruby
|
luisparravicini/photoftheday
|
/download.rb
|
UTF-8
| 640
| 2.5625
| 3
|
[] |
no_license
|
require 'tempfile'
require 'fileutils'
include FileUtils
urls_path = 'photos_urls.txt'
downloads_dir = ARGV.shift || 'wallpapers'
mkdir_p(downloads_dir) unless File.exists?(downloads_dir)
File.open(urls_path) do |io|
io.each_line do |url|
url.strip!.chomp!
dest_path = File.join(downloads_dir, File.basename(url))
next if File.exists?(dest_path)
puts url
tmp = Tempfile.new('wallpaper')
begin
out = `wget -nv "#{url}" -O "#{tmp.path}" 2>&1`
unless $?.success?
puts out
puts '-'*60
else
mv(tmp.path, dest_path)
end
ensure
tmp.unlink
end
end
end
| true
|
1ccf99b8550e807a5ee710ff443957dfe4879368
|
Ruby
|
ericovinicosta/pdti-ruby-respostas-exercicio04
|
/resposta01.rb
|
UTF-8
| 180
| 3.859375
| 4
|
[] |
no_license
|
# Faça um Programa que leia um vetor de 5 números inteiros e mostre-os.
numeros = []
for i in 0...5
print "Entre com o numero #{i}: "
numeros << gets.to_i
end
puts numeros
| true
|
ac9acbb0c3603f0e19b6de37a9ce61fe684c8ad4
|
Ruby
|
emreiser/ga-w1-thursday-quiz
|
/quiz.rb
|
UTF-8
| 197
| 3.40625
| 3
|
[] |
no_license
|
def multiples(multiple, max_num)
multipliers = (1..(max_num.to_i-1)).to_a
result = []
multipliers.map do |num|
result << (multiple.to_i * num)
end
return result
end
puts multiples(3, 6)
| true
|
3408747952f9935faaf0491715221dd06189250d
|
Ruby
|
shinh/test
|
/enum_inspect.rb
|
UTF-8
| 308
| 3.328125
| 3
|
[] |
no_license
|
def make_pure_enumrator(e)
def e.inspect
"#<Enumerator::#{to_a.inspect}>"
end
e
end
class Array
alias orig_each each
def each
make_pure_enumrator(orig_each)
end
end
class Range
alias orig_each each
def each
make_pure_enumrator(orig_each)
end
end
p [1,2,3].each
p (0..3).each
| true
|
26f879435bf11eb79da9bf550f9f39b4280aebe3
|
Ruby
|
paulokuda/dankathon
|
/app/models/user.rb
|
UTF-8
| 661
| 2.609375
| 3
|
[] |
no_license
|
class User < ActiveRecord::Base
has_secure_password
# relationships
has_many :items
# validations
validates :username, presence: true, uniqueness: { case_sensitive: false}
validates_presence_of :password, on: :create
validates_presence_of :password_confirmation, on: :create
validates_confirmation_of :password, message: "does not match"
validates_length_of :password, minimum: 4, message: "must be at least 4 characters long", allow_blank: true
# scopes
scope :alphabetical, -> { order('last_name, first_name') }
def self.authenticate(username, password)
find_by_username(username).try(:authenticate, password)
end
end
| true
|
93d45321a147bc37d1ae677619f16e2265a5178a
|
Ruby
|
afeiship/ruby-programing-book-notes
|
/docs/2018-08/2018-08-06/019-if-modifer.rb
|
UTF-8
| 99
| 3
| 3
|
[] |
no_license
|
a,b = 120,100;
if a > b
puts 'A > B'
end
## 等效于下面的
puts "a 比b 大" if a > b
| true
|
9a11ba123335dbcff2e62f9ed8dfe3fe91000697
|
Ruby
|
tfxl/CA_projects
|
/workbook_T1A1/code_Q11.rb
|
UTF-8
| 1,156
| 3.3125
| 3
|
[] |
no_license
|
class Consumables
attr_reader
attr_writer
attr_accessor
@@consumables_sold = []
def self.number_items_sold
@@consumables_sold.length
end
def self.profit
@@consumables_sold.sell_cost - @@consumables_sold.buy_cost
end
def initialize(buy_cost, sell_cost, size) #size will have default reference sizes of S, M, L
@buy_cost = buy_cost
@sell_cost = sell_cost
@size = size
end
end
class Food < Consumables
def initialize(is_gluten)
super(buy_cost, sell_cost, size)
@description = food_type #this changes from customer order to Burger | Chips | Pizza
@is_gluten = is_gluten
end
end
class Pizza < Food
def initialize(topping_type)
super(is_gluten) # can this get the parent class, or should the burger go directly under consumables
@topping_type = topping_type
end
end
class Drink < Consumables
def initialize()
super(buy_cost, sell_cost, size)
end
end
class Packaging < Consumables
def initialize(description) #this links to an array, or dictionary, with pre-defined terms
super(buy_cost, sell_cost, size)
@description = description
end
end
| true
|
8601511799cf0d797b3a2dbbd1f1542f7f4dc607
|
Ruby
|
rdark/yasst
|
/lib/yasst/provider/openssl.rb
|
UTF-8
| 2,434
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
require 'yasst/primatives/openssl'
module Yasst
class Provider
##
# OpenSSL provider
# ===== Parameters
# - *profile*
# ===== Required Parameters
# - *passphrase*
class OpenSSL < Yasst::Provider
include Yasst::Primatives::OpenSSL
attr_reader :profile
##
# initialize hook for superclass
def post_initialize(**args)
args[:profile].nil? && (@profile = Yasst::Profiles::OpenSSL.new) ||
(@profile = args[:profile])
validate_passphrase(@passphrase)
end
##
# Whether or not a passphrase is required for this provider
def passphrase_required?
true
end
##
# Encrypt a string using a unique salt + key for every encrypt action,
# and then package it up in a usable base64'd string with iv + salt
# prepended
#
# ===== Parameters
# - +string+
# A string to encrypt
# ===== Returns
# - String
def encrypt(string)
e_salt = salt
e_key = key(e_salt)
e_iv, ciphertext = p_encrypt_string(string, e_key, profile.algorithm)
p_pack_string(e_iv, e_salt, ciphertext)
end
##
# De-encode, unpack and decrypt a string
#
# ===== Parameters
# - +string+
# A base64-encoded string to decrypt. Must be in the same format as the
# encrypt method produces
# ===== Returns
def decrypt(string)
d_salt, d_iv, ciphertext = p_unpack_string(
string,
profile.key_len,
profile.iv_len,
profile.salt_bytes
)
p_decrypt_string(ciphertext, key(d_salt), d_iv, profile.algorithm)
end
private
##
# Returns a brand new salt
def salt
p_salt(profile.salt_bytes)
end
##
# Returns a new key for the configured key gen method.
# Called with no parameters, a fresh salt will be used
# ===== Parameters
# - +salt+
# Optional salt value to use when generating the key
def key(salt = nil)
salt.nil? && salt = new_salt
# Profile should raise NotImplementedErrror if unsupported key
# generation method is used
if profile.key_gen_method == :pbkdf2
return p_pbkdf2_key(@passphrase, salt,
profile.pbkdf2_iterations, profile.key_len)
end
end
end
end
end
| true
|
5b551a051e9d6d7a36b4ca940f74b350d95c077f
|
Ruby
|
TimPetricola/dayone-kindle
|
/lib/dayone-kindle/cli.rb
|
UTF-8
| 2,139
| 2.78125
| 3
|
[] |
no_license
|
module DayOneKindle
module CLI
def self.dialog(value)
script = <<-END
tell app "System Events"
display dialog "#{value}"
end tell
END
system('osascript ' + script.split(/\n/).map { |line| "-e '#{line}'" }.join(' ') + '> /dev/null 2>&1')
end
def self.options
return @options if @options
options = {
ask_confirmation: true,
tags: [],
dry_run: false,
archive: true
}
optparse = OptionParser.new do |opts|
opts.banner = 'Usage: dayone-kindle [options]'
opts.on '--dry', 'Outputs highlights instead of importing them (use for testing)' do
options[:dry_run] = true
end
opts.on '-t', '--tags reading,quote', Array, 'Tags to be saved with highlights' do |t|
options[:tags] = t
end
opts.on '--auto-confirm', 'Do not ask for confirmation before import' do
options[:ask_confirmation] = false
end
opts.on '--no-archive', 'Do not archive imported highlights on device' do
options[:archive] = false
end
end
optparse.parse!
@options = options
end
def self.run
tags = options[:tags]
DayOneKindle::Device.find_at('/Volumes').each do |kindle|
next if kindle.highlights.empty?
if options[:ask_confirmation]
label = "#{kindle.name} detected. Highlights will be imported to Day One."
next unless dialog(label)
end
store = DayOneKindle::DataStore.new(kindle.highlights, tags)
puts "#{store.entries.count} highlights to import"
puts "Tags: #{tags.empty? ? 'no tags' : tags.join(', ')}"
if options[:dry_run]
puts 'Dry run, no highlight imported'
else
entries = store.save!
puts "#{entries.count} highlights imported with tags"
if options[:archive]
path = kindle.archive_highlights!
puts "Highlights archived at #{path}"
end
kindle.clear_highlights!
puts 'Highlights cleared from device'
end
end
end
end
end
| true
|
5288cd4f9277a0db6634aa7afa2b51061f17e1c7
|
Ruby
|
kf8a/metadata
|
/app/models/variate.rb
|
UTF-8
| 2,037
| 2.515625
| 3
|
[] |
no_license
|
# frozen_string_literal: true
require 'rexml/document'
# A variate is a variable that is measured or recorded. It represents the
# column in a datatable.
class Variate < ApplicationRecord
include REXML
belongs_to :datatable, touch: true, optional: true
belongs_to :unit, optional: true
scope :valid_for_eml, -> { where("measurement_scale != '' AND description != ''") }
def to_eml(xml = ::Builder::XmlMarkup.new)
@eml = xml
@eml.attribute do
@eml.attributeName name
@eml.attributeDefinition description
eml_measurement_scale
end
end
def human_name
unit.try(:human_name)
end
private
def eml_measurement_scale
@eml.measurementScale do
self.measurement_scale = 'dateTime' if measurement_scale == 'datetime'
@eml.tag!(measurement_scale) do
measurement_scale_as_eml(measurement_scale)
end
end
end
def measurement_scale_as_eml(measurement_scale)
case measurement_scale
when 'interval' then eml_interval
when 'ratio' then eml_ratio
when 'ordinal' then nil
when 'nominal'then eml_nominal
when 'dateTime' then eml_date_time
end
end
def eml_unit
@eml.unit do
if unit.try(:in_eml)
@eml.standardUnit unit_name
else
@eml.customUnit unit_name
end
end
end
def unit_name
unit.try(:name)
end
def eml_date_time
@eml.formatString date_format.presence || 'YYYY-MM-DD'
@eml.dateTimePrecision '1'
@eml.dateTimeDomain do
@eml.bounds do
@eml.minimum '1987-4-18', 'exclusive' => 'true'
end
end
end
def eml_nominal
@eml.nonNumericDomain do
@eml.textDomain do
@eml.definition description
end
end
end
def eml_interval
eml_unit
eml_precision_and_number_type
end
def eml_ratio
eml_unit
eml_precision_and_number_type
end
def eml_precision_and_number_type
@eml.precision precision.to_s if precision
@eml.numericDomain do
@eml.numberType data_type
end
end
end
| true
|
9c1d22cbf1292199486791170753732291f550b4
|
Ruby
|
rbk/ruby_class
|
/modules/modules/include_vs_extend.rb
|
UTF-8
| 482
| 3.5
| 4
|
[] |
no_license
|
# include_vs_extend
module ModuleA
def self.included(base)
base.extend(ClassMethods)
end
def methodA
puts "methodA"
end
module ClassMethods
def methodB
puts "methodB"
end
end
end
class ClassA
include ModuleA
#extend ModuleA
end
# when included
#a = ClassA.new
#a.methodA
#a.methodB
# when extended
#ClassA.methodA
#ClassA.methodB
# when both are needed
a = ClassA.new
a.methodA
ClassA.methodB
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.