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 |
---|---|---|---|---|---|---|---|---|---|---|---|
b89b73204c8780ebc2b797d40e73172c9117b199
|
Ruby
|
snowistaken/ride-share-rails
|
/app/models/driver.rb
|
UTF-8
| 579 | 2.9375 | 3 |
[] |
no_license
|
class Driver < ApplicationRecord
has_many :trips
validates :name, presence: true
validates :vin, presence: true
def average_rating(id)
@driver = Driver.find_by(id: id)
ratings = []
@driver.trips.each do |trip|
ratings << trip.rating.to_f
end
return nil if ratings.empty?
return (ratings.sum / ratings.length).round(2)
end
def total_earnings(id)
@driver = Driver.find_by(id: id)
profit = []
@driver.trips.each do |trip|
profit << (trip.cost.to_f - 1.65) * 0.8
end
return (profit.sum / 100).round(2)
end
end
| true |
e5eac97fbf8f8e2e9b0c435c9323d735ac12894d
|
Ruby
|
Finble/learn_to_program
|
/ch09-writing-your-own-methods/old_school_roman_numerals.rb
|
UTF-8
| 442 | 3.578125 | 4 |
[] |
no_license
|
def old_roman_numeral (num)
raise 'Number must be positive' if num <= 0
roman_num = ''
roman_num << 'M' * (num/1000)
roman_num << 'D' * (num % 1000/500)
roman_num << 'C' * (num % 500/100)
roman_num << 'L' * (num % 100/50)
roman_num << 'X' * (num % 50/10)
roman_num << 'V' * (num % 10/5)
roman_num << 'I' * (num % 5/1)
return roman_num
end
puts old_roman_numeral(1999)
#have done exercise a lot in the past...
#rspec passed
| true |
7ea0212c6cc6605cf7a3c17daa51c10bd9431046
|
Ruby
|
supunic/Fortune-Checker
|
/vendor/bundle/ruby/2.6.0/gems/unparser-0.2.8/spec/support/parser_class_generator.rb
|
UTF-8
| 781 | 2.8125 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
module ParserClassGenerator
def self.generate_with_options(base_parser_class, builder_options)
# This builds a dynamic subclass of the base_parser_class (e.g. Parser::Ruby23)
# and overrides the default_parser method to return a parser whose builder
# has various options set.
#
# Currently the only builder option is :emit_file_line_as_literals
Class.new(base_parser_class) do
define_singleton_method(:default_parser) do |*args|
super(*args).tap do |parser|
parser.builder.emit_file_line_as_literals = builder_options[:emit_file_line_as_literals]
end
end
define_singleton_method(:inspect) do
"#{base_parser_class.inspect} with builder options: #{builder_options.inspect}"
end
end
end
end
| true |
b222880b412fdc2c1043dda50421ae5091bbf6ac
|
Ruby
|
gutenye/tagen
|
/lib/tagen/core/array/extract_options.rb
|
UTF-8
| 1,086 | 3.3125 | 3 |
[
"MIT"
] |
permissive
|
require "active_support/core_ext/array/extract_options"
class Array
# Extracts options from a set of arguments.
#
# @example
#
# dirs, o = ["foo", "bar", {a: 1}].extract_options(b: 2)
# -> ["foo", "bar"], {a: 1, b: 2}
#
# (dir,), o = ["foo", {a: 1}].extract_options
# -> "foo", {a: 1}
#
# @return [Array<Array,Hash>]
# @see extract_options!
def extract_options(default={})
if last.is_a?(Hash) && last.extractable_options?
[self[0...-1], default.merge(self[-1])]
else
[self, default]
end
end
# Extracts options from a set of arguments. Removes and returns the last
# element in the array if it's a hash, otherwise returns a blank hash.
#
# @example
#
# def options(*args)
# args.extract_options!(a: 1)
# end
#
# options(1, 2) -> {a: 1}
# options(1, 2, a: 2) -> {a: 2}
#
# @param [Hash] default default options
# @return [Hash]
def extract_options!(default={})
if last.is_a?(Hash) && last.extractable_options?
default.merge pop
else
default
end
end
end
| true |
c4da98157a979a74694d7ef4bbde283cd17f1657
|
Ruby
|
gilnahmias/nextpoop
|
/EthernetFrame.rb
|
UTF-8
| 6,061 | 2.859375 | 3 |
[] |
no_license
|
#!/usr/bin/env ruby
require 'ipaddr'
require 'pcaprub'
# https://en.wikipedia.org/wiki/EtherType
ETHER_TYPE = {
0x0800 => :ipv4,
0x0806 => :arp
}
module DataConverters
def mac_address(byte_str)
byte_str.unpack('C6').map { |s| sprintf('%02x', s) }.join(':')
end
def int8(byte_str)
byte_str.unpack('C')[0]
end
def int16(byte_str)
byte_str.unpack('n')[0]
end
def int32(byte_str)
byte_str.unpack('N')[0]
end
def ipv4_addr(byte_str)
IPAddr.new(int32(byte_str), Socket::AF_INET)
end
end
class EthernetFrame
extend DataConverters
attr_reader :fields
def self.parse(raw_byte_str)
raw_byte_str.force_encoding(Encoding::BINARY)
# The first 8 bytes 'preamble' and 'start of frame delimiter' seem to not
# be present when we use libpcap. At this point we've also had the frame
# check sequence stripped off and the packet may not have had padding added
# to it. That makes this a slightly modified 'layer 2 ethernet frame'. We
# can only really tell if we have all the headers we need by length + at
# least 1 for payload, so we mind as well check that...
unless raw_byte_str.length >= 15
fail(ArgumentError, 'Not enough bytes to be an ethernet frame.')
end
fields = {
mac_dest: mac_address(raw_byte_str[0,6]),
mac_src: mac_address(raw_byte_str[6,6])
}
# VLAN tag information is 4 bytes that exist between the src_destination
# and ethertype fields but is only present when a tag is set. This is
# indicated with the special value 0x8100 where the ether_type field
# normally is.
if int16(raw_byte_str[12,2]) == 0x8100
fields[:vlan_tag] = int32(raw_byte_str[12,4])
fields[:ether_type] = int16(raw_byte_str[16,2])
fields[:payload] = raw_byte_str[17..-1]
else
fields[:ether_type] = int16(raw_byte_str[12,2])
fields[:payload] = raw_byte_str[14..-1]
end
new(fields)
end
def payload
return @payload if @payload
if fields[:ether_type] <= 1500
# Only indicates payload *size*, we'd need to do sub-protocol detection
# ourselves. I believe payload extraction is handled within libpcap
# though it appears to leave padding in.
if fields[:ether_type] != fields[:payload].length
warn('Ethernet frame payload length mismatch (%i/%i).' % [fields[:ether_type], fields[:payload].length])
end
end
# Check if this is an ARP packet
case fields[:ether_type]
when 0x0800
# IPv4
when 0x0806
# ARP
@payload = ARPPacket.parse(fields[:payload], self)
when 0x8137
# IPX
when 0x86dd
# IPv6
else
# Unknown
@payload = fields[:payload]
end
end
def initialize(fields = {})
@fields = fields
end
end
class ARPPacket
extend DataConverters
attr_reader :fields
def self.parse(raw_byte_str, parent = nil)
raw_byte_str.force_encoding(Encoding::BINARY)
unless raw_byte_str.length >= 28
warn('Incorrect byte length (%i) for an ARP packet' % raw_byte_str.length)
end
fields = {
hardware_type: int16(raw_byte_str[0,2]),
protocol_type: int16(raw_byte_str[2,2]),
hardware_len: int8(raw_byte_str[4]),
protocol_len: int8(raw_byte_str[5]),
operation: int16(raw_byte_str[6,2])
}
# This is where the packet disection gets a little weird... We need to use
# a value we've already retrieved to build up the rest of the information.
# Man there has GOT to be a better way to do this... Maybe using a string
# scanner?
offset = 8
fields[:sender_hw_addr] = raw_byte_str[offset, fields[:hardware_len]]
offset += fields[:hardware_len]
fields[:sender_proto_addr] = raw_byte_str[offset, fields[:protocol_len]]
offset += fields[:protocol_len]
fields[:target_hw_addr] = raw_byte_str[offset, fields[:hardware_len]]
offset += fields[:hardware_len]
fields[:target_proto_addr] = raw_byte_str[offset, fields[:protocol_len]]
offset += fields[:protocol_len]
# Funny thing...
unless raw_byte_str.length == offset || raw_byte_str[offset..-1].bytes.select { |b| b != 0x00 }.empty?
warn('Additional hidden data found in ARP packet: %s' % raw_byte_str[offset..-1].inspect)
end
new(fields)
end
def hardware_type
return :ethernet if fields[:hardware_type] == 1
fields[:hardware_type]
end
def initialize(fields = {}, parent = nil)
@fields = fields
@parent = parent
end
# @return [:announcement, :gratuitous, :invalid, :probe, :request, :response]
def operation
return :announcement if fields[:target_proto_addr] == fields[:sender_proto_addr] && fields[:target_hw_addr] == fields[:sender_hw_addr]
return :gratuitous if fields[:target_proto_addr] == fields[:sensor_proto_addr] && fields[:target_hw_addr] == '00:00:00:00:00:00'
if fields[:operation] == 1
return :probe if fields[:target_proto_addr] == '0.0.0.0'
return :request
end
return :reply if fields[:operation] == 2
return :invalid
end
def output
{
hardware_type: hardware_type,
protocol_type: protocol_type,
operation: operation,
sender_hw_addr: sender_hw_addr,
sender_proto_addr: sender_proto_addr,
target_hw_addr: target_hw_addr,
target_proto_addr: target_proto_addr
}
end
def protocol_type
ETHER_TYPE[fields[:protocol_type]] || fields[:protocol_type]
end
def sender_hw_addr
return self.class.mac_address(fields[:sender_hw_addr]) if hardware_type == :ethernet
fields[:sender_hw_addr]
end
def sender_proto_addr
return self.class.ipv4_addr(fields[:sender_proto_addr]) if protocol_type == :ipv4
fields[:sender_proto_addr]
end
def target_hw_addr
return self.class.mac_address(fields[:target_hw_addr]) if hardware_type == :ethernet
fields[:target_hw_addr]
end
def target_proto_addr
return self.class.ipv4_addr(fields[:target_proto_addr]) if protocol_type == :ipv4
fields[:target_proto_addr]
end
end
| true |
66e0864209ce9bcb42cf01c6e525bfc23369d155
|
Ruby
|
amair/pivotal_to_pdf
|
/lib/pivotal_to_pdf/story.rb
|
UTF-8
| 663 | 2.71875 | 3 |
[] |
no_license
|
class Story < Pivotal
def label_text
return "" if !self.respond_to?(:labels) || self.labels.nil? || self.labels.empty?
labels
end
def points
return nil unless self.feature?
"Points: " + (self.respond_to?(:estimate) && !self.estimate.eql?(-1) ? self.estimate.to_s : "Not yet estimated")
end
def story_color
return "52D017" if feature?
return "FF0000" if bug?
return "FFFF00" if chore?
return "000000" # For Releases or Unknown type
end
private
["feature", "bug", "chore", "release"].each do |type_str|
class_eval <<-EOS
def #{type_str}?
self.story_type == "#{type_str}"
end
EOS
end
end
| true |
3e455e0cb575485b2e48cf27c1b5040952d99039
|
Ruby
|
gautamrekolan/shop
|
/app/helpers/pages_helper.rb
|
UTF-8
| 643 | 2.859375 | 3 |
[] |
no_license
|
module PagesHelper
def preview (string, count = 300)
# String::shorten (naiv)
# Autor: Martin Labuschin
# Erstellt am 29.Juli 2007
# String wird auf die durch count (optional, standard 30) bestimmte Anzahl von Zeichen gekürzt. Es werden dann ganze Wörter (erkannt durch Leerräume) zurückgegeben. Falls wirklich eine Kürzung duchgeführt wurde, wird ' ...' angehangen.
# BEMERKUNG: Es wird nur Plaintext erwartet
if string.length >= count
shortened = string[0, count]
splitted = shortened.split(/ /)
words = splitted.length
splitted[0, words-1].join(" ") + ' ...'
else
string
end
end
end
| true |
8b55c7b6beb720edce9de56f6bb72b431512d4e4
|
Ruby
|
now/rbtags
|
/lib/rbtags-1.0/file.rb
|
UTF-8
| 416 | 2.671875 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
class RbTags::File
def initialize(file, line)
@file, @line = file, Integer(line)
end
def name
@@expanded ||= Hash.new{ |files, file| files[file] = File.expand_path(file) }
@@expanded[@file]
end
def line
@@lines ||= Hash.new{ |lines, file|
lines[file] = File.open(file, 'rb'){ |io| io.map{ |line| line.chomp } }
}
@@lines[@file][@line - 1]
end
end
| true |
1350a0947c662955dadc33bd3fbe4e97a3cc1185
|
Ruby
|
MikeDulik/landlord-1
|
/models/Tenant.rb
|
UTF-8
| 199 | 3 | 3 |
[] |
no_license
|
class Tenant
attr_accessor :name, :age, :gender
def initialize(initial_name, initial_age, initial_gender)
@name = initial_name
@age = initial_age
@gender = initial_gender
end
end
| true |
28b479f7333e15438b106ed3ea1484056c89f167
|
Ruby
|
oamado/checkout
|
/basic_price_rule.rb
|
UTF-8
| 216 | 2.90625 | 3 |
[] |
no_license
|
require_relative 'abstract_price_rule'
class BasicPriceRule < AbstractPriceRule
def initialize(base_price)
@base_price = base_price
end
def calculate_price(quantity)
@base_price * quantity
end
end
| true |
cd57448ad79609a00039db76c85bc39dab39a96c
|
Ruby
|
bjf-flatiron/ruby-project-guidelines
|
/lib/bank.rb
|
UTF-8
| 378 | 2.65625 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
class Bank < ActiveRecord::Base
has_many :accounts
has_many :customers, through: :accounts
def self.total_banks
Bank.all.count
end
def self.Bank_id
Bank.all.map {|b| [b.id, b.name]}
end
def self.find_id(name)
x = Bank.find_by(name: name)
p x.id
end
def self.create_new(name, location)
self.create(name: name.downcase, location: location.downcase)
end
end
| true |
4ac98f02dcf686256ddfa4abcc7856a274af561a
|
Ruby
|
ewansheldon/Battle
|
/lib/game.rb
|
UTF-8
| 862 | 3.640625 | 4 |
[] |
no_license
|
class Game
attr_reader :attack, :players, :current_turn, :winner, :loser
def initialize(player_1, player_2)
@players = [player_1, player_2]
@player_1 = player_1
@player_2 = player_2
@current_turn = player_1
end
def player_1
@players.first
end
def player_2
@players.last
end
def attack
opponent_of(current_turn).receive_damage
end
def switch_turns
@current_turn = opponent_of(current_turn)
end
def opponent
opponent_of(current_turn)
end
def over?
if @player_1.hp == 0 || @player_2.hp == 0
@loser = @players.select { |player| player.hp == 0}.first
@winner = @players.select { |player| player.hp != 0}.first
return true
else
false
end
end
private
def opponent_of(the_player)
@players.select { |player| player != the_player }.first
end
end
| true |
d50a73d2182c619c58c62fcce5b2c6b7e1782988
|
Ruby
|
GreatMedivack/cwrc
|
/main.rb
|
UTF-8
| 12,950 | 2.59375 | 3 |
[] |
no_license
|
require 'telegram/bot'
require 'date'
require 'ap'
token = ''
require 'sqlite3'
@db = SQLite3::Database.new 'database.db'
RES_MSG = "\u{1F4E5}<b>Изменения на складе:</b> \n"
GET_MSG = "\t\t\n\u{1F53A}<b>Получено: </b>\n"
LOS_MSG = "\t\t\n\u{1F53B}<b>Потеряно: </b>\n"
NOTHING_MSG = "Нет изменений \n"
ITEMS = [:id, :amount, :user_id, :item_type_id, :in_report_list]
GET_ITEM = [:amount, :title, :cw_id, :valuable]
GET_ITEMS = [:amount, :title, :item_type_id, :valuable]
GET_VALUABLE_ITEMS = [:cw_id, :amount, :title]
USERS = [:id, :name, :level, :class, :cw_id, :updated_at]
TRADE_BOT = 278525885
CW_BOT = 265204902
PROFILE_LIFE_TIME = 600
STOCK_LIFE_TIME = 60
ADMIN = 98141300
VALUABLE_ITEM = "\u{2B50}"
SIMPLE_ITEM = "\u{1F539}"
NOT_RESOURCE = "\u{1F458}"
# Превый запуск
def user_initialize(user_id)
user = @db.execute("select * from users where cw_id=?", user_id)
if user == []
@db.execute "insert into users (cw_id) values ( ? )", user_id
user = @db.execute("select * from users where cw_id=?", user_id)
else
end
get_hash(user.first, USERS)
end
def insert_item(item, user_id)
@db.execute "insert into items (item_type_id, amount, user_id, in_report_list) values ( ?, ?, ?, ? )",
item[:cw_id],
item[:amount],
user_id,
1
end
def list_item_types
msg = ""
item_types = @db.execute("select id, title, valuable from item_types where cw_id=?", cw_id).flatten
item_types.each do |item|
msg += "#{item[1]} #{item[2] ==1 ? VALUABLE_ITEM : SIMPLE_ITEM} \/change_#{item[2]}_#{item[0]}\n"
end
msg
end
def change_valuable(id, val)
@db.execute "update item_types set valuable=? where id=?", val == 0 ? 1 : 0, id
end
def reset_statuses
@db.execute "update items set in_report_list=?", 0
end
def get_hash(data, model)
data ? model.map.with_index {|x, i| [x, data[i]]}.to_h : {}
end
def update_item(item, user_id)
@db.execute "update items set amount=?, in_report_list=? where item_type_id=? and user_id=?",
item[:amount],
1,
item[:cw_id],
user_id
end
# Работа с типами предметов
def get_item_name(cw_id)
@db.execute("select title from item_types where cw_id=?", cw_id).flatten.first
end
def get_item_types_ids
@db.execute("select cw_id from item_types").flatten
end
def add_item_type(title, cw_id)
@db.execute "insert into item_types (title, cw_id, valuable) values ( ?, ?, ?)",
title,
cw_id,
0
end
def update_item_status (item_type_id, user_id)
@db.execute "update items set in_report_list=? where item_type_id=? and user_id=?",
1,
item_type_id,
user_id
end
def get_item(item_type_id, user_id)
data = @db.execute("select amount, item_types.title, item_type_id, item_types.valuable from items inner join item_types on items.item_type_id = item_types.cw_id where item_type_id=? and user_id=?", item_type_id, user_id).flatten
data.empty? ? nil : GET_ITEM.map.with_index {|x, i| [x, data[i]]}.to_h
end
def get_valuable_resources(user_id)
@db.execute("select items.item_type_id, items.amount, item_types.title from items inner join item_types on items.item_type_id = item_types.cw_id where items.user_id=? and item_types.valuable=? and items.amount > ?", user_id, 1, 0)
end
def create_res_hide_btns(items)
buttons = []
line = []
items.each_with_index do |item, index|
h_item = get_hash(item, GET_VALUABLE_ITEMS)
line << Telegram::Bot::Types::InlineKeyboardButton.new( text: "#{h_item[:title]} x#{h_item[:amount]}",
switch_inline_query: "/wts_#{h_item[:cw_id]}_#{h_item[:amount]}_1000")
if (index + 1) % 3 == 0
buttons << line
line = []
end
end
buttons << line
markup = Telegram::Bot::Types::InlineKeyboardMarkup.new(inline_keyboard: buttons)
end
def update_profile(msg, user)
hero_name = hero_class = hero_level = 'unknown'
msg.each_line do |line|
if line =~ /, [А-Я][а-я]+ [А-Я][а-я]+ замка/
arr = line.split(',')
hero_name = arr[0].slice(/[а-яА-Яa-zA-Z0-9\-\(\) ]{4,16}/)
hero_class = arr[1].split().first
elsif line =~ /Уровень/
hero_level = line.slice(/\d+/)
end
end
updated_at = Time.now.strftime("%Y-%m-%d")
@db.execute "update users set name=?, level=?, class=?, updated_at=? where id=?",
hero_name,
hero_level,
hero_class,
updated_at,
user[:id]
end
def share_stock
@db.execute "select item_types.cw_id, item_types.title, sum(amount), item_types.valuable from items inner join item_types on items.item_type_id = item_types.cw_id where amount > 0 group by item_type_id order by item_types.valuable desc"
end
def valid_user?(id)
valid_users = @db.execute("select cw_id from valid_users").flatten
valid_users.include?(id)
end
def add_user_to_validlist(id)
@db.execute("insert into valid_users (cw_id) values ( ? )", id) unless valid_user?(id)
end
kb = [['Информация', 'Склад'], ['Спрятать ресурсы', 'Общий склад']]
markup = Telegram::Bot::Types::ReplyKeyboardMarkup.new(keyboard: kb, one_time_keyboard: false, resize_keyboard: true)
Telegram::Bot::Client.run(token) do |bot|
bot.listen do |message|
user = user_initialize(message.from.id)
case message
when Telegram::Bot::Types::CallbackQuery
when Telegram::Bot::Types::InlineQuery
if message.query =~ /wts_\d+_\d+_1000/
data = message.query.split('_')
title = get_item_name(data[1])
results = [
[1, "Спрятать #{title} x#{data[2]}", "/wts_#{data[1]}_#{data[2]}_1000"]
].map do |arr|
Telegram::Bot::Types::InlineQueryResultArticle.new(
id: arr[0],
title: arr[1],
input_message_content: Telegram::Bot::Types::InputTextMessageContent.new(message_text: arr[2])
)
end
bot.api.answer_inline_query(inline_query_id: message.id, results: results)
end
when Telegram::Bot::Types::Message
res_msg = ""
get_res = ""
los_res = ""
unless valid_user? message.from.id
bot.api.send_message(chat_id: 98141300, text: "#{message.from.id} \n#{message.text}\n\/adduser_#{message.from.id}")
next
end
if message.text == "/start"
msg = "Набери команду /stock в @ChatWarsTradeBot и отправь форвард полученного сообщения этому боту"
bot.api.send_message(chat_id: message.from.id, text: msg, reply_markup: markup)
next
end
if message.text == 'Спрятать ресурсы'
bot.api.send_message(chat_id: message.chat.id, text: 'Выбери ресурс', reply_markup: create_res_hide_btns(get_valuable_resources(user[:id])))
end
if message.text == 'Что прятать?'
bot.api.send_message(chat_id: message.chat.id, text: list_item_types, reply_markup: markup)
end
if message.text =~ /\/change_\d_\d+/
params = message.text.split('_')
change_valuable(params[1], params[2])
bot.api.send_message(chat_id: message.chat.id, text: list_item_types, reply_markup: markup)
end
if message.text =~ /Битва семи замков через/
if message.forward_from.nil? || message.forward_date.nil? || message.forward_from.id != CW_BOT
bot.api.send_message(chat_id: message.from.id, text: "Форвард не из @ChatWarsBot")
next
elsif Time.now.to_i - message.forward_date > PROFILE_LIFE_TIME
bot.api.send_message(chat_id: message.from.id, text: "Нужен профиль не старше 10 минут")
next
end
update_profile(message.text, user)
bot.api.send_message(chat_id: message.from.id, text: "Профиль обновлен")
next
end
if Date.today - Date.parse(user[:updated_at]) > 5
msg = "Твой профиль устарел. Набери /me в @ChatWarsBot и пришли форвард"
bot.api.send_message(chat_id: message.from.id, text: msg)
next
end
if message.text == "Информация"
msg = "#{user[:cw_id]}\nИмя:\t<b>#{user[:name]}</b>\nКласс:\t#{user[:class]}\nУровень:\t#{user[:level]}"
bot.api.send_message(chat_id: message.from.id, parse_mode: 'HTML', text: msg)
end
if message.text == "Склад"
items = @db.execute("select item_types.title, amount, item_types.valuable from items inner join item_types on items.item_type_id = item_types.cw_id where user_id=? and amount>? order by item_types.valuable desc", user[:id], 0)
stock = items.map {|item| "\t\t\t\t #{item[2] == 1 ? VALUABLE_ITEM : SIMPLE_ITEM}_#{item[0]}_ *x#{item[1]}*" }
msg = stock.join("\n")
msg = "Пусто" if msg.empty?
bot.api.send_message(chat_id: message.from.id, parse_mode: 'Markdown', text: "\u{1F4DC}*Содержимое склада*\n#{msg}")
end
if message.text == 'Общий склад'
items = share_stock
puts items
stock = items.map {|item| "\t\t\t\t #{item[3] == 1 ? VALUABLE_ITEM : (item[0] / 1000 > 0) ? NOT_RESOURCE : SIMPLE_ITEM}_#{item[1]}_ *x#{item[2]}*" }
msg = stock.join("\n")
msg = "Пусто" if msg.empty?
bot.api.send_message(chat_id: message.from.id, parse_mode: 'Markdown', text: "\u{1F4DC}*Содержимое всех складов*\n#{msg}")
end
if message.text =~ /\/send_message/
begin
parse = message.text.split('*')
bot.api.send_message(chat_id: parse[1].to_i, text: parse[2])
rescue
bot.api.send_message(chat_id: 98141300, text: 'Не отправлено')
next
end
end
if message.text == "/stock"
next
end
if message.text =~ /\/adduser_\d+/ && message.from.id == ADMIN
user_id = message.text.split('_').last.to_i
add_user_to_validlist(user_id)
next
end
#Основной говнокод
if message.text =~ /Твой склад с материалами/
if message.forward_from.nil? || message.forward_from.id != TRADE_BOT
bot.api.send_message(chat_id: message.from.id, text: "Форвард не из @ChatWarsTradeBot")
next
elsif Time.now.to_i - message.forward_date > STOCK_LIFE_TIME
bot.api.send_message(chat_id: message.from.id, text: "Нужен форвард не старше 1 минуты")
next
end
bot.api.send_message(chat_id: 98141300, text: "#{user[:name]} отправил репорт!\n ")
stock = []
cw_ids = get_item_types_ids
message.text.each_line do |line|
break if line == "\n"
next unless line =~ /^\/add_\d+ /
cw_id = line.slice(/^\/add_\d+ /).slice(/\d+/).to_i
title = line.slice(/[а-яА-Я][а-яА-Я 0-9]*[а-яА-Я]/).strip
unless cw_ids.include?(cw_id)
add_item_type(title, cw_id)
cw_ids << cw_id
end
amount = line.slice(/ \d+/).to_i
stock << {cw_id: cw_id, amount: amount}
end
# check stock
stock.each do |item|
db_item = get_item(item[:cw_id], user[:id])
if db_item
diff = item[:amount] - db_item[:amount]
if diff == 0
update_item_status(item[:cw_id], user[:id])
elsif diff > 0
get_res += "\t\t\t\t#{db_item[:valuable] == 1 ? VALUABLE_ITEM : SIMPLE_ITEM }#{db_item[:title]} +#{diff}\n"
update_item(item, user[:id])
else
los_res += "\t\t\t\t#{db_item[:valuable] == 1 ? VALUABLE_ITEM : SIMPLE_ITEM }#{db_item[:title]} #{diff}\n"
update_item(item, user[:id])
end
else
insert_item(item, user[:id])
db_item = get_item(item[:cw_id], user[:id])
get_res += "\t\t\t\t#{db_item[:valuable] == 1 ? VALUABLE_ITEM : SIMPLE_ITEM}#{db_item[:title]} +#{db_item[:amount]}\n"
end
end
#check db
items = @db.execute("select amount, item_types.title, item_type_id, item_types.valuable from items inner join item_types on items.item_type_id = item_types.cw_id where user_id=? and in_report_list=?", user[:id], 0)
items.each do |item|
h_item = get_hash(item, GET_ITEMS)
los_res += "\t\t\t\t#{h_item[:valuable] == 1 ? VALUABLE_ITEM : SIMPLE_ITEM }#{h_item[:title]} -#{h_item[:amount]}\n" if h_item[:amount] != 0
update_item({cw_id: h_item[:item_type_id], amount: 0}, user[:id])
end
res_msg += ( get_res != "" ? GET_MSG + get_res : "") + (los_res != "" ? LOS_MSG + los_res : "" )
final_msg = res_msg == "" ? NOTHING_MSG : RES_MSG + res_msg
bot.api.send_message(chat_id: message.from.id, parse_mode: 'HTML', text: final_msg)
reset_statuses
end
end
end
end
| true |
2d32e7d8ac9eb65791efd6c90dfd50e8605d42b4
|
Ruby
|
dalen/puppet-defn
|
/lib/puppet/parser/functions/apply.rb
|
UTF-8
| 717 | 2.640625 | 3 |
[] |
no_license
|
Puppet::Parser::Functions::newfunction(
:apply,
:type => :rvalue,
:arity => -3,
:doc => <<-'ENDHEREDOC') do |args|
Call a Puppet lambda
ENDHEREDOC
require 'puppet/parser/ast/lambda'
if args.length == 2
lam, arglist = *args
else
lam, arglist, pblock = *args
unless pblock.respond_to?(:puppet_lambda)
raise ArgumentError, ("apply(): wrong argument type (#{pblock.class}; must be a parameterized block.")
end
end
unless lam.respond_to?(:puppet_lambda)
raise ArgumentError, ("apply(): wrong argument type (#{lam.class} first param; must be a parameterized block.")
end
ret = lam.call(self,*arglist)
if pblock
pblock.call(self,ret)
else
ret
end
end
| true |
1ba672f9f4c3b8f445c3440bf8a22c7a9453a09d
|
Ruby
|
redhataccess/ascii_binder
|
/lib/ascii_binder/distro_branch.rb
|
UTF-8
| 2,561 | 2.640625 | 3 |
[
"MIT"
] |
permissive
|
require 'ascii_binder/helpers'
include AsciiBinder::Helpers
module AsciiBinder
class DistroBranch
attr_reader :id, :name, :dir, :distro, :distro_name, :distro_author
def initialize(branch_name,branch_config,distro)
@id = branch_name
@name = branch_config['name']
@dir = branch_config['dir']
@distro = distro
@distro_name = distro.name
@distro_author = distro.author
if branch_config.has_key?('distro-overrides')
if branch_config['distro-overrides'].has_key?('name')
@distro_name = branch_config['distro-overrides']['name']
end
if branch_config['distro-overrides'].has_key?('author')
@distro_author = branch_config['distro-overrides']['author']
end
end
end
def branch_path
@branch_path ||= File.join(preview_dir,@distro.id,@dir)
end
def branch_url_base
@branch_url_base ||= File.join('/',@dir)
end
def branch_stylesheet_dir
@branch_stylesheet_dir ||= File.join(branch_path,STYLESHEET_DIRNAME)
end
def branch_javascript_dir
@branch_javascript_dir ||= File.join(branch_path,JAVASCRIPT_DIRNAME)
end
def branch_image_dir
@branch_image_dir ||= File.join(branch_path,IMAGE_DIRNAME)
end
def is_valid?
validate
end
def errors
validate(true)
end
private
def validate(verbose=true)
errors = []
unless valid_string?(@id)
if verbose
errors << "Branch ID '#{@id}' is not a valid string."
else
return false
end
end
unless valid_string?(@name)
if verbose
errors << "Branch name '#{@name}' for branch ID '#{@id}' is not a valid string."
else
return false
end
end
unless valid_string?(@dir)
if verbose
errors << "Branch dir '#{@dir}' for branch ID '#{@id}' is not a valid string."
else
return false
end
end
unless valid_string?(@distro_name)
if verbose
errors << "Branchwise distro name '#{@distro_name}' for branch ID '#{@id}' is not a valid string."
else
return false
end
end
unless valid_string?(@distro_author)
if verbose
errors << "Branchwise distro author '#{@distro_author}' for branch ID '#{@id}' is not a valid string."
else
return false
end
end
return errors if verbose
return true
end
end
end
| true |
3c8b41718eef3d0fdb706addb1d4bacf8cf660a8
|
Ruby
|
chenschel/tdd_blackjack
|
/tests/blackjack/card_runner.rb
|
UTF-8
| 244 | 2.78125 | 3 |
[] |
no_license
|
# frozen_string_literal: true
require_relative 'card'
suit = 'Clubs'
rank = '9'
card = Card.new(suit, rank)
puts "Suit of card: '#{card.suit}'"
puts "Rank of card:'#{card.rank}'"
puts "Card: #{card}"
card.show = false
puts "Card: #{card}"
| true |
3e031836c66eeafccd82c70b48de45d22a78ca0f
|
Ruby
|
Julioliveira/Ruby
|
/Exercises/hourMilitary.rb
|
UTF-8
| 512 | 3.1875 | 3 |
[] |
no_license
|
militarHour = "-1";
hour12 = ""
hour24 = 0
min = ""
puts 'Enter the military hour'
militarHour = gets.chomp
hour24 = militarHour[0..1].to_i
min = militarHour[2..3]
if hour24 == 0 then
hour12 = "12:#{min} a.m."
elsif militarHour.size != 4
hour12 = ""
elsif hour24 < 0 || hour24 > 23 || min.to_i > 59
hour12 = ""
elsif hour24 <= 11 then
hour12 = "#{hour24}:#{min} a.m."
elsif hour24 == 12 then
hour12 = "12:#{min} p.m."
elsif hour24 <= 23 then
hour12 = "#{hour24 - 12}:#{min} p.m."
end
puts hour12
| true |
04826eb897c669de3fa1b5b785438b094dc550da
|
Ruby
|
buihaian/gridlook
|
/spec/helpers/application_helper_spec.rb
|
UTF-8
| 541 | 2.53125 | 3 |
[] |
no_license
|
require "spec_helper"
describe ApplicationHelper do
describe "#inspect_value" do
def h(x)
Rack::Utils.escape_html(x)
end
it "shows an array in paragraphs" do
inspect_value(["foo", "bar"]).should == "<p>foo</p><p>bar</p>"
end
it "shows a hash value by value" do
actual = inspect_value({ foo: "1", bar: ["2"] })
actual.should == '<p>foo = 1</p>'+
'<p>bar = ["2"]</p>'
end
it "inspects scalars" do
inspect_value(1).should == "1"
end
end
end
| true |
1ffb7b136e203ad08ab9dc47f71a93800c97b736
|
Ruby
|
donnymays/travel_api
|
/app/models/review.rb
|
UTF-8
| 1,180 | 2.5625 | 3 |
[] |
no_license
|
class Review < ApplicationRecord
# Validations
validates :city, :country, :content, :rating, :user_name, presence: true
validates :rating, numericality: { only_integer: true, less_than: 6, greater_than: 0}
# Scopes
scope :city, -> (city_name) { where("city ilike ?", "%#{city_name}%") }
scope :country, -> (country_name) { where("country ilike ?", "%#{country_name}%") }
scope :search, -> (city_name, country_name) { where("city ilike ? AND country ilike ?", "%#{city_name}%", "%#{country_name}%") }
scope :most_reviewed, -> { select("reviews.city, reviews.country, count(*)").
group("reviews.city, reviews.country").
order("count(*) DESC").
limit(2)
}
scope :highest_rated, -> { group("reviews.rating, reviews.id").
order("reviews.rating DESC").
limit(2)
}
scope :random_location, -> (city_array) { where("city ilike ?", "#{city_array.sample}") }
# Review.select("reviews.city, reviews.country, count(*)").group("reviews.city, reviews.country").order("count(*) DESC")
# Callback
before_save(:titleize)
private
def titleize
self.city = self.city.titleize
self.country = self.country.titleize
end
end
| true |
84f319e934ab067df3985bb006c47474caa86e60
|
Ruby
|
rishirajkumar97/vending_machine
|
/app/controllers/beverages_controller.rb
|
UTF-8
| 843 | 2.515625 | 3 |
[] |
no_license
|
# frozen_string_literal: true
# Beverages Controller to Get / Show/ Create new Beverages
class BeveragesController < ApplicationController
# Index method to get all the beverages
def index
beverages = Beverage.all
render json: {
items: ActiveModelSerializers::SerializableResource.new(beverages),
total_results: beverages.count
}
end
# create method to post a new Beverages to the database
def create
render json: Beverage.create!(beverage_post_params), status: :created
end
# show Method to revtrieve a single Beverage by ID
def show
params.require(%i[id])
render json: Beverage.find_by!(id: params[:id])
end
# to Delete a Beverage by ID
def destroy
params.require(%i[id])
beverage = Beverage.find_by!(id: params[:id])
beverage.destroy!
head :no_content
end
end
| true |
cced39d756b4c35a0122cf34f30a14792a3649ef
|
Ruby
|
staster86/Ruby_Lesson_24
|
/app.rb
|
UTF-8
| 1,531 | 2.6875 | 3 |
[
"MIT"
] |
permissive
|
require 'rubygems'
require 'sinatra'
require 'sinatra/reloader'
get '/' do
erb "Hello! <a href=\"https://github.com/bootstrap-ruby/sinatra-bootstrap\">Original</a> pattern has been modified for <a href=\"http://rubyschool.us/\">Ruby School</a>"
end
get '/about' do
erb :about
end
get '/visit' do
erb :visit
end
get '/contacts' do
erb :contacts
end
post '/visit' do
@color = params[:color]
@barber = params[:barber]
@username = params[:username]
@phone = params[:phone]
@datetime = params[:datetime]
hh = { :username => 'Введите имя',
:phone => 'Введите телефон',
:datetime => 'Введите дату и время' }
@error = hh.select {|key,_| params[key] == ""}.values.join(", ")
if @error != ''
return erb :visit
end
f = File.open "./public/user.txt", "a"
f.write "Парикхмахер: #{@barber}, Клиент: #{@username}, Телефон #{@phone}, Дата и время: #{@datetime}, Цвет: #{@color}\n"
f.close
erb "Хорошо уважаемый #{@username}! Ваш парикхмахер: #{@barber}, телефон для связи с Вами #{@phone}. Ждём Вас #{@datetime} и покрасим ваши волосы в #{@color} цвет."
end
post '/contacts' do
@email = params[:email]
@message = params[:message]
f = File.open "./public/contacts.txt", "a"
f.write "Почта: #{@email}, Сообщение: #{@message}\n"
f.close
erb "Спасибо за отзыв! Мы учтём Ваши пожелания."
end
| true |
bf082c7d931e2a7c84b0e22ce8c415c4205d6235
|
Ruby
|
sattelbergerp/pokemon-scraper-cb-000
|
/lib/pokemon.rb
|
UTF-8
| 503 | 3.296875 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
class Pokemon
attr_accessor :id, :name, :type, :hp, :db
def self.save(name, type, db)
db.execute("INSERT INTO pokemon(name, type) VALUES (?,?)", name, type)
end
def self.find(id, db)
row = db.execute("SELECT * FROM pokemon WHERE id = ?", [id])[0]
Pokemon.new(id: row[0], name: row[1], type: row[2], hp: row[3])
end
def initialize(hash)
hash.each do |k,v|
self.send("#{k}=", v)
end
end
def alter_hp(hp, db)
db.execute("UPDATE pokemon SET hp=? WHERE id=?", [hp, id])
end
end
| true |
6120914babeb49a022f15f78a1eb6a51e5327455
|
Ruby
|
Devtron3737/project_library
|
/RoutesAndControllers/bin/my_script.rb
|
UTF-8
| 761 | 2.734375 | 3 |
[] |
no_license
|
require 'addressable/uri'
require 'rest-client'
# my_script.rb
# def update_user
# url = Addressable::URI.new(
# scheme: 'http',
# host: 'localhost',
# port: 3000,
# path: '/users/1.json'
# ).to_s
#
# # begin
# puts RestClient.patch(
# url,
# { user: { name: "newguy", email: "newguy@email"} }
# )
# # rescue
# # raise "please put in the right parameters"
# # end
# end
#
#
#
# update_user
#
#
#
#
# my_script.rb
def create_user
url = Addressable::URI.new(
scheme: 'http',
host: 'localhost',
port: 3000,
path: '/users.json'
).to_s
begin
puts RestClient.patch(
url,
{ user: { username: "devin"} }
)
rescue
raise "please put in the right parameters"
end
end
create_user
| true |
cfce9bd8d1db8dcf61838e99e2ddcb5c52b927db
|
Ruby
|
mihir787/bizzspot
|
/app/services/mapbox_service.rb
|
UTF-8
| 549 | 2.703125 | 3 |
[] |
no_license
|
class MapboxService
attr_reader :connection
def initialize
@connection = Hurley::Client.new('http://api.tiles.mapbox.com')
end
def location(address)
add = address.split.join(' ').gsub(/[^0-9a-z]/i, ' ').gsub(" ", "+")
mapbox_body = parse(connection.get("v4/geocode/mapbox.places/#{add}.json?access_token=pk.eyJ1IjoibWloaXI3ODciLCJhIjoiNDE2NDkzNzdlZTA2N2RjMmM4NWNkNjA1MjIwMGMxNDIifQ.3ggS6ol72ln878GzLZnfDQ").body)
located = mapbox_body[:features].first
{address: located[:place_name], coordinates: located[:center]}
end
private
def parse(response)
JSON.parse(response, symbolize_names: true)
end
end
| true |
d0f5138bf23bfbc06bde1140a29395d73b1cd4c6
|
Ruby
|
jcmorrow/dominion-simulator
|
/big_money_player.rb
|
UTF-8
| 1,383 | 3.203125 | 3 |
[] |
no_license
|
require_relative 'player'
class BigMoneyPlayer < Player
def buy_something
case
when @treasure == 3 && !(@deck.includes("Silver"))
puts "I will buy a Silver"
buy(Silver)
when @treasure == 3 && @deck.includes("Silver")
puts "I will buy a village"
buy(Village)
when (@treasure == 4 || @treasure == 5) &&
(@deck.count("Smithy") <= @deck.count("Village"))
puts "I will buy a smithy"
buy(Smithy)
when @treasure == 6 || @treasure == 7
puts "I will buy a gold"
buy(Gold)
when @treasure >= 8
puts "I will buy a province"
buy(Province)
else
puts "I will buy nothing and try to engender pity in my opponents"
end
end
def play_cards
played = false
if(@hand.contains("Smithy") && @actions >= 2)
smithy = @hand.first("Smithy")
smithy.play(self)
@discard_pile << smithy
@actions = @actions - 1
played = true
elsif(@hand.contains("Village"))
village = @hand.first("Village")
village.play(self)
@discard_pile << village
@actions = @actions - 1
played = true
elsif(@hand.contains("Smithy"))
smithy = @hand.first("Smithy")
smithy.play(self)
@discard_pile << smithy
@actions = @actions - 1
played = true
end
if(@actions > 0 && played)
play_cards
end
end
end
| true |
0a619cd289f9bb00ed1bc8ebd8fd7c84c57c5c1d
|
Ruby
|
reach075710/study_Ruby
|
/AtCoder/ABC/ABC_143/C.rb
|
UTF-8
| 193 | 3.125 | 3 |
[] |
no_license
|
#set
n = gets.chomp.to_i
s = gets.chomp.split("")
#main
(0 .. n - 2).each do |i|
if s[n - 1 - i] == s[n - 2 -i] then
s.delete_at(n - 1 -i)
end
end
print ("#{s.join.length}\n")
| true |
a4cf62e9fc810878a67e54d7fb521920a717c74b
|
Ruby
|
fumihiroito/poiful
|
/lib/poiful/result.rb
|
UTF-8
| 1,935 | 2.78125 | 3 |
[
"MIT"
] |
permissive
|
module Poiful
class LineprofResult
def self.parse(raw_result)
raw_result.map do |file_path, r|
next unless r.size > 1
parse_result(file_path, r)
end.compact
end
private
def self.parse_result(file_path, result)
file_result = nil
begin
file_result = FileResult.new(file_path, result.shift)
rescue
return nil
end
file_result.file_obj.each_line.with_index do |code, idx|
next if result[idx] == nil
file_result.rows << RowResult.new(file_path, idx+1, result[idx], code)
end
file_result.file_obj.close
file_result
end
end
class Result
attr_reader :file
def initialize(file_path)
@file_path = file_path
@file = File.basename(file_path)
end
def render(formatter)
formatter.format(rows)
end
end
class FileResult < Result
attr_accessor :rows, :file_path, :total_wall_time, :total_cpu_time
def initialize(file_path, profile)
super(file_path)
unless File.exist?(file_path)
raise
end
@total_wall_time = profile[0] / 1000.0
@child_wall_time = profile[1] / 1000.0
@exclusive_wall_time = profile[2] / 1000.0
@total_cpu_time = profile[3] / 1000.0
@child_cpu_time = profile[4] / 1000.0
@exclusive_cpu_time = profile[5] / 1000.0
@total_allocated_bojects = profile[6] if profile.size == 7
@rows = []
end
def file_obj
@file_obj ||= File.open(@file_path)
end
end
class RowResult < Result
attr_reader :total_wall_time, :line, :calls, :code
def initialize(file_path, line_number, profile, code)
super(file_path)
@line = line_number
@total_wall_time = profile[0] / 1000.0
@total_cpu_time = profile[1] / 1000.0
@calls = profile[2]
@total_allocated_objects = profile[3] if profile.size == 4
@code = code
end
end
end
| true |
9e39beed1de18215a3bc7648f23db42069f4497c
|
Ruby
|
mpchadwick/jekyll-pre-commit
|
/lib/jekyll-pre-commit/checks/front_matter_variable_is_not_duplicate.rb
|
UTF-8
| 1,001 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
module Jekyll
module PreCommit
module Checks
class FrontMatterVariableIsNotDuplicate < Check
def check(staged, not_staged, site, args)
if !args["variables"]
@result[:message] += "No variables to check."
return @result
end
existing = Hash.new
not_staged.each do |post|
args["variables"].each do |variable|
if !existing[variable]
existing[variable] = Array.new
end
existing[variable].push(post.data[variable]) if post.data[variable]
end
end
staged.each do |post|
args["variables"].each do |variable|
if existing[variable].include? post.data[variable]
@result[:ok] = false
@result[:message] += "#{post.data["title"]}'s #{variable} was already used. "
end
end
end
@result
end
end
end
end
end
| true |
8db5e11ef39daa5735dd6b837c7e5708c07fc6b7
|
Ruby
|
betten/SoundCloud-Developer-Challenge
|
/server.rb
|
UTF-8
| 6,016 | 2.859375 | 3 |
[] |
no_license
|
#!/usr/bin/ruby
require 'webrick'
require 'stringio'
require 'cgi'
include WEBrick
#######################################
# UploadData - an object to keep track of upload
# data, includes progress hash and file path hash
########################################
class UploadData
class << self; attr_accessor :progress, :file end
@progress = Hash.new
@file = Hash.new
end
########################################
# FileUpload - servlet to handle file upload
# reads data in chunks updating progress, then writes
# file to ./uploads
########################################
class FileUpload < HTTPServlet::AbstractServlet
def do_POST(request, response)
# check that we've received file data to upload
unless request.content_type =~ /^multipart\/form-data; boundary=(.+)/
raise HTTPStatus::BadRequest
end
# uid should be passed in query string
query = request.query_string
params = CGI.parse(query)
uid = params['uid'].to_s
# set upload progress in hash for given uid
UploadData.progress[uid] = 0
# set total length of content to be loaded
total = request.content_length.to_f
# set chunk length loaded so far to 0
sofar = 0
# keep request chunks as string
body = String.new
# load file data by chunks
request.body do |chunk|
sofar = sofar + chunk.length.to_f
progress = ((sofar / total) * 100).to_i
UploadData.progress[uid] = progress
body << chunk
end
# parse body of request and raise error if file data is empty
filedata = parse_query(request['content-type'], body)
raise HTTPStatus::BadRequest if filedata['file'].empty?
# get the name of the file being uploaded
filename = get_filename(body)
# prevent duplicate file names
while File::exists?('uploads/' + filename)
parts = filename.split('.')
parts.insert(parts.length-1, Time.now.to_i.to_s)
filename = parts.join('.')
end
# write file to ./uploads directory
f = File.new('uploads/' + filename,'wb')
f.syswrite filedata['file']
f.close
# save the path to UploadData.file hash for future use
UploadData.file[uid] = f.path
# respond upload complete
response.status = 200
response['Content-Type'] = "text/plain"
response.body = 'upload complete'
end
########################################
# parse_query - takes file content type and body of file reuqest
# and parses the query using HTTPUtiles:parse_form_data
########################################
def parse_query(content_type, body)
boundary = content_type.match(/^multipart\/form-data; boundary=(.+)/)[1]
boundary = HTTPUtils::dequote(boundary)
return HTTPUtils::parse_form_data(body, boundary)
end
########################################
# get_filename - takes body of request and uses a regex
# to find filename
########################################
def get_filename(body)
filename = 'default_file_name'
if body =~ /filename="(.*)"/
filename = $1
end
return filename
end
end
########################################
# FileUploadProgress - servlet that returns progress of upload
# for file specified by uid param passed in get request, returns
# json object containign data
########################################
class FileUploadProgress < HTTPServlet::AbstractServlet
def do_GET(request, response)
# parse query string
query = request.query_string
params = CGI.parse(query)
uid = params['uid'].to_s
# make sure we have a usable uid
if uid.empty?
raise HTTPStatus::BadRequest
end
# create progress response json object
progress = <<-eos
{
"progress": "#{UploadData.progress[uid].to_s}"
}
eos
# reset progess if at 100
if not UploadData.progress[uid].nil? and UploadData.progress[uid] >= 100
UploadData.progress[uid] = 0
end
response.status = 200
response['Content-Type'] = "text/plain"
response.body = progress
end
end
########################################
# FileUploadStatus - servlet that returns absolute and relative
# paths to file specified by uid as json object in response to
# get request
########################################
class FileUploadStatus < HTTPServlet::AbstractServlet
def do_GET(request, response)
# parse query string
query = request.query_string
params = CGI.parse(query)
uid = params['uid'].to_s
# raise bad request if uid is no good
if uid.empty?
raise HTTPStatus::BadRequest
end
# json object containing paths to file
status = <<-eos
{
"relative": "#{UploadData.file[uid]}",
"absolute": "#{File.expand_path(UploadData.file[uid])}"
}
eos
response.status = 200
response['Content-Type'] = "text/plain"
response.body = status
end
end
########################################
# FileUploadTitle - called after file upload, responds to post
# request containing title text and returns title as well as
# file paths as json object
########################################
class FileUploadTitle < HTTPServlet::AbstractServlet
def do_POST(request, response)
# get uid from query
uid = request.query['uid'].to_s
# error if no uid povided
if uid.empty?
raise HTTPStatus::BadRequest
end
title = request.query['title'].to_s
# provide default title if none entered
title = 'default title' if title.empty?
# json object containing title and file paths
out = <<-eos
{
"title": "#{title.to_s}",
"relative": "#{UploadData.file[uid]}",
"absolute": "#{File.expand_path(UploadData.file[uid])}"
}
eos
response.status = 200
response['Content-Type'] = "text/plain"
response.body = out
end
end
# new server, specify port
server = HTTPServer.new(:Port => 8090)
# set rhtml as text/html
HTTPUtils::DefaultMimeTypes.store('rhtml', 'text/html')
# mount servlets to url paths
server.mount "/", HTTPServlet::FileHandler, '/home/soundcloud'
server.mount "/upload", FileUpload
server.mount "/progress", FileUploadProgress
server.mount "/status", FileUploadStatus
server.mount "/title", FileUploadTitle
# kill server on signals
['INT', 'TERM'].each { |signal|
trap(signal) { server.shutdown }
}
server.start
| true |
63158b3b38fddd3fd93243102832a087834c371e
|
Ruby
|
KellenKolbeck/coin_counter
|
/lib/coin_counter.rb
|
UTF-8
| 755 | 3.484375 | 3 |
[] |
no_license
|
class Fixnum
define_method(:coin_counter) do
coin_array = [0, 0, 0, 0]
remainder = self
if remainder > 25
coin_array[0] = (remainder/25).floor()
remainder = remainder - coin_array[0]*25
end
if remainder > 10
coin_array[1] = (remainder/10).floor()
remainder = remainder - coin_array[1]*10
end
if remainder > 5
coin_array[2] = (remainder/5).floor()
remainder= remainder - coin_array[2]*5
end
if remainder > 1
coin_array[3] = (remainder/1).floor()
remainder= remainder - coin_array[3]
end
"Your change is: " + coin_array[0].to_s + " quarters, " + coin_array[1].to_s + " dimes, " + coin_array[2].to_s + " nickels, and " + coin_array[3].to_s + " pennies."
end
end
| true |
d856ab9aef369be4130280ce99108d23fc629376
|
Ruby
|
ElaErl/Challenges-1
|
/Easy1/point_mutations.rb
|
UTF-8
| 354 | 3.640625 | 4 |
[] |
no_license
|
class DNA
def initialize(strand)
@strand = strand
end
def hamming_distance(other_strand)
size = (other_strand.size < @strand.size) ? (other_strand.size) : (@strand.size)
result = 0
@strand.each_char.with_index do |ch, ind|
break if ind > (size - 1)
result += 1 if ch != other_strand[ind]
end
result
end
end
| true |
9d865228a6db7b8a0fbea14ad7b7eedf063dfbd5
|
Ruby
|
he9lin/wangdu
|
/lib/travel_sky/flights.rb
|
UTF-8
| 830 | 2.625 | 3 |
[] |
no_license
|
# coding: utf-8
module TravelSky
class Flights
attr_reader :depart, :return, :data, :depart_dates, :return_dates, :depart_title, :return_title
def initialize(data)
@data = data
@depart = data.xpath("//webFlightInfoList//webFlightInfo")
@return = data.xpath("//webFlightInfoList1//WebFlightInfo")
@depart_dates = data.xpath("//webDateShowList//WebDateShow")
@return_dates = data.xpath("//webDateShowList1//WebDateShow")
request = data.xpath("//searchFlightInfoDTO").first
@depart_title = "#{request.orgTime.content} #{request.orgCityName.content} - #{request.destCityName.content}"
@return_title = "#{request.returnTime.content} #{request.destCityName.content} - #{request.orgCityName.content}"
rescue NoMethodError
end
end
end
| true |
0d2c99c1ccfc6a0a4c716f155628afde4688a112
|
Ruby
|
Mizanur09/Ruby-Selenium
|
/acceptance_test/module/Common_Functions.rb
|
UTF-8
| 2,957 | 2.78125 | 3 |
[] |
no_license
|
require_relative '../Helpers_pages/globalized'
include Globalized
module Functions
def isElementPresent?(how, what)
begin
element = @driver.find_element(how, what)
return element.displayed?
rescue Exception => e
return false
end
end
def isElementVisible(locator)
begin
element = find(locator)
return element.displayed?
rescue Exception=>e
return false
end
end
def verify_text_is_visible(locator, text)
wait_for_element_to_load(locator)
puts "Verifying this text: #{text} does display for this locator: #{locator} "
element = find(locator)
return element.text.strip.should == text
end
# def verify_element_is_visible(locator)
# begin
# puts "Verifying this locator: #{locator} does display"
# find(locator).displayed?.should == true
# return true
# rescue Selenium::WebDriver::Error::NoSuchElementError => e
# return true.should == false
# end
# end
def verify_text_is_not_visible(locator, text)
puts "Verifying this text: #{text} does not display for this locator: #{locator}"
element = find(locator)
return element.text.strip.should_not == text
end
def verify_element_is_not_visible(locator)
begin
puts "Verifying this locator: #{locator} does not display"
find(locator).displayed?.should == false
return true
rescue Selenium::WebDriver::Error::NoSuchElementError => e
return true.should == true
end
end
def executeJquery(jqueryStr)
@driver.execute_script(jQuery(jqueryStr))
end
def scrollIntoElement(elementId)
s = "document.getElementById('#{elementId}').scrollIntoView(true);"
@driver.execute_script(s)
end
def removeJumpScreen
@driver.execute_script("$('.container-fluid').css('overflow', 'visible');")
end
def findElement(how, what)
element = @driver.find_element(how, what)
return element
end
# Move to the right from modal (Pop-up)
def moveArrowInputRangeToRight(how,element, numberOfArrowMove)
findElement(how,element).send_keys :tab
sleep 1
for i in 1..numberOfArrowMove
findElement(how, element).send_keys :arrow_right
sleep 1
end
end
def moveArrowInputRangeToLeft(how,element, numberOfArrowMove)
findElement(how, element).send_keys :tab
sleep 0.5
for i in 1..numberOfArrowMove
findElement(how, element).send_keys :arrow_left
sleep 0.5
end
end
# Verify the field type ..
def getFieldType(fieldElement)
field = findElement(:css, fieldElement)
type = field.tag_name
if(type == "input")
type = field.attribute("type")
end
return type
end
#It will pull out the element color
def getElementColor(selector, cssvalue)
rgb = findElement(:css, selector).css_value(cssvalue).gsub(/rgba\(/,"").gsub(/\)/,"").split(",")
color = '#%02x%02x%02x' % [rgb[0], rgb[1], rgb[2]]
return color.upcase
end
end
| true |
21fafbb26d54bbd07d7afe2ed4a6f8f0e8c8f776
|
Ruby
|
benrodenhaeuser/exercises
|
/exercism/ruby/minesweeper/test.rb
|
UTF-8
| 733 | 3.828125 | 4 |
[] |
no_license
|
# source: http://exercism.io/submissions/9cc87ce6845e4ee9940dbbfb7482cca2
# Whenever I see a grid like object that I need to index twice, I'll try and abstract away the grid such that I can index it using a method that checks that the indices are valid and that guarantees that it indexes correctly - preferably using x and y as that side-steps the issue of needing to think about whether the grid is stored row-first or col-first.
class Board
def initialize(width, height)
@width = width
@height = height
@cells = Array.new(width * height)
end
def [](x, y)
fail ArgumentError if x < 0 || x >= @width
fail ArgumentError if y < 0 || y >= @height
@cells[x + y * @width] # what does this do?
end
end
| true |
b753453139a9596f1de4520a215fd2e2d415033b
|
Ruby
|
mnsapits/AA-Projects
|
/w2d4/two_sum.rb
|
UTF-8
| 732 | 3.65625 | 4 |
[] |
no_license
|
require "byebug"
def bad_two_sum?(arr, target)
idx1 = 0
while idx1 < arr.length
idx2 = idx1 + 1
while idx2 < arr.length
return true if arr[idx1] + arr[idx2] == target
idx2 += 1
end
idx1 += 1
end
false
end
def okay_two_sum?(arr, target)
sorted_arr = arr.sort
(0...arr.length).each do |idx|
return true unless sorted_arr[idx..-1].bsearch { |x| x == (target - sorted_arr[idx]) }.nil?
end
false
end
def pair_sum?(arr, target)
hash = Hash.new()
arr.each do |ele|
hash[ele] = true
end
hash.dup.each do |key,value|
# debugger
hash[key] = false
return true if hash[target - key]
hash[key] = true
end
false
end
arr = [0, 1, 5, 7]
p pair_sum?(arr, 6)
| true |
7d6251d870acd48402922f2fce767c387f99572b
|
Ruby
|
srirammca53/update_status
|
/rubystuff/12-05-2011/arthoper.rb
|
UTF-8
| 718 | 3.921875 | 4 |
[] |
no_license
|
class Arthematic
def add()
puts "enter any two numbers"
@num1=gets()
@num2=gets()
@[email protected][email protected]_i
puts "the total addition by your numbers #@num3"
end
def sub()
puts "enter any two numbers"
@num1=gets()
@num2=gets()
@[email protected][email protected]_i
puts "the total substraction by your numbers #@num3"
end
def mul()
puts "enter any two numbers"
@num1=gets()
@num2=gets()
@[email protected]_i*@num2.to_i
puts "the total multiplication by your numbers #@num3"
end
def div()
puts "enter any two numbers"
@num1=gets()
@num2=gets()
@[email protected]_i/@num2.to_i
puts "the total addition by your numbers #@num3"
end
end
obj1 = Arthematic.new()
obj1.add()
obj1.sub()
obj1.mul()
obj1.div()
| true |
c6c6478989b6bd86a3ef8ba60feb44ca05872939
|
Ruby
|
saurabhhack123/zerp
|
/lib/zerp.rb
|
UTF-8
| 337 | 2.921875 | 3 |
[
"MIT"
] |
permissive
|
require "zerp/version"
module Zerp
# Your code goes here...
class Chatter
def say_hello
if ARGV[0]=="help"
puts "Dayo can help you in building ruby gem"
elsif ARGV[0]=="time"
puts Time.new
else
puts 'This is zerp. Coming in loud and clear. Over.'
end
end
end
end
| true |
e73f7bbf152a70f474c8a85c85681fb6aa9ebc1f
|
Ruby
|
itsolutionscorp/AutoStyle-Clustering
|
/all_data/exercism_data/src/2968.rb
|
UTF-8
| 497 | 3.046875 | 3 |
[] |
no_license
|
def compute(first_strand,second_strand)
first_strand_array = first_strand.split('')
second_strand_array = second_strand.split('')
diff_counter = 0
counter = 0
if first_strand_array.length >= second_strand_array.length
length = second_strand_array.length
else
length = first_strand_array.length
end
while counter < length
if first_strand_array[counter] != second_strand_array[counter]
diff_counter += 1
end
counter +=1
end
diff_counter
end
| true |
5bd64993b16876185629c4a73a1a80c8050bcd6a
|
Ruby
|
shockt88/HollandMedia
|
/SBIF/import55.rb
|
UTF-8
| 480 | 2.859375 | 3 |
[] |
no_license
|
require 'csv'
require 'awesome_print'
class Grant
def initialize(row) ##### Class Gramt
@row = row #def initialize(company,address)
end
def company #@company = company
@row.field("Company") #@address = adddress
end
end
table = CSV.read('Small_Business_Improvement_Fund__SBIF__Grant_Agreements.csv', :headers => true)
ap table
print table
table.each do |row|
#print row
end
| true |
f682cfda109540f20916623ace320bb15798c4cc
|
Ruby
|
emil-kirilov/Code-Runners-Problems
|
/bidding/app/helpers/users_helper.rb
|
UTF-8
| 176 | 2.515625 | 3 |
[] |
no_license
|
module UsersHelper
def self.authenticate(email, password)
user = User.find_by(email)
return nil if user.nil?
return user if user.has_password?(password)
end
end
| true |
acc7f4a59ee13fd0ceb92e1b7b8b07528e390f52
|
Ruby
|
jamie-lb/projecteuler
|
/1/ruby/eulerProblem1.rb
|
UTF-8
| 88 | 3.375 | 3 |
[] |
no_license
|
sum = 0;
0.upto(999) {
|i|
if i%3 == 0 || i%5 == 0
sum += i;
end
}
puts sum;
| true |
d27799a741febbd62d395a207da20ba2aa7fefa5
|
Ruby
|
realtradam/bad-networking
|
/client.rb
|
UTF-8
| 1,530 | 3.03125 | 3 |
[] |
no_license
|
require 'socket'
require 'ruby2d'
s = UDPSocket.new
s.bind(nil, ARGV[0])
s.send("0 #{ARGV[0]}", 0, 'localhost', 4000)
# ignore first message from server
s.recvfrom(16)
#sema = Mutex.new
# Stores the current location of player
location = "#{ARGV[0]} 0-0"
# stores where squares last known locations are
state = {}
threads = []
# this gurantees something you choose will not be executed more then 60 times a second
def once_per_frame
last = Time.now
while true
yield
now = Time.now
_next = [last + (1 / 60), now].max
sleep(_next - now)
last = _next
end
end
# tell server where you are, once per frame
threads.push(Thread.new do
once_per_frame do
s.send("1 #{ARGV[0]} #{location}", 0, 'localhost', 4000)
end
end)
# Ctrl-c will kill threads
at_exit do
puts 'trapping'
threads.each do |t|
puts 'killing'
Thread.kill t
end
end
#reciever
threads.push(Thread.new do
loop do
text, _sender = s.recvfrom(16)
#sema.synchronize do
ary = text.split('-')
state[ary[0]] = [ary[1], ary[2]]
#end
end
end)
update do
puts get(:fps)
#sema.synchronize do
state.each do |_color, square|
Square.draw(color: [[1.0, 0.0, 0.0, 1.0],
[1.0, 0.0, 0.0, 1.0],
[1.0, 0.0, 0.0, 1.0],
[1.0, 0.0, 0.0, 1.0]],
x: square[0].to_i,
y: square[1].to_i,
size: 25)
end
#end
# update location of square
location = "#{get :mouse_x}-#{get :mouse_y}"
end
show
| true |
60ca81ff7d90cb613f848a2ee5231016b70bdea0
|
Ruby
|
saraid/OpenCatan
|
/server/lib/catan/turn.rb
|
UTF-8
| 12,600 | 2.671875 | 3 |
[] |
no_license
|
require 'catan/action'
require 'catan/trade'
module OpenCatan
class TurnStateException < OpenCatanException; end
class Player
# A turn begins when the previous turn ends.
# A turn ends when the player submits DONE.
class Turn
def initialize(game)
@game = game
@actions = []
@trades = []
@status = 'ok'
super()
end
def to_s; inspect; end
def to_json; summary.to_json; end
def inspect; summary.inspect; end
state_machine :dice_state, :namespace => 'dice', :initial => :rolling do
event :roll do
transition :rolling => :rolled
end
end
state_machine :robber_state, :initial => :robber_unmoved do
after_transition :on => :rolled_a_seven do |x, y| log "Rolled a 7!" end
after_transition :to => :discarding_cards, :do => :check_hand_sizes
event :rolled_a_seven do
transition :robber_unmoved => :discarding_cards
end
event :play_knight do
transition :robber_unmoved => :place_robber
end
event :discarding_done do
transition :discarding_cards => :place_robber
end
event :place_robber do
transition :place_robber => :stealing_cards
end
event :choose_robber_victim do
transition :stealing_cards => :robber_unmoved
end
end
def play_knight
super
@game.update_army_sizes
end
state_machine :purchase_state, :initial => :nothing do
event :buy_card do
transition :nothing => same, :if => :dice_rolled?
end
event :buy_settlement, :buy_road, :buy_boat, :buy_city, :road_building do
transition :nothing => :placing_piece, :if => :dice_rolled?
end
event :place_piece do
transition :placing_piece => :nothing, :if => :road_building_done?
transition :placing_piece => same
end
end
state_machine :monopoly_state, :initial => :nothing do
event :play_monopoly do
transition :nothing => :monopolizing
end
event :choose_monopolized_resource do
transition :monopolizing => :nothing
end
end
state_machine :trade_state, :initial => :nothing do
event :propose do
transition all => :trading
end
event :respond do
transition :trading => same
end
event :accept, :cancel do
transition :trading => :nothing
end
end
# Roll Action
def roll_dice(player)
raise OpenCatanException, "Already rolled" unless super || @game.setting_up?
@roll = player.act(Player::Action::Roll.new)
return if @game.setting_up?
rolled_a_seven and return if @roll == 7
log "Hexes with #{@roll}: #{@game.board.find_hexes_by_number(@roll).join(',')}"
@game.board.find_hexes_by_number(@roll).each do |hex|
if hex.has_robber?
log "#{hex} is being robbed!"
next
end
# TODO: This stuff should go into the Piece subclasses.
hex.intersections.each do |intersection|
(case intersection.piece
when Piece::Settlement
1
when Piece::City
2
else
0
end).times do |x|
intersection.piece.owner.receive hex.product
roll_result(intersection.piece.owner, hex.product)
end
end
end
end
# Done Action
def done
raise TurnStateException, "Waiting for you to roll" unless dice_rolled?
update_status
raise TurnStateException, @status if @status != 'ok'
@current_trade.cancel! if @current_trade
@done = true
@game.status
@game.advance_player
return self
end
def done?; @done; end
# Buy Actions
def buy_settlement(player)
player.act(Player::Action::BuySettlement.new) if super
end
def buy_road(player)
player.act(Player::Action::BuyRoad.new) if super
end
def buy_boat(player)
player.act(Player::Action::BuyBoat.new) if super
end
def buy_city(player)
player.act(Player::Action::BuyCity.new) if super
end
def buy_card(player)
player.act(Player::Action::BuyCard.new) if super
end
# Place Actions
def place_settlement(player, intersection)
intersection = @game.board.find_intersection(intersection)
player.act(Player::Action::PlaceSettlement.on(intersection)) if @game.setting_up? || place_piece
intersection.hexes.each do |hex| player.receive hex.product end if @game.placing_settlements_in_reverse?
@game.update_road_lengths
end
def place_road(player, path)
@roads_to_build -= 1 if @roads_to_build
player.act(Player::Action::PlaceRoad.on(@game.board.find_path(path))) if @game.setting_up? || place_piece
@game.update_road_lengths
end
def place_boat(player, path)
player.act(Player::Action::PlaceBoat.on(@game.board.find_path(path))) if @game.setting_up? || place_piece
@game.update_road_lengths
end
def upgrade(player, intersection)
player.act(Player::Action::UpgradeSettlement.on(@game.board.find_intersection(intersection))) if place_piece
end
def place_robber(player, hex)
hex = hex.split(',').collect do |i| i.to_i end
hex = @game.board[hex.first][hex.last]
player.act(Player::Action::PlaceRobber.on(hex)) if super
@stealables = hex.intersections.collect do |i| i.piece.owner if i.piece end.compact
@stealables.reject! do |player| player.hand_size.zero? end
choose_robber_victim(player, @stealables.first) if @stealables.length == 1
choose_robber_victim(nil, nil) if @stealables.empty?
end
# Spend Action
def spend_gold(player, resource_hash) # This should really go into an Action subclass
resources = JSON.parse(resource_hash)
resources.each_pair do |resource, amount|
amount.times do |x| player.receive(resource.to_sym, true) end
end
end
# Discard Action
def discard(player, resource_hash) # This should really go into an Action subclass
resources = JSON.parse(resource_hash)
resources.each_pair do |resource, amount|
player.resources[resource.to_sym] -= amount
end
@needs_to_discard[player] -= resources.inject(0) { |sum, n| sum + n.last }
@needs_to_discard.delete player if @needs_to_discard[player].zero?
discarding_done if @needs_to_discard.empty?
end
# Play Action
def play_card(player, card)
card = player.get_card(card)
player.act(Player::Action::PlayCard.new(card))
end
# Choose Action
def choose(player, option)
choose_monopolized_resource(player, option) if Catan::RESOURCES.keys.include? option.to_sym
choose_robber_victim(player, option)
end
def choose_robber_victim(player, victim)
return super if player.nil?
victim = victim.respond_to?(:resources) ? victim : @game.players[victim.to_i]
player.act(Player::Action::ChooseVictim.new(victim)) if super
end
def choose_monopolized_resource(player, resource)
super
resource = resource.to_sym
@game.players.select { |victim| victim != player }.each do |victim|
amount = victim.lose(resource)
log "#{player.name} stole #{amount} #{resource} from #{victim.name}"
amount.times do |i| player.receive resource end
end
end
# Trade Actions
def propose(player, offer, demand, limited_to)
super
@trades << TradeNegotiation.new(@game, player, limited_to) unless @trades.last && @trades.last.status == :pending
@current_trade = @trades.last
@current_trade.propose(player, offer, demand)
end
def respond(player, message)
@current_trade.respond(player, message) if super
end
def accept(player, offer)
offer = @game.players[offer.to_i]
@current_trade.accept(offer) if @current_trade.initiator == player && super
end
def cancel(player)
@current_trade.cancel! if @current_trade.initiator == player && super
end
private
#
# Handle Road Building card
#
def road_building
@roads_to_build = 2 if super
end
def road_building_done?
@roads_to_build == 0 || @roads_to_build.nil?
end
#
# Turn Status
#
def check_hand_sizes
@needs_to_discard ||= {}
@game.players.each do |player|
@needs_to_discard[player] = player.hand_size / 2 if player.hand_size >= 7
end
discarding_done if @needs_to_discard.empty?
end
def roll_result(player, resource)
@roll_results ||= {}
@roll_results[player] ||= {}
@roll_results[player][resource] ||= 0
@roll_results[player][resource] = @roll_results[player][resource].succ
update_status
end
def update_status
@needs_to_discard ||= {}
@gold_holders = @game.players.select do |player| player.has_gold? end
@status = "Waiting for #{@gold_holders.collect { |player| player.name }.join(', ')} to spend gold." and return unless @gold_holders.empty?
if robber_state != 'robber_unmoved'
case robber_state
when 'discarding_cards'
@status = "Waiting for #{@needs_to_discard.keys.collect { |player| player.name }.join(', ')} to discard cards" and return
when 'stealing_cards'
@status = "Waiting for #{@game.current_player.name} to steal cards. Options: #{@stealables.collect { |player| player.name }}." and return
end
end
@status = 'Purchasing' and return if purchase_state != 'nothing'
@status = 'ok'
end
def summary
update_status
roll_results = []
@roll_results.each_pair do |player, resources|
roll_results << "#{player.name} collected #{resources.collect { |resource, amount| "#{amount} #{resource}" }.join(', ')}"
end if @roll_results
{ :status => @status,
:roll_results => roll_results
}
end
end
end
class SetupTurn
def initialize(game)
@game = game
@placeholder_turn = Player::Turn.new(game)
@setup_methods = {:roll_dice => [], :place_settlement => 0, :place_road => 0, :spend_gold => nil}
@last_action = {}
end
attr_reader :setup_methods, :last_action
def done_determining_turn_order?
@game.players.length == @setup_methods[:roll_dice].length
end
def roll_dice(*args)
player = args.first
raise OpenCatanException, "Already rolled for turn order" if @setup_methods[:roll_dice].include? player
@setup_methods[:roll_dice] << player
@placeholder_turn.roll_dice(*args)
end
def place_settlement(*args)
player = args.first
raise OpenCatanException, "Not your turn" unless player == @game.current_player
raise OpenCatanException, "Now place a road or boat" if @last_action[:action] == :place_settlement
@setup_methods[:place_settlement] += 1
@placeholder_turn.place_settlement(*args)
@last_action = { :player => player, :action => :place_settlement }
end
def place_road(*args)
player = args.first
raise OpenCatanException, "Not your turn" unless player == @game.current_player
raise OpenCatanException, "Place a settlement first" unless @last_action[:action] == :place_settlement
@setup_methods[:place_road] += 1
@placeholder_turn.place_road(*args)
@game.advance_player unless @game.phase_1_done? || @game.phase_2_done?
@last_action = { :player => player, :action => :place_road }
end
def place_boat(*args)
player = args.first
raise OpenCatanException, "Not your turn" if player == @game.current_player
raise OpenCatanException, "Place a settlement first" unless @last_action[:action] == :place_settlement
@setup_methods[:place_road] += 1
@placeholder_turn.place_boat(*args)
@game.advance_player unless @game.phase_1_done? || @game.phase_2_done?
@last_action = { :player => player, :action => :place_road }
end
def spend_gold(*args)
@placeholder_turn.spend_gold(*args)
end
end
end
| true |
9c95958c0c26560dbb9463815fbaa6fad8d8e204
|
Ruby
|
essian/assignment_sinatra_blackjack
|
/helpers/spec/human_player_spec.rb
|
UTF-8
| 633 | 2.640625 | 3 |
[] |
no_license
|
require 'human_player'
require 'view'
require 'player_view'
describe HumanPlayer do
let(:human) { HumanPlayer.new }
let(:poor_human) { HumanPlayer.new( { purse: 0 } )}
describe '#purse_amount' do
it 'starts out at 100' do
expect(human.purse_amount).to eq(100)
end
end
describe '#purse_empty?' do
it 'returns false if purse is not empty' do
expect(human.purse_empty?).to eq(false)
end
it 'returns true if purse is empty' do
expect(poor_human.purse_empty?).to eq(true)
end
end
describe '#double_bet' do
it 'doubles winnings' do
#expect(human.)
end
end
end
| true |
0af6782a4ab572fd14e4a399201c92647d9e7c52
|
Ruby
|
intfrr/Dotfiles-3
|
/scripts/web_search.rb
|
UTF-8
| 294 | 2.609375 | 3 |
[] |
no_license
|
#!/usr/bin/env ruby
require 'open-uri'
term = ARGV[0]
if term.empty?
STDERR.puts "No search term specified"
exit
end
escaped_term = URI.escape(term)
if term.empty?
STDERR.puts "Invalid search term"
exit
end
base_url = "https://duckduckgo.com/?q="
`open #{base_url}#{escaped_term}`
| true |
2d214ad4cd307baf8943001ba3730a296203a50e
|
Ruby
|
thomanil/ruby101
|
/exercises/04/script.rb
|
UTF-8
| 1,544 | 2.84375 | 3 |
[
"CC-BY-4.0",
"CC-BY-3.0"
] |
permissive
|
# define methods...
# Hint: For the basic part ot the task you can just pull from
# a large dummy text, like the one below:
lorem_ipsum = <<LOREM
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut
enim ad minim veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in
reprehenderit in voluptate velit esse cillum dolore eu fugiat
nulla pariatur. Excepteur sint occaecat cupidatat non proident,
sunt in culpa qui officia deserunt mollit anim id est laborum.
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut
enim ad minim veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in
reprehenderit in voluptate velit esse cillum dolore eu fugiat
nulla pariatur. Excepteur sint occaecat cupidatat non proident,
sunt in culpa qui officia deserunt mollit anim id est laborum.
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut
enim ad minim veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in
reprehenderit in voluptate velit esse cillum dolore eu fugiat
nulla pariatur. Excepteur sint occaecat cupidatat non proident,
sunt in culpa qui officia deserunt mollit anim id est laborum.
LOREM
| true |
559de9ba6467879a024a820b7e2f59805d896c6c
|
Ruby
|
skageraz/ruby
|
/exo_14.rb
|
UTF-8
| 86 | 3.203125 | 3 |
[] |
no_license
|
puts "choisis un nombre"
n = gets.chomp.to_i
(0..n).reverse_each do |n|
puts n
end
| true |
b2463e0366e910f9eb88fad5015104d94313810b
|
Ruby
|
oivoodoo/versionius
|
/lib/versionius/version.rb
|
UTF-8
| 747 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
require 'grit'
require 'versionomy'
require 'rake'
module Versionius
class Version
def initialize(project_path)
@repo = Grit::Repo.new(project_path)
@version = Versionomy.parse(tag.name)
end
def minor
change(@version.bump(2))
end
def major
change(@version.bump(1))
end
def release
change(@version.bump(0))
end
private
def tag
@repo.tags.last || NoTag.new
end
def tag_version(version)
system "git tag #{version}"
end
def git_push
system "git push --tags origin master"
end
def change(version)
tag_version(version.to_s)
git_push
end
class NoTag
def name
"0.0.0"
end
end
end
end
| true |
f27eb2aa71d10aa3403c0fe5f88b48f9a83d47c6
|
Ruby
|
renuo/ruby-basics
|
/overloading_setter_getter.rb
|
UTF-8
| 515 | 3.921875 | 4 |
[
"MIT"
] |
permissive
|
class Food
attr_reader :weight
def initialize(_what, weight, _cals)
@weight = weight
end
# overrides the attr_reader :weight
def weight
puts 'used custom getter'
2
end
def weight=(weight)
puts 'used custom setter'
@weight = weight
end
end
# Food.new(nil,nil,nil).calories doesn't work, because is private by default
# puts Food.new(nil,nil,3).calories
food = Food.new('Salad', 300, 3)
puts food.weight
food.weight = 3 # even if i only gave it a attr_reader
puts food.weight
| true |
f09b56bb8369d41ae4f73092ab7c0552feb1dd63
|
Ruby
|
makevoid/try_clearwater_rc
|
/assets/js/serializers/invoices.rb
|
UTF-8
| 556 | 2.796875 | 3 |
[] |
no_license
|
require 'models/invoice'
require 'json'
class InvoicesSerializer
attr_reader :invoices
def initialize invoices
@invoices = invoices
end
def to_json
invoices.map { |invoice|
{
id: invoice.id,
name: invoice.name
}
}.to_json
end
def self.from_json json
hashes = JSON.parse(json)
invoices = hashes.map do |hash|
invoice = Invoice.allocate
hash.each do |attr, value|
invoice.instance_variable_set "@#{attr}", value
end
invoice
end
new(invoices)
end
end
| true |
f23833cd75ce2658912e860870c686a1e1cdc615
|
Ruby
|
johnnyji/math_game
|
/game.rb
|
UTF-8
| 1,338 | 3.796875 | 4 |
[] |
no_license
|
class Game
attr_accessor :game_over
def initialize
@player1 = nil
@player2 = nil
@current_player = nil
@game_over = false
end
def play
setup
execute
end
##### PRIVATE METHODS #####
private
def setup
@player1 = Player.new(prompt_player('player 1'))
@player2 = Player.new(prompt_player('player 2'))
@current_player = @player1
end
def execute
until one_player_loses
random_question = RandomQuestion.new
print "#{@current_player.name}, #{random_question.ask}: "
@current_player.answer = gets.chomp.to_i
unless answer_matches?(random_question)
@current_player.lives -= 1
puts 'WRONG ANSWER!'.colorize(:red)
display_player_status
else
puts "CORRECT".colorize(:green)
end
switch_players
end
puts "GAME OVER".colorize(:green)
end
def prompt_player(player)
print "What is your name #{player}: "
gets.chomp!
end
def answer_matches?(random_question)
@current_player.answer == random_question.answer
end
def one_player_loses
@player1.is_dead? || @player2.is_dead?
end
def display_player_status
puts @player1.display_lives
puts @player2.display_lives
end
def switch_players
@current_player = (@current_player == @player1 ? @player2 : @player1)
end
end
| true |
eadcab38d0911b3fb71cc62310577eaa54adb9ca
|
Ruby
|
cadyherron/assignment_association_practice
|
/test_file.rb
|
UTF-8
| 1,732 | 2.828125 | 3 |
[] |
no_license
|
#testingfile
#Basic Output
puts 'Users'
print User.all
puts 'Posts'
Post.all
puts 'Categories'
Category.all
puts 'Tags'
Tag.all
puts 'Comments'
Comment.all
#Relations
puts 'User Relations'
user = User.find(1)
user.comments
user.posts
#Set a collection of comments to replace a user's current comments
user.comments = [Comment.find(3), Comment.find(4)]
#user.comments = [Comment.first, Comment.second]
#List the posts authored by a given user
user.posts
#List the IDs of all posts authored by a given user
user.posts.ids
#Set a collection of Posts to replace that user's currently authored posts
user.posts = [Post.find(2), Post.find(3)]
puts 'Comment Relations'
comment = Comment.find(2)
comment.post
comment.user
#Set comment user to a different user
comment.user = User.find(2)
#Return a given comment's author
comment.user
#Return a given comment's parent post
comment.post
puts 'Post Relations'
post = Post.find(2)
post.comments
post.category
post.users
post.tags
#Set post to a different category
post.category = Category.find(2)
#List a given post's comments
post.comments
#Set a collection of Users to replace a given Post's authors in a similar way
post.users = [User.find(2), User.find(3)]
#Now use ids
user.post_ids = [2,3,4]
#List the authors of a given post
post.users
#Add a new tag to a given post by only using its ID
post.tags << 2
#List the tags on a given post
post.tags
puts 'Category'
category = Category.find(2)
#Remove one post from a category's collection of posts
category.posts.first.destroy
category.posts.find(id).destroy
puts 'Tag Relations'
tag = Tag.find(2)
#List the posts under a given tag
tag.posts
#Add a new post to a given tag by only using its ID
tag.post_ids << 4
| true |
c46697cd5cc64444f7b0941ebdf4ef5edb90701c
|
Ruby
|
tristang/lexicon
|
/lib/lexicon.rb
|
UTF-8
| 16,541 | 2.640625 | 3 |
[] |
no_license
|
require 'rwordnet'
require 'ruby-progressbar'
require 'lemmatizer'
require 'linguistics'
require 'pry'
Linguistics.use(:en, monkeypatch: false)
class Lexicon
@@path = File.join(File.dirname(__FILE__), 'lexicon')
SPACE = ' '
attr_reader :word_pos_frequencies, :ngram_frequencies, :word_list
def initialize
@lemm = Lemmatizer.new
@conf = Hash.new
@conf[:word_list_source_path] = File.join(@@path, 'UKACD.txt')
@conf[:word_list_path] = File.join(@@path, 'words.marshal')
@conf[:uk_to_us_source_path] = File.join(@@path, 'uk-us-spelling')
@conf[:uk_to_us_path] = File.join(@@path, 'uk_to_us.marshal')
@conf[:word_pos_frequencies_source_path] = File.join(@@path, 'word_pos_frequencies.yml')
@conf[:word_pos_frequencies_path] = File.join(@@path, 'word_pos_frequencies.marshal')
@conf[:dictionary_path] = File.join(@@path, 'dictionary.marshal')
@conf[:reverse_dictionary_path] = File.join(@@path, 'reverse_dictionary.marshal')
@conf[:ngrams_path] = File.join(@@path, '1grams.hash.trimmed')
# Always present
puts "Loading ngrams from marshal"
@ngram_frequencies = load_file(@conf[:ngrams_path])
puts "Culling ngrams"
@ngram_frequencies.select! do |k, v|
# Only letters (upper/lower), hypens, apostrophes, and spaces
# Exclude _POS tagged entries for now
next false unless is_valid_word(k)
# Exclude uncommon words
case k.length
when 1
# 'I' and 'a' are the only single letter words
k =~ /Ia/
when 2
# From 'kg' and more common
v >= 6937175
when 3
# From 'Zoe' and more common
v >= 499130
else
# Nothing less than this
v >= 30_000
end
end
# Save trimmed for reuse
File.open(@conf[:ngrams_path] + '.trimmed', 'w') do |file|
Marshal.dump(@ngram_frequencies, file)
end
# Cached marshal objects
if File.exists?(@conf[:word_list_path]) &&
File.exists?(@conf[:uk_to_us_path]) &&
File.exists?(@conf[:dictionary_path]) &&
File.exists?(@conf[:reverse_dictionary_path]) &&
File.exists?(@conf[:word_pos_frequencies_path])
puts "Loading from marshal"
@word_list = load_file(@conf[:word_list_path])
@uk_to_us = load_file(@conf[:uk_to_us_path])
@dictionary = load_file(@conf[:dictionary_path])
@reverse_dictionary = load_file(@conf[:reverse_dictionary_path])
@word_pos_frequencies = load_file(@conf[:word_pos_frequencies_path])
@size = @word_list.length
else
puts "Rebuilding everything..."
install
end
end
def to_s
"<Lexicon word_count=\"#{@size}\">"
end
alias_method :inspect, :to_s
def load_file(path)
File.open(path, 'r') do |fh|
Marshal.load(fh)
end
end
def install
# Word list to populate dictionary
create_word_list
@size = @word_list.length
create_uk_to_us_lookup
# POS frequencies
create_word_pos_frequencies
@dictionary = generate_dictionary(@word_list)
link_all_lemmas
link_all_synonyms
File.open(@conf[:dictionary_path], 'w') do |file|
Marshal.dump(@dictionary, file)
end
# Reverse words for reverse lookups (ends-with search)
@reverse_dictionary = generate_dictionary(@word_list.map(&:reverse))
File.open(@conf[:reverse_dictionary_path], 'w') do |file|
Marshal.dump(@reverse_dictionary, file)
end
end
def is_valid_word(word)
# Only letters, hyphens, apostrophes, spaces and hyphens allowed.
# Must start with a letter.
# Exclude _POS tagged entries for now
word =~ /^[a-z][a-z\-\'\ ]{1,15}$/i
end
def is_present_in_1grams(string)
# All words must be present in 1grams
words = string.split(SPACE)
words.any? && words.all?{ |w| @ngram_frequencies[w].to_i > 0 }
end
def create_word_list
words = []
discarded = []
puts "Adding words from UKACD"
File.open(@conf[:word_list_source_path], 'r') do |fh|
fh.each_line do |line|
line.chomp!
if is_present_in_1grams(line)
words << line
else
discarded << discarded
end
end
end
puts "Discarded #{discarded.length} words."
puts "Kept #{words.length} words from UKACD."
p
puts "Adding words from WordNet"
# Prime the wordnet cache
WordNet::Lemma.find_all("")
discarded = []
# Wordnet's cache has one hash for each POS with words as keys and the
# WordNet space separated database line as values
WordNet::Lemma.class_variable_get("@@cache").each do |pos, rows|
rows.each do |string, data|
string = string.gsub('_', ' ')
if is_present_in_1grams(string)
words << string
else
discarded << discarded
end
end
end
puts "Discarded #{discarded.length} from wordnet"
puts "Increased to #{words.length}"
words.uniq!
puts "Recuded to #{words.length}"
File.open(@conf[:word_list_path], 'w') do |file|
Marshal.dump(words, file)
end
@word_list = words
end
def single_words
@dictionary.to(
'*',
# Stop early at space character
character_comparator: proc { |_, node| node.character != SPACE },
destination_comparator: proc { |_, node| node.is_word },
deep_search: true
)
end
def phrases
@dictionary.to(
'*',
character_comparator: proc { true },
destination_comparator: proc { |_, node| node.is_phrase },
deep_search: true
)
end
def find(string)
# Call on root of dictionary
@dictionary.to(string)
end
def find_masked(masked_word)
@dictionary.to(
masked_word,
character_comparator: proc do |target, node|
# Don't find phrases
node.character != SPACE &&
# Matches character at position or target char is wildcard
node.character == target[node.depth] || target[node.depth] == '?'
end
)
end
def find_starting_with(word_start, reverse: false)
(reverse ? @reverse_dictionary : @dictionary).to(
word_start,
deep_search: true,
character_comparator: proc do |target, node|
# Don't find phrases
node.character != SPACE &&
# Letter must match, or we're past the end of the target start
(node.character == target[node.depth] || node.depth > target.length - 1)
end,
destination_comparator: proc do |target, node|
(node.depth >= target.length - 1) &&
node.is_word && !node.is_phrase
end
)
end
def find_ending_with(word_end)
# Look it up forewards in the reversed dict
find_starting_with(word_end.reverse, reverse: true).map(&:reverse)
end
def contains?(word)
lookup(word)&.is_word
end
def lookup(string)
position = @dictionary
string.chars.each do |c|
return nil unless position[c]
position = position[c]
end
position
end
alias_method :[], :lookup
def lookup_insensitive(string)
@dictionary.to(
string.downcase,
character_comparator: proc do |target, node|
# Matches character at position (case insensitive)
node.character.downcase == target[node.depth]
end
).any?
end
# Building methods
def generate_dictionary(words)
print "Generating dictionary tree... "
# Make the dictionary
dictionary = DictNode.new
words.each do |word|
# Start at the root
node = dictionary
# Place each character
word.chars.each do |char|
node[char] ||= DictNode.new(char, node)
node = node[char]
end
# Mark the final char as a word ending
node.is_word = true
node.is_phrase = word.include?(SPACE)
node.count = @ngram_frequencies[word]
end
puts "done."
dictionary
end
def link_all_lemmas
bar = ProgressBar.create(title: 'Linking lemmas', total: @size, throttle_rate: 0.1)
link_lemmas(@dictionary) do
bar.increment
end
end
def link_lemmas(node, &block)
if node.is_word
# Link this node to the node of its lemma (which may be itself)
node.lemma = self[@lemm.lemma(node.to_s)] || node
# Link each lemma to all of its inflected forms
if node.lemma?
# Stringify once
word = node.to_s
# Look up POS frequencies for all known POS for word
poss = @word_pos_frequencies[word]&.keys || []
poss.each do |pos|
case pos
when :vb, :vbp
[:past, :present_participle, :third_person_present].each do |tense|
if tense == :third_person_present
conjugation = word.en.conjugate(:present, :third_person_singular)
else
conjugation = word.en.conjugate(tense)
end
if (inflection_node = lookup(conjugation))
node.inflections[tense] = inflection_node
end
end
when :nn, :nnp
if (plural = lookup(word.en.plural))
node.inflections[:plural] = plural
end
end
end
end
# Callback at each word processed
yield
end
node.each do |char, n|
link_lemmas(n, &block)
end
end
def link_all_synonyms
bar = ProgressBar.create(title: 'Linking synonyms', total: @size, throttle_rate: 0.1)
link_synonyms(@dictionary) do
bar.increment
end
end
def link_synonyms(node, &block)
if node.is_word
node.synonyms = find_synonyms(node)
yield
end
node.each do |char, n|
link_synonyms(n, &block)
end
end
def find_synonyms(node)
word = node.to_s
wordnet_pos_tags = WordNet::Lemma.find_all(word.tr(' ', '_')).map(&:pos)
synonyms = wordnet_pos_tags.flat_map do |tag|
wordnet_lookup_syns(word, tag.to_sym)
end
# Look up POS frequencies for all known POS for word
frequency_tags = @word_pos_frequencies[word]&.keys || []
# Remove all that wordnet already had
frequency_tags -= wordnet_pos_tags.map { |t| normalise_pos_tag(t) }
# Find/generate synonyms for each known POS for word inflected from its lemma
synonyms += frequency_tags.flat_map do |pos|
lemma = (node.lemma || node).to_s
inflected_syns(lemma, pos)
end
# Remove the word itself
synonyms.delete(word)
synonyms.uniq!
# Exclude all synonyms that are closely related to the word including:
# - Alternative spellings
# - Hyphenated and non-hyphenated variants
# - Related words, eg. 'stagecoach' and 'coach'
synonyms.reject do |syn|
syn = syn.downcase.tr('-', '')
word = word.downcase.tr('-', '')
# Simple containment
next true if word.include?(syn)
next true if syn.include?(word)
# Complex similarity. Dehyphenate and check each synonym word for stem
# similarity to the main word.
syn.tr('-', '').split(' ').any? do |syn_word|
# Since we're checking for inclusion, skip over short words. Otherwise
# we'll reject phrases like "in the end" for "finally" because "finally"
# contains the word "in".
next false if syn_word.length < 3
# Americanize the spelling and take the stem of the word
s = americanize(syn_word).en.stem
w = americanize(word).en.stem
# Check for inclusion. This covers prefixes which aren't removed by the
# Porter Stemmer, like "color" and "discolor".
w.include?(s) || s.include?(w)
end
end
end
def normalise_pos_tag(tag)
case tag.to_sym
# Noun
when :n then :nn
# Verb
when :v then :vbp
# Adjective
when :a then :jj
# Adverb
when :r then :rb
end
end
def inflected_syns(lemma, pos)
generated_syns = case pos
when :vb, :vbp, :jj, :nn, :nnp
# Not inflected
[]
when :fw, :in, :ls, :sym, :det, :in, :uh, :ppc, :pp, :ppd, :ppl, :ppr,
:cd, :wrb, :wdt, :cc, :md, :wp, :wps, :pdt
# Known not handled
[]
when :nnps, :nns
# Plural nouns
wordnet_lookup_syns(lemma, :noun).map do |lemma_syn|
lemma_syn.en.plural
end
when :vbd, :vbn
# Verb: past tense (vbn = past/passive participle)
wordnet_lookup_syns(lemma, :verb).map do |lemma_syn|
lemma_syn.en.conjugate(:past)
end
when :vbg
# Verb: present participle (gerund)
wordnet_lookup_syns(lemma, :verb).map do |lemma_syn|
lemma_syn.en.conjugate(:present_participle)
end
when :vbz
# Verb: present, third person singular
wordnet_lookup_syns(lemma, :verb).map do |lemma_syn|
lemma_syn.en.conjugate(:present, :third_person_singular)
end
else
# puts "Unhandled POS: #{pos}"
[]
end
# Exclude any non-words generated
generated_syns.select do |syn|
@ngram_frequencies[syn].to_i > 0
end
end
def americanize(word)
@uk_to_us[word] || word
end
# Search wordnet for the lemma with a given POS and return cleaned syn list
def wordnet_lookup_syns(lemma, pos)
# Convert back to wordnet format
lemma = lemma.tr(' ', '_')
if (wordnet_lemma = WordNet::Lemma.find(lemma, pos))
# Fetch all synonyms (combining all senses of the word)
wordnet_lemma.synsets.flat_map(&:words).map do |w|
# Clean up the output
# - Adjectives can have an adjective marker at their end which needs be
# stripped. Eg. beautiful(ip), beautiful(p), beautiful(a)
# - Replace underscores with spaces
w.gsub(/\([a-z]*\)$/, '').tr('_', ' ')
end
else
[]
end
end
private
def create_word_pos_frequencies
puts "Loading word POS frequencies"
@word_pos_frequencies = Hash.new
File.open(@conf[:word_pos_frequencies_source_path], 'r') do |file|
while line = file.gets
/\A"?([^{"]+)"?: \{ (.*) \}/ =~ line
next unless $1 and $2
key, data = $1, $2
items = data.split(/,\s+/)
pairs = Hash.new
items.each do |i|
/([^:]+):\s*(.+)/ =~ i
pairs[$1.to_sym] = $2.to_f
end
@word_pos_frequencies[key] = pairs
end
end
File.open(@conf[:word_pos_frequencies_path], 'w') do |file|
Marshal.dump(@word_pos_frequencies, file)
end
end
def create_uk_to_us_lookup
@uk_to_us = Hash.new
File.open(@conf[:uk_to_us_source_path], 'r') do |file|
file.each_line do |line|
uk, us = line.split(SPACE)
@uk_to_us[uk] = us
end
end
File.open(@conf[:uk_to_us_path], 'w') do |file|
Marshal.dump(@uk_to_us, file)
end
end
end
class DictNode < Hash
attr_accessor :is_word, :is_phrase, :synonyms, :lemma
attr_reader :character, :inflections
def initialize(character = nil, parent = nil)
@character = character
@parent = parent
@synonyms = []
@inflections = {}
end
def to(target, character_comparator: nil, destination_comparator: nil, deep_search: false)
ret = []
# Continue if current character matches or at root node
if !@character || character_match?(target, character_comparator)
# Destination matches get stored for return
if destination_match?(target, destination_comparator)
ret << full_path.join
# Stop unless searching past first destination
return ret unless deep_search
end
# Continue to next letters in tree
ret << map do |_, node|
node.to(
target,
character_comparator: character_comparator,
destination_comparator: destination_comparator,
deep_search: deep_search
)
end.compact
end
ret.flatten
end
def destination_match?(target, comparator)
return comparator.call(target, self) if comparator
full_path.length == target.length && is_word
end
def character_match?(target, comparator)
return comparator.call(target, self) if comparator
target[depth] == @character
end
def full_path
@parent ? @parent.full_path + [@character] : []
end
def depth
# Depth should match string index, so the root node has a depth of -1,
# first letter has depth 0, etc.
@depth ||= full_path.length - 1
end
def to_s
full_path.join
end
def inspect
"<DictNode word='#{self.is_word ? self.to_s : '-'}' lemma=#{lemma? ? 'true' : 'false'}>"
end
# A node is a lemma if its lemma is itself
def lemma?
lemma == self
end
end
#binding.pry
| true |
93de1b291828e157f37e3e5c0b9c796b73125f94
|
Ruby
|
itsolutionscorp/AutoStyle-Clustering
|
/all_data/exercism_data/ruby/anagram/fcb9827e2e754a0fa504c81f28b6db27.rb
|
UTF-8
| 388 | 3.703125 | 4 |
[] |
no_license
|
class Anagram
def initialize(subject)
@subject = subject
end
def match(words)
words.select { |word| anagram?(word) }
end
private
attr_reader :subject
def normalized_subject
@normalized_subject ||= normalize(subject)
end
def anagram?(word)
normalized_subject.eql?(normalize(word))
end
def normalize(word)
word.downcase.chars.sort
end
end
| true |
c590741a66a7f12e88d42fff6ccc5c0753e5d23f
|
Ruby
|
harmolipi/ruby-projects
|
/bubble_sort.rb
|
UTF-8
| 308 | 3.59375 | 4 |
[] |
no_license
|
def bubble_sort(array)
sorted = false
until sorted
sorted = true
for i in 0...(array.length - 1)
if array[i] > array[i+1]
array[i], array[i+1] = array[i+1], array[i]
sorted = false
end
end
end
array
end
p bubble_sort([1, 3, 12, 105, 4, -5, 2, -26, 6, 2, 4])
| true |
5270cf6b23739736e388f67b6653ed831ee528d9
|
Ruby
|
franco84-2/reverse-each-word-001-prework-web
|
/reverse_each_word.rb
|
UTF-8
| 153 | 3.34375 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def reverse_each_word(phrase)
splitwords = phrase.split(" ")
reversed_words = splitwords.map { |word| word.reverse}
reversed_words.join(" ")
end
| true |
3f17fdb720ad59d2db0b1beb6f6ed2371c2e05ff
|
Ruby
|
MITLibraries/archivesspace_export_service
|
/exporter_app/lib/process_manager.rb
|
UTF-8
| 2,283 | 2.5625 | 3 |
[] |
no_license
|
class ProcessManager
def initialize
@processes_by_job = {}
@log = ExporterApp.log_for("ProcessManager")
end
def start_job(job, completed_callback)
@log.debug("Starting #{job}")
process = Process.new(job, completed_callback)
@processes_by_job[job] = process
process.call
end
def shutdown
@log.info("Shutting down")
@processes_by_job.each do |job, process|
process.terminate!
end
end
class Process
def initialize(job, completed_callback)
@job = job
@callback = completed_callback
@should_terminate = java.util.concurrent.atomic.AtomicBoolean.new(false)
@thread = :worker_not_started
@log = ExporterApp.log_for
end
def call
@thread = Thread.new do
log = ExporterApp.log_for
begin
Thread.current['name'] = "Job #{@job.id} (#{@job.task.class}) - #{Thread.current.to_s}@#{Thread.current.object_id}"
log.info("Running")
status = JobStatus::COMPLETED
log.debug("Running before hooks")
@job.before_hooks.each do |hook|
hook.call(@job.task)
end
begin
log.debug("Running main task")
@job.task.call(self)
log.debug("Running after hooks")
@job.after_hooks.each do |hook|
hook.call(@job.task)
end
@job.task.completed!
rescue
log.error($!)
log.error([email protected]("\n"))
status = JobStatus::FAILED
ensure
begin
status = terminated? ? JobStatus::TERMINATED : status
# NOTE: This callback happens on a different thread to the task itself
@callback.call(@job, status)
rescue
log.error($!)
log.error([email protected]("\n"))
end
end
rescue
log.error($!)
log.error([email protected]("\n"))
end
end
end
def running?
[email protected]_stop?(Time.now) && !terminated?
end
def terminate!
@log.info("I've been terminated :(")
@should_terminate.set(true)
@thread.join unless @thread == :worker_not_started
end
def terminated?
@should_terminate.get
end
end
end
| true |
ce60c55896a925be74ba572738ddc9b9454ab125
|
Ruby
|
lkowalick/draftmaster
|
/app/models/round_factory.rb
|
UTF-8
| 544 | 2.953125 | 3 |
[] |
no_license
|
class RoundFactory
def self.build(draft)
new(draft).send(:build)
end
private
attr_reader :draft
def initialize(draft)
@draft = draft
end
def build
round = draft.rounds.build(number: next_round_number)
round.matches = pairs_of_players.map do |pair|
match = Match.create
match.player_one = pair.first
match.player_two = pair.second
match
end
round
end
def pairs_of_players
draft.players.shuffle.each_slice(2)
end
def next_round_number
draft.next_round
end
end
| true |
2b19c68ac5d4d3d5d2c390ff3220df2265d3cabb
|
Ruby
|
craysiii/twitchbot
|
/lib/twitchbot/message.rb
|
UTF-8
| 3,746 | 3.03125 | 3 |
[
"MIT"
] |
permissive
|
require_relative 'user'
module Twitchbot
# Class responsible for parsing messages created in [EventHandler]
#
# TODO: Clean this up because its ugly
# TODO: Parse message-id
class Message
# @return [Integer] Number of bits that have been included in a message
attr_reader :bits
# @return [User] User that the message was sent by
attr_reader :user
# @return [Channel] Channel that the message was sent to
attr_reader :channel
# @return [String] IRC command of the raw IRC message
attr_reader :command
# @return [String] Raw IRC message received
attr_reader :raw
# @return [String] Sender of the IRC message
attr_reader :sender
# @return [String] Target of the IRC message
attr_reader :target
# @return [String] Content of the IRC message
attr_reader :payload
# @return [EventHandler] EventHandler associated with the IRC message
attr_reader :handler
def initialize(handler, raw_message)
@handler = handler
@raw = raw_message
msg = @raw.dup
@tags = msg.slice! /^\S+/ if tagged?
msg.lstrip!
/^(?<sender>:\S+) (?<command>\S+)( (?<target>\S+))?( (?<payload>.+))?$/ =~ msg
@sender = sender
@command = command
@target = target
@payload = payload
@channel = @handler.bot.channel
unless received_host?
if message? || whisper?
@payload.slice! 0, 1
@display_name = @tags[/display-name=(\w+)/, 1]
@user_id = @tags[/user-id=(?<user_id>\d+)/, 1]
/:(?<user>\w+)/ =~ @sender
if @channel.users.key? user
@channel.users[user].update_attributes @display_name, @user_id
else
@channel.users[user] = User.new user, @display_name, @user_id
end
@user = @channel.users[user]
end
if message?
/bits=(?<bits>\d+)/ =~ @tags
@bits = bits.nil? ? 0 : bits.to_i
/badges=(?<badges>[a-zA-Z\/,0-9\-]+)/ =~ @tags
@user.update_badges badges || ''
end
# Grab broadcaster status even though twitch doesn't inject it in the tags
# in a whisper
if whisper?
if @user.name.downcase.eql? @handler.bot.channel.name.downcase
@user.update_badges 'broadcaster/1'
end
end
end
end
# Method to determine if the IRC message includes any tags from the +:twitch.tv/tags+ capability
def tagged?
@raw.start_with? '@'
end
# Method to determine if the IRC message is an actual message to the [Channel] by a [User]
def message?
@command.eql? 'PRIVMSG'.freeze
end
# Method to determine if the IRC message is a whisper to the bot
def whisper?
@command.eql? 'WHISPER'.freeze
end
# Method to determine if the IRC message is a received host message from Twitch
def received_host?
message? && target.downcase.eql?(@handler.bot.channel.name.downcase) &&
/:\w+ is now hosting you./.match?(@payload)
end
# Method to respond to the IRC message target with a private message
def respond(message)
send_channel message if message?
send_whisper @user, message if whisper?
end
# Method to send a message to the joined [Channel]
def send_channel(message)
@handler.send_channel message
end
# Method to send a whisper to the specified [User]
def send_whisper(user, message)
@handler.send_whisper user, message
end
# Method to send a raw IRC message to the server
def send_raw(message)
@handler.send_raw message
end
# Method to determine if the IRC message is a PING challenge
def ping?
@raw.start_with? 'PING'
end
end
end
| true |
59dce0036da17022738fdbb53131c98b6ff9e22d
|
Ruby
|
nejcik/AkademiaRebased
|
/task_4_PAGE_FORM/app.rb
|
UTF-8
| 1,051 | 2.578125 | 3 |
[] |
no_license
|
require 'bundler'
Bundler.require(:default)
require 'sinatra/reloader'
require_relative 'simple_user'
require_relative 'forgot_password'
class App < Sinatra::Base
user = SimpleUser.new
user.update_password
get '/' do
if user.current_user
redirect '/logged'
else
erb :index
end
end
post '/' do
user.current_user = false
erb :index
end
get '/logged' do
if user.current_user
erb :logged
else
redirect '/'
end
end
post '/logged' do
user.input_password = params[:password]
if user.check_password(user.input_password)
user.current_user = true
erb :logged
else
redirect '/'
end
end
get '/forgot_password' do
erb :forgot_password
end
post '/changed' do
new_password = params[:new_password]
check_password = params[:check_password]
check = change_password(new_password,check_password)
if check == true
user.update_password
erb :changed
else
redirect :forgot_password
end
end
end
| true |
e5e241b2d32099689d287fe2aa735f4fa9a24e57
|
Ruby
|
bgoonz/UsefulResourceRepo2.0
|
/_OVERFLOW/Resource-Store/Bootcamp-repos/Curriculum/02_SQL/W_7D4_SQL_Fundamentals/sql_zoo/spec/04_select_within_select_spec.rb
|
UTF-8
| 4,703 | 2.828125 | 3 |
[
"MIT"
] |
permissive
|
require 'rspec'
require '04_select_within_select'
describe "SELECT within SELECT" do
describe "larger_than_russia" do
it "selects countries with a population larger than Russia" do
expect(larger_than_russia).to contain_exactly(
["Bangladesh"],
["Brazil"],
["China"],
["India"],
["Indonesia"],
["Pakistan"],
["United States of America"]
)
end
end
describe "richer_than_england" do
it "selects countries with a higher per capita GDP than the UK" do
expect(richer_than_england).to contain_exactly(
["Denmark"],
["Iceland"],
["Ireland"],
["Luxembourg"],
["Norway"],
["Sweden"],
["Switzerland"]
)
end
end
describe "neighbors_of_certain_b_countries" do
it "selects the correct names and continents" do
expect(neighbors_of_certain_b_countries).to contain_exactly(
["Albania", "Europe"],
["Andorra", "Europe"],
["Antigua and Barbuda", "Americas"],
["Armenia", "Europe"],
["Austria", "Europe"],
["Azerbaijan", "Europe"],
["Bahamas", "Americas"],
["Barbados", "Americas"],
["Belarus", "Europe"],
["Belgium", "Europe"],
["Belize", "Americas"],
["Bosnia-Hercegovina", "Europe"],
["Bulgaria", "Europe"],
["Costa Rica", "Americas"],
["Croatia", "Europe"],
["Cuba", "Americas"],
["Cyprus", "Europe"],
["Czech Republic", "Europe"],
["Denmark", "Europe"],
["Dominica", "Americas"],
["Dominican Republic", "Americas"],
["El Salvador", "Americas"],
["Estonia", "Europe"],
["Finland", "Europe"],
["Former Yugoslav Republic of Macedonia", "Europe"],
["France", "Europe"],
["Georgia", "Europe"],
["Germany", "Europe"],
["Greece", "Europe"],
["Grenada", "Americas"],
["Guatemala", "Americas"],
["Haiti", "Americas"],
["Honduras", "Americas"],
["Hungary", "Europe"],
["Iceland", "Europe"],
["Ireland", "Europe"],
["Italy", "Europe"],
["Jamaica", "Americas"],
["Latvia", "Europe"],
["Liechtenstein", "Europe"],
["Lithuania", "Europe"],
["Luxembourg", "Europe"],
["Malta", "Europe"],
["Moldova", "Europe"],
["Monaco", "Europe"],
["Nicaragua", "Americas"],
["Norway", "Europe"],
["Panama", "Americas"],
["Poland", "Europe"],
["Portugal", "Europe"],
["Romania", "Europe"],
["Russia", "Europe"],
["San Marino", "Europe"],
["Serbia and Montenegro", "Europe"],
["Slovakia", "Europe"],
["Slovenia", "Europe"],
["Spain", "Europe"],
["St Kitts and Nevis", "Americas"],
["St Lucia", "Americas"],
["St Vincent and the Grenadines", "Americas"],
["Sweden", "Europe"],
["Switzerland", "Europe"],
["The Netherlands", "Europe"],
["Trinidad and Tobago", "Americas"],
["Turkey", "Europe"],
["Ukraine", "Europe"],
["United Kingdom", "Europe"],
["Vatican", "Europe"]
)
end
end
describe "population_constraint" do
it "selects countries with a population between Poland and Canada" do
expect(population_constraint).to contain_exactly(
["Algeria", "32900000"],
["Kenya", "32800000"],
["Sudan", "35000000"],
["Tanzania", "38400000"]
)
end
end
describe "sparse_continents" do
it "selects countries in sparsely populated continents" do
expect(sparse_continents).to contain_exactly(
["Antigua and Barbuda", "Americas", "77000"],
["Bahamas", "Americas", "321000"],
["Barbados", "Americas", "272000"],
["Belize", "Americas", "266000"],
["Costa Rica", "Americas", "4300000"],
["Cuba", "Americas", "11300000"],
["Dominica", "Americas", "71000"],
["Dominican Republic", "Americas", "9000000"],
["El Salvador", "Americas", "6700000"],
["Grenada", "Americas", "103000"],
["Guatemala", "Americas", "13000000"],
["Haiti", "Americas", "8500000"],
["Honduras", "Americas", "7200000"],
["Jamaica", "Americas", "2700000"],
["Nicaragua", "Americas", "5700000"],
["Panama", "Americas", "3200000"],
["St Kitts and Nevis", "Americas", "46000"],
["St Lucia", "Americas", "152000"],
["St Vincent and the Grenadines", "Americas", "121000"],
["Trinidad and Tobago", "Americas", "1300000"]
)
end
end
end
| true |
d7a5e28c220db6f689fda06a1a17f4c63b4ab237
|
Ruby
|
Kate-v2/rails_engine_api
|
/spec/api/v1/filters/filtered_merchants_spec.rb
|
UTF-8
| 6,293 | 2.515625 | 3 |
[] |
no_license
|
require "rails_helper"
require "api_helper"
RSpec.describe "Merchant Filtering API" do
include APIHelper
describe 'Find' do
describe 'it filters name or id' do
before(:each) do
@merchant1, @merchant2, @merchant3 = create_list(:merchant, 3)
end
it 'finds by first name' do
name = @merchant1.name
name_up = @merchant1.name.upcase
name_down = @merchant1.name.downcase
name_camel = @merchant1.name.capitalize
get api_v1_merchants_find_path(name: name)
@merchant = json_data
expect(response).to be_successful
expect(@merchant['attributes']['id']).to eq(@merchant1.id)
get api_v1_merchants_find_path(name: name_up)
@merchant = json_data
expect(@merchant['attributes']['id']).to eq(@merchant1.id)
get api_v1_merchants_find_path(name: name_down)
@merchant = json_data
expect(@merchant['attributes']['id']).to eq(@merchant1.id)
get api_v1_merchants_find_path(name: name_camel)
@merchant = json_data
expect(@merchant['attributes']['id']).to eq(@merchant1.id)
end
it 'finds by id' do
id = @merchant1.id
get api_v1_merchants_find_path(id: id)
@merchant = json_data
expect(response).to be_successful
expect(@merchant.class).to eq(Hash)
expect(@merchant['attributes']['id']).to eq(id)
end
end
describe 'it filters by created or updated at date' do
before(:each) do
@merchant1 = create(:merchant)
sleep(1)
@merchant2 = create(:merchant)
end
it 'created_at' do
skip("can't figure out ApplicationRecord Date methods")
expect(@merchant1.created_at).to_not eq(@merchant2.created_at)
date = @merchant1.created_at
get api_v1_merchants_find_path(created_at: date)
@merchant = json_data
expect(@merchant['attributes']['id']).to eq(@merchant1.id)
date = @merchant2.created_at
get api_v1_merchants_find_path(created_at: date)
@merchant = json_data
expect(@merchant['attributes']['id']).to eq(@merchant2.id)
end
it 'updated_at' do
skip("can't figure out ApplicationRecord Date methods")
expect(@merchant1.updated_at).to_not eq(@merchant2.updated_at)
date = @merchant1.updated_at
get api_v1_merchants_find_path(updated_at: date)
@merchant = json_data
expect(@merchant['attributes']['id']).to eq(@merchant1.id)
date = @merchant2.updated_at
get api_v1_merchants_find_path(updated_at: date)
@merchant = json_data
expect(@merchant['attributes']['id']).to eq(@merchant2.id)
end
end
end
describe 'Find All' do
describe 'it filters by first or last name or id' do
before(:each) do
@merchant1, @merchant2, @merchant3 = create_list(:merchant, 3)
end
it 'finds by first name' do
name = @merchant1.name
name_up = @merchant1.name.upcase
name_down = @merchant1.name.downcase
name_camel = @merchant1.name.capitalize
get api_v1_merchants_find_all_path(name: name)
@merchants = json_data
@merchant = @merchants.first
expect(response).to be_successful
expect(@merchants.class).to eq(Array)
expect(@merchant['attributes']['id']).to eq(@merchant1.id)
get api_v1_merchants_find_all_path(name: name_up)
@merchants = json_data
@merchant = @merchants.first
expect(@merchant['attributes']['id']).to eq(@merchant1.id)
get api_v1_merchants_find_all_path(name: name_down)
@merchants = json_data
@merchant = @merchants.first
expect(@merchant['attributes']['id']).to eq(@merchant1.id)
get api_v1_merchants_find_all_path(name: name_camel)
@merchants = json_data
@merchant = @merchants.first
expect(@merchant['attributes']['id']).to eq(@merchant1.id)
end
it 'finds by id' do
id = @merchant1.id
get api_v1_merchants_find_all_path(id: id)
@merchants = json_data
@merchant = @merchants.first
expect(response).to be_successful
expect(@merchants.class).to eq(Array)
expect(@merchant['attributes']['id']).to eq(id)
end
end
describe 'it filters by created or updated at' do
before(:each) do
@merchant1 = create(:merchant)
sleep(1)
@merchant2 = create(:merchant)
end
it 'created_at' do
skip("can't figure out ApplicationRecord Date methods")
expect(@merchant1.created_at).to_not eq(@merchant2.created_at)
date = @merchant1.created_at
get api_v1_merchants_find_all_path(created_at: date)
@merchants = json_data
@merchant = @merchants.first
expect(response).to be_successful
expect(@merchants.to_a).to eq(Array)
expect(@merchant['attributes']['id']).to eq(@merchant1.id)
date = @merchant2.created_at
get api_v1_merchants_find_path(created_at: date)
@merchant = json_data
expect(@merchant['attributes']['id']).to eq(@merchant2.id)
end
it 'updated_at' do
skip("can't figure out ApplicationRecord Date methods")
expect(@merchant1.updated_at).to_not eq(@merchant2.updated_at)
date = @merchant1.updated_at
get api_v1_merchants_find_all_path(updated_at: date)
@merchants = json_data
@merchant = @merchants.first
expect(response).to be_successful
expect(@merchants.to_a).to eq(Array)
expect(@merchant['attributes']['id']).to eq(@merchant1.id)
date = @merchant2.updated_at
get api_v1_merchants_find_path(updated_at: date)
@merchant = json_data
expect(@merchant['attributes']['id']).to eq(@merchant2.id)
end
end
end
describe 'Random' do
before(:each) do
@merchant1, @merchant2, @merchant3 = create_list(:merchant, 3)
end
it 'returns a single random merchant' do
get api_v1_merchants_random_path
@merchant = json_data
expect(@merchant.class).to eq(Hash)
expect(@merchant['attributes']).to include('id')
end
end
end
| true |
2a22bb372d92e6f0581dcf00262da9f35368a6de
|
Ruby
|
pinapples73/week01
|
/day_5/homework/pet_shop.rb
|
UTF-8
| 2,384 | 3.421875 | 3 |
[] |
no_license
|
def pet_shop_name(shop_name)
return shop_name[:name]
end
def total_cash(shop_name)
return shop_name[:admin][:total_cash]
end
def add_or_remove_cash(shop_name, amount_cash)
return shop_name[:admin][:total_cash] += amount_cash
end
def pets_sold(shop_name)
return shop_name[:admin][:pets_sold]
end
def increase_pets_sold(shop_name, amount_pets)
return shop_name[:admin][:pets_sold] += amount_pets
end
def stock_count(shop_name)
return shop_name[:pets].length()
end
def pets_by_breed(shop_name, breed)
pet_by_breed = []
for pet in shop_name[:pets]
if breed == pet[:breed]
pet_by_breed.push(pet)
end
end
return pet_by_breed
end
def find_pet_by_name(shop_name, pet_name)
for pet in shop_name[:pets]
if pet_name == pet[:name]
return pet
end
end
return nil
end
def remove_pet_by_name(shop_name, pet_name)
for pet in shop_name[:pets]
if pet_name == pet[:name]
shop_name[:pets].delete(pet)
end
end
end
def add_pet_to_stock(shop_name, new_pet)
shop_name[:pets].push(new_pet)
end
def customer_cash(customer)
return customer[:cash]
end
def remove_customer_cash(customer, amount_cash)
customer[:cash] -= amount_cash
end
def customer_pet_count(customer)
return customer[:pets].length
end
def add_pet_to_customer(customer, new_pet)
customer[:pets].push(new_pet)
end
#----------OPTIONAL--------------------
def customer_can_afford_pet(customer, new_pet)
customer_cash = customer[:cash]
pet_cost = new_pet[:price]
if customer_cash >= pet_cost
return true
else
return false
end
end
# def sell_pet_to_customer(shop_name, sold_pet, customer)
# if sold_pet != nil
# if customer_can_afford_pet(customer, sold_pet) == true
# customer[:pets].push(sold_pet)
# shop_name[:admin][:pets_sold] += 1
# customer[:cash] -= sold_pet[:price]
# shop_name[:admin][:total_cash] += sold_pet[:price]
# end
# end
# end
#---------refactor of above code--------------
def sell_pet_to_customer(shop_name, sold_pet, customer)
#p find_pet_by_name(shop_name, sold_pet) != nil
if sold_pet != nil
if customer_can_afford_pet(customer, sold_pet) == true
add_pet_to_customer(customer, sold_pet)
increase_pets_sold(shop_name, 1)
remove_customer_cash(customer, sold_pet[:price])
add_or_remove_cash(shop_name, sold_pet[:price])
end
end
end
| true |
b899a04e868baa71cc2971fb90245ee3a15d7dca
|
Ruby
|
albertbahia/wdi_june_2014
|
/w03/d01/elizabeth_abernethy/hw_w03_d01/lib/pokemon_seed_script.rb
|
UTF-8
| 3,299 | 2.875 | 3 |
[] |
no_license
|
require_relative './pokemon_seed.rb'
require 'pry'
<<<<<<< HEAD
<<<<<<< HEAD
require_relative './pokemon.rb'
pokemon = get_pokemon
pokemon.each do |pokemon|
Pokemon.create({
name: pokemon[:name],
image: pokemon[:img],
hp: pokemon[:stats][:hp].to_i,
attack: pokemon[:stats][:attack].to_i,
defense: pokemon[:stats][:defense].to_i,
speed: pokemon[:stats][:speed].to_i,
species: pokemon[:type].join(' | '),
moves: pokemon[:moves][:level].map { |move| move[:name].capitalize}.join(' | '),
image: pokemon[:img],
classification: pokemon[:misc][:classification],
height: pokemon[:misc][:height],
happiness: pokemon[:misc][:happiness].to_i
})
binding.pry
# ---------------------------- MY WORK
# def get_moves(moves_hash)
# result = ''
# moves_hash.each do |key,value|
# value.each do |move_hash|
# result += "#{move_hash[:name]}"
# end
# return result
# end
# end
#
# pokemon.each do |pokemon|
# moves = get_moves(poke_hash[:moves])
# end
#
# pokemon.each do |pokemon|
# Pokemon.create({
# name: pokemon[:name],
# hp: pokemon[:stats][:hp],
# attack: pokemon[:stats][:attack],
# defense: pokemon[:stats][:defense],
# speed: pokemon[:stats][:speed],
# moves: get_moves(pokemon[:moves]),
# image: pokemon[:img],
# classification: pokemon[:misc][:classification],
# species: pokemon[:type].join(' | '),
# height: pokemon[:misc][:height],
# happiness: pokemon[:misc][:happiness]
# })
# end
=======
require 'active_record'
require_relative 'pokemon.rb'
ActiveRecord::Base.establish_connection({
database: 'pokemon_db',
adapter: 'postgresql'
})
=======
require_relative './pokemon.rb'
>>>>>>> hw_w03_d01
pokemon = get_pokemon
pokemon.each do |pokemon|
Pokemon.create({
name: pokemon[:name],
image: pokemon[:img],
hp: pokemon[:stats][:hp].to_i,
attack: pokemon[:stats][:attack].to_i,
defense: pokemon[:stats][:defense].to_i,
speed: pokemon[:stats][:speed].to_i,
species: pokemon[:type].join(' | '),
moves: pokemon[:moves][:level].map { |move| move[:name].capitalize}.join(' | '),
image: pokemon[:img],
classification: pokemon[:misc][:classification],
height: pokemon[:misc][:height],
happiness: pokemon[:misc][:happiness].to_i
})
binding.pry
<<<<<<< HEAD
binding.pry
>>>>>>> d9b22077024d9670774ab444d162143d8798012c
=======
# ---------------------------- MY WORK
# def get_moves(moves_hash)
# result = ''
# moves_hash.each do |key,value|
# value.each do |move_hash|
# result += "#{move_hash[:name]}"
# end
# return result
# end
# end
#
# pokemon.each do |pokemon|
# moves = get_moves(poke_hash[:moves])
# end
#
# pokemon.each do |pokemon|
# Pokemon.create({
# name: pokemon[:name],
# hp: pokemon[:stats][:hp],
# attack: pokemon[:stats][:attack],
# defense: pokemon[:stats][:defense],
# speed: pokemon[:stats][:speed],
# moves: get_moves(pokemon[:moves]),
# image: pokemon[:img],
# classification: pokemon[:misc][:classification],
# species: pokemon[:type].join(' | '),
# height: pokemon[:misc][:height],
# happiness: pokemon[:misc][:happiness]
# })
# end
>>>>>>> hw_w03_d01
| true |
a6ab8fc8bb7892ce9b8f89483562bbe13a695175
|
Ruby
|
alcngrk/DesignPatternStuff1
|
/Velocity.rb
|
UTF-8
| 298 | 2.640625 | 3 |
[] |
no_license
|
class StellarObj
#..
#..
#..
end
class Velocity
def initialize(StellarObject)
calculate_distance
adjust_velocity(@distance)
end
def calculate_distance(StellarObject)
@distance = calculate_distance(StellarObject)
end
def adjust_velocity(distance)
#...
end
end
| true |
941ea83b2346f77ed30ac7bb3232a1aad4ec4890
|
Ruby
|
msloekito/launchschool_iterators
|
/exercise3.rb
|
UTF-8
| 125 | 3.234375 | 3 |
[] |
no_license
|
pooch = ['pomeranian', 'spitz', 'samoyed', 'labrador', 'doberman']
pooch.each_with_index {|a, b| puts " #{b+1}. #{a} doge"}
| true |
aacbe66475226f97c32591be86b525dafb80fb15
|
Ruby
|
chazlarson/plex-dvr-post-processing
|
/process.rb
|
UTF-8
| 3,551 | 2.71875 | 3 |
[] |
no_license
|
#!/usr/bin/env ruby
require 'logger'
require 'tmpdir'
require 'shellwords'
PLEX_MEDIA_SCAN_PATH = "/Applications/Plex\ Media\ Server.app/Contents/MacOS/Plex\ Media\ Scanner"
PLEX_COMSKIP_PATH = "/Users/john/development/PlexComskip/PlexComskip.py"
HANDBRAKE_BIN = "/usr/local/bin/HandBrakeCLI"
HANDBRAKE_PRESET = "Very Fast 720p30"
HANDBRAKE_OUTPUT_EXTENSION = "m4v"
TEST_MODE = false
PID_FILE = File.join(File.dirname(__FILE__), 'current.pid')
Process.setpriority(Process::PRIO_PROCESS, 0, 20)
input = ARGV[0]
input = File.expand_path(input)
input_basename = File.basename(input)
input_dirname = File.dirname(input)
LOG_ROOT = File.join(File.dirname(__FILE__), 'logs')
FileUtils.mkdir_p LOG_ROOT
LOG_PATH = File.join(LOG_ROOT, "#{input_basename}.log")
LOG = Logger.new(LOG_PATH)
LOG.warn "TEST MODE IS ON" if TEST_MODE
LOG.debug "ARGV:\n\t#{ARGV.join("\n\t")}"
LOG.debug "ENV:\n#{ENV.collect{|k,v| "\t#{k}: #{v}"}.join("\n")}"
def lock
LOG.info "Waiting for lock on #{PID_FILE}"
File.open(PID_FILE, File::RDWR|File::CREAT, 0644) do |file|
begin
file.flock File::LOCK_EX
LOG.info "Lock established on #{PID_FILE}"
file.rewind
file.write "#{Process.pid}\n"
file.flush
file.truncate file.pos
yield
ensure
file.truncate 0
LOG.info "Releasing lock on #{PID_FILE}"
end
end
end
def subout(command, tag = false)
LOG.info command
IO.popen("#{command} 2>&1").each do |line|
LOG.debug "#{tag ? "[#{tag}] " : nil}#{line.strip}"
end
end
LOG.info "Processing \"#{input}\""
tmp_dir = Dir.mktmpdir
LOG.info "Created Temporary Working Directory \"#{tmp_dir}\""
input_tmp_path = File.join(tmp_dir, input_basename)
LOG.info "Copying \"#{input}\" to #{input_tmp_path}"
copy_command = "cp #{Shellwords::shellescape input} #{Shellwords::shellescape input_tmp_path}"
subout copy_command, 'COPY'
transcoded_tmp_path = "#{input_tmp_path}.#{HANDBRAKE_PRESET}.#{HANDBRAKE_OUTPUT_EXTENSION}"
lock do
LOG.info "Stripping Commercials"
comskip_command = "#{PLEX_COMSKIP_PATH} #{Shellwords::shellescape input_tmp_path}"
subout comskip_command, 'COMSKIP'
LOG.info "Transcoding"
transcode_command = "#{HANDBRAKE_BIN} --preset \"#{HANDBRAKE_PRESET}\" -i #{Shellwords::shellescape input_tmp_path} -o #{Shellwords::shellescape transcoded_tmp_path}"
transcode_command += " --stop-at duration:60" if TEST_MODE
subout transcode_command, 'TRANSCODE'
end
LOG.info "Copying processed file to source directory"
output = File.join(input_dirname, File.basename(transcoded_tmp_path))
LOG.info "Copying \"#{transcoded_tmp_path}\" to \"#{output}\""
copy_command = "cp #{Shellwords::shellescape transcoded_tmp_path} #{Shellwords::shellescape output}"
subout copy_command, 'COPY'
LOG.info "Moving the processed file over the original"
move_command = "mv #{Shellwords::shellescape output} #{Shellwords::shellescape input}"
if TEST_MODE
LOG.info "Skipping the move command because of TEST_MODE. Would have been:\n#{move_command}"
else
subout move_command, 'MOVE'
end
LOG.info "Deleting Temporary Working Directory \"#{tmp_dir}\""
FileUtils.rm_rf tmp_dir
# Detect if the script was run as a Plex POSTPROCESSING script or manually. If run manually, notify the Plex Media Server of the change.
unless input.include?('.grab')
LOG.info "Telling Plex to rescan \"#{input_dirname}\""
plex_media_scan_command = "#{Shellwords::shellescape PLEX_MEDIA_SCAN_PATH} --directory #{Shellwords::shellescape input_dirname}"
subout plex_media_scan_command, 'PLEX MEDIA SCAN'
end
LOG.info "Done!"
| true |
8e09bd82a9f82b1f7da1d2963df5fd853ef4d0ce
|
Ruby
|
bcurren/unison
|
/lib/unison/predicates/greater_than.rb
|
UTF-8
| 369 | 2.828125 | 3 |
[] |
no_license
|
module Unison
module Predicates
class GreaterThan < BinaryPredicate
def fetch_arel
Arel::GreaterThan.new(operand_1.fetch_arel, operand_2.fetch_arel)
end
def inspect
"#{operand_1.inspect}.gt(#{operand_2.inspect})"
end
protected
def apply(value_1, value_2)
value_1 > value_2
end
end
end
end
| true |
04782e2b6aa23c9f0fea2c61865869716fb28d5e
|
Ruby
|
nullstyle/online
|
/lib/online/tracker.rb
|
UTF-8
| 3,638 | 3.328125 | 3 |
[
"MIT"
] |
permissive
|
module Online
#
# Keeps a fuzzy set of 'online' users in a provided redis store.
#
class Tracker
SLICE_COUNT = 6
#
# Creates a new tracker using the provided redis client.
#
# @param redis [Redis] the redis client to use
# @param online_expiration_time=180 [Fixnum] The amount of inactivity in seconds in which to consider an id 'offline'
#
def initialize(redis, online_expiration_time=180)
@online_expiration_time = 180
@redis = redis
# uses floating point division + ceiling to round up
@slice_size = (online_expiration_time.to_f / SLICE_COUNT).ceil
@active_bucket_count = (@online_expiration_time.to_f / @slice_size).ceil
end
#
# Marks the provided id as online
# @param id [String] the id to mark online
#
def set_online(id)
slice_time = active_bucket_times.first
key = bucket_key(slice_time)
expires_at = slice_time.to_i + (@slice_size * SLICE_COUNT)
@redis.multi do
@redis.sadd(key, id)
@redis.expireat key, expires_at
end
true
end
#
# Marks the provided id as offline. This method removes the id
# from all active buckets using a pipelined call.
#
# @param id [String] the id to mark offline
#
def set_offline(id)
@redis.pipelined do
active_bucket_keys.each{|k| @redis.srem key, id }
end
true
end
#
# Queries redis to see if the provided id has been seen in the last
# `online_expiration_time` seconds.
#
# @param id [String] the id to query upon
#
# @return [Boolean] true if online, false if not
def online?(id)
@redis.pipelined do
active_bucket_keys.each{|k| @redis.sismember k, id }
end.any?
end
#
# Queries redis to see if the provided id has _not_ been seen in the last
# `online_expiration_time` seconds.
#
# @param id [String] the id to query upon
#
# @return [Boolean] true if offline, false if not
def offline?(id)
!online?(id)
end
#
# Returns an array of all online ids
#
# @return [Array<String>] the online ids
def all_online
@redis.pipelined do
active_bucket_keys.each{|k| @redis.smembers key }
end.inject(&:|)
end
private
#
# Returns a list of keys that represent the sets of online users
# from the provided time
# @param starting_at=Time.now [Time] [description]
#
# @return [Array<Time>] the quantized times for active buckets
def active_bucket_times(starting_at=Time.now)
keys = []
starting_at = starting_at.utc
@active_bucket_count.times do
keys << quantize_time_to_slize_size(starting_at)
starting_at -= @slice_size
end
keys
end
#
# The list of keys for buckets that are active
#
# @return [type] [description]
def active_bucket_keys
active_bucket_times.map &method(:bucket_key)
end
#
# Rounds the provided time down to the appropriate bucketed time
#
# @param time [Time] the starting time
#
# @return [Time] The quantized time
def quantize_time_to_slize_size(time)
seconds_since_epoch = time.to_i
remainder = seconds_since_epoch % @slice_size
Time.at(seconds_since_epoch - remainder)
end
#
# Converts a time to a bucket key
# @param time [Time] the time
#
# @return [String] the key
def bucket_key(time)
id = quantize_time_to_slize_size(time.utc).to_i
"online:slice:#{id}"
end
end
end
| true |
c4e15ed78c07ddc9ae19760fd0b315704bd4586e
|
Ruby
|
appfolio/stewfinder
|
/lib/stewfinder/command.rb
|
UTF-8
| 1,079 | 2.875 | 3 |
[
"MIT"
] |
permissive
|
require 'docopt'
require_relative 'finder'
require_relative 'version'
module Stewfinder
# Provides the command line interface to Stewfinder
class Command
DOC = <<-DOC
stewfinder: A tool to help discover code stewards.
Usage:
stewfinder [options] [PATH]
stewfinder -h | --help
stewfinder --version
Options:
--sort Sort the output list.
When PATH isn't provided stewfinder will use the present working directory.
DOC
.freeze
def initialize
@exit_status = 0
end
def run
options = Docopt.docopt(DOC, argv: argv, version: VERSION)
finder = Finder.new(File.absolute_path(options['PATH'] || Dir.pwd))
finder.print_stewards(options['--sort'])
@exit_status
rescue Docopt::Exit => exc
exit_with_status(exc.message, exc.class.usage != '')
rescue StandardError => exc
exit_with_status(exc.message)
end
private
def argv
ARGV
end
def exit_with_status(message, condition = true)
puts message
@exit_status = condition ? 1 : @exit_status
end
end
end
| true |
1e3f15bee97d7a04cb0e0c07265bbcec47f4cac7
|
Ruby
|
motoyu5623/BookReview
|
/write_review.rb
|
UTF-8
| 440 | 3.453125 | 3 |
[] |
no_license
|
def write_review(posts)
post = {}
puts "本のタイトルを入力してください"
post[:title] = gets.chomp
puts "本の評価(1〜5)を入力してください"
post[:point] = gets.chomp.to_i
if post[:point] < 1 || post[:point] > 5
puts "評価は1〜5で入力してください"
return
end
puts "本の感想を一言入力してください"
post[:review] = gets.chomp
posts << post
end
| true |
af302f6ac268f3fa710808d7a1be8011a21ec13f
|
Ruby
|
rellbows/Ruby101Project
|
/09_timer/timer.rb
|
UTF-8
| 1,384 | 3.8125 | 4 |
[] |
no_license
|
class Timer
#shortcut for GETTER method
#attr_reader :seconds
def initialize
@seconds = 0
end
#SETTER: this is how you change instance variables from outside
def seconds=(new_seconds)
@seconds = new_seconds
end
#GETTER: this returns the value of the instance variable
def seconds
@seconds
end
###This is the quick smart way###
def time_string
hours = @seconds/3600 #if not an hour will be stored as 0
remainder = @seconds%3600 #modulo gives the amount that remains
sprintf("%02d:%02d:%02d", hours, remainder/60, remainder%60) #string formatting
end
#####This was the unneccessarily long complicated way.####
#my first attempt (forgot about modulos)
=begin
rescue Exception => e
end
def time_string
time_calc
@time_ary.map! do |e|
if e.length == 2
e
else
e = "0" + e
end
end
@time_string = @time_ary.join(":")
end
def time_calc
time = @seconds
leftover = 0
if (time-3600) >= 0
hours = time/3600
leftover = time - (hours*3600)
if (leftover - 60) >= 0
minutes = leftover/60
seconds = leftover - (minutes*60)
else
minutes = 0
seconds = leftover
end
elsif (time-60) >= 0
hours = 0
minutes = time/60
seconds = time - 60
else
hours = 0
minutes = 0
seconds = time
end
@time_ary = [hours, minutes, seconds]
@time_ary.map! do |e|
e.to_s
end
end
=end
end
| true |
6959179e358dfed599616cc947c61b564141369d
|
Ruby
|
iamaimeemo/todo-ruby-basics-001-prework-web
|
/lib/ruby_basics.rb
|
UTF-8
| 542 | 3.90625 | 4 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def division(num1, num2)
return "#{num1}".to_f / "#{num2}".to_f
end
division 42, 7
def assign_variable (value)
"#{value}"
end
assign_variable "Bob"
def argue (phrase = "I'm right and you are wrong!")
"#{phrase}"
end
argue
def greeting (hello, name)
puts "#{hello}, #{name}"
end
greeting "Hi there", "Bobby"
def return_a_value
"Nice"
end
return_a_value
def last_evaluated_value
"firstly"
"expert"
end
last_evaluated_value
def pizza_party (yum_factor = "cheese")
return "#{yum_factor}"
end
pizza_party
pizza_party "pepperon"
| true |
9665b334709c9e37b53911e037f7d707e63ccd6f
|
Ruby
|
LeanKhan/ruby_your_fada
|
/web_guesser/web_guesser.rb
|
UTF-8
| 492 | 2.828125 | 3 |
[] |
no_license
|
# web_guesser app thingy
require 'sinatra'
require 'sinatra/reloader'
get '/' do
srand 1234
number = rand(101)
srand 1234
guess = params["guess"] ? params["guess"].to_i : nil
if(guess)
if(guess > number)
message = "Too High!"
elsif(guess < number)
message = "Too Low!"
else
message = "Just Right!"
end
end
erb :index, :locals => {:number => number, :message => message, :guess => guess}
end
| true |
3f5847936353527e1741fc8109deef696e2e6454
|
Ruby
|
VincentLloyd/scrapp
|
/lib/scrapp/game.rb
|
UTF-8
| 1,812 | 3.5625 | 4 |
[
"MIT"
] |
permissive
|
class Game
VALID_CHARS = [*'A'..'Z', '!', '*'].freeze
LETTER_VALUES = {
'A' => 1, 'B' => 3, 'C' => 3, 'D' => 2,
'E' => 1, 'F' => 4, 'G' => 2, 'H' => 4,
'I' => 1, 'J' => 8, 'K' => 5, 'L' => 1,
'M' => 3, 'N' => 1, 'O' => 1, 'P' => 3,
'Q' => 10, 'R' => 1, 'S' => 1, 'T' => 1,
'U' => 1, 'V' => 4, 'W' => 4, 'X' => 8,
'Y' => 4, 'Z' => 10
}.freeze
attr_accessor :error_code
attr_accessor :score
attr_accessor :word
def initialize(word)
@word = word
@error_code = validate_input(@word)
@score = score_word(@word) if @error_code.zero?
end
def validate_input(word)
if !valid_chars?(word)
@error_code = 1
elsif !valid_char_count?(word)
@error_code = 2
elsif !valid_star_pos?(word)
@error_code = 3
elsif !valid_bang_pos?(word)
@error_code = 4
else
@error_code = 0
end
end
def error?
@error_code > 0
end
def valid_chars?(word)
word.chars.all? { |char| VALID_CHARS.include? char.upcase }
end
def valid_char_count?(word)
word.scan(/\W{3,}/).length.zero?
end
def valid_star_pos?(word)
word.scan(/\A\W+/).join.scan(/[*]/).length.zero? ? true : false
end
def valid_bang_pos?(word)
word.scan(/\b\W+/).join.scan(/[!]/).length.zero? ? true : false
end
def score_letters(word)
word.scan(/\w/).map(&:upcase).reduce(0) do |total, current|
total + LETTER_VALUES[current]
end
end
def score_bonus_letters(word)
bonus_letters = word.scan(/(\w\b)(\W+)/).map do |letter|
letter[0].upcase * letter[1].length
end
bonus_letters.join.length.zero? ? 0 : score_letters(bonus_letters)
end
def score_word(word)
word_bonus = word.scan(/\A\W+/).join.length + 1
(score_letters(word) + score_bonus_letters(word)) * word_bonus
end
end
| true |
4f620af4facee80e1d95c39ee1c51056d356e54a
|
Ruby
|
poyben/add1920-ruben
|
/ut5/a1/net-change.rb
|
UTF-8
| 407 | 3.15625 | 3 |
[] |
no_license
|
#!/usr/bin/env ruby
def menu
puts '1 - DHCP'
puts '2 - Static'
puts '3 - Domestic'
input = gets.chop
if imput == '1'
system('dhclient eth0')
elsif imput == '2'
system('ip addr del dev eth0')
system('ip addr add 172.19.26.31/16 dev eth0')
elsif imput == '3'
system('ip addr del dev eth0')
system('ip addr add 192.168.1.12/24 dev eth0')
else
puts "Escoja una opción válida."
end
end
menu
| true |
53205236dcbb90c6edcee3ec234287b60e51959d
|
Ruby
|
serodriguez68/trailblazer-rails-basics
|
/app/services/my_transaction.rb
|
UTF-8
| 709 | 2.671875 | 3 |
[] |
no_license
|
class MyTransaction
extend Uber::Callable
def self.call(options, *)
result = ActiveRecord::Base.transaction { yield } # yield runs the nested pipe.
# If correct, yield will return an array with a lot of stuff. On the first
# position it will contain if the result is a rignt.
# i.e
# result[0] == Pipetree::Railway::Right
# will determine if the inner pipe was a success or not.
# There is an issue in the trailblazer repo to potentially improve this
byebug
result[0] == Pipetree::Railway::Right
# return value decides about left or right track!
rescue MyTransaction::Rollback
byebug
return false
end
class Rollback < StandardError; end
end
| true |
4f81bf086ccb658545cb1cdda027a55998916225
|
Ruby
|
EpicDream/shopelia
|
/lib/virtualis/report.rb
|
UTF-8
| 3,225 | 2.625 | 3 |
[] |
no_license
|
module Virtualis
class Report
require 'csv'
def self.parse(report_file)
data = {
:creation => [],
:authorization => [],
:compensation => [],
:errors => []
}
csv = CSV.read(report_file, col_sep:';')
header = csv.shift
unless header[0] == 'ENREG'
data[:errors] << "Invalid header for file #{report_file}: #{header.inspect}"
return data
end
header = csv.shift
file_date = DateTime.strptime("#{header[2]} CEST",'%d%m%Y %Z')
unless header[0] == '01' and header[1] =~ /\AFICHIER QUOTIDIEN/
data[:errors] << "Invalid header for file #{report_file}: #{header.inspect}"
return data
end
footer = csv.pop
unless footer[0] == '09' and footer[1] = csv.size - 2
data[:errrors] << "Invalid footer for file #{report_file}: #{footer.inspect}"
return data
end
csv.each do |line|
item = {}
begin
if line[0] == '02'
if line.size != 11
raise ArgmentError, "Invalid number of items (#{line.size})"
end
item[:numero_carte] = line[1].gsub(/000\Z/, '')
item[:etat] = line[2] == '0' ? 'active' : 'inactive'
item[:montant_demande] = line[3].to_i
item[:horodate_creation] = DateTime.strptime("#{line[4]} CEST", '%d%m%Y%H%M%S %Z')
item[:nombre_autorisation] = line[5].to_i
item[:montant_autorise] = line[6].to_i
item[:identifiant_commerce] = line[7].to_i
item[:nom_commerce] = line[8].gsub(/\\/, "\n")
item[:horodate_derniere_autorisation] = DateTime.strptime("#{line[9]} CEST", '%d%m%Y%H%M%S %Z')
data[:creation] << item
elsif line[0] == '03'
if line.size != 11
raise ArgumentError, "Invalid number of items (#{line.size})"
end
item[:numero_carte] = line[1].gsub(/000\Z/, '')
item[:numero_autorisation] = line[2].to_i
item[:horodate_autorisation] = DateTime.strptime("#{line[3]} CEST", '%d%m%Y%H%M%S %Z')
item[:code_reponse] = line[4].to_i
item[:type_mouvement] = line[5].to_i
item[:monnaie] = line[6].to_i
item[:montant] = line[7].to_i
item[:code_mcc] = line[8].to_i
item[:identifiant_commerce] = line[9].to_i
data[:authorization] << item
elsif line[0] == '04'
if line.size != 7
raise ArugmentError, "Invalid number of items (#{line.size})"
end
item[:numero_carte] = line[1].gsub(/000\Z/, '')
item[:horodate_operation] = DateTime.strptime("#{line[2]} CEST", '%d%m%Y%H%M%S %Z')
item[:code_operation] = line[3].to_i
item[:montant] = line[4].to_i
item[:horodate_creation] = DateTime.strptime("#{line[2]} CEST", '%d%m%Y%H%M%S %Z')
data[:compensation] << item
else
raise ArgumentError, "Invalid operation #{line[0]}"
end
rescue => e
data[:errors] << "Error in #{report_file}, line #{line.inspect}: #{e.to_s}"
end
end
return data
end
end
end
| true |
7847bf45010c3a1aef9a8272ac0cd104e2d88543
|
Ruby
|
nessche/opencellid-client
|
/lib/opencellid/opencellid.rb
|
UTF-8
| 4,787 | 2.984375 | 3 |
[
"MIT"
] |
permissive
|
require 'rexml/document'
require 'net/http'
require_relative 'cell'
require_relative 'response'
require_relative 'measure'
require_relative 'bbox'
require_relative 'error'
# The module for the opencellid-client gem
module Opencellid
# The main entry for this library. Each method maps to the corresponding method of the
# OpenCellId API defined at {http:://www.opencellid.org/api}.
class Opencellid
private
#the default URI used in all requests
DEFAULT_URI = 'http://www.opencellid.org'
# the list of parameters allowed in the options for get_cells_in_area
GET_IN_AREA_ALLOWED_PARAMS = [:limit, :mcc, :mnc]
public
attr_reader :key
# @param key [String] the API key used for "write" operations. Defaults to nil
def initialize(key=nil)
@key = key
end
# Retrieves the cell information based on the parameters specified inside the `cell` object
# @param[Cell] cell the object containing the parameters to be used in searching the database
# the result received from the server
def get_cell(cell)
query_cell_info '/cell/get', cell
end
# Retrieves the cell information and the measures used to calculate its position based on the parameters
# specified in the cell object
# @param[Cell] cell the object containing the parameters used to search the cell database
# @return[Response] the result received from the server
def get_cell_measures(cell)
query_cell_info '/cell/getMeasures', cell
end
# Retrieves all the cells located inside the bounding box and whose parameters match the ones specified in the options
# @param bbox [BBox] the bounding box limiting the cell search
# @param options [Hash] a hash containing further filtering criteria. Valid criteria are `:limit` (limiting the amount
# of results), `:mnc` specifying the mnc value of the desired cells and `:mcc` specifying the mcc value of the desired cells
# @return [Response] the result received from the server
def get_cells_in_area(bbox, options = {})
raise ArgumentError, 'options must be a Hash' unless options.is_a? Hash
raise ArgumentError, 'bbox must be of type BBox' unless bbox.is_a? BBox
params = {bbox: bbox.to_s, fmt: 'xml'}
params.merge!(options.reject { |key| !GET_IN_AREA_ALLOWED_PARAMS.include? key})
exec_req_and_parse_response '/cell/getInArea', params
end
# Adds a measure (specified by the measure object) to a given cell (specified by the cell object). In case of
# success the response object will also contain the cell_id and the measure_id of the newly created measure.
# Although the library does not check this, a valid APIkey must have been specified while initializing the
# this object
# @param cell [Object] the cell to which this measure must be added to
# @param measure [Object] the measure to be added
# @return [Response] the result obtained from the server
def add_measure(cell, measure)
raise ArgumentError, "cell must be of type Cell" unless cell.is_a? Cell
raise ArgumentError, "measure must be of type Measure" unless measure.is_a? Measure
params = cell.to_query_hash
params[:lat] = measure.lat
params[:lon] = measure.lon
params[:signal] = measure.signal if measure.signal
params[:measured_at] = measure.taken_on if measure.taken_on
exec_req_and_parse_response "/measure/add", params
end
# List the measures added with a given API key.
# @return [Response] the result received from the server
def list_measures
exec_req_and_parse_response "/measure/list"
end
# Deletes a measure previously added with the same API key.
# @param measure_id [Integer] the id of the measure to be deleted (obtained in the response from `add_measure` or via `list_measures`)
# @return [Response] the result received from the server
def delete_measure(measure_id)
raise ArgumentError,"measure_id cannot be nil" unless measure_id
exec_req_and_parse_response "/measure/delete", {id: measure_id}
end
protected
def query_cell_info(path, cell)
raise ArgumentError, "cell must be a Cell" unless cell.is_a? Cell
params = cell.to_query_hash
exec_req_and_parse_response path, params
end
def exec_req_and_parse_response(path, params = {})
params[:key] = @key if @key
uri = URI(DEFAULT_URI + path)
uri.query = URI.encode_www_form params if params.count > 0
res = Net::HTTP.get_response uri
if res.is_a? Net::HTTPOK
Response.from_xml res.body
else
response = Response.new false
response.error = ::Opencellid::Error.new(0, "Http Request failed with code #{res.code}")
response
end
end
end
end
| true |
62d0ac0dec184b8c48eacc1abfe599a303151b93
|
Ruby
|
kristjan/adventofcode
|
/2018/2/check.rb
|
UTF-8
| 363 | 3.53125 | 4 |
[] |
no_license
|
ids = File.readlines(ARGV[0]).map(&:strip)
def hist(s)
Hash.new(0).tap do |h|
s.chars.each {|ch| h[ch] += 1}
end
end
def has_two?(s)
hist(s).values.include?(2)
end
def has_three?(s)
hist(s).values.include?(3)
end
twos = threes = 0
ids.each do |id|
twos += 1 if has_two?(id)
threes += 1 if has_three?(id)
end
puts twos, threes, twos * threes
| true |
61c7fe2f55cc06e1c9c51e5b682d9cfc5a862fd1
|
Ruby
|
markburns/maze
|
/app/models/point.rb
|
UTF-8
| 1,094 | 3.5 | 4 |
[] |
no_license
|
class Point < Struct.new(:x, :y)
include Visitor::Visitable
def adjacent_to?(other)
return false unless other.is_a?(Point)
if left_of?(other)
Path::Left
elsif right_of?(other)
Path::Right
elsif above?(other)
Path::Up
elsif below?(other)
Path::Down
end
end
def horizontally_adjacent_to?(other)
(other.y == y) && next_to?(other.x, x)
end
def left_of?(other)
horizontally_adjacent_to?(other) && one_less?(other.x, x)
end
def right_of?(other)
horizontally_adjacent_to?(other) && one_more?(other.x, x)
end
def below?(other)
vertically_adjacent_to?(other) && one_more?(other.y, y)
end
def above?(other)
vertically_adjacent_to?(other) && one_less?(other.y, y)
end
def vertically_adjacent_to?(other)
(other.x == x) && next_to?(other.y, y)
end
def ==(other)
other.kind_of?(Point) && other.x == x && other.y == y
end
private
def next_to?(a, b)
one_less?(a,b) || one_more?(a,b)
end
def one_less?(a, b)
a == b + 1
end
def one_more?(a, b)
a == b - 1
end
end
| true |
f3de302ff1bed97ca48a6dd4cdeb5b2d9b271195
|
Ruby
|
skube/dotfiles
|
/bin/twitter-followers
|
UTF-8
| 709 | 2.53125 | 3 |
[
"LicenseRef-scancode-warranty-disclaimer"
] |
no_license
|
#!/usr/bin/env ruby
# GET https://api.twitter.com/1/friends/ids.json?cursor=-1&screen_name=twitterapi
require "twitter"
Twitter.configure do |config|
config.consumer_key = ENV["CONSUMER_KEY"]
config.consumer_secret = ENV["CONSUMER_SECRET"]
config.oauth_token = ENV["OAUTH_TOKEN"]
config.oauth_token_secret = ENV["OAUTH_TOKEN_SECRET"]
end
client = Twitter::Client.new
allowed_chars = /[^A-Za-z0-9_ #\@\$\.\-\/:]/
user = 63796828 # "@verified" user
followers = []
u = Twitter.user(user)
slots = [:id, :description, :friends_count]
obj = {}
slots.each do |field|
obj[field] = u[field].to_s.gsub(allowed_chars, "")
puts obj[field]
end
followers << obj
puts followers.to_yaml
| true |
bb910a927ebc6bd08ae26af48c06fb2f19596e99
|
Ruby
|
nguyenquangminh0711/ruby_jard
|
/lib/ruby_jard/reflection.rb
|
UTF-8
| 3,439 | 3.375 | 3 |
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
module RubyJard
##
# User classes may override basic Kernel methods, such as #inspect
# or #to_s, or even #is_a?. It's not very wise to call those methods
# directly, as there maybe side effects. Therefore, this class is
# to extract unbound methods from Kernel module, and then call them
# in Object's context.
class Reflection
def self.instance
@instance ||= new
end
def initialize
@method_cache = {
method: ::Kernel.method(:method).unbind,
instance_method: ::Kernel.method(:instance_method).unbind,
class: ::Kernel.method(:class).unbind,
respond_to?: ::Kernel.method(:respond_to?).unbind,
instance_variables: ::Kernel.method(:instance_variables).unbind,
instance_variable_get: ::Kernel.method(:instance_variable_get).unbind,
instance_variable_set: ::Kernel.method(:instance_variable_set).unbind,
inspect: ::Kernel.method(:inspect).unbind,
to_s: ::Kernel.method(:to_s).unbind,
is_a?: ::Kernel.method(:is_a?).unbind,
const_get: ::Kernel.method(:const_get).unbind,
const_defined?: ::Kernel.method(:const_defined?).unbind
}
@instance_method_cache = {
class: ::Kernel.instance_method(:class),
respond_to?: ::Kernel.instance_method(:respond_to?),
inspect: ::Kernel.instance_method(:inspect),
to_s: ::Kernel.instance_method(:to_s)
}
end
def call_is_a?(object, comparing_class)
@method_cache[:is_a?].bind(object).call(comparing_class)
end
def call_method(object, method_name)
@method_cache[:method].bind(object).call(method_name)
end
def call_class(object)
if call_is_a?(object, Module)
@method_cache[:class].bind(object).call
else
@instance_method_cache[:class].bind(object).call
end
end
def call_respond_to?(object, method_name)
if call_is_a?(object, Module)
@method_cache[:respond_to?].bind(object).call(method_name)
else
@instance_method_cache[:respond_to?].bind(object).call(method_name)
end
end
def call_instance_variables(object)
@method_cache[:instance_variables].bind(object).call
end
def call_instance_variable_get(object, variable)
@method_cache[:instance_variable_get].bind(object).call(variable)
end
def call_instance_variable_set(object, variable, value)
@method_cache[:instance_variable_set].bind(object).call(variable, value)
end
def call_inspect(object)
if call_is_a?(object, Module)
@method_cache[:inspect].bind(object).call
else
@instance_method_cache[:inspect].bind(object).call
end
end
def call_to_s(object)
if call_is_a?(object, Module)
@method_cache[:to_s].bind(object).call
else
@instance_method_cache[:to_s].bind(object).call
end
end
def call_const_get(object, const_name)
@method_cache[:const_get].bind(object).call(const_name)
end
def call_const_defined?(object, const_name)
@method_cache[:const_defined?].bind(object).call(const_name)
end
end
end
# Quesiton: Why this?
# Answer: The whole purpose of existence of this class is to dispatch Ruby's
# kernel methods on a object's context to prevent override or monkey-patching.
# The early all methods are stored, the safer Jard behaves.
RubyJard::Reflection.instance
| true |
ad4bcd6ac6de82e0d97458ec8ec4ff90a611f73a
|
Ruby
|
Jayyyy1011/programming-exercise
|
/28-word-count.rb
|
UTF-8
| 244 | 3.390625 | 3 |
[] |
no_license
|
# 请打开 wordcount.txt,计算每个单字出现的次数
file = File.open("wordcount.txt")
doc = File.read("wordcount.txt")
arr = doc.split(" ")
h = {}
arr.each do |v|
if h[v] == nil
h[v] = 1
else
h[v] += 1
end
end
puts h
| true |
ac270a2e856d033a6e0acbe7658a48598b98ac6e
|
Ruby
|
corewebdesign/dragonfly
|
/spec/dragonfly/serializer_spec.rb
|
UTF-8
| 2,264 | 2.59375 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
# encoding: utf-8
require 'spec_helper'
describe Dragonfly::Serializer do
include Dragonfly::Serializer
describe "base 64 encoding/decoding" do
[
'a',
'sdhflasd',
'/2010/03/01/hello.png',
'//..',
'whats/up.egg.frog',
'£ñçùí;',
'~'
].each do |string|
it "should encode #{string.inspect} properly with no padding/line break" do
b64_encode(string).should_not =~ /\n|=/
end
it "should correctly encode and decode #{string.inspect} to the same string" do
str = b64_decode(b64_encode(string))
str.force_encoding('UTF-8') if str.respond_to?(:force_encoding)
str.should == string
end
end
describe "b64_decode" do
it "converts (deprecated) '~' characters to '/' characters" do
b64_decode('asdf~asdf').should == b64_decode('asdf/asdf')
end
end
end
["psych", "syck"].each do |yamler|
describe "with #{yamler} yamler" do
before(:all) do
@default_yamler = YAML::ENGINE.yamler
YAML::ENGINE.yamler = yamler
end
after(:all) do
YAML::ENGINE.yamler = @default_yamler
end
[
[3,4,5],
{'wo' => 'there'},
[{'this' => :should, 'work' => [3, 5.3, nil, {'egg' => false}]}, [], true]
].each do |object|
it "should correctly yaml encode #{object.inspect} properly with no padding/line break" do
encoded = yaml_encode(object)
encoded.should be_a(String)
encoded.should_not =~ /\n|=/
end
it "should correctly yaml encode and decode #{object.inspect} to the same object" do
yaml_decode(yaml_encode(object)).should == object
end
end
describe "yaml_decode" do
it "should raise an error if the string passed in is empty" do
expect{ yaml_decode('') }.to raise_error(Dragonfly::Serializer::BadString)
expect{ yaml_decode(nil) }.to raise_error(Dragonfly::Serializer::BadString)
end
it "should raise an error if the string passed in is invalid YAML" do
input = b64_encode("\tfoo:\nbar")
expect{ yaml_decode(input) }.to raise_error(Dragonfly::Serializer::BadString)
end
end
end
end
end
| true |
7d60729fb3056d7e4e156dbfded9041d907c24fc
|
Ruby
|
amcrawford/scrabble-score-keeper
|
/test/scrabble_test.rb
|
UTF-8
| 814 | 2.921875 | 3 |
[] |
no_license
|
gem 'minitest'
require './lib/scrabble'
require 'minitest/autorun'
require 'minitest/pride'
require 'pry'
class ScrabbleTest < Minitest::Test
def test_it_can_score_a_single_letter
assert_equal 1, Scrabble.new.score("a")
assert_equal 4, Scrabble.new.score("f")
end
def test_it_can_score_a_word
assert_equal 9, Scrabble.new.score("amber")
end
def test_it_returns_0_for_empty_string
assert_equal 1, Scrabble.new.score("a")
assert_equal 0, Scrabble.new.score("")
end
def test_it_returns_0_for_nil
assert_equal 0, Scrabble.new.score(nil)
end
def test_it_returns_0_for_unknown_letters
assert_equal 1, Scrabble.new.score("a")
assert_equal 0, Scrabble.new.score("+")
end
def test_it_does_not_count_spaces
assert_equal 7, Scrabble.new.score("a bc")
end
end
| true |
6af349692a1d7924337fbf7282b7d863088060ce
|
Ruby
|
Marcos2015/Linux_Pra_Fast
|
/Ruby/Ruby/simple_grep.rb
|
UTF-8
| 232 | 2.875 | 3 |
[] |
no_license
|
pattern=Regexp.new(ARGV[0])
file=File.open(ARGV[1])
file. each_line do |line| # 读取文件对象的每一行
if pattern =~ line #然后每一行判断是否匹配pattern,即模式匹配
print line
end
end
file.close
| true |
a6f95bab68e439d1b1b5d172256ea7122a35a1b4
|
Ruby
|
mkrahu/launchschool
|
/100_program_backend_prep/ruby_book/methods/return.rb
|
UTF-8
| 174 | 3.734375 | 4 |
[] |
no_license
|
# return.rb
# Exercise in Ch3 'Method' in the LaunchSchool Learning to Program Ruby
def add_three(number)
number + 3
end
returned_value = add_three(4)
puts returned_value
| true |
00482664f8e5d1327e4e19f45175c7ac4f030b72
|
Ruby
|
ecksma/wdi-darth-vader
|
/04_ruby/d02/Myron_Johnson/ruby/hw_movie.rb
|
UTF-8
| 387 | 3.515625 | 4 |
[] |
no_license
|
class Movie
def initialize(title, year, include_year=false)
@title = title
@year = year
@include_year = include_year
end
def title
@title
end
def year
@year
end
def include_year
@include_year
end
def full_title
if include_year
return @title + ' ' + @year
end
return @title
end
end
| true |
4b99443433d1b50739a3e3f781036cfac726b4d8
|
Ruby
|
Kangb0tmang/wdi13_warmups
|
/concat_unique_strings/string.rb
|
UTF-8
| 151 | 3.140625 | 3 |
[] |
no_license
|
str1 = 'xyaabbbccccdefww'
str2 = 'xxxxyyyyabklmopq'
def longest(str1, str2)
str1.concat(str2).split('').uniq.sort.join
end
puts longest(str1, str2)
| true |
094e2e4f904d9feee5212b3d5b3fec4f7824257c
|
Ruby
|
joe42go/lesson_4
|
/ls_ttt.rb
|
UTF-8
| 6,225 | 3.96875 | 4 |
[] |
no_license
|
# 1. Display the initial empty 3x3 board.
# 2. Ask the user to mark a square.
# 3. Computer marks a square.
# 4. Display the updated board state.
# 5. If winner, display winner.
# 6. If board is full, display tie.
# 7. If neither winner nor board is full, go to #2
# 8. Play again?
# 9. If yes, go to #1
# 10. Good bye!
require 'pry' # press 'exit-program' in command line to exit out of pry
INITIAL_MARKER = ' '.freeze
PLAYER_MARKER = 'X'.freeze
COMPUTER_MARKER = 'O'.freeze
WINNING_LINES = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] +
[[1, 4, 7], [2, 5, 8], [3, 6, 9]] +
[[1, 5, 9], [3, 5, 7]]
CHOOSE_TURN = "choose".freeze # "choose" for turning on
def prompt(message)
puts "=> #{message}"
end
def clear_screen
system('clear') || system('cls')
end
def display_board(brd)
clear_screen
puts "You're a #{PLAYER_MARKER}. Computer is a #{COMPUTER_MARKER}"
puts ""
puts " | |"
puts " #{brd[1]} | #{brd[2]} | #{brd[3]} "
puts " | |"
puts "-----+-----+-----"
puts " | |"
puts " #{brd[4]} | #{brd[5]} | #{brd[6]} "
puts " | |"
puts "-----+-----+-----"
puts " | |"
puts " #{brd[7]} | #{brd[8]} | #{brd[9]} "
puts " | |"
puts ""
end
def initialize_board
new_board = {}
(1..9).each { |num| new_board[num] = INITIAL_MARKER }
new_board
end
def empty_squares(brd)
brd.keys.select { |num| brd[num] == INITIAL_MARKER }
end
def joinor(brd, separator= ', ', word = 'or')
brd[-1] = "#{word} #{brd.last}" if brd.size > 1
brd.join(separator)
end
def place_piece!(brd, current_player)
if current_player == "Player"
player_places_piece!(brd)
else
computer_places_piece!(brd)
end
end
def alternate_player(current_player)
if current_player == "Player"
"Computer"
else
"Player"
end
end
def player_places_piece!(brd)
square = ''
loop do
empty = empty_squares(brd)
prompt("Choose a square #{joinor(empty)}")
square = gets.chomp.to_i
break if empty_squares(brd).include?(square)
prompt("You need to enter a number that falls within #{empty.join(', ')}")
end
brd[square] = PLAYER_MARKER
end
def find_at_risk_square(line, board, marker)
if board.values_at(*line).count(marker) == 2
board.select { |k, v| line.include?(k) && v == INITIAL_MARKER }.keys.first
end
end
def computer_places_piece!(brd)
# square = empty_squares(brd).sample
# brd[square] = COMPUTER_MARKER
square = nil
WINNING_LINES.each do |line|
square = find_at_risk_square(line, brd, COMPUTER_MARKER)
square = find_at_risk_square(line, brd, PLAYER_MARKER) if !square
break if square
end
if !square && brd[5] == INITIAL_MARKER
square = 5
end
if !square
square = empty_squares(brd).sample
end
brd[square] = COMPUTER_MARKER
end
def board_full?(brd)
empty_squares(brd).empty?
end
def someone_won?(brd)
!!detect_winner(brd)
end
def user_score(brd, score)
if detect_winner(brd) == 'Player'
score + 1
else
score
end
end
def computer_score(brd, score)
if detect_winner(brd) == 'Computer'
score + 1
else
score
end
end
def detect_winner(brd)
WINNING_LINES.each do |line|
if brd.values_at(*line).count(PLAYER_MARKER) == 3
return 'Player'
elsif brd.values_at(*line).count(COMPUTER_MARKER) == 3
return 'Computer'
end
end
nil
end
loop do
prompt("Welcome to the Game of Tic-Tac-Toe")
prompt("First player to win 5 times wins the game")
sleep 2
player_wins = 0
computer_wins = 0
first_turn = nil
if CHOOSE_TURN == 'choose'
loop do
prompt("Who would like to go first? Press 'c' for Computer or 'p' for Player")
first_turn = gets.chomp.downcase
break if first_turn == 'c' || first_turn == 'p'
prompt("You need choose either 'c' or 'p'")
end
end
loop do
board = initialize_board
current_player = if first_turn == 'p'
"Player"
elsif first_turn == 'c'
"Computer"
else
"Player"
end
loop do
display_board(board)
break if someone_won?(board) || board_full?(board)
place_piece!(board, current_player)
current_player = alternate_player(current_player)
player_wins = user_score(board, player_wins)
computer_wins = computer_score(board, computer_wins)
# if first_turn == 'p'
# player_places_piece!(board)
# display_board(board)
# player_wins = user_score(board, player_wins)
# break if someone_won?(board) || board_full?(board)
# computer_places_piece!(board)
# display_board(board)
# computer_wins = computer_score(board, computer_wins)
# break if someone_won?(board) || board_full?(board)
# elsif first_turn == 'c'
# computer_places_piece!(board)
# display_board(board)
# computer_wins = computer_score(board, computer_wins)
# break if someone_won?(board) || board_full?(board)
# player_places_piece!(board)
# display_board(board)
# player_wins = user_score(board, player_wins)
# break if someone_won?(board) || board_full?(board)
# else
# player_places_piece!(board)
# display_board(board)
# player_wins = user_score(board, player_wins)
# break if someone_won?(board) || board_full?(board)
# computer_places_piece!(board)
# display_board(board)
# computer_wins = computer_score(board, computer_wins)
# break if someone_won?(board) || board_full?(board)
# end
end
if player_wins == 5 || computer_wins == 5
prompt("#{detect_winner(board)} won the entire game!")
sleep 2
break
elsif someone_won?(board)
prompt("#{detect_winner(board)} won this round!")
prompt("Current Score is Player #{player_wins} vs. Computer #{computer_wins}")
sleep 2
else
prompt "It's a tie!"
sleep 2
end
end
prompt("Would you like to play again? Enter 'Y' or 'N'")
response = gets.chomp
break unless response.downcase.start_with?('y')
end
prompt("Thank you for playing. See you next time")
| true |
d63d2dd13a504cc61fb47492c9896397e05dd23b
|
Ruby
|
tp00012x/Ruby-Course
|
/Introduction/statement_modifiers.rb
|
UTF-8
| 204 | 3.703125 | 4 |
[] |
no_license
|
number = 5000
if number > 2500
puts 'Huge number'
end
puts 'Huge number!' if number > 2500
#
if 1 < 2
puts 'Yes, it is!'
else
puts 'No, its not!'
end
puts 1 < 2 ? 'Yes, it is!' : 'No, its not!'
| true |
80bce8d362afc723001306458c4dd648eb025c07
|
Ruby
|
izumin5210/syncfiles-prototype
|
/datastore.rb
|
UTF-8
| 531 | 2.71875 | 3 |
[] |
no_license
|
class Datastore
PATH = 'data.json'
def initialize
@data = JSON.parse(open(PATH).read).with_indifferent_access
rescue Errno::ENOENT
@data = {
tokens: {},
pulls: {},
}.with_indifferent_access
save
end
def token_for(slug:)
@data.dig(:tokens, slug, :token)
end
def set_token(token, slug:)
@data[:tokens][slug] ||= {}
@data[:tokens][slug][:token] = token
save
end
private
def save
open(PATH, 'w') do |f|
f.puts JSON.pretty_generate(@data)
end
end
end
| true |
3adcafa64f3247de5b73f0f94a40c332f5502eb6
|
Ruby
|
jasonmiles/introduction_to_programming
|
/easyquiz1_question9.rb
|
UTF-8
| 268 | 3.234375 | 3 |
[] |
no_license
|
flintstones = {"Fred"=>0, "Wilma"=>1, "Barney"=>2, "Betty"=>3, "BamBam"=>4, "Pebbles"=>5}
barney = flintstones.to_a[2]
arr = ["Fred", "Barney", "Wilma", "Betty", "Pebbles", "BamBam"]
hash = Hash.new
arr.each do |word|
hash.store(word, arr.index(word))
end
p hash
| true |
a1e40db3175ec32566c0db1db17cdacd6f454bbc
|
Ruby
|
fabiopio/pact
|
/webmachine/database.rb
|
UTF-8
| 480 | 2.953125 | 3 |
[] |
no_license
|
require "sequel"
class ZooDB
def initialize
db = Sequel.sqlite
db.create_table :animals do
primary_key :id
String :name
String :specie
end
@animals = db[:animals]
end
def insert_an_animal(name, specie)
@animals.insert(:name => name, :specie => specie)
end
def get_first_animal
@animals.first
end
def clear
@animals.delete
end
def next_id
last = @animals.order(:id).last
last.nil? ? 0 : last.id + 1
end
end
ZOO_DB = ZooDB.new
| true |
fe26ece4909f4642b528c252193cb73f7fc08d54
|
Ruby
|
bluurosebud/minedmindskata
|
/math_functions/pizza.rb
|
UTF-8
| 84 | 2.546875 | 3 |
[] |
no_license
|
def crust()
result=["stuffed","thin","pan","deep dish"].sample
p result
end
crust
| true |
84199cf654cbae8a0dac2c439ce10dc4513db4e7
|
Ruby
|
paalvibe/zizou
|
/lib/ranking.rb
|
UTF-8
| 6,797 | 2.875 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
require 'slack'
require 'terminal-table'
require 'pp'
class Ranking
def self.usernames_in_game(game)
names = {team1: [], team2: []}
{team1: game.team_player1.player, team2: game.team_player2.player}.each do |team, player|
if player.is_a? PairPlayer
usernames = player.username.split
names[team] << usernames[0]
names[team] << usernames[1]
else
names[team] << player.username
end
end
names
end
def self.combined_players_sorted(games)
results = {}
players = {}
default_rating = 1500
games.each do |game|
# create list of results
names = usernames_in_game(game)
# game_names1 = # todo get team 1 names
# game_names2 = # todo get team 2 names
# players = self.add_player_entries(players, game) # can this be done more efficiently?
results[game.id.to_s] = {
created_at_str: game.created_at.to_s[0..9],
names: names,
goals: {team1: game.team_player1.score, team2: game.team_player2.score},
win:
{
team1: game.team_player1.score > game.team_player2.score,
team2: game.team_player2.score > game.team_player1.score,
}
}
end
# process all results
players = {}
other_team = {team1: :team2, team2: :team1}
# add missing players and collect team ratings
results.each do |id, result|
team_ratings = {team1: 0, team2: 0}
result[:names].each do |team, names|
names.each do |username|
if not (players.include?(username))
player = {name: Slack.username_by_id(username), rating: 1500, goals_for: 0, goals_against: 0, wins: 0, losses: 0}
players[username] = player
else
player = players[username]
end
team_ratings[team] += player[:rating] # add players rating to team rating for this result
end
end
# calculate rating deltas
rating_deltas = calculate_rating_deltas(team_ratings, result)
# apply deltas to player stats
result[:names].each do |team, names|
names.each do |username|
players[username][:rating] = players[username][:rating] + rating_deltas[team]
players[username][:goals_for] = players[username][:goals_for] + result[:goals][team]
players[username][:goals_against] = players[username][:goals_against] + result[:goals][other_team[team]]
if result[:win][team]
players[username][:wins] = players[username][:wins] + 1
else
players[username][:losses] = players[username][:losses] + 1
end
end
end
end
players.sort_by{|k, v| v[:rating]}.reverse
end
def self.calculate_rating_deltas(team_ratings, result)
other_team = {team1: :team2, team2: :team1}
rating_deltas = {}
default_win_weight = 10 # what multiplier of rating diff should be applied
score_diff_weight = 0.3 # how much should
base_delta_constant = 10
rating_diff_base_weight = 10
# example rating_points:
# beating stronger team |--VS--| beating weaker team
# team1 rating: 1000 + 1600 = 2600 |--VS--| 1600 + 1550 = 3050
# team2 rating 1600 + 1550 = 3050 |--VS--| 1000 + 1600 = 2600
# rating_diff = -450 |--VS--| 450
# rating_sum = 5650
# relative_rating_diff = -0.0796460177 |--VS--| 0.0796460177
# team1 goals: 10
# team2 goals: 6
# team1 goal_diff = 4
# team1 result_weight: 10 + 10 - 6 = 14
# team1 base_delta: 10 (base_delta_constant) * 14 (result_weight) / 20 (default_win_weight*2) = 70
# handicap_multiplier = 0.50 + (-0.079 * -1) / 2 = 0.535 |--VS--| (1 - 0.079) / 2 = 0.4605
# team1 rating delta: 7 (base_delta) * 10 (rating_diff_base_weight) * 0.535 (relative_rating_diff) = 56
# |--VS--| 7 (base_delta) * 10 (rating_diff_base_weight) * 0.4605 (relative_rating_diff) = 37
# team2 rating delta: -56 |--VS--| 32
team = :team1
rating_sum = team_ratings[team] + team_ratings[other_team[team]]
rating_diff = team_ratings[team] - team_ratings[other_team[team]]
relative_rating_diff = rating_diff / rating_sum.to_f
# ensure some diff if equal teams playing (otherwise 0 value for two new teams with equal rating)
if relative_rating_diff < 0
relative_rating_diff = -0.1 if relative_rating_diff > -0.1
else
relative_rating_diff = 0.1 if relative_rating_diff < 0.1
end
stronger_team_wins_multiplier = handicap_multiplier = (1 - relative_rating_diff) / 2 # (max 0.5)
weaker_team_wins_multiplier = 0.5 + ((relative_rating_diff * -1) / 2) # (min 0.5, max 1)
if result[:win][team] # beating a weaker team
if relative_rating_diff > 0 # playing a weaker team
handicap_multiplier = stronger_team_wins_multiplier
else # beating a stronger team
handicap_multiplier = weaker_team_wins_multiplier
end
else #loosing
if relative_rating_diff > 0 # loosing to a weaker team
handicap_multiplier = -weaker_team_wins_multiplier
else # loosing to a stronger team
handicap_multiplier = -stronger_team_wins_multiplier
end
end
result_weight = default_win_weight + result[:goals][team] - result[:goals][other_team[team]]
result_counter_weight = default_win_weight * 2.0
base_delta = base_delta_constant * (result_weight / result_counter_weight)
rating_delta = base_delta * rating_diff_base_weight * handicap_multiplier
rating_deltas[team] = rating_delta
rating_deltas[other_team[team]] = -rating_delta
rating_deltas
end
def self.games(n_weeks)
n_weeks = n_weeks.to_i
games = nil
if n_weeks == 0
games = Game.order(created_at: :desc)
else
from = (Date.today - (n_weeks * 7)).to_s
games = Game.where("created_at >= ?", from).order(created_at: :desc)
end
games
end
def self.combined(n_weeks)
combined_for_games(self.games(n_weeks))
end
def self.combined_for_games(games)
sorted_players = combined_players_sorted(games)
rows = []
idx = 0
sorted_players.each do |username, p|
idx = idx + 1
rows << ["#{idx}", p[:name], '%.2f' % p[:rating], p[:wins] + p[:losses], p[:wins], p[:losses], p[:goals_for], p[:goals_against], p[:goals_for] - p[:goals_against]]
end
table = Terminal::Table.new :title => "General player rating", :headings => ["Pos", "Name", "Rat.", "GP", "W", "L", "GF", "GA", "GD"], :rows => rows
# table.align_column(8, :right) # right align the diff column content
# table.align_column(9, :center) # center align the rating column content
"```#{table}```
Pos: Rating position. Rat: rating. GP: Games played. W: Won. L: Lost. GF: Goals For. GA: Goals against. GA: Goals diff.
"
end
end
| true |
3cb27832531d8ea7b0070144a9cd4307f822eea7
|
Ruby
|
mleone/questions
|
/reverse_list_mutation.rb
|
UTF-8
| 593 | 3.640625 | 4 |
[] |
no_license
|
require_relative 'lib'
# For each node, make it point to the previous node, and then run the function
# again on the following node, with the current node as the previous node.
def reverse_list_mutation(list, previous=nil)
next_node = list.next_node
list.next_node = previous
if next_node
reverse_list_mutation(next_node, list)
else
list
end
end
node1 = LinkedListNode.new(37)
node2 = LinkedListNode.new(99, node1)
node3 = LinkedListNode.new(12, node2)
LinkedList.print_values(node3)
puts "-------"
revlist = reverse_list_mutation(node3)
LinkedList.print_values(revlist)
| true |
1cf7af4d8e6901fb4d3d4e98db3964c16955c3af
|
Ruby
|
brahamshakti/word_transformer
|
/lib/transformer.rb
|
UTF-8
| 1,495 | 3.234375 | 3 |
[] |
no_license
|
require_relative 'graph'
class Transformer < Graph
def initialize(words)
super()
@word_nodes = add_nodes(words)
end
def is_diff_one?(str1, str2)
return false if(str1.size != str2.size)
count = 0
for i in 0...str1.size
if(str1[i]!=str2[i])
count = count+1
return false if(count > 1)
end
end
return true if(count==1)
return false
end
def add_unidirectional_edges()
for i in 0...@word_nodes.size
for j in i...@word_nodes.size
if is_diff_one?(@word_nodes[i], @word_nodes[j])
add_edge(@word_nodes[i], @word_nodes[j])
end
end
end
end
def find_first_node(start_node_name)
for i in 0...@word_nodes.size
if is_diff_one?(@word_nodes[i], start_node_name)
return @word_nodes[i]
end
end
end
def bfs(start_node_name, end_node_name)
visited = []
level = {}
queue = Queue.new
start_node = get_node(find_first_node(start_node_name))
return 0 unless start_node
level[start_node]=1
queue.enq(start_node)
end_node = get_node(end_node_name)
while(queue.size > 0)
current_node = queue.pop
if(current_node == end_node)
return level[current_node]+1
end
current_node.neighbors.each do |neighbor|
unless(visited.include?(neighbor))
level[neighbor]=level[current_node]+1
visited << neighbor
queue.enq(neighbor)
end
end
end
end
end
| true |
1b20a80b44b50906a21061eba719093b6bfc1fa1
|
Ruby
|
saracastellino/w2_d2_RUBY_multipleclasses_homework
|
/river.rb
|
UTF-8
| 392 | 3.484375 | 3 |
[] |
no_license
|
class River
attr_accessor :name, :fishes
def initialize(name, fishes)
@name = name
@fishes = fishes
end
def number_of_fishes()
return @fishes.length
end
def add_fish(fish)
@fishes.push(fish)
end
def remove_fish
@fishes.pop
end
#
#
# def pick_from_stop(bear)
# bear.stomach.each {|fish| add_fish(fish)}
# bear.clear_the_queue
#
# end
end
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.