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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
6d19b0eadd900c95969be13073f7a47b50edae44
|
Ruby
|
JackMarx/jn_chicago_employees
|
/lib/jn_chicago_employees.rb
|
UTF-8
| 997
| 3.078125
| 3
|
[] |
no_license
|
require "jn_chicago_employees/version"
require 'unirest'
module JnChicagoEmployees
class Employee
attr_reader :job_title, :department, :name, :salary
def initialize(employee_api_info)
@job_title = employee_api_info["job_titles"]
@department = employee_api_info["department"]
@name = employee_api_info["name"]
@salary = employee_api_info["employee_annual_salary"].to_i
end
def self.all
api_array = Unirest.get('https://data.cityofchicago.org/resource/xzkq-xp2w.json').body
create_employees(api_array)
end
def self.search(search_keyword)
api_array = Unirest.get("https://data.cityofchicago.org/resource/xzkq-xp2w.json?$q=#{search_keyword}").body
create_employees(api_array)
end
def self.create_employees(api_array)
employees = []
api_array.each do |employee_info|
employees << Employee.new(employee_info)
end
employees
end
private_class_method :create_employees
end
end
| true
|
357500961068268a763536a7a3dfb5cdc42c8408
|
Ruby
|
alakahakai/vector
|
/scripts/util/metadata/field.rb
|
UTF-8
| 7,033
| 2.703125
| 3
|
[
"Apache-2.0"
] |
permissive
|
#encoding: utf-8
class Field
# This classes was introduced to handle value grouping without breaking
# the current Array API.
#
# We introduced "groups" for component options. For example, the
# `influxdb_metrics` sink groups options by "v1" and "v2". This signals
# which options are supported across each InfluxDB version. The problem
# is that some of the option values differ based on the version being used.
# This class allows definitions to group example values in a backwards
# compatible way.
class Examples < Array
def initialize(examples)
groups = {}
array = []
if examples.is_a?(Hash)
groups = examples
examples.values.each do |value|
array += value
end
elsif examples.is_a?(Array)
groups = {"all" => examples}
array = examples
else
raise ArgumentError.new("Unsupported examples type: #{examples.class.name}")
end
@groups = groups
super(array)
end
def fetch_group_values!(group)
@groups.key?(group) ? @groups.fetch(group) : self
end
def inspect
"Fields::Examples<groups=#{@groups.inspect} array=#{super}>"
end
end
include Comparable
OBJECT_TYPES = ["struct", "table"]
attr_reader :name,
:category,
:children,
:default,
:default_label,
:description,
:enum,
:examples,
:field_path_notation,
:groups,
:partition_key,
:relevant_when,
:required,
:sort,
:templateable,
:toml_display,
:type,
:unit,
:warnings
def initialize(hash)
@children = (hash["children"] || {}).to_struct_with_name(constructor: self.class)
@common = hash["common"]
@default = hash["default"]
@description = hash.fetch("description")
@enum = hash["enum"]
@examples = Examples.new(hash["examples"] || []).freeze
@field_path_notation = hash["field_path_notation"] == true
@groups = (hash["groups"] || []).freeze
@name = hash.fetch("name")
@partition_key = hash["partition_key"] == true
@relevant_when = hash["relevant_when"]
@required = hash["required"] == true
@sort = hash["sort"]
@templateable = hash["templateable"] == true
@toml_display = hash["toml_display"]
@type = hash.fetch("type")
@unit = hash["unit"]
@warnings = (hash["warnings"] || []).collect(&:to_struct).freeze
# category
@category = hash["category"] || ((@children.to_h.values.empty?) ? "General" : @name.humanize)
# Requirements
if @name.include?("`<")
raise ArgumentError.new("#{@name}.name must be in the format of \"`[..]`\" instead of \"<...>\"")
end
if @required == true && !@default.nil?
raise ArgumentError.new("#{@name}.required must be false if there is a default")
end
if wildcard? && !object?
if !@examples.any? { |example| example.is_a?(Hash) }
raise ArgumentError.new("#{@name}#examples must be a hash with name/value keys when the name is \"*\"")
end
end
if @examples.any? && !@enum.nil? && !wildcard? && @examples != @enum.keys
raise ArgumentError.new("#{@name}.examples is invalid, remove it or match it exactly with the enum values")
end
if !@relevant_when.nil? && !@relevant_when.is_a?(Hash)
raise ArgumentError.new("#{@name}.relevant_when must be a hash of conditions")
end
# Examples
if @examples.empty?
if !@enum.nil?
@examples = Examples.new(@enum.keys)
elsif !@default.nil?
@examples = Examples.new([@default])
if @type == "bool"
@examples.push(!@default)
end
elsif @type == "bool"
@examples = Examples.new([true, false])
end
end
# Coercion
if @type == "timestamp"
@examples =
Examples.new(
@examples.collect do |example|
DateTime.iso8601(example)
end
)
end
# Requirements
if @examples.empty? && !wildcard? && @children.empty? && !object? && !array_of_objects?
raise "#{@name}#examples is required if a #default is not specified"
end
end
def <=>(other)
if !wildcard? && other.wildcard?
-1
else
name.downcase <=> other.name.downcase
end
end
def advanced?
if children.any?
children_list.any?(&:advanced?)
else
!common?
end
end
def all_warnings
@all_warnings ||=
begin
new_warnings = []
new_warnings +=
warnings.collect do |warning|
warning["option_name"] = name
warning
end
new_warnings +=
children_list.collect do |child|
child.all_warnings
end.
flatten
new_warnings.freeze
end
end
def array?
type.start_with?("[")
end
def array_of_objects?
OBJECT_TYPES.any? do |object_type|
type == "[#{object_type}]"
end
end
def config_sort_obj
@config_sort_obj ||= [sort || 99, "#{category}#{name}".downcase]
end
def object_of_object?
object? && children_list.length == 1 && children_list[0].object?
end
def children?
children.any?
end
def children_list
@children_list ||= @children.to_h.values.sort
end
def common?
@common == true || (@common.nil? && required?)
end
def common_children
@common_children ||= children.select(&:common?)
end
def context?
category.downcase == "context"
end
def default_infinity?
default == 18446744073709551615
end
def eql?(other)
self.<=>(other) == 0
end
def field_path_notation?
@field_path_notation == true
end
def get_relevant_sections(sections)
sections.select do |section|
section.referenced_options.include?(name) ||
section.referenced_options.any? { |o| o.end_with?(name) }
end
end
def group?(group_name)
if group_name.nil?
true
else
groups.any? do |group|
group.downcase == group_name.downcase
end
end
end
def human_default
"#{default} #{unit}"
end
def object?
OBJECT_TYPES.include?(type)
end
def optional?
!required?
end
def partition_key?
partition_key == true
end
def relevant_when?
!relevant_when.nil?
end
def relevant_when_kvs
relevant_when.collect do |k, v|
if v.is_a?(Array)
v.collect do |sub_v|
"#{k} = #{sub_v.to_toml}"
end
else
"#{k} = #{v.to_toml}"
end
end.flatten
end
def required?
@required == true
end
def sort?
@sort != nil
end
def templateable?
templateable == true
end
def to_h
{
name: name,
category: category,
children: children,
default: default,
description: description,
enum: enum,
examples: examples,
partition_key: partition_key,
relevant_when: relevant_when,
required: required?,
templateable: templateable,
type: type,
unit: unit
}
end
def wildcard?
name.start_with?("`[")
end
end
| true
|
321ba9c809d31468284a24869257d58be62461f9
|
Ruby
|
iamvery/advent-of-code-2019
|
/ruby/spec/space/simulation_spec.rb
|
UTF-8
| 2,715
| 3.109375
| 3
|
[] |
no_license
|
require "point"
require "space/simulation"
RSpec.describe Space::Simulation do
describe ".parse" do
it "returns simulation created from data" do
data = <<~DATA
<x=-1, y=0, z=2>
<x=2, y=-10, z=-7>
<x=4, y=-8, z=8>
<x=3, y=5, z=-1>
DATA
simulation = described_class.parse(data)
expect(simulation.moons).to eq([
described_class::Moon.new(Point.new(-1,0,2), Point.new(0,0,0)),
described_class::Moon.new(Point.new(2,-10,-7), Point.new(0,0,0)),
described_class::Moon.new(Point.new(4,-8,8), Point.new(0,0,0)),
described_class::Moon.new(Point.new(3,5,-1), Point.new(0,0,0)),
])
end
end
describe "#step" do
it "works with first example" do
data = <<~DATA
<x=-1, y=0, z=2>
<x=2, y=-10, z=-7>
<x=4, y=-8, z=8>
<x=3, y=5, z=-1>
DATA
simulation = described_class.parse(data)
simulation.step(1)
expect(simulation.moons).to eq([
described_class::Moon.new(Point.new(2,-1,1), Point.new(3,-1,-1)),
described_class::Moon.new(Point.new(3,-7,-4), Point.new(1,3,3)),
described_class::Moon.new(Point.new(1,-7,5), Point.new(-3,1,-3)),
described_class::Moon.new(Point.new(2,2,0), Point.new(-1,-3,1)),
])
simulation.step(1) # 2 steps
expect(simulation.moons).to eq([
described_class::Moon.new(Point.new(5,-3,-1), Point.new(3,-2,-2,)),
described_class::Moon.new(Point.new(1,-2,2), Point.new(-2,5,6)),
described_class::Moon.new(Point.new(1,-4,-1), Point.new(0,3,-6)),
described_class::Moon.new(Point.new(1,-4,2), Point.new(-1,-6,2)),
])
simulation.step(8) # 10 steps
expect(simulation.moons).to eq([
described_class::Moon.new(Point.new(2,1,-3), Point.new(-3,-2,1)),
described_class::Moon.new(Point.new(1,-8,0), Point.new(-1,1,3)),
described_class::Moon.new(Point.new(3,-6,1), Point.new(3,2,-3)),
described_class::Moon.new(Point.new(2,0,4), Point.new(1,-1,-1)),
])
end
end
describe "#total_energy" do
it "is calculated" do
data = <<~DATA
<x=-1, y=0, z=2>
<x=2, y=-10, z=-7>
<x=4, y=-8, z=8>
<x=3, y=5, z=-1>
DATA
simulation = described_class.parse(data)
simulation.step(10)
expect(simulation.total_energy).to eq(179)
end
end
describe "history repeating itself" do
it "happens after many steps" do
data = <<~DATA
<x=-1, y=0, z=2>
<x=2, y=-10, z=-7>
<x=4, y=-8, z=8>
<x=3, y=5, z=-1>
DATA
steps = described_class.detect_repetition(data)
expect(steps).to eq(2772)
end
end
end
| true
|
dc73ae41032fa6a6780c858baf564f7087d3addd
|
Ruby
|
medialy-dev/inin-document
|
/ruby/articles_array.rb
|
UTF-8
| 4,739
| 4.125
| 4
|
[] |
no_license
|
##############################################
# 配列の作り方
##############################################
# 空配列の作り方
hoge1 = []
p hoge1
# 初期値のある数値の配列の作り方
hoge2 = [1, 3, 5, 7]
p hoge2
# 初期値のある文字列の配列の作り方
hoge3 = %w(a i u e o)
p hoge3
# 初期値のあるシンボルの配列の作り方
hoge4 = %i(a i u e o)
p hoge4
##############################################
# 配列への追加
##############################################
# 演算子(<<)を使って配列を追加する
hoge5 = []
hoge5 << 1
p hoge5
# pushメソッドを使って配列を追加する
hoge6 = []
hoge6.push(1)
p hoge6
##############################################
# 配列(array)から指定位置の要素の取り出し方
##############################################
hoge7 = [1, 3]
# 配列(array)の要素は0から開始
# 上記だと [1, 3] は
# hoge7[0]が1に該当
# hoge7[1]が3に該当
p hoge7[0]
p hoge7[1]
# 配列(array)からfor文で順番に要素を取得する場合eachを使います
hoge7.each do |h|
p h
end
##############################################
# 配列(array)から要素を削除する
##############################################
# 配列(array)に一致した要素を全て削除する
hoge8 = [1, 1]
hoge8.delete(1)
p hoge8
# 空の配列(array)が返ってくる
# 配列(array)の指定位置の要素を削除する
# これは配列(array)から指定位置の要素の取り出し方(リンク)と同様の位置の指定です
hoge9 = [1, 3]
hoge9.delete_at(0)
##############################################
# 配列(array)から長さを求める
##############################################
hoge10 = [1, 3]
p hoge10.length
p hoge10.size
# lengthまたはsizeを使う。countは内部でeach処理を行い算出しているため遅くなる
##############################################
# 配列(array)から検索する
##############################################
# こちらでまとめているものは、Enumerableモジュールで配列(array)やハッシュの検索によく使われます。
# Enumerableについては別途まとめますがここでは素直な配列(array)検索のみを扱います。
# find 配列(array)から一つを検索する
# 配列(array) [1, 3, 5] の前から順番に条件に合致したものを検索していき
# 合致したものをが見つかった時点で処理が終了します。
# なのでこの場合1より大きいなので3が見つかった時点で処理が終了します。
hoge11 = [1, 3, 5]
p hoge11.find { |n| n > 1 }
# => 3
# 合致するものがない場合はnilが返ります
p hoge11.find { |n| n > 5 }
# => nil
# detectも同義です
p hoge11.detect { |n| n > 5 }
# => nil
# select 配列(array)から条件に合致する配列を作成する
# 条件に合致するものは全て取得して配列が返ります
p hoge11.select { |n| n > 1 }
# => [3, 5]
# 条件に合致したものが無い場合は空の配列が返ります
p hoge11.select { |n| n > 5 }
# => []
# find_allも同義です
p hoge11.find_all { |n| n > 5 }
# => []
##############################################
# 配列(array)で条件に合致するかどうか調べる
##############################################
# 配列(array)の中身を全て見て条件に合致しているものを探す
# 全て合致している場合はtrueが返ります
hoge12 = [1, 3, 5]
p hoge12.all? { |n| n > 0 }
# => true
# 一つでも合致していない場合はfalseが返ります
p hoge12.all? { |n| n > 1 }
# => false
# 配列(array)の中身を見て一つでも条件に合致するものを探す
# 一つでも条件に合致するものがあればtrueが返ります
p hoge12.any? { |n| n > 1 }
# => true
# 一つも合致しない場合falseが返ります
p hoge12.any? { |n| n > 5 }
# => false
##############################################
# 配列(array)から最大値と最小値を求める
##############################################
# 配列(array)から最大値を求める
hoge13 = [1, 3, 5]
p hoge13.max
# => 5
# 配列(array)から最小値を求める
p hoge13.min
# => 1
# 配列(array)から最小値と最大値の配列(array)を取得する
p hoge13.minmax
# => [1, 5]
##############################################
# 配列(array)に含まれる(include)かどうかを調べる
##############################################
# 配列(array)に一つでも含まれていればtrueが返る
hoge14 = %w(a a i u e o)
p hoge14.include?('a')
# => true
# 配列(array)は一つでも含まれていなければfalseが返る
p hoge14.include?('ka')
# => false
| true
|
a018e79cb56ab98d3fa08a0ec5f6be6470998cbe
|
Ruby
|
blambeau/icrb
|
/spec/full/test_integer.rb
|
UTF-8
| 872
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
require 'spec_helper'
module ICRb
describe Integer do
describe 'the literal IC' do
it 'should not have accessors' do
Integer.should_not respond_to(:literal)
1.should_not respond_to(:to_literal)
end
it 'should have the literal contract by default' do
Integer.dress("12").should eq(12)
Integer.undress(12).should eq("12")
end
it 'should accept zero' do
Integer.dress("0").should eq(0)
Integer.undress(0).should eq("0")
end
it 'should accept negative integers' do
Integer.dress("-12").should eq(-12)
Integer.undress(-12).should eq("-12")
end
it 'should recognize invalid literals' do
lambda{
Integer.dress("abc")
}.should raise_error(DressError, "Invalid input `abc` for Integer.literal")
end
end
end
end
| true
|
8fdaeb3317f313bc4348a0078ca1b2743f1866d9
|
Ruby
|
hellozts4120/RubyOnRails-JHU
|
/1-Ruby summary/assignment-Calc-Max-Word-Freq/module2_assignment.rb
|
UTF-8
| 1,885
| 3.796875
| 4
|
[] |
no_license
|
#Implement all parts of this assignment within (this) module2_assignment2.rb file
#Implement a class called LineAnalyzer.
class LineAnalyzer
attr_reader :highest_wf_count, :highest_wf_words, :content, :line_number
def initialize(content, line_number)
@content = content
@line_number = line_number
self.calculate_word_frequency
end
def calculate_word_frequency
@highest_wf_words = [];
word_frequency = Hash.new(0)
@content.split.each do |word|
word_frequency[word.downcase] += 1
end
pair = word_frequency.max_by{|key, value| value}
@highest_wf_count = pair[1]
word_frequency.each do |key, value|
if value == @highest_wf_count
@highest_wf_words ||= []
@highest_wf_words.push(key)
end
end
end
end
# Implement a class called Solution.
class Solution
attr_reader :analyzers, :highest_count_across_lines, :highest_count_words_across_lines
def initialize
@analyzers = Array.new
end
def analyze_file
line_count = 1
File.foreach("test.txt") do |line|
line_count += 1
@analyzers.push(LineAnalyzer.new(line, line_count))
end
end
def calculate_line_with_highest_frequency
array_v = []
@highest_count_words_across_lines = []
@analyzers.each do |element| array_v.push(element.highest_wf_count)
end
@highest_count_across_lines = array_v.max
@analyzers.each do |element| if element.highest_wf_count == @highest_count_across_lines
@highest_count_words_across_lines.push (element)
end
end
end
def print_highest_word_frequency_across_lines
puts"The following words have the highest word frequency per line:"
@highest_count_words_across_lines.each do |e|
puts "#{e.highest_wf_words} (appears in line #{e.line_number})"
end
end
end
| true
|
6a36eacd6108f5e7c333a57b4b86dafed5c52736
|
Ruby
|
Dpalazzari/codeChallenges
|
/Ruby/test/reverse_string_test.rb
|
UTF-8
| 932
| 3.1875
| 3
|
[] |
no_license
|
require 'minitest/autorun'
require 'minitest/emoji'
require './lib/reverse_string'
class ReverseStringTest < Minitest::Test
def setup
@reverse = ReverseString.new
end
def test_it_exists
assert @reverse
end
def test_it_reverses_a_string_easy_method
phrase = 'babooshka'
result = @reverse.easy_method(phrase)
assert_equal 'akhsoobab', result
end
def test_it_reverses_a_phrase_with_multiple_words_easy_method
phrase = 'super babooshka'
result = @reverse.easy_method(phrase)
assert_equal 'akhsoobab repus', result
end
def test_it_reverses_a_string_with_special_characters_easy_method
phrase = 'super babooshka!'
result = @reverse.easy_method(phrase)
assert_equal '!akhsoobab repus', result
end
def test_it_reverses_a_string_hard_method
phrase = 'babooshka ninny'
result = @reverse.hard_method(phrase)
assert_equal 'ynnin akhsoobab', result
end
end
| true
|
e798e786cae36d88c66a065cda70a97fcbce2530
|
Ruby
|
mujtaba-saboor/Ruby-calendar-event-scheduling
|
/event_details.rb
|
UTF-8
| 183
| 2.5625
| 3
|
[] |
no_license
|
# event details
class EventDetails
attr_accessor :event_name, :date, :id
def initialize(id, event_name, date)
@id = id
@event_name = event_name
@date = date
end
end
| true
|
7f04ba0c83f463ebdc33a1473dd3605d93d57b42
|
Ruby
|
alex-solo/ruby-problems
|
/chris-pine-book/13_cheat_method.rb
|
UTF-8
| 406
| 3.578125
| 4
|
[] |
no_license
|
class Die
def initialize
@number_showing = 4
end
def cheat
puts "What side do you want?"
input = gets.chomp.to_i
if input > 6
puts "Error"
else
@number_showing = input
end
end
def roll
@number_showing = 1 + rand(6)
end
def showing
@number_showing
end
end
die = Die.new
puts die.cheat
| true
|
b09c9f1689a29163e6f5e0c38dc8be0ab3475602
|
Ruby
|
ruby-concurrency/concurrent-ruby
|
/spec/concurrent/array_spec.rb
|
UTF-8
| 2,861
| 2.921875
| 3
|
[
"MIT",
"Ruby"
] |
permissive
|
require 'concurrent/array'
module Concurrent
RSpec.describe Array do
let!(:ary) { described_class.new }
describe '.[]' do
describe 'when initializing with no arguments' do
it do
expect(described_class[]).to be_empty
end
end
describe 'when initializing with arguments' do
it 'creates an array with the given objects' do
expect(described_class[:hello, :world]).to eq [:hello, :world]
end
end
end
describe '.new' do
describe 'when initializing with no arguments' do
it do
expect(described_class.new).to be_empty
end
end
describe 'when initializing with a size argument' do
let(:size) { 3 }
it 'creates an array with size elements set to nil' do
expect(described_class.new(size)).to eq [nil, nil, nil]
end
describe 'when initializing with a default value argument' do
let(:default_value) { :ruby }
it 'creates an array with size elements set to the default value' do
expect(described_class.new(size, default_value)).to eq [:ruby, :ruby, :ruby]
end
end
describe 'when initializing with a block argument' do
let(:block_argument) { proc { |index| :"ruby#{index}" } }
it 'creates an array with size elements set to the default value' do
expect(described_class.new(size, &block_argument)).to eq [:ruby0, :ruby1, :ruby2]
end
end
end
describe 'when initializing with another array as an argument' do
let(:other_array) { [:hello, :world] }
let(:fake_other_array) { double('Fake array', to_ary: other_array) }
it 'creates a new array' do
expect(described_class.new(other_array)).to_not be other_array
end
it 'creates an array with the same contents as the other array' do
expect(described_class.new(other_array)).to eq [:hello, :world]
end
it 'creates an array with the results of calling #to_ary on the other array' do
expect(described_class.new(fake_other_array)).to eq [:hello, :world]
end
end
end
context 'concurrency' do
it do
(1..Concurrent::ThreadSafe::Test::THREADS).map do |i|
in_thread(ary) do |ary|
1000.times do
ary << i
ary.each { |x| x * 2 }
ary.shift
ary.last
end
end
end.map(&:join)
expect(ary).to be_empty
end
end
describe '#slice' do
# This is mostly relevant on TruffleRuby
it 'correctly initializes the monitor' do
ary.concat([0, 1, 2, 3, 4, 5, 6, 7, 8])
sliced = ary.slice!(0..2)
expect { sliced[0] }.not_to raise_error
end
end
end
end
| true
|
398cf4eeec03304849aca5e6a998fb1eacc37d16
|
Ruby
|
CodingDojoDallas/ruby_dec_16
|
/Proctor_Brad/ruby_tdd/solar_system/solar_system_spec.rb
|
UTF-8
| 1,264
| 2.890625
| 3
|
[] |
no_license
|
require_relative 'solar_system'
RSpec.describe Planet do
before do
@planet = Planet.new
end
describe 'Planet Stuff' do
it 'has method add_planet that sets new instance with a name, description, and population' do
@planet.add_planet "Pluto", "round", 0
expect(@planet.name).to eq("Pluto")
expect(@planet.description).to eq("round")
expect(@planet.population).to eq(0)
end
end
end
RSpec.describe SolarSystem do
before do
@system = SolarSystem.new
end
describe 'Solar System Initialization' do
it "has getter and setter for name with default value of Andromeda" do
expect(@system.name).to eq("Andromeda")
end
end
describe 'Solar System Stuff' do
it "Solar System class should contain a list of all the planets in it" do
expect(@system.planets).to eq([])
end
it "has method count that should count all planets" do
expect(@system.count).to eq(0)
end
it "has method super_nova that should clear all planets" do
@system.super_nova
expect(@system.planets.empty?).to eq(true)
end
end
end
| true
|
8379a871ec924752745a1cc0f6345739bda8f132
|
Ruby
|
yonnyquiceno/bowling_score_calculator
|
/spec/modules/checkable_spec.rb
|
UTF-8
| 3,322
| 2.578125
| 3
|
[] |
no_license
|
# frozen_string_literal: true
require 'spec_helper'
describe Checkable do
let(:dummy_class) do
Class.new do
extend Checkable
end
end
describe '#strike?' do
context 'when throwing is equal to 10' do
it 'should return true' do
expect(dummy_class.send(:strike?, 10)).to be true
end
end
context 'when throwing is different from 10' do
it 'should return false' do
expect(dummy_class.send(:strike?, 6)).to be false
end
it 'should return false' do
expect(dummy_class.send(:strike?, -10)).to be false
end
it 'should return false' do
expect(dummy_class.send(:strike?, 19)).to be false
end
it 'should return false' do
expect(dummy_class.send(:strike?, 'F')).to be false
end
end
end
describe '#spare?' do
context 'when the throwing and next throwing points add up 10' do
it 'should return true' do
expect(dummy_class.send(:spare?, 3, 7)).to be true
end
end
context 'when the throwing and next throwing points does not add up 10' do
it 'should return false' do
expect(dummy_class.send(:spare?, 6, 7)).to be false
end
it 'should return false' do
expect(dummy_class.send(:spare?, -10, -1)).to be false
end
it 'should return false' do
expect(dummy_class.send(:spare?, 19, 0)).to be false
end
it 'should return false' do
expect(dummy_class.send(:spare?, 'F', 3)).to be false
end
end
end
describe '#foul?' do
context 'when the throwing is a foul' do
it 'should return true' do
expect(dummy_class.send(:foul?, 'F')).to be true
end
end
context 'when the throwing is not a foul' do
it 'should return false' do
expect(dummy_class.send(:foul?, 2)).to be false
end
it 'should return false' do
expect(dummy_class.send(:foul?, -10)).to be false
end
it 'should return false' do
expect(dummy_class.send(:foul?, 1)).to be false
end
end
end
describe '#regular_frame?' do
context 'when the throwing and next throwing points add up less than 10' do
it 'should return true' do
expect(dummy_class.send(:regular_frame?, 2, 3)).to be true
end
end
context 'when the throwing and next throwing points does not add up less than 10' do
it 'should return false' do
expect(dummy_class.send(:regular_frame?, 2, 8)).to be false
end
it 'should return false' do
expect(dummy_class.send(:regular_frame?, -2, -3)).to be false
end
it 'should return false' do
expect(dummy_class.send(:regular_frame?, 'F', 10)).to be false
end
end
end
describe '#last_frame?' do
context 'when frame is equal to 10' do
it 'should return true' do
expect(dummy_class.send(:last_frame?, 10)).to be true
end
end
context 'when frame is not equal to 10' do
it 'should return false' do
expect(dummy_class.send(:last_frame?, 2)).to be false
end
it 'should return false' do
expect(dummy_class.send(:last_frame?, -2)).to be false
end
it 'should return false' do
expect(dummy_class.send(:last_frame?, 'F')).to be false
end
end
end
end
| true
|
496c0ce677bca68bdd94e81de38534dbea6f1e22
|
Ruby
|
testsvr01/first_rb_repro
|
/hw_seeds.rb
|
UTF-8
| 2,319
| 3.625
| 4
|
[] |
no_license
|
selection = ""
while selection != "0"
puts "Welcome to my slug fest generator Enter a selection."
puts "1. Enter your Fighters"
puts "2. List Figthers"
puts "3. List matchups"
puts "0 exit"
selection = gets.chomp
if selection == "1"
@team_array=[]
puts "enter your Fighters name"
loop do
t1 = gets.chomp.to_s
puts "enter the next Fighter. \n To finish entering Fighters just hit return"
break if t1 == ''
@team_array << t1
end
system 'cls'
elsif selection == "2"
system 'cls'
@team_array.each_with_index do |val, index|
indexp1 =index + 1
puts "#{indexp1} #{val}"
end
elsif selection == "3"
system 'cls'
puts "match ups are"
if @team_array.length.odd?
bye = @team_array.first
puts "(1)#{bye} vs has a bye"
bteam_array = @team_array.map(&:clone)
bcounter = bteam_array.count
while bcounter
bteam_array.each_with_index do |val, index|
indexp1 =index + 2
bteam1 = bteam_array[1]
bteam2 = bteam_array.last
bteam_array.pop
bteam_array.shift
break if bteam_array.length == 0
print "#{indexp1} . #{bteam1} vs #{indexp1} . #{bteam2} \n"
end
bcounter -= 1
#puts "#{bcounter}" /this makes sure the value is getting passed
break if bcounter == 1
end
elsif @team_array.length.even?
bteam_array = @team_array.map(&:clone)
bcounter = bteam_array.count
while bcounter
bteam_array.each_with_index do |val, index|
indexp1 =index + 1
bteam1 = bteam_array.first
bteam2 = bteam_array.last
print "#{indexp1} . #{bteam1} vs #{indexp1} . #{bteam2} \n "
bteam_array.pop
bteam_array.shift
end
bcounter -= 1
#puts "#{bcounter}" /this makes sure the value is getting passed
break if bcounter == 0
end
end
elsif selection == "0"
puts "good bye"
else selection !=("0..3")
puts "incorrect entry please enter a selection listed below"
end
end
| true
|
07e5970f0cfe69049a63419600b912ce6cdde1d5
|
Ruby
|
HortusHonu/oop
|
/Image.rb
|
UTF-8
| 278
| 3.171875
| 3
|
[] |
no_license
|
class Image
def initialize
image = []
@image = image
end
def output_image
image.each do |x|
x.each do |cell|
puts cell
end
end
end
end
image = Image.new([
[0, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 0, 1],
[0, 0, 0, 0]
])
image.output_image
| true
|
63104929e77a6ecf7adca55c8d9a4815e72a30db
|
Ruby
|
EasyRPG/EV0001
|
/BotLog.rb
|
UTF-8
| 456
| 2.546875
| 3
|
[] |
no_license
|
# EV0001 Bot - Copyright 2011 vgvgf
class BotLog < Log
def initialize
super('')
@file = 'botlog.txt'
end
def add_log(str, time = true)
if time
super(Time.new.strftime("[%Y-%m-%d %H:%M] ") + str)
else
super(str)
end
end
def log_error(type, error)
self.add_log("#{type} ERROR: #{error}") rescue nil
self.add_log("\t\t#{error.backtrace[0]}", false) rescue nil
self.add_log("\t\t#{error.backtrace[1]}", false) rescue nil
end
end
| true
|
dca350722eb5a8f94b8a3a62563dc24c69caec10
|
Ruby
|
farisalasmary/kaldi-ruby-api
|
/speech_engine_wrapper_spec.rb
|
UTF-8
| 9,507
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
require 'rspec'
@root_folder = '/volume/rails'
$LOAD_PATH << "#{@root_folder}/ruby_api"
require 'engine_wrapper'
#require 'engine_wrapper'
RSpec.describe SpeechEngine do
before do
@root_folder = '/volume/rails'
end
describe 'wav_to_text' do
it 'should return correct segmentations and transcription of the executed bash script' do
# allow(subject).to receive(:allowed_extensions).and_return([true, 'mp3']) # stubbing
input_file = "#{@root_folder}/ruby_api/testing_data/kaldi_english_test_CUT_TESTING.wav"
output_file = "#{@root_folder}/ruby_api/testing_data/kaldi_english_test_CUT_TESTING.txt"
allow(subject).to receive(:system).and_return(true) # stubbing
text, segmentations, was_executed = subject.wav_to_text(input_file, output_file)
expected_segmentations = [
{"start"=>0.06, "end"=>0.21, "duration"=>0.15, "word"=>"there's"},
{"start"=>0.21, "end"=>0.32999999999999996, "duration"=>0.12, "word"=>"no"},
{"start"=>0.33, "end"=>0.72, "duration"=>0.39, "word"=>"reporting"},
{"start"=>0.72, "end"=>0.78, "duration"=>0.06, "word"=>"the"},
{"start"=>0.78, "end"=>1.05, "duration"=>0.27, "word"=>"wash"},
{"start"=>1.05, "end"=>1.1400000000000001, "duration"=>0.09, "word"=>"and"},
{"start"=>1.14, "end"=>1.6199999999999999, "duration"=>0.48, "word"=>"imposed"},
{"start"=>1.62, "end"=>1.7100000000000002, "duration"=>0.09, "word"=>"the"},
{"start"=>1.71, "end"=>2.2199999999999998, "duration"=>0.51, "word"=>"headline"},
{"start"=>2.22, "end"=>2.6700000000000004, "duration"=>0.45, "word"=>"whitehouse"},
{"start"=>2.67, "end"=>2.85, "duration"=>0.18, "word"=>"was"},
{"start"=>2.85, "end"=>3.12, "duration"=>0.27, "word"=>"worn"},
{"start"=>3.12, "end"=>3.72, "duration"=>0.6, "word"=>"giuliano"},
{"start"=>3.72, "end"=>3.87, "duration"=>0.15, "word"=>"was"},
{"start"=>3.87, "end"=>4.23, "duration"=>0.36, "word"=>"target"},
{"start"=>4.23, "end"=>4.29, "duration"=>0.06, "word"=>"of"},
{"start"=>4.29, "end"=>4.62, "duration"=>0.33, "word"=>"russian"},
{"start"=>4.62, "end"=>4.71, "duration"=>0.09, "word"=>"and"},
{"start"=>4.71, "end"=>4.95, "duration"=>0.24, "word"=>"told"}
]
expected_text = "THERE'S NO REPORTING THE WASH AND IMPOSED THE HEADLINE WHITEHOUSE WAS WORN GIULIANO WAS TARGET OF RUSSIAN AND TOLD"
expect(text).to eq expected_text
expect(segmentations).to eq expected_segmentations
expect(was_executed).to be true
end
end
describe 'allowed_extensions' do
it 'should return is_valid = false and the extension of the provided file in lower case' do
is_valid, extension = subject.allowed_extensions("filename.JPG")
expect(is_valid).to be false
expect(extension).to eq 'jpg'
end
it 'should return is_valid = false and the extension "wav"' do
is_valid, extension = subject.allowed_extensions("filename.wav")
expect(is_valid).to be true
expect(extension).to eq 'wav'
end
it 'should return is_valid = true and the extension "wav"' do
is_valid, extension = subject.allowed_extensions("filename.wav")
expect(is_valid).to be true
expect(extension).to eq 'wav'
end
it 'should return is_valid = true and the extension "ogg"' do
is_valid, extension = subject.allowed_extensions("filename.OGG")
expect(is_valid).to be true
expect(extension).to eq 'ogg'
end
it 'should return is_valid = true and the extension "mp3"' do
is_valid, extension = subject.allowed_extensions("filename.mp3")
expect(is_valid).to be true
expect(extension).to eq 'mp3'
end
it 'should return is_valid = true and the extension "mp4"' do
is_valid, extension = subject.allowed_extensions("filename.mp4")
expect(is_valid).to be true
expect(extension).to eq 'mp4'
end
it 'should return is_valid = true and the extension "flv"' do
is_valid, extension = subject.allowed_extensions("filename.flv")
expect(is_valid).to be true
expect(extension).to eq 'flv'
end
end
describe 'convert_flv_to_mp4' do
it 'should return was_executed = true if the system executes the ffmpeg command with no errors' do
# allow(subject).to receive(:set_command).and_return("Stubbing worked!!!!")
allow(subject).to receive(:allowed_extensions).and_return([true, 'flv']) # stubbing
#allow(subject).to receive(:system).and_return(true) # stubbing
input_file = "#{@root_folder}/ruby_api/testing_data/SVD_Eigenfaces_CUT.flv"
output_file = "#{@root_folder}/ruby_api/testing_data/SVD_Eigenfaces_CUT.mp4"
is_valid, extension, was_executed = subject.convert_flv_to_mp4(input_file, output_file)
expect(is_valid).to be true
expect(extension).to eq('flv')
expect(was_executed).to be true
end
it 'should return was_executed = false if the system is NOT provided with a FLV file' do
# allow(subject).to receive(:set_command).and_return("Stubbing worked!!!!")
allow(subject).to receive(:allowed_extensions).and_return([true, 'mp4']) # stubbing
#allow(subject).to receive(:system).and_return(true) # stubbing
input_file = "#{@root_folder}/ruby_api/testing_data/SVD_Eigenfaces_CUT.flv"
output_file = "#{@root_folder}/ruby_api/testing_data/SVD_Eigenfaces_CUT.mp4"
is_valid, extension, was_executed = subject.convert_flv_to_mp4(input_file, output_file)
expect(was_executed).to be false
end
end
describe 'convert_to_wav' do
it 'should return was_executed = true if the system executes the ffmpeg command with no errors while converting mp3 to wav' do
# allow(subject).to receive(:set_command).and_return("Stubbing worked!!!!")
allow(subject).to receive(:allowed_extensions).and_return([true, 'mp3']) # stubbing
input_file = "#{@root_folder}/ruby_api/testing_data/SVD_Eigenfaces_CUT.mp3"
output_file = "#{@root_folder}/ruby_api/testing_data/SVD_Eigenfaces_CUT.wav"
is_valid, extension, was_executed = subject.convert_to_wav(input_file, output_file)
expect(is_valid).to be true
expect(extension).to eq('mp3')
expect(was_executed).to be true
end
it 'should return was_executed = true if the system executes the ffmpeg command with no errors while converting mp4 to wav' do
# allow(subject).to receive(:set_command).and_return("Stubbing worked!!!!")
allow(subject).to receive(:allowed_extensions).and_return([true, 'mp4']) # stubbing
input_file = "#{@root_folder}/ruby_api/testing_data/SVD_Eigenfaces_CUT.mp4"
output_file = "#{@root_folder}/ruby_api/testing_data/SVD_Eigenfaces_CUT.wav"
is_valid, extension, was_executed = subject.convert_to_wav(input_file, output_file)
expect(is_valid).to be true
expect(extension).to eq('mp4')
expect(was_executed).to be true
end
it 'should return was_executed = true if the system executes the ffmpeg command with no errors while converting flv to wav' do
# allow(subject).to receive(:set_command).and_return("Stubbing worked!!!!")
allow(subject).to receive(:allowed_extensions).and_return([true, 'flv']) # stubbing
input_file = "#{@root_folder}/ruby_api/testing_data/SVD_Eigenfaces_CUT.flv"
output_file = "#{@root_folder}/ruby_api/testing_data/SVD_Eigenfaces_CUT.wav"
is_valid, extension, was_executed = subject.convert_to_wav(input_file, output_file)
expect(is_valid).to be true
expect(extension).to eq('flv')
expect(was_executed).to be true
end
it 'should return was_executed = true if the system executes the ffmpeg command with no errors while converting ogg to wav' do
# allow(subject).to receive(:set_command).and_return("Stubbing worked!!!!")
allow(subject).to receive(:allowed_extensions).and_return([true, 'ogg']) # stubbing
input_file = "#{@root_folder}/ruby_api/testing_data/SVD_Eigenfaces_CUT.ogg"
output_file = "#{@root_folder}/ruby_api/testing_data/SVD_Eigenfaces_CUT.wav"
is_valid, extension, was_executed = subject.convert_to_wav(input_file, output_file)
expect(is_valid).to be true
expect(extension).to eq('ogg')
expect(was_executed).to be true
end
end
end
| true
|
78237dc56a190d05e5d06ace75773ade0cf1987c
|
Ruby
|
NeuralNetworkingTechnologies/rann
|
/lib/rann/connection.rb
|
UTF-8
| 1,173
| 2.6875
| 3
|
[
"Apache-2.0"
] |
permissive
|
require "securerandom"
require "bigdecimal"
require "bigdecimal/util"
module RANN
class Connection
attr_accessor *%i(
output_neuron
input_neuron
weight
processed
enabled
id
)
def initialize input_neuron, output_neuron, weight = nil
@id = SecureRandom.hex
@output_neuron = output_neuron
@input_neuron = input_neuron
@weight = weight || initial_weight
@processed = false
@enabled = true
@locked = false
end
def process
if processable? && !processed?
out_value = input_neuron.value * weight
output_neuron.push_value! out_value
@processed = true
end
end
def neurons
[output_neuron, input_neuron]
end
def processable?
input_neuron.value
end
def enabled?
enabled
end
def processed?
processed
end
def locked?
@locked
end
def reset!
@processed = false
end
private
def initial_weight
if output_neuron.context?
1.to_d
else
rand.to_d BigDecimal.limit
end
end
end
end
| true
|
7f432f55620028d58bfc4d6df741fdfb1032d716
|
Ruby
|
dojorio/dojo-centro
|
/2009/20091021 - torre de hanoi - ruby/torre_de_hanoi.rb
|
UTF-8
| 278
| 2.859375
| 3
|
[] |
no_license
|
def resolver(entradas)
return "2 to c", "1 to c" if entradas == [1, 2, 0]
return ["1 to b", "2 to c", "1 to c"] if entradas == [21, 0, 0]
return [entradas[0].last " to c"] if entradas[0].to_s.length %2
["1 to c"]
end
| true
|
c422922edf678a5a604f01c45111f9d801596f92
|
Ruby
|
cody-brock/ruby_course
|
/sandbox/ifelse-methods.rb
|
UTF-8
| 1,731
| 4.59375
| 5
|
[] |
no_license
|
def multiply (first_num, second_num)
first_num.to_f * second_num.to_f
end
def divide (first_num, second_num)
first_num.to_f / second_num.to_f
end
def add (first_num, second_num)
first_num.to_f + second_num.to_f
end
def subtract (first_num, second_num)
first_num.to_f - second_num.to_f
end
def mod (first_num, second_num)
first_num.to_f % second_num.to_f
end
puts "Simple Calculator"
20.times { print "-" }
puts
puts "Please enter first number"
first_number = gets.chomp
puts "Please enter second number"
second_number = gets.chomp
puts "What do you want to do?"
puts "Enter 1 for multiply, 2 for division, 3 for addition, 4 for subtraction, and 5 for mod"
user_entry = gets.chomp
if user_entry === "1"
puts "You have chosen to multiply"
result = multiply(first_number, second_number)
puts result
elsif user_entry === "2"
puts "You have chosen to divide"
puts "Divided: #{divide(first_number, second_number)}"
elsif user_entry === "3"
puts "You have chosen to add"
puts "Added: #{add(first_number, second_number)}"
elsif user_entry === "4"
puts "You have chosen to subtract"
puts "Subtracted: #{subtract(first_number, second_number)}"
elsif user_entry === "5"
puts "You have chosen to mod"
puts "Modded: #{mod(first_number, second_number)}"
else
puts "Please choose a number from 1 to 5"
end
# If else stuff
# condition = true
# another_condition = false
# if !condition || !another_condition
# puts "this evaluated to true"
# else
# puts "this evaluated to false"
# end
# puts "lalala"
# name = "BLAH"
# if name === "Cody"
# puts "Welcome, Cody"
# elsif name === "Jack"
# puts "Welcome, Jack"
# elsif name === "Mary"
# puts "Howdy do"
# else
# puts "Welcome, rando"
# end
| true
|
3148a73139390268f284b1c70ddd02bcdfc3ec6f
|
Ruby
|
ispmor/learn_ruby
|
/04_pig_latin/pig_latin.rb
|
UTF-8
| 869
| 3.40625
| 3
|
[] |
no_license
|
#write your code here
def translate(text)
words = text.split(" ")
size = words.size
count = 0
words.each do |i|
if i[0] == 'a' || i[0] == 'e' || i[0] == 'i' || i[0] == 'o' || i[0] == 'u'
i = i + "ay"
elsif i[1] == 'a' || i[1] == 'e' || i[1] == 'i' || i[1] == 'o' || i[1] == 'u'
##wyjtek dla qu
if i[0]=='q' && i[1]=='u'
a = i.size
text2 = i[2..(a-1)] + i[0,2]+"ay"
i = text2
else
a = i.size
text2 = i[1,a] + i[0]+"ay"
i = text2
end
elsif i[2] == 'a' || i[2] == 'e' || i[2] == 'i' || i[2] == 'o' || i[2] == 'u'
if i[1]=='q' && i[2]=='u'
a = i.size
text2 = i[3,a] + i[0,3]+"ay"
i = text2
else
a = i.size
text2 = i[2..(a-1)] + i[0,2]+"ay"
i = text2
end
else
a = i.size
text2 = i[3,a] + i[0,3]+"ay"
i = text2
end
words[count] = i
count+=1
end
text = words.join(" ")
return text
end
| true
|
1c417e7c58c09e0f1f693a65ed9483ff1974b00e
|
Ruby
|
hydroflux/programming-univbasics-nds-green-grocer-part-2-den01-seng-ft-120720
|
/lib/grocer_part_2.rb
|
UTF-8
| 2,517
| 3.34375
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
require_relative './part_1_solution.rb'
def apply_coupons(cart, coupons)
# REMEMBER: This method **should** update cart
cart.each do |cart_item|
active_coupon = find_item_by_name_in_collection(cart_item[:item], coupons)
if active_coupon != nil
if cart_item[:count] >= active_coupon[:num]
num_items = active_coupon[:num]
# Create discount_item
discount_item = {
:item => cart_item[:item] + " W/COUPON",
:price => active_coupon[:cost] / num_items,
:clearance => cart_item[:clearance],
:count => active_coupon[:num]
}
# Add item with discount to updated cart
cart << discount_item
# Update number of cart item after applying coupon
cart_item[:count] = cart_item[:count] - num_items
end
end
end
cart
end
# def apply_coupons(cart, coupons)
# # REMEMBER: This method **should** update cart
# updated_cart = []
# cart.each do |cart_item|
# active_coupon = find_item_by_name_in_collection(cart_item[:item], coupons)
# if active_coupon != nil
# if cart_item[:count] >= active_coupon[:num]
# num_items = active_coupon[:num]
# # Create discount_item
# discount_item = {
# :item => cart_item[:item] + " W/COUPON",
# :price => active_coupon[:cost] / num_items,
# :clearance => cart_item[:clearance],
# :count => active_coupon[:num]
# }
# # Add item with discount to updated cart
# updated_cart << discount_item
# # Update number of cart item after applying coupon
# cart_item[:count] = cart_item[:count] - num_items
# if cart_item[:count] > 0
# cart_item << updated_cart
# end
# else
# updated_cart << cart_item
# end
# else
# updated_cart << cart_item
# end
# end
# updated_cart
# end
def apply_clearance(cart)
# REMEMBER: This method **should** update cart
cart.each do |cart_item|
if cart_item[:clearance] == true
cart_item[:price] = cart_item[:price] * 0.8
end
end
end
def checkout(cart, coupons)
consolidated_cart = apply_clearance(apply_coupons(consolidate_cart(cart), coupons))
checkout_total = 0
consolidated_cart.each do |cart_item|
checkout_total += cart_item[:price] * cart_item[:count]
end
if checkout_total >= 100
checkout_total *= 0.9
end
checkout_total.round(2)
end
| true
|
fddfcda447ad9a33d40d73d766ca90e29d650b54
|
Ruby
|
sourabh-ukkalgaonkar/ms_Word_pattren
|
/ms_word_pattern.rb
|
UTF-8
| 1,064
| 3.5
| 4
|
[] |
no_license
|
# frozen_string_literal: true
input = [
{ id: 1, title: 'heading1', heading_level: 0 },
{ id: 2, title: 'heading2', heading_level: 2 },
{ id: 3, title: 'heading3', heading_level: 1 },
{ id: 4, title: 'heading4', heading_level: 1 }
]
class MsWordPattern
def initialize(records)
@records = records
@main_heading = 0
@heading_levels = []
end
def convert
@records.each do |record|
if @heading_levels[record[:heading_level]].nil?
@heading_levels[record[:heading_level]] = 1
(0..record[:heading_level]).each do |i|
@heading_levels[i] = 1 if @heading_levels[i].nil?
end
else
@heading_levels[record[:heading_level]] += 1
end
puts "#{index(record[:heading_level])} #{record[:title]}"
end
end
def index(level)
str = ''
(0..level).each do |i|
value = @heading_levels[i].nil? ? 1 : @heading_levels[i]
str += value.to_s + '.'
end
(0..(level - 1)).each { |_i| str = "\t" + str }
str
end
end
mwp = MsWordPattern.new(input)
mwp.convert
| true
|
81464de7fd9ce396af3271727397f13892401710
|
Ruby
|
TimPetricola/redactor
|
/spec/lib/redactor/rule_spec.rb
|
UTF-8
| 2,489
| 2.90625
| 3
|
[
"MIT"
] |
permissive
|
require 'spec_helper'
describe Redactor::Rule do
it 'can be built with a regex' do
rule = Redactor::Rule.new(:foo, /foo/)
expect(rule.reason).to eq :foo
expect(rule.regex).to eq(/foo/)
end
it 'can be built with a block' do
rule = Redactor::Rule.new(:foo) { |input| input }
expect(rule.reason).to eq :foo
expect(rule.block).not_to be_nil
end
it 'needs a regex or a block' do
expect {
Redactor::Rule.new(:foo)
}.to raise_error(ArgumentError)
end
it 'can not have a regex and a block' do
expect {
Redactor::Rule.new(:foo, /foo/) { |input| input }
}.to raise_error(ArgumentError)
end
describe '#extract' do
context 'with regex' do
let(:text) do
'Lorem foo bar ipsum dolor sit amet, foobar adipiscing elit.'
end
let(:rule) { Redactor::Rule.new(:foo_bar, /foo ?bar/) }
let(:results) { rule.extract(text) }
it 'returns values and positions of first match' do
extract = results.first
expect(extract.rule).to be rule
expect(extract.value).to eq 'foo bar'
expect(extract.start).to eq 6
expect(extract.finish).to eq 12
end
it 'returns values and positions of others matches' do
extract = results[1]
expect(extract.rule).to be rule
expect(extract.value).to eq 'foobar'
expect(extract.start).to eq 36
expect(extract.finish).to eq 41
end
end
context 'with block' do
let(:text) do
'I want a kayak, a poney or a racecar.'
end
let(:rule) do
Redactor::Rule.new(:palindrome) do |input|
input.split(/\W+/)
.select { |w| w.length > 2 && w == w.reverse }
.map do |word|
start = input.index(word)
finish = start + word.length - 1
[start, finish]
end
end
end
let(:results) { rule.extract(text) }
it 'returns values and positions of first match' do
extract = results.first
expect(extract.rule).to be rule
expect(extract.value).to eq 'kayak'
expect(extract.start).to eq 9
expect(extract.finish).to eq 13
end
it 'returns values and positions of others matches' do
extract = results[1]
expect(extract.rule).to be rule
expect(extract.value).to eq 'racecar'
expect(extract.start).to eq 29
expect(extract.finish).to eq 35
end
end
end
end
| true
|
95f7d4d94047006daf340a9a060f44ff832c6d1e
|
Ruby
|
rezonant/crush
|
/lib/crush/functions.rb
|
UTF-8
| 3,646
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
class Array
def ls(*options)
common_dir = true
last_dir = nil
self.entries.each do |x|
unless x.kind_of? Crush::Entry
common_dir = false
break
end
if last_dir
common_dir = (last_dir == x.parent.full_path)
last_dir = x.parent.full_path
else
last_dir = x.parent.full_path
end
end
last_dir = nil
if options.member? :one
out = []
self.entries.each do |x|
if x.kind_of? Crush::Entry
colorized = (Dir.color_dir(x) if x.duck_query :dir?) or Dir.color_file(x)
else
colorized = x
end
out << " " + colorized
end
out << " -" + Term::dim("no entries") + "-" if out.length == 0
puts out.join("\n")
else
entries.map do |x|
suffix = (x.duck_query(:dir?) ? '/' : (x.duck_query(:executable?) ? '*' : ''))
if common_dir
::File.basename(x.full_path) + suffix
else
x.full_path + suffix
end
end .colorize(
lambda {|x| x.to_s.end_with?('/') } => ($CRUSH.options[:ls_dir_color] or :blue),
lambda {|x| x.to_s.end_with?('*') } => ($CRUSH.options[:ls_exec_color] or :green)
).columns
end
:sshh
end
end
module Math
def Math.PI
Math::PI
end
end
def import(*mods)
mods.each do |mod|
raise Exception.new("Crush must be purely bound") unless $CRUSH.is_pure?
if mod.kind_of? Module
$CRUSH.bind_include mod
else
begin
mod_orig = mod
mod_file = mod.to_s
mod_name = mod.to_s.capitalize + "Commands"
mod = eval mod_name
found = true
rescue
mod_rb = mod_file + '.rb'
found = $CRUSH.path.select { |path| FileTest.exists?("#{path}/#{mod_rb}") }.each do |path|
begin
require "#{path}/#{mod_rb}"
break true
rescue ::Exception => e; end;
end
found = false if found == []
if found == true
mod = eval mod.to_s.capitalize + "Commands"
end
end
if found
$CRUSH.bind_include mod
else
puts "could not import shell extension `#{mod_orig}'"
end
found
end
end
end
module RubyCommands
def p
$CRUSH.last!
end
def inspect(item)
if item.kind_of? Class
ri = `ri -f simple #{item.name}`
puts Term::underline("The `#{item.name}` class")
puts
puts "Instance methods:"
else
end
:sshh
end
def irb
system 'irb'
end
def backtrace(e = $e)
if e.nil?
"No exception has occurred."
else
$CRUSH.backtrace e
end
end
def ri(topic)
$CRUSH.ri topic
end
end
module CrushCommands
def dir(n)
Crush::Dir.new(n)
end
def help(topic = 'intro')
$CRUSH.help topic
end
def run(*args)
system args.join(" ")
end
end
module UnixCommands
def mount(*args)
Crush::Box.new.bash("mount #{args.join(" ")}")
end
def whoami
`whoami`.strip
end
def ps
Crush::Box.new.processes
end
def who
utmp.unpack 'S_I_A32A4A32A256SSI_I_I_lA20'
end
def man(topic)
system 'man ' + topic
end
def echo(v)
puts v
:sshh
end
def printf(v)
print v
:sshh
end
def ssh(host)
$CRUSH.ssh host
end
end
module WdCommands
def chdir(dest = nil)
$CRUSH.cd dest
end
alias :cd :chdir
def wd()
$CRUSH.wd
end
def pwd()
echo $CRUSH.wd.inspect
end
end
module TermCommands
def reset()
system 'reset'
:sshh
end
def clear()
$CRUSH.clear
end
alias :cls :clear
end
module CoreCommands
def time()
t = Time.now
yield
Time.now - t
end
end
module PrettyCommands
def columns(items)
if block_given?
Columnator.go(items) { |x| yield x }
else
Columnator.go(items)
end
end
end
module FileCommands
def ls(dest = ".")
$CRUSH.ls(dest)
end
def mv(from, to, verbose = false)
$CRUSH.mv from, to, verbose
end
end
| true
|
64f97e9e7d9961fc8f668a127385f8831254614a
|
Ruby
|
riazmohamed/LaunchSchool_lesson4
|
/working_with_blocks/additional_exercises/ex6.rb
|
UTF-8
| 296
| 3.84375
| 4
|
[] |
no_license
|
# ex6.rb
flintstones = %w(Fred Barney Wilma Betty BamBam Pebbles)
# my solution
new_arr = flintstones.map do |name|
name[0..2] # => Alternatively this name[0...3] could have worked too
end
p new_arr
# given solution
flintstones.map! do |name|
name[0, 3]
end
p flintstones
| true
|
983fffcf7cf30f3fa786a0214972f599fb72ae7f
|
Ruby
|
agent462/docface
|
/lib/docface/file_troll.rb
|
UTF-8
| 721
| 2.75
| 3
|
[
"Apache-2.0"
] |
permissive
|
module DocFace
class FileTroll
def troll(dir)
if File.directory?(dir)
index = Array.new
path = dir.gsub(/\\(?=\S)/, '/')
Dir.glob(File.join(path, '**/*.{md,MD,markdown,mdown}')).each do |file|
index << file
end
index
else
puts "The directory #{dir} does not exist."
exit
end
end
def index_hash(list)
tree = Hash.new
list.sort.each do |w|
h = tree
w.split('/').each do |part|
h = h[part] ||= Hash.new
end
end
tree
end
def cleanup(h)
return true if h.empty?
h.find_all{|k,v|h[k]=nil if v.is_a?(Hash)&&cleanup(v)}
false
end
end
end
| true
|
c671d0028f394a16b2444d56734038b87ab8fa5a
|
Ruby
|
yoshida-eth0/async_enum
|
/test/async_enum_test/thread_pool_test.rb
|
UTF-8
| 510
| 2.671875
| 3
|
[] |
no_license
|
require 'test_helper'
class ThreadPoolTest < Test
test 'pools can speed things up' do
default_start = Time.now
500.times.async.each{ true }
default_delta = Time.now - default_start
rated_start = Time.now
500.times.async(10).each{ true }
rated_delta = Time.now - rated_start
assert rated_delta < default_delta
end
test 'pools with ranges' do
vals = (0..7).async(4).map do |x|
x + 2
end
assert_equal [2, 3, 4, 5, 6, 7, 8, 9], vals
end
end
| true
|
8d1091ff53a0b0a4ead1352b5b0e2dd7e734fb5b
|
Ruby
|
kkrmno/imgrb
|
/lib/imgrb/chunks/critical_chunks.rb
|
UTF-8
| 2,858
| 2.625
| 3
|
[
"MIT",
"CC0-1.0"
] |
permissive
|
module Imgrb
module Chunks
#Instances of this class represent IDAT chunks. This chunk contains
#compressed image data.
class ChunkIDAT
include AbstractChunk, Critical, Public
def self.type #:nodoc:
"IDAT"
end
end
#Instances of this class represent IHDR chunks. This chunk contains header
#data. It must be the first chunk in a PNG file. It contains data on
#* width
#* height
#* bit depth
#* color type
#* compression method (only one possible)
#* filter method (only one possible)
#* interlace method (none or Adam7)
class ChunkIHDR
include AbstractChunk, Critical, Public
def self.type #:nodoc:
"IHDR"
end
##
#Returns a Imgrb::Headers::PngHeader
def get_data
data = @data.unpack("C*")
width = Shared::interpret_bytes_4(data[0..3])
height = Shared::interpret_bytes_4(data[4..7])
bit_depth = data[8]
color_type = data[9]
compression = data[10]
filter = data[11]
interlace = data[12]
return Imgrb::Headers::PngHeader.new(width, height,
bit_depth, compression,
color_type, filter, interlace)
end
end
#Instances of this class represent PLTE chunks. This chunk contains the
#palette data for those color types that require (or allow) it.
class ChunkPLTE
include AbstractChunk, Critical, Public
def self.type #:nodoc:
"PLTE"
end
##
#Returns array of palette bytes
def get_data
return @data.unpack("C*")
end
private
def when_read(data)
#Should also check that size does not exceed maximum (depends on image type)
if data.size < 1
raise Exceptions::ChunkError, "The palette chunk is empty"
end
end
end
#Instances of this class represent IEND chunks. This chunk must appear last
#in a PNG file. It marks the end of the datastream.
class ChunkIEND
include AbstractChunk, Critical, Public
def self.type #:nodoc:
"IEND"
end
##
#The IEND chunk does not contain any data.
def get_data
return nil
end
end
#Instances of this class represent CgBI chunks. Files containing this are
#probably not valid png file, but a proprietary, png-like image format.
class ChunkCgBI
include AbstractChunk, Critical, Private
def self.type #:nodoc:
"CgBI"
end
private
def when_read(data)
warn "CgBI chunk present. This is probably a CgBI-file, which may"\
" cause problems, since it is posing as a png-file but is invalid."
end
end
register_chunks(ChunkIDAT, ChunkIHDR, ChunkPLTE, ChunkIEND,
ChunkCgBI)
end
end
| true
|
ff1cb141977e33285b1c92462b08b7b543ee3f25
|
Ruby
|
nao58/ruby-tora-no-ana
|
/works/20140514/validator/method.rb
|
UTF-8
| 660
| 2.75
| 3
|
[] |
no_license
|
# encoding: utf-8
class Validator::Method
def self.custom setting, key_name, value
setting.call key_name, value
end
def self.min_length setting, key_name, value
"#{key_name}は#{setting}文字以上にしてください" unless setting <= value.size
end
def self.max_length setting, key_name, value
end
def self.regexp setting, key_name, value
end
def self.numeric setting, key_name, value
"#{key_name}には数値を指定してください" unless value =~ /^[0-9]+$/
end
def self.min setting, key_name, value
"#{key_name}は#{setting}以上である必要があります" unless value.to_i >= setting
end
end
| true
|
1377f58b29a4b935284849595495a3fac8e24785
|
Ruby
|
DouglasAllen/Rails-projects
|
/using_script/Rit-master/config/initializers/monkeypatches.rb
|
UTF-8
| 174
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
module QuantizeTime
def quantized_to_hour
self.change(:min => 0, :sec => 0)
end
end
class Time
include QuantizeTime
end
class DateTime
include QuantizeTime
end
| true
|
d81770ea1653c0a4e4057ac71b639a69fe79608c
|
Ruby
|
richmit/ex-ruby
|
/hashOfArray.rb
|
UTF-8
| 2,516
| 4.03125
| 4
|
[] |
no_license
|
#!/usr/local/bin/ruby
##
# @file hashOfArray.rb
# @author Mitch Richling <https://www.mitchr.me/>
# @Copyright Copyright 2006 by Mitch Richling. All rights reserved.
# @brief Building up a hash of arrays.@EOL
# @Keywords ruby example hash array perl
# @Std Ruby 1.8
#
# A common Perl idiom is to use a hash of arrays to
# categorize data -- the hash is built up as new data
# categories are discovered, and data is pushed onto the
# arrays for the appropriate category. This example
# program shows a few Ruby recipes for doing the same
# thing.
#
# See the hashOfCounts.rb example too.
data = [ [1, 2], [1, 3], [4, 5] ]
# Probably the most verbose way to do it..
aHash=Hash::new
data.each do |x,y|
if aHash.member?(x) then # Note: aHash.member?(x) == !aHash[x].nil?
aHash[x].push(y)
else
aHash[x] = Array.new(1, y) # or 'Array.new.push(y)', or '[ y ]'
end
end
puts("===============")
aHash.each do |x,y|
puts("#{x} : #{y.inspect}")
end
# This is a common ruby idiom
aHash=Hash::new
data.each do |x,y|
(aHash[x] ||= []).push(y) # Same as: aHash[x] = (aHash[x] || []); aHash[x].push(y)
end
puts("===============")
aHash.each do |x,y|
puts("#{x} : #{y.inspect}")
end
# The following is a rather perl-ish way to get it done. This example
# depends upon the fact that + creates a NEW object, and that + also
# concatenates arrays.
aHash=Hash.new(Array.new)
data.each do |x,y|
aHash[x] += Array.new(1, y)
end
puts("===============")
aHash.each do |x,y|
puts("#{x} : #{y.inspect}")
end
# WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING
# WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING
# WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING
#
# The following code doesn't do what you might expect!!!!
#
# aHash=Hash.new(Array.new) means that every time we evaluate
# aHash[foo] when foo is not already a key, we get the Array.new
# object specified in the constructor -- we get precisely that object,
# and not a copy. In the following code, we keep pushing y onto the
# array given in the constructor -- so if we evaluate aHash[foo] we
# get an array containing the values we pushed on! For this reason,
# the following code doesn't do what most Perl programmers expect.
aHash=Hash.new(Array.new)
data.each do |x,y|
aHash[x].push(y)
end
puts("===============")
aHash.each do |x,y|
puts("#{x} : #{y.inspect}")
end
puts("aHash[0]=#{aHash[0].inspect}")
| true
|
7a5c94ab6b6db5e91f93f87484c59fa06742504c
|
Ruby
|
colindeclue/adventofcode2019
|
/Day4/Day4.rb
|
UTF-8
| 1,186
| 3.28125
| 3
|
[] |
no_license
|
def qualifiesPart2(toCheck)
toCheck = toCheck.to_s
decreasing = true
hasDouble = false
groupCount = 0
for i in 1..toCheck.length - 1
if toCheck[i] == toCheck[i-1]
groupCount = groupCount + 1
else
if groupCount == 1
hasDouble = true
end
groupCount = 0
if toCheck[i] < toCheck[i-1]
return false
end
end
end
return hasDouble || groupCount == 1
end
def qualifies(toCheck)
toCheck = toCheck.to_s
decreasing = true
hasDouble = false
for i in 1..toCheck.length - 1
if toCheck[i] == toCheck[i-1]
hasDouble = true
elsif toCheck[i] < toCheck[i-1]
return false
end
end
return hasDouble
end
def Day4()
puts qualifiesPart2(111144)
part1Count = 0
part2Count = 0
for test in 256310..732737 do
if qualifies(test)
part1Count = part1Count + 1
if qualifiesPart2(test)
part2Count = part2Count + 1
end
end
end
puts "Part1: #{part1Count}"
puts "Part2: #{part2Count}"
end
| true
|
c0a7798b55617834ae29318b8b4e48d9f8f3398c
|
Ruby
|
ThuyNT13/data_structures
|
/tests/spec/linked_list_spec.rb
|
UTF-8
| 3,282
| 3.4375
| 3
|
[
"MIT"
] |
permissive
|
require_relative 'spec_helper'
describe LinkedList do
let(:my_list) { LinkedList.new }
let(:empty_list) { LinkedList.new }
before do
my_list.add("thing_1")
my_list.add("thing_2")
my_list.add("thing_3")
end
describe '#add' do
it 'adds an element to the end of the list' do
my_list.add("thing_4")
expect(my_list.get(3)).to eq("thing_4")
end
it 'returns the element added' do
expect(my_list.add("thing_4")).to eq("thing_4")
end
it 'grows indefinitely' do
4.upto(15).each do |i|
my_list.add("thing_#{i}")
end
expect(my_list.length).to eq(15)
end
end
describe '#get' do
it 'returns element at specified index' do
expect(my_list.get(0)).to eq("thing_1")
expect(my_list.get(1)).to eq("thing_2")
expect(my_list.get(2)).to eq("thing_3")
end
it 'throws error if no element exists at specified index' do
expect { my_list.get(3) }
.to raise_error(NoSuchElementError)
end
end
describe '#set' do
it 'replaces element at the specified index' do
my_list.set(1, "new_thing")
expect(my_list.get(1)).to eq("new_thing")
end
it 'throws error if no element exists at specified index' do
expect { my_list.set(3, "new_thing") }
.to raise_error(NoSuchElementError)
end
end
describe '#length' do
it 'returns number of items in list' do
expect(my_list.length).to eq(3)
my_list.add("thing_4")
expect(my_list.length).to eq(4)
end
end
describe '#first' do
it 'returns the first element' do
expect(my_list.first).to eq("thing_1")
end
it 'throws an error if the list is empty' do
expect { empty_list.first }
.to raise_error(NoSuchElementError)
end
end
describe '#last' do
it 'returns the last element' do
expect(my_list.last).to eq("thing_3")
end
it 'throws an error if the list is empty' do
expect { empty_list.last }
.to raise_error(NoSuchElementError)
end
end
describe '#insert' do
it 'adds element with specified value at the specified index' do
my_list.insert(1, "new_thing")
expect(my_list.get(0)).to eq("thing_1")
expect(my_list.get(1)).to eq("new_thing")
expect(my_list.get(2)).to eq("thing_2")
expect(my_list.get(3)).to eq("thing_3")
end
it 'throws error if no element exists at specified index' do
expect { my_list.insert(3, "new_thing") }
.to raise_error(OutOfBoundsError)
end
it "can insert at the front of the list" do
my_list.insert(0, "new_thing")
expect(my_list.get(0)).to eq("new_thing")
expect(my_list.get(1)).to eq("thing_1")
expect(my_list.get(2)).to eq("thing_2")
expect(my_list.get(3)).to eq("thing_3")
end
it "can insert at the front of the list even if the list is empty" do
empty_list.insert(0, "hello")
expect(empty_list.get(0)).to eq("hello")
expect(empty_list.length).to eq(1)
end
end
describe '#find' do
it "returns element" do
expect(my_list.find("thing_3")).to eq("thing_3")
end
it "throws error if no element was found" do
expect { my_list.find("something") }.to raise_error(NoElementFound)
end
end
end
| true
|
6b6538cdf2478f3c49d2015fd8b3595c5ffaa6fa
|
Ruby
|
shoutout-team/shoutout-app-api
|
/app/services/app_logger.rb
|
UTF-8
| 756
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
class AppLogger
attr_accessor :logger
def self.init(name = :app, custom_log_file_name = nil)
new(name, custom_log_file_name).logger
end
def initialize(name, custom_log_file_name)
@log_name = name.to_s
@custom_log_file_name = custom_log_file_name
create_log_file
@logger = Logger.new(log_file, 'weekly')
@logger.formatter = Logger::Formatter.new
@logger.progname = @log_name
end
def create_log_file
return if File.exist?(log_file)
require 'fileutils'
FileUtils.mkdir_p(log_path)
end
def log_file_name
@custom_log_file_name || @log_name
end
def log_path
Rails.root.join('log', @log_name)
end
def log_file
Rails.root.join('log', @log_name, "#{log_file_name}.log")
end
end
| true
|
ade3c984d4606a07c2d8b51c52e1ea2516c140ae
|
Ruby
|
santiagolv/rps_rcav
|
/app/controllers/game_controller.rb
|
UTF-8
| 2,155
| 2.640625
| 3
|
[] |
no_license
|
class GameController < ApplicationController
def user_plays_rock
moves = ["Rock","Paper","Scissors"]
@computer_move = moves.sample
if @computer_move == "Rock"
@img_url ="http://localhost:3000/assets/images/rock.png"
elsif @computer_move =="Paper"
@img_url="http://localhost:3000/assets/images/paper.png"
elsif @computer_move=="Scissors"
@img_url="http://localhost:3000/assets/images/scissors.png"
end
if @computer_move=="Rock"
@result="You tied!"
@label="label label-success"
elsif @computer_move=="Scissors"
@result="You won!"
@label="label label-success"
else
@result="You lost!"
@label="label label-danger"
end
render("game/play_rock.html.erb")
end
def user_plays_paper
moves = ["Rock","Paper","Scissors"]
@computer_move = moves.sample
if @computer_move == "Rock"
@img_url ="http://localhost:3000/assets/images/rock.png"
elsif @computer_move =="Paper"
@img_url="http://localhost:3000/assets/images/paper.png"
elsif @computer_move=="Scissors"
@img_url="http://localhost:3000/assets/images/scissors.png"
end
if @computer_move=="Rock"
@result="You won!"
@label="label label-success"
elsif @computer_move=="Scissors"
@result="You lost!"
@label="label label-danger"
else
@result="You tied!"
@label="label label-success"
end
render("game/play_paper.html.erb")
end
def user_plays_scissors
moves = ["Rock","Paper","Scissors"]
@computer_move = moves.sample
if @computer_move == "Rock"
@img_url ="http://localhost:3000/assets/images/rock.png"
elsif @computer_move =="Paper"
@img_url="http://localhost:3000/assets/images/paper.png"
else @img_url="http://localhost:3000/assets/images/scissors.png"
end
if @computer_move=="Rock"
@result="You lost!"
@label="label label-danger"
elsif @computer_move=="Scissors"
@result="You tied!"
@label="label label-success"
else
@result="You won!"
@label="label label-success"
end
render("game/play_scissors.html.erb")
end
end
| true
|
8de11b4898c094aed529884f14b48ffd9a105080
|
Ruby
|
1anchen/Code_Clan_Student
|
/specs/codeclan_student_spec.rb
|
UTF-8
| 916
| 2.984375
| 3
|
[] |
no_license
|
require("minitest/autorun")
require("minitest/rg")
require_relative("../codeclan_student")
class TestCodeclanStudent < MiniTest::Test
def setup
@student = Student.new("David", 21)
end
def test_get_student__name
new_student = @student
assert_equal("David", new_student.get_student_name())
end
def test_get_student__cohort
new_student = @student
assert_equal(21, new_student.get_student_cohort())
end
def test_set_student__name
new_student = @student
assert_equal("Phil", new_student.set_student_name("Phil"))
end
def test_set_student__cohort
new_student = @student
assert_equal(20, new_student.set_student_cohort(20))
end
def test_student_talk
new_student = @student
assert_equal("I want to Jump!!!", new_student.student_talk())
end
def test_student_favourite_language
new_student = @student
assert_equal("I love Ruby", new_student.student_favourite_language("Ruby"))
end
end
| true
|
ae290b05f5f5ca5ed335616497e1a9501fe3e424
|
Ruby
|
micahshute/rbtech
|
/spec/binary_tree_spec.rb
|
UTF-8
| 3,182
| 2.921875
| 3
|
[
"MIT"
] |
permissive
|
RSpec.describe Rbtech::BinaryTree do
let(:bt) do
r = Random.new
bta = Array.new(100) do
r.rand(1000)
end
described_class.new(nodes: bta)
end
describe "#root" do
it "returns the correct value" do
expect(bt.root).to eq(bt.nodes.first)
end
end
describe "#size" do
it "correctly returns the size of the binary tree" do
expect(bt.size).to eq(bt.nodes.length)
end
end
describe "#add" do
it "correctly adds a node at the bottom of the tree" do
last_node = bt.nodes.last
node_to_add = last_node + 5
bt.add(node_to_add)
expect(bt.nodes.last).to eq(node_to_add)
end
end
describe "#update" do
it "correclty updates a given node" do
r = Random.new
nth_node = r.rand(bt.nodes.length)
nth_value = bt.nodes[nth_node]
bt.update(index: nth_node, to: nth_value - 10)
expect(bt.nodes[nth_node]).to eq(nth_value - 10)
end
end
describe "#right_child_index" do
it "correctly calculates the right child index" do
r = Random.new
parent = r.rand(25)
expect(bt.right_child_index(parent)).to eq(parent * 2 + 2)
end
it "returns nil if there is no right child" do
parent = 80
expect(bt.right_child_index(parent)).to be(nil)
end
end
describe "#left_child_index" do
it "correctly calculates the left child index" do
r = Random.new
parent = r.rand(25)
expect(bt.left_child_index(parent)).to eq(parent * 2 + 1)
end
it "returns nil if there is no left child" do
parent = 80
expect(bt.left_child_index(parent)).to be(nil)
end
end
describe "#right_child" do
it "correctly calculates the right child" do
r = Random.new
parent = r.rand(25)
expect(bt.right_child(parent)).to eq(bt.nodes[parent * 2 + 2])
end
it "returns nil if there is no right child" do
parent = 80
expect(bt.right_child(parent)).to be(nil)
end
end
describe "#left_child" do
it "correctly calculates the left child" do
r = Random.new
parent = r.rand(25)
expect(bt.left_child(parent)).to eq(bt.nodes[parent * 2 + 1])
end
it "returns nil if there is no left child" do
parent = 80
expect(bt.left_child(parent)).to be(nil)
end
end
describe "#parent_index" do
it "correctly calculates the parent index" do
r = Random.new
child = r.rand(99) + 1
expect(bt.parent_index(child)).to eq((child - 1) / 2)
end
it "returns nil if there is no parent" do
expect(bt.parent_index(0)).to eq(nil)
end
it "returns nil for a child which does not exist" do
expect(bt.parent_index(bt.nodes.length)).to eq(nil)
end
end
describe "#parent" do
it "correctly calculates the parent" do
r = Random.new
child = r.rand(99) + 1
expect(bt.parent(child)).to eq(bt.nodes[bt.parent_index(child)])
end
it "returns nil if there is no parent" do
expect(bt.parent(0)).to eq(nil)
end
it "returns nil for a child which does not exist" do
expect(bt.parent(bt.nodes.length)).to eq(nil)
end
end
end
| true
|
777a1bf16e482173b834079c1b46f6baf2428b3f
|
Ruby
|
webdevoir/eefio-api
|
/app/services/transaction_extractor_service.rb
|
UTF-8
| 4,479
| 2.75
| 3
|
[
"CC0-1.0",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
class TransactionExtractorService
class << self
def extract_transactions_from raw_block:
puts "==> Extracting Transactions from RawBlock: #{raw_block.block_number}"
# Work with just the RawBlock’s content JSON blob
raw_block_content = JSON.parse(raw_block.content).with_indifferent_access
# Find the associated Block
block = Block.find_by block_number: raw_block.block_number
# Get the Transactions out of the RawBlock’s content hash
raw_transactions = raw_block_content['transactions']
# Ensure that BOTH happen together:
# The Transactions are created and the RawBlock is updated
Transaction.transaction do
raw_transactions.each do |raw_transaction|
raw_transaction = raw_transaction.with_indifferent_access
# Create a new empty Transaction object
transaction = block.transactions.new
# Add associated Block values
transaction.block_address = block.address
transaction.block_number = block.block_number
transaction.block_number_in_hex = block.block_number_in_hex
# TODO: extract token info from events/topics
# string token_sent_name:
# string token_sent_symbol:
# string token_sent_address:
# string token_sent_amount_in_hex:
# decimal token_sent_amount:
# Keys (on the left) are Transaction attributes (columns in the database on the transactions table)
# Values (on the right) are RawBlock.content attributes (keys in the JSON blob)
# Walk through each pair and save the value from the JSON blob into the new Transaction object
# Don’t convert value at all
{
address: :hash,
eth_sent_in_wei_in_hex: :value,
from: :from,
gas_price_in_wei_in_hex: :gasPrice,
gas_provided_in_hex: :gas,
index_on_block_in_hex: :transactionIndex,
input: :input,
nonce_in_hex: :nonce,
r: :r,
s: :s,
to: :to,
v_in_hex: :v
}.each do |transaction_attr, raw_transaction_attr|
transaction.send("#{transaction_attr}=", raw_transaction[raw_transaction_attr])
end
# Keys (on the left) are Block attributes (columns in the database on the blocks table)
# Values (on the right) are RawBlock.content attributes (keys in the JSON blob)
# Walk with each pair and save the value from the JSON blob into the new Block object
# Convert value from hexadecimal to an integer
{
eth_sent_in_wei: :value,
gas_price_in_wei: :gasPrice,
gas_provided: :gas,
index_on_block: :transactionIndex,
nonce: :nonce,
v: :v
}.each do |transaction_attr, raw_transaction_attr|
transaction.send("#{transaction_attr}=", raw_transaction[raw_transaction_attr].from_hex)
end
# Transaction#published_at is a special case because it’s stored as DateTime object
transaction.published_at = block.published_at
transaction.published_at_in_seconds_since_epoch = block.published_at_in_seconds_since_epoch
transaction.published_at_in_seconds_since_epoch_in_hex = block.published_at_in_seconds_since_epoch_in_hex
# Save the Block to the database
transaction.save
puts "+++ Saved Transaction: #{transaction.block_number} [#{transaction.index_on_block}]" if transaction.created_at.present?
end
# Mark the associated RawBlock that its Transactions data has been extracted
raw_block.update transactions_extracted_at: Time.current
end
end
def transactions_all_extracted?
RawBlock.with_unextracted_transactions.blank?
end
def update_transactions_extracted_up_to_block_number_setting! block_number:
setting = Setting.transactions_extracted_up_to_block_number
return if setting.content.to_i == block_number
puts "+++ Updated Setting: transactions_extracted_up_to_block_number: #{block_number}"
puts
setting.update content: block_number.to_i
end
end
end
| true
|
b0948ce88d5ebbc3c891442abf16dc56a8d2586c
|
Ruby
|
jasonleibowitz/coffeetalk_app
|
/spec/models/user_spec.rb
|
UTF-8
| 2,406
| 2.515625
| 3
|
[] |
no_license
|
require_relative '../spec_helper.rb'
describe User do
before :each do
@jason = User.new(first_name: "Jason", last_name: "Leibowitz", email: "leibo@gmail.com", dob: "1987-02-26", zipcode: "11201", admin: true, profile_pic: 'http://i.imgur.com/5z5NbX5.jpg', password: "hijesse", password_confirmation: "hijesse", about: "meh")
@jason.save
@steph = User.new(first_name: "Stephanie", last_name: "Eagle", email: "stepheagle@gmail.com", dob: "1990-09-01", zipcode: "10009", admin: false, profile_pic: "https://scontent-a-lga.xx.fbcdn.net/hphotos-ash2/t1.0-9/400523_4892829593917_1295297482_n.jpg", password: "password", password_confirmation: "password", about: "hi")
@steph.save
interest_array = ["Premier League Soccer", "American Politics", "Israel"]
interest_array.each do |interest|
Interest.create(name: interest, description: "tbd")
end
end
it { should validate_presence_of :first_name }
it { should validate_presence_of :last_name }
it { should validate_presence_of :email }
it { should validate_presence_of :dob }
it { should validate_presence_of :zipcode }
it { should validate_presence_of :profile_pic }
it { should validate_presence_of :about }
it { should validate_confirmation_of :password }
it { should validate_numericality_of(:zipcode).is_equal_to(5) }
it { should validate_uniqueness_of :email }
it { should have_many :requests }
it { should have_many(:meetings).through(:requests)}
describe "#age" do
it "gives the age from a birthdate" do
expect(@jason.age).to eq 27
end
end
describe "#latlon" do
it "converts the user's zipcode to latitude and longetude coordinate" do
expect(@jason.latlon.join(",")).to eq "40.695286,-73.98907"
end
end
describe "#haversine" do
it "take two users and return the distance in miles between them" do
expect(@jason.haversine(@jason.zipcode.to_lat.to_f, @jason.zipcode.to_lon.to_f, @steph.zipcode.to_lat.to_f, @steph.zipcode.to_lon.to_f)).to eq 2.264662447047386
end
end
describe "#update_interests" do
it "updates the current users interests based on params" do
params = {"utf8"=>"✓", "authenticity_token"=>"ARz5l32SBtc8RJqtzAKLSS9B64Ct5t+JcYja/aJhIjs=", "Premier League Soccer"=>"1", "American Politics"=>"1", "StartUp"=>"1", "Israel"=>"1", "commit"=>"Save changes"}
@jason.update_interests(params)
expect(@jason.interests).to have(3).items
end
end
end
| true
|
4fc263549fa03bebab1a2588cadcff64bca65c38
|
Ruby
|
izumichika/practice
|
/practiceReviewApp.rb
|
UTF-8
| 1,545
| 3.671875
| 4
|
[] |
no_license
|
def post_review(a_posts)
post = {}
puts "ジャンルを入力してください:"
post[:genre] = gets.chomp
puts "タイトルを入力してください:"
post[:title] = gets.chomp
puts "感想を入力してください:"
post[:review] = gets.chomp
line = "----------------------"
puts "ジャンル : #{post[:genre]}\n#{line}"
puts "タイトル : #{post[:title]}\n#{line}"
puts "感想 : \n#{post[:review]}\n#{line}"
a_posts << post
end
def read_review(a_posts)
if a_posts.empty?
puts "レビューが登録されていません"
else
puts "見たいレビューを選択してください"
number = 0
a_posts.each do |p|
puts "[#{number}] : #{p[:title]}のレビュー"
number += 1
end
input = gets.to_i
if input > a_posts.length
puts "その番号は登録されていません"
else
post = a_posts[input]
line = "----------------------"
puts "ジャンル : #{post[:genre]}\n#{line}"
puts "タイトル : #{post[:title]}\n#{line}"
puts "感想 : \n#{post[:review]}\n#{line}"
end
end
end
def end_program
exit
end
def exception
puts "入力された値は無効です"
end
posts = []
while true do
puts "レビュー数 : #{posts.length}"
puts "[0]レビューを書く\n[1]レビューを読む\n[2]アプリを終了する"
input = gets.to_i
if input == 0
posts = post_review(posts)
elsif input == 1
read_review(posts)
elsif input == 2
end_program
else
exception
end
end
| true
|
75b0874e1f0cb0f02b0cab6e176202feee6e6609
|
Ruby
|
h-z/positionable
|
/test/test_positionable.rb
|
UTF-8
| 4,475
| 2.875
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
require 'active_record'
#require "positionable"
require 'helper'
ActiveRecord::Migration.verbose = false
ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :database => ":memory:")
def setup_db
ActiveRecord::Schema.define(:version => 1) do
create_table :children do |t|
t.column :pos, :integer
t.column :parent_id, :integer
t.column :parent_type, :string
t.column :created_at, :datetime
t.column :updated_at, :datetime
end
end
end
def create_instances
1.upto(10).each {|t| ChildList.create! :pos => t, :parent_id => 5 }
11.upto(18).each {|t| ChildList.create! :pos => t-10, :parent_id => 3 }
19.upto(23).each {|t| ChildList.create! :pos => t-8, :parent_id => 5 }
end
def teardown_db
ActiveRecord::Base.connection.tables.each do |table|
ActiveRecord::Base.connection.drop_table(table)
end
end
class Child < ActiveRecord::Base
end
class Parent
@@instances = {}
def self.create id
return @@instances[id] unless @@instances[id].nil?
@@instances[id] = Parent.new(id)
@@instances[id]
end
def initialize _id
@id = _id
end
def children
ChildList.where(:parent_id => @id)
end
end
class ChildList < Child
positionable :position_column => :pos, :parent => :parent, :siblings => :children
def self.table_name() "children" end
def parent
Parent.create(parent_id)
end
end
class TestPositionable < Test::Unit::TestCase
context "initials" do
setup do
setup_db
create_instances
@child = ChildList.create! :pos => 1, :parent_id => 1
end
teardown do
teardown_db
end
should "work" do
assert_equal ChildList.find(3).parent, ChildList.find(5).parent
assert_not_equal ChildList.find(3).parent, ChildList.find(15).parent
assert_equal Parent.create(5).children.size, 10+5
assert_equal Parent.create(3).children.size, 8
assert_equal @child.parent.children.size, 1
end
end
end
class TestPositionable1 < Test::Unit::TestCase
context "positionable" do
setup do
setup_db
create_instances
@child = ChildList.find(2)
end
teardown do
teardown_db
end
should "reposition on demand" do
@child.reposition(5)
assert_equal @child.pos, 5
end
end
end
class TestPositionable2 < Test::Unit::TestCase
context "repositioned object" do
setup do
setup_db
create_instances
@child = ChildList.find(13)
@parent = Parent.create 3
end
teardown do
teardown_db
end
should "position to 14" do
assert_equal [1, 2, 3, 4, 5, 6, 7, 8], @parent.children.collect {|c| c.pos}
@child.reposition(14)
assert_equal [1, 2, 14, 3, 4, 5, 6, 7], @parent.children.collect {|c| c.pos}
end
should "position to 20" do
@child = @parent.children.first
assert_equal [1, 2, 3, 4, 5, 6, 7, 8], @parent.children.collect {|c| c.pos}
@child.reposition(20)
assert_equal [20, 1, 2, 3, 4, 5, 6, 7], @parent.children.collect {|c| c.pos}
end
should "positions to 20 from last" do
@child = @parent.children.last
assert_equal [1, 2, 3, 4, 5, 6, 7, 8], @parent.children.collect {|c| c.pos}
@child.reposition(20)
assert_equal [1, 2, 3, 4, 5, 6, 7, 20], @parent.children.collect {|c| c.pos}
end
should "remain at the same position" do
@child = @parent.children.last
assert_equal [1, 2, 3, 4, 5, 6, 7, 8], @parent.children.collect {|c| c.pos}
@child.reposition(@child.pos)
assert_equal [1, 2, 3, 4, 5, 6, 7, 8], @parent.children.collect {|c| c.pos}
end
should "remain at the same position after reposition again" do
assert_equal [1, 2, 3, 4, 5, 6, 7, 8], @parent.children.collect {|c| c.pos}
@child.reposition(20)
assert_equal [1, 2, 20, 3, 4, 5, 6, 7], @parent.children.collect {|c| c.pos}
@child.reposition(3)
assert_equal [1, 2, 3, 4, 5, 6, 7, 8], @parent.children.collect {|c| c.pos}
end
end
end
| true
|
26448e779e997e4ea455c28aaba8516778634d00
|
Ruby
|
fcnaud/leetcode-train
|
/144_binary_tree_preorder_traversal.rb
|
UTF-8
| 240
| 3
| 3
|
[] |
no_license
|
#!/usr/bin/ruby
def travel(root, arr)
if root
arr.push(root.val)
travel(root.left, arr)
travel(root.right, arr)
end
end
def preorder_traversal(root)
ret = Array.new
travel(root, ret)
return ret
| true
|
48dc24bc2f00db322610e38ad3f12a91ec4f4f21
|
Ruby
|
loganthomison/indivo_sample_surveys_app
|
/lib/basic_client/null_logger.rb
|
UTF-8
| 361
| 2.78125
| 3
|
[
"Apache-2.0"
] |
permissive
|
class NullLogger
# Class that implements the most popular parts of the Logger API, but just
# throws away the messages. Allows us to log things without having to
# check if @logger is set first.
def initialize(*args) end
def debug(msg) end
def info(msg) end
def warn(msg) end
def error(msg) end
def fatal(msg) end
def unknown(msg) end
end
| true
|
eb87a78af28f864f3dae02dc11e69921385182d8
|
Ruby
|
mkneale/Oystercards1
|
/lib/oystercard.rb
|
UTF-8
| 598
| 3.390625
| 3
|
[] |
no_license
|
class Oystercard
MAXIMUM_BALANCE = 90
MINIMUM_FARE = 1
attr_accessor :balance, :journey
def initialize
@balance = 0
@journey = false
end
def top_up(amount)
fail ("Maximum balance of 90 exceeded") if amount + balance > MAXIMUM_BALANCE
@balance += amount
end
def deduct_money(fare)
@balance -= fare
end
def in_journey?
@journey
end
def touch_in
fail ("Too little balance. Card now has a balance of #{balance}") if balance < MINIMUM_FARE
@journey = true
end
def touch_out
@balance -= MINIMUM_FARE
@journey = false
end
end
| true
|
a8dbd2805f8f2afc67506e70fea693f0206e1a80
|
Ruby
|
L-A-Davis/OO-mini-project-web-112017
|
/tools/console.rb
|
UTF-8
| 3,047
| 2.609375
| 3
|
[] |
no_license
|
require_relative "../config/environment.rb"
matt = User.new("matt")
alison = User.new("alison")
avi = User.new("avi")
carrot_cake = Recipe.new("carrot_cake")
pumpkin_pie = Recipe.new("pumpkin_pie")
coffee = Recipe.new("coffee")
ice_cream = Recipe.new("ice_cream")
stir_fry = Recipe.new("stir_fry")
carrot = Ingredient.new("carrot")
flour = Ingredient.new("flour")
egg = Ingredient.new("egg")
pumpkin = Ingredient.new("pumpkin")
sugar = Ingredient.new("sugar")
butter = Ingredient.new("butter")
coffee_beans = Ingredient.new("coffee_beans")
water = Ingredient.new("water")
milk = Ingredient.new("milk")
chocolate = Ingredient.new("chocolate")
rice = Ingredient.new("rice")
veggies = Ingredient.new("veggies")
soy_sauce = Ingredient.new("soy_sauce")
alison_carrot = alison.add_recipe_card(carrot_cake, "2017-11-30", 10)
alison_ice_cream = alison.add_recipe_card(ice_cream, "1917-11-03", 12)
avi_ice_cream = avi.add_recipe_card(ice_cream,"2030-4-12", 8)
avi_fry = avi.add_recipe_card(stir_fry, "2001-12-25", 7)
matt_pumpkin = matt.add_recipe_card(pumpkin_pie, "2017-11-20", 10)
matt_carrot = matt.add_recipe_card(carrot_cake, "2017-11-26", 10)
matt_coffee = matt.add_recipe_card(coffee, "2000-01-11", 6)
#matt_ice_cream = matt.add_recipe_card(ice_cream, "1993-03-24", 9)
carrot_cake_ing = carrot_cake.add_ingredients([carrot,flour,egg,sugar])
pumpkin_pie_ing = pumpkin_pie.add_ingredients([pumpkin,sugar,butter,flour])
coffee_ing = coffee.add_ingredients([coffee_beans,water,milk])
ice_cream_ing = ice_cream.add_ingredients([milk,chocolate,sugar])
stir_fry_ing = stir_fry.add_ingredients([veggies,rice,soy_sauce])
matt_rice = matt.declare_allergen(rice)
avi_milk = avi.declare_allergen(milk)
matt_flour = matt.declare_allergen(flour)
alison_rice = alison.declare_allergen(rice)
example = RecipeIngredient.all[4] #shows recipe ingredient stuff works
apple_pie = Recipe.new("Apple Pie")
fries = Recipe.new("French Fries")
beef = Recipe.new("Steak")
icecream = Recipe.new("Ice Cream")
lindsay = User.new("lindsay")
sam = User.new("Sam")
lindsay.add_recipe_card(apple_pie, 3)
garry = User.new("Garry")
lindsay.add_recipe_card(beef, 2)
sam.add_recipe_card(beef, 3)
garry.add_recipe_card(apple_pie, 2)
garry.add_recipe_card(fries, 3)
garry.add_recipe_card(beef, 5)
garry.add_recipe_card(icecream, 4)
test1 = garry.top_three_recipes
# test1 = Recipe.recipe_names
# test2 = Recipe.find_max
salt = Ingredients.new("salt")
flour = Ingredients.new("flour")
butter = Ingredients.new("butter")
sugar = Ingredients.new("sugar")
apples = Ingredients.new("apples")
cream = Ingredients.new("Cream")
pepper = Ingredients.new("Pepper")
broth = Ingredients.new("broth")
array = [salt, flour, butter, sugar]
array2 = [apples, cream]
apple_pie.add_ingredients(array)
beef.add_ingredients([pepper, broth])
apple_pie.add_ingredients(array2)
test3 = apple_pie.ingredients
garry.declare_allergen(apples)
garry.declare_allergen(cream)
lindsay.declare_allergen(apples)
lindsay.declare_allergen(flour)
apple_pie.allergens
garry.safe_recipies
binding.pry
| true
|
d90943e5ca0bb3a74947e7ba731339fe7ea9c34f
|
Ruby
|
roybapy/rails03
|
/script/sqlite/has_image.rb
|
UTF-8
| 690
| 2.609375
| 3
|
[] |
no_license
|
#!/usr/bin/env ruby
def has_img(c1, c2)
puts c1
puts c2
begin
db=SQLite3::Database.new("db/development.sqlite3")
puts "database started"
rs=db.execute("SELECT city FROM cityimg where city='#{c2}'")
puts rs
if rs[0] != nil
rs0=db.execute("SELECT thumb FROM cityimg where city='#{c2}'")
db.execute"update topdeals set imgl='#{rs0[0][0]}' where stop='#{c2}'"
rs1=db.execute("SELECT banner FROM cityimg where city='#{c2}'")
db.close
puts "inside0"
if rs1[0][0] == nil
puts "inside"
google_image_banner(c1, c2)
end
else
db.close
google_image(c1, c2)
google_image_banner(c1, c2)
end
rescue Exception => e
puts c1+c2
puts e
return r0
ensure
db.close if db
end
end
| true
|
ebfd74f3a1304da4fddfd3933dcd06a21adab1da
|
Ruby
|
TomasMacikas/RubyApp
|
/specOld/instance_checker_spec.rb
|
UTF-8
| 2,048
| 2.78125
| 3
|
[] |
no_license
|
require 'spec_helper'
describe InstanceChecker do
context 'initial data ' do
let(:number1) { described_class.new(10_000) }
let(:number2) { described_class.new(100) }
let(:float1) { described_class.new(1.3) }
let(:nil1) { described_class.new(nil) }
let(:string1) { described_class.new('string') }
let(:array1) { described_class.new([]) }
let(:bool1) { described_class.new(true) }
let(:bool2) { described_class.new(false) }
it 'instance_checker successfully then 10000' do
expect(number1.number_is_right?).to eq true
end
it 'delete instance_checker successful then 10' do
expect(number2.number_is_right?).to eq true
end
it 'delete instance_checker successful then not string' do
expect(string1.number_is_right?).to eq false
end
it 'delete instance_checker successful then not float' do
expect(float1.number_is_right?).to eq false
end
it 'delete instance_checker successful then not nil' do
expect(nil1.number_is_right?).to eq false
end
it 'valid to use' do
expect(array1.check_or_array).to eq true
end
it 'not valid for zero' do
expect(number1.check_or_array).to eq false
end
it 'not valid for string' do
expect(string1.check_or_array).to eq false
end
it 'not valid for bool' do
expect(bool1.check_or_array).to eq false
end
it 'not valid for nil' do
expect(nil1.check_or_array).to eq false
end
it 'text is valid' do
expect(string1.check_or_string_valid?).to eq true
end
it 'text is not valid 2' do
expect(number2.check_or_string_valid?).to eq false
end
it 'text is not valid 3' do
expect(bool1.check_or_string_valid?).to eq false
end
it 'text is not valid 4' do
expect(bool2.check_or_string_valid?).to eq false
end
it 'text is not valid 5' do
expect(array1.check_or_string_valid?).to eq false
end
it 'text is not valid 6' do
expect(number1.check_or_string_valid?).to eq false
end
end
end
| true
|
d2f825618694103fe1c0757e7c0c1b49685ee74e
|
Ruby
|
steveoro/goggles_core
|
/app/models/edition_type.rb
|
UTF-8
| 1,320
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
require 'drop_down_listable'
require 'localizable'
class EditionType < ApplicationRecord
include DropDownListable
include Localizable
validates :code, presence: { length: { maximum: 1 }, allow_nil: false }
validates :code, uniqueness: { message: :already_exists }
# ----------------------------------------------------------------------------
# Unique code used inside the DB to address the "Ordinal"-type row
ORDINAL_CODE = 'O'
# Unique ID used inside the DB to address the "Ordinal"-type row
ORDINAL_ID = 1
# Unique code used inside the DB to address the "Roman"-type row
ROMAN_CODE = 'R'
# Unique ID used inside the DB to address the "Roman"-type row
ROMAN_ID = 2
# Unique code used inside the DB to address the "None"-type row
NONE_CODE = 'N'
# Unique ID used inside the DB to address the "None"-type row
NONE_ID = 3
# Unique code used inside the DB to address the "Yearly"-type row
YEAR_CODE = 'A'
# Unique ID used inside the DB to address the "Yearly"-type row
YEAR_ID = 4
# Unique code used inside the DB to address the "Seasonal"-type row
SEASON_CODE = 'S'
# Unique ID used inside the DB to address the "Seasonal"-type row
SEASON_ID = 5
# ----------------------------------------------------------------------------
end
| true
|
f3603e97e9abd54dd693ffd4f73ab0fce123a6db
|
Ruby
|
gogolqx/nand2tetris-4
|
/jf647/10/jack_lexer.rb
|
UTF-8
| 2,761
| 2.796875
| 3
|
[] |
no_license
|
require 'rltk'
module Jack
class Lexer < RLTK::Lexer
# ignore whitespace
rule(/\s/)
# line comments
rule(/\/\/.*/) { push_state(:linecomment) }
rule(/./, :linecomment)
rule(/\n/, :linecomment) { pop_state }
# block comments
rule(/\/\*/) { push_state(:blockcomment) }
rule(/./, :blockcomment)
rule(/\n/, :blockcomment)
rule(/\*\//, :blockcomment) { pop_state }
# api comments
rule(/\/\*\*/) { push_state(:apicomment) }
rule(/./, :apicomment)
rule(/\n/, :apicomment)
rule(/\*\//, :apicomment) { pop_state }
# keywords
rule('class') { :CLASS }
rule('constructor') { :CONSTRUCTOR }
rule('function') { :FUNCTION }
rule('method') { :METHOD }
rule('field') { :FIELD }
rule('static') { :STATIC }
rule('var') { :VAR }
rule('int') { :INT }
rule('char') { :CHAR }
rule('boolean') { :BOOLEAN }
rule('void') { :VOID }
rule('true') { :TRUE }
rule('false') { :FALSE }
rule('null') { :NULL }
rule('this') { :THIS }
rule('let') { :LET }
rule('do') { :DO }
rule('if') { :IF }
rule('else') { :ELSE }
rule('while') { :WHILE }
rule('return') { :RETURN }
# symbols
rule('{') { :LBRACE }
rule('}') { :RBRACE }
rule('\(') { :LPAREN }
rule('\)') { :RPAREN }
rule('\[') { :LBRACKET }
rule('\]') { :RBRACKET }
rule('\.') { :DOT }
rule(',') { :COMMA }
rule(';') { :SEMICOLON }
rule('\+') { :PLUS }
rule('-') { :MINUS }
rule('\*') { :MULT }
rule('\/') { :DIV }
rule('&') { :AND }
rule('|') { :OR }
rule('<') { :LT }
rule('>') { :GT }
rule('=') { :EQUALS }
rule('~') { :NEG }
# integers
rule(/[0-9]+/) { |t| [ :INTEGER, t.to_i ] }
# strings
rule(/"[^"]+"/) { |t| [ :STRING, t.match(/"([^"]+)"/)[1] ] }
# identifier
rule(/[a-zA-Z_][\w_]*/) { |t| [ :IDENT, t.to_sym ] }
end
end
| true
|
e80edae79a241444d058b0fae9c9aab04993c5f9
|
Ruby
|
basu0001/first-pr-Hacktoberfest--2019
|
/codes/algorithms/merge_sort/ruby/merge_sort.rb
|
UTF-8
| 629
| 4.0625
| 4
|
[
"MIT"
] |
permissive
|
def sort(numbers)
return numbers if numbers.size <= 1
arr_len = numbers.size
half_size = (arr_len / 2).round
left_array = numbers.take(half_size)
right_array = numbers.drop(half_size)
sorted_left = sort(left_array)
sorted_right = sort(right_array)
merge(sorted_left, sorted_right)
end
def merge(left, right)
return left if right.empty?
return right if left.empty?
smallest_number = if left.first <= right.first
left.shift
else
right.shift
end
recursive = merge(left, right)
[smallest_number].concat(recursive)
end
arr = [1,8,4,5,7,3,9,2,6]
sort(arr)
# => [1, 2, 3, 4, 5, 6, 7, 8, 9]
| true
|
38bc57e897fb5231bbc05b48939008aba110d64e
|
Ruby
|
RabbitLee/IntSig_activity_2
|
/code/Index.rb
|
UTF-8
| 1,211
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
module Index
def Index.getNameFromUrl(argvString)
if pattern=/\(name=(.*?)\)/.match(argvString)
return pattern[1]
else
return 'nil'
end
end
def Index.getPhoneFromUrl(argvString)
if pattern=/\(phone=(.*?)\)/.match(argvString)
return pattern[1]
else
return 'nil'
end
end
def Index.getEmailFromUrl(argvString)
if pattern=/\(email=(.*?)\)/.match(argvString)
return pattern[1]
else
return 'nil'
end
end
def Index.getCompanyFromUrl(argvString)
if pattern=/\(company=(.*?)\)/.match(argvString)
return pattern[1]
else
return 'nil'
end
end
def Index.getDepartmentFromUrl(argvString)
if pattern=/\(department=(.*?)\)/.match(argvString)
return pattern[1]
else
return 'nil'
end
end
def Index.getPositionFromUrl(argvString)
if pattern=/\(position=(.*?)\)/.match(argvString)
return pattern[1]
else
return 'nil'
end
end
def Index.getItemFromUrl(argvString)
item=['name'=>getNameFromUrl(argvString),'phone'=>getPhoneFromUrl(argvString),'email'=>getEmailFromUrl(argvString),'company'=>getCompanyFromUrl(argvString),'department'=>getDepartmentFromUrl(argvString),'position'=>getPositionFromUrl(argvString)]
return item
end
end
| true
|
e742ef836aabc9dd3ed7f32e0e256cc660a7bc61
|
Ruby
|
streeter/dash-snippets
|
/Rakefile
|
UTF-8
| 4,921
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
require 'sqlite3'
require 'toml-rb'
require 'dotenv'
require 'logger'
require 'fileutils'
Dotenv.load
ENV['LOG_LEVEL'] ||= 'INFO'
raise ArgumentError, 'ENV["DASH_SNIPPET_PATH"] is required' unless ENV['DASH_SNIPPET_PATH']
namespace :dash do
TOML_PATH = './snippets'
DUMP_PATH = './snippets'
SNIPPET = 'snippet'
module Fields
TITLE = 'title'
BODY = 'body'
SYNTAX = 'syntax'
TAG = 'tag'
end
module OutputRecordsIndex
TITLE = 0
BODY = 1
SYNTAX = 2
TAG = 3
end
def build_snippets
initialize_log
@logger.debug('start build snippets')
load_snippets
connect_sqlite
delete_tables
@snippets.each.with_index(0) do |snippet, _i|
records = read_snippets_by_title(snippet[Fields::TITLE])
record_count = get_record_count(records)
create_snippet(snippet)
end
@logger.debug('finish build snippets')
end
def dump_snippets
initialize_log
@logger.debug('start dump snippets')
connect_sqlite
snippets = load_db_snippets
@logger.debug("\tsnippet count = #{snippets.size}")
snippets.each do |snippet|
outer = {}
inner = {}
inner[:title] = snippet[OutputRecordsIndex::TITLE]
inner[:body] = snippet[OutputRecordsIndex::BODY]
inner[:syntax] = snippet[OutputRecordsIndex::SYNTAX]
inner[:tag] = snippet[OutputRecordsIndex::TAG]
outer[:snippet] = inner
path = DUMP_PATH
if inner[:tag]
path = File.join(path, inner[:tag])
end
FileUtils.mkdir_p(path)
filename = normalize_filename(inner[:title])
File.open("#{path}/#{filename}.toml", "w") {|e|e.puts TomlRB.dump(outer) }
@logger.debug("\t complete output #{path}/#{filename}.toml ")
end
@logger.debug('finish dump snippets')
end
private
def initialize_log
@logger = Logger.new(STDOUT)
level = ENV['LOG_LEVEL']
@logger.level = Object.const_get("Logger::#{level}")
@logger.formatter =-> (severity, datetime, progname, message) {
"#{datetime.strftime('%Y/%m/%d %H:%M:%S')} - #{level} - #{message}\n"
}
end
def load_snippets
@snippets = Dir.glob("#{TOML_PATH}/**/*.toml").each_with_object([]) do |e, memo|
memo << TomlRB.load_file(e)[SNIPPET]
end
end
def delete_tables
@logger.debug("\tstart delete snippets")
@db = connect_sqlite
delete_table('snippets')
delete_table('tagsIndex')
delete_table('tags')
@logger.debug("\tfinish delete snippets")
end
def delete_table(table_name)
@db.execute("delete from #{table_name}")
@logger.debug("\t\tsuccess delete #{table_name}")
end
def connect_sqlite
@db = SQLite3::Database.new(ENV['DASH_SNIPPET_PATH'])
end
def read_snippets_by_title(title)
@db.execute('select count(*) from snippets where title = ?', title)
end
def get_record_count(records)
records.first.first
end
def create_snippet(snippet)
@logger.debug("\tcreate #{snippet[Fields::TITLE]}")
insert_tags_index(snippet)
create_tag_if_not_exist(snippet[Fields::TAG])
insert_snippet(snippet)
end
def insert_tags_index(snippet)
@logger.debug("\t\tinsert tagsIndex for title:#{snippet[Fields::TITLE]} tag: #{snippet[Fields::TAG]}")
if tag_exist?(snippet[Fields::TAG])
@db.execute('insert into tagsIndex values ((select tid from tags where tag = ?), ?)', snippet[Fields::TAG], next_sid)
else
@db.execute('insert into tagsIndex values (?, ?)', next_tid, next_sid)
end
end
def create_tag_if_not_exist(tag)
return if tag_exist?(tag)
@logger.debug("\t\tcreate tag #{tag}")
@db.execute('insert into tags values ((select max(tid) from tagsIndex), ?)', tag)
end
def next_sid
next_id('tagsIndex', 'sid')
end
def next_tid
next_id('tags', 'tid')
end
def next_id(table, column)
count = @db.execute("select count(*) from #{table}").first.first
return 1 if count == 0
@db.execute("select max(#{column}) from #{table}").first.first + 1
end
def tag_exist?(tag)
tag_count = @db.execute('select count(*) from tags where tag = ?', tag).first.first
tag_count == 1
end
def insert_snippet(snippet)
@logger.debug("\t\tcreate snippet #{snippet[Fields::TITLE]}")
@db.execute('insert into snippets values((select max(sid) from tagsIndex),?,?,?,?)',
snippet[Fields::TITLE],
snippet[Fields::BODY],
snippet[Fields::SYNTAX],
0
)
end
def load_db_snippets
sql =<<-SQL
select s.title, s.body, s.syntax, t.tag
from snippets s
inner join tagsIndex ti on s.sid == ti.sid
inner join tags t on ti.tid = t.tid
SQL
@db.execute(sql)
end
def normalize_filename(filename)
filename.gsub(/([^a-z|A-Z|0-9|\-_])/, '')
end
desc 'build snippets'
task :build do
build_snippets
end
desc 'dump snippets'
task :dump do
dump_snippets
end
end
| true
|
ded1af5f6e89fef48cd574bed16377cf3eb39f39
|
Ruby
|
LeipeLeon/optocht_kop
|
/app/helpers/application_helper.rb
|
UTF-8
| 2,081
| 2.78125
| 3
|
[] |
no_license
|
# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
def distance_of_time_in_dutch(from_time, to_time = Time.now, include_seconds = false)
from_time = Time.now if from_time.blank?
from_time = from_time.to_time if from_time.respond_to?(:to_time)
to_time = to_time.to_time if to_time.respond_to?(:to_time)
distance_in_minutes = (((to_time - from_time).abs)/60).round
distance_in_seconds = ((to_time - from_time).abs).round
case distance_in_minutes
when 0..1
return (distance_in_minutes == 0) ? '< min.' : '1 min.' unless include_seconds
case distance_in_seconds
when 0..4 then '< 5 sec.'
when 5..9 then '< 10 sec.'
when 10..19 then '< 20 sec.'
when 20..59 then '< 1 min.'
else '1 min.'
end
when 2..44 then "#{distance_in_minutes} min."
when 45..89 then '~ 1 uur'
when 90..1439 then "~ #{(distance_in_minutes.to_f / 60.0).round} uren"
when 1440..2879 then '1 dag'
when 2880..43199 then "#{(distance_in_minutes / 1440).round} dagen"
when 43200..86399 then '~ 1 maand'
when 86400..525599 then "#{(distance_in_minutes / 43200).round} maanden"
when 525600..1051199 then '~ 1 jaar'
else "over #{(distance_in_minutes / 525600).round} jaren"
end
end
def google_analytics
if GOOGLE_KEYS['analytics'] != ''
'<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src=\'" + gaJsHost + "google-analytics.com/ga.js\' type=\'text/javascript\'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("' + GOOGLE_KEYS['analytics'] + '");
pageTracker._trackPageview();
} catch(err) {}</script>'
end
end
def distance_in_m(delta)
Haversine.delta_to_m(delta)
end
end
| true
|
619360c540f7826aff1ea58ad7a19efc5e692bf5
|
Ruby
|
zacharytwhite/project-euler-solutions
|
/project_euler_rb/problem_052.rb
|
UTF-8
| 656
| 3.515625
| 4
|
[] |
no_license
|
# It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order.
# Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits.
i = 1
ans = []
loop do
pan = (2*i).to_s.split('')
multis = []
if pan.uniq.length == pan.length
is_answer = 3.upto(6).
map { |m|
multi = (i*m)
multis << multi
multi.to_s.split('')
}.all? { |a| pan.all? { |n| a.include?(n) } }
if is_answer
puts "Answer : #{i}"
break
end
dend
i += 1
end
# Complete!
# Answer = 142857
| true
|
be313df83e14511b25dd8cc962625a1a66c7f572
|
Ruby
|
learn-co-students/nyc-clarke-web-100719
|
/18-sessions-cookies/app/controllers/trivia_controller.rb
|
UTF-8
| 747
| 2.703125
| 3
|
[] |
no_license
|
class TriviaController < ApplicationController
def random
trivia_api = TriviaApi.new
@trivia_question = trivia_api.get_random_question
@choices = @trivia_question["incorrect_answers"]
@choices.push(@trivia_question["correct_answer"])
session[:correct_answer] = @trivia_question["correct_answer"]
@choices.shuffle!
render :random
end
def answer
# check user choice
# if user choice == correct answer
# do something
if params[:answer] == session[:correct_answer]
if session[:score]
session[:score] = session[:score] + 100
else
session[:score] = 100
end
end
redirect_to '/'
# if user choice != correct anser
# do something else
end
end
| true
|
44f8f8852abd54bc8a3a1de6287b215aaa4c2a95
|
Ruby
|
marco-beduschi/tic-tac-toe
|
/player.rb
|
UTF-8
| 245
| 2.59375
| 3
|
[] |
no_license
|
# frozen_string_literal: true
require './base_character.rb'
class Player < BaseCharacter
def initialize(game, marker)
@view = game.view
super
end
private
def choose_square
@board.get_square(@view.get_input - 1)
end
end
| true
|
478e977500b6dd5147995957dc8613331c68173d
|
Ruby
|
dallinder/ls_small_pbs_round2
|
/adv/2.rb
|
UTF-8
| 862
| 3.421875
| 3
|
[] |
no_license
|
def star(num)
stars = '*'
spaces = ' '
tracker = ((num - 1) / 2 ) - 1
tracker.downto(0) do |countd|
puts "#{stars}#{spaces * countd}#{stars}#{spaces * countd}#{stars}".center(num)
end
# puts "#{stars}#{spaces * 2}#{stars}#{spaces * 2}#{stars}".center(num)
# puts "#{stars}#{spaces * 1}#{stars}#{spaces * 1}#{stars}".center(num)
# puts "#{stars}#{spaces * 0}#{stars}#{spaces * 0}#{stars}".center(num)
puts "#{stars * num}".center(num)
# puts "#{stars}#{spaces * 0}#{stars}#{spaces * 0}#{stars}".center(num)
# puts "#{stars}#{spaces * 1}#{stars}#{spaces * 1}#{stars}".center(num)
# puts "#{stars}#{spaces * 2}#{stars}#{spaces * 2}#{stars}".center(num)
0.upto(tracker) do |count|
puts "#{stars}#{spaces * count}#{stars}#{spaces * count}#{stars}".center(num)
end
end
p star(21)
| true
|
9fb79ca88817b6d52dbc07dc7b9c9d4c67be4004
|
Ruby
|
horiaradu/dense-ranges-merger
|
/lib/ranges/node.rb
|
UTF-8
| 343
| 3.046875
| 3
|
[
"MIT"
] |
permissive
|
class Ranges::Node
attr_accessor :start, :finish
def initialize(start:, finish:)
raise ArgumentError if finish < start
@start = start
@finish = finish
end
def ==(other)
other.is_a?(Ranges::Node) &&
start == other.start &&
finish == other.finish
end
def <=>(other)
start <=> other.start
end
end
| true
|
beea3dfff3e77abd8bfe5eb70d76a841bf95006f
|
Ruby
|
marksweston/acts_as_raytracer
|
/lib/acts_as_raytracer/transform.rb
|
UTF-8
| 1,005
| 3.015625
| 3
|
[] |
no_license
|
class Transform
attr_accessor :transform_matrix
def initialize_from_matrix(matrix)
@transform_matrix = matrix
end
def *(multiplicand)
case multiplicand
when Point, Vector
return transform_point_or_vector(multiplicand)
when Transform
return self.class.new_from_matrix(self.transform_matrix * multiplicand.transform_matrix)
end
end
def transpose
return @transpose ||= self.class.new_from_matrix(self.transform_matrix.getTransposed)
end
def inverse
return @inverse ||= self.class.new_from_matrix(transform_matrix.getInverse)
end
private def transform_point_or_vector(point_or_vector)
transformable = RVec4.new(
point_or_vector.x,
point_or_vector.y,
point_or_vector.z,
point_or_vector.weighting
)
result = transformable.transform(transform_matrix)
return point_or_vector.class.new(
result.x.round(epsilon),
result.y.round(epsilon),
result.z.round(epsilon)
)
end
end
| true
|
71e9e545332da87fde6ae9415f0e038219c2d133
|
Ruby
|
vishallama/assignment_recursion_sprint
|
/palindrome/# palindrome_i.rb
|
UTF-8
| 130
| 3.546875
| 4
|
[] |
no_license
|
# palindrome_i.rb
def palindrome_i(str)
holder = ""
str.chars.reverse_each { |char| holder << char }
str == holder
end
| true
|
7e744c0d0c981924444e2bd7c9c23bbc8d11e3ca
|
Ruby
|
alinan-vn/ruby-oo-self-cash-register-lab-chicago-web-111819
|
/ignore_this_turbo.rb
|
UTF-8
| 384
| 3.96875
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
require 'pry'
class Snail
attr_accessor :name, :speed
def initialize(name, speed)
@name = name
@speed = speed
end
def speed_up(boost)
@speed += boost
end
end
binding.pry
turbo = Snail.new("Turbo", 200)
puts turbo.name # should print "Turbo"
puts turbo.speed # should print 200
turbo.speed_up(50)
puts turbo.speed # should print 250
| true
|
134f369bdfc7be1b587ede6511e14b94b8a60d27
|
Ruby
|
ivanadokic/programming-univbasics-4-array-concept-review-lab-dumbo-web-091619
|
/lib/array_methods.rb
|
UTF-8
| 179
| 3
| 3
|
[
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
def find_element_index(array, value_to_find)
array.index
puts array
end
def find_max_value(array)
array.find_max_value
end
def find_min_value(array)
array.find_min_value
end
| true
|
b4be0024ffa72c459f775fcc653303301524387f
|
Ruby
|
jeremyevans/sequel
|
/lib/sequel/extensions/pg_multirange.rb
|
UTF-8
| 13,729
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
# frozen-string-literal: true
#
# The pg_multirange extension adds support for the PostgreSQL 14+ multirange
# types to Sequel. PostgreSQL multirange types are similar to an array of
# ranges, where a match against the multirange is a match against any of the
# ranges in the multirange.
#
# When PostgreSQL multirange values are retrieved, they are parsed and returned
# as instances of Sequel::Postgres::PGMultiRange. PGMultiRange mostly acts
# like an array of Sequel::Postgres::PGRange (see the pg_range extension).
#
# In addition to the parser, this extension comes with literalizers
# for PGMultiRanges, so they can be used in queries and as bound variables.
#
# To turn an existing array of Ranges into a PGMultiRange, use Sequel.pg_multirange.
# You must provide the type of multirange when creating the multirange:
#
# Sequel.pg_multirange(array_of_date_ranges, :datemultirange)
#
# To use this extension, load it into the Database instance:
#
# DB.extension :pg_multirange
#
# See the {schema modification guide}[rdoc-ref:doc/schema_modification.rdoc]
# for details on using multirange type columns in CREATE/ALTER TABLE statements.
#
# This extension makes it easy to add support for other multirange types. In
# general, you just need to make sure that the subtype is handled and has the
# appropriate converter installed. For user defined
# types, you can do this via:
#
# DB.add_conversion_proc(subtype_oid){|string| }
#
# Then you can call
# Sequel::Postgres::PGMultiRange::DatabaseMethods#register_multirange_type
# to automatically set up a handler for the range type. So if you
# want to support the timemultirange type (assuming the time type is already
# supported):
#
# DB.register_multirange_type('timerange')
#
# This extension integrates with the pg_array extension. If you plan
# to use arrays of multirange types, load the pg_array extension before the
# pg_multirange extension:
#
# DB.extension :pg_array, :pg_multirange
#
# The pg_multirange extension will automatically load the pg_range extension.
#
# Related module: Sequel::Postgres::PGMultiRange
require 'delegate'
require 'strscan'
module Sequel
module Postgres
class PGMultiRange < DelegateClass(Array)
include Sequel::SQL::AliasMethods
# Converts strings into PGMultiRange instances.
class Parser < StringScanner
def initialize(source, converter)
super(source)
@converter = converter
end
# Parse the multirange type input string into a PGMultiRange value.
def parse
raise Sequel::Error, "invalid multirange, doesn't start with {" unless get_byte == '{'
ranges = []
unless scan(/\}/)
while true
raise Sequel::Error, "unfinished multirange" unless range_string = scan_until(/[\]\)]/)
ranges << @converter.call(range_string)
case sep = get_byte
when '}'
break
when ','
# nothing
else
raise Sequel::Error, "invalid multirange separator: #{sep.inspect}"
end
end
end
raise Sequel::Error, "invalid multirange, remaining data after }" unless eos?
ranges
end
end
# Callable object that takes the input string and parses it using Parser.
class Creator
# The database type to set on the PGMultiRange instances returned.
attr_reader :type
def initialize(type, converter=nil)
@type = type
@converter = converter
end
# Parse the string using Parser with the appropriate
# converter, and return a PGMultiRange with the appropriate database
# type.
def call(string)
PGMultiRange.new(Parser.new(string, @converter).parse, @type)
end
end
module DatabaseMethods
# Add the default multirange conversion procs to the database
def self.extended(db)
db.instance_exec do
raise Error, "multiranges not supported on this database" unless server_version >= 140000
extension :pg_range
@pg_multirange_schema_types ||= {}
register_multirange_type('int4multirange', :range_oid=>3904, :oid=>4451)
register_multirange_type('nummultirange', :range_oid=>3906, :oid=>4532)
register_multirange_type('tsmultirange', :range_oid=>3908, :oid=>4533)
register_multirange_type('tstzmultirange', :range_oid=>3910, :oid=>4534)
register_multirange_type('datemultirange', :range_oid=>3912, :oid=>4535)
register_multirange_type('int8multirange', :range_oid=>3926, :oid=>4536)
if respond_to?(:register_array_type)
register_array_type('int4multirange', :oid=>6150, :scalar_oid=>4451, :scalar_typecast=>:int4multirange)
register_array_type('nummultirange', :oid=>6151, :scalar_oid=>4532, :scalar_typecast=>:nummultirange)
register_array_type('tsmultirange', :oid=>6152, :scalar_oid=>4533, :scalar_typecast=>:tsmultirange)
register_array_type('tstzmultirange', :oid=>6153, :scalar_oid=>4534, :scalar_typecast=>:tstzmultirange)
register_array_type('datemultirange', :oid=>6155, :scalar_oid=>4535, :scalar_typecast=>:datemultirange)
register_array_type('int8multirange', :oid=>6157, :scalar_oid=>4536, :scalar_typecast=>:int8multirange)
end
[:int4multirange, :nummultirange, :tsmultirange, :tstzmultirange, :datemultirange, :int8multirange].each do |v|
@schema_type_classes[v] = PGMultiRange
end
procs = conversion_procs
add_conversion_proc(4533, PGMultiRange::Creator.new("tsmultirange", procs[3908]))
add_conversion_proc(4534, PGMultiRange::Creator.new("tstzmultirange", procs[3910]))
if respond_to?(:register_array_type) && defined?(PGArray::Creator)
add_conversion_proc(6152, PGArray::Creator.new("tsmultirange", procs[4533]))
add_conversion_proc(6153, PGArray::Creator.new("tstzmultirange", procs[4534]))
end
end
end
# Handle PGMultiRange values in bound variables
def bound_variable_arg(arg, conn)
case arg
when PGMultiRange
arg.unquoted_literal(schema_utility_dataset)
else
super
end
end
# Freeze the pg multirange schema types to prevent adding new ones.
def freeze
@pg_multirange_schema_types.freeze
super
end
# Register a database specific multirange type. This can be used to support
# different multirange types per Database. Options:
#
# :converter :: A callable object (e.g. Proc), that is called with the PostgreSQL range string,
# and should return a PGRange instance.
# :oid :: The PostgreSQL OID for the multirange type. This is used by Sequel to set up automatic type
# conversion on retrieval from the database.
# :range_oid :: Should be the PostgreSQL OID for the multirange subtype (the range type). If given,
# automatically sets the :converter option by looking for scalar conversion
# proc.
#
# If a block is given, it is treated as the :converter option.
def register_multirange_type(db_type, opts=OPTS, &block)
oid = opts[:oid]
soid = opts[:range_oid]
if has_converter = opts.has_key?(:converter)
raise Error, "can't provide both a block and :converter option to register_multirange_type" if block
converter = opts[:converter]
else
has_converter = true if block
converter = block
end
unless (soid || has_converter) && oid
range_oid, subtype_oid = from(:pg_range).join(:pg_type, :oid=>:rngmultitypid).where(:typname=>db_type.to_s).get([:rngmultitypid, :rngtypid])
soid ||= subtype_oid unless has_converter
oid ||= range_oid
end
db_type = db_type.to_s.dup.freeze
if soid
raise Error, "can't provide both a converter and :range_oid option to register" if has_converter
raise Error, "no conversion proc for :range_oid=>#{soid.inspect} in conversion_procs" unless converter = conversion_procs[soid]
end
raise Error, "cannot add a multirange type without a convertor (use :converter or :range_oid option or pass block)" unless converter
creator = Creator.new(db_type, converter)
add_conversion_proc(oid, creator)
@pg_multirange_schema_types[db_type] = db_type.to_sym
singleton_class.class_eval do
meth = :"typecast_value_#{db_type}"
scalar_typecast_method = :"typecast_value_#{opts.fetch(:scalar_typecast, db_type.sub('multirange', 'range'))}"
define_method(meth){|v| typecast_value_pg_multirange(v, creator, scalar_typecast_method)}
private meth
end
@schema_type_classes[db_type] = PGMultiRange
nil
end
private
# Recognize the registered database multirange types.
def schema_multirange_type(db_type)
@pg_multirange_schema_types[db_type] || super
end
# Set the :ruby_default value if the default value is recognized as a multirange.
def schema_post_process(_)
super.each do |a|
h = a[1]
db_type = h[:db_type]
if @pg_multirange_schema_types[db_type] && h[:default] =~ /\A#{db_type}\(.*\)\z/
h[:ruby_default] = get(Sequel.lit(h[:default]))
end
end
end
# Given a value to typecast and the type of PGMultiRange subclass:
# * If given a PGMultiRange with a matching type, use it directly.
# * If given a PGMultiRange with a different type, return a PGMultiRange
# with the creator's type.
# * If given an Array, create a new PGMultiRange instance for it, typecasting
# each instance using the scalar_typecast_method.
def typecast_value_pg_multirange(value, creator, scalar_typecast_method=nil)
case value
when PGMultiRange
return value if value.db_type == creator.type
when Array
# nothing
else
raise Sequel::InvalidValue, "invalid value for multirange type: #{value.inspect}"
end
if scalar_typecast_method && respond_to?(scalar_typecast_method, true)
value = value.map{|v| send(scalar_typecast_method, v)}
end
PGMultiRange.new(value, creator.type)
end
end
# The type of this multirange (e.g. 'int4multirange').
attr_accessor :db_type
# Set the array of ranges to delegate to, and the database type.
def initialize(ranges, db_type)
super(ranges)
@db_type = db_type.to_s
end
# Append the multirange SQL to the given sql string.
def sql_literal_append(ds, sql)
sql << db_type << '('
joiner = nil
conversion_meth = nil
each do |range|
if joiner
sql << joiner
else
joiner = ', '
end
unless range.is_a?(PGRange)
conversion_meth ||= :"typecast_value_#{db_type.sub('multi', '')}"
range = ds.db.send(conversion_meth, range)
end
ds.literal_append(sql, range)
end
sql << ')'
end
# Return whether the value is inside any of the ranges in the multirange.
def cover?(value)
any?{|range| range.cover?(value)}
end
alias === cover?
# Don't consider multiranges with different database types equal.
def eql?(other)
if PGMultiRange === other
return false unless other.db_type == db_type
other = other.__getobj__
end
__getobj__.eql?(other)
end
# Don't consider multiranges with different database types equal.
def ==(other)
return false if PGMultiRange === other && other.db_type != db_type
super
end
# Return a string containing the unescaped version of the multirange.
# Separated out for use by the bound argument code.
def unquoted_literal(ds)
val = String.new
val << "{"
joiner = nil
conversion_meth = nil
each do |range|
if joiner
val << joiner
else
joiner = ', '
end
unless range.is_a?(PGRange)
conversion_meth ||= :"typecast_value_#{db_type.sub('multi', '')}"
range = ds.db.send(conversion_meth, range)
end
val << range.unquoted_literal(ds)
end
val << "}"
end
# Allow automatic parameterization.
def sequel_auto_param_type(ds)
"::#{db_type}"
end
end
end
module SQL::Builders
# Convert the object to a Postgres::PGMultiRange.
def pg_multirange(v, db_type)
case v
when Postgres::PGMultiRange
if v.db_type == db_type
v
else
Postgres::PGMultiRange.new(v, db_type)
end
when Array
Postgres::PGMultiRange.new(v, db_type)
else
# May not be defined unless the pg_range_ops extension is used
pg_range_op(v)
end
end
end
Database.register_extension(:pg_multirange, Postgres::PGMultiRange::DatabaseMethods)
end
| true
|
99b3c876e29225648429ec324fe71b41cda7648b
|
Ruby
|
itsolutionscorp/AutoStyle-Clustering
|
/all_data/exercism_data/ruby/word-count/9513fb3818324c0a9d4be5b38b49baf9.rb
|
UTF-8
| 433
| 3.359375
| 3
|
[] |
no_license
|
class Phrase
def initialize(phrase)
@phrase = phrase
end
def word_count
WordCounter.new(words).count
end
private
def words
@phrase.split(/\W+/)
end
end
class WordCounter
def initialize(words)
@words = words
end
def count
@words.each_with_object(Hash.new(0)) do |word, counts|
counts[normalize(word)] += 1
end
end
private
def normalize(word)
word.downcase
end
end
| true
|
e4fe3c5f62f7e703ffc3557878a3a3d2b5be10d7
|
Ruby
|
blm768/bookie
|
/bookie/lib/bookie/database/job.rb
|
UTF-8
| 6,266
| 2.875
| 3
|
[
"MIT"
] |
permissive
|
require 'active_record'
require 'bookie/database/lock.rb'
require 'bookie/database/user.rb'
require 'bookie/database/system.rb'
module Bookie
module Database
##
#A reported job
#
#The various filter methods can be chained to produce more complex queries.
#
#===Examples
# Bookie::Database::Job.by_user_name('root').by_system_name('localhost').find_each do |job|
# puts job.inspect
# end
#
class Job < ActiveRecord::Base
belongs_to :user
belongs_to :system
has_one :system_type, :through => :system
##
#The time at which the job ended
def end_time
return start_time + wall_time
end
def end_time=(time)
self.wall_time = (time - start_time)
end
#To consider: disable #end_time= ?
def self.by_user(user)
where('jobs.user_id = ?', user.id)
end
##
#Filters by user name
#TODO: remove!
def self.by_user_name(user_name)
joins(:user).where('users.name = ?', user_name)
end
def self.by_system(system)
where('jobs.system_id = ?', system.id)
end
##
#Filters by system name
def self.by_system_name(system_name)
joins(:system).where('systems.name = ?', system_name)
end
##
#Filters by system type
def self.by_system_type(system_type)
joins(:system).where('systems.system_type_id = ?', system_type.id)
end
##
#Filters by command name
def self.by_command_name(c_name)
where('jobs.command_name = ?', c_name)
end
##
#Finds all jobs that were running at some point in a given time range
def self.by_time_range(time_range)
if time_range.empty?
self.none
else
time_range = time_range.exclusive
where('jobs.end_time > ? AND jobs.start_time < ?', time_range.begin, time_range.end)
end
end
##
#Similar to #by_time_range, but only includes jobs that are completely contained within the
#time range
def self.within_time_range(time_range)
if time_range.empty?
self.none
else
time_range = time_range.exclusive
#The second "<=" operator _is_ intentional.
#If the job's end_time is one second past the last value in the range, it
#is still considered to be contained within time_range because it did not
#run outside time_range; it only _stopped_ outside it.
where('? <= jobs.start_time AND jobs.end_time <= ?', time_range.begin, time_range.end)
end
end
##
#Finds all jobs that overlap the edges of the given time range
def self.overlapping_edges(time_range)
if time_range.empty?
self.none
else
time_range = time_range.exclusive
query_str = ['begin', 'end'].map{ |edge| "(jobs.start_time < :#{edge} AND jobs.end_time > :#{edge})" }.join(" OR ")
where(query_str, {:begin => time_range.begin, :end => time_range.end})
end
end
##
#Produces a summary of the jobs in the given time interval
#
#Returns a hash with the following fields:
#- <tt>:num_jobs</tt>: the number of jobs in the interval
#- <tt>:successful</tt>: the number of jobs that have completed successfully
#- <tt>:cpu_time</tt>: the total CPU time used
#- <tt>:memory_time</tt>: the sum of memory * wall_time for all jobs in the interval
#
#This method should probably not be chained with other queries that filter by start/end time.
#It also doesn't work with the limit() method.
#
#The time_range parameter is always treated as if time_range.exclude_end? is true.
def self.summary(time_range = nil)
jobs = self
num_jobs = 0
successful = 0
cpu_time = 0.0
memory_time = 0
if time_range
unless time_range.empty?
time_range = time_range.exclusive
#Any jobs that are completely within the time range can
#be summarized as-is.
jobs_within = jobs.within_time_range(time_range)
#TODO: optimize into one query?
num_jobs += jobs_within.count
successful += jobs_within.where(:exit_code => 0).count
cpu_time += jobs_within.sum(:cpu_time)
memory_time += jobs_within.sum('jobs.memory * jobs.wall_time')
#Any jobs that overlap an edge of the time range
#must be clipped.
jobs_overlapped = jobs.overlapping_edges(time_range)
jobs_overlapped.find_each do |job|
start_time = [job.start_time, time_range.begin].max
end_time = [job.end_time, time_range.end].min
clipped_wall_time = end_time.to_i - start_time.to_i
if job.wall_time != 0
cpu_time += Float(job.cpu_time * clipped_wall_time) / job.wall_time
memory_time += job.memory * clipped_wall_time
end
num_jobs += 1
successful += 1 if job.exit_code == 0
end
end
else
#There's no time_range constraint; just summarize everything.
num_jobs = jobs.count
successful = jobs.where(:exit_code => 0).count
cpu_time = jobs.sum(:cpu_time)
memory_time = jobs.sum('jobs.memory * jobs.wall_time')
end
return {
:num_jobs => num_jobs,
:successful => successful,
:cpu_time => cpu_time.round,
:memory_time => memory_time,
}
end
before_save do
write_attribute(:end_time, end_time)
end
before_update do
write_attribute(:end_time, end_time)
end
validates_presence_of :user, :system, :cpu_time,
:start_time, :wall_time, :memory, :exit_code
validates_each :command_name do |record, attr, value|
record.errors.add(attr, 'must not be nil') if value == nil
end
validates_each :cpu_time, :wall_time, :memory do |record, attr, value|
record.errors.add(attr, 'must be a non-negative integer') unless value && value >= 0
end
end
end
end
| true
|
5569beb70fda4b7665a054b738b12e6ef19b906c
|
Ruby
|
devkmsg/daemon_runner
|
/lib/daemon_runner/session.rb
|
UTF-8
| 3,936
| 3
| 3
|
[
"MIT"
] |
permissive
|
require 'diplomat'
module DaemonRunner
#
# Manage distributed locks with Consul
#
class Session
class SessionError < RuntimeError; end
class CreateSessionError < SessionError; end
include Logger
class << self
attr_reader :session
def start(name, **options)
@session = Session.new(name, options).renew!
raise CreateSessionError, 'Failed to create session' if @session == false
@session.verify_session
@session
end
# Acquire a lock with the current session, or initialize a new session
#
# @param path [String] A path in the Consul key-value space to lock
# @param lock_session [Session] The Session instance to lock the lock to
# @return [Boolean] `true` if the lock was acquired
#
def lock(path)
Diplomat::Lock.wait_to_acquire(path, session.id)
end
# Release a lock held by the current session
#
# @param path [String] A path in the Consul key-value space to release
# @param lock_session [Session] The Session instance that the lock was acquired with
#
def release(path)
Diplomat::Lock.release(path, session.id)
end
end
# Consul session ID
attr_reader :id
# Session name
attr_reader :name
# Period, in seconds, after which session expires
attr_reader :ttl
# Period, in seconds, that a session's locks will be
attr_reader :delay
# Behavior when a session is invalidated, can be set to either release or delete
attr_reader :behavior
# @param name [String] Session name
# @option options [Fixnum] ttl (15) Session TTL in seconds
# @option options [Fixnum] delay (15) Session release dealy in seconds
# @option options [String] behavior (release) Session release behavior
def initialize(name, **options)
logger.info('Initializing a Consul session')
@name = name
@ttl = options.fetch(:ttl, 15)
@delay = options.fetch(:delay, 15)
@behavior = options.fetch(:behavior, 'release')
init
end
# Check if there is an active renew thread
#
# @return [Boolean] `true` if the thread is alive
def renew?
@renew.is_a?(Thread) && @renew.alive?
end
# Create a thread to periodically renew the lock session
#
def renew!
return if renew?
@renew = Thread.new do
## Wakeup every TTL/2 seconds and renew the session
loop do
sleep ttl / 2
begin
logger.debug(" - Renewing Consul session #{id}")
Diplomat::Session.renew(id)
rescue Faraday::ResourceNotFound
logger.warn("Consul session #{id} has expired!")
init
rescue StandardError => e
## Keep the thread from exiting
logger.error(e)
end
end
end
self
end
# Stop the renew thread and destroy the session
#
def destroy!
@renew.kill if renew?
Diplomat::Session.destroy(id)
end
# Verify wheather the session exists after a period of time
def verify_session(wait_time = 2)
logger.info(" - Wait until Consul session #{id} exists")
wait_time.times do
exists = session_exist?
raise CreateSessionError, 'Error creating session' unless exists
sleep 1
end
logger.info(" - Found Consul session #{id}")
rescue CreateSessionError
init
end
private
# Initialize a session and store it's ID
#
def init
@id = Diplomat::Session.create(
:Name => name,
:TTL => "#{ttl}s",
:LockDelay => "#{delay}s",
:Behavior => behavior
)
logger.info(" - Initialized a Consul session #{id}")
end
# Does the session exist
def session_exist?
sessions = Diplomat::Session.list
sessions.any? { |s| s['ID'] == id }
end
end
end
| true
|
f07100249b42e83b72bbd8b5d5d94d693ab8de04
|
Ruby
|
akhilkrishna57/misc
|
/ruby/heap_sort.rb
|
UTF-8
| 950
| 3.625
| 4
|
[] |
no_license
|
def swap(a, i, j)
a[i], a[j] = a[j], a[i]
end
def left_child(i)
i * 2 + 1
end
def right_child(i)
i * 2 + 2
end
def max_heapify(a, n, i)
left = left_child(i)
right = right_child(i)
if left < n and a[left] > a[i]
largest = left
else
largest = i
end
if right < n and a[right] > a[largest]
largest = right
end
if largest != i
swap(a, largest, i)
max_heapify(a, n, largest)
end
end
def build_max_heap!(a)
(a.length / 2 - 1).downto(0) do |i|
max_heapify(a, a.length, i)
end
end
def heap_sort!(a)
build_max_heap!(a)
(a.length - 1).downto(1) do |i|
swap(a, 0, i)
max_heapify(a, i, 0)
end
return a
end
cases = [
[ ],
[ 1 ],
[ 1, 2 ],
[ 2, 1 ],
[ 1, 2, 3, 4, 5 ],
[ 5, 4, 3, 2, 1 ],
[ 5, 3, 2, 4, 1 ],
[ 1, 5, 2, 4, 6, 3 ],
[ 1, 2, 3, 4, 5, 6 ],
[ 6, 5, 4, 3, 2, 1 ]
]
(0...cases.length).each { |k| printf "Case %d: %s\n", k, heap_sort!(cases[k]).join(" ") }
| true
|
079c953271b01e2cff0445d618f5e8e624ecd2cd
|
Ruby
|
SettRaziel/wrf_forecast
|
/spec/forecast/measurand_text_spec.rb
|
UTF-8
| 554
| 2.578125
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
require "spec_helper"
require "ruby_utils/statistic"
require "wrf_forecast/threshold"
require "wrf_forecast/text"
describe WrfForecast::Text::MeasurandText do
describe ".new" do
context "given an array of data and some extreme values" do
it "tries to initialize the abstract class but fails in the abstract method" do
extreme_values = RubyUtils::ExtremeValues.new(0, 2)
expect {
WrfForecast::Text::MeasurandText.new(extreme_values, nil)
}.to raise_error(NotImplementedError)
end
end
end
end
| true
|
349e3571be74a7df987acd39d6a395fd9a4dca24
|
Ruby
|
restc/mypage_tools
|
/lib/mypage_tools/schedule_page.rb
|
UTF-8
| 2,213
| 3.140625
| 3
|
[
"MIT"
] |
permissive
|
module MypageTools
class SchedulePage
# Expects the myPage schedule page as a Nokogiri HTML object
def initialize page
@page = page
end
# Return string containing the date the week begins, i.e. "Sep 14, 2013"
# Matches from the raw_schedule_text using a regex
# http://rubular.com/r/OjRZ0q6cko
def week_begins
unless @week_begins
@week_begins = raw_schedule_text.scan(/\w+\s\d{1,2},\s\d{4}/)[0]
end
@week_begins
end
# Gross & Ugly.
# Returns an array where every item is a Shift object
def shift_array
unless @shift_array
@shift_array = []
days_of_week = %w[Saturday Sunday Monday Tuesday Wednesday Thursday Friday]
# Establishing variable scope
current_day = nil
current_date = nil
index_counter = 0
shift = nil
# Finds a day then creates shifts for that day from each following pair of times
raw_schedule_array.each do |item|
if days_of_week.member?(item)
current_day = item
# Figure out the date of the shift based on the day of the week & start date of the week
current_date = Date.parse(week_begins) + days_of_week.index(item)
index_counter = 0
elsif index_counter == 0
shift = Shift.new
shift.day_of_week = current_day
shift.date = current_date
shift.start = item
index_counter += 1
elsif index_counter == 1
shift.stop = item
index_counter = 0
@shift_array << shift
end
end
end
@shift_array
end
private
# Returns a string with all the necessary information to extract that week's schedule
def raw_schedule_text
unless @raw_schedule_text
xpath_to_schedule = "//div[@id = 'contentTimecard']/div/table/tbody/tr/td/table/tbody"
@raw_schedule_text = @page.search(xpath_to_schedule).text
end
@raw_schedule_text
end
# Data structure for schedule: [Day, Start, End, Day, Start, End, (Start), (End), etc...]
# Matched from the raw_schedule_text with a regex
# http://rubular.com/r/xOOFBOKFMM
def raw_schedule_array
unless @raw_schedule_array
@raw_schedule_array = raw_schedule_text.scan /[SMTWF]\w{2,5}day|\d{1,2}:\d{2}[A|P]M/
end
@raw_schedule_array
end
end
end
| true
|
dd27b43b4cede563207f449cf5459b1ab2a0e20c
|
Ruby
|
although2013/network
|
/elevator.rb
|
UTF-8
| 2,849
| 3.40625
| 3
|
[] |
no_license
|
require 'set'
class PeoplePool
attr_accessor :mutex
def initialize
@pool = {
f1: {
up: [5,5,6,7,8,9,10,11,15,15,11,8,17],
},
f4: {
up: [12, 12],
down: nil,
},
f11: {
up: [17],
down: [1, 2],
}
}
@mutex = Mutex.new
end
def pool
@pool
end
def shift(floor, updown, count)
waiting = @pool["f#{floor}".to_sym]&.[](updown)
if waiting
waiting.shift(count)
else
[]
end
end
end
class Elevator
def initialize(id)
@max_quantity = 6
@id = id
@current_floor = 1
@current_action = nil
@people = []
end
def running
loop do
if @people.empty?
target_floor, action = get_target_from_controller
if target_floor
run_to_a_target(target_floor, action)
else
sleep(0.5)
end
else
run_to_a_target
end
end
end
def target_floors_in_elevator
@people.sort.uniq
end
def get_target_from_controller
$people_pool.mutex.synchronize do
$people_pool.pool.keys.each do |floor|
if $people_pool.pool[floor]&.[](:up)&.any?
return floor.to_s[1..-1].to_i, :up
elsif $people_pool.pool[floor]&.[](:down)&.any?
return floor.to_s[1..-1].to_i, :down
end
end
p $people_pool.pool
return nil, nil
end
end
def moving_to_target_floor(out_target_floor, action)
if out_target_floor
@current_floor = out_target_floor
@current_action = action
else
@current_floor = case @current_action
when :up
target_floors_in_elevator.first
when :down
target_floors_in_elevator.last
end
end
puts "#{@id}: floor #{@current_floor}, #{@current_action}"
sleep(1)
end
def out_people
outing = @people.select { |p| p == @current_floor }
puts "#{@id}: out people #{outing}"
outing.each do |person|
sleep(0.2)
end
@people = @people.select { |p| p != @current_floor }
end
def in_people
can_in_count = @max_quantity - @people.count
# TODO
# @people << PeoplePool.pool[@current_floor][@current_action]
# .pop(can_in_count)
$people_pool.mutex.synchronize do
@people.push(*$people_pool.shift(@current_floor, @current_action, can_in_count))
end
puts "#{@id}: Elevator people: #{@people}"
end
def run_to_a_target(out_target_floor=nil, action=nil)
moving_to_target_floor(out_target_floor, action)
out_people
in_people
end
end
$people_pool = PeoplePool.new
threads = (1..5).map do |i|
elevator = Elevator.new(i)
Thread.new do
# $people_pool.mutex.synchronize do
elevator.running
# end
end
end
threads.each(&:join)
| true
|
e44eeca41f281db57154786b51c5a73b1b8d6736
|
Ruby
|
robinwu9000/App-Academy-Work
|
/w3d2/items.rb
|
UTF-8
| 794
| 2.96875
| 3
|
[] |
no_license
|
require_relative 'questions_db'
class Item
def self.db
QuestionsDatabase::instance
end
def db
self.class.db
end
def self.tbl_name
raise NotImplementedError
end
def self.find_by_id(id)
data = db.execute(<<-SQL, id)
SELECT *
FROM #{self.tbl_name}
WHERE id = ?
SQL
self.new(data.first)
end
def ==(other)
self.class == other.class && self.id == other.id
end
def save
id ? update : insert
end
protected
def update
raise NotImplementedError
end
def insert
raise NotImplementedError
end
def self.find_by_fieldname(field_name, value)
rows = db.execute(<<-SQL, value)
SELECT *
FROM #{self.tbl_name}
WHERE #{field_name} = ?
SQL
rows.map {|row| self.new(row)}
end
end
| true
|
625d8a4feee25ffb753bfc7964efb5f875995bfc
|
Ruby
|
chemunoz/Ironhack
|
/Day Exercises/WEEK4/DAY2/shortener/app/models/link.rb
|
UTF-8
| 183
| 2.609375
| 3
|
[] |
no_license
|
class Link < ActiveRecord::Base
def self.short(chars)
#result=(0..2).map { (97 + rand(26)).chr }.join
Array.new(chars.to_i){[ *'a'..'z', *'A'..'Z'].sample}.join
end
end
| true
|
930aa479cb531a8807c0787b76990938f8d4ec27
|
Ruby
|
SarahDrake01/ruby-class-variables-and-class-methods-lab-london-web-082619
|
/lib/song.rb
|
UTF-8
| 1,660
| 4.15625
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
class Song
#Define your `Song` class such that an individual song is initialized with a name, artist and genre.
#There should be an `attr_accessor` for those three attributes.
attr_accessor :name, :artist, :genre
@@count = 0
@@artists = []
@@genres = []
#Create a classe variable @@count.
#I used this variable to keep track of the number of new songs that are created from the song class.
#Your `#initialize` method should use the
# `@@count` variable and increment the value of that variable by `1`.
def initialize(song_name,artist,genre)
@name = song_name
@artist = artist
@genre = genre
@@count += 1
@@artists << artist
@@genres << genre
end
#Write a class method, `.count`, that resturns the total
#number of songs created.
def self.count
@@count
end
def self.artists
@@artists.uniq
end
#Create a class variablr genres that returns ans array
#of all of the genres of existings songs.
#This array should contain only unique genres no duplicates.
def self.genres
@@genres.uniq
end
#Write a class method genre_count, that returns a hash in which
#the keys are the names os each genre. Each genre key should
#point to a value that is the number of songs that have that genre.
def self.genre_count
genre_count = Hash.new(0)
@@genres.each {|genre| genre_count[genre] += 1}
genre_count
end
#Write a class method , artist_count, that returns
#a histogram similar to the genre_count, but for artist
#rather than genres.
def self.artist_count
artist_count = Hash.new(0)
@@artists.each {|artist| artist_count[artist] += 1}
artist_count
end
end
| true
|
03f6870368348529a7872846f78b0e44f7e075cd
|
Ruby
|
tulios/pong
|
/lib/pong/elements/ball.rb
|
UTF-8
| 2,555
| 2.703125
| 3
|
[] |
no_license
|
# encoding: utf-8
module Pong
class Ball < Chingu::GameObject
include Gosu
include Chingu
trait :bounding_box, :debug => false
traits :velocity, :collision_detection
DEFAULT_MOVIMENT_UNIT = 4
attr_accessor :moviment_unit, :bar
def initialize options = {}
@bar = options.delete :bar
super options.merge(:image => Image["resources/bola.png"])
@moviment_unit = DEFAULT_MOVIMENT_UNIT
reset_position!
calculate_velocity_y!
cache_bounding_box
end
def width
self.image.width
end
def height
self.image.height
end
def reset_position!
self.x = ((Pong.width + width) / 2) - (width / 2)
self.y = 150
@direction = :down
self.velocity_x = 0
calculate_velocity_y!
end
def up?
@direction == :up
end
def reach_top?
self.y <= 0
end
def reach_bottom?
self.y >= Pong.height
end
def reach_sides?
self.x <= 0 or self.x >= Pong.width
end
def under_the_bar?
self.y > @bar.y
end
def hit!
calculate_velocity_x!
end
def change_direction!
@direction = up? ? :down : :up
calculate_velocity_y!
end
def force_right!
self.velocity_x = self.velocity_x.abs
end
def force_left!
self.velocity_x = -self.velocity_x.abs
end
def force_side!
self.x < @bar.x ? self.force_left! : self.force_right!
end
def move!
self.y = up? ? self.y - @moviment_unit : self.y + @moviment_unit
end
def update
super
move!
if reach_top?
change_direction!
calculate_velocity_y!
end
self.velocity_x = (-1 * self.velocity_x) if reach_sides?
self.each_bounding_box_collision(Block) do |ball, block|
if block.visible? and not block.destroyed?
block.hit!
hit!
change_direction!
block.elastic? ? calculate_velocity_y!(1, 1) : calculate_velocity_y!
@bar.player.score += 50
@bar.player.update_score!
end
end
end
private
def calculate_velocity_y! random = 1, bonus = 0
value = 1 + rand(random)
self.velocity_y = up? ? (-value - bonus) : (+value + bonus)
end
def calculate_velocity_x! random = 5
value = @moviment_unit + rand(random)
self.velocity_x = if self.velocity_x == 0
(rand(2) == 0) ? -value : +value
else
(self.velocity_x <= 0) ? -value : +value
end
end
end
end
| true
|
1ceaeaa0b71fb400043fa6e09b02eb4e52167173
|
Ruby
|
NightFeather/pixiv
|
/lib/pixiv/illust/manga.rb
|
UTF-8
| 758
| 2.59375
| 3
|
[] |
no_license
|
require 'pixiv/downloader/task'
require 'pixiv/string_template'
module Pixiv
module Illust
class Manga < Base
attr_reader :page_count, :images
def download_meta template = '?user? - ?title?/?idx?'
ctr = Pixiv::Downloader::Task.new []
@images.each_pair do |idx, image|
filename = Pixiv::StringTemplate.convert template, self, idx: idx.to_s.rjust(2,'0')
filename += File.extname image
ctr.filelist << { src: image, dest: filename }
end
return ctr
end
def extract obj
super
@page_count = obj["page_count"]
@images = Hash[obj["meta_pages"].each_with_index.map { |page, idx| [idx, page["image_urls"]["original"]] }]
end
end
end
end
| true
|
9d33fb561c5d612acb622cd88d2e8fb03ffcfbc6
|
Ruby
|
abigoroth/kira-telegram-bot
|
/kira.rb
|
UTF-8
| 4,042
| 2.828125
| 3
|
[] |
no_license
|
require 'telegram/bot'
require "active_record"
require 'date'
require 'caxlsx'
db_config_admin = {
'database' => 'kira',
'schema_search_path' => 'public',
'adapter' => 'postgresql',
'encoding' => 'utf-8',
'pool' => 5
}
ActiveRecord::Base.establish_connection(db_config_admin)
token = <token>
class Expenses < ActiveRecord::Base
end
def get_expenses(month, year, chat_id)
Expenses.where("extract(month from created_at) = #{month} and extract(year from created_at) = #{year} and chat_id = '#{chat_id}'")
end
Telegram::Bot::Client.run(token) do |bot|
bot.listen do |message|
# begin
expenses = get_expenses(Time.now.month , Time.now.year, message.chat.id)
puts message.inspect
msg = message.text.split(" ") rescue []
case msg[0]
when '/help', '/start'
help_msg = "List of commands: \n"
help_msg << "/l : Listing your expenses \n"
help_msg << "/a <item> <price> : Adding expenses record. Item name can be spaced. \n"
help_msg << "/d <id> : Removing expenses \n"
help_msg << "/g <month> <year> : Getting expenses for a month of a year.\n"
help_msg << "Thank you. Please contact yakob.ubaidi@gmail.com for any issue."
bot.api.send_message(chat_id: message.chat.id, text: help_msg)
when '/l', '/list'
puts '/list'
tmp = "Expenses for #{Date::MONTHNAMES[Time.now.month]} #{Time.now.year} \n"
expenses.each_with_index do |e, idx|
tmp << "#{idx+1}. #{e.name.strip} (id:" + e.id.to_s + ") : #{e.price} \n"
end
tmp << "Total : RM#{expenses.sum(:price)}"
bot.api.send_message(chat_id: message.chat.id, text: tmp)
when '/d' , '/del'
if msg[1]
Expenses.find(msg[1]).destroy
bot.api.send_message(chat_id: message.chat.id, text: "Expenses deleted")
end
when '/g' , '/get_month'
if msg[1] && msg[2]
expenses = get_expenses(msg[1], msg[2], message.chat.id)
tmp = "Expenses for #{msg[1]} #{msg[2]} : \n"
expenses.each_with_index do |e, idx|
tmp << "#{idx+1}. #{e.name} (id:" + e.id.to_s + ") : #{e.price} \n"
end
tmp << "Total : RM#{expenses.sum(:price)}"
bot.api.send_message(chat_id: message.chat.id, text: tmp)
else
bot.api.send_message(chat_id: message.chat.id, text: "use /get_month <month> <year>")
end
when '/a', '/add'
splitted = message.text.split(" ")
namex = splitted[1..-2].join(" ")
price = splitted[-1]
if namex && price && namex != price
tmp = Expenses.create(name: namex, price: price, created_at: Time.now, chat_id: "#{message.chat.id}")
sum = expenses.sum(:price)
bot.api.send_message(chat_id: message.chat.id, text: "Expenses #{namex} (id:#{tmp.id}) added. Total expenses for this month is RM#{sum} ")
end
# Expenses.create(name: name, price: price, created_at: Time.now, chat_id: message.chat.id)
when 'export'
p = Axlsx::Package.new
month = expenses.group_by{|x| x.created_at.beginning_of_month }.keys.map{|x| x.strftime("%m %y") }
month_keys = expenses.group_by{|x| x.created_at.beginning_of_month }.keys
month.each do |m|
p.workbook.add_worksheet(:name => m) do |sheet|
sheet.add_row ["No", "Item", "Price", "Created"]
expenses.group_by{|x| x.created_at.beginning_of_month }[ month_keys[ month.index(m) ] ].each_with_index do |row,idx|
sheet.add_row [idx+1, row.name, row.price, row.created_at]
end
end
p.use_shared_strings = true
end
p.serialize("#{message.chat.id}.xlsx")
# bot.api.send_document(File.open("#{message.chat.id}.xlsx"))
`curl -v -F "chat_id=#{message.chat.id}" -F document=@#{message.chat.id}.xlsx https://api.telegram.org/bot#{token}/sendDocument`
end
# rescue Exception => e
# bot.api.send_message(chat_id: message.chat.id, text: e)
# end
end
end
| true
|
524f35c2a024140303c866896aa537f4ef70c90e
|
Ruby
|
presto53/rfusefs
|
/spec/pathmapper_spec.rb
|
UTF-8
| 6,445
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
#Pathmapper is hard to test because it is difficult to mock Dir/Pathname/File etc...
require "spec_helper"
require "fusefs/pathmapper"
require 'tmpdir'
require 'pathname'
class PMFixture
attr_reader :tmpdir
def initialize()
@tmpdir = Pathname.new(Dir.mktmpdir("rfusefs_pathmapper"))
pathmap(@tmpdir + "hello.txt","/textfiles/hello")
pathmap(@tmpdir + "mysong.mp3","/artist/album/mysong.mp3")
pathmap(@tmpdir + "apicture.jpeg","/pictures/201103/apicture.jpg")
end
def pathmap(real_file,mapped_path)
File.open(real_file.to_s,"w") do |f|
f << mapped_path
end
end
def fs
@fs ||= FuseFS::PathMapperFS.create(@tmpdir) do |file|
File.file?(file) ? IO.read(file.to_s) : nil
end
end
def mount()
return @mountpoint if @mountpoint
@mountpoint = Pathname.new(Dir.mktmpdir("rfusefs_pathmapper_mnt"))
FuseFS.mount(fs,@mountpoint)
sleep(0.5)
@mountpoint
end
def cleanup
if @mountpoint
FuseFS.unmount(@mountpoint)
sleep(0.5)
FileUtils.rmdir(@mountpoint)
end
FileUtils.rm_r(@tmpdir)
end
end
describe FuseFS::PathMapperFS do
before(:each) do
@fixture = PMFixture.new
@tmpdir = @fixture.tmpdir
@pathmapFS = @fixture.fs
end
after(:each) do
@fixture.cleanup
end
context "fusefs api" do
it "maps files and directories" do
@pathmapFS.directory?("/").should be_true
@pathmapFS.directory?("/textfiles").should be_true
@pathmapFS.directory?("/pictures/201103").should be_true
@pathmapFS.file?("/textfiles/hello").should be_true
@pathmapFS.directory?("/textfiles/hello").should be_false
@pathmapFS.file?("/artist/album/mysong.mp3").should be_true
@pathmapFS.directory?("/artist/album/mysong.mp3").should be_false
@pathmapFS.file?("/some/unknown/path").should be_false
@pathmapFS.directory?("/some/unknown/path").should be_false
end
it "lists the mapped contents of directories" do
@pathmapFS.contents("/").should =~ [ "textfiles","artist","pictures" ]
@pathmapFS.contents("/artist").should =~ [ "album" ]
@pathmapFS.contents("/textfiles").should =~ [ "hello" ]
end
it "reports the size of a file" do
@pathmapFS.size("/textfiles/hello").should == 16
end
it "reads the contents of a file" do
@pathmapFS.read_file("/textfiles/hello").should == "/textfiles/hello"
end
it "does not allow writes" do
@pathmapFS.can_write?("/textfiles/hello").should be_false
end
it "reports the atime,mtime and ctime of the mapped file" do
atime,mtime,ctime = @pathmapFS.times("/pictures/201103/apicture.jpg")
picture = @tmpdir + "apicture.jpeg"
atime.should == picture.atime()
mtime.should == picture.mtime()
ctime.should == picture.ctime()
end
it "reports filesystem statistics"
context "writing to a pathmapped FS" do
before(:each) do
@pathmapFS.allow_write=true
@pathmapFS.write_to("textfiles/hello","updated content")
end
it "updates the contents of the real file" do
hello_path = @tmpdir + "hello.txt"
hello_path.read.should == "updated content"
end
it "updates the contents of the mapped file" do
@pathmapFS.read_file("textfiles/hello").should == "updated content"
end
it "changes the reported file size" do
@pathmapFS.size("textfiles/hello").should == 15
end
it "changes the filesystem statistics"
end
end
context "a real Fuse mounted filesystem" do
before(:each) do
@pathmapFS.allow_write=true
@mountpoint = @fixture.mount
end
it "maps files and directories" do
(@mountpoint + "textfiles").directory?.should be_true
(@mountpoint + "textfiles/hello").file?.should be_true
end
it "lists the mapped contents of directories" do
(@mountpoint + "textfiles").entries.should =~ pathnames(".","..","hello")
end
it "represents the stat information of the underlying files" do
hellopath=(@mountpoint + "textfiles/hello")
realpath=(@tmpdir + "hello.txt")
mappedstat = hellopath.stat
realstat = realpath.stat
mappedstat.size.should == realstat.size
mappedstat.atime.should == realstat.atime
mappedstat.mtime.should == realstat.mtime
mappedstat.ctime.should == realstat.ctime
end
it "reads the files" do
hellopath= @mountpoint + "textfiles/hello"
hellopath.read.should == "/textfiles/hello"
end
it "writes the files" do
hellopath= @mountpoint + "textfiles/hello"
real_path = @tmpdir + "hello.txt"
hellopath.open("w") do |f|
f.print "updated content"
end
hellopath.read.should == "updated content"
real_path.read.should == "updated content"
end
end
context "a real Fuse mount with raw file access" do
before(:each) do
@pathmapFS.use_raw_file_access = true
@pathmapFS.allow_write = true
@mountpoint = @fixture.mount
end
it "reads files" do
hello_path = (@mountpoint + "textfiles/hello")
hello_path.open do |f|
f.seek(2)
f.read(3).should == "ext"
end
hello_path.sysopen do |f|
f.sysseek(1)
f.sysread(3).should == "tex"
end
end
it "writes files" do
hello_path = (@mountpoint + "textfiles/hello")
real_path = @tmpdir + "hello.txt"
hello_path.open("r+") do |f|
f.sysseek(2)
f.syswrite("zzz")
f.sysseek(0)
f.sysread(6).should == "/tzzzf"
end
real_path.read.should == "/tzzzfiles/hello"
end
end
end
| true
|
36b4cfa7a1498a0db21f49880ea9e753df7a803b
|
Ruby
|
kbanana/ada
|
/student_acct_gen.rb
|
UTF-8
| 913
| 3.625
| 4
|
[] |
no_license
|
#starting variables
student_names = []
student_ids = []
student_emails = []
num_students = 5
# gets student names from the user and puts them in an array
num_students.times do
puts "Please enter a student name (FIRST LAST) >"
student_names << gets.chomp.upcase
end
# generates random student ID numbers and puts them in an array
num_students.times do |name|
student_ids << rand(111111..999999).to_s
end
num_students.times do |i|
#gets the first intitial of the first name
first_intial = student_names[i][0]
#gets the last name
last_name = student_names[i].split(" ").last
#gets the last three digits of the ID
email_id = student_ids[i][3,3]
#generates email string and pushes to array
student_emails << "#{first_intial}#{last_name}#{email_id}@adadevelopersacademy.org"
end
#prints names, IDs, and emails in parallel
num_students.times do |i|
puts "#{student_names[i]} #{student_ids[i]} #{student_emails[i]}"
end
| true
|
61a2a92d61d99f1130cbca78dca75ccab3ad2a25
|
Ruby
|
18F/identity-idp
|
/app/services/profanity_detector.rb
|
UTF-8
| 1,715
| 3.328125
| 3
|
[
"CC0-1.0",
"LicenseRef-scancode-public-domain"
] |
permissive
|
# Detects profanity in a string, the list of profane words
# comes from the profanity_filter gem for now
module ProfanityDetector
module_function
# Calls a block until the result does not contain profanity
# @yield block that generates a random value
# @yieldreturn [String] string to check for profanity
def without_profanity(limit: 1_000)
limit.times do
word = yield
return word unless profane?(word)
end
raise 'random generator limit'
end
# Returns true if the string contains profanity inside it
# ProfanityFilter::Base.profane? splits by word, but this
# checks all substrings
def profane?(str)
preprocess_if_needed!
str_no_whitespace = str.gsub(/\W/, '').downcase
(min_profanity_length..[str_no_whitespace.length, max_profanity_length].min).each do |size|
profane_regex = @regex_by_length[size]
next if profane_regex.nil?
return true if profane_regex.match?(str_no_whitespace)
end
false
end
class << self
attr_reader :min_profanity_length
attr_reader :max_profanity_length
end
def preprocess_if_needed!
return if @preprocessed
# Map of {Integer => Set<string>}
profanity_by_length = Hash.new { |h, k| h[k] = Set.new }
ProfanityFilter::Base.dictionary.keys.each do |word|
profanity_by_length[word.size] << word.downcase
end
# Map of {Integer => Regexp}
@regex_by_length = Hash.new
profanity_by_length.each do |k, v|
escaped = v.to_a.map { |x| Regexp.escape(x) }
@regex_by_length[k] = Regexp.new("(#{escaped.join('|')})")
end
@min_profanity_length, @max_profanity_length = profanity_by_length.keys.minmax
@preprocessed = true
end
end
| true
|
cdd3c59a305a386294b5bb51caebead0ff24ac02
|
Ruby
|
palhamel/Ruby_exercises
|
/interpolation.rb
|
UTF-8
| 219
| 3.625
| 4
|
[] |
no_license
|
# Using String Interpolation
# https://www.digitalocean.com/community/tutorials/how-to-work-with-strings-in-ruby
my_name = "Arnie the Globetrotter"
my_age = 78
output = "My name is #{my_name} and my age is #{my_age}."
puts output
| true
|
08667c55923f50242420789152f8e2b218e4f727
|
Ruby
|
lungla-gael/Binary-Search-Trees
|
/Tree.rb
|
UTF-8
| 835
| 3.453125
| 3
|
[] |
no_license
|
require './Node.rb'
class Tree
attr_accessor :root
def initialize(array)
@root = build_tree(array.uniq)
end
def build_tree(array)
res = {}
array.each do |num|
difference = (array.filter{|a| a < num}.count - array.filter{|a| a > num}.count).abs
res[num] = difference
end
balanced = []
res.each { |key,value| balanced.push(key) if value === res.values.min }
Node.new(balanced[rand(balanced.length)]).tap do |tree|
array.each { |v| tree.insert v }
end
end
def insert(value)
root.insert(value)
end
def delete(value)
root.delete(value)
end
def find(value)
root.find(value)
end
def level_order(root_node)
root_node.level_order(root_node,[],[])
end
end
| true
|
d8329bb0434485ce7901e603d09457238c30abbf
|
Ruby
|
ogeidix/collaborative_editing
|
/app/insertion.rb
|
UTF-8
| 1,910
| 2.671875
| 3
|
[] |
no_license
|
###############################################################################
## Insertion
###############################################################################
## represents the Insertion change and inherits the behaviour from the Change class
## See change.rb for help
##
require_relative 'change'
module CollaborativeEditing
class Insertion < Change
attr_reader :content
def initialize (author, position, new_content)
super(author, position)
@content = new_content
end
def new_position
new_offset = @position.offset + @content.length
return Position.new(@position.node, new_offset, @position.version+1)
end
def conflict?(positions, history)
return false
end
def to_hash
super({:content => @content})
end
def perform_transformation(other_position)
new_offset = other_position.offset
if other_position.node == @position.node
if other_position.offset >= @position.offset
new_offset += @content.length
end
end
return Position.new(other_position.node, new_offset, @position.version+1)
end
def perform_change(document)
parent_node = REXML::XPath.first document.rexml_doc, @position.parent_node
i = 0
n = 0
c = @position.child_number.to_i
while (i < c) do
i +=1 if(parent_node.children[n].class == REXML::Text)
n += 1
end
current_node = parent_node.children[n-1]
prefix = current_node.value[0, @position.offset]
suffix = current_node.value[@position.offset, current_node.value.length]
current_node.value = prefix + @content + suffix
end
end
end
| true
|
ac705275cb89c67a9d7c2b8142c4564f49033546
|
Ruby
|
ppietrasik/weblog_parser
|
/lib/weblog_parser/unique_views_count.rb
|
UTF-8
| 730
| 2.671875
| 3
|
[] |
no_license
|
# frozen_string_literal: true
module WeblogParser
class UniqueViewsCount
def self.from_log_entries(log_entries)
log_entries
.group_by(&:webpage)
.transform_values(&by_uniq_ip)
.transform_values(&:count)
.map { |webpage, unique_views| new(webpage, unique_views) }
end
def initialize(webpage, unique_views)
@webpage = webpage
@unique_views = unique_views
end
attr_reader :webpage, :unique_views
def to_s
"#{webpage} #{unique_views} unique views"
end
def <=>(other)
unique_views <=> other.unique_views
end
def self.by_uniq_ip
->(entries) { entries.uniq(&:ip) }
end
private_class_method :by_uniq_ip
end
end
| true
|
7f5e721800ae0d020cab84c4d042c3d4f75db8d1
|
Ruby
|
square-circle-triangle/her
|
/lib/her/model/orm.rb
|
UTF-8
| 5,563
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
module Her
module Model
# This module adds ORM-like capabilities to the model
module ORM
# Initialize a new object with data received from an HTTP request
# @private
def initialize(single_data={}) # {{{
@data = {}
cleaned_data = single_data.inject({}) do |memo, item|
key, value = item
send "#{key}=".to_sym, value unless value.nil?
respond_to?("#{key}=") ? memo : memo.merge({ key => value })
end
@data.merge! self.class.parse_relationships(cleaned_data)
end # }}}
# Initialize a collection of resources
# @private
def self.initialize_collection(name, collection_data) # {{{
collection_data.map { |item_data| Object.const_get(name.to_s.classify).new(item_data) }
end # }}}
# Handles missing methods by routing them through @data
# @private
def method_missing(method, attrs=nil) # {{{
assignment_method = method.to_s =~ /\=$/
method = method.to_s.gsub(/(\?|\!|\=)$/, "").to_sym
if !attrs.nil? and assignment_method
@data ||= {}
@data[method.to_s.gsub(/\=$/, "").to_sym] = attrs
else
if @data and @data.include?(method)
@data[method]
else
super
end
end
end # }}}
# Override the method to prevent from returning the object ID (in ruby-1.8.7)
# @private
def id # {{{
@data[:id] || super
end # }}}
# Initialize a collection of resources with raw data from an HTTP request
#
# @param [Array] collection_data An array of model hashes
def new_collection(collection_data) # {{{
Her::Model::ORM.initialize_collection(self.to_s.underscore, collection_data)
end # }}}
# Return `true` if a resource was not saved yet
def new? # {{{
!@data.include?(:id)
end # }}}
# Fetch a specific resource based on an ID
#
# @example
# @user = User.find(1)
# # Fetched via GET "/users/1"
def find(id, params={}) # {{{
request(params.merge(:_method => :get, :_path => "#{build_request_path(params.merge(:id => id))}")) do |parsed_data|
new(parsed_data[:data])
end
end # }}}
# Fetch a collection of resources
#
# @example
# @users = User.all
# # Fetched via GET "/users"
def all(params={}) # {{{
request(params.merge(:_method => :get, :_path => "#{build_request_path(params)}")) do |parsed_data|
new_collection(parsed_data[:data])
end
end # }}}
# Create a resource and return it
#
# @example
# @user = User.create({ :fullname => "Tobias Fünke" })
# # Called via POST "/users/1"
def create(params={}) # {{{
resource = new(params)
wrap_in_hooks(resource, :create, :save) do |resource, klass|
params = resource.instance_eval { @data }
request(params.merge(:_method => :post, :_path => "#{build_request_path(params)}")) do |parsed_data|
resource.instance_eval do
@data = parsed_data[:data]
@errors = parsed_data[:errors]
end
end
end
resource
end # }}}
# Save an existing resource and return it
#
# @example
# @user = User.save_existing(1, { :fullname => "Tobias Fünke" })
# # Called via PUT "/users/1"
def save_existing(id, params) # {{{
resource = new(params.merge(:id => id))
resource.save
end # }}}
# Save a resource
#
# @example Save a resource after fetching it
# @user = User.find(1)
# # Fetched via GET "/users/1"
# @user.fullname = "Tobias Fünke"
# @user.save
# # Called via PUT "/users/1"
#
# @example Save a new resource by creating it
# @user = User.new({ :fullname => "Tobias Fünke" })
# @user.save
# # Called via POST "/users"
def save # {{{
params = { self.model_name => @data.dup }
resource = self
if @data[:id]
hooks = [:update, :save]
method = :put
else
hooks = [:create, :save]
method = :post
end
self.class.wrap_in_hooks(resource, *hooks) do |resource, klass|
klass.request(params.merge(:_method => method, :_path => "#{request_path}")) do |parsed_data|
_data = parsed_data[:data].blank? ? params[self.model_name] : parsed_data[:data]
@data = _data
@errors = parsed_data[:errors]
end
end
self
end # }}}
# Destroy a resource
#
# @example
# @user = User.find(1)
# @user.destroy
# # Called via DELETE "/users/1"
def destroy # {{{
params = @data.dup
resource = self
self.class.wrap_in_hooks(resource, :destroy) do |resource, klass|
klass.request(params.merge(:_method => :delete, :_path => "#{request_path}")) do |parsed_data|
@data = parsed_data[:data]
end
end
self
end # }}}
# Destroy an existing resource
#
# @example
# User.destroy_existing(1)
# # Called via DELETE "/users/1"
def destroy_existing(id, params={}) # {{{
request(params.merge(:_method => :delete, :_path => "#{build_request_path(params.merge(:id => id))}")) do |parsed_data|
new(parsed_data[:data])
end
end # }}}
end
end
end
| true
|
df8a3eedebd481f47e1cf59fb359ac1b726bba62
|
Ruby
|
NaisHRT/Ruby-Exercices
|
/exo_08.rb
|
UTF-8
| 250
| 3.828125
| 4
|
[] |
no_license
|
puts "Give me a number : "
print "> "
number = gets.chomp.to_i
i = 0
while i < number
number = number - 1
puts number
end
#demande un nombre à l'utilisateur, puis qui affiche un compte à rebours à partir de ce nombre, jusqu'à 0.
| true
|
a1e28ad2cac7a5694fd99ca755d27230527f72e4
|
Ruby
|
itggot-elias-stenhede/standard-biblioteket
|
/dev/factorial.rb
|
UTF-8
| 122
| 3.015625
| 3
|
[] |
no_license
|
def factorial(max)
sum = 1
i = 1
while i < max
i += 1
sum = sum * i
end
return sum
end
| true
|
6c9cb9fe1bfb8104540f6b4bf38f682044c6a93c
|
Ruby
|
DanL12186/ttt-3-display_board-example-bootcamp-prep-000
|
/lib/display_board.rb
|
UTF-8
| 261
| 2.640625
| 3
|
[] |
no_license
|
# Define a method display_board that prints a 3x3 Tic Tac Toe Board
def display_board
spacer = " | | "
lines = "-----------"
puts spacer
puts lines
puts spacer
puts lines
puts spacer
end
#[[["|","|","|"], ["|","|","|"], ["|","|","|"]]]
| true
|
86e9384c6f74f237b180ab2562b70d708e0fa0a3
|
Ruby
|
yuheik/leetcode
|
/21_merge_two_sorted_lists.rb
|
UTF-8
| 1,282
| 3.625
| 4
|
[] |
no_license
|
#! /usr/bin/ruby
# Definition for singly-linked list.
class ListNode
attr_accessor :val, :next
def initialize(val)
@val = val
@next = nil
end
end
def main(l1, l2)
p l1
p l2
head = ListNode.new(-1)
first = head
while (l1 && l2)
if (l1.val < l2.val)
tmp = l1.next
first.next = l1
l1 = tmp
else
tmp = l2.next
first.next = l2
l2 = tmp
end
first = first.next
end
if (l1.nil?)
first.next = l2
end
if (l2.nil?)
first.next = l1
end
p "answer----------"
p head.next
return head.next
end
if __FILE__ == $0
p "hogehoe"
((inp1 = ListNode.new(1)).next = ListNode.new(2)).next = ListNode.new(4)
p inp1
((inp2 = ListNode.new(1)).next = ListNode.new(3)).next = ListNode.new(4)
p inp2
((((exp = ListNode.new(1)).next =ListNode.new(1)).next =ListNode.new(2)).next =ListNode.new(3)).next = ListNode.new(4)
p exp
testcases = [
[[inp1, inp2], exp],
# [[], ""]
]
testcases.each do |testcase|
input = testcase[0]
expect = testcase[1]
puts "input #{input}"
puts "expect #{expect}"
result = main(input[0], input[1])
if (result == expect) ; puts "OK"
else ; puts "NG (result: #{result})"
end
puts "\n"
end
end
| true
|
81a6c5c9986996c3f2c50bc885a1a1003b68570a
|
Ruby
|
Icehawk78/payments_exercise
|
/app/models/loan.rb
|
UTF-8
| 393
| 2.5625
| 3
|
[] |
no_license
|
class Loan < ActiveRecord::Base
has_many :payments
# Current Balance = Funded Amount - SUM(Payments)
def balance
self.payments.map(&:amount).reduce(self.funded_amount, :-)
end
def as_json(options={})
# Uncomment if you want to expose payments on the index/show endpoints for loans
# super(include: [:payments], methods: :balance)
super(methods: :balance)
end
end
| true
|
62a4a86ab8ff416057a810662e046900ea2b6ee5
|
Ruby
|
regru/reg_api2-ruby
|
/spec/lib/reg_api2/sym_hash_spec.rb
|
UTF-8
| 2,108
| 3
| 3
|
[
"MIT"
] |
permissive
|
# -*- encoding : utf-8 -*-
describe RegApi2::SymHash do
let!(:hash) { RegApi2::SymHash.new }
describe :new do
it "should be kind of Hash" do
expect(hash).to be_kind_of(Hash)
end
end
describe :method_missing do
it "should assign key" do
hash.unique_key = "unique"
expect(hash["unique_key"]).to eq("unique")
end
it "should reassign key" do
hash["next_key"] = "a"
hash.next_key = "b"
expect(hash["next_key"]).to eq("b")
end
it "should return value" do
hash["another_key"] = "f"
expect(hash.another_key).to eq("f")
end
it "should return bool if key ends with ?" do
hash.ping = 15
expect(hash).to be_ping
hash.pong = nil
expect(hash).not_to be_pong
end
it "should return nil unless keypair present" do
expect(hash.absent_key).to be_nil
end
end
describe :respond_to? do
it "should always respond to any method" do
expect(hash).to respond_to(:any_method)
end
end
describe :include? do
it "should be has_key?" do
allow(hash).to receive(:has_key?).with("what").and_return(true)
expect(hash.include?("what")).to be true
end
end
describe :has_key? do
it "should represent symbol keys as strings" do
hash["frank"] = 56
expect(hash[:frank]).to eq(56)
expect(hash).to have_key("frank")
expect(hash).to have_key(:frank)
hash[:bravo] = 56
expect(hash["bravo"]).to eq(56)
expect(hash).to have_key("bravo")
expect(hash).to have_key(:bravo)
end
end
describe "self.from" do
it "should deeply clone structures with replacing hashes with SymHash" do
res = RegApi2::SymHash.from([{a: 1}, {b: 2}, [ 1, 2, 3 ]])
expect(res).to be_kind_of(Array)
expect(res).to have_exactly(3).elements
expect(res.first).to be_kind_of(RegApi2::SymHash)
expect(res[1]).to be_kind_of(RegApi2::SymHash)
expect(res.last).not_to be_kind_of(RegApi2::SymHash)
expect(res.last).to be_kind_of(Array)
expect(res.last).to eq([ 1, 2 , 3 ])
end
end
end
| true
|
e649b39e4f0aa74ae16c540deab33eee404242bf
|
Ruby
|
murtala/RubyTraining
|
/If_Else.rb
|
UTF-8
| 197
| 3.234375
| 3
|
[] |
no_license
|
x=1
if x>2
puts "x >2"
elseif x ==1 #else if not else-if like in java
puts "x =1"
else
puts "x<2"
end
# if can be used to check if something is true
$debug=0
print "debug\n" if $debug
| true
|
4d2851c67f651cf7c99f2de2fe9002099bf63e5a
|
Ruby
|
KarenSJW/ruby-automail
|
/mail_example.rb
|
UTF-8
| 663
| 2.5625
| 3
|
[] |
no_license
|
#!/usr/local/bin/ruby
require 'csv'
require 'net/smtp'
# 讀取csv
_receiver = ""
CSV.foreach("mail_headphone.csv") do |row|
_mail = <<MESSAGE_CONTENT
From: kevenkmupsy@gmail.com
To: #{row[2]}
Subject: headphone問卷發信測試
#{row[1]}你好
這是致伸科技的使用者經驗部門
請至以下連結填寫問卷:http://tinyurl.com/khdrgs9
在問卷開頭填入你專屬的代號#{row[0]}即可
最後別忘了在問卷最後填寫你的收件地址和收件姓名
我們會將禮券寄送給你
MESSAGE_CONTENT
Net::SMTP.start('smtp.gmail.com', 587, 'kevenkmupsy@gmail.com', 'kevenkmupsy', '9922cola', :plain) do |smtp|
smtp.send_message( _mail, row[2])
end
end
| true
|
f372aedbd4e8c4547bdcffd64f3e2c31733fb96a
|
Ruby
|
eyelean7/primes
|
/spec/prime_spec.rb
|
UTF-8
| 271
| 2.859375
| 3
|
[] |
no_license
|
require ("rspec")
require ("prime")
require ("pry")
describe('Fixnum#prime') do
it('returns primes up to a given number') do
expect(5.prime()).to(eq('2 3 5'))
end
it('returns primes up to a given number') do
expect(10.prime()).to(eq('2 3 5 7'))
end
end
| true
|
45e590b10184e4c298924443f596b46c0afecf90
|
Ruby
|
conciergelive/is_taggable_rails3
|
/test/tag_test.rb
|
UTF-8
| 1,415
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
require 'test_helper'
class TagTest < Minitest::Test
def teardown
Tag.destroy_all
end
def test_association
t = Tag.new
if t.respond_to?(:association)
assert_equal Tagging, t.association(:taggings).reflection.klass
else
assert_equal Tagging, t.taggings.proxy_reflection.klass
end
end
def test_duplicate_invalid
Tag.create!(:name => "duplicate")
refute Tag.new(:name => "duplicate").valid?
end
def test_dupes_across_kinds
assert Tag.create!(:name => "not dup", :kind => "something")
assert Tag.new(:name => "not dup").valid?
end
def test_tag_requires_name
refute Tag.new.valid?
end
def test_tag_errors
t = Tag.new
t.valid?
m = t.errors[:name]
assert_equal String, m.is_a?(Array) ? m.first.class : m.class
end
def test_find_or_initialize_with_name_like_and_kind
tag = Tag.create!(:name => "iamawesome", :kind => "awesomestuff")
assert_equal tag.id, Tag.find_or_initialize_with_name_like_and_kind("iaMawesome", "awesomestuff").id
end
def test_creating_and_finding_tag
tag = Tag.create!(:name => "iamawesome", :kind => "stuff")
assert Tag.find_or_initialize_with_name_like_and_kind("iaMawesome", "otherstuff").new_record?
end
def test_create_tag_and_find_by_kind
tag = Tag.create!(:kind => "language", :name => "french")
assert_equal tag.id, Tag.of_kind("language").first.id
end
end
| true
|
5951518637818fa23411f331d8a1fee51cba6d98
|
Ruby
|
aldelcy/IronHack-Class
|
/Week 2/Day 1/Sinatra/lib/todolist.rb
|
UTF-8
| 479
| 3.46875
| 3
|
[] |
no_license
|
class TodoList
attr_reader :tasks
def initialize
@tasks = []
end
def add_task(task)
@tasks << task
@tasks
end
def delete_task(task_id)
@task_id = task_id
@tasks.delete_if{ |item| item.id == @task_id}
end
def find_task_by_id(task_id)
@task_id = task_id
task_index = @tasks.find{|item| item.id==@task_id}
end
end
# list = TodoList.new
# list.add_task("Walk the dog")
# list.add_task("Buy the Milk")
# puts list.tasks
# list
| true
|
61c49f91b9c465bf5f7d9255150e9498f1d2eaf2
|
Ruby
|
hendricius/deliveries
|
/app/models/services/timetable.rb
|
UTF-8
| 4,283
| 3
| 3
|
[] |
no_license
|
class Timetable
# FIXME - Mit einbeziehen von TW durch zwei Zahlen in jedem Feld der Matrix.
# Neue Bedingung Auftragszeit <= TW && kleinste tTT
# FIXME - neue Methode für ein Fahrzeug - zwei Ordern betrachten, die beiden kürzesten und deren Einfluss auf die nächst schnellste
attr_accessor :driver_order_times, :orders, :drivers, :initial_table, :totaltime, :driver_order_times
def initialize(orders:[], drivers:[])
self.orders = orders
self.drivers = drivers
self.driver_order_times = []
self.totaltime = 0
end
# Assigns orders to drivers
def assign_based_on_algorithm!
#Matrix vorberteiten
build_timetable!
# Store the initial table for later reporting purposes
self.initial_table = driver_order_times
orders_count = orders.length
puts "MMMPDP"
count = 1
while orders_count > 0 do
# Schnellsten Carrier herausfinden
fastest_combination = fastest.clone
# Order dem schnellsten Carrier zu sortieren
order = fastest_combination.order.clone
driver = fastest_combination.driver
driver.set_order(fastest_combination.tour)
if orders_count > 1
# Order entfernen, weil bereits bearbeitet
remove_order!(order)
end
# Zeit in der Matrix neuberechnen
recalculate_driver_time!(fastest_combination.driver)
orders_count = orders_count - 1
end
# Report
drivers.each do |driver|
puts "#{driver.name} fährt #{driver.tour.time.round(2)} ZE"
if driver.id ="c1"
driver.tour.tour.each do |element|
puts element.name
end
end
self.totaltime = self.totaltime + driver.tour.time
end
puts "Gesamtfahrzeit: #{self.totaltime.round(2)} ZE"
end
# Matrix erstellen
def build_timetable!
orders.each do |order|
drivers.each do |driver|
add_driver_order_time(
DriverOrderTime.new(driver: driver, order: order, tour: driver.komplexe_tour(order).clone)
)
end
end
# Array mit allen Driver/Order Zeiten füllen
driver_order_times
end
def add_driver_order_time(driver_order_time)
self.driver_order_times += [driver_order_time]
end
# Return schnellste DriverOrderTime.
def fastest
fastest = driver_order_times.first
# Return nil wenn nur ein Element
if !fastest
return nil
end
# Abbruch wenn in der Matrix nur ein Element ist
return fastest if driver_order_times.length == 1
# Schnellste Tour/Carrier finden
driver_order_times.each do |driver_order_time|
if driver_order_time.tour.time < fastest.tour.time
fastest = driver_order_time.clone
end
end
fastest
end
#Matrixfeld enthalten zwei Infos (Array mit zwei Einträgen. 1. Zeit für Auftrag und 2. tTT)
#FIXME - Noch nicht für zwei Infos ausgelegt
def fastest_TW
fastest = driver_order_times.first
# Return nil wenn nur ein Element
if !fastest
return nil
end
# Abbruch wenn in der Matrix nur ein Element ist
return fastest if driver_order_times.length == 1
# Schnellste Tour/Carrier finden
driver_order_times.each do |driver_order_time|
if driver_order_time.tour.time < fastest.tour.time
fastest = driver_order_time.clone
end
end
fastest
end
# Removes all driver order times that contain a specific order
def remove_order!(order)
self.driver_order_times = driver_order_times.reject {|driver_order_time| driver_order_time.order.id == order.id }
driver_order_times
end
# Returns all the unique orders.
def orders_unique
driver_order_times.map{|dto| dto.order}.uniq
end
# Returns all the timetable times
def times
driver_order_times.map{|dto| dto.tour.time}
end
# Returns all the timetable unique drivers
def drivers_unique
driver_order_times.map{|dto| dto.order}.uniq
end
def recalculate_driver_time!(driver)
# Get all the combinations for the driver
combinations = driver_order_times.select {|driver_order_time| driver_order_time.driver.id == driver.id }
# Recalculate the time for each
combinations.each do |driver_order_time|
driver_order_time.tour = driver.komplexe_tour(driver_order_time.order).clone
end
end
end
| true
|
ba6ef9500d65af1b801f15a3ba9b92ade17d221e
|
Ruby
|
swathinimmala/dijkstra
|
/spec/dijkstra_spec.rb
|
UTF-8
| 1,513
| 3.25
| 3
|
[] |
no_license
|
require "spec_helper"
require_relative '../dijkstra'
describe "Dijkstra" do
before(:all) do
@matrix = [
[0, 7, 9, 0, 0, 14],
[7, 0, 10, 15, 0, 0],
[9, 10, 0, 11, 0, 2],
[0, 15, 11, 0, 6, 0],
[0, 0, 0, 6, 0, 9],
[14, 0, 2, 0, 9, 0]
]
end
context "accepts matrix and source parameters" do
it "accepts (matrix, src ) as parameters" do
expect { Dijkstra.new(@matrix, 0 ) }.to_not raise_error
end
it "raises an error without parameters" do
expect { Dijkstra.new }.to raise_error(ArgumentError)
end
it "raises an error with one parameter" do
expect { Dijkstra.new(@matrix) }.to raise_error(ArgumentError)
end
end
context "calculate shortest path" do
context "from source 1" do
subject { Dijkstra.new(@matrix, 0) } # index of 1 is 0
it "should give valid shortest paths" do
expect(subject.dijkstra).to eq([0, 7, 9, 20, 20, 11])
end
it "should not give invalid shortest paths" do
expect(subject.dijkstra).to_not eq([0,7,9,12])
end
end
context "from source 2" do
subject { Dijkstra.new(@matrix, 1) } # index of 2 is 1
it "should give valid shortest paths" do
expect(subject.dijkstra).to eq([7,0,10,15,21,12])
end
it "should not give invalid shortest paths" do
expect(subject.dijkstra).to_not eq([0,7,9,12])
end
end
it "should fail with invalid source" do
dijkstra = Dijkstra.new(@matrix, 9)
expect {dijkstra.dijkstra}.to raise_error
end
end
end
| true
|
8a1a7aa791019abc8906bcdaa6a72edbb88c5ae7
|
Ruby
|
hn4ever/AloeBae
|
/app/models/product.rb
|
UTF-8
| 768
| 2.65625
| 3
|
[] |
no_license
|
class Product < ApplicationRecord
belongs_to :merchant
has_and_belongs_to_many :categories
has_many :reviews
validates :name, presence: true, uniqueness: {case_sensitive: false}
validates :price, presence: true, numericality: {greater_than: 0}
validates :merchant, presence: true
scope :available, -> { where(discontinued: false).where.not(inventory: 0) }
def out_of_stock
self.inventory == 0
end
def average_rating
avg_rating = reviews.where.not(rating: nil).sum(:rating)
total_reviews = reviews.count(:rating)
return nil if total_reviews.zero? || avg_rating.zero?
avg_rating /= total_reviews
return avg_rating
end
def decrease_inventory(amount_to_decrease)
self.inventory -= amount_to_decrease
end
end
| true
|
ab0fe00ab7f5bcad9398b035d41fccbc236e0a68
|
Ruby
|
testertina/Euler-3
|
/euler3.rb
|
UTF-8
| 951
| 4.0625
| 4
|
[] |
no_license
|
require 'prime'
class Euler3
def multiple_of(multiple, number)
number / multiple
end
def highest_prime(number)
all_primes = number.prime_division
last_prime = all_primes.last # This will give us [6857, 1]
# We only want the first one
puts last_prime[0] # or last_prime.first
end
# def multiples_of(number)
# range = (1..(number/2))
# multiples = []
# range.each do |i|
# if number % i == 0
# multiples.push(i)
# end
# end
# multiples
# end
# def if_num_prime(num)
# range = (2...(num / 2))
# count = 0
# range.each do |i|
# if num % i == 0
# count +=1
# end
# end
# count
# end
# def prime_array(number)
# array = multiples_of(number)
# even_array = []
# for num in array do
# if if_num_prime(num) == 0
# even_array.push(num)
# end
# end
# p even_array[-1]
# end
end
x = Euler3.new
# x.multiples_of(600851475143)
x.highest_prime(600851475143)
| true
|
7f392b288ca45855a71e249a5ddc9e8efac161db
|
Ruby
|
fbado66/key-for-min-value-nyc04-seng-ft-071220
|
/key_for_min.rb
|
UTF-8
| 347
| 3.53125
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
# prereqs: iterators, hashes, conditional logic
# Given a hash with numeric values, return the key for the smallest value
def key_for_min_value(name_hash)
smallest_value = 10000
name_hash.each do |key, value|
if value < smallest_value
smallest_value = value
end
end
smallest_value
name_hash.key(smallest_value)
end
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.