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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
f19de996e0b13e9db86bcaf7aa44da6071aaf5eb
|
Ruby
|
JennicaStiehl/ruby-exercises
|
/initialize/lib/horse.rb
|
UTF-8
| 176
| 3.609375
| 4
|
[] |
no_license
|
class Horse
attr_reader :name
attr_accessor :diet
def initialize(name)
@name = name
@diet = []
end
def add_to_diet(food)
@diet << food
end
end
| true
|
a3af1e0fbf9cce938fcb2110ab4ba8b54d6e5d13
|
Ruby
|
synesissoftware/xqsr3-xml
|
/test/unit/xml/utilities/tc_navigation.rb
|
UTF-8
| 1,172
| 2.703125
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] |
permissive
|
#!/usr/bin/env ruby
$:.unshift File.join(File.dirname(__FILE__), *(['..'] * 4), 'lib')
require 'xqsr3/xml/utilities/navigation'
require 'xqsr3/extensions/test/unit'
require 'test/unit'
require 'nokogiri'
class Test_Xqsr3_XML_Utilities_Navigation < Test::Unit::TestCase
include ::Xqsr3::XML::Utilities::Navigation
def test_get_descendants_1
xml_s = <<END_OF_rhs_doc
<?xml version="1.0"?>
<document>
<outer>
<mid_2>
<inner>some more text</inner>
</mid_2>
<mid_1>
<inner>some text</inner>
</mid_1>
</outer>
</document>
END_OF_rhs_doc
xml = ::Nokogiri.XML(xml_s)
doc = xml.children.first
descs = self.class.get_descendants xml.children.first
assert_not_nil descs
assert_kind_of ::Array, descs
assert_operator 7, :<=, descs.size
%w{ outer mid_1 mid_2 }.each do |name|
assert(descs.find { |el| name == el.name }, "did not find an element named '#{name}' in the collection #{descs}")
end
texts = descs.select { |el| el.text? }
[ 'some text', 'some more text' ].each do |text|
assert(texts.find { |el| text == el.text }, "did not find an element with the text '#{text}' in the collection #{texts}")
end
end
end
| true
|
6f7853760e8ab9e82446db8a2fae162947843104
|
Ruby
|
guyviner/codecorelife
|
/day12/PersonalityQuiz/app.rb
|
UTF-8
| 1,662
| 3.109375
| 3
|
[] |
no_license
|
require "sinatra"
#downloaded sinatra reloader to keep the server fresh
require "sinatra/reloader"
# tell it to reference the root
get "/" do
erb :index, layout: :template
# or erb(:index, {layout: :template}) , alternative syntax
# need to embed some ruby to actually see it , using erb
end
post '/index' do
# add a post to listen for input back to the server
# get the temperature that the user entered
@q1 = params[:q1]
@q2 = params[:q2]
@q3 = params[:q3]
if @q1 == "With" && @q2 == "Rash" && @q3 == "Ideas"
@result = "Rational"
elsif @q1 == "Without" && @q2 == "Rash" && @q3 == "Ideas"
@result = "Rational"
elsif @q1 == "With" && @q2 == "Rash" && @q3 == "Facts"
@result = "Guardian"
elsif @q1 == "With" && @q2 == "Compash" && @q3 == "Facts"
@result = "Guardian"
elsif @q1 == "Without" && @q2 == "Rash" && @q3 == "Facts"
@result = "Artisan"
elsif @q1 == "Without" && @q2 == "Compash" && @q3 == "Facts"
@result = "Artisan"
elsif @q1 == "With" && @q2 == "Compash" && @q3 == "Ideas"
@result = "Idealist"
elsif @q1 == "Without" && @q2 == "Compash" && @q3 == "Ideas"
@result = "Idealist"
end
# With deadline | Rational | Ideas > Rational
# With deadline | Rational | Facts > Guardian
# Without deadline | Rational | Ideas > Rational
# Without deadline | Rational | Facts > Artisan
# With deadline | Compassionate | Ideas > Idealist
# With deadline | Compassionate | Facts > Guardian
# Without deadline | Compassionate | Ideas > Idealist
# Without deadline | Compassionate | Facts > Artisan
# erb :index, layout: :template
if @result = "Rational"
"<h1>You are rational</h1>"
end
end
| true
|
85705dc4f7251fb03300810066b6ab9a495283f6
|
Ruby
|
sigus/solutions
|
/cf/1077A.rb
|
UTF-8
| 93
| 2.75
| 3
|
[] |
no_license
|
t = gets.to_i
t.times do
a, b, k = gets.split.map(&:to_i)
p(a*((k + 1)/2) - b*(k/2))
end
| true
|
2864c448120b99860aee256abc948ab6b2fa4abd
|
Ruby
|
epair/autodo
|
/app/models/list.rb
|
UTF-8
| 591
| 2.59375
| 3
|
[] |
no_license
|
class List < ActiveRecord::Base
has_many :cards
belongs_to :board
validates :title, presence: true
validates :board_id, presence: true
def self.generate_calendar(date, board_id)
i = 0
while i < 8 do
new_date = date + i
date_title = new_date.strftime('%a %b %d')
List.create(title: date_title, board_id: board_id)
i += 1
end
end
def self.generate_kanban(board_id)
List.create(title: "To Do", board_id: board_id)
List.create(title: "In Progress", board_id: board_id)
List.create(title: "Completed", board_id: board_id)
end
end
| true
|
4bbdc019a6572a79ab8bed394b8c3d1fc8a96d0a
|
Ruby
|
derekjmaloney/anagram-detector-v-000
|
/lib/anagram.rb
|
UTF-8
| 182
| 3.359375
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
# Your code goes here!
require 'pry'
class Anagram
def initialize(word)
@word = word
end
def match(array)
array.select {|w| w.split("").sort == @word.split("").sort}
end
end
| true
|
9dd96f96af1764982a63a7c8c50823ffc46e962e
|
Ruby
|
simonc/absolute_renamer
|
/lib/absolute_renamer/interpreters/original_filename_interpreter.rb
|
UTF-8
| 503
| 2.6875
| 3
|
[] |
no_license
|
require 'absolute_renamer/interpreters/base'
module AbsoluteRenamer
module Interpreters
class OriginalFilenameInterpreter < Base
def search_and_replace(part_name, new_value, path_handler)
original_value = path_handler.send(part_name)
new_value.gsub(/\$/) { original_value }
.gsub(/&/) { original_value.upcase }
.gsub(/%/) { original_value.downcase }
.gsub(/\*/) { camelcase original_value }
end
end
end
end
| true
|
8ce169c5345403c2302638e80b8bddf5b65483aa
|
Ruby
|
bbuchalter/decoder
|
/lib/decoder/county.rb
|
UTF-8
| 212
| 2.65625
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
module Decoder
class County
include ::CommonMethods
attr_accessor :name, :fips
def initialize(args)
self.name = args[:name]
self.fips = args[:fips].to_i if args[:fips]
end
end
end
| true
|
a2a9a7f251093721de946de097550101cbde61ed
|
Ruby
|
anshulacro/myapp
|
/testwithnoko.rb
|
UTF-8
| 854
| 2.859375
| 3
|
[] |
no_license
|
require 'rubygems'
require 'nokogiri'
require 'open-uri'
PAGE_URL = "http://ruby.bastardsbook.com/files/hello-webpage.html"
XML_URL= "http://asciicasts.com/episodes.xml"
page = Nokogiri::HTML(open(PAGE_URL))
xml_page=Nokogiri::XML(open(XML_URL))
puts xml_page
puts page.css("title")[0].name # => title
puts page.css("title")[0].text # => My webpage
links = page.css("a")
puts links.length # => 6
puts links[0].text # => Click here
puts links[0]["href"] # => http://www.google.com
news_links = page.css("a").select{|link| link['data-category'] == "news"}
news_links.each{|link| puts link['href'] }
xml_page.xpath("//channel").each do |post|
puts post.xpath("//title").text
puts post.xpath("//description").text
puts post.xpath("//link")
%w[title].each do |n|
puts post.at(n).text
end
end
| true
|
0f64a516e89e3ead50e40cb739e831dd79b2ba2f
|
Ruby
|
andrewgho/movewin-ruby
|
/examples/findleaks
|
UTF-8
| 1,327
| 2.734375
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
#!/usr/bin/env ruby
# Load local development directories, if it looks like we are in a repository
DIRNAME = File.dirname(__FILE__);
if File.exists?("#{DIRNAME}/../lib/movewin.rb") &&
File.directory?("#{DIRNAME}/../ext/movewin")
then
$LOAD_PATH.unshift("#{DIRNAME}/../lib", "#{DIRNAME}/../ext")
else
require 'rubygems'
end
require 'movewin'
class MemTracker
def initialize
@vsz = nil
@rss = nil
end
def refresh!
output = `ps auxw | grep '#{$0}$' | grep -v grep | awk '{ print $5, $6 }'`
vsz, rss = output.chomp.split(' ').collect { |s| s.to_i }
if @vsz.nil? || @rss.nil?
puts "#{vsz} #{rss}"
elsif vsz != @vsz || rss != @rss
puts "#{vsz} #{rss} (#{addplus(vsz - @vsz)} #{addplus(rss - @rss)})"
end
@vsz = vsz
@rss = rss
end
private
def addplus(n)
n > 0 ? "+#{n}" : "#{n}"
end
end
RUNS = 1024
TICKS = 60
SHOW_EVERY = (RUNS / TICKS).to_i
m = MemTracker.new
m.refresh!
i = 0
while i < RUNS
windows = MoveWin.windows
windows = nil
if i == 0
m.refresh!
$stderr.puts "#{RUNS} runs, #{SHOW_EVERY} runs/tick"
$stderr.print 'Progress: ['
0.upto(RUNS - 1) { |j| $stderr.print '-' if j % SHOW_EVERY == 0 }
$stderr.print "]\rProgress: ["
end
$stderr.print '*' if i % SHOW_EVERY == 0
i += 1
end
$stderr.puts ']'
m.refresh!
exit 0
| true
|
e5df85c80fa5a38edcd34bbc9ecb1e14b33dad14
|
Ruby
|
quietpochatok/hangman
|
/main.rb
|
UTF-8
| 1,225
| 2.953125
| 3
|
[] |
no_license
|
if Gem.win_platform?
Encoding.default_external = Encoding.find(Encoding.locale_charmap)
Encoding.default_internal = __ENCODING__
[STDIN, STDOUT].each do |io|
io.set_encoding(Encoding.default_external, Encoding.default_internal)
end
end
require_relative 'lib/console_interface'
require_relative 'lib/game'
# 1. Поздороваться с пользователем
puts "Приветствую!"
# 2. Загрузить случайное слово из файла
sample_word_for_game = File.readlines("#{__dir__}/data/words.txt", encoding: 'UTF-8', chomp: true).sample
# Создание игры самой.
game = Game.new(sample_word_for_game)
console_interface = ConsoleInterface.new(game)
# 3. Пока не закончилась игра
until game.over?
# 3.1. Вывести чередное состояние игры
console_interface.print_out
# 3.2. Спросить очередную букву
letter_from_gets = console_interface.get_input
# 3.3. Обновление состояние игры
game.play!(letter_from_gets)
end
# 4. Вывести финальное состояние игры
console_interface.print_out
| true
|
5681d5ca87a6eb589d3e769d91d06009e8bed3ab
|
Ruby
|
molit-korea/main
|
/Pages/2017 국토교통 빅데이터 해커톤 참가작/molit_HAB-master/elastic/logstash-5.5.2/vendor/bundle/jruby/1.9/gems/logstash-filter-metrics-4.0.3/lib/logstash/filters/metrics.rb
|
UTF-8
| 8,640
| 2.890625
| 3
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
# encoding: utf-8
require "securerandom"
require "logstash/filters/base"
require "logstash/namespace"
# The metrics filter is useful for aggregating metrics.
#
# IMPORTANT: Elasticsearch 2.0 no longer allows field names with dots. Version 3.0
# of the metrics filter plugin changes behavior to use nested fields rather than
# dotted notation to avoid colliding with versions of Elasticsearch 2.0+. Please
# note the changes in the documentation (underscores and sub-fields used).
#
# For example, if you have a field `response` that is
# a http response code, and you want to count each
# kind of response, you can do this:
# [source,ruby]
# filter {
# metrics {
# meter => [ "http_%{response}" ]
# add_tag => "metric"
# }
# }
#
# Metrics are flushed every 5 seconds by default or according to
# `flush_interval`. Metrics appear as
# new events in the event stream and go through any filters
# that occur after as well as outputs.
#
# In general, you will want to add a tag to your metrics and have an output
# explicitly look for that tag.
#
# The event that is flushed will include every 'meter' and 'timer'
# metric in the following way:
#
# ==== `meter` values
#
# For a `meter => "something"` you will receive the following fields:
#
# * "[thing][count]" - the total count of events
# * "[thing][rate_1m]" - the per-second event rate in a 1-minute sliding window
# * "[thing][rate_5m]" - the per-second event rate in a 5-minute sliding window
# * "[thing][rate_15m]" - the per-second event rate in a 15-minute sliding window
#
# ==== `timer` values
#
# For a `timer => [ "thing", "%{duration}" ]` you will receive the following fields:
#
# * "[thing][count]" - the total count of events
# * "[thing][rate_1m]" - the per-second event rate in a 1-minute sliding window
# * "[thing][rate_5m]" - the per-second event rate in a 5-minute sliding window
# * "[thing][rate_15m]" - the per-second event rate in a 15-minute sliding window
# * "[thing][min]" - the minimum value seen for this metric
# * "[thing][max]" - the maximum value seen for this metric
# * "[thing][stddev]" - the standard deviation for this metric
# * "[thing][mean]" - the mean for this metric
# * "[thing][pXX]" - the XXth percentile for this metric (see `percentiles`)
#
# The default lengths of the event rate window (1, 5, and 15 minutes)
# can be configured with the `rates` option.
#
# ==== Example: Computing event rate
#
# For a simple example, let's track how many events per second are running
# through logstash:
# [source,ruby]
# ----
# input {
# generator {
# type => "generated"
# }
# }
#
# filter {
# if [type] == "generated" {
# metrics {
# meter => "events"
# add_tag => "metric"
# }
# }
# }
#
# output {
# # only emit events with the 'metric' tag
# if "metric" in [tags] {
# stdout {
# codec => line {
# format => "rate: %{[events][rate_1m]}"
# }
# }
# }
# }
# ----
#
# Running the above:
# [source,ruby]
# % bin/logstash -f example.conf
# rate: 23721.983566819246
# rate: 24811.395722536377
# rate: 25875.892745934525
# rate: 26836.42375967113
#
# We see the output includes our events' 1-minute rate.
#
# In the real world, you would emit this to graphite or another metrics store,
# like so:
# [source,ruby]
# output {
# graphite {
# metrics => [ "events.rate_1m", "%{[events][rate_1m]}" ]
# }
# }
class LogStash::Filters::Metrics < LogStash::Filters::Base
config_name "metrics"
# syntax: `meter => [ "name of metric", "name of metric" ]`
config :meter, :validate => :array, :default => []
# syntax: `timer => [ "name of metric", "%{time_value}" ]`
config :timer, :validate => :hash, :default => {}
# Don't track events that have `@timestamp` older than some number of seconds.
#
# This is useful if you want to only include events that are near real-time
# in your metrics.
#
# For example, to only count events that are within 10 seconds of real-time, you
# would do this:
#
# filter {
# metrics {
# meter => [ "hits" ]
# ignore_older_than => 10
# }
# }
config :ignore_older_than, :validate => :number, :default => 0
# The flush interval, when the metrics event is created. Must be a multiple of 5s.
config :flush_interval, :validate => :number, :default => 5
# The clear interval, when all counter are reset.
#
# If set to -1, the default value, the metrics will never be cleared.
# Otherwise, should be a multiple of 5s.
config :clear_interval, :validate => :number, :default => -1
# The rates that should be measured, in minutes.
# Possible values are 1, 5, and 15.
config :rates, :validate => :array, :default => [1, 5, 15]
# The percentiles that should be measured and emitted for timer values.
config :percentiles, :validate => :array, :default => [1, 5, 10, 90, 95, 99, 100]
def register
require "metriks"
require "socket"
require "atomic"
require "thread_safe"
@last_flush = Atomic.new(0) # how many seconds ago the metrics where flushed.
@last_clear = Atomic.new(0) # how many seconds ago the metrics where cleared.
@random_key_preffix = SecureRandom.hex
unless (@rates - [1, 5, 15]).empty?
raise LogStash::ConfigurationError, "Invalid rates configuration. possible rates are 1, 5, 15. Rates: #{rates}."
end
@metric_meters = ThreadSafe::Cache.new { |h,k| h[k] = Metriks.meter metric_key(k) }
@metric_timers = ThreadSafe::Cache.new { |h,k| h[k] = Metriks.timer metric_key(k) }
end # def register
def filter(event)
# TODO(piavlo): This should probably be moved to base filter class.
if @ignore_older_than > 0 && Time.now - event.timestamp.time > @ignore_older_than
@logger.debug("Skipping metriks for old event", :event => event)
return
end
@meter.each do |m|
@metric_meters[event.sprintf(m)].mark
end
@timer.each do |name, value|
@metric_timers[event.sprintf(name)].update(event.sprintf(value).to_f)
end
end # def filter
def flush(options = {})
# Add 5 seconds to @last_flush and @last_clear counters
# since this method is called every 5 seconds.
@last_flush.update { |v| v + 5 }
@last_clear.update { |v| v + 5 }
# Do nothing if there's nothing to do ;)
return unless should_flush?
event = LogStash::Event.new
event.set("message", Socket.gethostname)
@metric_meters.each_pair do |name, metric|
flush_rates event, name, metric
metric.clear if should_clear?
end
@metric_timers.each_pair do |name, metric|
flush_rates event, name, metric
# These 4 values are not sliding, so they probably are not useful.
event.set("[#{name}][min]", metric.min)
event.set("[#{name}][max]", metric.max)
# timer's stddev currently returns variance, fix it.
event.set("[#{name}][stddev]", metric.stddev ** 0.5)
event.set("[#{name}][mean]", metric.mean)
@percentiles.each do |percentile|
event.set("[#{name}][p#{percentile}]", metric.snapshot.value(percentile / 100.0))
end
metric.clear if should_clear?
end
# Reset counter since metrics were flushed
@last_flush.value = 0
if should_clear?
#Reset counter since metrics were cleared
@last_clear.value = 0
@metric_meters.clear
@metric_timers.clear
end
filter_matched(event)
return [event]
end
# this is a temporary fix to enable periodic flushes without using the plugin config:
# config :periodic_flush, :validate => :boolean, :default => true
# because this is not optional here and should not be configurable.
# this is until we refactor the periodic_flush mechanism per
# https://github.com/elasticsearch/logstash/issues/1839
def periodic_flush
true
end
private
def flush_rates(event, name, metric)
event.set("[#{name}][count]", metric.count)
event.set("[#{name}][rate_1m]", metric.one_minute_rate) if @rates.include? 1
event.set("[#{name}][rate_5m]", metric.five_minute_rate) if @rates.include? 5
event.set("[#{name}][rate_15m]", metric.fifteen_minute_rate) if @rates.include? 15
end
def metric_key(key)
"#{@random_key_preffix}_#{key}"
end
def should_flush?
@last_flush.value >= @flush_interval && (!@metric_meters.empty? || !@metric_timers.empty?)
end
def should_clear?
@clear_interval > 0 && @last_clear.value >= @clear_interval
end
end # class LogStash::Filters::Metrics
| true
|
29b63441b37bcde2c865e388c444d92c2d4873b6
|
Ruby
|
johnnykalalua/ruby-challenges
|
/12. Advanced Arguemnt Emily Greeting/Advanced_argument_Emily_greeting.rb
|
UTF-8
| 486
| 3.96875
| 4
|
[] |
no_license
|
puts "What is your name?"
user_name = gets.to_s
def determine_current_hour
current_time = Time.new
current_hour = current_time.hour
end
def greeting(user_name)
current_hour = determine_current_hour
if (current_hour > 3 && current_hour < 12)
time = "morning"
elsif (current_hour > 12 && current_hour < 18)
time = "afternoon"
elsif (current_hour > 18 || current_hour < 2)
time = "evening"
end
puts "Good #{time}, #{user_name.capitalize}"
end
greeting (user_name)
| true
|
65792ec76047e29be3c5e2ca2b52974212adcf80
|
Ruby
|
tullur/mampf
|
/app/models/link.rb
|
UTF-8
| 1,091
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
# Link class
# JoinTable for medium<->medium many-to-many-relation
# describes which media are related to a given medium
class Link < ApplicationRecord
belongs_to :medium
belongs_to :linked_medium, class_name: 'Medium'
# we do not want duplicate entries
validates :linked_medium, uniqueness: { scope: :medium }
# after saving, we symmetrize the relation
after_save :create_inverse, unless: :inverse?
# we do not want a medium to be in relation to itself
after_save :destroy, if: :self_inverse?
# after a link is destroyed, destroy the link in the other direction as well
after_destroy :destroy_inverses, if: :inverse?
private
def self_inverse?
medium_id == linked_medium_id
end
def create_inverse
self.class.create(inverse_link_options)
end
def destroy_inverses
inverses.destroy_all
end
def inverse?
self.class.exists?(inverse_link_options) || self_inverse?
end
def inverses
self.class.where(inverse_link_options)
end
def inverse_link_options
{ linked_medium_id: medium_id, medium_id: linked_medium_id }
end
end
| true
|
f6668943e62685ce578374b5b8dc87fd748cce1b
|
Ruby
|
iwaseasahi/design_pattern_with_ruby
|
/facade/html_writer.rb
|
UTF-8
| 551
| 2.90625
| 3
|
[] |
no_license
|
class HtmlWriter
def initialize(writer)
@writer = writer
end
def title(title)
@writer.puts('<html>')
@writer.puts('<head>')
@writer.puts('<title>' + title + '</title>')
@writer.puts('</head>')
@writer.puts('<body>')
@writer.puts('<h1>' + title + '</h1>')
end
def paragraph(msg)
@writer.puts('<p>' + msg + '</p>')
end
def link(href, caption)
paragraph('<a href="' + href + '">' + caption + '</a>')
end
def mailto(mail_address, user_name)
link('mailto:' + mail_address, user_name)
end
end
| true
|
89ac8b5d31ab40750d602330f504ba121b5f42bd
|
Ruby
|
mmaltar/flighter
|
/isa-backend-flighter-mmaltar-feature-hw8/app/services/world_cup/match.rb
|
UTF-8
| 1,739
| 2.8125
| 3
|
[] |
no_license
|
module WorldCup
class Match
attr_accessor :venue, :status, :starts_at
attr_reader :home_team_goals, :home_team_code, :home_team_name,
:away_team_goals, :away_team_code, :away_team_name,
:events, :goals
def initialize(match = {})
@venue = match['venue']
@status = match['status']
initialize_start(match['datetime'])
initialize_teams(match)
initialize_events(match)
end
def initialize_teams(match = {})
@home_team_goals = match.dig('home_team', 'goals')
@home_team_name = match.dig('home_team', 'country')
@home_team_code = match.dig('home_team', 'code')
@away_team_goals = match.dig('away_team', 'goals')
@away_team_name = match.dig('away_team', 'country')
@away_team_code = match.dig('away_team', 'code')
end
def initialize_start(datetime)
@starts_at = Time.parse(datetime).utc
end
def initialize_events(match = {})
@events = (match['home_team_events'] + match['away_team_events'])
.map do |e|
WorldCup::Event.new(e)
end
@goals = @events.select { |e| e.type.include?('goal') }
end
def result
if status == 'future'
'--'
else
"#{home_team_goals} : #{away_team_goals}"
end
end
def to_s
"##{id}: #{type}@#{time} - #{player}"
end
def goals_num
if status == 'future'
'--'
else
@home_team_goals + @away_team_goals
end
end
def as_json(_opts = {})
{
away_team: @away_team_name,
goals: goals_num,
home_team: @home_team_name,
score: result,
status: @status,
venue: @venue
}
end
end
end
| true
|
ff59bfcefdb7736836d4fbebec1c284a0dabf743
|
Ruby
|
ykumawat/cartoon-collections-ruby-cartoon-collections-000
|
/cartoon_collections.rb
|
UTF-8
| 598
| 3.484375
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def roll_call_dwarves(dwarves)# code an argument here
# Your code here
dwarves.each_with_index do |dwarf, index|
puts "#{index+1}.#{dwarf}"
end
end
def summon_captain_planet(calls)# code an argument here
# Your code here
calls.collect{|call|"#{call.capitalize}!"}
end
def long_planeteer_calls(calls)# code an argument here
# Your code here
calls.any?{|word| word.length > 4}
end
def find_the_cheese(cheeses)# code an argument here
# the array below is here to help
cheese_types = ["cheddar", "gouda", "camembert"]
cheeses.find{|cheese| cheese_types.include?(cheese)}
end
| true
|
83d05667e987a562526c0631f6b70470878165bd
|
Ruby
|
joannajohn0214/kwk-l1-garden-gnome-oo-lab-kwk-students-l1-raleigh-072318
|
/garden_gnome.rb
|
UTF-8
| 1,236
| 3.890625
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
# Code your instances here
class GardenGnome
def name=(name)
@name= name
end
def name
@name
end
def age=(age)
@age=age
end
def age
@age
end
def gluten_allergy=(gluten_allergy)
@gluten_allergy=gluten_allergy
end
def gluten_allergy
@gluten_allergy
end
def personality=(personality)
@personality=personality
end
def personality
@personality
end
def hat_color=(hat_color)
@hat_color=hat_color
end
def hat_color
@hat_color
end
def initialize(personality = "evil", hat_color = "red")
@personality = personality
@hat_color = hat_color
end
def gnaw
return "Gnawing on a tree!!!"
end
def shout
return "GNARLY!!!"
end
def introduce_self
return "Hello humans, my name is #{@name}, I am #{@age} years old, and you'll rue the day you crossed me!"
end
end
gnome1 = GardenGnome.new
gnome1.name = "Walter the Worst"
puts gnome1.name
gnome2= GardenGnome.new
gnome2.name="James the Jerk"
gnome2.age="3421"
puts gnome2.name
puts gnome2.age
gnome3= GardenGnome.new
gnome3.name="Alfred the Abhorrent"
gnome3.age="579"
gnome3.gluten_allergy=TRUE
puts gnome3.name
puts gnome3.age
puts gnome3.gluten_allergy = "Has a gluten allergy"
| true
|
a14e105b1ccad81b263bae8c1b68040a23f0dbd3
|
Ruby
|
betweenparentheses/ruby_building_blocks
|
/caesar_cipher.rb
|
UTF-8
| 924
| 3.96875
| 4
|
[] |
no_license
|
#working version!
def caesar_cipher (string, num)
shift = num % 26
chars = string.split(//)
chars.map! do |char|
char_num = char.ord
was_letter = false
was_letter = true if (char =~ (/\w/)) #checks if it was originally a letter rather than space or punctuation
#wraparound check. handles capitals and lowercases separately to protect against a large shift causing case confusion
if (char_num <= 90 && was_letter && (char_num + shift) > 90)
char_num -= 26
elsif ((char_num >= 97) && was_letter && (char_num + shift) > 122)
char_num -= 26
end
char_num += shift if was_letter
char = char_num.chr
end
chars.join
end
print "Enter a phrase to put into secret code: "
phrase = gets.chomp
print "Enter a number that represents the distance you want to shift each letter down the alphabet (HINT--Use negative numbers to decode):"
shift_num = gets.chomp.to_i
puts caesar_cipher(phrase, shift_num)
| true
|
822b7cb55f159e5c995809fa2d139b47e925fd3d
|
Ruby
|
russellschmidt/BlocBooks
|
/app/controllers/books_controller.rb
|
UTF-8
| 796
| 2.59375
| 3
|
[] |
no_license
|
class BooksController < BlocWorks::Controller
def welcome
render :welcome, book: 'Loquacious Ruby'
end
def index
render :index, books: Book.all
end
def show
book = Book.find(params['id'])
render :show, book: book
end
def new
render :new
end
def create
# add to db
redirect :index
end
def edit
render :edit, book: Book.find(get_book_id)
end
def update
@id = Book.find(get_book_id)
# update db
redirect :index
end
def destroy
@id = Book.find(get_book_id)
# delete from db
redirect :index
end
private
def get_book_id
# access env variable and get URI
# parse env variable to find '?id=1'
# parse the '1' out
uri = @env["REQUEST_URI"].to_s
id_query = uri.match(/\?([\w-])+(=[\w-]*)/).to_s
id_query.split('=')[1].to_i
end
end
| true
|
895efb10eaaf3be005088f6bbe3bc6f4cd5df075
|
Ruby
|
Diley/studio_game
|
/_partial_versions/fundraising_program/fundraising_program_v18/fundrequest.rb
|
UTF-8
| 1,822
| 3.40625
| 3
|
[] |
no_license
|
require_relative 'project'
require_relative 'die'
require_relative 'funding_round'
require_relative 'pledge_pool'
class FundRequest
attr_accessor :name
def initialize(name)
@name = name
@projects = []
end
def add_project(project)
@projects << project
end
def request_funding(rounds)
pledges = PledgePool::PLEDGES
puts "There are #{pledges.size} pledges:"
pledges.each do |pledge|
puts "\tA #{pledge.name} plage is worth #{pledge.amount}"
end
1.upto(rounds) do |round|
puts "\nRequest Funding on Round: #{round}"
@projects.each do |project|
FundingRound.take_turn(project)
end
end
end
def print_project_stats(project)
"#{project.name}".ljust(30, '.') + "#{project.funding}".ljust(9,'.') + "#{project.target_funding}".ljust(9,'.')
end
def print_project_funding_left(project)
"#{project.name}".ljust(30, '.') + "#{project.funding_left}"
end
def print_stats
puts "\nStats for #{@name}"
fully_funded, under_funded = @projects.partition { |project| project.fully_funded? }
puts "\nFully funded projecs:"
fully_funded.each { |project| puts print_project_stats(project) }
puts "\nUnder funded projecs:"
under_funded.each { |project| puts print_project_stats(project) }
puts "\nProjects with more fundings left"
under_funded.sort.each { |project| puts print_project_funding_left(project) }
@projects.each do |project|
puts "\nProject #{project.name} pledges:"
project.each_pledge do |pledge|
puts "$#{pledge.amount} in #{pledge.name} pledges"
end
puts "$#{project.pledges_amount} in total pledges"
end
# @projects.sort.each { |project| puts print_project_funding_left(project) unless project.fully_funded? }
end
def total_pledges_amount
@projects.each.reduce(0) { |sum, project| sum += project.pledges_amount }
end
end
| true
|
261d87f552c43de909454f03b4bd5b786bddcfd6
|
Ruby
|
kiwofusi/column_name_conv
|
/2_column_name_conv2_timeover.rb
|
UTF-8
| 2,362
| 3.078125
| 3
|
[] |
no_license
|
=begin
start:1854
end:1915(21m)
end:1925(31m) リファクタリング&バグ修正
start2:1925
end2:2016 ruby column_name_conv2.rb 1 1 成功
deadline:2024 終了……
26**0 => 1
A=>1
AA=> (26**1 * 1) + (26**0 * 1)
BA=> (26**1 * 2) + (26**0 * 1)
BB=> (26**1 * 2) + (26**0 * 2)
AAA=> (26**2 * 1) + (26**1 * 1) + (26**0 * 1)
XFD=> (26**2 * 24) + (26**1 * 6) + (26**0 * 4) => 16384
27 => (26**1 * 1) + (26**0 * 1) => AA
27/26 = 1...1
26 => (26**0 * 26) => Z
16384 => (26**2 * 24) + (26**1 * 6) + (26**0 * 4) => XFD
16384 % 26**2 => 160(rest)
16384 / 26**2 => 24 => X # 割り算がプラスになる一番大きい値を特定する
160 % 26**1 => 4(rest)
160 / 26**1 => 6 => F
4 % 26**0 => 4 => D # restが26以下なら終了
・繰り返しで考える
・再帰させる
・文字の枠で考える(割り算のひっ算)
=end
mode = {0=>:to_num, 1=>:to_char}[ARGV[0].to_i]
val_to_conv = ARGV[1]
num_of = {'A'=>1, 'B'=>2, 'C'=>3, 'D'=>4, 'E'=>5, 'F'=>6, 'G'=>7, 'H'=>8, 'I'=>9, 'J'=>10, 'K'=>11, 'L'=>12, 'M'=>13, 'N'=>14, 'O'=>15, 'P'=>16, 'Q'=>17, 'R'=>18, 'S'=>19, 'T'=>20, 'U'=>21, 'V'=>22, 'W'=>23, 'X'=>24, 'Y'=>25, 'Z'=>26}
def do_div(result, rest_num, char_of) # 引数をmodしたときにプラスになる一番大きい値
div_num = 0 # rest_num を割る値
p rest_num
if rest_num < char_of.size # 終了条件
puts result += char_of[rest_num]
return result
end
# 次回の rest_num は mod で求まる
# result の追加文字は rest_num / 26**div_num で求まる
result_div = 1 # dummy
while result_div > 0 # 割り算が0になったら、そのひとつまえのdiv_numを使おう
result_div = rest_num / char_of.size**div_num
div_num += 1
end
div_num -= 1 # rest_num を割ってあまりが出る最大の数
puts result += char_of[rest_num / char_of.size**div_num]
puts next_rest_num = rest_num % char_of.size**div_num
do_div(result, next_rest_num, char_of)
end
if mode == :to_num
column_name = val_to_conv
result = 0
column_name.split(//).reverse.each_with_index do |char, place| # split忘れず!
result += (num_of.size**place) * num_of[char]
end
puts result
elsif mode == :to_char
column_num = val_to_conv.to_i
char_of = num_of.invert
result = ""
puts do_div(result, column_num, char_of)
end
| true
|
79d08c86b9276368a71402d17113c864d6ae7471
|
Ruby
|
ostarling/planner
|
/planning/ordering.rb
|
UTF-8
| 11,468
| 2.90625
| 3
|
[] |
no_license
|
module Math
def self.min a,b
a<b ? a : b
end
def self.max a,b
a>b ? a : b
end
end
module Planning
class OrderingException < Exception
end
class OrderingData
attr_reader :prev_version, :version
attr_writer :order
def initialize prev_version, version, order=nil, next_ords=nil, prev_ords=nil
@prev_version = prev_version
if prev_version.nil? && (order.nil? || next_ords.nil? || prev_ords.nil? )
#raise "Invalid arguments: either prev_version or both order and next_ords should be non-nil"
raise "Invalid arguments: either prev_version should be non-nil "+
"or order, next_ords and prev_ords all should be non-nil"
end
@version = version
@order = order
@next_ords = next_ords
@prev_ords = prev_ords
end
def chain version, order, next_ords, prev_ords
OrderingData.new self, version, order, next_ords, prev_ords
end
def order
@order.nil? ? @prev_version.order : @order
end
def next_ords
@next_ords.nil? ? @prev_version.next_ords : @next_ords
end
def prev_ords
@prev_ords.nil? ? @prev_version.prev_ords : @prev_ords
end
def order_unset?
@order.nil?
end
def next_ords_unset?
@next_ords.nil?
end
def prev_ords_unset?
@prev_ords.nil?
end
end
class Ordering
# @@debug = true
attr_reader :step
attr_accessor :trace
def initialize orderings, step, order, version
@orderings = orderings
@step = step
# prev_version, version, order, next_ords, prev_ords
@data = OrderingData.new nil, version, order, [], []
@trace = 0
end
def order= value
if @data.order_unset? && @data.version==@orderings.cur_version
@data.order = value
else
@data = @data.chain @orderings.cur_version, value, nil, nil
end
end
def order
@data.order
end
def next_ords
@data.next_ords
end
def prev_ords
@data.prev_ords
end
def add_next_ords ord
unless @data.next_ords.include? ord
new_next_ords=[]
new_next_ords.push *(@data.next_ords)
new_next_ords << ord
if @data.next_ords_unset? && @data.version==@orderings.cur_version
@data.next_ords = new_next_ords
else
@data = @data.chain @orderings.cur_version, nil, new_next_ords, nil
end
ord.add_prev_ords self
end
end
private
def add_prev_ords ord
new_prev_ords=[]
new_prev_ords.push *(@data.prev_ords)
new_prev_ords << ord
if @data.prev_ords_unset? && @data.version==@orderings.cur_version
@data.prev_ords = new_prev_ords
else
@data = @data.chain @orderings.cur_version, nil, nil, new_prev_ords
end
end
public
def to_s
"{step #{@step} @#{trace}, "+
"order=#{@data.order}, version=#{@data.version}, "+
"next=[#{list_to_s(@data.next_ords)}]}"
end
def list_to_s list
list.collect{|ord| ord.step.to_s+":"+ord.order.to_s }.join(',')
end
# @@MIN_GEN=-2000000000
# @@MAX_GEN=2000000000
def min_next
unless next_ords.empty?
next_ords.inject{|min, ord| min.order>ord.order ? ord : min}
else
nil
end
end
#
# Reverts to the specified version.
# If this entry is older than the version specified, returns false.
# Otherwise returns true
#
def revert_to version
while !@data.nil? && @data.version > version
@data = @data.prev_version
end
!@data.nil?
end
end
class Orderings
def initialize start, finish
@steps = {}
@version = 0
@order_step = 10
@trace=0
@start = start
@finish = finish
# it is implied that start is before finish
#ostart = get_ordering @start
#ofinish = get_ordering @finish
#ostart.add_next_ords ofinish
end
def cur_version
@version
end
def get_ordering step, order=1
ord = @steps[step]
if ord.nil?
ord = Ordering.new self, step, order, @version
@steps[step] = ord
end
ord
end
def revert_to version
puts "Orderings: Reverting to version #{version}"
vals = @steps.values
vals.each{|ord|
@steps.delete ord.step unless ord.revert_to version
}
@version = version
end
def dump
puts "Dumping orderings"
@steps.each{|step,ord|
puts "#{step} ==> ["+ord.next_ords.map{|o| o.step}.join(", ")+"]"
#puts "#{step} => #{ord}"
}
puts "=="
end
# def dump_tree start=nil
# if start.nil?
# m = @steps.each_value.inject{|m,s| m.order<s.order ? m : s}
# end
# end
# returns
# 1 - if the step is after 'relative_to' step
# -1 - if the step is before 'relative_to' step
# 0 - if there is no defined ordering relation between these steps
def get_relative_position step, relative_to
#this method must not be invoked with relative_to equal to @start or @finish
raise if [@start,@finish].include? relative_to
#handle special cases
return -1 if step==@start
return 1 if step==@finish
ostep = get_ordering step
orel = get_ordering relative_to
if ostep.order < orel.order
#'step' can possibly be before
res = find_before orel, ostep
return res.nil? ? 0 : -1
elsif ostep.order > orel.order
#'step' can possibly be after
res = find_after orel, ostep
return res.nil? ? 0 : 1
else
#'step' is surely unrelated
return 0
end
end
def find_after obase, ostep
obase.next_ords.each do |o|
return o if o.step = ostep.step
if o.order < ostep.order
res = find_after o, ostep
return res unless res.nil?
end
end
return nil
end
def find_before obase, ostep
obase.prev_ords.each do |o|
return o if o.step = ostep.step
if o.order > ostep.order
res = find_before o, ostep
return res unless res.nil?
end
end
return nil
end
def add step1, step2
# check obvious ordering violations
raise OrderingException.new("Can't put @{step2} after the GOAL step") if step1==@finish
raise OrderingException.new("Can't put @{step1} before the INITIAL step") if step2==@start
# don't actually add orderings like AFTER INITIAL and BEFORE GOAL
# as it is implied and enforced for all other steps
if step1==@start || step2==@finish
return
end
@trace += 1 # allocate a new unique trace value
@version += 1
begin
o1 = get_ordering step1
o2 = get_ordering step2
#p o1, o2
unless o1.next_ords.include? o2
puts "Adding ordering #{step1} << #{step2}"
o1.add_next_ords o2
#o2.prev << o1
#puts "next_ords became #{o1.next_ords}"
if o1.order >= o2.order
propogate o2, o1.order
end
# else
# puts "Ignoring duplicate ordering"
end
rescue OrderingException
puts "Failed to add ordering #{step1} << #{step2}"
@version -= 1
revert_to @version
raise
end
end
def propogate ordering, order
#p "in propogate with #{ordering} and #{order}"
if ordering.trace == @trace
raise OrderingException.new, "Circular reference", caller
end
ordering.trace = @trace
min_ord = ordering.min_next
min_next = min_ord.nil? ? nil : min_ord.order
# if there is no next
if min_next.nil?
ordering.order = order + @order_step
# p "there is no next, setting gerenation to #{ordering.order} "
return
end
#max_prev = ordering.max_prev
if order+1 < min_next
# p "case 1"
ordering.order = (min_next - order) / 2 + order
else
if order-min_next > @order_step
# p "case 2"
ordering.order = order + @order_step
else
# p "case 3"
ordering.order = order + @order_step / 2
end
ordering.next_ords.each{|o|
propogate o, ordering.order if o.order<=ordering.order }
end
end
end
class IteratorPathElement
attr_accessor
def initialise orderings
@orderings = orderings
@position = 0
end
def has_more?
@position+1 < @orderings.size
end
def next
if has_more?
@position += 1
@orderings[@position]
else
nil
end
end
#returns the current ordering
def cur_ordering
@orderings
end
end
class OrderingNetIterator
def initialize base_ordering, method_name=:prev_ords
@base = base_ordering
@path = [] #corresponds to
@method_name = method_name
end
def get_data ordering
ordering.__send__(@method_name)
end
#moves pointer to the next step in the tree
#returns the next Ordering element or nil no more elements left
def next
# if the path is empty attempt create the first path element
if @path.empty?
ords = get_data @base
if ords.empty?
# if the base ordering has no related orderings to traverse
# return false
return nil
else
#otherwise create the path element
@path << IteratorPathElement.new(ords[0])
return ords[0]
end
else
# The path is not empty, we have to advance to the next element
cur_elem = @path[-1]
# We use the depth-first algorithm, check whether we can deepen first
ords = get_data(cur_elem.cur_ordering)
unless ords.empty?
# deepen the path
@path << IteratorPathElement.new(ords[0])
return ords[0]
else
# move to next element
# remove path elements which have enumerated already all their children
until cur_elem.has_more?
@path.pop
if @path.empty?
return nil
end
cur_elem = @path[-1]
end
#actually move to the next sibling element
return cur_element.next
end
end
end
def get_current
return nil if @path.size==0
cur_elem = @path[-1]
get_data(cur_elem[:ord])[cur_elem[:idx]]
end
end
class LazyTreeLinearizer
def initilize iterator
@iterator = iterator
@linearized = []
end
def get idx
raise if idx<0
if idx<=@linearized.size
@linearized[idx]
else
i=@linearized.size
while i<=idx
elem = @iterator.next
unless elem.nil?
@linearized << elem
i += 1
else
return nil
end
end
return @linearized[-1]
end
end
end
class LinearizerIterator
def initalize linearizer
@linearizer = linearizer
self.reset
end
def reset
@position = 0
end
def next
res = @linearizer.get @position
@position +=1 unless res.nil?
res
end
end
class FileringLinearizer
def initialize @linearizer_iterator
@cached = []
end
end
end
| true
|
ccc2548344608a11e31ecb2898e55c4f4fb15676
|
Ruby
|
westonganger/rodf
|
/lib/rodf/row.rb
|
UTF-8
| 945
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
module RODF
class Row < Container
attr_reader :number
def initialize(number=0, opts={})
@number = number
@elem_attrs = {}
@elem_attrs['table:style-name'] = opts[:style] unless opts[:style].nil?
if opts[:attributes]
@elem_attrs.merge!(opts[:attributes])
end
super
end
def cells
@cells ||= []
end
def cell(*args, &block)
x = Cell.new(*args, &block)
cells << x
return x
end
def cells_xml
cells.map(&:xml).join
end
def style=(style_name)
@elem_attrs['table:style-name'] = style_name
end
def add_cells(*elements)
if elements.first.is_a?(Array)
elements = elements.first
end
elements.each do |element|
cell(element)
end
end
def xml
Builder::XmlMarkup.new.tag! 'table:table-row', @elem_attrs do |xml|
xml << cells_xml
end
end
end
end
| true
|
0d7e692ba8d75de4b01131502b39726d64475ddb
|
Ruby
|
Catharz/Raids-Per-Loot
|
/app/models/player_character.rb
|
UTF-8
| 956
| 2.671875
| 3
|
[] |
no_license
|
# @author Craig Read
#
# PlayerCharacter is a composite representing
# the Player and one of their Characters.
# This is used to simplify editing loot statistics
# for a particular player and character.
class PlayerCharacter
include Virtus.model
extend ActiveModel::Naming
include ActiveModel::Conversion
attr_reader :id
attr_reader :player
attr_reader :character
attribute :id, Integer
attribute :player, Player
attribute :character, Character
def initialize(character_id)
@id = character_id.to_i
@character = Character.find(id)
@player = Player.find(@character.player_id)
end
def reload
@character.reload
@player.reload
end
def persisted?
false
end
def save
true
end
def eql?(other)
@id.eql? other.id and @character.eql? other.character and @player.eql? other.player
end
def ==(other)
@id == other.id and @character == other.character and @player == other.player
end
end
| true
|
78f8e60521901f93b363163a3596ccba492aa7b3
|
Ruby
|
kgoettling/ruby_lessons
|
/lesson_3_practice_problems/medium_1/medium_1_7.rb
|
UTF-8
| 262
| 4.0625
| 4
|
[] |
no_license
|
# What is the output of the following code?
answer = 42
def mess_with_it(some_number)
some_number += 8
end
new_answer = mess_with_it(answer)
p answer - 8
# A: The code will output '34' to the screen. The variable answer is
# not modified by the method.
| true
|
f55aee5f0440285e56f597b6f1ac1e75d1475f86
|
Ruby
|
jarombra/codecademy_Ruby
|
/lessonSeries/04_RB_thithMeanthWar/07_returningTheFinalStringErThtring.rb
|
UTF-8
| 234
| 3.890625
| 4
|
[] |
no_license
|
print "Type a phrase that uses the letter 's'"
user_input = gets.chomp
user_input.downcase!
if user_input.include? "s"
user_input.gsub!(/s/, "th")
puts "WAAAA! #{user_input}!"
else
puts "The letter 's' was not found"
end
| true
|
b8b87430fc6959dc9f1cbcd692c923b6b777c0ca
|
Ruby
|
Josh-Gotro/ruby-oo-object-relationships-collaborating-objects-lab-austin-web-030920
|
/lib/song.rb
|
UTF-8
| 784
| 3.453125
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
require 'pry'
class Song
attr_accessor :name, :artist
@@all = []
def initialize (name)
# binding.pry
@name = name
@@all << self
end
def self.all
@@all
end
def self.new_by_filename (filename)
# binding.pry
# associates new song instance with the artist from the filename
artist, song = filename.split(" - ")
new_song = self.new(song)
new_song.artist_name = artist
new_song
#"Michael Jackson - Black or White - pop.mp3"
end
def artist_name= (name)
self.artist = Artist.find_or_create_by_name(name)
artist.add_song(self)
# binding.pry
end
# name
# => "Michael Jackson"
# self
# => #<Song:0x00007fee74aa1f08 @name="Black or White">
end
| true
|
ab97e8e253ae14c9aed03bf225d70194e40bee07
|
Ruby
|
clucas/caplinkedex
|
/app/models/book.rb
|
UTF-8
| 1,392
| 2.65625
| 3
|
[] |
no_license
|
require 'csv'
class Book < ApplicationRecord
searchkick
validates :title, presence: true
validates :author, presence: true
validates :publisher, presence: true
validates :category, presence: true
validates :published_on, presence: true
composed_of :unit_cost,
:class_name => 'Money',
:mapping => [%w(unit_cost fractional), %w(currency currency_as_string)],
:constructor => Proc.new { |unit_cost, currency| Money.new(unit_cost, currency || Money.default_currency) },
:converter => Proc.new { |value| value.respond_to?(:to_money) ? (value.to_f.to_money rescue Money.empty) : Money.empty }
CSV_FILE = File.join( Rails.root.to_s, 'db', "import", "books.csv")
def price
unit_cost.to_d * ( 1 + MARKUP[self.category] )
end
def display_price
price.to_s
end
def self.import_csv(file)
begin
CSV.foreach(CSV_FILE, { headers: true, header_converters: :symbol }) do |row|
book = Book.find_or_initialize_by(title: row[:title], author: row[:author], publisher: row[:publisher], category: row[:category], published_on: row[:published_on])
book.attributes = row.to_hash.merge({:currency => "USD"})
book.unit_cost = row[:unit_cost].to_f * 100.0
book.save!
end
rescue Exception => e
puts e.message
puts "Book could not be created"
end
end
end
| true
|
8cd22e4ce4422a2776ce6ea18f4b1708183d3526
|
Ruby
|
baya/topic-api
|
/app/errors/api_error.rb
|
UTF-8
| 331
| 2.703125
| 3
|
[] |
no_license
|
module ApiError
Base = Class.new(StandardError)
Unauthorized = Class.new(Base)
CODE = {
Unauthorized => 401
}
def self.raise_error(error_class_name, error_msg = nil)
error_class = const_get(error_class_name)
raise error_class, error_msg
end
def self.get_code(error)
CODE[error.class]
end
end
| true
|
6d19e149a4e892edb703c797848aa27a90149821
|
Ruby
|
envato/flip
|
/lib/flip/abstract_value_in_list_strategy.rb
|
UTF-8
| 800
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
module Flip
class AbstractValueInListStrategy < AbstractStrategy
include StrategyPersistence
def description
raise NotImplementedError
end
def value_param_name
raise NotImplementedError
end
def knows?(definition, options = {})
options[value_param_name] && on?(definition, options)
end
def valid_options
return ["allowed_values"]
end
def on?(definition, options = {})
if options[value_param_name]
values = Array(options[value_param_name])
matching_values = allowed_values(definition) & values
!matching_values.empty?
end
end
private
def allowed_values(definition)
values_string = get(definition, "allowed_values") || ""
values_string.split(/[\s,]+/)
end
end
end
| true
|
b15c20333270231050f50bb258bb8cf2ab7df83e
|
Ruby
|
Illianthe/ProjectEuler
|
/solutions/023/non_abundant_sums.rb
|
UTF-8
| 897
| 3.609375
| 4
|
[] |
no_license
|
# Problem #23 - http://projecteuler.net/problem=23
require '../../lib/utility.rb'
include Utility
def non_abundant_sums
abundant_numbers = Hash.new(false)
# Find all abundant numbers. We have an upper limit of 28111 because
# we will only check for sums up to 28123 (and 12 is the smallest abundant #)
(12..28111).each do |i|
sum_of_divisors = proper_divisors(i).inject(:+)
abundant_numbers[i] = true if sum_of_divisors > i
end
# Check to see if each integer can be written as a sum of two abundant #s.
# Sum the ones that can't be.
sum = 0
(1..28123).each do |i|
non_abundant = true
abundant_numbers.each do |key, value|
next if !value
break if key > i
difference = i - key
if abundant_numbers[difference]
non_abundant = false
break
end
end
sum += i if non_abundant
end
sum
end
p non_abundant_sums
| true
|
78e7cca7328f523ecbeaca0066e346218da1374d
|
Ruby
|
leandroalemao/gb-blog
|
/app/facades/archive.rb
|
UTF-8
| 388
| 3.03125
| 3
|
[] |
no_license
|
module Facades
class Archive
def initialize(posts = [])
@posts = posts
end
def years
@posts.map { |post| publication_year(post) }.uniq
end
def posts_from_year(year)
@posts.select { |post| publication_year(post) == year }
end
private
attr_reader :posts
def publication_year(post)
post.published_at.year
end
end
end
| true
|
3a8bf80d55200567886bbfe8ca32cea1b2dbe652
|
Ruby
|
Joellehelm/silicon-valley-code-challenge-austin-web-091619
|
/app/models/funding_round.rb
|
UTF-8
| 487
| 2.734375
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
require_relative "venture_capitalist"
require_relative "startup"
class FundingRound
attr_reader :startup, :venture_capitalist, :type, :investment, :all
# attr_accessor :type, :investment
@@all = []
def initialize(startup, vc, type, amount)
if amount.class == Float && amount.positive?
@startup = startup
@venture_capitalist = vc
@type = type
@investment = amount * 1.00
@@all << self
end
end
def self.all
@@all
end
end
| true
|
8fa819e9acd33ec910c23b29b317dcc4f6e15eb6
|
Ruby
|
jeanlazarou/calco
|
/spec/errors_spec.rb
|
UTF-8
| 2,431
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
require 'calco'
RSpec.configure do |c|
c.alias_example_to :detect
end
describe 'Spreadsheet errors' do
detect "variable does not exist" do
expect {
spreadsheet do
sheet do
column value_of(:some_var)
end
end
}.to raise_error("Unknown variable some_var")
end
detect "function using an unknown variable" do
expect {
doc = spreadsheet do
definitions do
function some_var + 1
end
end
}.to raise_error("Unknown function or variable 'some_var'")
end
detect "assiging value to unknown variable" do
doc = spreadsheet do
sheet do
end
end
expect {
doc.save($stdout) do |spreadsheet|
sheet = spreadsheet.current
sheet[:some_var] = 12
end
}.to raise_error("Unknown variable 'some_var'")
end
detect "reference to an unknown function" do
expect {
spreadsheet do
sheet do
column :some_function
end
end
}.to raise_error("Unknown function or variable 'some_function'")
end
detect "using an unknown function" do
expect {
spreadsheet do
definitions do
function name: some_function
end
end
}.to raise_error("Unknown function or variable 'some_function'")
end
detect "declaring a variable twice" do
expect {
spreadsheet do
definitions do
set var: 12
set var: "hello"
end
end
}.to raise_error("Variable 'var' already set")
end
detect "declaring a function twice" do
expect {
spreadsheet do
definitions do
function f: 12
function f: "hello"
end
end
}.to raise_error("Function 'f' already defined")
end
detect "unnamed option for column" do
expect {
spreadsheet do
definitions do
set price: 11
end
sheet do
column :price, 'pp'
end
end
}.to raise_error(ArgumentError, "Options should be a Hash")
end
detect "unknown column id" do
expect {
doc = spreadsheet do
definitions do
set a: 'a'
end
sheet do
column :a
end
end
doc.current.replace_content :no_id, nil
}.to raise_error(RuntimeError, "Column id 'no_id' not found")
end
end
| true
|
1915867bfa2af988df047f51b72f4a476119af22
|
Ruby
|
famished-tiger/Zenlish
|
/spec/zenlish/inflect/inflection_rule_spec.rb
|
UTF-8
| 4,060
| 2.875
| 3
|
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
require_relative '../../../lib/zenlish/wclasses/common_noun'
require_relative '../../../lib/zenlish/lex/lexeme'
require_relative '../../../lib/zenlish/lex/lexical_entry'
require_relative '../../../lib/zenlish/inflect/feature_heading'
require_relative '../../../lib/zenlish/inflect/method_heading'
require_relative '../../../lib/zenlish/inflect/literal_asis'
require_relative '../../../lib/zenlish/inflect/input_asis'
require_relative '../../../lib/zenlish/inflect/equals_literal'
require_relative '../../../lib/zenlish/inflect/formal_argument'
require_relative '../../../lib/zenlish/inflect/matches_pattern'
require_relative '../../../lib/zenlish/inflect/substitution'
# Load the class under test
require_relative '../../../lib/zenlish/inflect/inflection_rule'
module Zenlish
module Inflect
# rubocop: disable Naming/VariableNumber
describe InflectionRule do
# One rule in row representation:
# | plural | ~ /[^aeiouy]y$/ | sub(base_form, /y$/, "ies")|
# Heading part
let(:feature_name) { 'NUMBER' }
let(:heading0) { FeatureHeading.new(feature_name) }
let(:method_name) { 'base_form' }
let(:heading1) { MethodHeading.new(method_name) }
let(:headings) { [heading0, heading1] }
# Condition part
let(:feature_value) { :plural }
let(:arg_0) { FormalArgument.new(0) }
let(:cond_0) { EqualsLiteral.new(arg_0, feature_value) }
let(:arg_1) { FormalArgument.new(1) }
let(:patt) { /[^aeiouy]y$/ }
let(:cond_1) { MatchesPattern.new(arg_1, patt) }
let(:conditions) { [cond_0, cond_1] }
# Consequent part
let(:suffix) { LiteralAsIs.new('ies') }
let(:base) { InputAsIs.new(arg_1) }
let(:pattern) { /y$/ }
let(:consequent) { Substitution.new(base, pattern, suffix) }
subject { InflectionRule.new(conditions, consequent) }
context 'Initialization:' do
it 'should be initialized with condition and consequent parts' do
expect do
InflectionRule.new(conditions, consequent)
end.not_to raise_error
end
it 'should know its condition part' do
expect(subject.conditions).to eq(conditions)
end
it 'should know its consequent part' do
expect(subject.consequent).to eq(consequent)
end
end # context
context 'Provided services:' do
let(:fake_lexeme) { double('dummy-fake_lexeme') }
let(:c_noun) { WClasses::CommonNoun.new }
let(:an_entry) { Lex::LexicalEntry.new('cherry') }
let(:lexeme) { Lex::Lexeme.new(c_noun, an_entry) }
it 'should succeed when all conditions succeed with actuals' do
actuals = [:plural, 'cherry']
expect(subject.success?(headings, fake_lexeme, actuals)).to be_truthy
end
it 'should fail when one condition fails with actuals' do
actuals = [:singular, 'cherry']
expect(subject.success?(headings, fake_lexeme, actuals)).to be_falsy
actuals = [:plural, 'girl']
expect(subject.success?(headings, fake_lexeme, actuals)).to be_falsy
end
it 'should generate inflected form when rule iworks for actuals' do
actuals = [:plural, 'cherry']
expect(subject.apply(headings, fake_lexeme, actuals)).to eq('cherries')
end
it 'should succeed when all conditions succeed for given lexeme' do
expect(subject.success?(headings, lexeme, [])).to be_truthy
end
it 'should fail when one condition fails with given lexeme' do
entry_2 = Lex::LexicalEntry.new('animal')
lex_m2 = Lex::Lexeme.new(c_noun, entry_2)
expect(subject.success?(headings, lex_m2, [])).to be_falsy
end
it 'should generate inflected form when rule works for given lexeme' do
expect(subject.apply(headings, lexeme, [])).to eq('cherries')
end
end # context
end # describe
# rubocop: enable Naming/VariableNumber
end # module
end # module
| true
|
3859ca2b9705a33ddef989c82b3adc4064d63679
|
Ruby
|
mohankapaganti/day3
|
/access_specify.rb
|
UTF-8
| 268
| 3.34375
| 3
|
[] |
no_license
|
class A
#By default initialize method is a private
# public :This is used or comment1 is used
public
def m1
puts "Public method1"
end
def m2
puts "Public method2"
end
public :m1,:m2 #comment 1
end
a1=A.new
a1.m1 #Public method1
a1.m2 #Public method25
| true
|
6cc2950ca6c0dab29ecc7f535bb92fc160afb802
|
Ruby
|
fantasticfears/ffi-icu
|
/spec/transliteration_spec.rb
|
UTF-8
| 1,132
| 2.53125
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
# encoding: utf-8
require "spec_helper"
module ICU
describe Transliteration::Transliterator do
def transliterator_for(*args)
Transliteration::Transliterator.new(*args)
end
[
["Any-Hex", "abcde", "\\u0061\\u0062\\u0063\\u0064\\u0065"],
["Lower", "ABC", "abc"],
["en", "雙屬性集合之空間分群演算法-應用於地理資料", "shuāng shǔ xìng jí hé zhī kōng jiān fēn qún yǎn suàn fǎ-yīng yòng yú de lǐ zī liào"],
["Devanagari-Latin", "दौलत", "daulata"]
].each do |id, input, output|
it "should transliterate #{id}" do
tl = transliterator_for(id)
tl.transliterate(input).should == output
end
end
end # Transliterator
describe Transliteration do
it "should provide a list of available ids" do
ids = ICU::Transliteration.available_ids
ids.should be_kind_of(Array)
ids.should_not be_empty
end
it "should transliterate custom rules" do
ICU::Transliteration.translit("NFD; [:Nonspacing Mark:] Remove; NFC", "âêîôû").should == "aeiou"
end
end # Transliteration
end # ICU
| true
|
3f889bf007315eefbbeb110f4c1aa21f0998e425
|
Ruby
|
ratamabahata/lesson_2
|
/5_year.rb
|
UTF-8
| 606
| 3.71875
| 4
|
[] |
no_license
|
# Ввод данных
puts 'Введите день месяца'
day = gets.chomp.to_i
puts 'Введите число месяца'
month = gets.chomp.to_i
puts 'Введите год'
year = gets.chomp.to_i
days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
days[1] = 29 if (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
number_day = days.take(month - 1).sum + day
puts "Порядковый номер даты - #{number_day}"
#sum = 0
#for i in 0..month-2
# sum += days[i]
#end
#sum += day
#
#puts "Порядковый номер даты: #{sum}"
#=end
| true
|
b109279c586429a1585ef895a73608f845a2b2c5
|
Ruby
|
mespealva/patronesyciclos
|
/patrones.rb
|
UTF-8
| 1,797
| 3.515625
| 4
|
[] |
no_license
|
num = ARGV[0].to_i
def letra_o(n)
print "*" * n
puts
(n-2).times do |i|
(n).times do |j|
if j== 0 || j==(n-1)
print "*"
else
print " "
end
end
puts
end
print "*" * n
puts
end
def letra_i(n)
print "*" * n
puts
(n-2).times do |i|
(n).times do |j|
if j==(n/2)
print "*"
else
print " "
end
end
puts
end
print "*" * n
puts
end
def letra_z(n)
print "*" * n
puts
(n-2).times do |i|
(n).times do |j|
if j==(n-i)-2
print '*'
else
print ' '
end
end
puts
end
print "*" * n
puts
end
def letra_x(n)
(n).times do |i|
(n).times do |j|
if i==(j) || j==(n-i)-1
print '*'
else
print ' '
end
end
puts
end
end
#
def numero_cero(n)
print "*" * n
puts
(n-2).times do |i|
(n).times do |j|
if j==(0) || j==(i+1) || j==(n-1)
print "*"
else
print " "
end
end
puts
end
print "*" * n
puts
end
def navidad(n)
n.times do |i|
n.times do |j|
if j==(n/2) || j==(n/2-i) || j==(n/2+i)
print '*'
else
print ' '
end
end
puts
end
n.times do |h|
if h!=(n-1) || h!=(n+1)
print '*'
else
print ' '
end
end
end
letra_o(num)
puts
letra_i(num)
puts
letra_z(num)
puts
letra_x(num)
puts
numero_cero(num)
puts
navidad(num)
puts
| true
|
da0f1abe484e66152bd901d80e32bb5c94ff9fc0
|
Ruby
|
justindell/ProjectEuler
|
/ruby/src/problem7.rb
|
UTF-8
| 68
| 2.875
| 3
|
[] |
no_license
|
require 'mathn.rb'
puts "10001st Prime: #{Prime.take(10001).last}"
| true
|
051658d436f548c6765e39581b791f4ac28828e7
|
Ruby
|
JakeH91/Career-Foundry
|
/practice/program.rb
|
UTF-8
| 96
| 3.703125
| 4
|
[] |
no_license
|
def greeting
puts "Please enter your name"
name = gets.chomp
puts "Hey " + name
end
greeting
| true
|
38c506d2e2c3a23b68baa75a4249047578c8ad13
|
Ruby
|
cougarsyankeesfan/ltp
|
/DaManT_12.rb
|
UTF-8
| 137
| 3.4375
| 3
|
[] |
no_license
|
# get the character at the number within the [>>>] method
da_man = 'Mr. T'
big_T = da_man[4]
puts big_T
big_T = da_man[1]
puts big_T
| true
|
13b72a9a00f2379842c3264808ef1039e22c69dc
|
Ruby
|
amanelis/bulldozer
|
/document_titles.rb
|
UTF-8
| 2,683
| 2.734375
| 3
|
[] |
no_license
|
require 'rubygems'
require 'thread'
require 'json'
require 'uri'
require 'open-uri'
require 'nokogiri'
require 'mechanize'
require 'net/http'
require 'active_record'
require 'rails/all'
require File.expand_path(File.dirname(__FILE__) + '/models/document')
require File.expand_path(File.dirname(__FILE__) + '/models/professor')
require File.expand_path(File.dirname(__FILE__) + '/models/state')
require File.expand_path(File.dirname(__FILE__) + '/models/result')
require File.expand_path(File.dirname(__FILE__) + '/models/university')
ActiveRecord::Base.establish_connection(
:adapter => "mysql",
:host => "localhost",
:username => "root",
:password => "",
:database => "fratfolder_development",
:pool => 75
)
# Store our threads
threads = []
# Queue to store the docs
q = Queue.new
# Keep track of success failure
count = 0
errors = 0
success = 0
# Grab the documents based on no title
documents = Document.all
documents.collect { |d| q << d }
# Number of threads
25.times do
threads << Thread.new(q) { |q|
until q.empty?
doc = q.pop
begin
url = doc.url
page = Nokogiri::HTML(open(url))
rescue Exception
puts "[ERROR] Could not open the URL"
errors += 1
next
end
begin
# Grab the css element
page_title = page.css('.content_header_full').first
page_category = page.css('tr:nth-child(4) a').first
page_date = page.css('tr:nth-child(6) td:nth-child(2)').first
page_description = page.css('.koofer_sample_text').first
title = page_title.nil? ? '' : page_title.content
category = page_category.nil? ? '' : page_category.content
date = page_date.nil? ? '' : page_date.content
description = page_description.nil? ? '' : page_description.content
rescue NoMethodError
puts "[ERROR] NoMethodError for page_text.content on doc: #{doc.id} for #{url}"
errors += 1
next
end
# Now save the attribute
doc.update_attributes!(:title => title, :category => page_category, :term => date, :description => description)
puts "[SUCCESS][#{count}] Updated title on document: #{doc.id} with title: #{doc.title}"
success += 1
count += 1
end
}
end
# Join these hoes
threads.each { |t| t.join }
puts "[FINISHED] Process completed. Errors: #{errors}, and Success: #{success}--------------------------------------------------"
| true
|
4db433dcd290c6e5505f635e487a18f07ed09ed1
|
Ruby
|
blackmagic42/ruby-thp
|
/exo_16.rb
|
UTF-8
| 102
| 3.28125
| 3
|
[] |
no_license
|
puts"combien d'étages veux tu?"
etages=gets.to_i
for n in 0..etages
puts" "*(etages-n) +"#"*n
end
| true
|
c83035ad06454ec2f846503746ccb925c8dac713
|
Ruby
|
gditrick/tpl
|
/helpers/integer.rb
|
UTF-8
| 370
| 3.25
| 3
|
[] |
no_license
|
class Integer
def second
self
end
alias :seconds :second
def minute
60.seconds*self
end
alias :minutes :minute
def hour
60.minutes*self
end
alias :hours :hour
def day
24.hours*self
end
alias :days :day
def week
7.days*self
end
alias :weeks :week
def ago
Time.now - self
end
end
| true
|
0ea198c553620d720bad531ae643c7db5efd85e4
|
Ruby
|
nikhiljagtap/puppet
|
/lib/puppet/util/http_proxy.rb
|
UTF-8
| 5,951
| 2.71875
| 3
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
require 'uri'
require 'puppet/ssl/openssl_loader'
require 'puppet/http'
module Puppet::Util::HttpProxy
def self.proxy(uri)
if http_proxy_host && !no_proxy?(uri)
Net::HTTP.new(uri.host, uri.port, self.http_proxy_host, self.http_proxy_port, self.http_proxy_user, self.http_proxy_password)
else
http = Net::HTTP.new(uri.host, uri.port, nil, nil, nil, nil)
# Net::HTTP defaults the proxy port even though we said not to
# use one. Set it to nil so caller is not surprised
http.proxy_port = nil
http
end
end
def self.http_proxy_env
# Returns a URI object if proxy is set, or nil
proxy_env = ENV["http_proxy"] || ENV["HTTP_PROXY"]
begin
return URI.parse(proxy_env) if proxy_env
rescue URI::InvalidURIError
return nil
end
return nil
end
# The documentation around the format of the no_proxy variable seems
# inconsistent. Some suggests the use of the * as a way of matching any
# hosts under a domain, e.g.:
# *.example.com
# Other documentation suggests that just a leading '.' indicates a domain
# level exclusion, e.g.:
# .example.com
# We'll accommodate both here.
def self.no_proxy?(dest)
no_proxy = self.no_proxy
unless no_proxy
return false
end
unless dest.is_a? URI
begin
dest = URI.parse(dest)
rescue URI::InvalidURIError
return false
end
end
no_proxy.split(/\s*,\s*/).each do |d|
host, port = d.split(':')
host = Regexp.escape(host).gsub('\*', '.*')
#If this no_proxy entry specifies a port, we want to match it against
#the destination port. Otherwise just match hosts.
if port
no_proxy_regex = %r(#{host}:#{port}$)
dest_string = "#{dest.host}:#{dest.port}"
else
no_proxy_regex = %r(#{host}$)
dest_string = "#{dest.host}"
end
if no_proxy_regex.match(dest_string)
return true
end
end
return false
end
def self.http_proxy_host
env = self.http_proxy_env
if env and env.host
return env.host
end
if Puppet.settings[:http_proxy_host] == 'none'
return nil
end
return Puppet.settings[:http_proxy_host]
end
def self.http_proxy_port
env = self.http_proxy_env
if env and env.port
return env.port
end
return Puppet.settings[:http_proxy_port]
end
def self.http_proxy_user
env = self.http_proxy_env
if env and env.user
return env.user
end
if Puppet.settings[:http_proxy_user] == 'none'
return nil
end
return Puppet.settings[:http_proxy_user]
end
def self.http_proxy_password
env = self.http_proxy_env
if env and env.password
return env.password
end
if Puppet.settings[:http_proxy_user] == 'none' or Puppet.settings[:http_proxy_password] == 'none'
return nil
end
return Puppet.settings[:http_proxy_password]
end
def self.no_proxy
no_proxy_env = ENV["no_proxy"] || ENV["NO_PROXY"]
if no_proxy_env
return no_proxy_env
end
if Puppet.settings[:no_proxy] == 'none'
return nil
end
return Puppet.settings[:no_proxy]
end
# Return a Net::HTTP::Proxy object.
#
# This method optionally configures SSL correctly if the URI scheme is
# 'https', including setting up the root certificate store so remote server
# SSL certificates can be validated.
#
# @param [URI] uri The URI that is to be accessed.
# @return [Net::HTTP::Proxy] object constructed tailored for the passed URI
def self.get_http_object(uri)
proxy = proxy(uri)
if uri.scheme == 'https'
cert_store = OpenSSL::X509::Store.new
cert_store.set_default_paths
proxy.use_ssl = true
proxy.verify_mode = OpenSSL::SSL::VERIFY_PEER
proxy.cert_store = cert_store
end
if Puppet[:http_debug]
proxy.set_debug_output($stderr)
end
proxy.open_timeout = Puppet[:http_connect_timeout]
proxy.read_timeout = Puppet[:http_read_timeout]
proxy
end
# Retrieve a document through HTTP(s), following redirects if necessary. The
# returned response body may be compressed, and it is the caller's
# responsibility to decompress it based on the 'content-encoding' header.
#
# Based on the the client implementation in the HTTP pool.
#
# @see Puppet::Network::HTTP::Connection#request_with_redirects
#
# @param [URI] uri The address of the resource to retrieve.
# @param [symbol] method The name of the Net::HTTP method to use, typically :get, :head, :post etc.
# @param [FixNum] redirect_limit The number of redirections that can be followed.
# @return [Net::HTTPResponse] a response object
def self.request_with_redirects(uri, method, redirect_limit = 10, &block)
current_uri = uri
response = nil
0.upto(redirect_limit) do |redirection|
proxy = get_http_object(current_uri)
headers = { 'Accept' => '*/*', 'User-Agent' => Puppet[:http_user_agent] }
if Puppet.features.zlib?
headers["Accept-Encoding"] = Puppet::HTTP::ACCEPT_ENCODING
end
response = proxy.send(:head, current_uri, headers)
Puppet.debug("HTTP HEAD request to #{current_uri} returned #{response.code} #{response.message}")
if [301, 302, 307].include?(response.code.to_i)
# handle the redirection
current_uri = URI.parse(response['location'])
next
end
if method != :head
if block_given?
response = proxy.send("request_#{method}".to_sym, current_uri, headers, &block)
else
response = proxy.send(method, current_uri, headers)
end
Puppet.debug("HTTP #{method.to_s.upcase} request to #{current_uri} returned #{response.code} #{response.message}")
end
return response
end
raise RedirectionLimitExceededException, _("Too many HTTP redirections for %{uri}") % { uri: uri }
end
end
| true
|
88c7327b08a32de49ada0ac496a948505f06dc5f
|
Ruby
|
lynrco/lynr.co
|
/lib/lynr/controller/component/authentication.rb
|
UTF-8
| 1,179
| 2.5625
| 3
|
[] |
no_license
|
require './lib/lynr/controller'
module Lynr::Controller
# # `Lynr::Controller::Authentication`
#
# Provide methods to determine the state of authentication, whether or
# not a valid user exists. This helps decouple authentication from
# authorization.
#
module Authentication
# ## `Authentication#authenticated?(req)`
#
# Determine if there is an autheniticated user attached to `req`.
# This check is done by assessing the 'dealer_id' property of the
# session attached to `req`.
#
def authenticated?(req)
!req.session['dealer_id'].nil?
end
# ## `Authentication#authenticates?(email, password)`
#
# Check if `email` and `password` successfully authenticate against
# the identity determined by `email.
#
def authenticates?(email, password)
account = dealer_dao.get_by_email(email)
!account.nil? && !account.identity.nil? && account.identity.auth?(email, password)
end
# ## `Authentication#account_exists?(email)`
#
# Check if there is an identity associated with `email`.
#
def account_exists?(email)
dealer_dao.account_exists?(email)
end
end
end
| true
|
4a66c875b8f9b16307a979b0a216eedf0361e846
|
Ruby
|
ortizjs/algorithms_
|
/LeetcodeQuestions/beautiful_arrangements_ii-667.rb
|
UTF-8
| 708
| 3.296875
| 3
|
[] |
no_license
|
# @param {Integer} n
# @param {Integer} k
# @return {Integer[]}
def construct_array(n, k)
res = Array(n)
idx = 0
min = 1
max = n
is_max = false
res[idx] = min
idx += 1
min += 1
while k > 1
res[idx] = max
idx += 1
max -= 1
is_max = true
k -= 1
if k > 1
res[idx] = min
idx += 1
min += 1
k -= 1
is_max = false
end
end
while idx < n
if is_max
res[idx] = max
idx += 1
max -= 1
else
res[idx] = min
idx += 1
min += 1
end
end
res
end
| true
|
6a040d46fec84f3ccaa509d3adc35e656b9d6d01
|
Ruby
|
Demeco/nor_robo_01
|
/analyzer.rb
|
UTF-8
| 1,478
| 3.28125
| 3
|
[] |
no_license
|
# coding: utf-8
#= 解析クラス
=begin
文章を解析する働きを持つ
解析結果オブジェクト Sampleを返す
Sampleもここで一緒に定義する
=end
#require 'mecab'
require 'natto'
require_relative 'dictionary.rb'
#== 基底クラス
class Analyzer
def initialize(name,dictionaries)
@name = name
end
def analyze(input)
return ''
end
def name
return @name
end
end
#== 単語の基本形を学習してくる
class MecabAnalyzer < Analyzer
def initialize(name,dictionaries)
super
@natto = Natto::MeCab.new
@dictionaries = dictionaries
end
def save()
@dictionaries.each do |dic|
dic.save()
end
end
def analyze(input)
#学習
@natto.parse(input) do |n|
features = n.feature.split(",")
if /名詞|動詞|副詞|形容詞/ =~ features[0]#辞書に放り込むタイプの単語なら原型を放り込む
case features[0]
when '名詞' then
@dictionaries[1].add_word(features[6]) if features[6] != "*"
when '動詞' then
@dictionaries[2].add_word(features[6])
when '副詞' then
@dictionaries[3].add_word(features[6])
when '形容詞' then
@dictionaries[4].add_word(features[6])
end
end
end
end
end
#== Sampleクラス
=begin
解析結果のオブジェクト
変数を色々持っていると言うだけのしろもの
=end
class Sample
end
| true
|
d0c1b98b901061e36d8aa1baad082eebea1d3f0e
|
Ruby
|
christophertoy/TwO-O-Player-Math-Game
|
/main.rb
|
UTF-8
| 722
| 3.921875
| 4
|
[] |
no_license
|
require "./players"
require "./questions"
p1 = Players.new("Player 1")
p2 = Players.new("Player 2")
def turn(player)
question = Questions.new()
puts "#{player.name}: #{question.ask}"
answer1 = gets.chomp.to_i
if answer1 == question.answer
puts "YES! You are correct"
else
puts "Seriously? No!"
player.remove_life
end
end
loop do
puts "----- NEW TURN -----"
turn(p1)
if p1.game_over
puts "Player 2 wins with a score of #{p2.life}/3"
break
end
puts "P1: #{p1.life}/3 vs P2: #{p2.life}/3"
puts "----- NEW TURN -----"
turn(p2)
if p2.game_over
puts "Player 1 wins with a score of #{p1.life}/3"
break
end
puts "P1: #{p1.life}/3 vs P2: #{p2.life}/3"
end
puts "----- GAME OVER -----"
puts "Good bye!"
| true
|
43d04b2970a5f94a8042d58d3b12d0e39f1e2861
|
Ruby
|
konovalov-nk/ERA
|
/lib/ERA/arrays/repeat_and_missing_number_array.rb
|
UTF-8
| 1,195
| 3.796875
| 4
|
[
"MIT"
] |
permissive
|
module ERA
module Arrays
# Original URL: https://www.interviewbit.com/problems/repeat-and-missing-number-array/
#
# You are given a read only array of n integers from 1 to n.
# Each integer appears exactly once except A which appears twice and B which
# is missing.
# Return A and B.
#
# Note: Your algorithm should have a linear runtime complexity.
# Could you implement it without using extra memory?
# Note that in your output A should precede B.
#
# For example:
# Input: [3 1 2 5 3]
# Output: [3, 4]
# A = 3, B = 4
#
# Tags: math
# Time Complexity: O(n)
# Space Complexity: O(1)
class RepeatAndMissingNumberArray
# @param array : constant array of integers
# @return an integer
def solution(array)
return -1 unless array.is_a? Array
return [0, 0] unless array.size > 1
n = array.size
arithmetic = (n + 1) * n / 2
quadratic = (n + 1) * (2 * n + 1) * n / 6
x, y = array.reduce([arithmetic, quadratic]) do |(x, y), el|
[x - el, y - el**2]
end
[(y / x - x) / 2, (y / x + x) / 2]
end
end
end
end
| true
|
31b896a1602f49841b76921924236bbd1e1931b9
|
Ruby
|
moonlighters/webobots
|
/spec/lib/emulation_system/emulation/vector_spec.rb
|
UTF-8
| 2,144
| 3.265625
| 3
|
[] |
no_license
|
require 'emulation_system_helper'
describe EmulationSystem::Emulation::Vector do
before do
@v = Vector.new 2, 3
end
it "should be creatable" do
@v.x.should == 2
@v.y.should == 3
end
describe ".[]" do
it "should act as .new" do
u = Vector[@v.x, @v.y]
u.x.should == @v.x
u.y.should == @v.y
end
end
describe "#+" do
it "should add vectors" do
u = @v + Vector.new(-0.5, +0.5)
u.x.should == @v.x - 0.5
u.y.should == @v.y + 0.5
end
it "should add to vector" do
u = Vector.new 5, 15
u += @v
u.x.should == 5 + @v.x
u.y.should == 15 + @v.y
end
end
describe "#-" do
it "should substract vectors" do
u = @v - Vector.new(100, -50)
u.x.should == @v.x - 100
u.y.should == @v.y + 50
end
it "should substract from vector" do
u = Vector.new -11, -11.1
u -= @v
u.x.should == -11 - @v.x
u.y.should == -11.1 - @v.y
end
end
describe "unary minus" do
it "should negate vector" do
u = -@v
u.x.should == -@v.x
u.y.should == -@v.y
end
end
describe "#*" do
it "should multiply vector by a scalar" do
u = @v*1.5
u.x.should == 1.5*@v.x
u.y.should == 1.5*@v.y
end
end
describe "#/" do
it "should divide vector by a scalar" do
u = @v/1.5
u.x.should == @v.x/1.5
u.y.should == @v.y/1.5
end
end
describe "#abs" do
it "should return vector norm" do
Vector.new(3,4).abs.should == 5
end
end
describe "#near?" do
it "should return true if vectors are equal" do
@v.should be_near_to @v, 0
@v.should be_near_to @v, 1
end
it "should return true if distance between points represented by vectors is less than or equals to radius" do
u = @v + Vector[3,4]
@v.should be_near_to u, 5
u.should be_near_to @v, 5
end
it "should return true if distance between points represented by vectors is less than or equals to radius" do
u = @v + Vector[3,4]
@v.should_not be_near_to u, 3
u.should_not be_near_to @v, 3
end
end
end
| true
|
22780414545706091b3a6efcb957a8ec41dac064
|
Ruby
|
softilluminationsdipak/shw
|
/lib/i_contact_response.rb
|
UTF-8
| 1,053
| 2.859375
| 3
|
[] |
no_license
|
require 'rexml/document'
class IContactResponse
attr_reader :xml, :error_code, :error_message
def initialize(body)
@xml = REXML::Document.new(body)
unless self.successful?
@error_code = xml.root.elements['error_code'].text.to_i
@error_message = xml.root.elements['error_message'].text
end
end
def self.failure
IContactResponse.new('<?xml version="1.0" encoding="UTF-8"?><response status="failed"><error_code>-1</error_code><error_message>General Failure</error_message></response>')
end
def self.limit
IContactResponse.new('<?xml version="1.0" encoding="UTF-8"?><response status="limit"><error_code>-2</error_code><error_message>Reached 60 requests per minute limit</error_message></response>')
end
def successful?
@xml.root.attributes['status'] == 'success'
end
def limit?
@xml.root.attributes['status'] == 'limit'
end
def to_s
o = self.successful? ? "" : "Request was unsuccessful: (#{@error_code}) #{@error_message}\n"
@xml.write(o, 1)
return o
end
end
| true
|
94920a34e54a041e10b385ef7d5ed4f1f07b2e2c
|
Ruby
|
colehart/HTTP
|
/lib/server.rb
|
UTF-8
| 1,053
| 3.1875
| 3
|
[] |
no_license
|
require 'socket'
class Server
def initialize(port)
@tcp_server = TCPServer.new(port)
end
def run
loop do
intro
path = gets.chomp
connection = @tcp_server.accept
request_lines = populate_lines(connection)
respond(path, request_lines, connection)
connection.close
exit while path == "/shutdown"
end
connection.shutdown(:WR)
end
def intro
puts """
Please choose a path:
/, /hello, /datetime, or /shutdown
"""
print ">>"
end
def populate_lines(connection)
line = connection.gets.chomp
request_lines = []
request_lines << line
until line.empty?
line = connection.gets.chomp
request_lines << line
end
request_lines
end
def respond(path, request_lines, connection)
responder = Responder.new(request_lines)
responder.determine_response(path)
connection.puts responder.print_header
connection.puts responder.print_output(path)
responder.count_hello if path == "/hello"
responder.count_total
end
end
| true
|
a29f5dff21b5526f8ce8a41d6f691f8d56f134e0
|
Ruby
|
codequest-eu/polish_number
|
/lib/polish_number/classify_numbers.rb
|
UTF-8
| 409
| 3.53125
| 4
|
[
"GPL-2.0-only",
"MIT"
] |
permissive
|
module PolishNumber
class ClassifyNumbers
def initialize(value, digits)
@value = value.to_i
@digits = digits
end
def self.call(value, digits)
new(value, digits).call
end
def call
return :one if @value == 1
return :few if @digits && (2..4).cover?(@digits[-1]) && @digits[-2] != 1
:many
end
end # class ClassifyNumbers
end # module PolishNumber
| true
|
9c406d33e3a67f546af948f421c89c42853e8bb1
|
Ruby
|
kidooom/ruby_traning
|
/highline_test.rb
|
UTF-8
| 552
| 3.21875
| 3
|
[] |
no_license
|
require 'highline/import'
username = ask("Enter user: ") { |q| q.echo = true }
password = ask("Enter password: ") { |q| q.echo = false }
ask("retry number?: ", Integer) { |q| q.in = 0..10 }
interests = ask("Interests? (comma sep list) ", lambda { |str| str.split(/,\s*/) })
p interests
say("This should be <%= color('bold', BOLD) %>!")
choose do |menu|
menu.prompt = "Please choose your favorite programming language? "
menu.choice(:ruby) { say("Good choice!") }
menu.choices(:python, :perl) { say("Not from around here, are you?") }
end
| true
|
acf83c787a51d3057a1d346245bde29c23ef8d92
|
Ruby
|
zhiqiang-yu/RHOSP-deploy
|
/usr/share/foreman/extras/rdoc/rdoc_prepare_script.rb
|
UTF-8
| 1,963
| 2.75
| 3
|
[] |
no_license
|
#!/usr/bin/ruby193-ruby
verbose = false
require 'fileutils'
# Takes a list of directories and copies them, ignoring version control directories, to a new location
# It then sanitizes them by removing any circular symlinks
# It must return the new root directory for the tree
modules_root = "/tmp/puppet"
FileUtils.mkpath modules_root unless File.exist? modules_root
FileUtils.rm_rf Dir.glob("#{modules_root}/*")
FileUtils.chdir "/"
dirs = ARGV[0..100]
# We need to copy in the checked out puppet modules tree. Skipping all the .svn entries.
modules = "/etc/puppet/modules"
exit -1 unless system "tar --create --file - --exclude-vcs #{modules[1..-1]} | tar --extract --file - --read-full-records --directory #{modules_root}"
# This copies in the /etc/puppent/env directory symlink trees
exit -1 unless system "tar --create --file - --exclude-vcs #{dirs.map{|d| d[1..-1]}.join(" ")} | tar --extract --file - --read-full-records --directory #{modules_root}"
for dir in dirs
here = modules_root + dir
# Scan each modulepath for symlinks and remove them if they point at ".".
# If they are absolute, recreate them pointing at the copied tree location
Dir.foreach(here) do |entry|
linkfile = here + "/" + entry
next unless File.ftype(linkfile) == "link"
target = File.readlink(linkfile)
File.unlink(linkfile) if target == "."
if target=~/^\//
File.unlink(linkfile)
File.symlink modules_root + target, linkfile
end
end
end
# Look through the resulting tree and remove broken and cyclic links
links = `find #{modules_root} -type l`
for link in links
link.chomp!
# Remove links pointing to missing files
unless File.exist?(File.readlink(link))
File.unlink(link)
next
end
# Remove links pointing to "."
if File.readlink(link) =~ /\.|\,\//
File.unlink(link)
puts "Removing #{link}" if verbose
else
puts "link #{link} points to #{File.readlink(link)}" if verbose
end
end
puts modules_root
| true
|
722a4e1ef995f63e96b2e1c84046e54cfe0fc6ae
|
Ruby
|
ozwtkm/rails_rubyquest
|
/app/models/session.rb
|
UTF-8
| 2,442
| 2.859375
| 3
|
[] |
no_license
|
# 他のmodelとは異なり、
# SQL操作しないし実態が異なるが、
# コントローラからsessionへの操作インターフェースがmodelと類似するため、sessionhelperではなくmodelとして実装。
class Session
@@cache = nil
attr_accessor :id, :variables, :is_logined
def self.get(sessionid=nil)
if sessionid.nil?
session = Session.new()
else
cache = Session.cache_client()
session_key = "XXX_rubyquest_session:" + sessionid
begin
session_variables = Marshal.load(cache.get(session_key))
if session_variables[:user_id].nil?
tmp_session = Session.new(sessionid, session_variables, is_logined: false)
else
tmp_session = Session.new(sessionid, session_variables, is_logined: true)
end
rescue
tmp_session = Session.new() #sessionが無いとbeginの1行目でエラーになる
end
session = tmp_session
end
session
end
# 擬似シングルトン。そのうち専用クラスつくる
def self.cache_client()
@@cache ||= Redis.new(:host => "localhost", :port => 6379)
@@cache
end
def is_logined?()
@is_logined
end
# restartも包含してる
def start()
logout()
@id = generate_session_id()
save()
end
# 意味論的にも実装問題的にもset-cookieはcontrollerで。
def login(user_id)
@id = generate_session_id()
@variables[:user_id] = user_id
@is_logined = true
save()
end
def logout()
unless @id.nil?
session_key = "XXX_rubyquest_session:" + @id
cache = Session.cache_client()
cache.del(session_key)
@id = nil
end
@variables = {}
@is_logined = false
end
private
def initialize(sessionid=nil, variables={}, is_logined: false)
@id = sessionid #cookieの値のことね。
@variables = variables
@is_logined = is_logined
end
def save()
cache = Session.cache_client()
session_key = "XXX_rubyquest_session:" + @id
cache.set(session_key, Marshal.dump(@variables))
end
def generate_session_id()
SecureRandom.hex(50)
end
end
| true
|
af47afcd24cabf9d65f3943ba68e508e7549f89e
|
Ruby
|
luikore/property-list
|
/lib/property-list/ascii_parser.rb
|
UTF-8
| 5,120
| 2.859375
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
module PropertyList
# Parse ASCII plist into a Ruby object
def self.load_ascii text
AsciiParser.new(text).parse
end
class AsciiParser #:nodoc:
def initialize src
@lexer = StringScanner.new src.strip
end
def parse
res = parse_object
skip_space_and_comment
if !@lexer.eos? or res.nil?
syntax_error "Unrecognized token"
end
res
end
def skip_space_and_comment
@lexer.skip(%r{(?:
[\x0A\x0D\u2028\u2029\x09\x0B\x0C\x20]+ # newline and space
|
//[^\x0A\x0D\u2028\u2029]* # one-line comment
|
/\*(?:.*?)\*/ # multi-line comment
)+}mx)
end
def parse_object
skip_space_and_comment
case @lexer.peek(1)
when '{'
parse_dict
when '('
parse_array
when '"'
parse_string '"'
when "'"
parse_string "'" # NOTE: not in GNU extension
when '<'
parse_extension_value
when /[\w\.\/]/
parse_unquoted_string
end
end
def parse_dict
@lexer.pos += 1
hash = {}
while (skip_space_and_comment; @lexer.peek(1) != '}')
k = \
case @lexer.peek(1)
when '"'
parse_string '"'
when "'"
parse_string "'"
when /\w/
parse_unquoted_string
end
if !k
syntax_error "Expect dictionary key"
end
skip_space_and_comment
if !@lexer.scan(/=/)
syntax_error "Expect '=' after dictionary key"
end
skip_space_and_comment
v = parse_object
if v.nil?
syntax_error "Expect dictionary value"
end
skip_space_and_comment
if !@lexer.scan(/;/)
syntax_error "Expect ';' after dictionary value"
end
skip_space_and_comment
hash[k] = v
end
if @lexer.getch != '}'
syntax_error "Unclosed hash"
end
hash
end
def parse_array
@lexer.pos += 1
array = []
while (skip_space_and_comment; @lexer.peek(1) != ')')
obj = parse_object
if obj.nil?
syntax_error "Failed to parse array element"
end
array << obj
skip_space_and_comment
@lexer.scan(/,/)
end
if @lexer.getch != ')'
syntax_error "Unclosed array"
end
array
end
def parse_string delim
@lexer.pos += 1
# TODO (TextMate only, xcode cannot parse it) when delim is ', '' is the escape
chars = []
while (ch = @lexer.getch) != delim
case ch
when '\\'
case @lexer.getch
when '\\'
chars << '\\'
when '"'
chars << '"'
when "'"
chars << "'"
when 'b'
chars << "\b"
when 'n'
chars << "\n"
when 'r'
chars << "\r"
when 't'
chars << "\t"
when 'U', 'u'
if (hex = @lexer.scan /[0-9a-h]{4}/i)
chars << [hex.to_i(16)].pack('U')
else
syntax_error "Expect 4 digit hex code"
end
when /(\d)/
oct_init = $1
if (oct = @lexer.scan /[0-7]{2}/)
chars << [(oct_init + oct).to_i(8)].pack('U')
else
syntax_error "Expect 3 digit oct code"
end
else
syntax_error "Bad escape"
end
else
chars << ch
end
end
chars.join
end
def parse_unquoted_string
@lexer.scan /[\w\.\/]+/
end
def parse_extension_value
@lexer.pos += 1
case @lexer.peek(2)
when '*D' # date
@lexer.pos += 2
if (d = @lexer.scan /\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} [+\-]\d{4}\>/)
Date.strptime d.chop, "%Y-%m-%d %H:%M:%S %z"
else
syntax_error "Expect date value"
end
when '*I' # integer
@lexer.pos += 2
if (i = @lexer.scan /[\+\-]?\d+\>/)
i.chop.to_i
else
syntax_error "Expect integer value"
end
when '*R' # real
@lexer.pos += 2
if (r = @lexer.scan /[\+\-]?\d+(\.\d+)?([eE][\+\-]?\d+)?\>/)
r.chop.to_f
else
syntax_error "Expect real value"
end
when '*B' # boolean
@lexer.pos += 2
case @lexer.scan(/[YN]\>/)
when 'Y>'
true
when 'N>'
false
else
syntax_error "Expect boolean value"
end
else
parse_data
end
end
def parse_data
if (h = @lexer.scan /[0-9a-f\s]*\>/i)
h = h.gsub /[\s\>]/, ''
data = [h].pack 'H*'
StringIO.new data
else
syntax_error "Expect hex value"
end
end
def syntax_error msg
pre = @lexer.string[0...@lexer.pos]
line = pre.count("\n") + 1
col = pre.size - (pre.rindex("\n") || -1)
raise SyntaxError, msg + " at line: #{line} col: #{col} #{@lexer.inspect}", caller
end
end
end
| true
|
f98db9ee1109861192f67d4a2551446b964d3e8a
|
Ruby
|
bird1204/codeSignal
|
/interview/Common Techniques/adv_count_inversions.rb
|
UTF-8
| 1,176
| 3.703125
| 4
|
[] |
no_license
|
# The inversion count for an array indicates how far the array is from being sorted. If the array is already sorted, then the inversion count is 0. If the array is sorted in reverse order, then the inversion count is the maximum possible value.
# Given an array a, find its inversion count. Since this number could be quite large, take it modulo 109 + 7.
# Example
# For a = [3, 1, 5, 6, 4], the output should be countInversions(a) = 3.
# The three inversions in this case are: (3, 1), (5, 4), (6, 4).
#O(n log n) using merge_sort
def countInversions(a)
def merge arr,*new
return [0,arr] if arr.size == 1
inv_merge = i = j = 0
inv_left, left = merge(arr[0...mid = arr.size / 2])
inv_right, right = merge(arr[mid..-1])
while i < mid && j < right.size
if right[j] < left[i]
inv_merge += mid - i
new << right[j]
j += 1
else
new << left[i]
i += 1
end
end
[inv_left + inv_merge + inv_right, new + (i < mid ? left[i..-1] : right[j..-1]) ]
end
merge(a)[0] % (10 ** 9 + 7)
end
| true
|
406999d05545f890e401abaa00549ceb8f0d1726
|
Ruby
|
OpenRubyRMK/game-engine
|
/data/scripts/new_rpg_data/enemy_ability.rb
|
UTF-8
| 683
| 2.65625
| 3
|
[] |
no_license
|
require_relative "battler_ability"
require_relative "enemy"
module RPG
class Enemy
attr_accessor :abilities
private
def abilities_cs_init
@abilities = {}
end
def abilities_cs_to_xml(xml)
xml.abilities{
@abilities.each{|k,l| xml.ability(:name=>k,:level=>l) }
}
end
def abilities_cs_parse(enemy)
enemy.xpath("abilities/ability").each {|node|
@abilities[node[:name].to_sym]=node[:level].to_i
Ability.parse_xml(node) unless node.children.empty?
}
end
end
end
module Game
class Enemy
private
def enemy_abilities_cs_init_after
rpg.abilities.each do |k,l|
temp=add_ability(k)
l.times {temp.levelup}
end
end
end
end
| true
|
4b55b5640a15c816e6ea7ff349f03b01b69979cc
|
Ruby
|
antoniofogaca/rails
|
/modulo/metodos/app.rb
|
UTF-8
| 243
| 2.859375
| 3
|
[] |
no_license
|
require_relative 'pagamento'
include Pagamento
puts "Digite a bandeira do cartão"
b = gets.chomp
puts "Digite o número do cartão"
c = gets.chomp
puts "Informe o valor"
v = gets.chomp
puts pagar(b, c, v)
puts Pagamento::pagar(b, c, v)
| true
|
254ed3e61a587080868c66b67d0f2ef7f7eac5b2
|
Ruby
|
kathryn0908/programming-univbasics-nds-green-grocer-denver-web-033020
|
/grocer.rb
|
UTF-8
| 2,305
| 3.8125
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
# Constants help us "name" special numbers
CLEARANCE_ITEM_DISCOUNT_RATE = 0.20
BIG_PURCHASE_DISCOUNT_RATE = 0.10
def find_item_by_name_in_collection(name, collection)
i = 0
while i < collection.length do
return collection[i] if name === collection[i][:item]
i += 1
end
nil
end
def consolidate_cart(cart)
i = 0
result = []
while i < cart.count do
item_name = cart[i][:item]
sought_item = find_item_by_name_in_collection(item_name, result)
if sought_item
sought_item[:count] += 1
else
cart[i][:count] = 1
result << cart[i]
end
i += 1
end
result
end
# Don't forget, you can make methods to make your life easy!
def mk_coupon_hash(c)
rounded_unit_price = (c[:cost].to_f * 1.0 / c[:num]).round(2)
{
:item => "#{c[:item]} W/COUPON",
:price => rounded_unit_price,
:count => c[:num]
}
end
# A nice "First Order" method to use in apply_coupons
def apply_coupon_to_cart(matching_item, coupon, cart)
matching_item[:count] -= coupon[:num]
item_with_coupon = mk_coupon_hash(coupon)
item_with_coupon[:clearance] = matching_item[:clearance]
cart << item_with_coupon
end
def apply_coupons(cart, coupons)
i = 0
while i < coupons.count do
coupon = coupons[i]
item_with_coupon = find_item_by_name_in_collection(coupon[:item], cart)
item_is_in_basket = !!item_with_coupon
count_is_big_enough_to_apply = item_is_in_basket && item_with_coupon[:count] >= coupon[:num]
if item_is_in_basket and count_is_big_enough_to_apply
apply_coupon_to_cart(item_with_coupon, coupon, cart)
end
i += 1
end
cart
end
def apply_clearance(cart)
i = 0
while i < cart.length do
item = cart[i]
if item[:clearance]
discounted_price = ((1 - CLEARANCE_ITEM_DISCOUNT_RATE) * item[:price]).round(2)
item[:price] = discounted_price
end
i += 1
end
cart
end
def checkout(cart, coupons)
total = 0
i = 0
ccart = consolidate_cart(cart)
apply_coupons(ccart, coupons)
apply_clearance(ccart)
while i < ccart.length do
total += items_total_cost(ccart[i])
i += 1
end
total >= 100 ? total * (1.0 - BIG_PURCHASE_DISCOUNT_RATE) : total
end
# Don't forget, you can make methods to make your life easy!
def items_total_cost(i)
i[:count] * i[:price]
end
| true
|
a2a408dbcdb2b05171598780257f36f8bff6d95f
|
Ruby
|
jwshinx/SubscriptionCircus
|
/lib/address.rb
|
UTF-8
| 353
| 3.015625
| 3
|
[] |
no_license
|
class Address
attr_reader :address, :zip, :isactive
def initialize options={}
@address = options[:address] ? options[:address] : 'N/A'
@zip = options[:zip] ? options[:zip] : 'N/A'
@isactive = options[:isactive] ? options[:isactive] : false
end
def to_s
%Q{
address: #{@address}
zip: #{@zip}
isactive: #{@isactive}
}
end
end
| true
|
bf7c5018a5591c9d7f2aa93661c2a48df79ed55d
|
Ruby
|
chegwer/PinePractice
|
/ch5.rb
|
UTF-8
| 431
| 3.859375
| 4
|
[] |
no_license
|
#full name greeting
puts "Howdy! What's your first name?"
first = gets.chomp
puts "Thanks! How about your middle name?"
middle = gets.chomp
puts "Alright, how about your last name?"
last = gets.chomp
puts "It's nice to meet you #{first} #{middle} #{last}!"
#your favourite number is bogus
puts "What's your favourite number?"
number = gets.chomp
puts "#{number}?"
better = number.to_i
better = better + 1
puts "Mine is #{better}."
| true
|
0a713e2035dd4de18892fc0bed3e25fed231802f
|
Ruby
|
Finble/ruby-kickstart
|
/session2/3-challenge/5_array.rb
|
UTF-8
| 806
| 4.5625
| 5
|
[
"MIT"
] |
permissive
|
# Write a function named mod_three which takes an array of numbers,
# and return a new array consisting of their remainder when divided by three.
# Exclude any numbers which are actually dividible by three.
#
# EXAMPLES:
# mod_three [0] # => []
# mod_three [1] # => [1]
# mod_three [2] # => [2]
# mod_three [3] # => []
# mod_three [4] # => [1]
# mod_three [5] # => [2]
# mod_three [6] # => []
# mod_three [7] # => [1]
#
# mod_three [0,1,2,3,4,5,6,7] # => [1, 2, 1, 2, 1]
def mod_three(numbers)
numbers.map { |number| number % 3 }.select { |number| number % 3 != 0 }
end
# noted that you can do this either way around, start with .map or .select
# puts mod_three [4, 3, 5] works...
# but why does this method know numbers (param) can be an array and accepts arrays (when challenge 4 does not?)
| true
|
97ddd456e9fbf564ece9af2cf51d76551a540433
|
Ruby
|
jr1412594/ruby-check
|
/reverse_method_on_a_array.rb
|
UTF-8
| 126
| 2.84375
| 3
|
[] |
no_license
|
# p "Hello".reverse
# array = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
# p array.reverse!
# p array
queue = [4, 8, 15, 16, 23, 42]
| true
|
8388c7cf1ce658918220702e33f904f155a271ce
|
Ruby
|
jantman/puppet-facter-facts
|
/python_version.rb
|
UTF-8
| 2,069
| 2.6875
| 3
|
[] |
no_license
|
# Facter facts for python versions and paths
# https://github.com/jantman/puppet-facter-facts/blob/master/python_version.rb
Facter.add("python_default_version") do
setcode do
begin
Facter::Util::Resolution.exec('python -c "import sys; print(\'.\'.join(map(str, sys.version_info[:3])));" 2>/dev/null')
rescue
false
end
end
end
Facter.add("python_default_bin") do
setcode do
begin
/^(\/.+)$/.match(Facter::Util::Resolution.exec('which python 2>/dev/null'))[1]
rescue
false
end
end
end
Facter.add("python_usrbin_version") do
setcode do
begin
Facter::Util::Resolution.exec('/usr/bin/python -c "import sys; print(\'.\'.join(map(str, sys.version_info[:3])));" 2>/dev/null')
rescue
false
end
end
end
def add_python_paths
pythons = {
'python24_path' => 'python2.4',
'python26_path' => 'python2.6',
'python27_path' => 'python2.7',
'python31_path' => 'python3.1',
'python32_path' => 'python3.2',
'python33_path' => 'python3.3',
'python34_path' => 'python3.4',
}
versions = Array.new
python_latest_path = nil
python_latest_ver = nil
pythons.keys.sort.each do|factname|
binname = pythons[factname]
Facter.add(factname) do
begin
path = /^(\/.+)$/.match(Facter::Util::Resolution.exec("which #{binname} 2>/dev/null"))[1]
ver = Facter::Util::Resolution.exec("#{path} -c \"import sys; print('.'.join(map(str, sys.version_info[:3])));\" 2>/dev/null")
versions.push(ver)
python_latest_path = path
python_latest_ver = ver
setcode do
path
end
rescue
nil
end
end
end
Facter.add("python_latest_path") do
setcode do
python_latest_path
end
end
Facter.add("python_latest_version") do
setcode do
python_latest_ver
end
end
Facter.add("python_versions") do
setcode do
versions
end
end
Facter.add("python_versions_str") do
setcode do
versions.join(",")
end
end
end
add_python_paths()
| true
|
549f4c8f94472c6647082154525d51d122d14756
|
Ruby
|
abhramishra/Ruby
|
/array.rb
|
UTF-8
| 157
| 3.546875
| 4
|
[] |
no_license
|
num = [9,2,55,41,22,43,66,10]
even = []
odd = []
num.each do |n|
if n % 2 == 0
even.push(n)
else
odd.push(n)
end
end
puts "#{even}"
puts "#{odd}"
| true
|
d2bd9ee637991539693ce952370aae31a20f80f7
|
Ruby
|
prakriti12/lyricit
|
/lib/lyricit/make_it_personal.rb
|
UTF-8
| 512
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
module Lyricit
module MakeItPersonal
def self.get_lyrics name, artist
print "Getting Lyrics for:\nSong: #{name.strip}\nArtist: #{artist}"
return :incomplete_info if name.strip == "" || artist.strip == ""
res = Faraday.get("http://makeitpersonal.co/lyrics?artist=#{artist.strip}&title=#{name.strip}")
return nil if res.status.to_i != 200
return :not_found if res.body.include?("Sorry")
return res.body
end
end
end
| true
|
7157d09d3f917f817fd9f724b8e8c384d4d33c2b
|
Ruby
|
jodonnell/Bankruptcy-Plan
|
/payment.rb
|
UTF-8
| 286
| 2.984375
| 3
|
[] |
no_license
|
class Payment
attr_accessor :creditor, :payment
def initialize c, p
@creditor = c
@payment = p
end
def ==(other)
@creditor == other.creditor and @payment == other.payment
end
def to_s
"#{ @creditor.name } %0.2f" % [(@payment / 100.0).round(2)]
end
end
| true
|
6dfab1802210f12cdb93aa6fc8097552a1500e6a
|
Ruby
|
ruidealencar/new_feature_ruby_2.5.0
|
/Remove_top_level_constant_lookup/example_1.rb
|
UTF-8
| 595
| 3.125
| 3
|
[] |
no_license
|
class Project
end
class Category
end
Project::Category
# Ruby 2.4
# retorna a constante de nível superior com um aviso se não for capaz de encontrar uma constante no escopo especificado.
# Isso não funciona bem nos casos em que precisamos que as constantes sejam definidas com o mesmo nome no nível superior e também no mesmo escopo.
warning: toplevel constant Category referenced by Project::Category
=> Category
# ruby 2.5
# gera um erro se não for capaz de encontrar uma constante no escopo especificado.
NameError: uninitialized constant Project::Category
Did you mean? Category
| true
|
f6b0029acc8e96d70ecfeae1e52dd9762cbb0c39
|
Ruby
|
ramaaa22/entrega2
|
/Animales/aguila.rb
|
UTF-8
| 121
| 2.828125
| 3
|
[] |
no_license
|
require_relative 'ave'
class Aguila < Ave
def volar
puts "vuelo"
end
def caminar
puts "camino como aguila"
end
end
| true
|
1eb66795e2081544391d39035551f1b897baaed7
|
Ruby
|
rawls/railway
|
/bin/update_station_list
|
UTF-8
| 2,621
| 3.1875
| 3
|
[
"MIT"
] |
permissive
|
#!/usr/bin/env ruby
# frozen_string_literal: true
require 'nokogiri'
require 'net/http'
require 'uri'
require 'csv'
require 'yaml'
require 'pathname'
YAML_PATH = Pathname.new(__FILE__).realpath.parent.parent + 'config' + 'stations.yml'
# Updates the project's config/stations.yml with the latest data
def update_station_list
log('This script overwrites your local copy of config/stations.yml with the latest data from nationalrail.co.uk and '\
'railwaycodes.org.uk')
log('Press [ENTER] to continue or [Ctrl+c] to quit')
gets
# Fetch data from the web
stations = fetch_stations
locations = fetch_locations
# Add location data to the current active station list
stations.each { |crs, data| data.merge!(locations[crs]) if locations[crs] }
write_yaml(stations)
log('Your station list has been updated')
end
# Gets the current list of stations from the national rail website's station codes csv file
def fetch_stations
log(' - Fetching station list...', false)
results = {}
response = get_response('https://www.nationalrail.co.uk/static/documents/content/station_codes.csv')
CSV.new(response, headers: true).each do |row|
results[row['CRS Code']] ||= {}
results[row['CRS Code']][:name] = row['Station Name']
end
log('DONE')
results
end
# Scrapes location data for stations from the railwaycodes.org.uk website
def fetch_locations
log(' - Fetching location data (takes ~25s)...', false)
results = {}
('a'..'z').to_a.each do |letter|
response = get_response("http://www.railwaycodes.org.uk/stations/station#{letter}.shtm")
Nokogiri::HTML(response).xpath('//table/tr').each do |row|
cols = row.xpath('./td').map(&:text)
crs = row.xpath('./td').first.xpath('./a').first['name'].upcase rescue nil
unless [crs, cols[6], cols[7]].include?(nil) || [crs, cols[6], cols[7]].include?('')
results[crs] = { latitude: cols[7].to_f, longitude: cols[6].to_f }
end
end
sleep(1) # be nice to railwaycodes.org.uk
end
log('DONE')
results
end
# Write the stations.yml to disk
def write_yaml(stations)
log(' - Writing YAML...', false)
File.open(YAML_PATH.to_s, 'w') { |file| file.write(stations.to_yaml) }
log('DONE')
end
# Returns the response body for a GET request
def get_response(url)
uri = URI(url)
Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https') do |http|
request = Net::HTTP::Get.new uri
return http.request(request).body
end
end
# Puts without a linebreak
def log(str, newline = true)
return puts(str) if newline
print str.ljust(60, ' ')
STDOUT.flush
end
update_station_list
| true
|
580207f0da2a9082b5a15101a633604c1b68c015
|
Ruby
|
colemandavid55/list_more
|
/lib/list_more/repos/lists_repo.rb
|
UTF-8
| 3,050
| 3
| 3
|
[] |
no_license
|
module ListMore
module Repositories
class ListsRepo < RepoHelper
def all
result = db.exec('SELECT * FROM lists').entries
result.map{ |entry| build_list entry }
end
def save list
sql = %q[INSERT INTO lists (name, user_id) VALUES ($1, $2) RETURNING *]
result = db.exec(sql, [list.name, list.user_id])
build_list result.first
end
def update list
sql = %q[UPDATE lists SET name = $1 WHERE id = $2 RETURNING *]
result = db.exec(sql, [list.name, list.id])
build_list result.first
end
# def get_list_id list_name
# sql = %q[SELECT id FROM lists WHERE name = $1]
# result = db.exec(sql, [list_name])
# result.first['id']
# # empty array could be returned here, check if something was found
# end
# def share_list other_user_id, list_id
# sql = %q[INSERT INTO shared_lists (user_id, list_id) VALUES ($1, $2) RETURNING *]
# result = db.exec(sql, [other_user_id, list_id])
# result.first
# end
# Make sure there is some verification of contents, array could be empty result.first is a good example
def get_user_lists user_id
sql = %q[SELECT * FROM lists
WHERE user_id = $1
]
result = db.exec(sql, [user_id])
result.entries.map{ |entry| build_list entry }
end
def find_by_id list_id
sql = %q[SELECT * FROM lists
WHERE id = $1
]
result = db.exec(sql, [list_id])
build_list result.first
end
def get_lists_shared_with_user user_id
sql = %q[
SELECT l.name as name
, l.id as id
, l.user_id as user_id
FROM shared_lists s
JOIN lists l
ON s.list_id = l.id
JOIN users u
ON u.id = s.user_id
WHERE u.id = $1
]
result = db.exec(sql, [user_id])
result.entries.map{ |entry| build_list entry }
end
def destroy_list list
sql = %q[DELETE FROM lists
WHERE id = $1
]
db.exec(sql, [list.id])
end
def build_list data
ListMore::Entities::List.new data
end
end
end
end
# Notes for repos from nick, have methods to get entire profile based on id or username, return entire user object
# Did i get anything with my methods
# Entity pattern in ruby: build a user/list/item object
# Make a class for user => attr_accessor :id :username, attr_reader :password
# Within lib directory, we want a entities folder with this class within
# class User : def init (username, password, id=mil) : def has_password? (string_password) code would be whatever bcrypt needs to do to verify password, return true
# within server.rb user = URepo.find_by_username(username); if user.has_password?(params[:password]) then do all the login stuff else return an error of some sort
#
| true
|
4f804649d1ad17a82bb630b73940c613cf7fc66e
|
Ruby
|
spheregenomics/factura2
|
/app/models/entity.rb
|
UTF-8
| 1,371
| 2.5625
| 3
|
[] |
no_license
|
class Entity < ActiveRecord::Base
has_many :integrations, :dependent => :destroy
STATUS_ACTIVE = 'active'
STATUS_INACTIVE = 'inactive'
SYSTEM_ORACLE = 'oracle'
SYSTEM_MYOB = 'myob'
SYSTEM_PEOPLESOFT = 'peoplesoft'
SYSTEM_SAP = 'sap'
SYSTEM_OTHER = 'other'
validates :name, :address, :phone, :presence => true
validates :status, :inclusion => { :in => [STATUS_ACTIVE, STATUS_INACTIVE], :message => "Please assign a status."}
validates :system, :inclusion => { :in => [SYSTEM_ORACLE, SYSTEM_MYOB, SYSTEM_PEOPLESOFT, SYSTEM_SAP, SYSTEM_OTHER], :message => "Please choose a system."}
class << self
def status_collection
{
"Active" => STATUS_ACTIVE,
"Inactive" => STATUS_INACTIVE
}
end
def system_collection
{
"Oracle eBusiness" => SYSTEM_ORACLE,
"MYOB" => SYSTEM_MYOB,
"PeopleSoft" => SYSTEM_PEOPLESOFT,
"SAP" => SYSTEM_SAP,
"Other" => SYSTEM_OTHER
}
end
end
def status_tag
case self.status
when STATUS_INACTIVE then :warning
when STATUS_ACTIVE then :ok
end
end
def system_tag
case self.system
when SYSTEM_ORACLE then :ok
when SYSTEM_MYOB then :ok
when SYSTEM_PEOPLESOFT then :ok
when SYSTEM_SAP then :ok
when SYSTEM_OTHER then :ok
end
end
end
| true
|
ade0ac499e3046f3a5d7fcdf84130cd2175d8f1d
|
Ruby
|
tonynassif/square_array-cb-000
|
/square_array.rb
|
UTF-8
| 236
| 3.46875
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def square_array(array)
squared_array = []
array.each { |element| squared_array.push(element ** 2) }
return squared_array
end
=begin alternate solution
def square_array(array)
array.collect! { |element| element ** 2}
end
=end
| true
|
2f5fdd955ac45c4639c0293f2de630f92f7935d5
|
Ruby
|
sebaquevedo/desafiolatam
|
/guia_array_hash/ejercicio5.rb
|
UTF-8
| 1,226
| 3.8125
| 4
|
[
"MIT"
] |
permissive
|
a = [1 ,2, 3]
b = [:azul, :rojo, :amarillo]
c = ["Tacos", "Quesadillas", "Hamburguesas"]
def put_arrays(a,b,c)
a.each_with_index do |value,index|
puts "#{value} "+ ":#{b[index]} ," +"#{c[index]}"
end
end
def put_arrays_reverse(a,b,c)
rev = b.reverse
a.each_with_index do |value,index|
puts "#{value} "+ ":#{rev[index]} ," +"#{c[index]}"
end
end
require 'pp'
def zip_arrays(a,b,c)
new_array = []
a.each_with_index do |value,index|
new_array[index] = "#{value} "+ ":#{b[index]} ," +"#{c[index]}"
end
p new_array
end
put_arrays(a,b,c)
puts
put_arrays_reverse(a,b,c)
puts
zip_arrays(a,b,c)
Se tienen dos arreglos
El primero es del tipo [1,2,3,0,1,2,2,1,2,1,2,0,3] El segundo es del tipo [:azul, :verde, :amarillo]
Se pide cambiar todas las apariciones del número que aparece en el arreglo 1 por el elemento con el mismo
índice del arreglo 2, en caso de no existir el elemento deberá ser remplazado por nil.
El resultado de este ejercicio debería quedar:
nombres = [ :verde,:amarillo ,nil , :azul ,:verde ,:amarillo ]
array_numeros = [1,2,3,0,1,2,2,1,2,1,2,0,3]
def cambiar_apariciones(numeros,nombres)
pnumeros.map!{ |num| if nombres.indlude? 'num' }
end
cambiar_apariciones(array_numeros,nombres)
| true
|
f9e7f938af43a52376238c7e5e3bf8dce2c8d55c
|
Ruby
|
DaoCalendar/stardate
|
/app/models/grammar.rb
|
UTF-8
| 1,503
| 3.03125
| 3
|
[
"MIT"
] |
permissive
|
class Grammar
def self.parse(string)
date = Grammar.parse_date string.slice!(/^\d+\/\d+(\/\d+)?\s/)
tag_list = (string.slice!(/\s\[.+\]$/) || '').gsub(/(^\s\[)|(\]$)/, '')
if string =~ /^(\$|\+)/
words = string.split ' '
explicit_value = words.shift.gsub('$', '')
string = words.join ' '
if string =~ /-/
words = string.split ' - '
vendor = words.shift
description = words.join ' - '
else
vendor = string
end
Item.new :date=>date, :explicit_value=>explicit_value, :vendor_name=>vendor,
:description=>description, :tag_list=>tag_list
elsif string =~ /^(Ran|ran)/
distance, minutes = string.split(/^(Ran|ran) /).last.split(' ')
Run.new :date=>date, :distance=>distance, :minutes=>minutes
else
Note.new :date=>date, :body=>string
end
rescue
Note.new :date=>Time.zone.now.to_date, :body=>'Failed to parse'
end
def self.parse_date(string=nil)
return Time.zone.now.to_date if string.nil?
pieces = string.strip.split('/').collect(&:to_i)
case pieces.length
when 1
Date.new Time.zone.now.to_date.year, Time.zone.now.to_date.month, pieces.first
when 2
Date.new Time.zone.now.to_date.year, pieces.first, pieces.last
when 3
pieces[2] = pieces[2] + 2000 if pieces[2] < 100
Date.new pieces[2], pieces[0], pieces[1]
else
Time.zone.now.to_date
end
rescue
Time.zone.now.to_date
end
end
| true
|
bc864594eb9eaf5e7fe8cf54e414e95eb78dc0e2
|
Ruby
|
grantspeelman/lottoinmypocket
|
/db/seeds.rb
|
UTF-8
| 1,606
| 2.625
| 3
|
[] |
no_license
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ :name => 'Chicago' }, { :name => 'Copenhagen' }])
# Mayor.create(:name => 'Daley', :city => cities.first)
require "csv"
def import_results(model,file)
all_lotto_draws = CSV.read(file)
all_lotto_draws.shift # get rid of header titles
while(!all_lotto_draws.empty?) do
lotto_draw = all_lotto_draws.shift
record = model.new(:number => lotto_draw[0],
:date => Date.parse(lotto_draw[1]),
:ball1 => lotto_draw[2],
:ball2 => lotto_draw[3],
:ball3 => lotto_draw[4],
:ball4 => lotto_draw[5],
:ball5 => lotto_draw[6],
:ball6 => lotto_draw[7],
:bonus_ball => lotto_draw[8],
:prize_payable => lotto_draw[23],
:rollover => lotto_draw[24],
:rollover_count => lotto_draw[25],
:next_estimated_jackpot => lotto_draw[26],
:next_guaranteed_jackpot => lotto_draw[27],
:total_sales => lotto_draw[28],
:draw_machine => lotto_draw[29],
:ball_set => lotto_draw[30])
(1..7).each do |i|
record.divisions.build(:number => i,
:payout => lotto_draw[8 + i],
:winners => lotto_draw[15 + i])
end
record.save!
end
end
import_results(LottoPlusDraw,"#{Rails.root}/db/lotto_plus_draw_results.csv")
import_results(LottoDraw,"#{Rails.root}/db/lotto_draw_results.csv")
#Ball.create_balls
#TwoBallCombo.create_combos
#ThreeBallCombo.create_combos
| true
|
8c330c50434a5911081facd530f7a1346aa76bdc
|
Ruby
|
myGrid/t2-server-gem
|
/bin/t2-delete-runs
|
UTF-8
| 3,205
| 2.734375
| 3
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
#!/usr/bin/env ruby
# Copyright (c) 2010-2012 The University of Manchester, UK.
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the names of The University of Manchester nor the names of its
# contributors may be used to endorse or promote products derived from this
# software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# Author: Robert Haines
require 'rubygems'
require 't2-server-cli'
include T2Server::CLI
# set up options
options = {}
conn_params, creds = register_options("Usage: t2-delete-runs [options] "\
"server-address [run-ids...]") do |opt|
opt.separator " Where server-address is the full URI of the server to "\
"connect to,"
opt.separator " e.g.: http://example.com:8080/taverna, run-ids are the "\
"id numbers"
opt.separator " of the runs you want to delete and [options] can be:"
opt.on("--all", "Delete all runs on the server") do
options[:all] = true
end
opt.on("-f", "--finished", "Delete only finished runs. Combine with --all "\
"to delete all finished runs") do
options[:finished] = true
end
end
# get runs and server address from the arguments
runs = []
address = ""
for arg in ARGV
if arg.match(/https?:\/\//) == nil
runs << arg
else
address = arg
end
end
uri, creds = parse_address(address, creds)
# connect...
begin
server = T2Server::Server.new(uri, conn_params)
rescue RuntimeError => e
puts e
exit 1
end
# ...get the runs...
server_runs = server.runs(creds)
# ...and delete them!
for run in server_runs
begin
if options[:all] || runs.include?(run.id)
if options[:finished]
run.delete if run.finished?
else
run.delete
end
end
rescue T2Server::AuthorizationError => ae
puts "You are not authorized to delete run '#{run.id}' - skipping."
next
rescue T2Server::T2ServerError => e
puts "There was a problem while deleting run '#{run.id}' - skipping."
next
end
end
| true
|
d8729de0412c36f52fc9b11a29a92b0b04936090
|
Ruby
|
SuperLazyDog/Algorithm-Practise
|
/books/oreilly/s6_tree/practice/42.rb
|
UTF-8
| 1,297
| 3.734375
| 4
|
[] |
no_license
|
require 'securerandom'
class TreeNode
attr_accessor :data, :first_child, :next_sibling
def initialize(data)
@data = data
@seed = SecureRandom
end
def show
puts "show tree"
_show(self)
puts ""
end
def self.build_tree(ary)
return if ary.empty?
data = ary.shift
node = TreeNode.new(data)
if SecureRandom.random_number(2) == 1
node.next_sibling = build_tree(ary)
else
node.first_child = build_tree(ary)
end
return node
end
private
def _show(node)
return if node.nil?
print "#{node.data}\t"
if !node.next_sibling.nil?
_show(node.next_sibling)
end
if !node.first_child.nil?
puts "\n"
_show(node.first_child)
end
end
end
tree = TreeNode.build_tree((1..100).to_a)
tree.show
# -------------------------
# 6-42
# -------------------------
def is_structually_equal(a, b)
if [a, b].compact.count == 1
return false
elsif [a, b].compact.count == 0
return true
end
return is_structually_equal(a.next_sibling, b.next_sibling) && is_structually_equal(a.first_child, b.first_child)
end
puts "is_structually_equal: #{is_structually_equal(tree, tree)}"
tree2 = TreeNode.build_tree((1..100).to_a)
tree2.show
puts "is_structually_equal: #{is_structually_equal(tree, tree2)}"
| true
|
ee6fb033ad6cfa99a14317ff196712c3dbc4d37a
|
Ruby
|
fab9/devbootcat
|
/vendor/bundle/gems/tins-1.3.0/lib/tins/token.rb
|
UTF-8
| 893
| 3.234375
| 3
|
[
"MIT"
] |
permissive
|
module Tins
class Token < String
DEFAULT_ALPHABET = ((?0..?9).to_a + (?a..?z).to_a + (?A..?Z).to_a).freeze
#def initialize(bits: 128, length: nil, alphabet: DEFAULT_ALPHABET)
def initialize(options = {})
bits = options[:bits] || 128
length = options[:length]
alphabet = options[:alphabet] || DEFAULT_ALPHABET
alphabet.size > 1 or raise ArgumentError, 'need at least 2 symbols in alphabet'
if length
length > 0 or raise ArgumentError, 'length has to be positive'
else
bits > 0 or raise ArgumentError, 'bits has to be positive'
length = (Math.log(1 << bits) / Math.log(alphabet.size)).ceil
end
self.bits = (Math.log(alphabet.size ** length) / Math.log(2)).floor
token = ''
length.times { token << alphabet[rand(alphabet.size)] }
super token
end
attr_accessor :bits
end
end
| true
|
cb2519aae69acb8cf1259075b97bfa4dafdf7e1e
|
Ruby
|
jonasschneider/fichteplan
|
/lib/parser.rb
|
UTF-8
| 1,488
| 2.828125
| 3
|
[] |
no_license
|
require 'fichte'
require 'change'
require 'nokogiri'
require 'date'
class Fichte::Parser
def initialize data = ''
@data = data
@doc = Nokogiri::HTML.parse(@data)
end
def rows
@doc.css("tr.list:not(:first-child)").map do |row|
row.css("td").map do |cell|
txt = cell.text.gsub("\302\240", "")
if txt.empty? || txt == '---'
nil
else
txt
end
end
end
end
def row_to_params row
keys = %w(num stunde neues_fach vertreter raum detail altes_fach klasse).map{|v|v.to_sym}
params = {}
raise "Row length doesn't match (expected #{keys.length}, got #{row.length})" if row.length != keys.length
row.each_with_index do |val, i|
params[keys[i]] = val && val.match(/^\d+$/) ? val.to_i : val
end
params[:date] = date
if params[:klasse].nil?
nil
else
params
end
end
def split_forms changes
changes.map do |change|
if change[:klasse].match(", ")
change[:klasse].split(", ").map{|k| x=change.dup; x[:klasse] = k; x}
else
change
end
end.flatten
end
def changes
split_forms(rows.map{|r| row_to_params r }.compact).map{|p| Fichte::Change.new p }
end
def date
Date.parse(@doc.css(".mon_title").first.text.split(" ").first)
end
def next_page_name
if next_page_link = @doc.css("meta[http-equiv=\"refresh\"]").first
next_page_link['content'].gsub('7; URL=', '')
end
end
end
| true
|
a29282b73ea38228352752470aae879a4dacfa31
|
Ruby
|
skomer/hw_w2d1
|
/engine_class.rb
|
UTF-8
| 170
| 2.84375
| 3
|
[] |
no_license
|
class Engine
attr_reader :speed_bonus, :fuel_usage
def initialize(speed_bonus, fuel_usage)
@speed_bonus = speed_bonus
@fuel_usage = fuel_usage
end
end
| true
|
e2a7e81b10361704e172d113b72c4f1f3fcde828
|
Ruby
|
itsolutionscorp/AutoStyle-Clustering
|
/all_data/exercism_data/src/4319.rb
|
UTF-8
| 118
| 3.203125
| 3
|
[] |
no_license
|
class Hamming
def compute(strand1, strand2)
(0..strand1.length).count{|i| strand1[i] != strand2[i]}
end
end
| true
|
88e7548159d68cb246311d825fbb782cc766ee54
|
Ruby
|
VanQuishi/Connect-Four
|
/spec/connect_four_spec.rb
|
UTF-8
| 3,239
| 3.09375
| 3
|
[] |
no_license
|
require './lib/connect_four.rb'
describe Player do
describe "#is_filled_below?" do
it "check last row cell if the \'cells\' below it are filled" do
Player.empty()
user = Player.new('X')
expect(user.is_filled_below?(3,5)). to eq(true)
end
it "check a cell that have all filled cells below" do
user = Player.new('X')
board = Player.class_variable_get(:@@board)
board[0][3] = 'X'
board[0][4] = 'X'
board[0][5] = 'X'
expect(user.is_filled_below?(0,2)). to eq(true)
end
it "check a cell that don't have all filled cells below" do
user = Player.new('X')
expect(user.is_filled_below?(0,1)). to eq(false)
end
end
describe "#drop" do
it "notify a sucessful drop" do
user = Player.new('X')
board = Player.class_variable_get(:@@board)
board[1][5] = 'X'
expect(user.drop(1,4)).to eq(true)
end
it "notify a failed drop" do
user = Player.new('X')
expect(user.drop(0,1)).to eq(false)
end
end
describe "#isInside?" do
it "returns true for a win comnbination that is inside the board" do
user = Player.new('X')
expect(user.isInside?(0,5)).to eq(true)
end
it "returns false for a win comnbination that is not inside the board" do
user = Player.new('X')
expect(user.isInside?(0,6)).to eq(false)
end
end
describe "#vertical_win?" do
it "returns true for a win vertiacally" do
user = Player.new('X')
board = Player.class_variable_get(:@@board)
board[1][2] = 'X'
board[1][3] = 'X'
board[1][4] = 'X'
board[1][5] = 'X'
expect(user.vertical_win?(1)).to eq(true)
end
it "returns false for no win vertiacally" do
user = Player.new('X')
expect(user.vertical_win?(3)).to eq(false)
end
end
describe "#horizontal_win?" do
it "returns true for a win horizontally" do
user = Player.new('X')
board = Player.class_variable_get(:@@board)
board[0][5] = 'X'
board[1][5] = 'X'
board[2][5] = 'X'
board[3][5] = 'X'
expect(user.horizontal_win?(5)).to eq(true)
end
it "returns false for no win horizontally" do
user = Player.new('X')
board = Player.class_variable_get(:@@board)
expect(user.horizontal_win?(4)).to eq(false)
end
end
describe "#diagonal_win?" do
it "returns true for a win diagonally" do
user = Player.new('X')
board = Player.class_variable_get(:@@board)
board[2][4] = 'X'
board[0][2] = 'X'
expect(user.diagonal_win?(3,5)).to eq(true)
end
it "returns false for no win diagonally" do
user = Player.new('X')
board = Player.class_variable_get(:@@board)
expect(user.diagonal_win?(2,5)).to eq(false)
end
end
end
| true
|
de378755027fbba668278c4a2a675b4a0b12b7e7
|
Ruby
|
ATMartin/maildump
|
/lib/email_processor.rb
|
UTF-8
| 572
| 2.53125
| 3
|
[] |
no_license
|
class EmailProcessor
def initialize (email)
puts "**********INIT THE EMAIL**********"
@email = email
end
def process
puts "******TRYING TO GET #{@email.to[0][:token]}!******"
if !Inbox.pluck(:slug).include? @email.to[0][:token].to_s
puts "******NO INBOX FOUND FOR #{@email.to[0][:token]}!*****"
return
end
EmailMessage.create({
to: @email.to[0][:email],
from: @email.from[:email],
subject: @email.subject,
body: @email.body,
inbox_id: Inbox.find_by(slug: @email.to[0][:token]).id
})
end
end
| true
|
a3898399f21386617ba9445aca34f83a1dfe220b
|
Ruby
|
mejialvarez/reto5
|
/store_question.rb
|
UTF-8
| 443
| 3.3125
| 3
|
[] |
no_license
|
require 'csv'
require_relative 'question'
class StoreQuestion
attr_reader :questions
def initialize
@questions = []
build_questions
end
def take!
@questions.shift
end
def length
@questions.length
end
private
def build_questions
store = CSV.read('store-questions.txt').shuffle
store.each do |question|
@questions << Question.new(question[0],question[1])
end
end
end
| true
|
c7a011ddc88018ed186d996893b7907337b8f8eb
|
Ruby
|
dstodolny/chess
|
/lib/chess.rb
|
UTF-8
| 1,650
| 3.09375
| 3
|
[
"MIT"
] |
permissive
|
require_relative "chess/version"
require 'open-uri'
require 'pstore'
module Chess
module ChessHelper
def get_xy(san)
coordinates = {
"A" => 0, "B" => 1, "C" => 2, "D" => 3,
"E" => 4, "F" => 5, "G" => 6, "H" => 7,
"1" => 0, "2" => 1, "3" => 2, "4" => 3,
"5" => 4, "6" => 5, "7" => 6, "8" => 7
}
x = coordinates[san[0]]
y = coordinates[san[1]]
[x, y]
end
def get_san(xy)
x = xy[0]
y = xy[1]
return nil if x < 0 || x > 7 || y < 0 || y > 7
letters = {
0 => "A", 1 => "B", 2 => "C", 3 => "D",
4 => "E", 5 => "F", 6 => "G", 7 => "H"
}
letters[x] + (y + 1).to_s
end
def distance(from, to)
(from - to).abs
end
def other_color(color)
color == :white ? :black : :white
end
def get_sans(from, to) # get list of standard algebraic notation coordinates
if from[0] < to[0]
(from[0]..to[0]).to_a.map { |e| e + from[1] }
else
(to[0]..from[0]).to_a.map { |e| e + from[1] }.reverse
end
end
def get_castling_san(rook_position)
rook_position[0] == "H" ? "G" + rook_position[1] : "C" + rook_position[1]
end
def neighbours(letter)
neighbours = [(letter.upcase.ord - 1).chr, (letter.upcase.ord + 1).chr]
neighbours.delete_if { |letter| letter < "A" || letter > "H" }
end
def all_moves
moves = []
("A".."H").each { |let| 1.upto(8) { |num| moves << let + num.to_s } }
moves
end
end
end
lib_path = File.expand_path(File.dirname(__FILE__))
Dir[lib_path + "/chess/**/*.rb"].each { |file| require file }
| true
|
d2028f5820946b03b27ef0a7ee57b911e59ea34c
|
Ruby
|
lekan20/Rails-Bodega
|
/app/models/user.rb
|
UTF-8
| 502
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
class User < ActiveRecord::Base
has_secure_password
has_many :user_items
has_many :items, :through => :user_items
accepts_nested_attributes_for :user_items
def cart_quantity
# Gives the total quantity of items of a user
self.user_items.sum do |user_item|
user_item.quantity
end
end
def cart_price
# Adds up the total price of the users item
self.user_items.sum do |user_item|
Item.find(user_item.item_id).price * user_item.quantity
end
end
end
| true
|
9f319ca2b19b67f33609712d0affc2a109ed25ce
|
Ruby
|
tommydangerous/cracking
|
/2/4.rb
|
UTF-8
| 316
| 3.59375
| 4
|
[] |
no_license
|
# Write code to partition a linked list around a value x,
# such that all nodes less than x come before all nodes
# greater than or equal to x.
require_relative "linked_list"
ll = LinkedListFactory.linked_list
nodes = ll.nodes
node = nodes[nodes.size / 2]
ll.print
p node.data
ll.partition node.data
ll.print
| true
|
927cc1f89440da7caa941092a76e0f32b9f55130
|
Ruby
|
wincent/wincent-on-rails
|
/app/models/tag.rb
|
UTF-8
| 3,825
| 2.71875
| 3
|
[] |
no_license
|
class Tag < ActiveRecord::Base
has_many :taggings
has_many :taggables, :through => :taggings
validates_presence_of :name
validates_format_of :name,
:with => /\A[a-z0-9]+(\.[a-z0-9]+)*\z/i,
:message => 'may only contain words (letters and numbers) separated by ' +
'periods'
validates_uniqueness_of :name
attr_accessible :name
# returns a floating point number between 0 and 1 to denote a tag's relative popularity
def normalized_taggings_count
max = Tag.maximum :taggings_count # the Rails query cache will cache this
min = Tag.minimum :taggings_count # the Rails query cache will cache this
range = max - min
count = self.taggings_count
(count - min).to_f / range
end
# normalize tag names to lowercase
def name= string
super(string ? string.downcase : string)
end
def to_param
(changes['name'] && changes['name'].first) || name
end
# Make `link_to(tag, tag)` do something reasonable.
def to_s
name
end
def self.find_with_tag_names *tag_names
tag_names.reject! { |t| t.blank? }
return [] if tag_names.empty?
query = Array.new(tag_names.length, 'name = ?').join ' OR '
where(query, *tag_names).to_a
end
# Given tag_names "foo", "bar" etc, find all items tagged with those
# tags and identify what other tags could be used to narrow the search.
def self.tags_reachable_from_tag_names *tag_names
count = tag_names.length
return [] if count < 1 or count > 5 # sanity limit: no more than 5 joins
raise ArgumentError if tag_names.include?(nil)
tags = find_with_tag_names *tag_names
tags_reachable_from_tags *tags
end
# Given actual tag objects, find all items tagged with those tags and
# identify what other tags could be used to narrow the search.
def self.tags_reachable_from_tags *tags
# Goal here is to produce a query string that looks like this
# (when "one-level deep", ie. looking at "foo"):
#
# SELECT t2.tag_id AS id, tags.name, tags.taggings_count
# FROM tags, taggings AS t1
# JOIN taggings AS t2
# WHERE t1.tag_id = 38
# AND t2.taggable_id = t1.taggable_id
# AND t2.taggable_type = t1.taggable_type
# AND tags.id = t2.tag_id
# AND t2.tag_id NOT IN (38)
# GROUP BY t2.tag_id;
#
# Here is a sample when goal is "two levels deep"
# (ie. looking at "foo bar"):
#
# SELECT t3.tag_id AS id, tags.name, tags.taggings_count
# FROM tags, taggings AS t1
# JOIN taggings AS t2
# JOIN taggings AS t3
# WHERE t1.tag_id = 38
# AND t2.tag_id = 40
# AND t2.taggable_id = t1.taggable_id
# AND t2.taggable_type = t1.taggable_type
# AND t3.taggable_id = t1.taggable_id
# AND t3.taggable_type = t1.taggable_type
# AND tags.id = t3.tag_id
# AND t3.tag_id NOT IN (38, 40)
# GROUP BY t3.tag_id;
tags = tags.flatten
count = tags.length
return [] if count < 1 or count > 5 # sanity limit: no more than 5 joins
tag_ids = tags.collect(&:id) # will raise if any tag is nil
query = ["SELECT t#{count + 1}.tag_id AS id, tags.name, tags.taggings_count"]
joins = ['taggings AS t1']
ands = []
count.times do |i|
joins << "taggings AS t#{i + 2}"
ands.unshift "t#{count - i}.tag_id = #{tag_ids[count - i - 1]}"
ands << "t#{i + 2}.taggable_id = t1.taggable_id"
ands << "t#{i + 2}.taggable_type = t1.taggable_type"
end
ands << "tags.id = t#{count + 1}.tag_id"
ands << "t#{count + 1}.tag_id NOT IN (" + tag_ids.join(', ') + ')'
query << "FROM tags, " + joins.join(' JOIN ')
query << "WHERE " + ands.join(' AND ')
query << "GROUP BY t#{count + 1}.tag_id"
query = query.join ' '
Tag.find_by_sql query
end
end
| true
|
4e34118d7e16ffd76e155e485f976cbb886fbabc
|
Ruby
|
Aerithe77/ruby
|
/exo_11.rb
|
UTF-8
| 200
| 3.375
| 3
|
[] |
no_license
|
puts "Choisi un nombre !"
print "=>"
nombre_choisi = gets.chomp.to_i
if nombre_choisi > 0
nombre_choisi.times do
puts "Salut, ça farte ?"
end
else
puts "Tu es un malin toi !"
end
| true
|
d08c2c5210f742d222524d6e45cbcb76895d659d
|
Ruby
|
ChrisZou/programmingruby
|
/chapter18/fibonacci_sequence.rb
|
UTF-8
| 175
| 3.078125
| 3
|
[
"Apache-2.0"
] |
permissive
|
#!/usr/bin/env ruby
def fibonacci_sequence
Enumerator.new do |generator|
i1, i2 = 1, 1
loop do
generator.yield i1
i1, i2 = i2, i1+i2
end
end
end
| true
|
320df7abc751f1a2c991a038ca24bbac6ceb4eb7
|
Ruby
|
FiveYellowMice/labrat
|
/lib/labrat/twitter_sync.rb
|
UTF-8
| 8,023
| 2.703125
| 3
|
[] |
no_license
|
require 'cgi'
require 'json'
require 'concurrent'
require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/numeric/time'
require 'twitter'
##
# Sync Twitter with Telegram channel.
class LabRat::TwitterSync
attr_reader :api
include LabRat::Util
def initialize(bot)
setup_instance_variables(bot)
@api = Twitter::REST::Client.new do |config|
%w(consumer_key consumer_secret access_token access_token_secret).each do |k|
config.send "#{k}=", @config.twitter.send(k)
end
end
unless @options.test_tweet
Concurrent::TimerTask.execute(execution_interval: 30.minutes, run_now: true) do
begin
run
rescue => e
log_error e
end
end
else
Concurrent::Future.execute do
begin
process_tweet @api.status(@options.test_tweet)
rescue => e
log_error e
end
end
end
end
##
# Do the work.
def run
log_info { "Syncing with Twitter..." }
params = {
trim_user: false,
exclude_replies: false,
include_rts: true
}
if @options.debug_mode || !last_tweet_id
log_debug { "Debug mode is on or last_tweet_id.txt not found, getting 1 most recent Tweet." }
params[:count] = 1
else
params[:since_id] = last_tweet_id
end
tweets = @api.user_timeline(params).delete_if do |t|
t.reply? || t.source =~ /labrat/i
end.sort do |a, b|
a.created_at - b.created_at
end
log_info { "Found #{tweets.length} new Tweets." }
tweets.each do |tweet|
process_tweet tweet
self.last_tweet_id = tweet.id unless @options.debug_mode
end
end
##
# Deal with one Tweet.
def process_tweet(tweet)
log_info { "New Tweet: #{tweet.uri}" }
if tweet.retweeted_status.present?
text =
"Retweeted from <a href=\"https://twitter.com/#{tweet.retweeted_status.user.screen_name}\">@#{tweet.retweeted_status.user.screen_name}</a>:\n" +
convert_all_entities(tweet.retweeted_status)
send_media_of tweet.retweeted_status, retweeted: true
elsif tweet.quoted_status?
text =
convert_all_entities(tweet) + "\n\n" +
"Retweeted from <a href=\"https://twitter.com/#{tweet.quoted_status.user.screen_name}\">@#{tweet.quoted_status.user.screen_name}</a>:\n" +
convert_all_entities(tweet.quoted_status)
send_media_of tweet.quoted_status, retweeted: true
else
text = convert_all_entities(tweet)
send_media_of tweet
end
text = text + "\n\n<a href=\"#{tweet.uri}\">Reply</a>"
@bot.telegram.api.send_message(
chat_id: @config.twitter.target_channel,
text: text,
parse_mode: 'HTML',
disable_web_page_preview: true
)
end
##
# Convert all entities in a Tweet to HTML string.
def convert_all_entities(tweet)
log_debug { tweet.text }
text = tweet.text
entities = tweet.uris + tweet.user_mentions + tweet.hashtags + tweet.media
entities.sort! {|a, b| b.indices[0] - a.indices[0] } # Reverse
# Remove last entity that is a link to media or quoted Tweet or truncated.
if entities[0] && entities[0].indices[1] == tweet.text.length
last_entity = entities[0]
if
last_entity.respond_to?(:sizes) || # Responds to sizes means it is a media.
(
last_entity.is_a?(Twitter::Entity::URI) &&
(tweet.truncated? || tweet.quoted_status?)
)
then
log_debug { "Last entity should be removed." }
text = text[ 0 ... last_entity.indices[0] ]
entities.shift
end
end
# Remove all media entities from list.
entities.delete_if {|e| e.respond_to? :sizes }
if entities.any?
log_debug { "There are #{entities.length} entities." }
entities.each_index do |i|
entity = entities[i]
previous_entity = entities[i - 1]
next_entity = entities[i + 1]
log_debug { "#{i} #{entity.class} #{entity.indices}" }
text_before_entity = text[ 0 ... entity.indices[0] ]
text_after_entity = text[ entity.indices[1] .. -1 ]
log_debug { "Text before entity: #{text_before_entity}" }
log_debug { "Text after entity: #{text_after_entity}" }
if !previous_entity
# Last entity in position.
text_after_entity = h(text_after_entity)
end
if !next_entity
# First entity in position.
text_before_entity = h(text_before_entity)
else
# If there is next entity.
text_between_next_and_current_entity = text_before_entity[ next_entity.indices[1] ... entity.indices[0] ]
text_before_end_of_next_entity = text_before_entity[ 0 ... next_entity.indices[1] ]
text_before_entity = text_before_end_of_next_entity + h(text_between_next_and_current_entity)
end
text = text_before_entity + convert_entity(entity) + text_after_entity
log_debug { "Text after converting this entity: #{text}" }
end
else
text = h(text)
end
return text
end
##
# Convert entity to HTML string.
def convert_entity(entity)
case entity
when Twitter::Entity::URI
"<a href=\"#{h entity.expanded_url}\">#{h entity.display_url}</a>"
when Twitter::Entity::UserMention
"<a href=\"https://twitter.com/#{entity.screen_name}\">@#{entity.screen_name}</a>"
when Twitter::Entity::Hashtag
"<a href=\"https://twitter.com/hashtag/#{h encode_uri_component entity.text}\">##{h entity.text}</a>"
else
''
end
end
##
# Send media of Tweet.
def send_media_of(tweet, retweeted: false)
tweet.media.each do |media|
log_debug { media.class.to_s }
begin
case media
when Twitter::Media::Photo
@bot.telegram.api.send_photo(
chat_id: @config.twitter.target_channel,
photo: media.media_url_https,
caption: retweeted ? 'Retweeted: ' + media.url : media.url,
disable_notification: true
)
when Twitter::Media::Video
video_url = media.video_info.variants.select {|v|
v.content_type == 'video/mp4'
}.sort {|a, b|
a.bitrate - b.bitrate
}[-1].url
if video_url
@bot.telegram.api.send_video(
chat_id: @config.twitter.target_channel,
video: video_url,
caption: retweeted ? 'Retweeted: ' + media.url : media.url,
disable_notification: true
)
end
else
@bot.telegram.api.send_message(
chat_id: @config.twitter.target_channel,
text: "Unsupported media type:\n" + '<code>' + h(JSON.pretty_generate(media.to_h)) + '</code>',
parse_mode: 'HTML',
disable_notification: true
)
end
rescue => e
log_error e
@bot.telegram.api.send_message(
chat_id: @config.twitter.target_channel,
text: "Error sending media: #{e.class} #{e}",
disable_notification: true
)
end
end
end
##
# Read ID of last Tweet.
def last_tweet_id
return @last_tweet_id if @last_tweet_id
begin
id_str = File.read(File.expand_path('last_tweet_id.txt', @options.data_dir)).chomp
rescue Errno::ENOENT
return nil
end
if id_str =~ /^\d+$/
id = id_str.to_i
@last_tweet_id = id
return id
else
return nil
end
end
##
# Change ID of last Tweet.
def last_tweet_id=(val)
File.write(File.expand_path('last_tweet_id.txt', @options.data_dir), val.to_s + "\n")
@last_tweet_id = val
end
##
# Escape HTML special characters in Telegram's way
def h(str)
CGI.unescape_html(str.to_s)
.gsub('&', '&')
.gsub('"', '"')
.gsub('<', '<')
.gsub('>', '>')
end
private :h
end
| true
|
a821f2e939a7ed7226f974cd29eb932652e1d20e
|
Ruby
|
mevdschee/AdventOfCode2018
|
/day11/part2.rb
|
UTF-8
| 935
| 2.953125
| 3
|
[] |
no_license
|
input = IO.read('input').chomp.to_i
size = 300
field = {}
(1..size).each do |x|
(1..size).each do |y|
rid = x + 10
num = (rid * y + input) * rid
field[[x, y]] = (num / 100) % 10 - 5
end
end
summed = {}
(1..size).each do |x|
col = 0
(1..size).each do |y|
col += field[[x, y]]
left = (summed[[x - 1, y]] || 0)
summed[[x, y]] = left + col
end
end
threads = []
(0..size).each do |s|
threads << Thread.new do
result = nil
(0..size - s).each do |x|
(0..size - s).each do |y|
sum = 0
if x > 0 && y > 0
sum += summed[[x, y]] + summed[[x + s, y + s]]
sum -= summed[[x + s, y]] + summed[[x, y + s]]
end
result = [[x + 1, y + 1, s], sum] if result.nil? || sum > result[1]
end
end
Thread.current['result'] = result
end
end
threads.each(&:join)
best = threads.max_by { |t| t['result'][1] }['result']
puts best[0].join(',')
| true
|
24d46b08a2b9f88a35c8777d8854d40f71072a55
|
Ruby
|
spilth/l8
|
/lib/l8/smartlight.rb
|
UTF-8
| 1,860
| 2.78125
| 3
|
[
"MIT"
] |
permissive
|
require 'rubyserial'
module L8
class Smartlight
CMD_L8_DISP_CHAR = 0x7f
CMD_L8_LED_SET = 0x43
CMD_L8_MATRIX_OFF = 0x45
CMD_L8_MATRIX_SET = 0x44
CMD_L8_POWEROFF = 0x9d
CMD_L8_SET_LOW_BRIGHTNESS = 0x9a
CMD_L8_SET_ORIENTATION = 0x80
CMD_L8_STATUSLEDS_ENABLE = 0x9e
CMD_L8_SUPERLED_SET = 0x4b
def initialize(serial_port)
@serial_port = Serial.new(serial_port)
Kernel.at_exit { @serial_port.close }
end
def clear_matrix
send_command [CMD_L8_MATRIX_OFF]
end
def set_led(x, y, r, g, b)
send_command [CMD_L8_LED_SET, x, y, b, g, r, 0x00]
end
def set_superled(r,g,b)
send_command [CMD_L8_SUPERLED_SET, b, g, r]
end
def display_character(character)
send_command [CMD_L8_DISP_CHAR, character.bytes[0], 0]
end
def enable_status_leds
send_command [CMD_L8_STATUSLEDS_ENABLE, 1]
end
def disable_status_leds
send_command [CMD_L8_STATUSLEDS_ENABLE, 0]
end
def set_brightness(level)
brightness = 0
brightness = 2 if level == :low
brightness = 1 if level == :medium
send_command [CMD_L8_SET_LOW_BRIGHTNESS, brightness]
end
def power_off
send_command [CMD_L8_POWEROFF]
end
def set_matrix(pixels)
data = Util.pixels_to_two_byte_array(pixels)
send_command [CMD_L8_MATRIX_SET] + data
end
def set_orientation(orientation)
value = 1
value = 2 if orientation == :down
value = 5 if orientation == :right
value = 6 if orientation == :left
send_command [CMD_L8_SET_ORIENTATION, value]
end
private
def send_command payload
frame = Frame.new(payload)
@serial_port.write frame
result = @serial_port.read(6)
while (result == '') do
result = @serial_port.read(6)
end
end
end
end
| true
|
336aa6e3d6d6da4ad990c535fe5fd9196168e474
|
Ruby
|
kyletolle/everything-blog
|
/lib/everything/blog/source/site.rb
|
UTF-8
| 1,739
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
require 'forwardable'
require_relative 'index'
require_relative 'posts_finder'
require_relative 'stylesheet'
require_relative 'page'
require_relative 'media'
module Everything
class Blog
module Source
class Site
include Everything::Logger::LogIt
def files
info_it("Reading blog source files from `#{Everything.path}`")
# TODO: Also test memoization, and running compact
# TODO: Want to only include the index and stylesheet if those pages
# have changed and need to be regenerated?
@files ||=
[ blog_index, stylesheet ]
.concat(pages)
.concat(media_for_posts)
.tap do |o|
info_it("Processing a total of `#{o.count}` source files")
end
# .compact
end
private
def class_name
self.class.to_s
end
def blog_index
Everything::Blog::Source::Index.new(public_post_names_and_titles)
end
def posts_finder
@posts_finder ||= Everything::Blog::Source::PostsFinder.new
end
def stylesheet
Everything::Blog::Source::Stylesheet.new
end
def pages
posts_finder.posts.map do |post|
Everything::Blog::Source::Page.new(post)
end
end
def media_for_posts
posts_finder.media_for_posts.map do |media_path|
Everything::Blog::Source::Media.new(media_path)
end
end
def public_post_names_and_titles
{}.tap do |h|
posts_finder.posts.map do |post|
h[post.name] = post.title
end
end
end
end
end
end
end
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.