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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
0e0714431e814457732b3f554ae6c632b6013c70 | Ruby | timgentry/ndr_support | /lib/ndr_support/safe_file.rb | UTF-8 | 4,014 | 2.84375 | 3 | [
"MIT"
] | permissive | require 'ndr_support/safe_path'
class SafeFile
def initialize(*args)
a = self.class.get_fname_mode_prms(*args)
fname = a[0]
mode = a[1]
prms = a[2]
if prms
@file = File.new(fname, mode, prms)
else
@file = File.new(fname, mode)
end
# Just in case better clone the object
# Ruby object are passed by reference
@file_name = fname.clone
end
def self.open(*args)
return SafeFile.new(*args) unless block_given?
f = SafeFile.new(*args)
yield f
f.close
end
def close
@file.close
end
def read
verify @file_name, 'r'
@file.read
end
def write(data)
verify @file_name, 'w'
@file.write(data)
end
def each(*args, &block)
verify @file_name, 'r'
@file.each(*args, &block)
end
alias_method :each_line, :each
def path
@file_name.clone
end
def self.extname(file_name)
verify file_name
File.extname(file_name)
end
def self.read(file_name)
verify file_name, 'r'
File.read(file_name)
end
def self.readlines(*args)
fail ArgumentError, "Incorrect number of arguments - #{args.length}" if args.length > 2 or args.length == 0
verify args[0], 'r'
File.readlines(*args)
end
def self.directory?(file_name)
verify file_name
File.directory?(file_name)
end
def self.exist?(file_name)
self.exists?(file_name)
end
def self.exists?(file_name)
verify file_name
File.exist?(file_name)
end
def self.file?(file_name)
verify file_name
File.file?(file_name)
end
def self.zero?(file_name)
verify file_name
File.zero?(file_name)
end
def self.basename(file_name, suffix = :none)
verify file_name
if suffix == :none
File.basename(file_name)
else
File.basename(file_name, suffix)
end
end
def self.safepath_to_string(fname)
verify fname
fname.to_s
end
def self.basename_file
# SECURE: 02-08-2012 TPG Can't assign to __FILE__
File.basename(__FILE__)
end
def self.dirname(path)
verify path
res = path.clone
res.path = File.dirname(path)
res
end
def self.delete(*list)
verify list, 'w'
list.each do |file|
File.delete(file) if File.exist?(file)
end.length
end
private
def verify(file_names, prm = nil)
self.class.verify(file_names, prm)
end
def self.verify(file_names, prm = nil)
[file_names].flatten.each do |file_name|
fail ArgumentError, "file_name should be of type SafePath, but it is #{file_name.class}" unless file_name.class == SafePath
if prm
[prm].flatten.each do |p|
fail SecurityError, "Permissions denied. Cannot access the file #{file_name} with permissions #{prm}. The permissions are #{file_name.permissions}" unless file_name.permissions.include?(p)
end
end
end
end
def self.verify_mode(file_name, mode)
if mode.match(/\A(r\+)|(w\+)|(a\+)\Z/)
verify file_name, ['w', 'r']
elsif mode.match(/\Aw|a\Z/)
verify file_name, ['w']
elsif mode.match(/\Ar\Z/)
verify file_name, ['r']
else
fail ArgumentError, "Incorrect mode. It should be one of: 'r', 'w', 'r+', 'w+', 'a', 'a+'"
end
end
def self.get_fname_mode_prms(*args)
case args.length
when 1
verify_mode(args[0], 'r')
fname = args[0]
mode = 'r'
prms = nil
when 2
fail ArgumentError unless args[1].is_a?(Integer) || args[1].is_a?(String)
if args[1].is_a?(Integer)
verify_mode(args[0], 'r')
mode = 'r'
prms = args[1]
else
verify_mode(args[0], args[1])
mode = args[1]
prms = nil
end
fname = args[0]
when 3
fail ArgumentError unless args[1].is_a?(String) && args[2].is_a?(Integer)
verify_mode(args[0], args[1])
fname = args[0]
mode = args[1]
prms = args[2]
else
fail ArgumentError, "Incorrect number of arguments #{args.length}"
end
[fname, mode, prms]
end
end
| true |
1c98da37e723e38baec898dc11f7649c5c8a02f5 | Ruby | bingxie/code-questions | /lib/leetcode/739_daily-temperatures.rb | UTF-8 | 967 | 3.6875 | 4 | [
"MIT"
] | permissive | # 从前往后的方法
def daily_temperatures(t)
result = Array.new(t.size, 0)
previous_index = [0]
t.each_with_index do |temp, idx|
next if idx == 0
while !previous_index.empty? && temp > t[previous_index[-1]]
result[previous_index[-1]] = idx - previous_index[-1]
previous_index.pop
end
previous_index << idx
end
result
end
t = [73, 74, 75, 71, 69, 72, 76, 73]
p daily_temperatures(t) # [1,1,4,2,1,1,0,0]
# 从后往前的方法
# @param {Integer[]} t
# @return {Integer[]}
def daily_temperatures(t)
stack = []
res = Array.new(t.size, 0)
(0...t.size).reverse_each do |i|
temp = t[i]
if stack.size == 0
res[i] = 0
elsif temp < stack.last[0]
res[i] = 1
else
while stack.size > 0 && temp >= stack.last[0]
stack.pop
end
if stack.size == 0
res[i] = 0
else
res[i] = stack.last[1] - i
end
end
stack.push([temp, i])
end
res
end
| true |
66b7932eb5c53687012e44d9ca804bf3c3201fe8 | Ruby | shaggyone/ems_russia | /lib/ems_russia/cacher.rb | UTF-8 | 2,175 | 2.828125 | 3 | [] | no_license | require File.expand_path('../cacher_module.rb', __FILE__)
require 'yaml'
module EmsRussia
class Cacher
include ::EmsRussia::CacherInstanceModule
extend ::EmsRussia::CacherClassModule
attr_accessor :value
attr_accessor :expire_at
def initialize(attributes = {:value => nil, :expire_at => DateTime.now - 1000.years})
@value = attributes[:value]
@expire_at = attributes[:expire_at] || DateTime.now + 30.days
end
def self.init(options = {})
self.clear_cache
if options[:file]
@@cached_values = YAML.load_file(options[:file])
end
end
def self.get_cached(key)
contained_values[key]
end
def self.set_cached(key, value, expire_at)
a = (contained_values[key] ||= self.new(:key => key))
a.value = value
a.expire_at = expire_at
a
end
def self.contained_values
@@cached_values ||= {}
end
def self.cached_values
contained_values
end
def self.clear_cache
@@cached_values = {}
end
def self.save_cache(filename)
File.open(filename, 'w') do |f|
YAML::dump(@@cached_values, f)
end
end
end
end
__END__
def self.get(key, datetime = DateTime.now, &block)
unless cached?(key)
return nil unless block_given?
new_expired_at = datetime + 30.days
value = yield(((a=cached_values[key]) ? a.clone : new), new_expired_at)
if value.kind_of? self then
cached_values[key] = value
else
cache_value key, value, new_expired_at
end
end
cached_values[key].value
end
def expired?(datetime = DateTime.now)
self.expire_at <= datetime
end
def self.cached?(key, datetime = DateTime.now)
return false unless cached_values.key?(key)
! expired?(key, datetime)
end
def self.expired?(key, datetime = DateTime.now)
cached_values[key].expired?
end
def self.cache_value(key, value, expire_at = DateTime.now + 15.days)
cached_values[key] = Cacher.new(:value => value,
:expire_at => expire_at )
end
end
end
| true |
c2ff38a3b52ffe51521c467f9e1cf90316afd443 | Ruby | jfarrell/sumo-ruby-client | /lib/sumologic/core_ext/numeric.rb | UTF-8 | 1,006 | 3.171875 | 3 | [
"Apache-2.0"
] | permissive | #
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
class Numeric
def seconds
self
end
alias :second :seconds
def minutes
self * 60
end
alias :minute :minutes
def hours
self * 60.minutes
end
alias :hour :hours
def days
self * 24.hours
end
alias :day :days
def weeks
self * 7.days
end
alias :week :weeks
def ago(time = Time.now)
time - self
end
alias :until :ago
def since(time = Time.now)
time + self
end
alias :from_now :since
end
| true |
d1da6ae6ffdb59fb0a4c5c65d5e528cde9dff247 | Ruby | marcwright/WDI_ATL_1_Instructors | /REPO - DC - Students/w01/d04/Thomas/wines.rb | UTF-8 | 1,355 | 3.203125 | 3 | [] | no_license | require "pry"
wine_cellar = [
{:label => "Rutherford Hill", :type => "Chardonnay", :color => "white"},
{:label => "Nina Veneto", :type => "Pinot Grigio", :color => "white"},
{:label => "Wairau River", :type => "Sauvignon Blanc", :color => "white"},
{:label => "Tangley Oaks", :type => "Merlot", :color => "red"},
{:label => "Chimney Rock", :type => "Cabernet Sauvignon", :color => "red"},
{:label => "Sanford", :type => "Pinot Noir", :color => "red"},
{:label => "Alderbrook", :type => "Pinot Noir", :color => "red"},
{:label => "Colavita", :type => "Pinot Noir", :color => "red"},
{:label => "Markham", :type => "Chardonnay", :color => "white"},
{:label => "Angeline", :type => "Pinot Noir", :color => "red"}
]
#1
def add_wine(label,type,color)
wine_cellar.push({:label => label, :type => type, :color => color})
end
add_wine("California","Pinot Noir","red")
#2
random_wine = wine_cellar[rand(wine_cellar.length)]
#3
white_wine = wine_cellar.select do |wine|
wine[:color].include?("white")
#need to nail down this x[:] thing...
end
#4
wine_types = wine_cellar.map do |wine|
wine[:type]
end
wine_types.uniq
#5
two_word_labels = wine_cellar.select do |wine|
wine[:label].include?(" ")
end
#6
pinot_noirs = wine_cellar.select do |wine|
wine.has_value?("Pinot Noir")
end
pinot_noir_labels = pinot_noirs.map do |wine|
wine[:label]
end
binding.pry | true |
7800e54ce6ae1c3e60e2f358112251f5b507f9e7 | Ruby | JulianArnold/LRTHW | /pine.rb | UTF-8 | 201 | 3.859375 | 4 | [] | no_license | puts 'Hello, what\'s your name?'
name = gets.chomp
puts 'Hello ' + name + '.'
if name == 'Julian'
puts 'What an unusual name.'
else
if name == 'Geraldine'
puts 'What a lovely name.'
end
end
| true |
05555609ee0312da9d51ed12e2a3c32410782d50 | Ruby | scoin/phase_0_unit_2 | /week_6/8_BONUS_CarClass/my_solution.rb | UTF-8 | 2,946 | 4.125 | 4 | [] | no_license | # U2.W6: Create a Car Class from User Stories
# I worked on this challenge by myself
# 2. Pseudocode
# 3. Initial Solution
class Car
def initialize(model, color, year = 2014)
@my_car = "#{color.capitalize} #{year.capitalize} #{model.capitalize}"
@speed = 0
@mileage = 0.0
@pizza_stack = []
@last_action = []
@last_action << "Created #{@my_car}"
puts @last_action[@last_action.size - 1]
end
def drive(distance, speed_limit = @speed)
@mileage += distance
@speed = speed_limit
unless @speed == 0
puts "Driving #{distance} miles at #{@speed} MPH"
@last_action << "Drove #{distance} miles at #{@speed} MPH"
else
puts "You are not going anywhere! Tell me how fast to go!"
end
end
def accelerate(mph = 5)
@speed += mph.abs
@last_action << "Accelerated to #{@speed} MPH"
puts @last_action[@last_action.size - 1]
end
def slow_down(mph = 5)
@speed -= mph.abs
if @speed == 0
puts "You're already stopped! Get back to work dude!"
return
end
@last_action << "Slowed down to #{@speed} MPH"
puts @last_action[@last_action.size - 1]
end
def stop
@speed = 0
@last_action << "You stopped"
puts @last_action[@last_action.size - 1]
end
def check_speed
puts "You are going #{@speed} MPH"
@speed
end
def turn(direction)
if direction.downcase == 'left' || direction.downcase == 'right'
@last_action << "Turned #{direction}"
puts @last_action[@last_action.size - 1]
@speed = 0
else
puts "Turn 'left' or 'right'. What do you think this is, a spaceship?"
end
end
def check_mileage
puts "You have traveled #{@mileage} miles"
@mileage
end
def replay
@last_action.each{|string| puts string }
end
def get_pizza(*pies)
pies.each{|pie| @pizza_stack << pie
@last_action << "Got #{pie.type} pizza for delivery"}
pies.size.downto(1) do |i| puts @last_action[@last_action.size - i] end
end
def deliver_pizza
delivered = @pizza_stack.shift
if(@speed == 0)
@last_action << "Delivered a #{delivered.type} pizza. Well done!"
else
@last_action << "Threw #{delivered.type} pizza out the window at #{@speed} MPH."
end
puts @last_action[@last_action.size - 1]
end
end
class Pizza
def initialize(type = "Plain")
@type = type
end
def type
@type
end
end
# 4. Refactored Solution
# 1. DRIVER TESTS GO BELOW THIS LINE
first = Car.new("Oldsmobile 88", "Burgundy", "1989")
first.get_pizza(Pizza.new("Anchovy"), Pizza.new("Vegan"), Pizza.new("Hawaiian"))
first.drive(0.25, 25)
first.stop
first.turn("right")
first.drive(1.5, 35)
first.check_speed
first.slow_down(20)
first.drive(0.25)
first.stop
first.turn("left")
first.drive(1.4, 35)
first.accelerate
first.accelerate
first.accelerate(45)
first.deliver_pizza
first.stop
first.deliver_pizza
first.deliver_pizza
first.check_mileage
# 5. Reflection
#Super fun one! No real challenge here, just continuing to cement classes. I'm feeling really strong after all this review! | true |
9c8ed557fbcc55fb7e484919339dbdaf22bd695b | Ruby | nahi/openpgp4u | /lib/pgp/packet/literaldata.rb | UTF-8 | 2,041 | 2.71875 | 3 | [] | no_license | # Copyright 2004 NAKAMURA, Hiroshi <nakahiro@sarion.co.jp>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'pgp/packet/packet'
module PGP
module Packet
class LiteralData < Packet
FORMATS = {
0x62 => "Binary",
0x74 => "Text",
0x75 => "Text(UTF-8)",
}
def self.format_include?(format)
FORMATS.key?(format)
end
def self.format_label(format)
FORMATS[format]
end
def initialize
super(11)
@format = @filename = @mtime = @body = nil
end
attr_reader :format
attr_accessor :filename
attr_accessor :mtime
attr_accessor :body
def format=(format)
@format = format
end
def scan(io)
io.puts "Format - #{format_label}"
io.puts "File name - #{@filename}"
io.puts "The modification date or the creation time of the packet - #{@mtime}"
io.puts "Body - #{@body.size} bytes"
end
def format_label
LiteralData.format_label(@format)
end
private
def dump_body
raise "ToDo"
end
def self.loader(port, length)
initpos = port.readlength
packet = new()
packet.format = load_format(port)
packet.filename = load_filename(port)
packet.mtime = load_time(port)
packet.body = port.read(length - (port.readlength - initpos))
packet
end
def self.scanner(io, port, length)
loader(port, length).scan(io)
end
def self.load_format(port)
load_1octet(port)
end
def self.load_filename(port)
size = load_1octet(port)
port.read(size)
end
add_loader(11, method(:loader))
add_scanner(11, method(:scanner))
end
end
end
| true |
efb821d104dd16ddb48b1f4c131c55957335cec8 | Ruby | CharlaCeansky/tic-tac-toe-rb-v-000 | /lib/tic_tac_toe.rb | UTF-8 | 1,854 | 3.953125 | 4 | [] | no_license | WIN_COMBINATIONS= [
top_row_win=[0,1,2],
middle_row_win=[3,4,5],
bottom_row_win=[6,7,8],
left_column_win=[0,3,6],
middle_column_win=[1,4,7],
right_column_win=[2,5,8],
left_diagonal_win=[0,4,8],
right_diagonal_win=[2,4,6],
]
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
def input_to_index(user_input)
user_input.to_i - 1
end
def move(board, index, current_player)
board[index] = current_player
end
def position_taken?(board, location)
board[location] != " " && board[location] != ""
end
def valid_move?(board, index)
index.between?(0,8) && !position_taken?(board, index)
end
def turn_count(board)
turns=0
board.each do |token|
if token == "X" || token == "O"
turns += 1
end
end
turns
end
def turn(board)
puts "Please enter 1-9:"
input = gets.strip
index = input_to_index(input)
if valid_move?(board, index)
move(board, index, current_player(board))
display_board(board)
else
turn(board)
end
end
def current_player(board)
turn_count(board) % 2 == 0?"X":"O"
end
def won?(board)
WIN_COMBINATIONS.detect do |i|
board[i[0]] == board[i[1]] && board[i[0]] == board[i[2]] && position_taken?(board,i[0])
end
end
def full?(board)
board.all? do |i|
i == "X" || i == "O"
end
end
def draw?(board)
full?(board) && !won?(board)
end
def over?(board)
full?(board) || won?(board) || draw?(board)
end
def winner(board)
board[won?(board)[0]] if won?(board)
end
def play(board)
counter=0
until over?(board)
turn(board)
counter+=1
end
if winner(board)
puts "Congratulations #{winner(board)}!"
else draw?(board)
puts "Cat's Game!"
end
end
| true |
e5ee0d5deae55706943488513fdc0086f852e1fd | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/ruby/bob/2339ac8cda464cae9c1feda49f11ca7e.rb | UTF-8 | 235 | 3.4375 | 3 | [] | no_license | class Bob
def hey (str)
/\S/.match(str) or
return 'Fine. Be that way!'
/\p{Upper}/.match(str) and !/\p{Lower}/.match(str) and
return 'Woah, chill out!'
/\?\z/.match(str) and
return 'Sure.'
return 'Whatever.'
end
end
| true |
e618494922d4842b85bc1bf09de520c8c7c9edd1 | Ruby | chadbrewbaker/PowerComputing | /rec.rb | UTF-8 | 162 | 3.453125 | 3 | [] | no_license |
def faaa(n)
if( n==0)
return 2
end
if( n == 1)
return 6
end
return (3*faaa(n-1) + 5*faaa(n-2))
end
0.upto(10) do |n|
puts faaa(n)
end
| true |
75ecfc90d00ed49ed1408a8cc4f1b577a3ca6476 | Ruby | wabilin/Simple-SIC-XE-Assembler-in-Ruby | /main.rb | UTF-8 | 222 | 2.640625 | 3 | [] | no_license | #!usr/bin/ruby
$LOAD_PATH << "."
require 'assembler'
input_file = ARGV[0]
output_file = ARGV[1]
asm = Assembler.new
asm.read_sourse(File.read(input_file))
asm.pass_one
asm.pass_two
asm.print File.open(output_file, "w")
| true |
bf021bcc95f83752ba077294827a331187799683 | Ruby | ayucv/smsRuby | /lib/smsruby.rb | UTF-8 | 6,971 | 3.40625 | 3 | [] | no_license | require 'smsruby/send'
require 'smsruby/receive'
#
# The Smsruby class represent the connection between the client and the SMS middleware.
# Defines the API functions of the SMS middleware
#
class Smsruby
# Reference an instance of the Sender class
attr_reader :sender
# Reference an instance of the Receive class
attr_reader :receiver
#
# Obtain the sender and receiver instances, allowing users to send and receive
# messages trought the API functions.
# The initialize function can receive 4 arguments: the first one is the send type
# to be used by the Sender class, the second one is the location of the configuration
# file used by the Sender class, the third one is the receivetype used in the Receive
# class and the fourth one is the time that receive threads will remain active. If 0 is
# past, receive threads will remain active until stop_receive method is called.
#
# A simple example of how to use smsRuby is shown below:
#
# require 'rubygems'
# require 'smsruby'
#
# sms = Smsruby.new
#
# sms.sender.dst=['0412123456']
# sms.send("Hello world")
#
# sms.receive{ |message,dest|
# puts "Hello world"
# }
#
# Other example:
#
# require 'rubygems'
# require 'smsruby'
#
# sms = Smsruby.new(:sendtype=> BDsend.new, :location=> 'config_sms.yml', :receivetype=> 0, :time=> 15, :ports=>['/dev/ttyACM0'])
#
# sms.send("Hello world")
#
# sms.receive(['358719846826017']){ |message,dest|
# puts "Message received: #{message.text}, from #{message.source_number}"
# puts "The phone receiving the message has imei number #{dest}"
# }
#
# A final example:
#
# require 'rubygems'
# require 'smsruby'
#
# sms = Smsruby.new
#
# sms.sender.sendtype = Configsend.new
# sms.send("Hello world")
#
# sms.receiver.receivetype=1
# sms.receive(['358719846826017']){ |message,dest|
# puts "Message received: #{message.text}, from #{message.source_number}"
# puts "The phone receiving the message has imei number #{dest}"
# }
#
def initialize(*args)
begin
params={}
params=args.pop if args.last.is_a? Hash
!params[:sendtype] ? sendtype=Plainsend.new : sendtype = params[:sendtype]
!params[:location] ? location = 'config_sms.yml' : location = params[:location]
!params[:receivetyoe] ? receivetype = 0 : receivetype = params[:receivetype]
!params[:time] ? time = 0 : time = params[:time]
!params[:ports] ? ports=nil : ports = params[:ports]
@sender=Sender.new(sendtype,location)
@receiver=Receive.new(receivetype,time)
@sender.adm.open_ports(ports) unless @sender.adm.avlconn
rescue Exception => e
puts "Instance of connection administrator fail. Detail: #{e.message}"
end
end
#
# High level function to send an SMS message. The text to be sent must be passed
# as an argument. the values of the other options can be set trought the Sender
# class, the destination number(s) is required. A code block can be past to send
# function and will be executed if an error occurs sending the message. The code
# block can use one argument, this is the string error giving by Sender class
#
def send(msj)
@sender.send(msj){|e| yield e if block_given?}
end
#
# Hight level function to receive SMS message(s). The imei of the phones that are
# going to receive can be passed as an argument, if not, all the phones configured
# to receive ( trought config_sms.yml ) will be used. The values of the other options
# can be set trought the Receive class. A code block can be passed to the receive
# function and will be executed for every received message, the block can use 2
# given arguments. The first argument is a message object with the following structure:
#
# message{
# int error if error is different from 0 an error has ocurred
# int index the index memory in the phone of the received message
# string date reception date of the message
# string status the status of the received message (read, unread ,unknown,..)
# string source_number The number of the phone sending the message
# string text The text of the received message
# string type_sms The sms type of the received message (text, mms,...)
# }
#
# The second argument represent the imei of the phone receiving the message
#
def receive(imeis=nil)
@receiver.receive(imeis){|x,y| yield x,y if block_given? }
end
#
# High level function to update and reload changes made to the configuration
# file used in the Sender and the Connection Administrator
#
def update_config
unless !@sender.adm.avlconn
@sender.adm.reload_file
end
end
#
# High level function to update available connections in case a new one is
# attached or an available one is unattach. An update of the configuration
# file is also made when update_conn function is invoked
#
def update_conn
if !@sender.adm.avlconn
@sender.adm.open_profiles
end
@sender.adm.update_connections unless !@sender.adm.avlconn
update_config
end
#
# High level function to get all available connection. The result is a hash
# containing the number of the connection and an object of the Connection class.
# A code block can be passed to get_conn function and will be executed for each
# available connection found by the Connection Administrator
#
def get_conn
unless !@sender.adm.avlconn
conn= @sender.adm.get_connections{ |pm|
yield pm if block_given?
}
end
return conn
end
#
# High level function that wait for both receive and send threads and terminate
# all active connections. A call to close function must be made at the end
# of the user program
#
def close
sleep(1)
unless !@receiver.adm.avlconn
Thread.list.each{|t| t.join if (t[:type]=='r' or t[:type]=='sp') }
@receiver.adm.get_connections.each{|conn|
conn[1].close
}
end
end
#
# High level function that stops all receiving threads that are configured to
# obtain messages for a spicified period of time
#
def stop_receive
sleep(1)
unless !@receiver.adm.avlconn
Thread.list.each{|t| t.exit if t[:type]=='r'}
@receiver.adm.get_connections.each{|conn|
conn[1].status="available" if ((conn[1].typec=='r' and conn[1].status=="receiving") or (conn[1].typec=='sr' and conn[1].status=="receiving"))}
end
end
#
# High level function that wait for all active receive threads without terminate
# the active connections.
#
def wait_receive
sleep(1)
unless !@receiver.adm.avlconn
Thread.list.each{|t| t.join if t[:type]=='r'}
@receiver.adm.get_connections.each{|conn|
conn[1].status="available" if ((conn[1].typec=='r' and conn[1].status=="receiving") or (conn[1].typec=='sr' and conn[1].status=="receiving"))}
end
end
end
| true |
d53a2e07e91343e151e72e5bbacc3ab31b920c4d | Ruby | pyelton/Synteny-based-annotator | /fasta_parser.rb | UTF-8 | 772 | 2.96875 | 3 | [] | no_license | require 'ostruct'
class Fasta_file
attr_reader :file, :sequence, :header
def initialize(fasta_file)
@sequence = Array.new
@file = File.open(fasta_file)
end
def each_object #goes through file fasta objects
fasta = OpenStruct.new
sequence = Array.new
index = 0
buffer = Array.new
@file.each_line do |line|
if line =~ />/
unless index == 0
buffer.push(fasta)
end
fasta = OpenStruct.new
fasta.header = line.split(">")[1]
fasta.index = index
fasta.index = index += 1
sequence = Array.new
else
sequence.push(line.chomp)
fasta.sequence = sequence.to_s
end
end
buffer.push(fasta)
@buffer = buffer
end
end #end of Fasta class
| true |
8d9d2a0cc7be6304a60e676fdb8765a6d0659cde | Ruby | nmking22/war_or_peace | /test/deck_test.rb | UTF-8 | 1,803 | 3.328125 | 3 | [] | no_license | require 'minitest/autorun'
require 'minitest/pride'
require './lib/card'
require './lib/deck'
class DeckTest < Minitest::Test
def setup
@card1 = Card.new(:diamond, 'Queen', 12)
@card2 = Card.new(:spade, '3', 3)
@card3 = Card.new(:heart, 'Ace', 14)
@cards = [@card1, @card2, @card3]
@deck = Deck.new(@cards)
end
def test_it_exists
assert_instance_of Deck, @deck
end
def test_it_has_readable_attributes
assert_equal [@card1, @card2, @card3], @deck.cards
end
def test_it_can_find_rank_of_card_at
assert_equal 12, @cards[0].rank
assert_equal 3, @cards[1].rank
assert_equal 14, @cards[2].rank
end
def test_it_can_identify_high_ranking_cards
assert_equal [@card1, @card3], @deck.high_ranking_cards
end
def test_it_can_calculate_percent_of_high_ranking_cards
assert_equal 66.67, @deck.percent_high_ranking
end
def test_it_can_remove_cards
assert_equal @card1, @deck.remove_card
assert_equal [@card2, @card3], @deck.cards
end
def test_it_can_add_cards
card4 = Card.new(:club, '5', 5)
@deck.add_card(card4)
assert_equal [@card1, @card2, @card3, card4], @deck.cards
end
def test_it_can_populate_deck
deck = Deck.new
deck.populate_standard_deck
# How do I test this? Also test no duplicates?
assert_equal 52, deck.cards.length
end
def test_it_can_shuffle
skip
deck = Deck.new
deck.populate_standard_deck
shuffled_deck = deck.shuffle_deck
# This test doesn't work, but the method does what I want it to
refute deck.cards, shuffled_deck
end
def test_it_can_cut_deck
deck = Deck.new
deck.populate_standard_deck
deck.cut_deck
assert assert_equal 26, deck.cut_cards[0].length
assert assert_equal 26, deck.cut_cards[1].length
end
end
| true |
4ef1494fb8f0ee4685dc413f81c51970b67ed301 | Ruby | ed-mare/jsonapiserver-example | /app/forms/v1/add_book.rb | UTF-8 | 807 | 2.625 | 3 | [] | no_license | module V1
class AddBook
attr_reader :book
def initialize(book_params, author_params, publisher_params)
@book = Book.new(book_params)
@author = Author.new(author_params) if author_params.present?
@publisher = Publisher.new(publisher_params) if publisher_params.present?
end
def save
@book.author = @author if @author
@book.publisher = @publisher if @publisher
@book.save || bubble_errors
rescue ActiveRecord::NotNullViolation => e
bubble_errors
end
protected
def bubble_errors
[@author, @publisher].each do |record|
if record.respond_to?(:errors) && record.errors.present?
@book.errors.add("#{record.class.name}:", record.errors.full_messages.first)
end
end
false
end
end
end
| true |
f2eeb1684ea1d664b43fff55b4c51df86f228b37 | Ruby | UANDES-4103-201910/lab-assignment-2-juanesgh | /problems/frequency_finder.rb | UTF-8 | 112 | 3.046875 | 3 | [] | no_license | def find_frequency(sentence, word)
a = sentence.downcase.split()
b = word.downcase()
return a.count(b)
end | true |
58c3579612234c9ce5e25ec077668ab894cf73f6 | Ruby | hussyvel/ruby | /udemy_ruby_curso_jackson_pires/atributos_virtuais.rb | UTF-8 | 349 | 3.09375 | 3 | [] | no_license | # frozen_string_literal: true
class Carro
attr_accessor :marca, :modelo
def velocidade_maxima
300
end
def descricao
"Marca: #{@marca} e Modelo: #{modelo}"
end
end
carro = Carro.new
carro.marca = 'Voyagem'
carro.modelo = 'Focus'
puts "Marca: #{carro.marca}"
puts "Modelo: #{carro.modelo}"
puts "Descrição: #{carro.descricao}"
| true |
e0a5fb8bcf3a5f9e699800733c754efcfaebf5bc | Ruby | kulisfunk/week_2_day_4 | /employee_system/specs/agent_spec.rb | UTF-8 | 454 | 2.703125 | 3 | [] | no_license | require 'minitest/autorun'
require 'minitest/rg'
require_relative '../agent.rb'
class TestAgent < MiniTest::Test
def setup()
@agent = Agent.new("James", "Bond")
end
def test_name()
actual = "The names " + @agent.surname + ", " + @agent.name + " " + @agent.surname
assert_equal("The names Bond, James Bond", actual)
end
def test_name()
actual = @agent.full_name()
assert_equal("The names Bond, James Bond", actual)
end
end
| true |
cdc3208bc04d759f327a96d54812479c2f3982d4 | Ruby | redazures/ruby-object-initialize-lab-ruby-intro-000 | /lib/dog.rb | UTF-8 | 238 | 3.640625 | 4 | [] | no_license | class Dog
def initialize(name, breed="Mutt")
@name=name
@breed=breed
end
def name
@name
end
def name=(name)
@name=name
end
def breed
@breed
end
def breed=(newbreed)
@breed=newbreed
end
end
| true |
8d1deb664a143e1f61ed29e2eac9447300cbbef8 | Ruby | IvanKhoteev/part1 | /prog2.rb | UTF-8 | 207 | 3.171875 | 3 | [] | no_license | def coincidence(array = false,range = false)
out = []
if array && range
array.each do |el|
if range.include?(el)
out.push(el)
end
end
end
return out
end
puts coincidence( )
| true |
aee146fda7a35927fb43bc3bfb49d283a5a12d70 | Ruby | pohor/algorithms_exercises | /first steps in ruby/20.rb | UTF-8 | 189 | 3.46875 | 3 | [] | no_license | puts "Podaj mi liczbę:"
usr_num = gets.to_i
sum = 0
div = 1
while div < usr_num
sum += (usr_num / div) % 10
div *= 10
end
puts "Suma cyfr w podanej przez Ciebie liczbie to #{sum}."
| true |
2c1f48e17f143cdf1bd46e5ee5b180e2e70ed3ea | Ruby | tcd/gql | /lib/gql/parse/union.rb | UTF-8 | 348 | 2.53125 | 3 | [
"MIT"
] | permissive | module Gql
module Parse
# @param data [Hash<Symbol>]
# @return [Gql::Models::Union]
def self.union(data)
union = Gql::Models::Union.new()
union.name = data[:name]
union.description = data[:description]
union.types = data[:possibleTypes].map { |pt| pt[:name] }
return union
end
end
end
| true |
aab2622239099b18759f422082f7304d6671ff4d | Ruby | FiskSMK/aggregations-2 | /scripts/dbrzezinski/s_to_a.rb | UTF-8 | 591 | 2.65625 | 3 | [] | no_license | require 'mongo'
include Mongo
coll = MongoClient.new("localhost", 27017).db("train").collection("questions")
coll.find.each do |record|
tags = record['tags']
tags = tags.to_s unless tags.is_a? String or tags.is_a? Array
coll.update({ "_id" => record['_id'] }, { "$set" => { "tags" => tags.split(" ") } }) if tags.is_a? String
end
data = coll.aggregate([
{ "$unwind" => "$tags" },
{ "$group" => { _id: "$tags", number: { "$sum" => 1 } } }
])
all_tags = data.map{|e| e["number"]}.reduce(:+)
diff_tags = data.count
puts "All tags: #{all_tags}"
puts "Different tags: #{diff_tags}" | true |
1ba7872d3bdeed9a85792a7ec9c0b4deba2c9a62 | Ruby | jasooonko/library_import | /import_user.rb | UTF-8 | 2,572 | 3.078125 | 3 | [] | no_license | require "csv"
require "mysql"
$data_file = '/Users/jasonko/Dropbox/church/library/library_excel/person_information.csv'
$addr_file = '/Users/jasonko/Dropbox/church/library/library_excel/address.csv'
$addr_csv = CSV.open( $addr_file, "r", headers: true, :header_converters => :symbol )
def getuser(row)
lname = row[1]
fname = row[2]
mname = row[3]
if(!lname.nil?)
lname = lname.strip.capitalize
else
lname = '#####'
end
if(!fname.nil?)
fname = fname.strip.split.map(&:capitalize).join(' ')
end
if(!mname.nil?)
mname = row[3].gsub(' ', '')
end
if(fname.nil? && mname.nil?)
fname = row[0]
end
return {:id => row[0], :lname => lname, :fname => fname, :mname => mname, :gender => row[6]}
end
def get_addr(house_id)
address = open($addr_file).grep(/^#{house_id},/)
#puts address[0]
#1720,8185198716,34-48 89th Street,,"Jackson Heiacxkson",NY,11372,,FALSE
if address[0].nil? then return
else
addr = address[0].split(',')
a = { :phone => addr[1], :street => "#{addr[2]}, #{addr[3]}", :city => addr[4], :state => addr[5], :zipcode => addr[6], :country => addr[7]}
return a
end
end
def print(statement)
puts statement + '\n'
end
#users.each do |user|
def insert(statement)
id = 0
begin
con = Mysql.new '192.168.1.11', 'jko', 'password', 'library'
#puts statement
con.query(statement)
rs = con.query('SELECT LAST_INSERT_ID();')
id = rs.fetch_row
rescue Mysql::Error => e
puts e.errno
puts e.error
ensure
con.close if con
end
return id[0]
end
users = []
CSV.foreach($data_file, headers: true, :header_converters => :symbol) do |row|
house_id = row[8]
user = getuser(row)
users.push(user)
statement = "INSERT INTO users (lname, fname, mname, gender, created) VALUES ('#{user[:lname]}', '#{user[:fname]}', '#{user[:mname]}','#{user[:gender]}','#{Time.now.to_s}');"
user_id = insert(statement)
house = get_addr(house_id)
if (!house.nil?)
puts statement = "INSERT INTO address (address1, city, state, zipcode, country, created) VALUES ('#{house[:street]}', '#{house[:city]}', '#{house[:state]}','#{house[:zipcode]}','#{house[:country]}','#{Time.now.to_s}');"
puts house
house_id = insert(statement)
puts "user_id=#{user_id} | house_id=#{house_id}"
puts statement = "INSERT INTO users_address (user_id, addr_id, created) VALUES ('#{user_id}', '#{house_id}', '#{Time.now.to_s}');"
insert(statement)
puts statement = "UPDATE users set phone = '#{house[:phone]}' WHERE id = #{user_id}"
insert(statement)
puts '---------'
end
end
| true |
3eb99de6f391e96f41642aba1bc2591fad7bc177 | Ruby | juliansibaja84/fluffy-bassoon | /other/random_scripts/ruby/decoder.rb | UTF-8 | 1,150 | 3.734375 | 4 | [] | no_license |
a=[ '000000',
'000001',
'000010',
'000011',
'000100',
'000101',
'000111',
'001000',
'001001',
'001010',
'001011',
'001100',
'001101',
'001110',
'001111',
'010000',
'010001',
'010010',
'010011',
'010100',
'010101',
'010110',
'010111',
'011000',
'011001',
'011010',
'011011',
'011100',
'011101',
'011110',
'011111',
'100001',
'100010',
'100011',
'100100',
'100101',
'100110',
'100111',
]
b=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l",
"m","n","ñ","o","p","q","r","s","t","u","v","w","x","y","z"," "]
dict = Hash.new
puts "[!]Va codificar o decodificar?(1=cod,0=dec)"
choice = gets.chomp
if choice == "1"
acum=0;
for i in b do
dict[i]=a[acum]
acum+=1
end
puts "[!]Ingrese la/s palabra/s:"
pac = gets.chomp
pac = pac.split(//)
for i in pac
puts dict[i]
end
elsif choice == "0"
acum=0;
for i in a do
dict[i]=b[acum]
acum+=1
end
puts "[!]Ingrese el/los código/s [separado por espacio]:"
pac = gets.chomp
pac = pac.split(' ')
for i in pac
printf dict[i]
end
puts ''
else
puts "¡Usted es una mala persona!"
end
#puts dict
| true |
86aa48dac7e1aebb6b7053a32a4f088a42b8b7b3 | Ruby | hasumikin/mrubyc | /test/models/my_block.rb | UTF-8 | 252 | 3.296875 | 3 | [
"BSD-3-Clause"
] | permissive | class MyBlock
def initialize
@result = Array.new
end
def func1
yield
end
def each_double(array)
array.each do |v|
double(v)
end
end
def double(val)
@result << val * 2
end
def result
@result
end
end
| true |
15f45ef199f38dbb37a7ecca83ee30f9940b7981 | Ruby | oclaussen/chef-cookie-cutter | /lib/chef/cookie_cutter/autodocs/resource_dsl.rb | UTF-8 | 3,392 | 2.59375 | 3 | [
"Unlicense"
] | permissive | # frozen_string_literal: true
class Chef
module CookieCutter
module Autodocs
##
# Extensions to the Chef resource DSL
#
module ResourceDSL
##
# Describes an action on the resource
#
class Action
attr_reader :name
attr_accessor :description
attr_accessor :internal
def initialize(name, description = '', internal: false)
@name = name
@description = description
@internal = internal
end
end
##
# Extensions of the Chef resource class DSL
#
module ClassMethods
##
# Get the name of the resource
#
# @return [String] the resource name
#
def name
resource_name
end
##
# Get or set a description for the resource.
#
# @param text [String] if given, will set the description of the resource to this text
# @return [String] the description of the resource
#
def description(text = nil)
@description = text unless text.nil?
return @description unless @description.nil?
''
end
##
# Get a short description for the resource. The short description is
# simply the first full sentence of the normal #description.
#
# @return [String] the first sentence of the description
#
def short_description
match = Regexp.new('^(.*?\.(\z|\s))', Regexp::MULTILINE).match(description)
return description if match.nil?
match[1].tr("\n", ' ').strip
end
##
# Get the descriptions for actions on the resource.
#
# @return [Hash<Symbol, Action>] the description set for the actions
#
def action_descriptions
@action_descriptions ||= {
# Ignore the :nothing action by default
nothing: Action.new(:nothing, internal: true)
}
end
##
# Describe an action on the resource.
#
# @param name [Symbol] the action name
# @yield [Action] the action description
#
def describe_action(name, &blk)
action_descriptions[name] ||= Action.new(name)
action_descriptions[name].instance_eval(&blk) if block_given?
end
end
# @!visibility private
module ClassMethodsMP
def action(name, description = nil, internal: nil, &blk)
super(name, &blk)
describe_action(name) do |a|
a.description = description unless description.nil?
a.internal = internal unless internal.nil?
end
end
def lazy(description = 'a lazy value', &blk)
lazy_proc = super(&blk)
lazy_proc.instance_variable_set :@description, description
lazy_proc.define_singleton_method :description do
@description
end
lazy_proc
end
end
# @!visibility private
def self.included(base)
class << base
include ClassMethods
prepend ClassMethodsMP
end
end
end
end
end
end
| true |
cc97beea126b9cbcb5f7530bbe87a5ac8d2ca8b6 | Ruby | bleything/kuler | /test/test_kuler_theme.rb | UTF-8 | 1,065 | 2.5625 | 3 | [
"MIT"
] | permissive | require "test/unit"
require 'pathname'
require "kuler"
class TestKulerTheme < Test::Unit::TestCase
FIXTURES = Pathname.new( File.dirname(__FILE__) ).expand_path + "fixtures"
def setup
xml = FIXTURES + "single_random_result.xml"
nodes = Nokogiri::XML( xml.read ).at( "//kuler:themeItem" )
@theme = Kuler::Theme.new( nodes )
end
########################################################################
### Basics
def test_create
assert_equal 15325, @theme.theme_id
assert_equal "sandy stone beach ocean diver", @theme.title
assert_equal %w( beach diver ocean sandy stone ), @theme.tags
assert_equal 4, @theme.rating
assert_equal "ps", @theme.author_name
assert_equal 17923, @theme.author_id
assert_equal 5, @theme.swatches.size
@theme.swatches.each do |swatch|
assert_kind_of Kuler::Swatch, swatch
end
end
def test_hex_codes
expected = [
"#e6e2af",
"#a7a37e",
"#efecca",
"#046380",
"#002f2f"
]
assert_equal expected, @theme.hex_codes
end
end
| true |
413729117c6037c01b7de5f5595a76f7a6cae985 | Ruby | mengyushi/LeetCode | /Ruby/983.rb | UTF-8 | 621 | 3.03125 | 3 | [] | no_license | # @param {Integer[]} days
# @param {Integer[]} costs
# @return {Integer}
def mincost_tickets(days, costs)
return 0 if days.empty?
first = days.min
last = days.max
results = [0]
1.upto(last-first+1) do |day|
if days.include?(day+first-1)
cands = []
cands << (day-1>=0 ? (results[day-1]+costs[0]):costs[0])
cands << (day-7>=0 ? (results[day-7]+costs[1]):costs[1])
cands << (day-30>=0 ? (results[day-30]+costs[2]):costs[2])
results << cands.min
else
results << results.last
end
end
results.last
end
| true |
1590ae75bbd76ea322ff798b38c4603a166cd67c | Ruby | terrybu/AlgorithmsCodingPractice | /Ruby/findLargestSubsequence.rb | UTF-8 | 916 | 4.0625 | 4 | [] | no_license | def findLargestIncreasingSubsequence(array)
arrayOfSubarrays = findIncreasingSubsequences(array)
arrayTotals = []
for subarray in arrayOfSubarrays
arrayTotals << determineIncrease(subarray)
end
answerIndex = arrayTotals.index(arrayTotals.max)
return arrayOfSubarrays[answerIndex]
end
def determineIncrease(array)
increase = 0
increase = array[-1] - array[0]
return increase
end
def findIncreasingSubsequences(array)
result = []
for i in 0..array.length-2
if array[i] < array[i+1]
newSeq = []
newSeq.push(array[i], array[i+1])
#we found the smallest possible increasing subseq.
#find out how deep the rabbit hole goes
j = i + 1 #index 1
while (array[j] < array[j+1])
newSeq << array[j+1]
j += 1
end
result << newSeq
end
end
return result
end
p findLargestIncreasingSubsequence([1,100,3,500,-1,-100,2,5,1000,-500]) | true |
554c163e236620666bc7e5388169a0131fc46425 | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/ruby/bob/49de948322534d78bd466f06aaa07f39.rb | UTF-8 | 558 | 3.828125 | 4 | [] | no_license | class MessageProcessor
def initialize message
@message = message.strip
end
def find_response
if @message.empty?
'Fine. Be that way!'
elsif contains_no_lowercase_letters?
'Woah, chill out!'
elsif ends_with_a_question_mark?
'Sure.'
else
'Whatever.'
end
end
private
def contains_no_lowercase_letters?
@message.index(/[a-z]/).nil?
end
def ends_with_a_question_mark?
@message.end_with? '?'
end
end
class Bob
def hey message
MessageProcessor.new(message).find_response
end
end
| true |
23da332438f4a65af10e1ad3df03526059d4fe0b | Ruby | DashaDasha88/jungle | /spec/user_spec.rb | UTF-8 | 4,355 | 2.796875 | 3 | [] | no_license | require 'rails_helper'
RSpec.describe User, type: :model do
describe 'Validations' do
it 'password is required' do
expect(@user).to_not be_valid
expect(@user.errors.messages[:password]).to include('can\'t be blank')
end
it 'password and password confirmation need to match' do
user1 = User.new
user1.first_name = "Joe"
user1.last_name = "Mama"
user1.email = "joe@test.com"
user1.password = "lollipop"
user1.password_confirmation = "lollipop"
user1.save
user2 = User.new
user2.first_name = "Joe"
user2.last_name = "House"
user2.email = "joe@test.com"
user2.password = "lollipop"
user2.password_confirmation = "lollylops"
user2.save
expect(full_user.password).to eq(full_user.password_confirmation)
expect(full_user2.password).to_not eq(full_user2.password_confirmation)
end
it 'email is required' do
user = User.new(email: nil)
expect(user).to be_invalid
expect(user.errors[:email]).to include("can't be blank")
user.email = 'test@test.com' # valid state
user.valid?
expect(user.errors[:email]).not_to include("can't be blank")
end
it 'email must be unique' do
user1 = User.new
user1.first_name = 'Jim'
user1.last_name = 'Bob'
user1.email = 'jim@test.com'
user1.password = 'bloo'
user1.password_confirmation = 'bloo'
user1.save
user2 = User.new
user2.first_name = 'Jim'
user2.last_name = 'Blob'
user2.email = 'jim@test.com'
user2.password = 'bloo'
user2.password_confirmation = 'bloo'
user2.save
expect(u.errors[:email].first).to eq('email already taken')
end
it 'first name is required' do
user = User.new(first_name: nil)
expect(@user).to_not be_valid
expect(@user.errors.messages[:first_name]).to include('can\'t be blank')
user.first_name = 'first_name'
user.valid?
expect(user.errors[:first_name]).not_to include("can\t be blank")
end
it 'last name is required' do
user = User.new(last_name: nil)
expect(@user).to_not be_valid
expect(@user.errors.messages[:last_name]).to include('can\'t be blank')
user.last_name = 'last_name'
user.valid?
expect(user.errors[:last_name]).not_to include("can\t be blank")
end
it 'password must have minimum length of 5 charactes' do
user = User.new
user.first_name = 'Mary'
user.last_name = 'Bary'
user.email = 'mary@test.com'
user.password = '1234'
user.password_confirmation = '1234'
expect(user).to be_invalid
end
end
describe '.authentication_with_credentials' do
it 'should pass if email and password are valid' do
user = User.new
user.first_name = "Joe"
user.last_name = "Mama"
user.email = "joe@test.com"
user.password = "lollipop"
user.password_confirmation = "lollipop"
user.save
valid_user = User.authenticate_with_credentials("joe@test.com", "lollipop")
expect(valid_user).to eq(user)
end
it 'should not pass if email and password are invalid' do
user = User.new
user.first_name = "Joe"
user.last_name = "Mama"
user.email = "joe@test.com"
user.password = "lollipop"
user.password_confirmation = "lollipop"
user.save
invalid_user = User.authenticate_with_credentials("jane@test.com", "lollipop")
expect(invalid_user).to_not eq(user)
end
it 'should pass with spaces in the email' do
user = User.new
user.first_name = "Joe"
user.last_name = "Mama"
user.email = "joe@test.com"
user.password = "lollipop"
user.password_confirmation = "lollipop"
user.save
valid_user = User.authenticate_with_credentials(" joe@test.com ", "lollipop")
expect(valid_user).to eq(user)
end
if 'should pass with uppsercase letters in the email' do
user = User.new
user.first_name = "Joe"
user.last_name = "Mama"
user.email = "joe@test.com"
user.password = "lollipop"
user.password_confirmation = "lollipop"
user.save
valid_user = User.authenticate_with_credentials("JOE@test.com", "lollipop")
expect(valid_user).to eq(user)
end
end
end | true |
0fbfb0aa82a42306ea2cc003b9a366e487881004 | Ruby | MaeelAli/learn_ruby | /08_book_titles/book.rb | UTF-8 | 328 | 3.5625 | 4 | [] | no_license | class Book
attr_reader :title
def title=(new_title)
except = ["and", "or", "the", "of", "in", "a", "an"]
words = new_title.split
words[0].capitalize!
words[1..-1].map do |x|
if !except.include?(x)
x.capitalize!
end
end
@title = words.join(" ")#new_title.capitalize
end
end | true |
822122c32fdd43b09731be7ca357897f7506c97e | Ruby | Piotr0007/zjazd3PD | /sito2.rb | UTF-8 | 211 | 3.3125 | 3 | [] | no_license | def sito(x=2,y)
n = x..y
o = []
p = []
for i in n
next if o.include? i
ii = i *2
while ii <= n.last do
o << ii
ii = ii +i
end
p << i unless o.include?(i)
puts i
end
end
sito(50)
| true |
521406d1bc8db99b8a1cc13f8697df9d57d8b777 | Ruby | bhenderson/indifferent_hash | /test/ar_hash.rb | UTF-8 | 1,194 | 3.25 | 3 | [
"MIT"
] | permissive | # Basic implementation of HashWithIndifferentAccess for benchmark comparison.
class ARHash < Hash
def self.[](other) self.convert(other) end
def self.convert(other)
case other
when self
other
when Hash
new.update other
when Array
other.map{|o| convert(o)}
else
other
end
end
alias_method :regular_writer, :[]= unless method_defined?(:regular_writer)
alias_method :regular_update, :update unless method_defined?(:regular_update)
def default(key = nil)
if key.is_a?(Symbol) && include?(key = key.to_s)
self[key]
else
super
end
end
def []=(key, value)
regular_writer(convert_key(key), convert_value(value))
end
def update(other_hash)
if other_hash.is_a? self.class
super(other_hash)
else
other_hash.to_hash.each_pair do |key, value|
if block_given? && key?(key)
value = yield(convert_key(key), self[key], value)
end
regular_writer(convert_key(key), convert_value(value))
end
self
end
end
def convert_key(key)
key.kind_of?(Symbol) ? key.to_s : key
end
def convert_value(value)
self.class.convert(value)
end
end
| true |
7e9f16438da222af4a1eada98df3002379060129 | Ruby | MaleehaBhuiyan/ruby-oo-practice-has-many-through-template-nyc01-seng-ft-060120 | /lib/membership.rb | UTF-8 | 274 | 2.859375 | 3 | [] | no_license | class Membership
attr_accessor :student, :club, :date
@@all = []
def initialize(student, club, id)
@student = student
@club = club
@date = date
@@all << self
end
def self.all
@@all
end
end
| true |
d07b4cbdf753e677cc48ee618992995dd9d036cb | Ruby | prwelber/practice | /read_in.rb | UTF-8 | 123 | 2.6875 | 3 | [] | no_license | File.open('./9235', "r") do |file_handle|
file_handle.each_line do |server|
server.split(" ")
puts server.max
end
end | true |
522f4188406873a9fbfb8114d55afc6c7868f24d | Ruby | amit-personal/sample-rails-app | /app/models/link.rb | UTF-8 | 1,498 | 2.65625 | 3 | [] | no_license | class Link < ApplicationRecord
belongs_to :user
has_many :comments
has_many :votes
# where(created_at: (Time.now - 24.hours)..Time.now).order(hot_score: :desc)
scope :hottest, -> { where(created_at: (Time.now - 24.hours)..Time.now).order(points: :desc) }
scope :newest, -> { order(created_at: :desc) }
validates :title,
presence: true,
uniqueness: { case_sensitive: false }
validates :url,
format: { with: %r{\Ahttps?://} },
allow_blank: true
def comment_count
comments.length
end
def upvotes
votes.sum(:upvote)
end
def downvotes
votes.sum(:downvote)
end
def calc_hot_score
points = (1 + (upvotes - downvotes))
time_ago_in_hours = ((Time.now - created_at) / 3600).round
score = hot_score_val(points, time_ago_in_hours)
update_attributes(points: points, hot_score: score)
end
def self.api_format
self.distinct.collect{ |link|
{
:id => link.id,
:title => link.title,
:points => link.points,
:username => link.user.username,
:email => link.user.email,
:source => domain_name(link.url),
:url => link.url,
:time => link.created_at.try(:strftime, "%d %b %Y")
}
}
end
def self.domain_name(url)
uri = Addressable::URI.parse(url)
return uri.host
end
private
def hot_score_val(points, time_ago_in_hours, gravity = 1.8)
(points - 1) / (time_ago_in_hours + 2) ** gravity
end
end
| true |
46243f0398e6470f4330b199c8304f97a7136158 | Ruby | MengruHan/ruby-learning | /faraday.rb | UTF-8 | 1,748 | 2.96875 | 3 | [] | no_license | #!/usr/bin/ruby
# -*- coding: UTF-8 -*-
require 'JSON'
require 'FARADAY'
require 'CSV'
require 'dotenv'
Dotenv.load ('.env')
TOKEN = ENV['TOKEN']
response = Faraday.get("https://faria.openapply.cn/api/v1/students?auth_token=#{TOKEN}&per_page=10")
puts response #将返回一个 “#<Faraday::Response:0x00007fdea703df58>”带有响应状态,标头和正文的对象
# puts response.status # =>响应状态 200
# puts response.headers # => 标头
# puts response.body # => 正文
JSON.parse (response.body),symbolize_names: true # 解析JSON字符串
info = JSON.parse (response.body) #所有的信息
# puts info.class
stud = info["students"]
# puts stud # 学生的信息
# f=File.new(File.join("/Users/ruhan/files","Test.csv"), "w+") #创建一个新的csv文件(w+ 读写模式。如果文件存在,则重写已存在的文件。如果文件不存在,则创建一个新文件用于读写。)
# file = File.open(File.join("/Users/ruhan/files","students.csv"),"w+") #file.join 返回一个字符串,由指定的项连接在一起
# file.new 方法创建一个 File 对象用于读取、写入或者读写,读写权限取决于 mode 参数
# File.open 方法创建一个新的 file 对象,并把该 file 对象赋值给文件。
column_name = stud.first.keys # 散列的第一个列
# s = CSV.generate do |csv|
# csv << column_name
# stud.each do |x| #遍历values值
# csv << x.values
# end
# end
#f.colse
# File.write(file , s) #把s写入到file(文件)里面
# file.close #File.close 方法来关闭该文件
CSV.open("/Users/ruhan/files/file.csv", "wb") do |csv|
csv << column_name
stud.each do |x| #遍历values值
csv << x.values
end
end | true |
e4304462c225acf7f9cb979e1556a9643a2549f8 | Ruby | rachaelsh/ruby-object-attributes-lab-v-000 | /lib/person.rb | UTF-8 | 183 | 2.578125 | 3 | [] | no_license | class Person
def name=(name_set)
@name = name_set
end
def name
@name
end
def job=(job_set)
@job = job_set
end
def job
@job
end
end
| true |
8f414a217adff2d3b37c2862a5e7c71a8ca21066 | Ruby | blambeau/viiite | /benchmarks/miscellaneous/sloppy_and_tidy.rb | UTF-8 | 489 | 2.8125 | 3 | [
"MIT"
] | permissive | # A benchmark pioneered by @tenderlove
# @see https://gist.github.com/1170106
class Sloppy
def sloppy; @sloppy; end
end
class Tidy
def initialize; @tidy = nil; end
def tidy; @tidy; end
end
Viiite.bench do |b|
tidy = Tidy.new
sloppy = Sloppy.new
b.variation_point :ruby, Viiite.which_ruby
b.range_over([ 1, 10, 100, 10_000, 100_000_000 ], :size) do |n|
b.report(:tidy) { n.times{ tidy.tidy } }
b.report(:sloppy) { n.times{ sloppy.sloppy } }
end
end
| true |
86bb4825cc6b6fcec656268578322a0c07a0447d | Ruby | mneumann/rubyjs | /test/test_exception.rb | UTF-8 | 826 | 3.21875 | 3 | [] | no_license | class TestException
def self.main
p "before block"
begin
p "in block"
end
p "after block"
###
begin
p "block"
rescue
p "rescue"
rescue Exception => a
p "another rescue"
p a
else
p "else"
end
p RuntimeError.new("test")
puts "before begin"
begin
puts "before raise"
raise Exception, "blah"
puts "after raise"
rescue
puts "noooo"
rescue Exception => a
p a
puts "yes"
ensure
puts "ensure"
end
puts "after begin"
puts "--"
begin
puts "abc"
raise "r"
rescue
p $!
puts "b"
ensure
puts "e"
end
#
# Test arity checks
#
begin
p("hallo".to_s(2))
rescue ArgumentError => a
p a
end
end
end
| true |
48aa7f3e91c8a828309c6bea960e90c98e9fb515 | Ruby | mozg1984/eva-lang | /spec/block_spec.rb | UTF-8 | 645 | 2.609375 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
require 'eva'
require 'parser/EvaParser'
RSpec.describe Eva do
subject(:eva_machine) { Eva.new }
describe '#eval block expression' do
let(:expr) do
'(begin
(var x 10)
(var y 20)
(+ (* x y) 30)
)'
end
let(:result) { 230 }
it { expect(expr).to be_evaluated_to(result) }
context 'when block with nested block expression' do
let(:expr) do
'(begin
(var x 10)
(begin (var x 20) x)
x
)'
end
let(:result) { 10 }
it { expect(expr).to be_evaluated_to(result) }
end
end
end
| true |
f31783cb55ab7fc6653feed7d3850a0602decf89 | Ruby | nllevin/W6D1 | /word_chainer.rb | UTF-8 | 1,612 | 3.609375 | 4 | [] | no_license | class WordChainer
attr_reader :dictionary, :all_seen_words
attr_accessor :current_words
def initialize(dictionary_file_name)
@dictionary = File.readlines(dictionary_file_name, chomp: true).to_set
end
def adjacent_words(word)
alphabet = ("a".."z").to_a
new_words = []
(0...word.length).each do |i|
alphabet.each do |letter|
new_word = word.dup
new_word[i] = letter
new_words << new_word if dictionary.include?(new_word) && new_word != word
end
end
new_words
end
def run(source, target)
@current_words = [source]
@all_seen_words = {source => nil}
explore_current_words until current_words.empty? || all_seen_words.include?(target)
build_path(target)
end
def explore_current_words
new_current_words = []
current_words.each do |current_word|
adjacent_words(current_word).each do |adjacent_word|
next if all_seen_words.include?(adjacent_word)
new_current_words << adjacent_word
all_seen_words[adjacent_word] = current_word
end
end
self.current_words = new_current_words
#new_current_words.each{|new_word| puts new_word + " <- " + all_seen_words[new_word]}
end
def build_path(target)
path = []
current_word = target
until current_word.nil?
path << current_word
current_word = @all_seen_words[current_word]
end
path.reverse
end
end | true |
8701bb092c424bfe3c06680505e593f760e5ef5e | Ruby | alakim/grains | /NHtml/BuildTagDefinitions.rb | WINDOWS-1251 | 3,422 | 2.921875 | 3 | [] | no_license | $stdout = File.open("TagDefinitions.cs", "w+")
tags = ['DIV', 'P', 'SPAN', 'A', 'PRE', 'UL', 'OL', 'LI', 'INPUT', 'TEXTAREA', 'TABLE', 'TR', 'TH', 'TD', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6']
attributes = ['class', 'width', 'height', 'border', 'cellpadding', 'cellspacing', 'align', 'valign', 'style', 'src', 'href', 'id', 'name', 'type', 'title']
puts <<END_OF_CS
// ******************** ! **************************
// * *
// * *
// * *
// * *
// * *
// * *
// * BuildTagDefinitions.rb *
// * *
// *********************************************************
using System;
using System.Collections.Generic;
using System.Text;
namespace IVC.Markup {
public static partial class Html {
END_OF_CS
tags.each do|name|
puts <<-END_OF_TAG
/// <summary> #{name}</summary>
/// <param name="content"></param>
public static string #{name.capitalize}(params object[] content) {
return Tag("#{name.downcase}", content);
}
/// <summary> #{name}</summary>
/// <param name="content"></param>
public static string #{name.capitalize}(object content) {
return #{name.capitalize}(new object[] { content });
}
END_OF_TAG
end
attributes.each do|name|
puts <<-END_OF_ATTR
/// <summary> #{name}</summary>
/// <param name="val"> </param>
public static string A_#{name}(object val) {
return Attribute("#{name}", val);
}
END_OF_ATTR
end
puts ' }'
puts <<END_OF_CS
public abstract partial class Template {
END_OF_CS
tags.each do|name|
puts <<-END_OF_TAG
/// <summary> #{name}</summary>
/// <param name="content"></param>
protected static string #{name.capitalize}(object content) {
return Html.#{name.capitalize}(content);
}
/// <summary> #{name}</summary>
/// <param name="content"></param>
protected static string #{name.capitalize}(params object[] content) {
return Html.#{name.capitalize}(content);
}
END_OF_TAG
end
puts <<END_OF_METHOD
/// <summary> </summary>
/// <param name="name"> </param>
/// <param name="val"> </param>
public static string Attribute(string name, object val) {
return Html.Attribute(name, val);
}
END_OF_METHOD
attributes.each do|name|
puts <<-END_OF_ATTR
/// <summary> #{name}</summary>
/// <param name="val"> </param>
protected static string A_#{name}(object val) {
return Html.A_#{name}(val);
}
END_OF_ATTR
end
puts ' }'
puts '}'
$stdout.close
| true |
a5f4e9e106520c2c53dc183ee66d500b9ee0ef30 | Ruby | cfoust/leetcode-problems | /problems/insert-delete-getrandom-o1-duplicates-allowed/solution.rb | UTF-8 | 894 | 3.96875 | 4 | [] | no_license | class RandomizedCollection
=begin
Initialize your data structure here.
=end
def initialize()
end
=begin
Inserts a value to the collection. Returns true if the collection did not already contain the specified element.
:type val: Integer
:rtype: Boolean
=end
def insert(val)
end
=begin
Removes a value from the collection. Returns true if the collection contained the specified element.
:type val: Integer
:rtype: Boolean
=end
def remove(val)
end
=begin
Get a random element from the collection.
:rtype: Integer
=end
def get_random()
end
end
# Your RandomizedCollection object will be instantiated and called as such:
# obj = RandomizedCollection.new()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.get_random() | true |
b121c0d4a1a4a74f35abb8a9929404f2c9e726e1 | Ruby | sho12chk/ruby_lesson | /heredoc.rb | UTF-8 | 788 | 3.390625 | 3 | [] | no_license | puts <<~TEXT
私の
名前は
神里です
TEXT
# putsを使用した場合
puts "おはよう"
puts "こんにちは"
puts "こんばんは"
# ヒアドキュメントを使用した場合
puts <<~TEXT
おはよう
こんにちは
こんばんは
TEXT
puts <<~亜亜亜
おはよう
こんにちは
こんばんは
亜亜亜
puts <<~あああ
おはよう
こんにちは
こんばんは
あああ
puts <<~aaa
おはよう
こんにちは
こんばんは
aaa
puts <<~111
おはよう
こんにちは
こんばんは
111
# putsを使用した場合(空文字で改行)
puts "おはよう"
puts ""
puts "こんにちは"
puts "こんばんは"
# ヒアドキュメントを使用した場合(Enterで改行)
puts <<~TEXT
おはよう
こんにちは
こんばんは
TEXT
| true |
a739b4daa3a4343bc3ab02404ca93e1439bf63b3 | Ruby | janebranden/launch-school-intro-to-programming | /01_basics/basics2.rb | UTF-8 | 450 | 4.65625 | 5 | [] | no_license | # basics2.rb
# Use the modulo operator, division, or a combination of both to take a 4 digit number and find the digit in the:
# 1) thousands place
# 2) hundreds place
# 3) tens place
# 4) ones place
number = 2017
thousands = number / 1000
hundreds = number % 1000 / 100
tens = number % 100 / 10
ones = number % 10
puts "number = #{number}"
puts "thousands = #{thousands}"
puts "hundreds = #{hundreds}"
puts "tens = #{tens}"
puts "ones = #{ones}" | true |
bce06254cf2c33c09d3ddc14cbeb516921e80806 | Ruby | ess/wrapomatic | /spec/wrapomatic/wrapper_spec.rb | UTF-8 | 1,702 | 2.9375 | 3 | [
"MIT"
] | permissive | require 'spec_helper'
module Wrapomatic
describe Wrapper do
let(:dummy) {Object.new}
let(:text) {"This is some text to wrap. It is intentionally long and contains a few newlines\nto ensure that all of the features of the wrapper\nwork\nas\nexpected."}
describe '.new' do
it 'has a default indentation level' do
expect(described_class.new(text).indents).to eql(0)
expect(described_class.new(text, 1).indents).to eql(1)
end
it 'has a default column cutoff' do
expect(described_class.new(text).columns).to eql(80)
expect(described_class.new(text, 0, 10).columns).to eql(10)
end
end
describe '#lines' do
let(:wrapper) {described_class.new(text)}
let(:lines) {wrapper.lines}
it 'is an array of strings' do
expect(lines).to be_a(Array)
lines.each do |line|
expect(line).to be_a(String)
end
end
it 'contains no line that is bigger than the cutoff' do
lines.each do |line|
expect(line.length > wrapper.columns).to eql(false)
end
end
context 'when given text that contains newlines' do
let(:lines_before) {['line 1', 'line 2', 'line 3']}
let(:text) {lines_before.join("\n")}
it 'has at least the same number of lines as the input' do
expect(lines.length >= lines_before.length).to eql(true)
end
end
end
describe '#wrapped' do
let(:wrapper) {described_class.new(text)}
let(:lines) {wrapper.lines}
let(:wrapped) {wrapper.wrapped}
it 'is lines joined by newlines' do
expect(wrapped).to eql(lines.join("\n"))
end
end
end
end
| true |
3f592aaa55605c16d1a2f2919504094380f4ef6e | Ruby | FDA/precisionFDA | /app/helpers/space_reports_helper.rb | UTF-8 | 1,315 | 2.578125 | 3 | [
"CC0-1.0"
] | permissive | module SpaceReportsHelper
def generate_report(user, data, filters)
"""
<h3>Interaction Report</h3>
<div>Report date: #{Date.today.strftime("%m/%d/%Y")}</div>
<div>Report by: #{user.full_name}</div>
<br>
<div>Filters</div>
<div>Start date: #{filters[:dates][:start_date]}</div>
<div>End date: #{filters[:dates][:end_date]}</div>
<div>Users: #{filters[:users] || "all"}</div>
#{content_objects(data)}
"""
end
def content_objects(data)
result = ""
data.each do |content_type|
object_type = content_type[0]
objects = content_type[1]
raw = """
<h5>#{object_type.upcase}</h5>
<div>Items found: #{objects.size}</div>
<br>
<table>
#{content_object(objects)}
</table>
"""
result.concat(raw)
end
result
end
def content_object(data)
result = ""
data.each do |item|
raw = """
<tr>
<td>
<div>User: #{item[:user_fullname]}</div>
</td>
<td>
<div>Created at: #{item[:created_at]}</div>
</td>
</tr>
<tr>
<td>
<div>#{item[:object_name]}</div>
</td>
</tr>
"""
result.concat(raw)
end
result
end
end
| true |
b9b7beae87e90212f15ef3606612233c7e402a96 | Ruby | svenfuchs/gem-release | /lib/gem/release/context.rb | UTF-8 | 1,092 | 2.515625 | 3 | [
"MIT",
"MPL-2.0"
] | permissive | require 'gem/release/context/gem'
require 'gem/release/context/git'
require 'gem/release/context/paths'
require 'gem/release/context/ui'
module Gem
module Release
class Context
attr_accessor :config, :gem, :git, :ui
def initialize(*args)
opts = args.last.is_a?(Hash) ? args.pop : {}
name = args.shift
@config = Config.new
@gem = Gem.new(name || File.basename(Dir.pwd))
@git = Git.new
@ui = Ui.new(opts)
end
def run(cmd)
system(cmd)
end
def gem_cmd(cmd, *args)
::Gem::Commands.const_get("#{cmd.to_s.capitalize}Command").new.invoke(*args.flatten)
# TODO what's with the return value? maybe add our own abstraction that can check the result?
true
end
def in_dirs(args, opts, &block)
Paths::ByNames.new(args, opts).in_dirs(&block)
end
def in_gem_dirs(args, opts, &block)
Paths::ByGemspecs.new(args, opts).in_dirs(&block)
end
def abort(str)
ui.error(str)
exit 1
end
end
end
end
| true |
7fb526b4e6e0ac270ae15bfc8e9744ce2d3fe14b | Ruby | jasmarc/kmeans | /lib/tfidf.rb | UTF-8 | 3,705 | 3.453125 | 3 | [] | no_license | require "array_hacks.rb"
require "string_hacks.rb"
class TFIDF
attr_reader :word_list, :term_document_matrix
def initialize(dir_glob, stoplist)
@word_list = Hash.new # This is our main wordlist
@documents = Hash.new # Let's keep track of each docs' sizes
@stop_list = File.read(stoplist).split # Words that don't count
Dir[dir_glob].each do |document|
# Let's read that document and get the words
words_in_document = File.read(document).split_with_index(' ')
# We want to remember this document's size. We'll need it later.
@documents[document] = words_in_document.size
# For every word in this document
words_in_document.each do |word, location|
word.stem! # we do some basic stemming
# Let's add it to our "word list"
# along with what document it came from
# and where in the document we saw it
add(word, document, location) unless word_does_not_belong(word)
end
end
@words_hash = create_words_hash()
@term_document_matrix = compute_term_document_matrix
end
def compute_term_document_matrix
words_array = @word_list.sort
# words array is like this:
# [["brown", {"./test2/file01.txt"=>[6], "./test2/file02.txt"=>[4]}],
# ["dog", {"./test2/file01.txt"=>[12], "./test2/file02.txt"=>[0]}],
# ["jason", {"./test2/file02.txt"=>[10]}],
# ["quick", {"./test2/file01.txt"=>[0]}]]
td_matrix = Array.new(@documents.size) { Array.new(words_array.size) { 0 } }
threads = []
words_array.each do |entry|
word = entry[0]
docs = entry[1].keys.map { |doc| doc }
docs.each do |doc|
threads << Thread.new(word, doc) do |w, d|
td_matrix[doc_to_num(d)][word_to_num(w)] = tfidf(w, d)
end
end
end
threads.each {|t| t.join}
return td_matrix
end
def word_to_num(s)
@words_hash[s]
end
def num_to_word(n)
@words_hash.invert[n]
end
def doc_to_num(s)
s.scan(/\d\d/).last.to_i-1
end
def num_to_doc(n)
"file%02d.txt" % (n+1)
end
:private
def create_words_hash
words = @word_list.sort.map { |x| x.first }
words.to_hash_keys { |x| words.index(x) }
end
# When we add an entry to a wordlist, we want to know
# 1. The word itself
# 2. What document it came from
# 3. Where in that document is the word located
def add(word, document, location)
@word_list[word] = Hash.new if @word_list[word].nil?
@word_list[word][document] = Array.new if @word_list[word][document].nil?
@word_list[word][document] << location
end
# Let's not include empty, null, or words in the stop list
def word_does_not_belong(word)
word.nil? || word.empty? || @stop_list.index(word)
end
# document frequency: the number of documents in the collection in which the term occurs
def df(t)
@word_list[t].size
end
# inverse document frequency: idf is a measure of the informativeness of the term.
# We use [log(N/dft)] instead of [N/dft] to “dampen” the
# effect of idf.
def idf(t)
Math.log10(@documents.size.to_f/df(t).to_f)
end
# term frequency: number of times that t occurs in d
def tf(t, d)
begin
raise "wordlist doesn't contain #{t}" if @word_list[t].nil?
raise "#{t} doesn't appear in #{d}" if @word_list[t][d].nil?
@word_list[t][d].size
rescue Exception => e
raise "Error in tf: #{t}, #{d} #{e}\n"
end
end
# log frequency weight: The log frequency weight of term t in d
def w(t, d)
tf(t, d) > 0 ? 1 + Math.log10(tf(t, d)) : 0
end
# The tf.idf weight of a term is the product of its
# tf weight and its idf weight.
def tfidf(t, d)
w(t, d) * idf(t)
end
end | true |
00bd28a3fdf53399b7dada1f8497f4999827cd2f | Ruby | anime-memes/json-csv-parser-task | /checker.rb | UTF-8 | 1,204 | 3.5625 | 4 | [] | no_license | # class that checks data for errors and deletes hashes with errors
class Checker
class << self
def check_data(file_data)
errors = []
file_data.each do |data_hash|
errors << check_name(data_hash)
errors << check_cost(data_hash)
end
# delete hashes that contain errors
checked_data = file_data.delete_if { |data_hash| check_name(data_hash) || check_cost(data_hash) }
[errors.compact, checked_data]
end
private
# name field should be present and its value should be a String
def check_name(hash)
return '"name" doesn\'t exist' if !(hash.keys.include?('name')) || (hash.keys.include?('name') && hash['name'].nil?)
return '"name" isn\'t a String' unless hash['name'].is_a?(String)
end
# cost field should be present and its value should be a positive Numeric
def check_cost(hash)
return '"cost" doesn\'t exist' if !(hash.keys.include?('cost')) || (hash.keys.include?('cost') && hash['cost'].nil?)
return '"cost" isn\'t a Numeric' unless hash['cost'].is_a?(Numeric)
return '"cost" isn\'t an integer' unless hash['cost'].integer?
return '"cost" is zero' if hash['cost'].zero?
return '"cost" is negative' if hash['cost'].negative?
end
end
end | true |
213140d0adb0e6c871a819fd15ce3912325122aa | Ruby | mcousin/tippspiel | /app/models/open_liga_db_league.rb | UTF-8 | 4,044 | 2.578125 | 3 | [] | no_license | require "savon"
require "fuzzystringmatch"
class OpenLigaDbLeague < ActiveRecord::Base
attr_accessible :league_id, :league, :oldb_league, :oldb_season
belongs_to :league
SERVICE_URL = "http://www.openligadb.de/Webservices/Sportsdata.asmx?WSDL"
def import_matches
unless (matchdays_aligned? and teams_aligned?)
Rails.logger.error("Failed to import matches: Matchday descriptions are not aligned.") unless matchdays_aligned?
Rails.logger.error("Failed to import matches: Team names are not aligned.") unless teams_aligned?
return
end
structs_for(:matches).each do |struct|
league.reload
home_team = league.teams.find_by_name(struct[:name_team1]) || league.teams.create(name: struct[:name_team1])
away_team = league.teams.find_by_name(struct[:name_team2]) || league.teams.create(name: struct[:name_team2])
matchday = league.matchdays.find_or_create_by_description(struct[:group_name])
match = matchday.matches.find_or_create_by_home_team_id_and_away_team_id(home_team.id, away_team.id)
update_match(match, struct)
end
end
def update_matches
league.matches.each do |match|
struct = structs_for(:matches).find{|struct| struct[:name_team1] == match.home_team.name and
struct[:name_team2] == match.away_team.name }
if struct
update_match(match, struct)
else
Rails.logger.error("Failed to update match '#{match}' (id=#{match.id}): Team names are not aligned.")
end
end
end
def refresh!
refresh_structs_for :matches
end
private
def request(method_name, body = {})
@client ||= Savon.client(SERVICE_URL)
@client.request(method_name, body: body).body["#{method_name}_response".to_sym]["#{method_name}_result".to_sym]
end
def structs_for(resource)
refresh_structs_for(resource) unless instance_variable_defined?("@structs_for_#{resource}")
instance_variable_get("@structs_for_#{resource}")
end
def refresh_structs_for(*args)
args.each do |resource|
case resource
when :teams
structs = request(:get_teams_by_league_saison, league_shortcut: oldb_league, league_saison: oldb_season)[:team]
when :matchdays
structs = request(:get_avail_groups, league_shortcut: oldb_league, league_saison: oldb_season)[:group]
when :matches
structs = request(:get_matchdata_by_league_saison, league_shortcut: oldb_league, league_saison: oldb_season)[:matchdata]
end
instance_variable_set("@structs_for_#{resource}", structs)
end
end
def teams_aligned?
team_names = structs_for(:teams).map{|struct| struct[:team_name]}
league.teams.all?{|team| team_names.include?(team.name)}
end
def matchdays_aligned?
matchday_descriptions = structs_for(:matchdays).map{|struct| struct[:group_name]}
league.matchdays.all?{|matchday| matchday_descriptions.include?(matchday.description)}
end
def update_match(match, struct)
match.assign_attributes(score_a: convert_score(struct[:points_team1]),
score_b: convert_score(struct[:points_team2]),
match_date: struct[:match_date_time_utc],
has_ended: struct[:match_is_finished] )
if match.changed?
if match.save
Rails.logger.info("Match '#{match}' successfully updated.")
else
Rails.logger.error("Failed to update match '#{match}' (id=#{match.id}): #{match.errors.full_messages}")
end
end
end
# OLDB sets empty scores to -1, which is converted to nil by this helper method
def convert_score(score)
return nil if score.to_i < 0
score
end
# not needed atm, could be useful for auto-align team names or matchday descriptions
def string_distance(str1, str2)
jarow = FuzzyStringMatch::JaroWinkler.create(:pure)
jarow.getDistance(str1, str2)
end
end
| true |
b5e458100083da16cc000ce4db7d5f8767c24e9b | Ruby | drewundone/development | /cable.rb | UTF-8 | 206 | 3.046875 | 3 | [] | no_license | COMPOUND = 4332
COMPOUND2 = 565
puts 'What is the diameter of the first cable?'
diameter = gets.chomp
puts 'What is the compound?'
answer = gets.chomp
puts 'Please enter COMPOUND1 or COMPOUND2'
end
| true |
5433b3c805c076a8f3c653afcceb30890d2e81f3 | Ruby | slc21/ICS-Course | /ch13/orangeTree.rb | UTF-8 | 1,580 | 4.4375 | 4 | [] | no_license | class Tree
def initialize name
@name = name
@height = 0
@yearPass = 0
@oranges = 0
puts "#{@name} has sprouted"
puts "Type 'help' to begin"
end
def oneYearPass
@height = @height + rand(4) + rand(2)
puts "One year passes..."
@yearPass = @yearPass + 1
if @height >= rand(21)
@oranges = @oranges + rand(21)
end
end
def height
puts "#{@name} is #{@height} feet tall"
end
def age
puts "#{@name} is #{@yearPass} years old"
if @yearPass >= rand(21)
puts "#{@name} has died."
exit
end
end
def orangeCount
if @oranges == 0
puts "No oranges this year"
else
puts "#{@name} has #{@oranges} oranges"
end
end
def pickOrange
puts "There are #{@oranges} oranges."
if @oranges > 0
puts "How many would you like?"
num = gets.chomp
@oranges = @oranges - num.to_i
puts "You have taken #{num} oranges"
else
puts "No oranges this year"
end
end
end
puts "Welcome to the Garden of Eden, here's your tree. What will you name it?"
name = gets.chomp
plant = Tree.new name
while true
input = gets.chomp
if input == "next"
plant.oneYearPass
end
if input == "size"
plant.height
end
if input == "age"
plant.age
end
if input == "fruit"
plant.orangeCount
end
if input == "gimme"
plant.pickOrange
end
if input == "help"
puts "commands are next, size, age, fruit, and gimme. Press ENTER to exit"
end
if input == ''
puts "Come back again!"
exit
end
end
| true |
54db203d9c9c5f5319ad7f3345b5270f541b8436 | Ruby | sangster/mocapi | /lib/mocapi/models/amortization_period.rb | UTF-8 | 505 | 3.046875 | 3 | [] | no_license | module Mocapi
module Models
class AmortizationPeriod
VALID_RANGE = (5..25).freeze
# @param years [Integer] The length of the amortization period, in years
def initialize(years)
unless VALID_RANGE.include?(years)
raise ArgumentError,
format('Amortization of %d years is not within valid range: %p',
years, VALID_RANGE)
end
@years = years
end
def to_i
@years
end
end
end
end
| true |
8e9e0fd004b97b739d06999f6f5c9a0cca41ae60 | Ruby | gardnerl-bit/intro_Ruby_bookLS | /ch10_exercises/exercise4.rb | UTF-8 | 92 | 3.203125 | 3 | [] | no_license | arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
#append
arr.push(11)
#prepend
arr.unshift(0)
p arr
| true |
4f44709327ffe10e88851d2dd534069917ca7d02 | Ruby | BurdetteLamar/rdoc_toc | /bin/rdoc_toc | UTF-8 | 1,049 | 2.671875 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env ruby
require 'rdoc_toc'
# Confirm that we're in a git project.
git_dir = `git rev-parse --show-toplevel`.chomp
unless $?.success?
message = <<EOT
rdoc_toc must run inside a .git project.
That is, the working directory one of its parents must be a .git directory.
EOT
raise RuntimeError.new(message)
end
# Each command foo has a corresponding Ruby executable _foo.
def command_keywords
dir_path = File.dirname(__FILE__)
dirs = Dir.entries(dir_path)
command_file_names = dirs.select{|x| x.start_with?('_') }
command_file_names.collect {|x| x.sub(/^_/, '')}
end
def usage
puts <<-EOT
Usage: rdoc_toc command [options] [args]
where
* Command is one of #{command_keywords.inspect}.
EOT
exit
end
command_keyword = ARGV[0]
unless command_keywords.include?(command_keyword)
usage
end
bindir = File.dirname(__FILE__)
bin_file_path = File.absolute_path(File.join(
bindir,
'_' + command_keyword,
))
command = "ruby #{bin_file_path} #{ARGV.join(' ')}"
system(command)
| true |
2b171bbc8c828d1031bc97aaeb9dde39d06e83f2 | Ruby | donghL-dev/Study-RubyOnRails | /Ruby/test.rb | UTF-8 | 266 | 3.796875 | 4 | [] | no_license | list = []
a = gets.chomp
b = a.to_i #정수로 형변환 시켜줌.
for i in 1..b
print "#{i}번째 숫자를 입력하세요 :"
number = gets.chomp
list.push(number)
end
list.each do |i|
puts "당신이 입력한 숫자는 #{i}입니다."
end
| true |
8309bafc66b651cd9541f00dc747d166bf91dcaa | Ruby | LeonardoRO/chemistrykit-examples | /google/formulas/lib/formula.rb | UTF-8 | 986 | 2.953125 | 3 | [] | no_license | # Encoding: utf-8
# This is where you can define generic helper functions
# that are inhereted by your formulas.
# The ones below are borrowed from:
# http://elemental-selenium.com/tips/9-use-a-base-page-object
class Formula < ChemistryKit::Formula::Base
attr_reader :driver
def initialize(driver)
@driver = driver
end
def visit(url='/')
driver.get(ENV['BASE_URL'] + url)
end
def find(locator)
driver.find_element locator
end
def clear(locator)
find(locator).clear
end
def type(locator, input)
find(locator).send_keys input
end
def click_on(locator)
find(locator).click
end
def displayed?(locator)
driver.find_element(locator).displayed?
true
rescue Selenium::WebDriver::Error::NoSuchElementError
false
end
def text_of(locator)
find(locator).text
end
def title
driver.title
end
def wait_for(seconds=5)
Selenium::WebDriver::Wait.new(:timeout => seconds).until { yield }
end
end
| true |
8e3ae21d3453699201f1a9784e34b81bb41b064f | Ruby | JeanTimothee/TCC | /app/controllers/students_controller.rb | UTF-8 | 1,072 | 2.515625 | 3 | [] | no_license | class StudentsController < ApplicationController
def index
@lessons = Lesson.all
@students = Student.all
# search params
@students = Student.search_by_first_last_name(params[:query]) if params[:query].present?
if params[:level].present?
level_query = params[:level].map do |level|
LEVEL_NUMBER[level]
end
@students = @students.where(level: level_query)
end
@students = @students.where(age: params[:age]) if params[:age].present?
@students = Student.all if @students.count == 0
# filters collections
if @students.count > 1
@ages = @students.map do |student|
student.age
end
@ages = @ages.uniq.sort!
nb_levels = @students.map do |student|
student.level
end
nb_levels = nb_levels.uniq.filter { |item| item != nil }
@levels = nb_levels.sort!.map do |level|
NUMBER_LEVEL[level]
end
@students = @students.order(:last_name)
else
@ages = @students[0].age
@levels = NUMBER_LEVEL[@students[0].level]
end
end
end
| true |
c343a33f41182c29431191cf3e6294325d5ffef2 | Ruby | mikeblatter/automation_object | /lib/automation_object/blue_print/composite/hook_action.rb | UTF-8 | 2,011 | 2.515625 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
# Require parent class
require_relative 'base'
require_relative 'hook_element_requirements'
module AutomationObject
module BluePrint
module Composite
# HookAction composite class
class HookAction < Base
# Get the order to run the hook in
# @return [Array<Symbol>] list of hook methods to run in given order
def hook_order
adapter.hook_order
end
# Get length of hook actions
# @return [Integer] length of hook actions
def length
adapter.length
end
# See if hook actions are empty
# @return [Boolean] if hook actions are empty
def empty?
adapter.empty?
end
# @return [Symbol, nil] screen to change to
def change_screen
adapter.change_screen
end
# @return [Symbol, nil] new screen
def new_screen
adapter.new_screen
end
# @return [Boolean]
def close_screen
adapter.close_screen
end
# @return [Boolean]
def close_modal
adapter.close_modal
end
# @return [Boolean]
def change_to_previous_screen
adapter.change_to_previous_screen
end
# @return [Symbol, nil]
def show_modal
adapter.show_modal
end
# @return [Array]
def possible_screen_changes
adapter.possible_screen_changes
end
# @return [Boolean] reset the screen?
def reset_screen
adapter.reset_screen
end
# @return [Numeric] amount of time to sleep
def sleep
adapter.sleep
end
# Custom method for array of children instead of Hash
# @return [Array<AutomationObject::BluePrint::Composite::HookElementRequirements>] array of wait for element children
def wait_for_elements
adapter.wait_for_elements
end
end
end
end
end
| true |
705432f547d8f3d4ec20eb4a9d6120e9aa2a396d | Ruby | BinetLoisir/FlipperMap | /app/controllers/map_controller.rb | UTF-8 | 3,597 | 2.640625 | 3 | [] | no_license | class MapController < ApplicationController
def map
@latitude = Bar.first[:latitude]
@longitude = Bar.first[:longitude]
google_bar_list = Google.all.map do |bar|
stars = [[(bar[:rating].to_f - 0.01) * 2 - 5, 3].min, 0].max.to_i
pbs = 0
description = "<b>#{bar[:name]}"
description += " (#{bar[:rating]}/5)" if bar[:rating].to_f > 0
description += '</b><br>'
cheap_bar = CheapBar.find_by(google_id: bar[:place_id])
if cheap_bar
description += "#{cheap_bar[:price]} € en happy hour"
description += cheap_bar[:original_price] > 0 ? " (#{cheap_bar[:original_price]} € sinon)<br>" : "<br>"
description += "#{cheap_bar[:happy_hour]}" unless cheap_bar[:happy_hour] == "Happy hour: h - h"
description += '<br>'
end
pinball_bar = Bar.find_by(google_id: bar[:place_id])
if pinball_bar
pinball_bar.location.map do |location|
description += "<a href=\"#{location.flip[:url]}\" class=\"hidden-link-black\">#{location.flip[:name]}"
description += " (#{location.flip[:rating]}/10)" if location.flip[:rating].to_f > 0
description += '<br></a>'
end
pbs = [pinball_bar.location.size, 2].min
end
icon_url = "/assets/#{stars}_stars_#{pbs}_pinballs.png"
{
"lat" => bar[:latitude].to_s,
"lng" => bar[:longitude].to_s,
"picture" => {
"url" => icon_url,
"width" => 70,
"height" => 70
},
"infowindow" => description
}
end
first_bar_list = Bar.all.map do |bar|
next if bar[:google_id]
description = "<a href=\"#{bar[:url]}\" class=\"hidden-link-black\"><b>#{bar[:name]}"
description += " (#{bar.google_rating}/5)" if bar.google_rating.to_f > 0
description += '</b></a><br>'
bar.location.map do |location|
description += "<a href=\"#{location.flip[:url]}\" class=\"hidden-link-black\">#{location.flip[:name]}"
description += " (#{location.flip[:rating]}/10)" if location.flip[:rating].to_f > 0
description += '<br></a>'
end
stars = [[(bar.google_rating.to_f - 0.01) * 2 - 5, 3].min, 0].max.to_i
pbs = [bar.location.size, 2].min
icon_url = "/assets/#{stars}_stars_#{pbs}_pinballs.png"
{
"lat" => bar[:latitude].to_s,
"lng" => bar[:longitude].to_s,
"picture" => {
"url" => icon_url,
"width" => 70,
"height" => 70
},
"infowindow" => description
}
end.compact
second_bar_list = CheapBar.all.map do |bar|
next if bar[:google_id]
description = "<b>#{bar[:name]}"
description += " (#{bar.google_rating}/5)" if bar.google_rating.to_f > 0
description += '</b><br>'
description += "#{bar[:price]} € en happy hour"
description += bar[:original_price] > 0 ? " (#{bar[:original_price]} € sinon)<br>" : "<br>"
description += "#{bar[:happy_hour]}" unless bar[:happy_hour] == "Happy hour: h - h"
stars = [[(bar.google_rating.to_f - 0.01) * 2 - 5, 3].min, 0].max.to_i
icon_url = "/assets/#{stars}_stars_0_pinballs.png"
{
"lat" => bar[:latitude].to_s,
"lng" => bar[:longitude].to_s,
"picture" => {
"url" => icon_url,
"width" => 70,
"height" => 70
},
"infowindow" => description
}
end.compact
@bar_list = google_bar_list.concat(first_bar_list.concat(second_bar_list)).to_json
end
def info
end
def pinballs
end
def contact
end
end
| true |
e4641d68d8f5376cc0e9ca99d40160e2cc84cb4d | Ruby | sampreet-chawla/GA-unit4-ruby-intro-to-ruby | /instrructor_examples/fizz_buzz.rb | UTF-8 | 744 | 3.984375 | 4 | [] | no_license | # https://repl.it/@jkeohan/Ruby-FizzBuzz-Solutions
# WHILE LOOP
# i = 0
# while i < 35 do
# if i % 3 == 0 && i % 5 == 0
# puts "fizz buzz #{i}"
# elsif i % 3 == 0
# puts "fizz " + i.to_s
# elsif i % 5 == 0
# puts "buzz"
# else
# puts i
# end
# i += 1
# end
# FOR IN LOOP
# for i in 0..35
# if i % 3 == 0 && i % 5 == 0
# puts "fizz buzz #{i}"
# elsif i % 3 == 0
# puts "fizz " + i.to_s
# elsif i % 5 == 0
# puts "buzz"
# end
# end
def fizz_buzz2 max_value
0.upto(max_value - 1) do |i|
case true
when (i % 3 == 0) && (i % 5 == 0)
puts "fizzbuzz"
when i % 3 == 0
puts "fizz"
when i % 5 == 0
puts "buzz"
else
# puts i
end
end
end
fizz_buzz2 35
| true |
92727ca11acb03e7a69b57acdfd71b459714aea2 | Ruby | jemyers/classroom | /vendor/bundle/ruby/2.6.0/gems/dependency_checker-0.2.0/bin/dependency-checker | UTF-8 | 1,854 | 2.640625 | 3 | [] | no_license | #!/usr/bin/env ruby
require 'optparse'
require 'dependency_checker'
require 'json'
options = {}
OptionParser.new { |opts|
opts.on('-o module,version', '--override module,version', Array, 'Forge name of module and semantic version to override') do |override|
options[:override] = override
end
opts.on('-c', '--current', 'Extract override version from metadata.json inside current working directory') do |current_override|
options[:current_override] = current_override
end
opts.on('-v', '--[no-]verbose', 'Run verbosely') do |verbose|
options[:verbose] = verbose
end
opts.on('-h', '--help', 'Display help') do
puts opts
exit
end
}.parse!
# Determine which modules to pass on to runner
managed_modules = nil
unless ARGV.empty?
# If length == 1, only pass first argument, else pass the array of metadata.json files
managed_modules = ((ARGV.length == 1) ? ARGV[0] : ARGV)
end
# Raise error if both :override and :current_override are specified
if options[:override] && options[:current_override]
raise OptionParser::InvalidOption, 'You can not select both override and current override options'
end
# If :current_override is specified, retrieve name and version of module in current working directory
if options[:current_override]
metadata_json = JSON.parse(File.read('metadata.json'))
module_name = metadata_json['name'].sub('-', '/')
module_version = metadata_json['version']
override_check = metadata_json.is_a?(Hash) && !metadata_json.empty?
options[:override] = [module_name, module_version] if override_check
raise OptionParser::InvalidOption, 'Unable to find local metadata.json in current working directory' unless override_check
end
# Default :verbose to false
options[:verbose] ||= false
DependencyChecker::Runner.run_with_args(managed_modules, options[:override], options[:verbose])
| true |
386edeb80a1f0309ce43537a9832b15756a45100 | Ruby | jeffkreeftmeijer/guidedown | /bin/guidedown | UTF-8 | 691 | 2.578125 | 3 | [] | no_license | #!/usr/bin/env ruby
require_relative '../lib/guidedown'
require 'optparse'
options = {}
OptionParser.new do |opts|
opts.banner = "Usage: guidedown [options]"
opts.on("-h", "--help", "Show this message") do
puts opts
exit
end
opts.on("--html-code-blocks", "Wrap code blocks in `<code>` and `<pre>` tags instead of backticks.") do
options[:html_code_blocks] = true
end
opts.on("--no-filenames", "Remove filenames from code camples.") do
options[:no_filenames] = true
end
opts.on("--sticky-info-strings", "Remove leading spaces from info strings.") do
options[:sticky_info_strings] = true
end
end.parse!
puts Guidedown.new(ARGF.read, options).to_s
| true |
ce7975863a8b5361a22c0a09ac743fc6d32c20f8 | Ruby | tajimata/freemarket_sample_57a | /db/fixtures/01_Category.rb | UTF-8 | 12,184 | 2.609375 | 3 | [] | no_license | # 00 親カテゴリー作成
# 01 レディースの子カテゴリー作成
# 02 メンズの子カテゴリー作成
# 03 ベビー・キッズの子カテゴリー作成
# 04 インテリア・住まい・小物の子カテゴリー作成
# 05 本・音楽・ゲームの子カテゴリー作成
# 06 おもちゃ・ホビー・グッズの子カテゴリー作成
# 07 コスメ・香水・美容の子カテゴリー作成
# 08 家電・スマホ・カメラの子カテゴリー作成
# 09 スポーツ・レジャーの子カテゴリー作成
# 10 ハンドメイドの子カテゴリー作成
# 11 チケットの子カテゴリー作成
# 12 自動車・オートバイの子カテゴリー作成
# 13 その他の子カテゴリー作成
# 00 親カテゴリー作成
Category.seed(:id,
{id: 1, name: "レディース"},
{id: 2, name: "メンズ"},
{id: 3, name: "ベビー・キッズ"},
{id: 4, name: "インテリア・住まい・小物"},
{id: 5, name: "本・音楽・ゲーム"},
{id: 6, name: "おもちゃ・ホビー・グッズ"},
{id: 7, name: "コスメ・香水・美容"},
{id: 8, name: "家電・スマホ・カメラ"},
{id: 9, name: "スポーツ・レジャー"},
{id: 10, name: "ハンドメイド"},
{id: 11, name: "チケット"},
{id: 12, name: "自動車・オートバイ"},
{id: 13, name: "その他"},
)
# 01 レディースの子カテゴリー作成
parent_id = Category.find_by(name: "レディース").id
Category.seed(:id,
{id: 14, name: "トップス", ancestry: parent_id },
{id: 15, name: "ジャケット/アウター", ancestry: parent_id },
{id: 16, name: "パンツ", ancestry: parent_id },
{id: 17, name: "スカート", ancestry: parent_id },
{id: 18, name: "ワンピース", ancestry: parent_id },
{id: 19, name: "靴", ancestry: parent_id },
{id: 20, name: "ルームウェア/パジャマ", ancestry: parent_id },
{id: 21, name: "レッグウェア", ancestry: parent_id },
{id: 22, name: "帽子", ancestry: parent_id },
{id: 23, name: "バッグ", ancestry: parent_id },
{id: 24, name: "アクセサリー", ancestry: parent_id },
{id: 25, name: "ヘアアクセサリー", ancestry: parent_id },
{id: 26, name: "小物", ancestry: parent_id },
{id: 27, name: "時計", ancestry: parent_id },
{id: 28, name: "ウィッグ/エクステ", ancestry: parent_id },
{id: 29, name: "浴衣/水着", ancestry: parent_id },
{id: 30, name: "スーツ/フォーマル/ドレス", ancestry: parent_id },
{id: 31, name: "マタニティ", ancestry: parent_id },
{id: 32, name: "その他", ancestry: parent_id },
)
# 02 メンズの子カテゴリー作成
parent_id = Category.find_by(name: "メンズ").id
Category.seed(:id,
{id: 33, name: "トップス", ancestry: parent_id },
{id: 34, name: "ジャケット/アウター", ancestry: parent_id },
{id: 35, name: "パンツ", ancestry: parent_id },
{id: 36, name: "靴", ancestry: parent_id },
{id: 37, name: "バッグ", ancestry: parent_id },
{id: 38, name: "スーツ", ancestry: parent_id },
{id: 39, name: "帽子", ancestry: parent_id },
{id: 40, name: "アクセサリー", ancestry: parent_id },
{id: 41, name: "小物", ancestry: parent_id },
{id: 42, name: "時計", ancestry: parent_id },
{id: 43, name: "水着", ancestry: parent_id },
{id: 44, name: "レッグウェア", ancestry: parent_id },
{id: 45, name: "アンダーウェア", ancestry: parent_id },
{id: 46, name: "その他", ancestry: parent_id },
)
# 03 ベビー・キッズの子カテゴリー作成
parent_id = Category.find_by(name: "ベビー・キッズ").id
Category.seed(:id,
{id: 47, name: "ベビー服(女の子用) ~95cm", ancestry: parent_id },
{id: 48, name: "ベビー服(男の子用) ~95cm", ancestry: parent_id },
{id: 49, name: "ベビー服(男女兼用) ~95cm", ancestry: parent_id },
{id: 50, name: "キッズ服(女の子用) 100cm~", ancestry: parent_id },
{id: 51, name: "キッズ服(男の子用) 100cm~", ancestry: parent_id },
{id: 52, name: "キッズ服(男女兼用) 100cm~", ancestry: parent_id },
{id: 53, name: "キッズ靴", ancestry: parent_id },
{id: 54, name: "子ども用ファッション小物", ancestry: parent_id },
{id: 55, name: "おむつ/トイレ/バス", ancestry: parent_id },
{id: 56, name: "外出/移動用品", ancestry: parent_id },
{id: 57, name: "授乳/食事", ancestry: parent_id },
{id: 58, name: "ベビー家具/寝具/室内用品", ancestry: parent_id },
{id: 59, name: "おもちゃ", ancestry: parent_id },
{id: 60, name: "行事/記念品", ancestry: parent_id },
{id: 61, name: "その他", ancestry: parent_id },
)
# 04 インテリア・住まい・小物の子カテゴリー作成
parent_id = Category.find_by(name: "インテリア・住まい・小物").id
Category.seed(:id,
{id: 62, name: "キッチン/食器", ancestry: parent_id },
{id: 63, name: "ベッド/マットレス", ancestry: parent_id },
{id: 64, name: "ソファ/ソファベッド", ancestry: parent_id },
{id: 65, name: "椅子/チェア", ancestry: parent_id },
{id: 66, name: "机/テーブル", ancestry: parent_id },
{id: 67, name: "収納家具", ancestry: parent_id },
{id: 68, name: "ラグ/カーペット/マット", ancestry: parent_id },
{id: 69, name: "カーテン/ブラインド", ancestry: parent_id },
{id: 70, name: "ライト/照明", ancestry: parent_id },
{id: 71, name: "寝具", ancestry: parent_id },
{id: 72, name: "インテリア小物", ancestry: parent_id },
{id: 73, name: "季節/年中行事", ancestry: parent_id },
{id: 74, name: "その他", ancestry: parent_id },
)
# 05 本・音楽・ゲームの子カテゴリー作成
parent_id = Category.find_by(name: "本・音楽・ゲーム").id
Category.seed(:id,
{id: 75, name: "本", ancestry: parent_id },
{id: 76, name: "漫画", ancestry: parent_id },
{id: 77, name: "雑誌", ancestry: parent_id },
{id: 78, name: "CD", ancestry: parent_id },
{id: 79, name: "DVD/ブルーレイ", ancestry: parent_id },
{id: 80, name: "レコード", ancestry: parent_id },
{id: 81, name: "テレビゲーム", ancestry: parent_id },
)
# 06 おもちゃ・ホビー・グッズの子カテゴリー作成
parent_id = Category.find_by(name: "おもちゃ・ホビー・グッズ").id
Category.seed(:id,
{id: 82, name: "おもちゃ", ancestry: parent_id },
{id: 83, name: "タレントグッズ", ancestry: parent_id },
{id: 84, name: "コミック/アニメグッズ", ancestry: parent_id },
{id: 85, name: "トレーディングカード", ancestry: parent_id },
{id: 86, name: "フィギュア", ancestry: parent_id },
{id: 87, name: "楽器/器材", ancestry: parent_id },
{id: 88, name: "コレクション", ancestry: parent_id },
{id: 89, name: "ミリタリー", ancestry: parent_id },
{id: 90, name: "美術品", ancestry: parent_id },
{id: 91, name: "アート用品", ancestry: parent_id },
{id: 92, name: "その他", ancestry: parent_id },
)
# 07 コスメ・香水・美容の子カテゴリー作成
parent_id = Category.find_by(name: "コスメ・香水・美容").id
Category.seed(:id,
{id: 93, name: "ベースメイク", ancestry: parent_id },
{id: 94, name: "メイクアップ", ancestry: parent_id },
{id: 95, name: "ネイルケア", ancestry: parent_id },
{id: 96, name: "香水", ancestry: parent_id },
{id: 97, name: "スキンケア/基礎化粧品", ancestry: parent_id },
{id: 98, name: "ヘアケア", ancestry: parent_id },
{id: 99, name: "ボディケア", ancestry: parent_id },
{id: 100, name: "オーラルケア", ancestry: parent_id },
{id: 101, name: "リラクゼーション", ancestry: parent_id },
{id: 102, name: "ダイエット", ancestry: parent_id },
{id: 103, name: "その他", ancestry: parent_id },
)
# 08 家電・スマホ・カメラの子カテゴリー作成
parent_id = Category.find_by(name: "家電・スマホ・カメラ").id
Category.seed(:id,
{id: 104, name: "スマートフォン/携帯電話", ancestry: parent_id },
{id: 105, name: "スマホアクセサリー", ancestry: parent_id },
{id: 106, name: "PC/タブレット", ancestry: parent_id },
{id: 107, name: "カメラ", ancestry: parent_id },
{id: 108, name: "テレビ/映像機器", ancestry: parent_id },
{id: 109, name: "オーディオ機器", ancestry: parent_id },
{id: 110, name: "美容/健康", ancestry: parent_id },
{id: 111, name: "冷暖房/空調", ancestry: parent_id },
{id: 112, name: "生活家電", ancestry: parent_id },
{id: 113, name: "その他", ancestry: parent_id },
)
# 09 スポーツ・レジャーの子カテゴリー作成
parent_id = Category.find_by(name: "スポーツ・レジャー").id
Category.seed(:id,
{id: 114, name: "ゴルフ", ancestry: parent_id },
{id: 115, name: "フィッシング", ancestry: parent_id },
{id: 116, name: "自転車", ancestry: parent_id },
{id: 117, name: "トレーニング/エクササイズ", ancestry: parent_id },
{id: 118, name: "野球", ancestry: parent_id },
{id: 119, name: "サッカー/フットサル", ancestry: parent_id },
{id: 120, name: "テニス", ancestry: parent_id },
{id: 121, name: "スノーボード", ancestry: parent_id },
{id: 122, name: "スキー", ancestry: parent_id },
{id: 123, name: "その他スポーツ", ancestry: parent_id },
{id: 124, name: "アウトドア", ancestry: parent_id },
{id: 125, name: "その他", ancestry: parent_id },
)
# 10 ハンドメイドの子カテゴリー作成
parent_id = Category.find_by(name: "ハンドメイド").id
Category.seed(:id,
{id: 126, name: "アクセサリー(女性用)", ancestry: parent_id },
{id: 127, name: "ファッション/小物", ancestry: parent_id },
{id: 128, name: "アクセサリー/時計", ancestry: parent_id },
{id: 129, name: "日用品/インテリア", ancestry: parent_id },
{id: 130, name: "趣味/おもちゃ", ancestry: parent_id },
{id: 131, name: "キッズ/ベビー", ancestry: parent_id },
{id: 132, name: "素材/材料", ancestry: parent_id },
{id: 133, name: "二次創作物", ancestry: parent_id },
{id: 134, name: "その他", ancestry: parent_id },
)
# 11 チケットの子カテゴリー作成
parent_id = Category.find_by(name: "チケット").id
Category.seed(:id,
{id: 135, name: "音楽", ancestry: parent_id },
{id: 136, name: "スポーツ", ancestry: parent_id },
{id: 137, name: "演劇/芸能", ancestry: parent_id },
{id: 138, name: "イベント", ancestry: parent_id },
{id: 139, name: "映画", ancestry: parent_id },
{id: 140, name: "施設利用券", ancestry: parent_id },
{id: 141, name: "優待券/割引券", ancestry: parent_id },
{id: 142, name: "その他", ancestry: parent_id },
)
# 12 自動車・オートバイの子カテゴリー作成
parent_id = Category.find_by(name: "自動車・オートバイ").id
Category.seed(:id,
{id: 143, name: "自動車本体", ancestry: parent_id },
{id: 144, name: "自動車タイヤ/ホイール", ancestry: parent_id },
{id: 145, name: "自動車パーツ", ancestry: parent_id },
{id: 146, name: "自動車アクセサリー", ancestry: parent_id },
{id: 147, name: "オートバイ車体", ancestry: parent_id },
{id: 148, name: "オートバイパーツ", ancestry: parent_id },
{id: 149, name: "オートバイアクセサリー", ancestry: parent_id },
)
# 13 その他の子カテゴリー作成
parent_id = Category.find(13).id
Category.seed(:id,
{id: 150, name: "まとめ売り", ancestry: parent_id },
{id: 151, name: "ペット用品", ancestry: parent_id },
{id: 152, name: "食品", ancestry: parent_id },
{id: 153, name: "飲料/酒", ancestry: parent_id },
{id: 154, name: "日用品/生活雑貨/旅行", ancestry: parent_id },
{id: 155, name: "アンティーク/コレクション", ancestry: parent_id },
{id: 156, name: "文房具/事務用品", ancestry: parent_id },
{id: 157, name: "事務/店舗用品", ancestry: parent_id },
{id: 158, name: "その他", ancestry: parent_id },
) | true |
ee1fad8deaf47631fbcdc276cb8ee026f954486a | Ruby | keixcruick90/programming-univbasics-4-array-methods-lab-dumbo-web-102819 | /lib/array_methods.rb | UTF-8 | 513 | 3.703125 | 4 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | def using_include(array, element)
array.include?(element)
end
def using_sort(array)
anime = ["Rurouni Kenshin", "Yu Yu Hakusho", "I", "Inuyasha", "wow"]
anime.sort
end
def using_reverse(array)
fun = ["wow", "blue", "tandem", "arrays!"]
fun.reverse
end
def using_first(array)
words = ["wow", "damn", "boy", "facts"]
words.first
end
def using_last(array)
l = ["hello", "top", "vers", "chorus", "arrays!"]
l.last
end
def using_size(array)
a = ["boom", "wail", "block", "house", "rum", "vodka"]
a.size
end
| true |
bb65b059e41312b92072ffb4a0dfd310a03ef44f | Ruby | DianeEugenie/cinema_sql_and_ruby | /console.rb | UTF-8 | 3,237 | 2.765625 | 3 | [] | no_license | require_relative("./models/customer.rb")
require_relative("./models/film.rb")
require_relative("./models/ticket.rb")
require_relative("./models/screening.rb")
require("pry-byebug")
Ticket.delete_all()
Screening.delete_all()
Customer.delete_all()
Film.delete_all()
customer1 = Customer.new(
{
"name" => "Phoebe",
"funds" => 50
}
)
customer2 = Customer.new(
{
"name" => "Piper",
"funds" => 40
}
)
customer3 = Customer.new(
{
"name" => "Prue",
"funds" => 70
}
)
customer1.save()
customer2.save()
customer3.save()
# customer1.delete()
# customer3.name = "Paige"
# customer3.update()
film1 = Film.new(
{
"title" => "The Witches",
"price" => 5
}
)
film2 = Film.new(
{
"title" => "Something Wicked This Way Comes",
"price" => 7
}
)
film3 = Film.new(
{
"title" => "The Craft",
"price" => 5
}
)
film1.save()
film2.save()
film3.save()
# film2.delete()
# film3.title = "Practical Magic"
# film3.update()
screening1 = Screening.new(
{
"screen_time" => "14:00"
}
)
screening2 = Screening.new(
{
"screen_time" => "16:00"
}
)
screening3 = Screening.new(
{
"screen_time" => "17:00"
}
)
screening4 = Screening.new(
{
"screen_time" => "18:00"
}
)
screening1.save()
screening2.save()
screening3.save()
screening4.save()
ticket1 = Ticket.new(
{
"customer_id" => customer1.id,
"film_id" => film1.id,
"screening_id" => screening1.id
}
)
ticket2 = Ticket.new(
{
"customer_id" => customer2.id,
"film_id" => film2.id,
"screening_id" => screening2.id
}
)
ticket3 = Ticket.new(
{
"customer_id" => customer3.id,
"film_id" => film3.id,
"screening_id" => screening4.id
}
)
ticket4 = Ticket.new(
{
"customer_id" => customer2.id,
"film_id" => film3.id,
"screening_id" => screening3.id
}
)
ticket5 = Ticket.new(
{
"customer_id" => customer3.id,
"film_id" => film2.id,
"screening_id" => screening2.id
}
)
ticket6 = Ticket.new(
{
"customer_id" => customer1.id,
"film_id" => film2.id,
"screening_id" => screening4.id
}
)
ticket7 = Ticket.new(
{
"customer_id" => customer3.id,
"film_id" => film2.id,
"screening_id" => screening1.id
}
)
ticket8 = Ticket.new(
{
"customer_id" => customer3.id,
"film_id" => film2.id,
"screening_id" => screening2.id
}
)
ticket9 = Ticket.new(
{
"customer_id" => customer3.id,
"film_id" => film3.id,
"screening_id" => screening4.id
}
)
# ticket10 = Ticket.new(
# {
# "customer_id" => customer3.id,
# "film_id" => film2.id,
# "screening_id" => screening2.id
# }
# )
#
# ticket11 = Ticket.new(
# {
# "customer_id" => customer3.id,
# "film_id" => film2.id,
# "screening_id" => screening2.id
# }
# )
# ticket12 = Ticket.new(
# {
# "customer_id" => customer2.id,
# "film_id" => film2.id,
# "screening_id" => screening2.id
# }
# )
ticket1.save()
ticket2.save()
ticket3.save()
ticket4.save()
ticket5.save()
ticket6.save()
ticket7.save()
ticket8.save()
ticket9.save()
# ticket10.save()
# ticket11.save()
# ticket12.save()
# ticket2.delete()
# ticket5.customer_id = customer2.id
# ticket5.update()
binding.pry
nil
| true |
bb04075fc597e5788159af03b9a216f6ccc6b7ac | Ruby | jinshen-cn/meetapp | /app/helpers/sessions_helper.rb | UTF-8 | 551 | 2.546875 | 3 | [] | no_license | module SessionsHelper
def current_user=(user)
@current_user = user
session[:session_token] = user.session_token
end
def current_user
return nil if session[:session_token].nil?
@current_user ||= User.find_by_session_token(session[:session_token])
end
def logged_in?
!current_user.nil?
end
def logout_current_user!
current_user.reset_session_token!
session[:session_token] = nil
end
def require_current_user!
if !logged_in?
flash[:notices] = ["Must be logged in to do that"]
redirect_to new_session_url
end
end
end
| true |
35a6c0acff1d9eb418d7f6b9cc2059db79486523 | Ruby | tjisher/quiz14 | /lcd_tests.rb | UTF-8 | 8,282 | 3.5 | 4 | [] | no_license | ##ToC
# Basic Assignments
# Output
# Time object as input
# Logger
# Character and encoding changes
require './lcd.rb'
require 'minitest/autorun'
class LCDTest < MiniTest::Test
#Basic Assignments
def test_assignment_string
lcd = LCD.new
lcd.values = "01234"
assert_equal "01234", lcd.values,
"Values to display should be saved and retrieved properly"
end
def test_assignment_scale
lcd = LCD.new
lcd.scale = 1
assert_equal 1, lcd.scale,
"Scale should be saved and retrieved properly"
end
def test_assignment_scale_default
lcd = LCD.new
assert_equal 2, lcd.scale,
"Scale default should be 2"
assert_equal 2, LCD::SCALE_DEFAULT,
"Scale default should be 2 and be present in SCALE_DEFAULT constant"
end
def test_assignment_string_invalid
lcd = LCD.new
lcd.values = "01234a"
assert_equal "01234", lcd.values,
"Invalid values should be ignored"
end
def test_is_valid
lcd = LCD.new
assert_equal true, lcd.valid_characters.include?( "1"),
"Valid Characters list should exist and include '1'"
all_numbers = "0123456789"
assert (lcd.values = all_numbers).length == all_numbers.length
"Valid Characters list should contains all numbers"
assert_equal false, lcd.is_valid?( "01234a"),
"is_valid method should report presence of illegal characters"
end
def test_assignment_integer
lcd = LCD.new
lcd.values = 10234
assert_equal "10234", lcd.values,
"Integer values should be accepted as strings"
end
#Output
def test_responds_to_to_s
lcd = LCD.new
refute_match /#\<LCD:/, lcd.to_s,
"to_s opertaion should be appropiate"
assert_equal "", lcd.to_s,
"Output empty string as default"
end
def test_output_single_scaled
lcd = LCD.new
lcd.values = "0"
lcd.scale = 1
lcd.update_output
zero = <<-STR
-
| |
| |
-
STR
assert_equal zero, lcd.output,
"Output of '0' scale 1 does not match expected"
end
def test_output_single
lcd = LCD.new
lcd.values = "0"
lcd.update_output
zero = <<-STR
--
| |
| |
| |
| |
--
STR
assert_equal zero, lcd.output,
"Output of '0' scaled to 2 does not match expected"
end
def test_output_two_values_scaled
lcd = LCD.new
lcd.values = "01"
lcd.scale = 1
lcd.update_output
two_numbers = <<-STR
-
| | |
| | |
-
STR
assert_equal two_numbers, lcd.output,
"Output of two values '01' scale 1 does not match expected"
end
def test_output_two_values
lcd = LCD.new
lcd.values = "01"
lcd.update_output
zero_one = <<-STR
--
| | |
| | |
| | |
| | |
--
STR
assert_equal zero_one, lcd.output,
"Output of two values '01' does not match expected"
end
def test_output_all_numbers
lcd = LCD.new
lcd.values = "0123456789"
lcd.scale = 1
lcd.update_output
all_numbers = <<-STR
- - - - - - - -
| | | | | | | | | | | | | |
- - - - - - -
| | | | | | | | | | | | |
- - - - - - -
STR
assert_equal all_numbers, lcd.output,
"Output of 0123456789 scale 1 does not match expected"
end
def test_output_against_spec_example_scaled
lcd = LCD.new
lcd.values = "6789"
lcd.scale = 1
lcd.update_output
all_numbers = <<-STR
- - - -
| | | | | |
- - -
| | | | | |
- - -
STR
assert_equal all_numbers, lcd.output,
"Output of 6789 scale 1 does not match expected"
end
def test_output_against_spec_example
lcd = LCD.new
lcd.values = "012345"
lcd.update_output
all_numbers = <<-STR
-- -- -- --
| | | | | | | |
| | | | | | | |
-- -- -- --
| | | | | | |
| | | | | | |
-- -- -- --
STR
assert_equal all_numbers, lcd.output,
"Output of 012345 does not match expected"
end
#Time object as input
def test_assignment_time
lcd = LCD.new
lcd.values = "12:34"
assert_equal "12:34", lcd.values,
"Time style values (12:34) should be accepted as strings"
end
def test_assignment_time_object
lcd = LCD.new
t = Time.now
lcd.values = t
assert lcd.values.match( /\d\d:\d\d/),
"Time objects should be accepted and return simple time ie '12:34'"
end
def test_assignment_time_object_format
lcd = LCD.new
t = Time.new( 2000, 10, 31, 23, 59)
lcd.values = t
assert_equal "23:59", lcd.values,
"Time from objects should be in 24hr format"
t = Time.new( 2000, 10, 31, 01, 59)
lcd.values = t
assert_equal "01:59", lcd.values,
"Time from objects should be padded"
end
def test_assignment_time_object_local
lcd = LCD.new
t = Time.now
lcd.values = t
assert_equal t.strftime( "%H:%M"), lcd.values,
"Time objects should be accepted and return local padded time values in 24hour clock ie '01:01' or '23:59'"
end
def test_output_time_with_semicolon
lcd = LCD.new
lcd.values = "67:89"
lcd.scale = 1
lcd.update_output
all_numbers = <<-STR
- - - -
| | . | | | |
- - -
| | | . | | |
- - -
STR
assert_equal all_numbers, lcd.output,
"Output of 67:89 scale 1 does not match expected"
end
#Logger
def test_logger_active
lcd = LCD.new
lcd.values = "01"
lcd.update_output
lcd.values = "02"
lcd.update_output
assert_equal 2, lcd.logger.count,
"Logger should record values"
end
def test_logger_data
lcd = LCD.new
lcd.values = "01"
lcd.update_output
zero_one = <<-STR
--
| | |
| | |
| | |
| | |
--
STR
assert_equal "01", lcd.logger.last[:values],
"Logger should record the values given for a job"
assert lcd.logger.last[:finished_at].is_a?(Time),
"Logger should record time job finished"
assert_equal zero_one, lcd.logger.last[:output],
"Logger should record the output given for a job"
assert_equal 2, lcd.logger.last[:scale],
"Logger should record the scale given for a job"
end
#Character and encoding changes
def test_displayed_characters
lcd = LCD.new
assert !lcd.vertical_character.empty?,
"Verticle Character should be accesible and present"
assert !lcd.horizontal_character.empty?,
"Horizontal Character should be accesible and present"
assert_equal "|", lcd.vertical_character,
"Verticle Character should default to '|'"
assert_equal "-", lcd.horizontal_character,
"Horizontal Character should default to '-'"
end
def test_displayed_characters_change
lcd = LCD.new
lcd.vertical_character = '@'
lcd.horizontal_character = '='
assert_equal "@", lcd.vertical_character,
"Verticle Character should changable"
assert_equal "=", lcd.horizontal_character,
"Horizontal Character should changable"
end
def test_displayed_characters_output
lcd = LCD.new
lcd.vertical_character = '@'
lcd.horizontal_character = '='
lcd.values = "01"
lcd.update_output
zero_one = <<-STR
==
@ @ @
@ @ @
@ @ @
@ @ @
==
STR
assert_equal zero_one, lcd.output,
"Newly set Horizontal/Verticle Character should output"
end
def test_characters_accessible
lcd = LCD.new
assert lcd.character_encoding.count > 0,
"Character Encoding should be accessible and pre-populated"
end
def test_characters_overrideable
lcd = LCD.new
lcd.character_encoding = nil
assert lcd.character_encoding.nil?,
"Character Encoding should be overrideable"
one_encoded = { "1" => [0, 2, 0, 2, 0]}
lcd.character_encoding = one_encoded
assert_equal one_encoded, lcd.character_encoding,
"Character Encoding should accept properly formed hashes"
end
def test_characters_updated_output
lcd = LCD.new
one_encoded = { "1" => [0, 2, 0, 2, 0]}
lcd.character_encoding = one_encoded
lcd.values = "1"
lcd.update_output
one = <<-STR
|
|
|
|
STR
assert_equal one_encoded, lcd.character_encoding,
"Character Encoding should accept properly formed hashes"
assert_equal one, lcd.output,
"Changed Character Encoding should still output correctly"
lcd.values = "01"
lcd.update_output
assert_equal one, lcd.output,
"Changed Character Encoding should cope with missing characters"
end
end
| true |
1573cca45f155cb8a3fb283378a2e9f846472446 | Ruby | rf-/keynote | /lib/keynote/presenter.rb | UTF-8 | 3,976 | 2.90625 | 3 | [
"MIT"
] | permissive | # encoding: UTF-8
module Keynote
# Keynote::Presenter is a base class for presenters, objects that encapsulate
# view logic.
#
# @see file:README.md
class Presenter
include Keynote::Rumble
class << self
attr_writer :object_names
# Define the names and number of the objects presented by this class.
# This replaces the default one-parameter constructor with one that takes
# an extra parameter for each presented object.
#
# @param [Array<Symbol>] objects One symbol for each of the models that
# will be required to instantiate this presenter. Each symbol will be
# used as the accessor and instance variable name for its associated
# parameter, but an object of any class can be given for any parameter.
#
# @example
# class PostPresenter
# presents :blog_post, :author
# end
#
# # In a view
# presenter = k(:post, @some_post, @some_user)
# presenter.blog_post # == @some_post
# presenter.author # == @some_user
#
def presents(*objects)
self.object_names = objects.dup
objects.unshift :view
attr_reader(*objects)
param_list = objects.join(', ')
ivar_list = objects.map { |o| "@#{o}" }.join(', ')
class_eval <<-RUBY
def initialize(#{param_list}) # def initialize(view, foo)
#{ivar_list} = #{param_list} # @view, @foo = view, foo
end # end
RUBY
end
# Define a more complete set of HTML5 tag methods. The extra tags are
# listed in {Keynote::Rumble::COMPLETE}.
def use_html_5_tags
Rumble.use_html_5_tags(self)
end
# List the object names this presenter wraps. The default is an empty
# array; calling `presents :foo, :bar` in the presenter's class body will
# cause `object_names` to return `[:foo, :bar]`.
# @return [Array<Symbol>]
def object_names
@object_names ||= []
end
end
# @private (used by Keynote::Cache to keep the view context up-to-date)
attr_writer :view
# Create a presenter. The default constructor takes one parameter, but
# calling `presents` replaces it with a generated constructor.
# @param [ActionView::Base] view_context
# @see Keynote::Presenter.presents
def initialize(view_context)
@view = view_context
end
# Instantiate another presenter.
# @see Keynote.present
def present(*objects, &blk)
Keynote.present(@view, *objects, &blk)
end
alias k present
# @private
def inspect
objects = self.class.object_names
render = proc { |name| "#{name}: #{send(name).inspect}" }
if objects.any?
"#<#{self.class} #{objects.map(&render).join(", ")}>"
else
"#<#{self.class}>"
end
end
# @private
def respond_to_missing?(method_name, include_private = true)
@view.respond_to?(method_name, true)
end
# Presenters proxy unknown method calls to the view context, allowing you
# to call `h`, `link_to`, and anything else defined in a helper module.
#
# @example
# def title_link
# link_to blog_post_url(blog_post) do
# "#{h author.name} — #{h blog_post.title}".html_safe
# end
# end
def method_missing(method_name, *args, **kwargs, &block)
if @view.respond_to?(method_name, true)
@view.send(method_name, *args, **kwargs, &block)
else
super
end
end
# @private
# We have to make a logger method available so that ActionView::Template
# can safely treat a presenter as a view object.
def logger
Rails.logger
end
private
# We have to explicitly proxy `#capture` because ActiveSupport creates a
# `Kernel#capture` method.
def capture(*args, &block)
@view.capture(*args, &block)
end
end
end
| true |
1fb249ef24d8973ec595ded6a5f05011da9368f4 | Ruby | goldhoorn/utilrb | /test/test_array.rb | UTF-8 | 248 | 2.6875 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | require 'utilrb/test'
require 'utilrb/array'
class TC_Array < Minitest::Test
def test_to_s
assert_equal("[1, 2]", [1, 2].to_s)
end
def test_to_s_recursive
obj = [1, 2]
obj << obj
assert_equal("[1, 2, ...]", obj.to_s)
end
end
| true |
2141a4353ecd36c3540a4a41eec8191bf645c988 | Ruby | unabatede/shagit | /lib/enhancing_grit.rb | UTF-8 | 799 | 3.078125 | 3 | [
"MIT"
] | permissive | # this adds a method called 'repo_name' that returns only the filename without path or file extension
require 'pathname'
require 'find'
module Grit
# return foldername including extension
def shagit_foldername
foldername = Pathname.new(self.path).basename.to_s
end
# return foldername from path without extension
def shagit_name
foldername = Pathname.new(self.shagit_foldername).basename.to_s
# extract repository name without .git extension
repo_name = foldername.match(/^[\w\s]+/).to_s
end
# return size of folder containing the repository in Kilobytes
def shagit_size
dirsize = 0
# recursively search the repositories path and sum up all file sizes
Find.find(self.path) do |file|
dirsize += File.stat(file).size
end
dirsize
end
end | true |
71fb2d91edb43474990ca7cb67e1ac35cd41e041 | Ruby | bethsecor/ruby-exercisms | /sum-of-multiples/sum_of_multiples.rb | UTF-8 | 458 | 3.5625 | 4 | [] | no_license | class SumOfMultiples
def initialize(*multiples)
@multiples = multiples
end
def to(ceiling_number)
if ceiling_number < @multiples.min
0
else
sum_multiples(ceiling_number)
end
end
def sum_multiples(ceiling_number)
numbers = (1...ceiling_number).to_a
result = []
@multiples.each do |multiple|
result << numbers.select { |num| num % multiple == 0 }
end
result.flatten.uniq.reduce(:+)
end
end
| true |
b5c3fdfcd91f2b464bddd418b8b6f37f4a0cf569 | Ruby | cynthiacd/betsy | /app/models/product_order.rb | UTF-8 | 908 | 2.703125 | 3 | [] | no_license | class ProductOrder < ApplicationRecord
belongs_to :order, optional: false
belongs_to :product, optional: false
validates_uniqueness_of :order_id,
scope: [:product_id],
message: "This item is already in the cart"
validate :quantity, :check_quantity
# you should be sending argument as hash
def self.add_product(product_id, order_id)
product_order = ProductOrder.new
product_order.product_id = product_id
product_order.order_id = order_id
product_order.quantity = 1
return product_order
end
def check_quantity
product = Product.find_by(id: self.product_id)
if product.nil? || product.inventory.nil?
errors.add(:product_order, "This item is not available")
elsif self.quantity > product.inventory
errors.add(:product_order, "There is not enough stock to accommodate your order")
end
end
end
| true |
8b55840c05725f78a5659e2d543991371c897d27 | Ruby | acidhelm/kq_olympic_scoring_test | /test.rb | UTF-8 | 2,264 | 2.84375 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
require "dotenv/load"
require "json"
require "optparse"
require "rest-client"
require_relative "bracket"
require_relative "config"
require_relative "match"
require_relative "player"
require_relative "scene"
require_relative "team"
require_relative "tournament"
Options = Struct.new(:tournament_name, :api_key, :use_cache, :update_cache) do
def initialize
# Set up defaults. The tournament name and API key members default to
# values in ENV, to stay compatible with the old method of always reading
# those strings from ENV.
self.tournament_name = ENV["CHALLONGE_SLUG"]
self.api_key = ENV["CHALLONGE_API_KEY"]
self.use_cache = false
self.update_cache = false
end
end
def parse_command_line
options = Options.new
parser = OptionParser.new do |p|
script_name = File.basename $0
p.banner = "Usage: #{script_name} -t tournament_name [-a api_key] [-c] [-u]"
p.on("-t", "--tournament SLUG_OR_ID", "The slug or Challonge ID of the tournament") do |value|
options.tournament_name = value
end
p.on("-a", "--api-key API_KEY", "Your Challonge API key") do |value|
options.api_key = value
end
p.on("-c", "--use-cache", "Use cached HTTP responses") do |value|
options.use_cache = value
end
p.on("-u", "--update-cache", "Update the cached HTTP responses") do |value|
options.update_cache = value
end
p.on_tail("-h", "--help", "Print this help") do
$stderr.puts p
exit 0
end
end
# Parse the command line.
parser.parse ARGV
# Check that we have a tournament name and API key.
if options.tournament_name.nil?
$stderr.puts "No tournament name was specified", parser
exit 1
end
if options.api_key.nil?
$stderr.puts "No API key was specified", parser
exit 1
end
options
end
def main
tournament = Tournament.new(parse_command_line)
if tournament.load
tournament.calculate_points
puts tournament.scene_scores.sort
else
puts "No brackets were loaded."
end
end
if __FILE__ == $0
main
end
| true |
cb7d7f042e39e0b839485b889db4ddb82e323e4b | Ruby | jsb/attic | /mirror/jsb/irc.rb | UTF-8 | 2,480 | 3.296875 | 3 | [] | no_license | require 'socket'
require 'iconv'
def try_to_convert(string, from, to)
begin
string = Iconv.iconv(to, from, string).to_s
return string
rescue Iconv::IllegalSequence, Iconv::InvalidCharacter
return string
end
end
class IRCLineFormatError < StandardError; end
class Client
ServerUsesUTF8 = false
def initialize(server_name, server_port, nick, realname=nick)
@server_name = server_name
@server_port = server_port
@server_socket = nil
@server_connected = false
@nick = nick
@realname = realname
end
def connect()
if(@server_socket = TCPSocket.new(@server_name, @server_port))
@server_connected = true
log_on
Thread.new(self) {|target| target.main_loop }
else
@server_connected = false
end
end
def main_loop()
loop do
break unless @server_connected
if(raw_line = get_line)
parse_line(raw_line)
end
end
end
def log_on
send_line "NICK #{@nick}"
send_line "USER #{@realname} localhost localhost #{@realname}"
end
def get_line
if @server_connected
result = @server_socket.gets
if(result)
result = try_to_convert(result, 'utf-8', 'ascii') if ServerUsesUTF8
return result.chomp
end
else
nil
end
end
def send_line(line)
if @server_connected
line = try_to_convert(line, 'ascii', 'utf-8') if ServerUsesUTF8
@server_socket.puts(line.chomp)
else
nil
end
end
def parse_line(line)
if(line =~ /^(:(\S+) )?([A-Z0-9]+)( (.+))?$/)
user = $2
command = $3
parameters = $5
temp_array = parameters.split(/:/)
parameter_array = temp_array[0].split(/ +/)
parameter_array << temp_array[1..-1].join(':') if(temp_array[1..-1].size > 0)
method_name = 'event_'+command.downcase
if(self.methods.include?(method_name))
event = self.method(method_name)
event.call(user, *parameter_array)
else
any_event(command, user, *parameter_array)
end
else
raise IRCLineFormatError, "Line format invalid."
end
end
def event_ping(user, *params)
send_line("PONG #{params}")
end
def any_event(command, user, *params)
# Does nothing.
# You may overload this to catch commands you dont want to treat in any special way.
end
end
| true |
5569e8d88912d3b364aeb601b780dc6c51958fb7 | Ruby | livash/Poker | /lib/hand.rb | UTF-8 | 2,606 | 3.5625 | 4 | [] | no_license | require_relative 'deck'
require_relative 'card_suits_faces'
class Hand
include CardSuitsFaces
attr_accessor :cards
def initialize(cards)
@cards = cards
end
#private
def suits_hash
return_hash = {}
cards.each do |card|
if return_hash[card.suit].nil?
return_hash[card.suit] = 1
else
return_hash[card.suit] += 1
end
end
return_hash
end
def faces_hash
return_hash = {}
cards.each do |card|
if return_hash.has[card.face]
return_hash[card.face] = 1
else
return_hash[card.face] += 1
end
end
return_hash
end
def is_straight_flush?
is_flush? && is_straight?
end
# def sort
# @cards = @cards.sort do
# |x, y| FACE_VALUES[x.face] <=> FACE_VALUES[y.face]
# end
# @cards
# end
def is_four_kind?
faces_hash.each do |val, count|
return true if count == 4
end
false
end
def is_full_house?
is_one_pair? && is_three_kind?
end
def is_flush?
suits_hash.each do |suit, count|
return true if count == 5
end
false
end
def is_straight?
smallest = smallest_card
aces = aces_array
cars_ordered = []
if smallest.face == 2 && aces.size == 1
smallest = aces[0]
elsif aces.size == 0
ii = 0
while ii <= 5
cards.each do |card|
card.has_face?(FACE_VALUES.index(FACE_VALUES[smallest.face] + 1))
ii += 1
end
end
end
# iterate up to see that each next card is one larger than the previous one
end
def has_face?(card)
@cards.include?(card)
end
def aces_array
aces_arr = []
cards.each do |card|
aces_arr << card if card.face == :A
end
aces_arr
end
def smallest_card #but not ace
small = cards[0]
ace_card = nil
cards.each do |card|
next if card.face == :A
small = card if FACE_VALUES[small.face] > FACE_VALUES[card.face]
end
small
end
def is_three_kind?
faces_hash.each do |val, count|
rturn true if count == 3
end
false
end
def is_two_pair?
pairs == 2
end
def is_one_pair?
pairs == 1
end
def pairs
pair_count = 0
faces_hash.each do |val, count|
pair_count += 1 if count == 2
end
pair_count
end
def high_card
h_card = cards[0]
cards.each do |card|
return card if card.face == :A
h_card = card if FACE_VALUES[h_card.face] > FACE_VALUES[card.face]
end
h_card
end
end | true |
b2d17f278091729d05f17a19409ef756f0cff5b2 | Ruby | JoseGomez247/codeacamp | /prework/Jueves/hashkeys.rb | UTF-8 | 259 | 3.546875 | 4 | [] | no_license | def hash_keys(hash)
arr= []
hash.each_key do |key|#separo el hash en "keys"
arr << key#imprimo el key dentro de un array
end
arr
end
p hash_keys({"Vegetal" => ['zanahoria', 'elote' ], "Fruta" => ['manzana', 'arandano']}) == ["Vegetal", "Fruta"] | true |
9da9633b26c97eb4818bbcb57262a99fd861b070 | Ruby | AshleyRapone/Intro_to_Programming_Ruby | /Exercises/Example3.rb | UTF-8 | 214 | 4.34375 | 4 | [] | no_license | #Now, using the same array from #2, use the select method to extract all odd numbers into a new array.
numbers = [1,2,3,4,5,6,7,8,9,10]
new_array = numbers.select do |number|
number % 2 != 0
end
puts new_array
| true |
48c721091601086feb57fcee9ba2efac672d4456 | Ruby | taw/z3 | /spec/integration/algebra_problems_spec.rb | UTF-8 | 427 | 2.515625 | 3 | [
"MIT"
] | permissive | describe "Algebra Problems" do
it do
expect("algebra_problems").to have_output <<EOF
Solution to problem 01:
Solution to problem 03:
* x = -22
* |-6| = 6
* |x-2| = 24
Solution to problem 04:
* ax = -4
* ay = -5
* bx = -1
* by = -1
* |a-b| = 5
Solution to problem 05:
* x = 9/2
* y = 0
Solution to problem 06:
* answer = 6
* x1 = 1
* x2 = 2
* y1 = 7
* y2 = 13
Solution to problem 10:
* x = 1
* |-2x + 2| = 0
EOF
end
end
| true |
80e0a284db11e783995da20c8d66572dc7a2a949 | Ruby | murashit/murashitbot | /lib/murashitbot/command.rb | UTF-8 | 946 | 2.734375 | 3 | [
"MIT"
] | permissive | require 'thor'
module Murashitbot
class Command < Thor
desc 'init USERNAME', 'Authorize and generate config file.'
def init(name)
Murashitbot::Generator.start
end
desc 'parse USERNAME', 'Parse source.txt and cache results.'
def parse(name)
db = Murashitbot::Parser.start(name)
db.dump(name)
end
desc 'tweet USERNAME', '...'
def tweet(name)
c = Murashitbot::Client.new(name)
c.post
end
desc 'reply USERNAME', '@...'
def reply(name)
c = Murashitbot::Client.new(name)
c.reply
end
desc :usage, 'Show usage.'
def usage
puts <<-EOM
Usage:
# 1. Initialize
$ mkdir bots; cd bots
$ murashitbot init USERNAME
# 2. Edit USERNAME/source.txt
# 3. Parse
murashitbot parse USERNAME
# 4. Tweet!!
$ murashitbot post USERNAME
$ murashitbot reply USERNAME
EOM
end
end
end
| true |
8cada18e8374cb91b285a05ff37f750699664f72 | Ruby | jph98/ant-colony-optimisation | /ant.rb | UTF-8 | 2,891 | 3.296875 | 3 | [] | no_license | #!/usr/bin/env ruby
class Ant
attr_accessor :x, :y, :mode, :state, :direction
RANDOM_MOVEMENT = :random
PHEROMONE_MODE = :pher
LOOK_AROUND = :look
DEBUG = false
STATE = "A"
DIRECTIONS = [:N, :NE, :E, :SE, :S, :SW, :W, :NW]
def initialize(x, y, random_direction_change)
@x = x
@y = y
@food_collected = 0
@random_direction_change = random_direction_change
@direction = get_random_direction_without([])
puts "Generated: #{@direction} for #{@x} and #{@y}" if DEBUG
@mode = RANDOM_MOVEMENT
@carrying_food = false
end
def collect_food()
@food_collected += 1
end
def get_coords(max_x, max_y)
if @mode.eql? RANDOM_MOVEMENT
# Implement lookaround
puts "Max x: #{max_x}, max y: #{max_y}" if DEBUG
assign_direction(max_x, max_y)
puts "before: direction: #{@direction} coords: #{@x} #{@y}" if DEBUG
@y -= 1 if @direction.eql? :N
@y -= 1 and @x += 1 if @direction.eql? :NE
@x += 1 if @direction.eql? :E
@y += 1 and @x += 1 if @direction.eql? :SE
@y += 1 if @direction.eql? :S
@y += 1 and @x -= 1 if @direction.eql? :SW
@x -= 1 if @direction.eql? :W
@y -= 1 and @x -= 1 if @direction.eql? :NW
puts "after: direction: #{@direction} #{@x} #{@y}" if DEBUG
return @x, @y
elsif @mode.eql? PHEROMONE_MODE
# TODO
end
end
def direction_unchanged(new_direction)
return true if new_direction == nil
end
def assign_direction(max_x, max_y)
invalid_directions = []
invalid_directions << :N if @y.eql? 0
invalid_directions << :NE if @y.eql? 0 or @x.eql? max_x
invalid_directions << :NW if @y.eql? 0 or @x.eql? 0
invalid_directions << :E if @x.eql? max_x
invalid_directions << :S if @y.eql? max_y
invalid_directions << :SE if @y.eql? max_y or @x.eql? max_x
invalid_directions << :SW if @y.eql? max_y or @x.eql? 0
invalid_directions << :W if @x.eql? 0
# Only assign a random direction if the current one is invalid
if invalid_directions.include? @direction or @random_direction_change.eql? true
sleep 3 if DEBUG
puts "Assign random: #{@direction}: #{@x} #{@y} within bounds #{max_x} #{max_y}" if DEBUG
@direction = get_random_direction_without(invalid_directions)
puts "Assigned random: #{@direction}" if DEBUG
end
end
def get_random_direction_without(ommitted_directions)
valid_directions = DIRECTIONS - ommitted_directions
puts "Valid directions: #{valid_directions}" if DEBUG
return random_direction(valid_directions)
end
def random_direction(valid_directions)
num = rand(0..(valid_directions.length - 1))
puts "Num is: #{num}" if DEBUG
dir = valid_directions[num]
puts "New dir: #{dir}" if DEBUG
return dir
end
def is_carrying_food?
if @food_collected.eql? 0
return false
else
return true
end
end
def state()
return STATE.colorize(:light_green)
end
def to_s
return "[Ant: x:#{x}, y:#{y} food: #{@food_collected}]"
end
end | true |
00bb7f2da2f5c986aade6a31b86bb2c9157c8631 | Ruby | jgorset/kingpin | /lib/kingpin/frameworks/django.rb | UTF-8 | 764 | 2.6875 | 3 | [] | no_license | require "pathname"
module Kingpin
module Frameworks
class Django < Framework
class << self
# Determine whether the web application at the given path
# is developed with Django.
#
# path - A string describing the path to the root of a web application.
#
# Returns true if the path contains a Django application, or false if
# it does not.
def detect(path)
path = Pathname.new(path)
# Define some traits of an application developed with Django.
traits = [
"manage.py"
]
traits.each do |trait|
return false unless path.join(trait).exist?
end
true
end
end
end
end
end
| true |
dfb3b04711166dffffa263f172a787020c5d0f69 | Ruby | mr-bat/cs291a_project1 | /function.rb | UTF-8 | 3,210 | 2.921875 | 3 | [] | no_license | # frozen_string_literal: true
require 'json'
require 'jwt'
require 'pp'
def lowercaseKeys(hash)
result = {}
hash.to_hash.each_pair do |k, v|
result.merge!(k.downcase => v)
end
result
end
def main(event:, context:)
# You shouldn't need to use context, but its fields are explained here:
# https://docs.aws.amazon.com/lambda/latest/dg/ruby-context.html
request = lowercaseKeys event
# return print request
if request['path'] == '/token'
if request['httpmethod'] == 'POST'
generate_token(request: request)
else
response(status: 405)
end
elsif request['path'] == '/'
if request['httpmethod'] == 'GET'
get_token_data(request: request)
else
response(status: 405)
end
else
response(body: request, status: 404)
end
end
def generate_token(request: event)
body = {}
begin
body = JSON.parse(request['body'])
rescue StandardError
return response(status: 422)
end
# return response(status: 422) unless request['body'].class == Hash
unless lowercaseKeys(request['headers'])['content-type'] == 'application/json'
return response(status: 415)
end
payload = {
data: body,
exp: Time.now.to_i + 5,
nbf: Time.now.to_i + 2
}
token = JWT.encode payload, ENV['JWT_SECRET'], 'HS256'
response(body:
{
token: token
}, status: 201)
end
def get_token_data(request: event)
authorizationHeader = lowercaseKeys(request['headers'])['authorization']
unless authorizationHeader.class == String && authorizationHeader.start_with?('Bearer ')
return response(status: 403)
end
begin
token = lowercaseKeys(request['headers'])['authorization'][7..-1]
decoded_token = JWT.decode token, ENV['JWT_SECRET'], true, algorithm: 'HS256'
return response(status: 401) unless decoded_token[0].key?('data')
return response(body: decoded_token[0]['data'], status: 200)
rescue JWT::ExpiredSignature, JWT::ImmatureSignature
# Handle invalid token, e.g. logout user or deny access
return response(status: 401)
rescue StandardError
return response(status: 403)
end
end
def response(body: nil, status: 200)
{
body: body ? body.to_json + "\n" : '',
statusCode: status
}
end
if $PROGRAM_NAME == __FILE__
# If you run this file directly via `ruby function.rb` the following code
# will execute. You can use the code below to help you test your functions
# without needing to deploy first.
ENV['JWT_SECRET'] = 'NOTASECRET'
# Call /token
PP.pp main(context: {}, event: {
'body' => '{"name": "bboe"}',
'headers' => { 'Content-Type' => 'application/json' },
'httpMethod' => 'POST',
'path' => '/token'
})
# Generate a token
payload = {
data: { user_id: 128 },
exp: Time.now.to_i + 5,
nbf: Time.now.to_i + 2
}
token = JWT.encode payload, ENV['JWT_SECRET'], 'HS256'
# Call /
sleep(2)
PP.pp main(context: {}, event: {
'headers' => {
'Authorization' => "Bearer #{token}",
'Content-Type' => 'application/json'
},
'httpMethod' => 'GET',
'path' => '/'
})
end
| true |
1313a61a6a1bdb7ee9a6dabc247724ee87a70e2c | Ruby | MrCesar107/Sample-Catalogue-App | /app/utils/catalogues.rb | UTF-8 | 229 | 2.640625 | 3 | [] | no_license | # frozen_string_literal: true
class Catalogues # :nodoc:
attr_reader :status
def initialize(status)
@status = status
end
def catalogues
status.eql?('active') && Catalogue.active || Catalogue.inactive
end
end
| true |
7d5bdc81663e1c45a0eb669a024a406c4ba38f15 | Ruby | MaciejLorens/codility | /6.rb | UTF-8 | 425 | 3.234375 | 3 | [] | no_license | def solution(a)
n = a.length
l = Array.new(n + 1)
l[0] = -1
for i in 0 .. (n - 1)
l[i + 1] = a[i]
end
count = 0
pos = (n + 1) / 2
candidate = l[pos]
for i in 1 .. n
if (l[i] == candidate) then
count = count + 1
end
end
if (count > n / 2) then
return candidate;
end
return -1
end
A = []
A[0] = 1
A[1] = 2
A[2] = 2
A[3] = 2
A[4] = 2
A[5] = 3
A[6] = 4
A[7] = 4
p solution(A)
| true |
80482bc3c02bb5210eca7d83319e92dfe6da95b3 | Ruby | stefanlenoach/Reddit-Bot-Maker | /upvoter.rb | UTF-8 | 973 | 2.59375 | 3 | [] | no_license | require 'rubygems'
require 'watir'
require 'selenium-webdriver'
require 'watir-webdriver'
require 'bench'
class Upvote
def initialize
@bots = File.open("reddit_bots.txt").readlines.map {|line| line}
@i = 0
end
def upvote
@browser = Watir::Browser.new :chrome
@browser.goto('https://www.reddit.com/')
sleep(1)
@browser.text_field(:name => 'user').set(@bots[@i])
sleep(1)
@browser.text_field(:name => 'passwd').set("redditbot123")
sleep(1)
#@browser.checkbox(:id => 'rem-login-main').set
@browser.button(class: 'btn').click
sleep(1)
@browser.goto('https://www.reddit.com/r/HillaryForPrison/comments/4qlh3b/reminder_hillary_clinton_is_under_criminal/')
sleep(1)
if @browser.div(class: 'arrow up login-required access-required')
@browser.div(class: 'arrow up login-required access-required').click
end
sleep(5)
@browser.close
@i += 1
end
end
a = Upvote.new
while true
a.upvote
end
| true |
37f81007701d89a1feb5e964c971377643078606 | Ruby | miyohide/just_kidding_ken_all_parser | /db_to_yaml.rb | UTF-8 | 1,160 | 2.671875 | 3 | [] | no_license | require 'yaml'
require 'active_record'
ActiveRecord::Base.establish_connection(
adapter: 'postgresql',
host: 'localhost',
username: 'user1',
password: 'user1',
database: 'ken_all'
)
class Todofuken < ActiveRecord::Base
end
class City < ActiveRecord::Base
end
class Town < ActiveRecord::Base
end
todofuken = Todofuken.order(:id)
city = City.order(:id)
town = Town.order(:id)
File.open("addresses.yml", "w") { |f|
f.write("addresses:\n")
f.write(" prefectural:\n")
todofuken.each do |record|
f.write(" - ['#{record.todofuken_kanji}', '#{record.todofuken_hira}', '#{record.todofuken_kana}', #{record.todofuken_number}]\n")
end
f.write(" city:\n")
city.each do |record|
f.write(" - ['#{record.city_kanji}', '#{record.city_hira}', '#{record.city_kana}', #{record.todofuken_number}, #{record.city_number}]\n")
end
f.write(" town:\n")
town.each do |record|
if record.town_kanji != '以下に掲載がない場合'
f.write(" - ['#{record.town_kanji}', '#{record.town_hira}', '#{record.town_kana}', #{record.todofuken_number}, #{record.city_number}]\n")
end
end
}
| true |
74ef404a3113e3453d2160e8e2dc0c55e2433fb3 | Ruby | Almnir/rubies | /searchXML1.rb | UTF-8 | 1,603 | 2.671875 | 3 | [] | no_license | require 'nokogiri'
fileSchools = File.open('d:\SCREEEENSHOOOTS\тест\rbd_Schools.xml')
fileSchoolsClasses = File.open('d:\SCREEEENSHOOOTS\тест\rbd_SchoolClasses.xml')
docSchools = Nokogiri::XML(fileSchools)
docSchoolsClasses = Nokogiri::XML(fileSchoolsClasses)
idsSchools = []
idsSchoolsClasses = []
idsSchoolsClassesId = []
docSchools.xpath("//ns1:GIADBSet/ns1:rbd_Schools/ns1:SchoolID").each do |e|
idsSchools << e.text
# e.values.each do |v|
# puts v
# if !e.text.strip.empty? and v.include? "Локальный_ID" then
# puts e.text
# end
# end
end
count = 0
docSchoolsClasses.xpath("//ns1:GIADBSet/ns1:rbd_SchoolClasses/ns1:SchoolID").each do |e|
idsSchoolsClasses << e.text
count +=1
# e.values.each do |v|
# puts v
# if !e.text.strip.empty? and v.include? "Локальный_ID" then
# puts e.text
# end
# end
end
docSchoolsClasses.xpath("//ns1:GIADBSet/ns1:rbd_SchoolClasses/ns1:SchoolClassID").each do |e|
idsSchoolsClassesId << e.text
count +=1
# e.values.each do |v|
# puts v
# if !e.text.strip.empty? and v.include? "Локальный_ID" then
# puts e.text
# end
# end
end
idsSchoolsClasses.each do |s|
unless idsSchools.include? s
puts s
end
end
idsSchoolsClassesId.tally.each do |k,v|
if v > 1
puts "SchoolClassID: #{k} -- повторов: #{v}"
end
end
# puts count
fileSchools.close
fileSchoolsClasses.close | true |
0252c4a1793a14a34411b6c69dd83cfe57ff11e1 | Ruby | fatih/shoulda-matchers | /spec/warnings_spy/reader.rb | UTF-8 | 950 | 3 | 3 | [
"MIT"
] | permissive | class WarningsSpy
class Reader
attr_reader :warning_groups
def initialize(filesystem)
@warnings_file = filesystem.warnings_file
@current_group = []
@warning_groups = []
end
def read
warnings_file.rewind
warnings_file.each_line do |line|
process_line(line)
end
add_group(current_group)
end
protected
attr_reader :warnings_file, :current_group
private
def process_line(line)
if start_of_group?(line)
add_group(current_group)
@current_group = []
end
current_group << line
end
def start_of_group?(line)
line =~ /^\S/
end
def add_group(group)
unless group.empty? || group_already_added?(group)
warning_groups << group
end
end
def group_already_added?(group_to_be_added)
warning_groups.any? do |group|
group == group_to_be_added
end
end
end
end
| true |
f1d2d312e6abef67a5051b3d598b68400fa72e73 | Ruby | rvachon1/rb130 | /exercises/challenges/easy1/series.rb | UTF-8 | 1,000 | 4.53125 | 5 | [] | no_license | =begin
Write a program that will take a string of digits and give you all the possible
consecutive number series of length n in that string.
Rules:
-Input: String of digits
-Ouput: Array of digit arrays
-Sliced arrays must consist of consecutive numbers
-Every sliced array must be unique
-Raises ArgumentError if size of sliced array is greater than num of String digits
ALGO:
-Initialize array to hold sliced arrays: slices
-Iterate through each digit in string
-Grab specified number of items: num
-Convert them to integer
-Shovel into slices
-Return slices
=end
class Series
def initialize(digits)
@digits = digits.chars.map(&:to_i)
end
def slices(num)
validate_input(num)
slices = []
counter = 0
while counter <= (@digits.size-num)
slices << @digits[counter..counter+num-1]
counter += 1
end
slices
end
private
def validate_input(num)
raise ArgumentError, "Argument too big for Digit String." if num > @digits.size
end
end
| true |
38ba5ae326f3ff4b9cd5e050276be8129acb72c0 | Ruby | RodolfoPena/E7CP2A1 | /ejercicio1.rb | UTF-8 | 1,747 | 4.1875 | 4 | [] | no_license | # 1. Utilizando *map* generar un nuevo arreglo con cada valor aumentado en 1.
# 2. Utilizando *map* generar un nuevo arreglo que contenga todos los valores convertidos a *float*.
# 3. Utilizando *map* generar un nuevo arreglo que contenga todos los valores convertidos a *string*.
# 4. Utilizando *reject* descartar todos los elementos <u>menores</u> a 5 en el array.
# 5. Utilizando *select* descartar todos los elementos <u>mayores</u> a 5 en el array.
# 6. Utilizando *inject* obtener la suma de todos los elementos del array.
# 7. Utilizando *group_by* agrupar todos los números por paridad (si son pares, es un grupos, si son impares es otro grupo).
# 8. Utilizando *group_by* agrupar todos los números mayores y menores que 6.
a = [1, 2, 3, 9, 1, 4, 5, 2, 3, 6, 6]
def aumentar_en_1(array)
new_array = Array.new()
array.map { |k| new_array[k] = k + 1 }
end
print aumentar_en_1(a)
puts ""
def convertir_en_float(array)
new_array = Array.new()
array.map { |k| new_array[k] = k.to_f }
end
print convertir_en_float(a)
puts ""
def convertir_en_string(array)
new_array = Array.new()
array.map { |k| new_array[k] = k.to_s }
end
print convertir_en_string(a)
puts ""
def sacar_menores_5(array)
array.reject {|k| k < 5}
end
print sacar_menores_5(a)
puts ""
def sacar_mayores_5(array)
array.select { |k| k < 5 }
end
print sacar_mayores_5(a)
puts ""
def suma_elementos(array)
array.inject(0){ |sum,x| sum + x }
end
print suma_elementos(a)
puts ""
def agrupar_pares_impares(array)
array.group_by { |k| k.even? }
end
print agrupar_pares_impares(a)
puts ""
def agrupar_mayores_menores_6(array)
array.group_by { |k| k > 6 }
end
print agrupar_mayores_menores_6(a)
puts ""
| true |
49aa6fb6f5502a548d90d469e7bea5a3acadaae4 | Ruby | hobodave/nagios-probe | /lib/nagios-probe.rb | UTF-8 | 1,163 | 2.96875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | module Nagios
OK = 0
WARNING = 1
CRITICAL = 2
UNKNOWN = 3
class Probe
attr_reader :retval, :message
def initialize(opts = {})
@opts = opts
@retval = Nagios::OK
@message = "OK: #{ok_message}"
end
def crit?
return false unless check_crit
@retval = Nagios::CRITICAL
@message = "Critical: #{crit_message}"
true
end
def warn?
return false unless check_warn
@retval = Nagios::WARNING
@message = "Warning: #{warn_message}"
true
end
def ok?
return false unless check_ok
@retval = Nagios::OK
@message = "OK: #{ok_message}"
true
end
def check_ok
true
end
def run
if !crit?
if !warn?
if !ok?
@retval = Nagios::UNKNOWN
raise RuntimeError, "crit? warn? and ok? all returned false"
end
end
end
end
def crit_message
"Default message - override crit_message."
end
def warn_message
"Default message - override warn_message."
end
def ok_message
"Default message - override ok_message."
end
end
end | true |
134b5899ed620614650ae396fe9e43a40dbd9779 | Ruby | artisanengine/artisanengine | /spec/acceptance/visitors/goods/options/select_good_options_spec.rb | UTF-8 | 3,481 | 2.703125 | 3 | [] | no_license | require 'acceptance/acceptance_helper'
feature 'Select a Variant Using Option Drop-Downs', %q{
In order to select a variation of a good
As a visitor
I want to use option drop-downs to choose the variant.
} do
background do
# Given a good exists with three options and three variants,
@good = Factory( :good_with_three_options_and_variants, name: 'Bag of Tricks' )
# And I am on the show good page for the good,
visit good_page_for 'Bag of Tricks'
end
scenario "A visitor can select a variant using the variant drop-down" do
# Then I should see a variant drop down.
page.should have_selector 'select.main_variant_selector' do
page.should have_selector 'option', text: 'Small / Blue / Cloth'
page.should have_selector 'option', text: 'Medium / Blue / Cloth'
page.should have_selector 'option', text: 'Medium / Red / Cloth'
end
end
scenario "A visitor can select a variant using option drop-downs", js: true do
# The Size drop-down should have Small, Medium, and Large options.
within 'select#size' do
page.should have_selector 'option', text: 'Small'
page.should have_selector 'option', text: 'Medium'
page.should have_selector 'option', text: 'Large'
end
# The Color drop-down should have Red and Blue options.
within 'select#color' do
page.should have_selector 'option', text: 'Red'
page.should have_selector 'option', text: 'Blue'
end
# The Material drop-down should have Cloth option.
within 'select#material' do
page.should have_selector 'option', text: 'Cloth'
end
end
scenario "The price updates automatically when a variant is selected", js: true do
# Given the first variant has a price of 25
@good.variants.first.update_attributes price: "$25.00"
# And the last variant has a price of 50
@good.variants.last.update_attributes price: "$50.00"
# And I reload the page,
visit good_page_for 'Bag of Tricks'
# Then I should see $25.00,
page.should have_selector '#price', text: '$25.00'
# And when I select the last variant,
select 'Large', from: 'Size'
select 'Red', from: 'Color'
select 'Cloth', from: 'Material'
# Then I should see $50.00.
page.should have_selector '#price', text: '$50.00'
# And when I click Add to Order,
click_button 'Add to Order'
# Then I should see a line item from the variant.
within '.line_item' do
page.should have_content 'Bag of Tricks'
page.should have_content '$50.00'
page.should have_content 'Large / Red / Cloth'
end
end
scenario "A visitor does not see select lists for a good with only the Default option" do
# Given there is a good with only the default option,
good = Good.generate name: 'Plain Vanilla'
good.variants.first.update_attributes price: "$50.00"
# When I visit the page for the good,
visit good_page_for 'Plain Vanilla'
# Then I should not see any select lists,
page.should have_no_selector 'select'
# And I should see the variant's price.
page.should have_selector '#price', text: '$50.00'
# And when I click Add to Order,
click_button 'Add to Order'
# Then I should see a line item with the good's name and price.
within '.line_item' do
page.should have_content 'Plain Vanilla'
page.should have_content '$50.00'
end
end
end | true |
d2541b16d60bf703f0ec76ffb2505f1ff77d4a4a | Ruby | xanzor/Qwant | /FullStack/Bootcamp Ruby/Ruby Quest01/ex02/my_first_variable_string.rb | UTF-8 | 49 | 2.5625 | 3 | [] | no_license | my_string = "Learning is growing"
puts(my_string) | true |
978aaa1ea9bc68470e3cf81dd73db42e7ed6748a | Ruby | bkozhaev/test | /lib/test_body.rb | UTF-8 | 1,620 | 3.609375 | 4 | [] | no_license | class TestBody
#1. Сократил написание сеттеров
attr_reader :user_name, :points
def initialize(user_name, file_path)
@user_name = user_name
@points = 0
@count = 0
#2. Вывел ссылку на файл в main.rb а сам метод привязал к (file_path)
#3. Изменил чтение строки с файла одной строкой
begin
@lines = File.readlines(file_path, encoding: 'UTF-8')
rescue SystemCallError => e
puts "Файл #{file_path} был не найден #{e}"
end
end
def finished?
@count >= @lines.size
end
# создал отдельный метод по подсчету очкое,
# вывел действие по подсчету очков с метода ask_next_question
def get_user_points (user_input)
case user_input
when 1 then @points += 2
when 3 then @points += 1
end
end
# создал метод для вывода вопроса отдельно от метода ask_next_question
def print_question
puts "\nВопрос №#{@count + 1}\n\r"
puts @lines[@count]
end
def ask_next_question
print_question
user_input = nil
while user_input != 1 && user_input != 2 && user_input != 3
puts <<~STR
Нажмите:
"1 - Enter" Если ваш ответ "да"
"2 - Enter" Если ваш ответ "нет"
"3 - Enter" Если ваш ответ "иногда"
STR
user_input = STDIN.gets.to_i
end
get_user_points(user_input)
@count += 1
end
end
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.