text stringlengths 10 2.61M |
|---|
require "yaml"
# Add a .sum method to all arrays, for convenience
class Array
def sum
self.reduce(&:+) # & is `to_proc`
# self.reduce(:+) works here, but not for all functions taking a block
# self.reduce { |a,b| a + b }
end
end
path = ARGV.first || raise("Please specify a file to load")
puts "Reading file from path: #{path}"
widgets = YAML.load_file path
puts "The most expensive widget:"
puts widgets.max_by { |w| w[:price] }
puts
puts "The least expensive widget:"
puts widgets.min_by { |w| w[:price] }
puts
puts "Total revenue:"
revenue = widgets.map { |w| w[:price] * w[:sold] }.sum
puts "$#{revenue}"
puts
puts "Total profit:"
profit = widgets.map do |w|
profit_per = w[:price] - w[:cost_to_make]
profit_per * w[:sold]
end.sum # Note: this works the same as the same as the sum above
puts "$#{profit}"
puts
puts "Best sellers:"
widgets.sort_by { |w| -w[:sold] }.first(10).each_with_index do |w,i|
puts "#{i+1}) #{w[:name]}"
end
puts
puts "Department stats:"
# Overly clever solution
breakdown = widgets.
group_by { |w| w[:department] }.
map { |d,ws| [d, ws.map { |w| w[:sold] }.sum] }
# Probably better
breakdown = widgets.each_with_object({}) do |widget, hash|
department = widget[:department]
hash[department] ||= 0
hash[department] += widget[:sold]
end
breakdown.sort_by { |_,count| -count }.each do |department, count|
puts "#{department} sold #{count} widgets"
end
|
require 'orocos/test'
describe Orocos::OutputReader do
if !defined? TEST_DIR
TEST_DIR = File.expand_path(File.dirname(__FILE__))
DATA_DIR = File.join(TEST_DIR, 'data')
WORK_DIR = File.join(TEST_DIR, 'working_copy')
end
include Orocos::Spec
it "should not be possible to create an instance directly" do
assert_raises(NoMethodError) { Orocos::OutputReader.new }
end
it "should offer read access on an output port" do
Orocos.run('simple_source') do |source|
source = source.task('source')
output = source.port('cycle')
# Create a new reader. The default policy is data
reader = output.reader
assert(reader.kind_of?(Orocos::OutputReader))
assert_equal(nil, reader.read) # nothing written yet
end
end
it "should allow to read opaque types" do
Orocos.run('echo') do |source|
source = source.task('Echo')
output = source.port('output_opaque')
reader = output.reader
source.configure
source.start
source.write_opaque(42)
sleep(0.2)
# Create a new reader. The default policy is data
sample = reader.read
assert_equal(42, sample.x)
assert_equal(84, sample.y)
end
end
it "should allow reusing a sample" do
Orocos.run('echo') do |source|
source = source.task('Echo')
output = source.port('output_opaque')
reader = output.reader
source.configure
source.start
source.write_opaque(42)
sleep(0.2)
# Create a new reader. The default policy is data
sample = output.new_sample
returned_sample = reader.read(sample)
assert_same returned_sample, sample
assert_equal(42, sample.x)
assert_equal(84, sample.y)
end
end
it "should be able to read data from an output port using a data connection" do
Orocos.run('simple_source') do |source|
source = source.task('source')
output = source.port('cycle')
source.configure
source.start
# The default policy is data
reader = output.reader
sleep(0.2)
assert(reader.read > 1)
end
end
it "should be able to read data from an output port using a buffer connection" do
Orocos.run('simple_source') do |source|
source = source.task('source')
output = source.port('cycle')
reader = output.reader :type => :buffer, :size => 10
source.configure
source.start
sleep(0.5)
source.stop
values = []
while v = reader.read_new
values << v
end
assert(values.size > 1)
values.each_cons(2) do |a, b|
assert(b == a + 1, "non-consecutive values #{a.inspect} and #{b.inspect}")
end
end
end
it "should be able to read data from an output port using a struct" do
Orocos.run('simple_source') do |source|
source = source.task('source')
output = source.port('cycle_struct')
reader = output.reader :type => :buffer, :size => 10
source.configure
source.start
sleep(0.5)
source.stop
values = []
while v = reader.read_new
values << v.value
end
assert(values.size > 1)
values.each_cons(2) do |a, b|
assert(b == a + 1, "non-consecutive values #{a.inspect} and #{b.inspect}")
end
end
end
it "should be able to clear its connection" do
Orocos.run('simple_source') do |source|
source = source.task('source')
output = source.port('cycle')
reader = output.reader
source.configure
source.start
sleep(0.5)
source.stop
assert(reader.read)
reader.clear
assert(!reader.read)
end
end
it "should raise ComError if the remote end is dead and be disconnected" do
Orocos.run 'simple_source' do |source_p|
source = source_p.task('source')
output = source.port('cycle')
reader = output.reader
source.configure
source.start
sleep(0.5)
source_p.kill(true, 'KILL')
assert_raises(Orocos::CORBA::ComError) { reader.read }
assert(!reader.connected?)
end
end
it "should get an initial value when :init is specified" do
Orocos.run('echo') do |echo|
echo = echo.task('Echo')
echo.start
reader = echo.ondemand.reader
assert(!reader.read, "got data on 'ondemand': #{reader.read}")
echo.write(10)
sleep 0.1
assert_equal(10, reader.read)
reader = echo.ondemand.reader(:init => true)
sleep 0.1
assert_equal(10, reader.read)
end
end
describe "#disconnect" do
it "disconnects from the port" do
task = new_ruby_task_context 'test' do
output_port 'out', '/double'
end
reader = task.out.reader
reader.disconnect
assert !reader.connected?
assert !task.out.connected?
end
it "does not affect the port's other connections" do
task = new_ruby_task_context 'test' do
output_port 'out', '/double'
end
reader0 = task.out.reader
reader1 = task.out.reader
reader0.disconnect
assert !reader0.connected?
assert reader1.connected?
assert task.out.connected?
end
end
if Orocos::SelfTest::USE_MQUEUE
it "should fallback to CORBA if connection fails with MQ" do
begin
Orocos::MQueue.validate_sizes = false
Orocos::MQueue.auto_sizes = false
Orocos.run('echo') do |echo|
echo = echo.task('Echo')
reader = echo.ondemand.reader(:transport => Orocos::TRANSPORT_MQ, :data_size => Orocos::MQueue.msgsize_max + 1, :type => :buffer, :size => 1)
assert reader.connected?
end
ensure
Orocos::MQueue.validate_sizes = true
Orocos::MQueue.auto_sizes = true
end
end
end
end
|
Given(/^I am on the capital one home page$/) do
visit(StatementsPage)
end
When(/^I click the "([^"]*)" link in the footer$/) do |footer_link|
on(StatementsPage).select_link footer_link
end
Then(/^I land on the url "(.*?)"$/) do |url|
on(StatementsPage).wait_until do
@browser.windows.last.url.include? url
end
end
Then(/^I land on the form resubmission page$/) do
expect(@browser.windows.last.url).not_to include("/login")
expect(@browser.windows.last.url).not_to include("/mfaha")
end
When(/^I Click on the Legal Disclosures page$/) do
on(StatementsPage).legal_disclosures
end
Given(/^the user logs in with header footer account$/) do
visit(LoginPage)
on(LoginPage) do |page|
DataMagic.load('default.yml')
username = page.data_for(:header_footer_account)['username']
password = page.data_for(:header_footer_account)['password']
ssoid = page.data_for(:header_footer_account)['ssoid']
page.login(username, password, ssoid)
end
visit(StatementsPage)
on(StatementsPage).wait_for_page_to_load
end
Then(/^The year has changed I should see the current year reflected in the copyright date in the footer.$/) do
time=Time.new
on(StatementsPage).dynamic_year.include? time.year.to_s
end
When(/^I click the link in the footer, then I expect to land on the correct page$/) do |table|
table.raw.each do |footer_link, url|
on(StatementsPage) do |page|
page.wait_for_footer_to_load
page.select_link footer_link
page.wait_for_external_page_to_load
end
expect(@browser.windows.last.url).to include url
end
end |
require 'spec_helper'
require 'resque'
describe Item do
it { should validate_presence_of(:name) }
it { should validate_presence_of(:price_in_dollars) }
it { should validate_numericality_of(:price_in_dollars, :allow_blank => true) }
it { should validate_length_of(:name, :maximum => 255) }
it { should belong_to(:user) }
end
describe Item, 'with price_in_dollars of 1500' do
subject { Item.new(:price_in_dollars => 1500) }
its(:price) { should == 1500_00 }
end
describe Item, 'with price_in_dollars of FooBar' do
subject { Item.new(:price_in_dollars => 'FooBar') }
its(:price_in_dollars) { should == 'FooBar' }
end
describe Item, "with price_in_dollars of '10'" do
subject { Item.new(:price_in_dollars => '10') }
its(:price) { should == 1000 }
end
describe Item, "with a price_in_dollars of -10" do
subject { Item.new(:price_in_dollars => -10) }
its(:price) { should == -1000 }
it { should have_an_invalid(:price_in_dollars) }
end
describe "given today is April fools" do
before(:each) { Timecop.freeze Time.utc( 2010, 04, 01 ) }
describe Item, "bought yesterday" do
subject { Item.new(:when => 'Yesterday') }
its(:when) { should == Date.new( 2010, 03, 31 ) }
end
describe Item, "bought today" do
subject { Item.new(:when => 'Today') }
its(:when) { should == Date.new( 2010, 04, 01 ) }
end
describe Item, "bought last friday" do
subject { Item.new(:when => "Last friday") }
its(:when) { should == Date.new(2010, 03, 26) }
end
describe Item, "bought this friday" do
subject { Item.new(:when => "this friday") }
its(:when) { should == Date.new(2010, 04, 02) }
end
end
describe Item, "with a photo_url" do
before(:each) do
FakeWeb.register_uri(:get, "http://test.host/picture.png", :body => "data")
end
subject {
Factory.build(:item, :photo => nil, :photo_url => "http://test.host/picture.png")
}
context "when the photo exists" do
before(:each) do
@picture = File.read(root_path('spec/fixtures/files/picture.png'))
FakeWeb.register_uri(:get, "http://test.host/picture.png", :body => @picture)
end
it { should be_valid }
it "should save the photo from the url" do
subject.save!
subject.photo_file_name.should_not be_nil
end
end
context "when the does not exist" do
before(:each) do
FakeWeb.register_uri(:get, "http://test.host/picture.png",
:body => '', :status => ["404", "Not Found"])
end
it { should_not be_valid }
end
end
describe Item, "successfully posted" do
it "should be broadcasted to twitter" do
user = Factory(:user)
item = Factory.build(:item, :user => user)
item.should_receive(:broadcast_to_twitter)
item.save
end
end
describe Item, "#broadcast_to_twitter" do
before(:each) do
Resque.stub!(:enqueue)
FakeWeb.register_uri(:post, "http://twitter.com/statuses/update.json",
:body => {:id => 123145}.to_json)
@item = Factory(:item, :user => Factory(:user))
end
describe "on success" do
it "saves the twitter status id to the item" do
Resque.should_receive(:enqueue).with(Purchase, @item.id, @item.user_id)
@item.twitter_status_id = nil
@item.broadcast_to_twitter
end
end
describe "on failure" do
it "sets the twitter status id to nil" do
FakeWeb.register_uri(:post, "http://twitter.com/statuses/update.json",
:body => '', :status => ["404", "Not Found"])
@item.broadcast_to_twitter
@item.twitter_status_id.should be_nil
end
end
end
describe Item, "with no src twitter status id" do
it "should be creatable" do
lambda {
Factory(:item)
}.should_not raise_error(ActiveRecord::RecordInvalid)
end
end
describe Item, "with a src twitter status id that doesn't exist yet" do
it "should be creatable" do
lambda {
Factory(:item, :src_twitter_status_id => 1001)
}.should_not raise_error(ActiveRecord::RecordInvalid)
end
context "when another item comes in with the same src twitter status id" do
it "should not be creatable" do
Factory(:item, :src_twitter_status_id => 1001)
lambda {
Factory(:item, :src_twitter_status_id => 1001)
}.should raise_error(ActiveRecord::RecordInvalid)
end
end
end
describe Item, "with a date like Nov 28, 2009" do
subject do
@item = Item.new(:when => "Nov 28, 2009")
@item.valid?
@item
end
its(:when) { should == Date.new(2009, 11, 28) }
end
describe Item, "with an unparseable date like 'Last Foobar'" do
subject do
@item = Item.new(:when => "Last FooBar")
end
it { should_not be_valid }
it do
subject.valid?
subject.errors[:when].should_not be_empty
end
end
describe Item, "with no date given" do
subject do
@item = Item.new(:when => "")
end
it { should_not be_valid }
it do
subject.valid?
subject.errors[:when].should be_empty
end
end
|
class Reply < ActiveRecord::Base
validates_length_of :raw, :within => 3..900, :too_long => "De reactie is te lang", :too_short =>"De reactie is te kort."
belongs_to :kunstvoorwerp
belongs_to :user
end
|
# Author:: Marta Garcia (mailto:alu0101015927@ull.edu.es)
# Copyright:: Cretive Commons
# License:: Distributes under the same terms as Ruby
#
# == Estructura Node
# Esta estructura se ha creado para describir a los nodos
# que contiene la clase lista
#
Node = Struct.new(:value, :next, :prev)
#
# == Clase List
# Esta clase se ha creado para describir el comportamiento
# de una lista doblemente enlazada.
# Se ha incluido el mixin Enumerable
# * initialize
# * insert
# * extract
# * to_s
# * length
# * empty
# * each
#
class List
include Enumerable, Comparable
attr_accessor :head, :tail
# Se ponen a nil el nodo del inicio y del final
def initialize
@head = nil
@tail = nil
end
# Se inserta un valor por el final
def insert(value)
node = Node.new(value, nil, @tail)
@head = node if @head.nil?
@tail.next = node unless @tail.nil?
@tail = node
end
# Se extrae un nodo por el inicio
def extract
return nil if self.empty
aux = @head
@head = @head.next
@head.prev = nil unless @head.nil?
@tail = nil if @head.nil?
aux.next = nil
aux
end
# Se convierte en string la lista
def to_s
node = Node.new(nil,nil,nil)
node = @head
tmp = "{"
if !(node.nil?)
tmp += " #{node.value.to_s}"
node = node.next
end
while !(node.nil?)
tmp += ", #{node.value.to_s}"
node = node.next
end
tmp += " }"
tmp
end
# Se calcula la longitud de la lista
def length
size = 0
node = @head
while !(node.nil?)
size = size + 1
node = node.next
end
size
end
# Se calcula si la lista está vacia
def empty
@head.nil?
end
# Se incluye el metodo del mixin Enumerable
# Se define como una iteracion sobre los nodos de la lista
def each(&block)
node = Node.new(nil,nil,nil)
node = @head
while !(node.nil?)
yield node.value
node = node.next
end
end
def sort_for
tmp = map{|x| x.gasto_energetico_total}
orden = []
orden.push(tmp[0])
for i in (1..length - 1)
for j in (0..i)
if(orden[j] >= tmp[i])
orden.insert(j,tmp[i])
break
elsif(orden[orden.length - 1] <= tmp[i])
orden.push(tmp[i])
break
end
end
end
orden
end
def sort_each
tmp = map{ |x| x.gasto_energetico_total}
i = 0
tmp.each do |x|
a = x
i1 = i
j = i1 + 1
tmp[j..tmp.length - 1].each do |y|
if (a > y)
a = y
i1 = j
end
j+=1
end
tmp[i1] = x
tmp[i] = a
i+=1
end
tmp
end
end
#
# == Metodo clasificar
# Este metodo se ha creado para describir la
# clasificacion de una lista de etiquetas
# nutricionales en funcion de la cantidad de
# sal y la cantidad de ingesta recomendada
def clasificar (lista)
sal_ir = List.new()
sal_mal = List.new()
node = lista.extract
while !(node.nil?)
if node.value.sal > 6
sal_mal.insert(node.value.sal)
else
sal_ir.insert(node.value.sal)
end
node = lista.extract
end
"{#{sal_ir.to_s}, #{sal_mal.to_s}}"
end
#
# == Metodo clasificar_imc
# Este metodo se ha creado para describir la
# clasificacion de una lista de paciente en
# funcion del imc para comprobar si tienen o
# no obesidad
#
def clasificar_imc (lista)
con_ob = List.new()
sin_ob = List.new()
node = lista.extract
while !(node.nil?)
if node.value.datos.indice_masa_corporal >= 30.0
con_ob.insert(node.value.datos.indice_masa_corporal)
else
sin_ob.insert(node.value.datos.indice_masa_corporal)
end
node = lista.extract
end
clasificacion = List.new
clasificacion.insert(sin_ob)
clasificacion.insert(con_ob)
clasificacion.to_s
end
|
class AddDefaultValueToPriceCents100 < ActiveRecord::Migration[5.2]
def change
change_column :tshirts, :price_cents, :integer, :default => 2500
end
end
|
class Game
@@dictionary = File.open("dictionary.txt").map do |line|
line.chomp
end
attr_reader :fragment
def initialize(*players)
@players = players
@fragment = ''
@losses = Hash.new(0)
end
def self.dictionary
@@dictionary
end
def valid_play?(letter)
return false if !('a'..'z').include?(letter) && letter.length != 1
@@dictionary.any? do |word|
word.start_with?(fragment + letter)
end
end
def in_dictionary?
@@dictionary.any? do |word|
word == fragment
end
end
def next_player!
@players.rotate!
end
def take_turn(player)
player.guess { |letter| valid_play?(letter) }
end
def computer_turn(computer)
computer.guess(@fragment, @players.size) { |letter| valid_play?(letter) }
end
def record(player)
"GHOST".slice(0, @losses[player])
end
def display_standings
puts "\nScoreboard:"
@players.each do |player|
puts "#{player.name}: #{record(player)}"
end
end
def lost_game?
@losses.values.include?(5)
end
def remove_player(player)
@players.delete(player)
@losses.delete(player)
end
def play_round
loop do
current_player, previous_player = @players.first, @players.last
guess = current_player.kind_of?(AiPlayer) ? computer_turn(current_player) : take_turn(current_player)
puts "\n#{current_player.name} chose #{guess}"
@fragment += guess
puts "\nFragment: #{fragment}\n"
if in_dictionary?
@losses[current_player] += 1
puts "#{current_player.name} lost!!\n"
display_standings
break
end
next_player!
end
end
def run
loop do
@fragment = ''
play_round
if lost_game?
losing_player = @losses.key(5)
puts "#{losing_player.name} has been dropped from the game."
remove_player(losing_player)
end
break if @players.length == 1
end
puts "#{@players.first.name} wins the game!"
end
end
|
require './telegraph'
describe 'telegraph' do
it 'should decode morse signal arrays' do
expect(decode([DOT])).to eq('E')
expect(decode([DOT, DOT, DOT])).to eq('S')
expect(decode([DASH, DOT, DOT, DOT, DOT])).to eq('6')
expect(decode([DOT, DOT, DASH, DASH])).to eq('?')
end
it 'should convert bits into morse signal arrays' do
expect(bits_to_signals "1").to eq([[DOT]])
expect(bits_to_signals "111").to eq([[DASH]])
expect(bits_to_signals "101").to eq([[DOT, DOT]])
expect(bits_to_signals "10111").to eq([[DOT, DASH]])
end
it 'should split characters on runs of three zeros' do
expect(bits_to_signals "10001").to eq([[DOT], [DOT]])
expect(bits_to_signals "111010001110001").to eq([[DASH, DOT], [DASH], [DOT]])
end
it 'should treat runs of two ones as dots and runs of four or more ones as dashes' do
expect(bits_to_signals "11").to eq([[DOT]])
expect(bits_to_signals "1111").to eq([[DASH]])
expect(bits_to_signals "111110011").to eq([[DASH, DOT]])
expect(bits_to_signals "11111000011").to eq([[DASH], [DOT]])
end
it 'should encode strings to morse signal arrays' do
expect(encode('E')).to eq([[DOT]])
expect(encode('Q')).to eq([[DASH, DASH, DOT, DASH]])
expect(encode('HI')).to eq([[DOT, DOT, DOT, DOT], [DOT, DOT]])
end
it "should upcase strings and ignore characters it doesn't know" do
expect(encode('e²')).to eq([[DOT]])
expect(encode('hi?')).to eq([[DOT, DOT, DOT, DOT], [DOT, DOT]])
expect(encode('u2')).to eq([[DOT, DOT, DASH], [DOT, DOT, DASH, DASH, DASH]])
end
it "should convert signals to a bit array" do
expect(signals_to_bits([[DOT]])).to eq([1])
expect(signals_to_bits([[DASH]])).to eq([1, 1, 1])
expect(signals_to_bits([[DASH, DOT]])).to eq([1, 1, 1, 0, 1])
expect(signals_to_bits([[DASH, DOT], [DOT, DASH]])).to eq([1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1])
end
end |
# frozen_string_literal: true
require 'test_helper'
class DeployTaskTest < KubernetesDeploy::TestCase
include EnvTestHelper
def test_that_it_has_a_version_number
refute_nil(::KubernetesDeploy::VERSION)
end
def test_initializer
KubernetesDeploy::DeployTask.new(
namespace: "",
context: "",
logger: logger,
current_sha: "",
template_paths: ["unknown"],
).run
assert_logs_match("Configuration invalid")
assert_logs_match("Namespace must be specified")
assert_logs_match("Context must be specified")
assert_logs_match(/File (\S+) does not exist/)
end
end
|
RSpec::Matchers.define :have_audit_row do |expected|
match do |actual|
actual.all(:xpath, "//tr[td[contains(.,'#{expected}')]]").any?
end
failure_message do |actual|
"expected that a table row for audit '#{expected}' would be found"
end
failure_message_when_negated do |actual|
"expected that a table row for audit '#{expected}' would not be found"
end
end
|
require 'digest/sha1'
class User < ActiveRecord::Base
# Virtual attribute for the unencrypted password
attr_accessor :password
attr_protected :is_admin
attr_protected :twitter_friend_with
has_many :claims, :order => "created_at desc", :dependent => :destroy
has_many :scores, :order => "created_at desc", :dependent => :destroy
has_and_belongs_to_many :friends, :class_name => 'User', :join_table => 'user_friend', :association_foreign_key => 'user_id', :foreign_key => 'friend_id', :uniq => true
has_and_belongs_to_many :friends_of, :class_name => 'User', :join_table => 'user_friend', :association_foreign_key => 'friend_id', :foreign_key => 'user_id', :uniq => true
belongs_to :team
belongs_to :city
validates_presence_of :login
validates_presence_of :password, :if => :password_required?
validates_presence_of :password_confirmation, :if => :password_required?
validates_length_of :password, :within => 3..40, :if => :password_required?
validates_confirmation_of :password, :if => :password_required?
validates_length_of :login, :within => 1..32
validates_uniqueness_of :login, :case_sensitive => false
validates_uniqueness_of :email, :case_sensitive => false, :if => Proc.new { |user| not user.email.empty? }
validates_format_of :email, :with => /(^([^@\s]+)@((?:[-_a-z0-9]+\.)+[a-z]{2,})$)|(^$)/i, :if => Proc.new { |user| not user.email.empty?}
validates_uniqueness_of :twittername, :if => Proc.new { |user| not user.twittername.empty? }
validate :colour_is_somewhat_visible
validates_presence_of :city
before_save :encrypt_password
before_save :update_twitter_friend
before_validation :random_color_if_not_set
before_validation :clean_notify_fields
before_create :initial_score_before
after_create :initial_score_after
after_create :add_initial_friend
after_save :save_team
def self.generate_password
password = "%04d" % (1+rand(9999))
end
def self.each
self.find(:all).each yield
end
def rank
@rank ||= Score.rank_for(self)
end
def spots
# super not performant
@spots ||= load_spots
end
def load_spots
spots = []
self.claims.each do |claim|
spots << claim.spot if claim.spot.current_owner == self
end
spots.uniq
end
def add_initial_friend
developers = User.find :all, :conditions => ["login in (?)", ["oneup", "consti", "stereotype", "sushimako"]]
return if developers.empty?
developers.each do |developer|
self.friends << developer
developer.friends << self
developer.save
end
self.save
end
def self.find_all_by_name name
self.find_all_by_login name
end
def self.find_by_name name
u = self.find_by_login(name)
return self.find_by_email(name) unless u
u
end
def save_team
team.save if team
end
def colour_3= value
team.colour = value if team
end
def colour_3
team.colour if team
end
def clean_notify_fields
twittername.strip! unless twittername.empty?
email.strip! unless email.empty?
end
def before_destroy
raise "not allowed to destroy users!"
end
def colour_is_somewhat_visible
if self.colour_1 == self.colour_2
self.errors.add "Colour 1 and 2 can't be the same. Other players won't be able to read your name, kbai?!"
end
end
# validate :leetness_of_password
#
# def leetnes_of_password
# # we also allow/generate only 3key passwords. but if we force a lot of non alphanumerical characters in, i hope i make htem hard to crack. but easy to type on cellphones.
# # this also creates a minigame for our uses to guess 1337 passwords (or the identifiers that give a higher leet score)
# leet_factor = 0
# %w(! " § $ € « @ % & / = ? ß ` ´ * + ' # , ; . : - _ < > ^ ° # ').each do |leet_character|
# leet_factor += 1 if self.password.include? leet_character
# end
#
# errors.add "password not 1337 enough, please use special characters, like @ in your password." if leet_factor > 1
# end
def friend_of? user
self.friends_of.each do |friend|
return true if friend == user
end
return false
end
def name
self.login || self.twittername # i think twittername is never called, but i don't know if it works the other way round if twittername is nil and not "", but is twittername nil or "". dunno. ask rails. try in script/console or ask ruby in irb. :P
end
# def self.find_florian
# self.find_by_login 'oneup'
# end
#
# def after_create
# flo = User.find_florian
# return unless flo
# self.friends = [flo]
# self.save
# flo.friends << self
# flo.save
# end
def random_color_if_not_set
self.colour_1 = "#%06x" % rand(0xffffff) if not self.colour_1 or self.colour_1.empty?
end
def initial_score_before
self.scores_seen_until = Time.now
end
def initial_score_after
self.score 50, "signed up"
end
def score!(points, description)
self.scores.create :points => points, :description => description
if points > 0
message = "bam! #{description}, got #{points} points!"
elsif points < 0
message = "fck! #{description}, lost #{points.abs} points!"
else
message = description
end
self.notify_all message
end
def score points=nil, description=nil
return score!(points, description) unless points.nil?
self.scores.inject(0) {|n, s| n += s.points}
end
def can_claim? spot
return spot.current_owner != self
end
def can_edit_spots?
is_admin?
end
def notify_all message
# don't call this function "notify". it will wreak havoc and send all kind of strange "before_save", "after_save" messages. ruby built in function names & message passing system gone wild ^_^
if should_twitter?
notify_twitter(message)
elsif should_mail? # if i'm notified via sms, i don't want a mail aswell (especially since some users get twitter notify mails)
notify_mail(message)
end
message
end
def should_twitter?
(not twittername.empty?) and is_notify_mail_on? and ENV["RAILS_ENV"] == 'production'
end
def should_mail?
(not email.empty?) and is_notify_mail_on? and ENV["RAILS_ENV"] == 'production'
end
def is_notify_mail_on?
# soon to be turned into a database field @hacketyhack
true
end
def is_notify_twitter_on?
# soon to be turned into a database field @hacketyhack
true
end
def notify_mail message
begin # maybe this try except is not needed
NotifyMailer.deliver_message(self, message)
rescue => e
logger.error(e)
#TODO: MAIL US
end
end
def notify_twitter message
begin
#TODO: probably very stupid, should be done differently. code copied from http://snippets.dzone.com/posts/show/3714 (for rest see environment.rb)
TWITTER.d(self.twittername, message) if should_twitter?
rescue Exception => e
RAILS_DEFAULT_LOGGER.error("Twitter error while sending to #{self.twittername}. Message: #{message}. Exception: #{e.to_s}.")
end
end
def claim spot
return nil unless self.can_claim? spot
my_claim = Claim.create :user => self, :spot => spot
points = 100
if my_claim.crossed_claim
my_claim.crossed_claim.user.score -20, "fck! crossed by #{self.name} at #{spot.name}"
self.score points, "crossed #{my_claim.crossed_claim.user.name} @ #{spot.name}"
else
self.score points, "claimed #{spot.name}"
end
my_claim
end
def owned_spots
self.claims.collect do |claim|
claim.spot if claim.spot.current_owner == self
end.compact.uniq
end
# Authenticates a user by their login name and unencrypted password. Returns the user or nil.
def self.authenticate(login, password)
u = find_by_login(login) || find_by_email(login)
u && u.authenticated?(password) ? u : nil
end
# Encrypts some data with the salt.
def self.encrypt(password, salt)
Digest::SHA1.hexdigest("--#{salt}--#{password}--")
end
# Encrypts the password with the user salt
def encrypt(password)
self.class.encrypt(password, salt)
end
def authenticated?(password)
crypted_password == encrypt(password)
end
def remember_token?
remember_token_expires_at && Time.now.utc < remember_token_expires_at
end
# These create and unset the fields required for remembering users between browser closes
def remember_me
self.remember_token_expires_at = 2.weeks.from_now.utc
self.remember_token = encrypt("#{email}--#{remember_token_expires_at}")
save(false)
end
def forget_me
self.remember_token_expires_at = nil
self.remember_token = nil
save(false)
end
def claims_for_last_days_grouped_by_day days_count
# this is totally not 100% correct and probably slow, but 1up doesn't mind as long as it gets the point across
now = Time.new
check_day = now - days_count.days
claims = []
while check_day <= now
claims << self.claims.find(:all, :conditions => ["created_at >= ? and created_at < ?", check_day, check_day+1.days])
check_day += 1.days
end
claims
end
def may_be_friend_of? user
return false if user == nil
return false if user == self
# todo already friend
true
end
protected
# before filter
def encrypt_password
return if password.blank?
self.salt = Digest::SHA1.hexdigest("--#{Time.now.to_s}--#{login}--") if new_record?
self.crypted_password = encrypt(password)
end
def password_required?
crypted_password.blank? || !password.blank?
end
def update_twitter_friend
if self.twitter_friend_with != self.twittername:
begin
TWITTER.create_friendship self.twittername if should_twitter?
rescue Exception => e
RAILS_DEFAULT_LOGGER.error("Twitter error while creating_friendship with #{self.twittername}. Exception: #{e.to_s}.")
end
self.twitter_friend_with = self.twittername
end
end
end
|
class UserCourseship < ActiveRecord::Base
validates_uniqueness_of :user_id, :scope => :course_id
belongs_to :user
belongs_to :course
attr_accessible :course_id, :user_id
end |
require "test_helper"
class CarbideActionTest < Minitest::Test
def test_execute_block_within_context
context = TestContext.new
action = Carbide::Action.new(context) do
self.value = 42
end
action.execute
assert_equal 42, context.value
end
def test_execute_pass_args_to_block
context = TestContext.new
action = Carbide::Action.new(context) do |arg|
self.value = arg
end
action.execute(42)
assert_equal 42, context.value
end
def test_execute_can_refer_variables_outside_of_block
context = TestContext.new
var = 42
action = Carbide::Action.new(context) do
self.value = var
end
action.execute
assert_equal 42, context.value
end
def test_execute_can_change_variables_outside_of_block
context = TestContext.new
var = 42
action = Carbide::Action.new(context) do
var += 1
end
action.execute
assert_equal 43, var
end
def test_throwing_break_stops_executing_block
context = TestContext.new
context.value = 42
action = Carbide::Action.new(context) do
throw :break
self.value = 43
end
action.execute
assert_equal 42, context.value
end
end
|
class Api::V1::ConfirmationsController < Devise::ConfirmationsController
respond_to :json
def create
self.resource = resource_class.send_confirmation_instructions(resource_params)
yield resource if block_given?
if successfully_sent?(resource)
respond_with({}, location: after_resending_confirmation_instructions_path_for(resource_name))
else
respond_with(resource)
end
end
def show
self.resource = resource_class.confirm_by_token(params[:confirmation_token])
yield resource if block_given?
if resource.errors.empty?
set_flash_message!(:notice, :confirmed)
respond_with_navigational(resource){ redirect_to after_confirmation_path_for(resource_name, resource) }
else
respond_with_navigational(resource.errors, status: :unprocessable_entity) { render :new }
end
end
protected
# The path used after confirmation.
def after_confirmation_path_for(resource_name, resource)
if signed_in?(resource_name)
signed_in_root_path(resource)
else
"#{Rails.configuration.application.frontend}/confirmrmation"
end
end
end |
class Format < ActiveRecord::Base
belongs_to :developer, :class_name => "Developer",
:foreign_key => "id_developer";
end |
class User < ApplicationRecord
has_many :course_users
has_many :courses, through: :course_users
has_many :tasks
has_many :posts
has_many :comments
#Esta asosiacion es solo si la asosiacion es directa. En este caso es indirecta pues cuenta con un modelo intermedio
#Por tal razon se utiliza has_many :course_users y has_many :users, through: :course_users
#has_and_belongs_to_many :course_users #new
#verificar los valores de maximum
validates :names, presence: true, length: { maximum: 50 }
validates :lastnames, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 64 },
format: { with: VALID_EMAIL_REGEX },
uniqueness: true
has_secure_password
validates :password, presence: true, length: { maximum: 65 }, on: :create
attr_accessor :reset_token, :rol, :img
def as_json options=nil
options ||= {}
options[:methods] = ((options[:methods] || []) + [:rol, :img])
super options
end
# Returns the hash digest of the given string.
def User.digest(string)
cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
BCrypt::Engine.cost
BCrypt::Password.create(string, cost: cost)
end
# Returns a random token.
def User.new_token
SecureRandom.urlsafe_base64
end
# Returns true if the given token matches the digest.
def authenticated?(attribute, token)
digest = send("#{attribute}_digest")
return false if digest.nil?
BCrypt::Password.new(digest).is_password?(token)
end
# Returns true if a password reset has expired.
def password_reset_expired?
reset_sent_at < 2.hours.ago
end
# Sets the password reset attributes.
def create_reset_digest
self.reset_token = User.new_token
update_attribute(:reset_digest, User.digest(reset_token))
update_attribute(:reset_sent_at, Time.zone.now)
end
# Sends password reset email.
def send_password_reset_email
UserMailer.password_reset(self).deliver_now
end
end
|
# frozen_string_literal: true
require_relative 'chronometer/dsl'
require_relative 'chronometer/event'
require_relative 'chronometer/trace_event'
require_relative 'chronometer/version'
class Chronometer
attr_reader :trace_events
def self.from_file(path, contents: File.read(path))
new do
instance_eval(contents, path)
end
end
def initialize(&blk)
dsl = DSL.new
dsl.instance_exec(&blk)
@events = dsl.events
@tracepoints = dsl.tracepoints
@trace_event_queue = Queue.new
@trace_events = []
end
def install!
@events.each { |e| install_method_hook(e) }
@tracepoints.each { |tp| install_tracepoint(tp) }
end
def drain!
loop { @trace_events << @trace_event_queue.pop(true) }
rescue ThreadError
nil
end
def associate_sub_slices!
parents = []
@trace_events.each do |event|
case event.event_type
when :B
parents << event
when :E
parent = parents.pop
event.sub_slices.replace parent.sub_slices if parent
parents.last.sub_slices << event unless parents.empty?
end
end
end
def print_trace_event_report(dest, metadata: {})
raise ArgumentError, 'cannot manually specify :traceEvents' if metadata.key?(:traceEvents)
require 'json'
File.open(dest, 'w') do |f|
f << JSON.generate(metadata)
f.seek(-1, :CUR) # remove closing }
f << ',' unless metadata.empty?
f << '"traceEvents":['
@trace_events.each_with_index do |te, i|
f << ',' unless i == 0
f << JSON.generate(te.to_h)
end
f << ']}'
end
end
def self.timestamp_us
Time.now.utc.to_f.*(1_000_000).round
end
def register_trace_event(event)
@trace_event_queue << event
end
private
def install_method_hook(event)
cls = event.cls
method = event.method
unbound_method = cls.instance_method(method)
arg_labels = unbound_method.parameters.map(&:last)
timer = self
cls.send(:define_method, method) do |*args, &blk|
context = event.context.call(self) if event.context
args_dict = arg_labels.zip(args).to_h
args_dict[:context] = context if context
start_time = ::Chronometer.timestamp_us
event_type = event.event_type
if event_type == :X
timer.register_trace_event TraceEvent.new(
process_id: Process.pid,
thread_id: Thread.current.object_id,
start_time_usec: ::Chronometer.timestamp_us,
event_type: :B,
name: event.name
)
event_type = :E
end
r0 = Process.clock_gettime(Process::CLOCK_MONOTONIC)
begin
unbound_method.bind(self).call(*args, &blk)
ensure
duration = Process.clock_gettime(Process::CLOCK_MONOTONIC).-(r0).*(1_000_000).round
timer.register_trace_event TraceEvent.new(
process_id: Process.pid,
thread_id: Thread.current.object_id,
start_time_usec: event_type == :E ? ::Chronometer.timestamp_us : start_time,
event_type: event_type,
name: event.name,
args: args_dict,
category: event.category,
duration: duration,
cls: cls,
method: method
)
end
end
end
def install_tracepoint(tracepoint)
event_name, blk = tracepoint
TracePoint.trace(event_name) do |tp|
next if tp.path == __FILE__
args = {
process_id: Process.pid,
thread_id: Thread.current.object_id,
start_time_usec: ::Chronometer.timestamp_us,
event_type: :I,
name: event_name
}
args.update blk.call(tp) if blk
te = TraceEvent.new(**args)
register_trace_event(te)
end
end
end
|
class ShortenedUrl < ApplicationRecord
validates :user_id, presence: true
validates :short_url, presence: true,
uniqueness: { scope: :user_id, message: 'Users can only have one instance of specific URL'}
validates :long_url, presence: true,
uniqueness: { scope: :user_id, message: 'Users can only have one instance of specific URL'}
belongs_to(
:requester, primary_key: :id, foreign_key: :user_id, class_name: "User"
)
end
|
require 'action_dispatch'
module TwirpRails
module Routes # :nodoc:
module Helper
def mount_twirp(name, handler: nil, scope: 'twirp')
TwirpRails.handle_dev_error "mount twirp route #{name}" do
case name
when Class
raise 'handler param required when name is a class' unless handler&.is_a?(Class)
service_class = name
when String, Symbol
service_class = Helper.constantize_first "#{name}_service", name
unless service_class
msg = "mount_twirp of #{name} error. #{name.camelize}Service or #{name.camelize} class is not found"
raise TwirpRails::Error, msg
end
handler ||= "#{name}_handler".camelize.constantize
else
raise 'twirp service name required'
end
service = service_class.new(handler.new)
Helper.run_create_hooks service
if scope
scope scope do
mount service, at: service.full_name
end
else
mount service, at: service.full_name
end
end
end
def self.constantize_first(*variants)
variants.each do |name|
clazz = name.to_s.camelize.safe_constantize
return clazz if clazz
end
nil
end
def self.install
ActionDispatch::Routing::Mapper.include TwirpRails::Routes::Helper
end
cattr_accessor :create_service_hooks
def self.on_create_service(&block)
Helper.create_service_hooks ||= []
Helper.create_service_hooks << block
end
def self.run_create_hooks(service)
return unless Helper.create_service_hooks
Helper.create_service_hooks.each do |hook|
hook.call service
end
end
end
end
end
|
=begin
irb(main):024:0> family = { uncles: ["bob", "joe", "steve"],
irb(main):025:1* sisters: ["jane", "jill", "beth"],
irb(main):026:1* brothers: ["frank","rob","david"],
irb(main):027:1* aunts: ["mary","sally","susan"]
irb(main):028:1> }
=> {:uncles=>["bob", "joe", "steve"], :sisters=>["jane", "jill", "beth"], :brothers=>["frank", "rob", "david"], :aunts=>["mary", "sally", "susan"]}
irb(main):029:0> family.select{|x,y| k == brothers || k == sisters}
NameError: undefined local variable or method `k' for main:Object
from (irb):29:in `block in irb_binding'
from (irb):29:in `select'
from (irb):29
from /usr/bin/irb:12:in `<main>'
irb(main):030:0> family.select {|x,y| x == brothers}
NameError: undefined local variable or method `brothers' for main:Object
from (irb):30:in `block in irb_binding'
from (irb):30:in `select'
from (irb):30
from /usr/bin/irb:12:in `<main>'
irb(main):031:0> family [:brothers]
=> ["frank", "rob", "david"]
irb(main):032:0> family [:brothers] [:sisters]
TypeError: no implicit conversion of Symbol into Integer
from (irb):32:in `[]'
from (irb):32
from /usr/bin/irb:12:in `<main>'
irb(main):033:0> family [:brothers], [:sisters]
SyntaxError: (irb):33: syntax error, unexpected '\n', expecting :: or '[' or '.'
from /usr/bin/irb:12:in `<main>'
irb(main):034:0> immediate_family = family.select do |k, v|
irb(main):035:1*
irb(main):036:1* k == :sisters || k == :brothers
irb(main):037:1>
irb(main):038:1* end
=> {:sisters=>["jane", "jill", "beth"], :brothers=>["frank", "rob", "david"]}
irb(main):039:0> arr = immediate_family.values.flatten
=> ["jane", "jill", "beth", "frank", "rob", "david"]
irb(main):040:0> p arr
["jane", "jill", "beth", "frank", "rob", "david"]
=> ["jane", "jill", "beth", "frank", "rob", "david"]
irb(main):041:0>
=end
family = { uncles: ["bob", "joe", "steve"],
sisters: ["jane", "jill", "beth"],
brothers: ["frank","rob","david"],
aunts: ["mary","sally","susan"]
}
#save into a variable by adding immediate_family = which wil be a new hash containing key sisters and brothers
immediate_family = family.select do |k, v| #k key v value
#determine if th key is sisters or the key is brothers
k == :sisters || k == :brothers #evaluate to true or false
# if this evaluates to true the key value pair will be returned in a new hash
end
arr = immediate_family.values.flatten
p arr
|
# -*- coding: utf-8 -*-
#
# Environment
#
# 変更不能な設定たち
# コアで変更されるもの
# CHIの設定
require 'config'
module Environment
# このアプリケーションの名前。
NAME = CHIConfig::NAME
# 名前の略称
ACRO = CHIConfig::ACRO
# pidファイル
PIDFILE = CHIConfig::PIDFILE
# コンフィグファイルのディレクトリ
CONFROOT = CHIConfig::CONFROOT
# 一時ディレクトリ
TMPDIR = CHIConfig::TMPDIR
# ログディレクトリ
LOGDIR = CHIConfig::LOGDIR
SETTINGDIR = CHIConfig::SETTINGDIR
# キャッシュディレクトリ
CACHE = CHIConfig::CACHE
# プラグインディレクトリ
PLUGIN_PATH = CHIConfig::PLUGIN_PATH
# AutoTag有効?
AutoTag = CHIConfig::AutoTag
# 再起動後に、前回取得したポストを取得しない
NeverRetrieveOverlappedMumble = CHIConfig::NeverRetrieveOverlappedMumble
class Version
extend Gem::Deprecate
OUT = 9999
ALPHA = 1..9998
DEVELOP = 0
include Comparable
attr_reader :major, :minor, :debug, :devel
alias :mejor :major
deprecate :mejor, "major", 2018, 01
def initialize(major, minor, debug, devel=0)
@major = major
@minor = minor
@debug = debug
@devel = devel
end
def to_a
[@major, @minor, @debug, @devel]
end
def to_s
case @devel
when OUT
[@major, @minor, @debug].join('.')
when ALPHA
[@major, @minor, @debug].join('.') + "-alpha#{@devel}"
when DEVELOP
[@major, @minor, @debug].join('.') + "-develop"
end
end
def to_i
@major
end
def to_f
@major + @minor/100
end
def inspect
"#{Environment::NAME} ver.#{self.to_s}"
end
def size
to_a.size
end
def <=>(other)
self.to_a <=> other.to_a
end
end
# このソフトのバージョン。
VERSION = Version.new(*CHIConfig::VERSION.to_a)
end
|
DeleteTeamStatusMutation = GraphQL::Relay::Mutation.define do
name 'DeleteTeamStatus'
input_field :team_id, !types.ID
input_field :status_id, !types.String
input_field :fallback_status_id, !types.String
return_field :team, TeamType
resolve -> (_root, inputs, ctx) {
_type_name, id = CheckGraphql.decode_id(inputs['team_id'])
team = GraphqlCrudOperations.load_if_can(Team, id, ctx)
team.delete_custom_media_verification_status(inputs['status_id'], inputs['fallback_status_id'])
{ team: team }
}
end
|
require 'net/ssh'
require_relative 'config_parser'
require 'pry'
class Deployer
attr_accessor :session
def initialize(config_parser)
@config_parser = config_parser
@ssh_config = Net::SSH
@session = Net::SSH.start('viagem', nil, config: true)
end
def configs
@config_parser.to_h
end
end |
require 'rails_helper'
describe User do
context 'when create a user' do
subject(:user) { build_stubbed(:user) }
# == Attributes ===============================================================================
# == Relationships ============================================================================
# == Validations ==============================================================================
it { is_expected.to validate_presence_of(:name) }
end
end
|
class Api::UsersController < ApplicationController
def index
@users = User.all
render "api/users/index"
end
def create
@user = User.create(user_params)
if @user.save
login(@user)
render "api/users/show"
else
render json: @user.errors.full_messages, status: 422
end
end
def update
@user = current_user
if @user
if @user.update(user_params)
render :show
else
render json: @user.errors.full_messages, status: 400
end
else
render json: "No User Found", status: 404
end
end
def show
@user = User.find_by(username: params[:username])
@posts = @user.posts
end
def following
@user = User.find_by(username: params[:username])
@users = @user.following
render "api/users/following"
end
def followers
@user = User.find_by(username: params[:username])
@followers = @user.followers
render "api/users/followers"
end
def search
if params[:query]["body"].length > 0
@users = User.where("username ~ ?", params[:query]["body"])
else
@users = User.none
end
render "api/users/search"
end
private
def user_params
params.require(:user).permit(:username, :email, :password, :image)
end
end
|
class CreateOrbitzImports < ActiveRecord::Migration
def self.up
create_table :orbitz_imports do |t|
t.column :filename, :string
t.column :created_at, :datetime
end
add_index :orbitz_imports, :filename
end
def self.down
drop_table :orbitz_imports
end
end
|
class Story < ActiveRecord::Base
include Flagging
belongs_to :author, class_name: "User"
belongs_to :parent, class_name: "Story"
belongs_to :snippet
has_many :story_tags
has_many :tags, through: :story_tags
has_many :votes
has_many :children, class_name: "Story", foreign_key: :parent_id
has_many :flags, as: :flaggable
has_many :badges
validates_presence_of :title, :on => :update
validates_presence_of :content, :on => :update
searchable do
text :title, :boost => 5.0
text :content
end
def self.published
Story.all.where(published: true).shuffle
end
def vote_count
self.votes.where(liked: true).count
end
def self.most_popular
stories = Story.all.where(published: true).sort_by(&:vote_count).reverse.take(5)
stories.map { |story| {story => story.vote_count} }
end
def self.all_most_popular
Story.all.where(published: true).sort_by(&:vote_count).reverse
end
def self.all_most_recent
Story.all.where(published: true).sort_by(&:created_at).reverse
end
def self.most_recent
Story.all.where(published: true).sort_by(&:created_at).reverse.take(5)
end
def award_badge
has_a_first_story_badge = false
self.badges.each do |badge|
has_a_first_story_badge = true if badge.title = "First Story Written"
end
return "First Story Written" if has_a_first_story_badge
if !has_a_first_story_badge
badge = Badge.create(title: "First Story Written", story_id: self.id)
self.badges << badge
return badge.title
end
end
def most_voted
current_stories = Story.all.sort_by {|story| story.votes.count }
if self.votes.count > current_stories.last.votes.count
badge = Badge.create(title: "Most Voted", story_id: self.id)
return badge.title
end
end
def remove_dangerous_html_tags!
Sanitize.fragment(self, Sanitize::Config::RESTRICTED)
end
def as_json(options={})
{ id: id,
type: "stories",
published: published,
title: title,
children: self.children }
end
def self.random_story
Story.published.first
end
end
|
require "bundler/setup"
require "rack/access_log"
RSpec.configure do |config|
# Enable flags like --only-failures and --next-failure
config.example_status_persistence_file_path = ".rspec_status"
config.expect_with :rspec do |c|
c.syntax = :expect
end
end
RSpec::Matchers.define "log_with" do |logger, level, message|
supports_block_expectations
match do |actual|
expect(logger).to receive(level).with(message)
execute_with_error_handling(&actual)
true
end
def execute_with_error_handling
yield
rescue
nil
end
end
|
# frozen_string_literal: true
require "rails_helper"
RSpec.describe ReportPresenter do
describe "#state" do
it "returns the string for the state" do
report = build(:report, state: "active")
result = described_class.new(report).state
expect(result).to eql("Active")
end
end
describe "#can_edit_message" do
it "returns the right message corresponding to the report state" do
report = build(:report, state: "active")
result = described_class.new(report).can_edit_message
expect(result).to eql(t("label.report.can_edit.active"))
report.state = "awaiting_changes"
result = described_class.new(report).can_edit_message
expect(result).to eql(t("label.report.can_edit.awaiting_changes"))
report.state = "in_review"
result = described_class.new(report).can_edit_message
expect(result).to eql(t("label.report.can_edit.in_review"))
report.state = "submitted"
result = described_class.new(report).can_edit_message
expect(result).to eql(t("label.report.can_edit.submitted"))
end
end
describe "#deadline" do
it "returns the formatted date for the deadline" do
report = build(:report, deadline: Date.today)
result = described_class.new(report).deadline
expect(result).to eql I18n.l(Date.today)
end
end
describe "#approved_at" do
it "returns the formatted datetime for the Report's approval date" do
now = Time.current
report = build(:report, approved_at: now)
result = described_class.new(report).approved_at
expect(result).to eql I18n.l(now, format: :detailed)
end
end
describe "#uploaded_at" do
context "when the report has an `export_filename`" do
it "parses the timestamp from the uploaded report's filename" do
report = build(:report, export_filename: "FQ4 2020-2021_GCRF_BA_report-20230111184653.csv")
result = described_class.new(report).uploaded_at
expect(result).to eql "2023-01-11 18:46"
end
end
context "when the report has no `export_filename`" do
it "returns nil" do
report = build(:report, export_filename: nil)
result = described_class.new(report).uploaded_at
expect(result).to be_nil
end
end
end
context "generating filenames" do
let(:report) {
build(:report,
financial_quarter: 1,
financial_year: 2020,
fund: create(:fund_activity, :gcrf),
organisation: build(:partner_organisation, beis_organisation_reference: "BOR"),
description: "My report")
}
describe "#filename_for_activities_template" do
context "non-ISPF" do
it "returns the URL-encoded filename for the activities template CSV dowload" do
result = described_class.new(report).filename_for_activities_template(is_oda: nil)
expect(result).to eql "FQ1 2020-2021-GCRF-BOR-activities_upload.csv"
end
end
context "ISPF ODA" do
it "returns the URL-encoded filename for the activities template CSV dowload" do
report.update(fund: create(:fund_activity, :ispf))
result = described_class.new(report).filename_for_activities_template(is_oda: true)
expect(result).to eql "FQ1 2020-2021-ISPF-ODA-BOR-activities_upload.csv"
end
end
context "ISPF non-ODA" do
it "returns the URL-encoded filename for the activities template CSV dowload" do
report.update(fund: create(:fund_activity, :ispf))
result = described_class.new(report).filename_for_activities_template(is_oda: false)
expect(result).to eql "FQ1 2020-2021-ISPF-non-ODA-BOR-activities_upload.csv"
end
end
end
describe "#filename_for_actuals_template" do
it "returns the URL-encoded filename for the actuals template CSV dowload" do
result = described_class.new(report).filename_for_actuals_template
expect(result).to eql "FQ1 2020-2021-GCRF-BOR-actuals_upload.csv"
end
end
describe "#filename_for_forecasts_template" do
it "returns the URL-encoded filename for the forecasts template CSV dowload" do
result = described_class.new(report).filename_for_forecasts_template
expect(result).to eql "FQ1 2020-2021-GCRF-BOR-forecasts_upload.csv"
end
end
describe "#filename_for_all_reports_download" do
it "returns the URL-encoded filename for the aggregated download of all reports" do
result = described_class.new(report).filename_for_all_reports_download
expect(result).to eql "FQ1 2020-2021-All-Reports.csv"
end
end
end
end
|
# frozen_string_literal: true
require 'feature_helper'
feature 'Admin accepts invitation' do
context 'library card login user' do
let(:library_card_org) { FactoryBot.create(:organization, :library_card_login, subdomain: 'lco') }
before do
switch_to_subdomain(library_card_org.subdomain)
@invited_user = AdminInvitationService.invite(email: 'test_invite@example.com', organization: library_card_org)
end
it 'should have an ok response' do
token = @invited_user.raw_invitation_token
visit "/users/invitation/accept?invitation_token=#{token}"
expect(page).to have_content('Set your password')
end
end
end
|
require 'rack/request'
require 'rack/less'
require 'rack/less/options'
require 'rack/less/source'
module Rack::Less
# Provides access to the HTTP request.
# Request objects respond to everything defined by Rack::Request
# as well as some additional convenience methods defined here
# => from: http://github.com/rtomayko/rack-cache/blob/master/lib/rack/cache/request.rb
class Request < Rack::Request
include Rack::Less::Options
CSS_PATH_FORMATS = ['.css']
# The HTTP request method. This is the standard implementation of this
# method but is respecified here due to libraries that attempt to modify
# the behavior to respect POST tunnel method specifiers. We always want
# the real request method.
def request_method
@env['REQUEST_METHOD']
end
def path_info
@env['PATH_INFO']
end
def http_accept
@env['HTTP_ACCEPT']
end
def path_resource_name
File.basename(path_info, path_resource_format)
end
def path_resource_format
File.extname(path_info)
end
def cache
File.join(options(:root), options(:public), options(:hosted_at))
end
# The Rack::Less::Source that the request is for
def source
@source ||= begin
source_opts = {
:folder => File.join(options(:root), options(:source)),
:cache => Rack::Less.config.cache? ? cache : nil,
:compress => Rack::Less.config.compress?
}
Source.new(path_resource_name, source_opts)
end
end
def for_css?
(http_accept && http_accept.include?(Rack::Less::MIME_TYPE)) ||
(media_type && media_type.include?(Rack::Less::MIME_TYPE )) ||
CSS_PATH_FORMATS.include?(path_resource_format)
end
def hosted_at?
File.basename(File.dirname(path_info)) == File.basename(options(:hosted_at))
end
def exists?
File.exists?(File.join(cache, "#{path_resource_name}#{path_resource_format}"))
end
# Determine if the request is for existing LESS CSS file
# This will be called on every request so speed is an issue
# => first check if the request is a GET on a css resource :hosted_at (fast)
# => don't process if a file already exists in :hosted_at
# => otherwise, check for less source files that match the request (slow)
def for_less?
get? &&
for_css? &&
hosted_at? &&
!exists? &&
!source.files.empty?
end
end
end
|
class Pizza
attr_reader :name, :toppings, :state
def initialize(name, toppings)
@name = name
@toppings = toppings
@state = 'raw'
end
def bake
puts "Baking #{name} ..."
@state = 'baked'
end
end
class PizzaStore
def take_order(pizza_type)
case pizza_type
when 'pepperoni'
pizza = Pizza.new('Pepperoni Pizza', ['pepperoni', 'shredded mozzarella cheese'])
when 'chicken'
pizza = Pizza.new('Chicken Pizza', ['chicken', 'mushroom', 'spinach'])
else
pizza = Pizza.new('Cheese Pizza', ['cheese'])
end
pizza.bake
pizza
end
end
|
class AddTypeToHistory < ActiveRecord::Migration[5.2]
def change
add_column :histories, :type_history, :integer
end
end
|
class AddCurrentPointsToUsers < ActiveRecord::Migration[6.0]
def change
add_column :users, :current_points, :integer, default: 0
end
end
|
class ReviewSerializer < ActiveModel::Serializer
attributes :id, :title, :rating, :body, :user_id, :recipe_id
end
|
require 'test_helper'
class ProductTest < ActiveSupport::TestCase
fixtures :products
test "product attributes must not be empty" do
product = Product.new
assert product.invalid?
assert product.errors[:title].any?
assert product.errors[:description].any?
assert product.errors[:price].any?
assert product.errors[:image_url].any?
end
test "product price must be positive" do
product = Product.new(title: "My book title",
description: 'desc',
image_url: 'zzz.jpg')
product.price = -1
assert product.invalid?
assert_equal "must be greater than or equal to 0.01",
product.errors[:price].join('; ')
product.price = 1
assert product.valid?
end
test "image_url shoud be an image url :)" do
p = Product.new(title: "My book title",
description: 'desc',
price: 1)
ok = %w{ fred.gif fred.jpg frend.png FRED.png }
bad = %w{ fred.doc fred.exe }
ok.each do |item|
p.image_url = item
assert p.valid?, "#{item} should be a valid image_url"
end
bad.each do |item|
p.image_url = item
assert p.invalid?, "#{item} should not be valid image_url"
end
end
test "product title is unique" do
product = Product.new(title: products(:ruby).title,
description: 'yyy',
price: 1,
image_url: 'fred.gif')
assert !product.save
end
end
|
class AsyncCommandsUpdateStatusEnum < ActiveRecord::Migration
def self.up
change_column :async_commands, :status, :enum, AsyncCommand::STATUS_DB_OPTS
end
def self.down
end
end
|
class CreateUser < ActiveRecord::Migration
def change
create_table(:users) do |t|
t.string :college_id
t.string :laundry_id
t.string :name, null: false
t.decimal :mobile_number, null: false, precision: 10, scale: 0
t.string :gender, null: false
t.string :degree, null: false
t.string :department, null: false
t.integer :year_of_joining, null: false
t.timestamps
end
add_index :users, :college_id
add_index :users, :laundry_id
add_index :users, :name
add_index :users, :mobile_number
end
end
|
require 'securerandom'
require 'base64'
module Travis
module GithubSync
module Encryption
require 'travis/github_sync/support/encryption/decrypt'
require 'travis/github_sync/support/encryption/encrypt'
ENCRYPTION_PREFIX = '--ENCR--'
class << self
def encrypt(string, options)
Encrypt.new(string, options).apply
end
def decrypt(string, options)
Decrypt.new(string, options).apply
end
end
def create_aes(mode = :encrypt, key, iv)
aes = OpenSSL::Cipher::AES.new(256, :CBC)
aes.send(mode)
aes.key = key
aes.iv = iv
aes
end
def create_iv
SecureRandom.hex(8)
end
def add_iv(string, iv)
"#{string}#{iv}"
end
def extract_iv(string)
[string[-16..-1], string[0..-17]]
end
def encode(str)
Base64.strict_encode64(str)
end
def decode(str)
Base64.strict_decode64(str)
end
end
end
end
|
class UserAnswer < ApplicationRecord
belongs_to :answer
belongs_to :user
belongs_to :team
validates :answer, presence: true
validates :user, presence: true
validates :team, presence: true
end
|
class User < ActiveRecord::Base
has_many :usertoengines, foreign_key: "idusers", primary_key: "idusers"
has_many :engines, :through => :usertoengines
default_scope {order(:username => :ASC)}
end |
require "pp"
class RomanNumerals
class << self
def to_roman(numeric)
added = recur_to_roman(numeric, [])
added.join
end
def from_roman(roman)
added, subtracted = recur_from_roman(roman.split(//), [], [])
added.reduce(:+) - subtracted.reduce(:+).to_i
end
private
def recur_to_roman(num, added)
look = nr.sort_by { |n, _v| -1 * n }.to_h
max_key = look.keys.detect { |n| (num / n) > 0 }
cnt, rest = num.divmod(max_key)
cnt.times { added << look[max_key] }
return added if rest.zero?
recur_to_roman(rest, added)
end
def recur_from_roman(arr, added, subtracted)
look = rn
first, second, rest = look[arr[0]], look[arr[1]], arr[2..-1]
(second.nil? || first >= second) ? added << first : subtracted << first
return [added, subtracted] if second.nil?
recur_from_roman([arr[1]] + rest, added, subtracted)
end
def rn
{ "I" => 1,"V" => 5, "X" => 10, "L" => 50, "C" => 100, "D" => 500, "M" => 1000 }
end
def nr
rn.invert.merge({
900 => "CM", 400 => "CD", 90 => "XC", 40 => "XL", 9 => "IX", 4 => "IV"
})
end
end
end
pp RomanNumerals.to_roman(2008)
|
# To enable email activation messages copy the file:
# config/mailer.sample.yml
# to: config/mailer.yml
# and enter valid email settings.
#
# the default_url_option are used when resolving named routes
#
if (File.exists?("#{RAILS_ROOT}/config/mailer.yml"))
mailer_settings = YAML::load(IO.read("#{RAILS_ROOT}/config/mailer.yml"))
ActionMailer::Base.default_url_options[:host] = mailer_settings[:host]
ActionMailer::Base.delivery_method = mailer_settings[:delivery_method]
ActionMailer::Base.smtp_settings = mailer_settings[:smtp]
end |
class Api::V1::PostsController < BaseApiController
def index
posts = Post.all.order(created_at: "DESC")
render json: posts
end
def create
post = Post.create post_params
render json: post
end
private
def post_params
params.permit(:title, :body, :published_at)
end
end
|
class CreateCollectionVirtualRepositoryJoins < ActiveRecord::Migration
def change
create_table :collection_virtual_repository_joins do |t|
t.references :collection, index: false, foreign_key: true
t.references :virtual_repository, index: false, foreign_key: true
t.timestamps null: false
end
add_index :collection_virtual_repository_joins, [:virtual_repository_id, :collection_id], unique: true,
name: 'collection_virtual_repository_join_unique_index'
add_index :collection_virtual_repository_joins, :collection_id, name: 'collection_virtual_repository_join_collection_index'
end
end
|
require 'singleton'
class Settings
include Singleton
attr_accessor :location
attr_accessor :local_addresses
class <<self
attr_accessor :configuration_file
end
self.configuration_file=Rails.root.join('config', 'sk_web.yml').to_s
def initialize
filename=Settings.configuration_file
# Require that the file exists, throw an exception if not
yaml=YAML.load(ERB.new(File.new(filename).read).result)
config=yaml['config']
@location = config['location'] || "???"
@local_addresses = config['local_addresses'] || []
end
# address is an array of 4 strings
def address_matches(spec, address)
(0..3).all? { |i| spec[i]=='*' || spec[i]==address[i] }
end
# address is a string
def address_is_local?(address)
@local_addresses.any? { |spec| address_matches spec.strip.split('.'), address.strip.split('.') }
end
end
|
# prints the current prices for Bitcoin, Dogecoin, and Litecoin against USD from all available exchanges
require 'httpclient'
require 'json'
api_key = '0223-428b-9ecd-120a' # bitcoin from block.io
response = HTTPClient.new.get("https://block.io/api/v1/get_current_price/?api_key=#{api_key}&price_base=USD")
response = JSON.parse(response.content)
# get prices for Bitcoin
puts "The request has succeeded" if response['status'].eql?('success')
if (response['status'].eql?('success'))
# print the prices
prices = response['data']['prices']
prices.each do |current_price|
# print out the price and exchange name
puts "Price from #{current_price['exchange']} is #{current_price['price']} USD/BTC"
end
end
# exit
|
module SS::Model::File
extend ActiveSupport::Concern
extend SS::Translation
include SS::Document
include SS::Reference::User
attr_accessor :in_file, :in_files, :resizing
included do
store_in collection: "ss_files"
seqid :id
field :model, type: String
field :state, type: String, default: "closed"
field :name, type: String
field :filename, type: String
field :size, type: Integer
field :content_type, type: String
belongs_to :site, class_name: "SS::Site"
permit_params :state, :name, :filename
permit_params :in_file, :in_files, in_files: []
permit_params :resizing
before_validation :set_filename, if: ->{ in_file.present? }
before_validation :validate_filename, if: ->{ filename.present? }
validates :model, presence: true
validates :state, presence: true
validates :filename, presence: true, if: ->{ in_file.blank? && in_files.blank? }
validate :validate_size
before_save :rename_file, if: ->{ @db_changes.present? }
before_save :save_file
before_destroy :remove_file
end
module ClassMethods
def root
"#{Rails.root}/private/files"
end
def resizing_options
[
[I18n.t('views.options.resizing.320×240'), "320,240"],
[I18n.t('views.options.resizing.240x320'), "240,320"],
[I18n.t('views.options.resizing.640x480'), "640,480"],
[I18n.t('views.options.resizing.480x640'), "480,640"],
[I18n.t('views.options.resizing.800x600'), "800,600"],
[I18n.t('views.options.resizing.600x800'), "600,800"],
[I18n.t('views.options.resizing.1024×768'), "1024,768"],
[I18n.t('views.options.resizing.768x1024'), "768,1024"],
[I18n.t('views.options.resizing.1280x720'), "1280,720"],
[I18n.t('views.options.resizing.720x1280'), "720,1280"],
]
end
public
def search(params)
criteria = self.where({})
return criteria if params.blank?
if params[:name].present?
criteria = criteria.search_text params[:name]
end
if params[:keyword].present?
criteria = criteria.keyword_in params[:keyword], :name, :filename
end
criteria
end
end
public
def path
"#{self.class.root}/ss_files/" + id.to_s.split(//).join("/") + "/_/#{id}"
end
def public_path
"#{site.path}/fs/" + id.to_s.split(//).join("/") + "/_/#{filename}"
end
def url
"/fs/" + id.to_s.split(//).join("/") + "/_/#{filename}"
end
def thumb_url
"/fs/" + id.to_s.split(//).join("/") + "/_/thumb/#{filename}"
end
def public?
state == "public"
end
def state_options
[[I18n.t('views.options.state.public'), 'public']]
end
def name
self[:name].presence || basename
end
def basename
filename.to_s.sub(/.*\//, "")
end
def extname
filename.to_s.sub(/.*\W/, "")
end
def image?
filename =~ /\.(bmp|gif|jpe?g|png)$/i
end
def resizing
(@resizing && @resizing.size == 2) ? @resizing.map(&:to_i) : nil
end
def resizing=(s)
@resizing = (s.class == String) ? s.split(",") : s
end
def read
Fs.exists?(path) ? Fs.binread(path) : nil
end
def save_files
return false unless valid?
in_files.each do |file|
item = self.class.new(attributes)
item.in_file = file
item.resizing = resizing
next if item.save
item.errors.full_messages.each { |m| errors.add :base, m }
return false
end
true
end
def uploaded_file
file = Fs::UploadedFile.new("ss_file")
file.binmode
file.write(read)
file.rewind
file.original_filename = basename
file.content_type = content_type
file
end
def generate_public_file
if site && basename.ascii_only?
file = public_path
data = self.read
return if Fs.exists?(file) && data == Fs.read(file)
Fs.binwrite file, data
end
end
def remove_public_file
Fs.rm_rf(public_path) if site
end
private
def set_filename
self.filename = in_file.original_filename if filename.blank?
self.size = in_file.size
self.content_type = ::SS::MimeType.find(in_file.original_filename, in_file.content_type)
end
def validate_filename
self.filename = filename.gsub(/[^\w\-\.]/, "_")
end
def save_file
errors.add :in_file, :blank if new_record? && in_file.blank?
return false if errors.present?
return if in_file.blank?
if image? && resizing
width, height = resizing
image = Magick::Image.from_blob(in_file.read).shift
image = image.resize_to_fit width, height if image.columns > width || image.rows > height
binary = image.to_blob
else
binary = in_file.read
end
dir = ::File.dirname(path)
Fs.mkdir_p(dir) unless Fs.exists?(dir)
Fs.binwrite(path, binary)
end
def remove_file
Fs.rm_rf(path)
remove_public_file
end
def rename_file
return unless @db_changes["filename"]
return unless @db_changes["filename"][0]
remove_public_file if site
end
def validate_size
if in_file.present?
validate_limit(in_file)
elsif in_files.present?
in_files.each { |file| validate_limit(file) }
end
end
def validate_limit(file)
filename = file.original_filename
ext = filename.sub(/.*\./, "").downcase
limit_size = SS::MaxFileSize.find_size(ext)
return true if file.size <= limit_size
errors.add :base, :too_large_file, filename: filename,
size: number_to_human_size(file.size),
limit: number_to_human_size(limit_size)
false
end
def number_to_human_size(size)
ApplicationController.helpers.number_to_human_size(size)
end
end
|
namespace :dev do
desc "Configura o ambiente de desenvolvimento"
task setup: :environment do
if Rails.env.development?
# spinner = TTY::Spinner.new("[:spinner] Executando tarefas ...", format: :pulse_2)
# outro modelo
# spinner = TTY::Spinner.new("[:spinner] Apagando BD...")
# spinner.auto_spin # Automatic animation with default interval
# puts %x(rails db:drop db:create db:migrate db:seed)
# ou
# puts %x(rails db:drop)
# puts %x(rails db:create)
# puts %x(rails db:migrate)
# puts %x(rails db:seed)
# spinner.stop("Concluído com sucesso!") # Stop animation
# spinner.success("(Concluído com sucesso!)")
# Spinner um a um
# spinner = TTY::Spinner.new("[:spinner] Apagando BD...")
# spinner.auto_spin # Automatic animation with default interval
# puts %x(rails db:drop)
# spinner.success("(Concluído com sucesso!)")
# spinner = TTY::Spinner.new("[:spinner] Criando BD...")
# spinner.auto_spin # Automatic animation with default interval
# puts %x(rails db:create)
# spinner.success("(Concluído com sucesso!)")
# spinner = TTY::Spinner.new("[:spinner] Migrando as tabelas...")
# spinner.auto_spin # Automatic animation with default interval
# puts %x(rails db:migrate)
# spinner.success("(Concluído com sucesso!)")
# spinner = TTY::Spinner.new("[:spinner] Populando as tabelas...")
# spinner.auto_spin # Automatic animation with default interval
# puts %x(rails db:seed)
# spinner.success("(Concluído com sucesso!)")
# spinner utilizando metodo
show_spinner("Apagando banco de dados...") do
# bloco que será adicionado ao yield
%x(rails db:drop)
end
show_spinner("Criando BD....") do
%x(rails db:create)
end
show_spinner("Migrando as tabelas....") do
%x(rails db:migrate)
end
# show_spinner("Populando as tabelas....") do
# %x(rails db:seed)
# end
# chamando agora a task
# alterando ordem pois as coins precisam de um mining_type
%x(rails dev:add_mining_types)
%x(rails dev:add_coins)
# quando o codigo é somente uma linha, pode ser assim
# show_spinner("Populando as tabelas....") { %x(rails db:seed) }
else
puts "Você não está em ambiente de desenvolvimento!"
end
end
desc "Cadastra as moedas"
task add_coins: :environment do
# mining_type: MiningType.all.sample sorteia um mining type existente
if Rails.env.development?
show_spinner("Cadastrando moedas....") do
coins = [
{
description: 'Bitcoin',
acronym: 'BTC',
url_image: 'https://img2.gratispng.com/20180324/tre/kisspng-bitcoin-cryptocurrency-logo-zazzle-ethereum-bitcoin-5ab6e422d6fc54.3809289415219353948806.jpg',
# mining_type: MiningType.all.sample
# mining_type: MiningType.where(acronym: 'PoW').first
mining_type: MiningType.find_by(acronym: 'PoW')
},
{
description: 'Ethereum',
acronym: 'ETH',
url_image: 'https://img.favpng.com/8/11/1/logo-ethereum-bitcoin-vector-graphics-portable-network-graphics-png-favpng-ej52fCZ1rTD6Zn7dLNtBzbSR0.jpg',
mining_type: MiningType.all.sample
},
{
description: 'Dash',
acronym: 'DASH',
url_image: 'https://media.dash.org/wp-content/uploads/dash-d.png',
mining_type: MiningType.all.sample
}
]
coins.each do |coin|
Coin.find_or_create_by!(coin)
end
end
end
end
desc "Cadastro dos tipos de mineração"
task add_mining_types: :environment do
if Rails.env.development?
show_spinner("Cadastrando tipos de mineração....") do
mining_types = [
{
description: 'Proof of Work',
acronym: 'PoW',
},
{
description: 'Proof of Stake',
acronym: 'PoS',
},
{
description: 'Proof of Capacity',
acronym: 'PoC',
}
]
mining_types.each do |mining_type|
MiningType.find_or_create_by!(mining_type)
end
end
end
end
private
# um metodo para não repetir demais
def show_spinner(msg_start, msg_end = "Concluído")
spinner = TTY::Spinner.new("[:spinner] #{msg_start}")
spinner.auto_spin # Automatic animation with default interval
# yield = bloco de código que será embutido
yield
spinner.success("(#{msg_end})")
end
end
|
# encoding: utf-8
module Antelope
module Generator
# Generates an output file, mainly for debugging. Included always
# as a generator for a grammar.
class Output < Group
register_as "output"
register_generator Info, "info"
register_generator Error, "error"
end
end
end
|
Given(/^I have no cheese$/) do
puts "I am so sad I have no cheese"
end
When(/^I press the cheese button$/) do
puts "There is hope. I hope this machine works"
end
Then(/^I should have (\d+) piece of cheese$/) do |num_pieces|
puts "Rejoice! We have #{num_pieces} pieces of cheese."
end
|
require 'kiba'
require 'kiba-common/sources/csv'
require 'kiba-common/destinations/csv'
require 'kiba-common/dsl_extensions/show_me'
module Lookup
module_function
def csv_to_hash(file)
CSV.foreach(file, headers: true).each_with_object({}) do |r, memo|
memo[r.fetch("id")] = r.to_h
end
end
end
|
# -*- coding: utf-8 -*-
#
# Copyright 2013 whiteleaf. All rights reserved.
#
require_relative "../database"
require_relative "../downloader"
module Command
class Update < CommandBase
def self.oneline_help
"小説を更新します"
end
def initialize
super("[<target> ...] [options]")
@opt.separator <<-EOS
・管理対象の小説を更新します。
更新したい小説のNコード、URL、タイトル、IDもしくは別名を指定して下さい。
IDは #{@opt.program_name} list を参照して下さい。
・対象を指定しなかった場合、すべての小説の更新をチェックします。
・一度に複数の小説を指定する場合は空白で区切って下さい。
・全て更新する場合、convert.no-openが設定されていなくても保存フォルダは開きません。
Examples:
narou update # 全て更新
narou u # 短縮コマンド
narou update 0 1 2 4
narou update n9669bk 異世界迷宮で奴隷ハーレムを
narou update http://ncode.syosetu.com/n9669bk/
Options:
EOS
@opt.on("-n", "--no-convert", "変換をせずアップデートのみ実行する") {
@options["no-convert"] = true
}
@opt.on("-a", "--convert-only-new-arrival", "新着のみ変換を実行する") {
@options["convert-only-new-arrival"] = true
}
end
def execute(argv)
super
mistook_count = 0
update_target_list = argv.dup
no_open = false
if update_target_list.empty?
Database.instance.each_key do |id|
update_target_list << id
end
no_open = true
end
tagname_to_ids(update_target_list)
update_target_list.each_with_index do |target, i|
display_message = nil
data = Downloader.get_data_by_target(target)
if !data
display_message = "<bold><red>[ERROR]</red></bold> #{target} は管理小説の中に存在しません".termcolor
elsif Narou.novel_frozen?(target)
if argv.length > 0
display_message = "ID:#{data["id"]} #{data["title"]} は凍結中です"
else
next
end
end
Helper.print_horizontal_rule if i > 0
if display_message
puts display_message
mistook_count += 1
next
end
result = Downloader.start(target)
case result.status
when :ok
unless @options["no-convert"] ||
(@options["convert-only-new-arrival"] && !result.new_arrivals)
convert_argv = [target]
convert_argv << "--no-open" if no_open
Convert.execute!(convert_argv)
end
when :failed
puts "ID:#{data["id"]} #{data["title"]} の更新は失敗しました"
mistook_count += 1
when :canceled
puts "ID:#{data["id"]} #{data["title"]} の更新はキャンセルされました"
mistook_count += 1
when :none
puts "#{data["title"]} に更新はありません"
end
end
exit mistook_count if mistook_count > 0
rescue Interrupt
puts "アップデートを中断しました"
exit Narou::EXIT_ERROR_CODE
end
end
end
|
class PurchaseUploader < CarrierWave::Uploader::Base
def store_dir
"uploads/purchase/#{mounted_as}/#{model.id}"
end
end
|
Rails.application.routes.draw do
# Scoped to place locale in URL instead of at the end
# If now setting included in URL the default is used
scope "(:locale)", locale: /en|es/ do
# Static pages
get '/:locale' => 'pages#home'
root to: 'pages#home'
get 'about', to: 'pages#about'
# Articles pages
resources :articles
# User pagess
get 'signup', to: 'users#new'
resources :users, except: [:new]
# Login pages
get 'login', to: 'sessions#new'
post 'login', to: 'sessions#create'
delete 'logout', to: 'sessions#destroy'
# Categories pages
resources :categories, except: [:destroy]
end
end
|
class Room < ActiveRecord::Base
validates :name, presence: true
validates :capacity, presence: true, numericality: { greater_than: 0 }
has_many :reservations
end
|
#only need one of the two conditions to be truthy
#takes two arguments and return true if only one arguments is true
#false otherwise
#input: two boolean
#output: one boolean
def xor?(one, two)
(one && two) || !(one || two) ? false : true
end
def xor2?(value1, value2)
!!(value1 && !value2) || (value2 && !value1)
end
p xor?(5.even?, 4.even?) == true
p xor?(5.odd?, 4.odd?) == true
p xor?(5.odd?, 4.even?) == false
p xor?(5.even?, 4.odd?) == false
result = xor2?(5.even?, 4.even?)
p result.class |
class FilmMailer < ApplicationMailer
default from: "aspdata@gmail.com"
def film_list
@films = Film.all.limit 2
@url = 'http://www.themodernview.com'
mail(to: 'aspdata@gmail.com', subject: 'New Film List')
end
end
|
class ProductsController < ApplicationController
before_action :set_product, only: [:show, :edit, :update, :destroy,:back,:report,:like]
before_action :authenticate_user!, except: [:index]
# GET /products
# GET /products.json
def index
if params["category_id"].nil?
@products = Product.all.where(:active=>true)
else
@products = Product.where(:category_id=>params["category_id"],:active=>true)
end
end
# GET /products/1
# GET /products/1.json
def show
end
# GET /products/new
def new
@product = Product.new
end
# GET /products/1/edit
def edit
end
# POST /products
# POST /products.json
def create
@product = Product.new(product_params)
respond_to do |format|
if @product.save
format.html { redirect_to @product, notice: "Product created Successfully" }
format.json { render action: 'show', status: :created, location: @product }
else
format.html { render action: 'new' }
format.json { render json: @product.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /products/1
# PATCH/PUT /products/1.json
def update
respond_to do |format|
if @product.update(product_params)
format.html { redirect_to @product, notice: "Product updated Successfully" }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @product.errors, status: :unprocessable_entity }
end
end
end
# DELETE /products/1
# DELETE /products/1.json
def destroy
@product.destroy
respond_to do |format|
format.html { redirect_to products_url }
format.json { head :no_content }
end
end
def my_products
if params["category_id"].nil?
@products = Product.where(:user_id=>current_user.id)
else
@products = Product.where(:category_id=>params["category_id"],:user_id=>current_user.id)
end
end
def back
BackProduct.create(:product_id=>@product.id,:user_id=>current_user.id)
backers_total = @product.backers_total + 1
@product.update_columns(:backers_total=>backers_total)
respond_to do |format|
format.html { redirect_to @product }
end
end
def report
ReportProduct.create(:product_id=>@product.id,:user_id=>current_user.id)
respond_to do |format|
format.html { redirect_to @product }
end
end
def like
current_user.like!(@product)
respond_to do |format|
format.html { redirect_to @product }
end
end
def recommended
if params["category_id"].nil?
@products = Product.all.where(:active=>true)
else
@products = Product.where(:category_id=>params["category_id"],:active=>true)
end
end
def popular
if params["category_id"].nil?
@products = Product.all.where('backers_total >?',0).sort_by(&:backers_total)
else
@products = Product.where('category_id =? and backers_total >?',params["category_id"],0).sort_by(&:backers_total)
end
end
def favorite
liked_product_ids = Like.where(:liker_id=>1).pluck(:id)
if params["category_id"].nil?
@products = Product.where(:id=>liked_product_ids)
else
@products = Product.where(:id=>liked_product_ids,:category_id=>params["category_id"])
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_product
@product = Product.find(params[:id])
end
def product_params
params.require(:product).permit(:title, :project, :funding_goal, :description, :category_id, :facebook_url, :website,:risks,:user_id,:location,:future_plans,:short_description,:raised_amount,:backers_total,:tag_list,:image,:video)
end
end
|
require_relative "operations"
require_relative "configuration"
require_relative "paths"
module Gaudi
# A Gaudi::Component is a logical grouping of a set of source and header files that maps to a directory structure.
#
# Given a base directory where sources reside, the name of Component is used to map to one or more Component source directories.
#
# By convention we define an inc/ directory where "public" headers reside. These headers form the interface of the Component
# and the directory is exposed by Gaudi for use in include statements.
class Component
include StandardPaths
attr_reader :identifier, :platform, :configuration, :name, :directories, :test_directories, :config_files
# This is set to the name of the program or library containing the component when building a deployment. Default is empty
attr_accessor :parent
def initialize(name, system_config, platform)
@parent = nil
@directories = determine_directories(name, system_config.source_directories, system_config, platform)
@test_directories = determine_test_directories(@directories)
@config_files = Rake::FileList[*directories.pathmap("%p/build.cfg")].existing
if @config_files.empty?
@configuration = Configuration::BuildConfiguration.new(name)
else
@configuration = Configuration::BuildConfiguration.load(@config_files)
end
@system_config = system_config
@platform = platform
@name = @identifier = configuration.prefix
end
# The components sources
def sources
determine_sources(directories, @system_config, @platform).uniq
end
# All headers
def headers
determine_headers(directories, @system_config, @platform).uniq
end
# The headers the component exposes
def interface
Rake::FileList[*interface_paths.pathmap("%p/**/*{#{@system_config.header_extensions(platform)}}")]
end
# The include paths for this Component
def interface_paths
determine_interface_paths(directories).uniq
end
# All files
def all
sources + headers
end
# All components upon which this Component depends on
def dependencies
configuration.dependencies.map { |dep| Component.new(dep, @system_config, platform) }
end
# External (additional) include paths
def external_includes
@system_config.external_includes(@platform) + @configuration.external_includes
end
# List of include paths for this component
#
# This should be a complete list of all paths to include so that the component compiles succesfully
def include_paths
incs = directories
incs += interface_paths
incs += external_includes
dependencies.each { |dep| incs += dep.interface_paths }
return incs.uniq
end
# Test sources
def test_files
src = @system_config.source_extensions(platform)
hdr = @system_config.header_extensions(platform)
Rake::FileList[*test_directories.pathmap("%p/**/*{#{src},#{hdr}}")]
end
end
# A Gaudi::Program is a collection of components built for a specific platform.
class Program < Component
attr_reader :deployment_name
def initialize(config_file, deployment_name, system_config, platform)
@parent = self
@configuration = Configuration::BuildConfiguration.load([config_file])
@name = @identifier = configuration.prefix
@system_config = system_config
@platform = platform
begin
@directories = determine_directories(@name, system_config.source_directories, system_config, platform)
rescue GaudiError
@directories = FileList.new
end
@test_directories = determine_test_directories(@directories)
@config_files = Rake::FileList[config_file]
@deployment_name = deployment_name
end
# External (additional) libraries the Program depends on.
def external_libraries
@system_config.external_libraries(@platform) + @configuration.external_libraries(@system_config, platform)
end
# List of resources to copy with the program artifacts
def resources
@configuration.resources
end
# All components upon which this Program depends on
def dependencies
deps = configuration.dependencies.map { |dep| program_dependency(dep) }
end
# All shared library components this Program depends on
def shared_dependencies
deps = configuration.shared_dependencies.map { |dep| program_dependency(dep) }
end
private
def program_dependency(dep_name)
c = Component.new(dep_name, @system_config, platform)
c.parent = self
return c
end
end
# A Deployment is a collection of Programs compiled for multiple platforms
#
# It maps to a directory structure of
# deployment
# |name
# |platform1
# |platform2
# |program1.cfg
# |program2.cfg
class Deployment
attr_reader :name
def initialize(name, system_config)
@name = name
@directories = determine_directories(name, system_config.source_directories)
@system_config = system_config
raise GaudiError, "Cannot find directories for #{name} " if @directories.empty?
validate
end
# Returns the list of platforms this Deployment has programs for
def platforms
Rake::FileList[*@directories.pathmap("%p/*")].existing.pathmap("%n")
end
# A Program instance for every program configuration on the given platform
def programs(platform)
Rake::FileList[*@directories.pathmap("%p/#{platform}/*.cfg")].existing.map { |cfg| Program.new(cfg, name, @system_config, platform) }
end
def to_s
name
end
private
def validate
platforms.each do |platform|
program_names = programs(platform).map { |program| program.name }
if program_names.uniq.size < program_names.size
raise GaudiError, "No duplicate program names allowed on the same platform. Found duplicates on platform #{platform}"
end
end
end
def determine_directories(name, source_directories)
Rake::FileList[*source_directories.pathmap("%p/deployments/#{name}")].existing
end
end
end
|
require 'pry'
class WordProblem
attr_reader :question
def initialize(str)
@question = str
end
def format_equation(string)
string = string.dup
string = string.gsub('plus', '+')
string = string.gsub('minus', '-')
string = string.gsub('divided by', '/')
string = string.gsub('multiplied by', '*')
string
end
def evaluate_first_sequence(split_equation, current_total)
current_equation = split_equation.shift(3)
first_num = current_equation.first.to_i
second_num = current_equation.last.to_i
operation = current_equation[1].to_sym
current_total += first_num.send(operation, second_num)
current_total
end
def evaluate_next_sequence(split_equation, current_total)
current = split_equation.shift(2)
operation = current[0].to_sym
second_num = current[1].to_i
current_total = current_total.send(operation, second_num)
end
def answer
raise ArgumentError unless question.match(/What is -*[0-9]+ (?:plus|minus|divided by|multiplied by) -*[0-9]+(?: (?:plus|minus|divided by|multiplied by) -*[0-9]+)*\?/)
string = question.match(/-*[0-9]+ (plus|minus|multiplied by|divided by) -*[0-9]+( (plus|minus|multiplied by|divided by) -*[0-9]+)*/).to_s
equation = format_equation(string)
split_equation = equation.split
current_total = 0
count = 0
loop do
current_total = evaluate_first_sequence(split_equation, current_total) if count.zero?
current_total = evaluate_next_sequence(split_equation, current_total) unless split_equation.empty?
return current_total if split_equation.empty?
count += 1
end
end
end
|
# encoding: utf-8
require 'spec_helper'
describe SourcingsController do
before(:each) do
#the following recognizes that there is a before filter without execution of it.
controller.should_receive(:require_signin)
controller.should_receive(:require_employee)
end
render_views
describe "'index'" do
it "returns http success for eng" do
session[:hydr_eng] = true
u = FactoryGirl.create(:user)
cust = FactoryGirl.create(:customer)
proj = FactoryGirl.create(:project, :customer_id => cust.id)
src = FactoryGirl.create(:sourcing, :project_id => proj.id, :src_eng_id => u.id)
get 'index', :project_id => proj.id
response.should be_success
end
it "should OK for mech eng" do
cust = FactoryGirl.create(:customer)
proj = FactoryGirl.create(:project, :customer_id => cust.id)
u = FactoryGirl.create(:user)
src = FactoryGirl.create(:sourcing, :project_id => proj.id, :src_eng_id => u.id)
session[:mech_eng] = true
get 'index', :project_id => proj.id
response.should be_success
end
end
describe "'new'" do
it "reject those without rights" do
proj = FactoryGirl.create(:project)
src = FactoryGirl.attributes_for(:sourcing, :project_id => proj.id)
get 'new', :project_id => proj.id
response.should redirect_to URI.escape("/view_handler?index=0&msg=权限不足!")
end
it "should allow vp eng" do
proj = FactoryGirl.create(:project)
src = FactoryGirl.attributes_for(:sourcing, :project_id => proj.id)
session[:vp_eng] = true
get 'new', :project_id => proj.id
response.should be_success
end
end
describe "'create'" do
it "reject those without right" do
proj = FactoryGirl.create(:project)
src = FactoryGirl.attributes_for(:sourcing, :project_id => proj.id)
get 'create', :project_id => proj.id, :sourcing => src
response.should be_success
end
it "should OK for vp_eng and increase record count by 1 " do
session[:vp_eng] = true
u = FactoryGirl.create(:user)
proj = FactoryGirl.create(:project)
src = FactoryGirl.attributes_for(:sourcing, :input_by_id => u.id, :project_id => proj.id)
lambda do
get 'create', :project_id => proj.id, :sourcing => src
response.should redirect_to URI.escape("/view_handler?index=0&msg=计划已保存!")
end.should change(Sourcing, :count).by(1)
end
it "should redirec to 'new' for data error and no record count increase" do
session[:ceo] = true
u = FactoryGirl.create(:user)
proj = FactoryGirl.create(:project)
src = FactoryGirl.attributes_for(:sourcing, :prod_name => nil, :input_by_id => u.id, :project_id => proj.id)
lambda do
get 'create', :project_id => proj.id, :sourcing => src
response.should render_template('new')
end.should change(Sourcing, :count).by(0)
end
end
describe "GET 'edit'" do
it "reject those without rights" do
proj = FactoryGirl.create(:project)
src = FactoryGirl.create(:sourcing, :project_id => proj.id)
get 'edit', :project_id => proj.id, :id => src.id
response.should redirect_to URI.escape("/view_handler?index=0&msg=权限不足!")
end
it "should OK for vp eng" do
proj = FactoryGirl.create(:project)
session[:vp_eng] = true
u = FactoryGirl.create(:user)
src = FactoryGirl.create(:sourcing, :input_by_id => u.id, :project_id => proj.id)
get 'edit', :project_id => proj.id, :id => src.id
response.should be_success
end
end
describe "GET 'update'" do
it "success for ceo" do
proj = FactoryGirl.create(:project)
session[:ceo] = true
u = FactoryGirl.create(:user)
src = FactoryGirl.create(:sourcing, :input_by_id => u.id, :project_id => proj.id)
get 'update', :project_id => proj.id, :id => src.id, :sourcing => {:name => 'new new name'}
response.should redirect_to URI.escape("/view_handler?index=0&msg=计划已更改!")
end
it "redirect to 'edit' with data error" do
proj = FactoryGirl.create(:project)
session[:vp_eng] = true
u = FactoryGirl.create(:user)
src = FactoryGirl.create(:sourcing, :input_by_id => u.id, :project_id => proj.id)
get 'update', :project_id => proj.id, :id => src.id, :sourcing => {:start_date => nil}
response.should render_template('edit')
end
it "should update approved_by_vp_eng" do
proj = FactoryGirl.create(:project)
session[:vp_eng] = true
u = FactoryGirl.create(:user)
src = FactoryGirl.create(:sourcing, :input_by_id => u.id, :project_id => proj.id)
get 'update', :project_id => proj.id, :id => src.id, :sourcing => {:approved_by_vp_eng => true}
response.should redirect_to URI.escape("/view_handler?index=0&msg=计划已更改!")
end
end
describe "approve" do
it "should nothing happens for those without rights" do
proj = FactoryGirl.create(:project)
u = FactoryGirl.create(:user)
session[:user_id] = u.id
src= FactoryGirl.create(:sourcing, :input_by_id => u.id, :approved_by_vp_eng => false, :project_id => proj.id)
put 'approve', :project_id => proj.id, :id => src.id, :sourcing => {:approved_by_vp_eng => true}
response.should redirect_to URI.escape("/view_handler?index=0&msg=权限不足!")
end
it "should approve for vp_eng" do
session[:vp_eng] = true
session[:ceo] = false
proj = FactoryGirl.create(:project)
u = FactoryGirl.create(:user)
session[:user_id] = u.id
src = FactoryGirl.create(:sourcing, :input_by_id => u.id, :approved_by_vp_eng => false, :project_id => proj.id)
get 'approve', :project_id => proj.id, :id => src.id, :sourcing => {:approved_by_vp_eng => true, :approve_vp_eng_id => session[:user_id],
:approve_date_vp_eng => Time.now }
src.reload.approved_by_vp_eng.should eq true
src.reload.approve_vp_eng_id.should eq session[:user_id]
src.reload.approve_date_vp_eng.strftime("%Y/%m/%d").should eq Time.now.utc.strftime("%Y/%m/%d")
response.should redirect_to project_sourcing_path(proj, src)
end
it "should approve for ceo" do
session[:ceo] = true
proj = FactoryGirl.create(:project)
u = FactoryGirl.create(:user)
session[:user_id] = u.id
src = FactoryGirl.create(:sourcing, :input_by_id => u.id, :approved_by_vp_eng => true, :project_id => proj.id)
get 'approve', :project_id => proj.id, :id => src.id, :sourcing => {:approved_by_ceo => true, :approve_ceo_id => session[:user_id],
:approve_date_ceo => Time.now }
src.reload.approved_by_ceo.should eq true
src.reload.approve_ceo_id.should eq session[:user_id]
src.reload.approve_date_ceo.strftime("%Y/%m/%d").should eq Time.now.utc.strftime("%Y/%m/%d")
response.should redirect_to project_sourcing_path(proj, src)
end
end
describe "dis_apporve" do
it "should dis_approve for vp_eng" do
session[:vp_eng] = true
session[:ceo] = false
proj = FactoryGirl.create(:project)
u = FactoryGirl.create(:user)
session[:user_id] = u.id
src = FactoryGirl.create(:sourcing, :input_by_id => u.id, :approved_by_vp_eng => false, :project_id => proj.id)
get 'dis_approve', :project_id => proj.id, :id => src.id, :sourcing => {:approved_by_vp_eng => false, :approve_vp_eng_id => session[:user_id],
:approve_date_vp_eng => Time.now }
src.reload.approved_by_vp_eng.should eq false
src.reload.approve_vp_eng_id.should eq session[:user_id]
src.reload.approve_date_vp_eng.strftime("%Y/%m/%d").should eq Time.now.utc.strftime("%Y/%m/%d")
response.should redirect_to project_sourcing_path(proj, src)
end
it "should dis_approve for ceo" do
session[:ceo] = true
proj = FactoryGirl.create(:project)
u = FactoryGirl.create(:user)
session[:user_id] = u.id
src = FactoryGirl.create(:sourcing, :input_by_id => u.id, :approved_by_vp_eng => true, :project_id => proj.id)
get 'dis_approve', :project_id => proj.id, :id => src.id, :sourcing => {:approved_by_ceo => false, :approve_ceo_id => session[:user_id],
:approve_date_ceo => Time.now }
src.reload.approved_by_ceo.should eq false
src.reload.approve_ceo_id.should eq session[:user_id]
src.reload.approve_date_ceo.strftime("%Y/%m/%d").should eq Time.now.utc.strftime("%Y/%m/%d")
response.should redirect_to project_sourcing_path(proj, src)
end
end
describe "re_approve by ceo" do
it "should re_approve for ceo" do
session[:ceo] = true
proj = FactoryGirl.create(:project)
u = FactoryGirl.create(:user)
session[:user_id] = u.id
src = FactoryGirl.create(:sourcing, :input_by_id => u.id, :approved_by_vp_eng => true, :project_id => proj.id)
get 're_approve', :project_id => proj.id, :id => src.id, :sourcing => {:approved_by_ceo => nil, :approve_ceo_id => nil, :approve_date_ceo => nil,
:approved_by_vp_eng => nil, :approve_vp_eng_id => nil, :approve_date_vp_eng => nil }
src.reload.approved_by_ceo.should eq nil
src.reload.approve_ceo_id.should eq nil
src.reload.approve_date_ceo.should eq nil
src.reload.approved_by_vp_eng.should eq nil
src.reload.approve_vp_eng_id.should eq nil
src.reload.approve_date_vp_eng.should eq nil
response.should redirect_to project_sourcing_path(proj, src)
end
end
describe "stamp for comp_sec ONLY" do
it "should stamp for comp_sec" do
session[:comp_sec] = true
proj = FactoryGirl.create(:project)
u = FactoryGirl.create(:user)
session[:user_id] = u.id
src = FactoryGirl.create(:sourcing, :input_by_id => u.id, :approved_by_vp_eng => true, :project_id => proj.id)
get "stamp", :project_id => proj.id, :id => src.id, :sourcing => { :stamp => true }
response.should redirect_to project_sourcing_path(proj, src)
src.reload.stamped.should eq true
end
it "should not stamp for all others" do
proj = FactoryGirl.create(:project)
u = FactoryGirl.create(:user)
session[:user_id] = u.id
src = FactoryGirl.create(:sourcing, :input_by_id => u.id, :approved_by_vp_eng => true, :project_id => proj.id)
get "stamp", :project_id => proj.id, :id => src.id, :sourcing => { :stamp => true }
response.should redirect_to URI.escape(SUBURI + "/view_handler?index=0&msg=权限不足!")
end
end
describe "GET 'show'" do
it "should reject those without right" do
u = FactoryGirl.create(:user)
proj = FactoryGirl.create(:project)
src = FactoryGirl.create(:sourcing, :input_by_id => u.id, :project_id => proj.id)
get 'show', :project_id => proj.id, :id => src.id
response.should redirect_to URI.escape("/view_handler?index=0&msg=权限不足!")
end
it "returns http success for those with right" do
proj = FactoryGirl.create(:project)
session[:elec_eng] = true
u = FactoryGirl.create(:user)
src = FactoryGirl.create(:sourcing, :input_by_id => u.id, :project_id => proj.id, :eng_id => u.id)
get 'show', :project_id => proj.id, :id => src.id
response.should be_success
end
end
describe "seach result" do
it "should do search for coo" do
session[:coo] = true
cust = FactoryGirl.create(:customer)
eng = FactoryGirl.create(:user)
proj = FactoryGirl.create(:project, :customer_id => cust.id)
src = FactoryGirl.create(:sourcing, :project_id => proj.id, :eng_id => eng.id, :src_eng_id => nil)
p_search = FactoryGirl.attributes_for(:sourcing)
get 'search_results', :sourcing => p_search
response.should be_success
assigns(:sourcings).should eq([src])
end
end
end
|
class User < ApplicationRecord
has_secure_password
has_many :exes
validates :name, presence: true
validates :email, presence: true, format: /\A[a-z0-9_\-\.]+@[a-z0-9_\-\.]+\.[a-z]+\z/i
validates :password, presence: true, confirmation: true
end
|
class Post < ActiveRecord::Base
attr_accessible :content, :published_at, :title, :publish
attr_accessor :publish
belongs_to :user
validates :title, :presence => true, :length => { :minimum => 3, :maximum => 255 }
validates :content, :length => { :minimum => 0, :maximum => 10000 }
before_save :set_published_at
scope :published, where("published_at IS NOT NULL")
scope :alive, where("deleted_at IS NULL")
scope :my, lambda { |user|
where(:user_id => user.id).order("updated_at DESC")
}
scope :accessible, lambda { |user|
where("user_id = ? OR published_at IS NOT NULL", user.id)
}
def published
published_at != nil
end
def deleted
deleted_at != nil
end
private
def set_published_at
if (publish == true || publish == "true" || publish == "1") && published_at.nil?
self.published_at = Time.now
elsif (publish != true && publish != "true" && publish != "1") && published_at
self.published_at = nil
end
end
end
|
class Picture::CompleteSerializer < ActiveModel::Serializer
attributes :id, :original, :mini, :thumb, :medium, :normal, :large, :kind, :imageable_type
def original
object.attachment.url
end
def mini
object.attachment.url :mini
end
def thumb
object.attachment.url :thumb
end
def medium
object.attachment.url :medium
end
def normal
object.attachment.url :normal
end
def large
object.attachment.url :large
end
end |
Pod::Spec.new do |s|
s.name = "AdobeVideoHeartbeat"
s.version = "1.4.1.2"
s.homepage = "https://github.com/Adobe-Marketing-Cloud/video-heartbeat"
s.source = { :http => "http://repository.neonstingray.com/content/repositories/thirdparty/com/adobe/ios/video-heartbeat/1.4.1.2/video-heartbeat-1.4.1.2.zip" }
s.platform = :ios
s.xcconfig = { 'LIBRARY_SEARCH_PATHS' => '"$(PODS_ROOT)/AdobeVideoHeartbeat"',
'OTHER_LDFLAGS' => '"$(PODS_ROOT)/AdobeVideoHeartbeat/VideoHeartbeat.a"'}
s.preserve_paths = 'VideoHeartbeat.a'
s.source_files = '*.h'
end
|
#!/usr/bin/env ruby -w
# encoding: UTF-8
require 'rubygems'
require "em-http-request"
require 'htmlentities' #decode html special caracter to caracter
require_relative '../../../../lib/logging'
require_relative '../../../flow'
require_relative 'traffic_source'
#------------------------------------------------------------------------------------------
# Pre requis gem
#------------------------------------------------------------------------------------------
module Tasking
module TrafficSource
SEC = 1
MIN = 60 * SEC
HOUR = 60 * MIN
DAY = 24 * HOUR
class Page
include Addressable
SEPARATOR = "%SEP%"
NO_LIMIT = 0
# attribut en input
attr :url, # url de la page
:title, # titre recuper� de la page html
:id # id logique d'une page
attr_accessor :links # liens conserv�s de la page
def initialize(id, url, title, links)
@id = id
@url = url
@title = title
@links = links.nil? ? [] : links # si pas de line recuperer lors du scrape alors []
end
def to_s(*a)
uri = URI.parse(@url)
url = "/"
url = uri.path unless uri.path.nil?
url += "?#{uri.query}" unless uri.query.nil?
url += "##{uri.fragment}" unless uri.fragment.nil?
"#{@id}#{SEPARATOR}#{uri.scheme}#{SEPARATOR}#{uri.host}#{SEPARATOR}#{url}#{SEPARATOR}#{@title}#{SEPARATOR}#{@links}"
end
# End Class Page ------------------------------------------------------------------------------------------------
end
class Direct < TrafficSource
#------------------------------------------------------------------------------------------
# Globals variables
#------------------------------------------------------------------------------------------
EOFLINE ="\n"
SEPARATOR="%SEP%"
SEPARATOR1 = '|'
SCRAPING_WEBSITE = "scraping-website"
# Input
attr :host # le hostname du site
# Output
attr :f, #fichier contenant les links
:ferror, # fichier contenant les links en erreur
:fleaves #fichier contenant les id des links ne contenant pas de lien
# Private
attr :delay, #temporisation pour retry update state in calendar
:start_time, # heure de départ
:nbpage, # nbr de page du site
:idpage, # clé d'identification d'une page
:known_url, # contient les liens identifiés
# 2 moyens pour stopper la recherche : nombre de page et la duree de recherche, le premier atteint on stoppe
:count_page, # nombre de page que lon veut recuperer 0 <=> toutes les pages
:max_duration, # durée d'exécution max de la recuperation des lien : en seconde.
:schemes, #les schemes que l'on veut
:types, # types de destination du lien : local au site, ou les sous-domaine, ou internet
:host,
:run_spawn,
:start_spawn,
:stop_spawn,
:push_file_spawn,
:saas_host,
:saas_port, #host et port du serveur de scraping en mode saas
:time_out, #time out de la requet de scraping
:calendar_server_port,
:event_id, #utiliser pour identifier event qui a déclencher la task pour maj le state de l'event chez calendar et staupweb
:policy_id #utiliser pour identifier la task chez statupweb
#--------------------------------------------------------------------------------------------------------------
# scraping_device_platform_plugin
#--------------------------------------------------------------------------------------------------------------
# --------------------------------------------------------------------------------------------------------------
def initialize(website_label, date_building, policy_type, event_id, policy_id)
super(website_label, date_building, policy_type)
@event_id = event_id
@policy_id = policy_id
@delay = Random.new
@logger = Logging::Log.new(self, :staging => $staging, :debugging => $debugging)
end
# max_duration (en jours)
def scraping_pages(url_root, count_page, max_duration, schemes, types)
@logger.an_event.info("Scraping pages for #{@website_label} for #{@date_building} is starting")
parameters = Parameter.new(__FILE__)
@saas_host = parameters.saas_host.to_s
@saas_port = parameters.saas_port.to_s
@time_out = parameters.time_out_saas_scrape.to_i
@calendar_server_port = parameters.calendar_server_port
@host = url_root
@count_page = count_page
@max_duration = max_duration * DAY
@schemes = schemes
@types = types
$sem = Mutex.new
w = self
@start_spawn = EM.spawn {
w.start()
}
@stop_spawn = EM.spawn {
w.stop()
}
@run_spawn = EM.spawn { |urls|
w.run(urls)
}
@known_url = Hash.new(0)
# delete les fichiers existants : on ne conserve qu'un resultat de scrapping par website
delete_all_output_files
@start_spawn.notify
end
def delete_all_output_files
@logger.an_event.info("deleting all files #{SCRAPING_WEBSITE}-#{@website_label}* ")
Dir.entries(TMP).each { |file|
File.delete(TMP + file) if File.fnmatch("#{SCRAPING_WEBSITE}-#{@website_label}*", file)
}
end
def start
@nbpage = 0
@idpage = 1
urls = Array.new
urls << [@host, 1] # [url , le nombre d'essai de recuperation de la page associe a l'url]
@known_url[@host] = @idpage
@start_time = Time.now
#creation du fichier de reporting des erreurs d'acces au lien contenus par les pages
@ferror = Flow.new(TMP, SCRAPING_WEBSITE, @policy_type, @website_label, @date_building, 1, ".error")
# creation du premier volume de données
@f = Flow.new(TMP, SCRAPING_WEBSITE, @policy_type, @website_label, @date_building, 1, ".txt")
#scraping website
@logger.an_event.debug("scrapping website options : ")
@logger.an_event.debug("count_page : #{@count_page}")
@logger.an_event.debug("max duration : #{@max_duration}")
@logger.an_event.debug("schemes : #{@schemes}")
@logger.an_event.debug("types : #{@types}")
@run_spawn.notify urls
@logger.an_event.info("scrapping of #{@website_label} is running ")
end
def run(urls)
url = urls.shift
count_try = url[1]
url = url[0]
options = {}
options = proxy(@geolocation.to_json) unless @geolocation.nil?
url_saas = "http://#{@saas_host}:#{@saas_port}/?action=scrape&"
url_saas += "&url=#{HTMLEntities.new.decode(url)}"
url_saas += "&host=#{@host}"
url_saas += "&schemes=#{@schemes.join(SEPARATOR1)}"
url_saas += "&types=#{@types.join(SEPARATOR1)}"
url_saas += "&count=#{(@count_page > 0) ? @count_page - @idpage : @count_page}" #limite le nombre de lien dès le saas
@logger.an_event.debug "url link scraping saas #{url_saas}"
http = EM::HttpRequest.new(URI.encode(url_saas), options).get
http.callback {
# http.reponse = {'url' => @url,
# 'title' => @title,
# 'links' => @links}
begin
id = @known_url[url]
result = JSON.parse(http.response)
scraped_page = Page.new(id, url, result['title'], result['links'])
if @count_page > @idpage or @count_page == 0
$sem.synchronize {
scraped_page.links.each { |link|
if @known_url[link] == 0
urls << [link, 1]
@idpage += 1
@known_url[link] = @idpage
end
}
}
end
scraped_page.links.map! { |link| @known_url[link] }
output(scraped_page)
@nbpage += 1
display(urls)
if urls.size > 0 and
(@count_page > @nbpage or @count_page == 0) and
Time.now - @start_time < @max_duration
@run_spawn.notify urls
else
@stop_spawn.notify
end
rescue Exception => e
@logger.an_event.error "scraping direct function run : #{e.message}"
end
}
http.errback {
@ferror.write("url = #{url} try = #{count_try} Error = #{http.state}\n")
count_try += 1
urls << [url, count_try] if count_try < 4 # 3 essai max pour une url
if urls.size > 0 and
(@count_page > @nbpage or @count_page == 0) and
Time.now - @start_time < @max_duration
@run_spawn.notify urls
else
@stop_spawn.notify
end
}
end
def stop
@f.close
@ferror.close
try_count = 3
begin
response = RestClient.patch "http://localhost:#{@calendar_server_port}/tasks/#{@event_id}/?state=over", :content_type => :json, :accept => :json
raise response.content unless [200, 201].include?(response.code)
rescue Exception => e
@logger.an_event.error "cannot update state over task <Scraping_website> for #{@website_label}/#{@policy_type}/#{@date_building} in calendar : #{e.message}"
rescue RestClient::RequestTimeout => e
@logger.an_event.warn "try #{try_count}, cannot update state over task <Scraping_website> for #{@website_label}/#{@policy_type}/#{@date_building} in calendar"
try_count -= 1
sleep @delay.rand(10..50)
retry if try_count > 0
@logger.an_event.error "cannot update state over task <Scraping_website> for #{@website_label}/#{@policy_type}/#{@date_building} in calendar : #{e.message}"
else
@logger.an_event.info "update state over task <Scraping_website> for #{@website_label}/#{@policy_type}/#{@date_building} in calendar."
end
begin
task = {:state => "over",
:finish_time => Time.now
}
response = RestClient.patch "http://#{$statupweb_server_ip}:#{$statupweb_server_port}/tasks/#{@event_id}",
JSON.generate(task),
:content_type => :json,
:accept => :json
raise response.content unless [200, 201].include?(response.code)
rescue Exception => e
@logger.an_event.warn "task <Scraping_website> for #{@website_label}/#{@policy_type}/#{@date_building} not update with OVER to statupweb => #{e.message}"
@logger.an_event.warn "task #{task}"
else
end
end
def push_file(id_file, last_volume = false)
begin
id_file.push($authentification_server_port,
$input_flows_server_ip,
$input_flows_server_port,
$ftp_server_port,
id_file.vol, # on pousse que ce volume
last_volume)
@logger.an_event.info("push flow <#{id_file.basename}> to input flows server (#{$input_flows_server_ip}:#{$input_flows_server_port})")
rescue Exception => e
@logger.an_event.debug e
@logger.an_event.error("cannot push flow <#{id_file.basename}> to input flows server (#{$input_flows_server_ip}:#{$input_flows_server_port})")
end
end
private
def display(urls)
delay_from_start = Time.now - @start_time
mm, ss = delay_from_start.divmod(60) #=> [4515, 21]
hh, mm = mm.divmod(60) #=> [75, 15]
dd, hh = hh.divmod(24) #=> [3, 3]
@logger.an_event.info("#{@website_label} nb page = #{@nbpage} from start = #{dd} days, #{hh} hours, #{mm} minutes and #{ss.round(0)} seconds avancement = #{((@nbpage * 100)/(@nbpage + urls.size)).to_i}% nb/s = #{(@nbpage/delay_from_start).round(2)} raf #{urls.size} links")
end
def output(page)
@f.write(page.to_s + "#{EOFLINE}")
if @f.size > Flow::MAX_SIZE
# informer input flow server qu'il peut telecharger le fichier
output_file = @f
@f = output_file.new_volume()
output_file.close
end
end
def proxy(geolocation)
if !geolocation[:ip].nil? and !geolocation[:port].nil? and
!geolocation[:user].nil? and !geolocation[:pwd].nil?
proxy = {:proxy => {:host => geolocation[:ip], :port => geolocation[:port]}}
elsif !geolocation[:ip].nil? and !geolocation[:port].nil? and
geolocation[:user].nil? and geolocation[:pwd].nil?
proxy = {:proxy => {:host => geolocation[:ip], :port => geolocation[:port]}}
else
raise "direct not set geolocation : #{geolocation.to_s}"
end
proxy
end
end
end
end
|
# == Schema Information
#
# Table name: datasets
#
# id :bigint not null, primary key
# file_count :integer
# name :string(255)
# programming_language :string(255)
# token :string(255) not null
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_datasets_on_token (token)
#
class DatasetSerializer < ApplicationSerializer
attributes :token, :programming_language, :zipfile
def zipfile
url_for(object.zipfile)
end
end
|
# See Programming Ruby, p. 96
0.upto(9) do |x|
print x, " "
end
|
# frozen_string_literal: true
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'entity_test_extensions'
require 'rails/test_help'
require 'minitest/reporters'
Minitest::Reporters.use! Minitest::Reporters::SpecReporter.new
MOCK_ACCOUNT_ID = 1010101010101010
class MockModel
include ActiveModelCloudDatastore
attr_accessor :name
validates :name, presence: true
def attributes
%w(name)
end
end
# Make the methods within EntityTestExtensions available as class methods.
MockModel.send :extend, EntityTestExtensions
module ActiveSupport
class TestCase
def setup
if `lsof -t -i TCP:8181`.to_i == 0
datastore_path = Rails.root.join('tmp', 'test_datastore')
# Start the test Cloud Datastore Emulator in 'testing' mode (data is stored in memory only).
system('gcd.sh start --port=8181 --testing ' + datastore_path.to_s + '&')
sleep 3
end
CloudDatastore.dataset
end
def teardown
MockModel.delete_all_test_entities!
end
end
end
|
$:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "autogrid/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "autogrid"
s.version = Autogrid::VERSION
s.authors = ["Christopher Thornton"]
s.email = ["rmdirbin@gmail.com"]
s.homepage = "https://github.com/cgthornt/autogrid"
s.summary = "Autogrid automatically creates grids for your models"
s.description = "Want an easy way to create data grids? Now you can easily with autogrid!"
s.files = Dir["{app,lib,vendor}/**/*"] + ["Rakefile", "README.md"]
s.add_dependency "rails", "~> 3.2.8"
s.add_dependency "jquery-datatables-rails", "~> 1.10.0"
s.add_development_dependency "sqlite3"
end
|
module Rfm
module Metadata
class LayoutMeta < CaseInsensitiveHash
def initialize(layout)
@layout = layout
end
def field_controls
self['field_controls'] ||= CaseInsensitiveHash.new
end
def field_names
field_controls.values.collect{|v| v.name}
end
def field_keys
field_controls.keys
end
def value_lists
self['value_lists'] ||= CaseInsensitiveHash.new
end
# def handle_new_field_control(attributes)
# name = attributes['name']
# field_control = FieldControl.new(attributes, self)
# field_controls[get_mapped_name(name)] = field_control
# end
def receive_field_control(fc)
#name = fc.name
field_controls[get_mapped_name(fc.name)] = fc
end
# Should this be in FieldControl object?
def get_mapped_name(name)
(@layout.field_mapping[name]) || name
end
end
end
end
|
class CreateItems < ActiveRecord::Migration[5.1]
def change
create_table :items do |t|
t.string :name
t.string :description
t.string :image_url, default: 'http://www.spore.com/static/image/500/404/515/500404515704_lrg.png'
t.integer :quantity
t.money :current_price
t.boolean :enabled, default: true
t.references :merchant, foreign_key: {to_table: :users}
t.timestamps
end
end
end
|
require 'active_admin'
require 'active_admin/async_export/build_download_format_links'
require 'active_admin/async_export/version'
require 'active_admin/async_export/resource_controller_extension'
require 'active_admin/async_export/async_export_mailer'
require 'active_admin/async_export/railtie'
module ActiveAdmin
module AsyncExport
def self.from_email_address=(address)
@from_email_address = address
end
def self.from_email_address
@from_email_address || 'admin@example.com'
end
end
end
|
require 'byebug'
class MaxIntSet
def initialize(max)
@max = max
@store = Array.new(max, false)
end
def insert(num)
raise "Out of bounds" unless is_valid?(num)
@store[num] = true
end
def remove(num)
@store[num] = false
end
def include?(num)
@store[num] == true
end
private
def is_valid?(num)
num < @max && num > 0
end
def validate!(num)
end
end
class IntSet
def initialize(num_buckets = 20)
@store = Array.new(num_buckets) { Array.new }
end
def insert(num)
self[num] << num unless self[num].include?(num)
end
def remove(num)
self[num].delete(num) if self[num].include?(num)
end
def include?(num)
self[num].include?(num)
end
private
def [](num)
i = num % num_buckets
@store[i]
end
def num_buckets
@store.length
end
end
class ResizingIntSet
attr_reader :count
def initialize(num_buckets = 20)
@store = Array.new(num_buckets) { Array.new }
@count = 0
end
def insert(num)
unless full?
unless self[num].include?(num)
self[num] << num
@count += 1
end
else
# debugger
resize!
insert(num)
# self[num] << num
# @count += 1
end
end
def remove(num)
if self[num].include?(num)
self[num].delete(num)
@count -= 1
end
end
def include?(num)
self[num].include?(num)
end
def full?
count >= num_buckets
end
private
def [](num)
# optional but useful; return the bucket corresponding to `num`
i = num % num_buckets
@store[i]
end
def num_buckets
@store.length
end
def resize!
old_store = @store.dup
old_store.flatten!
@count = 0
@store = Array.new(num_buckets * 2) { Array.new }
until old_store.empty?
insert(old_store.shift)
end
end
end
|
class Scorecard
attr_reader :score
def initialize(team)
@team = team
@score = scorecard
end
def scorecard
{@team => {1.1=>0, 1.2=>0, 2.1=>0, 2.2=>0, 3.1=>0, 3.2=>0, 4.1=>0, 4.2=>0, 5.1=>0,
5.2=>0, 6.1=>0, 6.2=>0, 7.1=>0, 7.2=>0, 8.1=>0, 8.2=>0, 9.1=>0, 9.2=>0, 10.1=>0, 10.2=>0, 10.3=>0} }
end
def reset_scorecard
@score[@team].clear
end
def add_roll(turn, pins)
@turn = turn
@score[@team][turn] = pins
end
def strike?(input1, input2)
input1 == 10 || input2 == 10
end
def spare?(input1, input2)
input1 + input2 == 10 && (input1 != 10 || input2 != 10)
end
def next_frame_nil?(input1, input2)
input1 == nil || input2 == nil
end
def sum_a_frame(next_roll_1, next_roll_2)
next_roll_1 + next_roll_2
end
def tenth_frame
@score[@team][10.1]+@score[@team][10.2] == 10 || @score[@team][10.1]+@score[@team][10.2] == 20
end
def total(frame)
score = 0
while frame > 0 do
this_frame_roll1, this_frame_roll2 = @score[@team][frame+0.1], @score[@team][frame+0.2]
next_frame_roll1, next_frame_roll2 = @score[@team][frame+1.1], @score[@team][frame+1.2]
score += sum_a_frame(this_frame_roll1, this_frame_roll2)
if strike?(this_frame_roll1, this_frame_roll2)
unless next_frame_nil?(next_frame_roll1, next_frame_roll2)
score += sum_a_frame(next_frame_roll1, next_frame_roll2)
end
elsif spare?(this_frame_roll1, this_frame_roll2)
unless next_frame_roll1 == nil
score += next_frame_roll1
end
end
frame -= 1
end
score += @score[@team][10.3] if tenth_frame
score
end
end
|
# frozen_string_literal: true
module Neighbour
def neighbour?(cell, mine)
is_between?(cell[:x], mine[:x]) && is_between?(cell[:y], mine[:y])
end
def is_between?(cell_position, mine_position)
cell_position + 1 == mine_position ||
cell_position - 1 == mine_position
end
end
|
module MeditationSessionsHelper
def options_for_duration
options_for_select(available_duration_options)
end
private
def available_duration_options
[
[ '1 minute', 1 ],
[ '2 minutes', 2 ],
[ '5 minutes', 5 ],
[ '10 minutes', 10 ],
[ '15 minutes', 15 ],
[ '20 minutes', 20 ],
[ '30 minutes', 30 ],
[ '45 minutes', 45 ],
[ '1 hour', 60 ],
[ '2 hours', 60*2 ],
[ '4 hours', 60*4 ],
[ '8 hours', 60*8 ],
]
end
end
|
module PostsHelper
def destroy_post_link(post)
if can? :destroy, post
link_to t('post.button.destroy'),
post_path(post),
class: 'btn btn-danger',
method: :delete,
data: { confirm: t('common.delete_confirmation'), confirm_title: t('common.delete') }
end
end
def edit_post_link(post)
if can? :update, post
link_to t('post.button.edit'), edit_post_path(post), class: 'btn btn-warning'
end
end
def post_link(post, text = t('post.button.show'))
if can? :read, post
link_to text, post_path(post), class: 'btn btn-info'
end
end
end |
class KensakusController < ApplicationController
include AdminHelper
layout "admin"
before_filter :validate_admin
before_filter :set_tab_index
before_filter :prepare_config
FILTER_NO_RESULT = "no_result"
FILTER_HAS_RESULT = "has_result"
def set_tab_index
@tab = 5
end
def index
@filter = params[:filter]
if @filter == FILTER_NO_RESULT
criteria = Kensaku.where(last_n_results: 0)
elsif @filter == FILTER_HAS_RESULT
criteria = Kensaku.where(last_n_results: {"$gt" => 0})
else
criteria = Kensaku.all
end
@kensakus = criteria.order_by([[:updated_at, :desc]]).page(params[:page]).per(10)
@title = I18n.t 'admin.kensaku'
render 'admin/kensaku/index'
end
end |
class UpdateColumnsWorkerCenterOfStudies < ActiveRecord::Migration
def change
change_column :worker_center_of_studies, :start_date, :integer
change_column :worker_center_of_studies, :end_date, :integer
end
end
|
class Car
attr_reader :name, :price
attr_writer :name, :price
def to_s
"#{@name}: #{@price}"
end
end
c1 = Car.new
c2 = Car.new
c1.name = "Porsche"
c1.price = 23500
c2.name = "Volkswagen"
c2.price = 9500
puts "The #{c1.name} costs #{c1.price}"
p c1
p c2
# All Ruby variables are private. It is possible to access them only via methods. These methods are often called setters and getters. Creating a setter and a getter method is a very common task. Therefore Ruby has convenient methods to create both types of methods. They are attr_reader, attr_writer and attr_accessor.
# The attr_reader creates getter methods. The attr_writer method creates setter methods and instance variables for this setters. The attr_accessor method creates both getter, setter methods and their instance variables. |
class Pelicula < ApplicationRecord
# belongs_to :language
# belongs_to :country
# belongs_to :genre
has_many :comentarios, dependent: :destroy
has_attached_file :poster, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png"
validates_attachment_content_type :poster, content_type: /\Aimage\/.*\z/
end
|
# frozen_string_literal: true
class ChaptersController < HtmlController
include Pagy::Backend
has_scope :table_order, type: :hash
has_scope :search, only: [:index]
def index
authorize Chapter
@pagy, @chapters = pagy apply_scopes(policy_scope(ChapterSummary, policy_scope_class: ChapterPolicy::Scope))
end
def new
authorize Chapter
@chapter = Chapter.new
end
def create
@chapter = Chapter.new chapter_params
authorize @chapter
@chapter.mlid = @chapter.mlid&.upcase
return notice_and_redirect t(:chapter_created, chapter: @chapter.chapter_name), chapters_url if @chapter.save
@chapters = Chapter.includes(:organization, groups: [:students]).all
render :new
end
def show
@chapter = Chapter.find params.require :id
authorize @chapter
@pagy, @groups = pagy apply_scopes(GroupSummary.where(chapter_id: @chapter.id))
end
def edit
@chapter = Chapter.find params.require :id
authorize @chapter
end
def update
@chapter = Chapter.includes(:organization).find params.require :id
authorize @chapter
return notice_and_redirect t(:chapter_updated, chapter: @chapter.chapter_name), chapter_url if @chapter.update chapter_params
render :edit, status: :unprocessable_entity
end
private
def chapter_params
params.require(:chapter).permit :chapter_name, :organization_id, :mlid
end
end
|
# == Schema Information
#
# Table name: health_posts
#
# id :integer not null, primary key
# phone_number :string
# health_center_id :integer
# created_at :datetime not null
# updated_at :datetime not null
# code :string
#
class HealthPost < ActiveRecord::Base
include SendsMessages
belongs_to :health_center
has_many :agents
has_many :tecnicos
after_create :set_random_code
def set_random_code
random = rand(1000..9999).to_s
update_attributes(code: random)
end
end
|
module Cms::ResourceHelper
def assc(attr)
attr.gsub('_id', '').to_sym
end
def attributes
@attributes ||=
if params[:action] == 'index'
remove_text_column_types column_names
else
remove_system_updated_fields column_names
end
end
def column_names
@column_names ||= columns_hash.keys
end
def column_type(key)
columns_hash[key]
end
def column_types(keys=attributes)
keys.map { |key| column_type(key) }
end
def nested?(params)
params.keys.each { |key| return key.gsub('_id', '').to_sym if key.end_with?('_id') }
end
def panel_header_type(action)
case action
when 'new', 'create'
'new'
when 'edit', 'update'
'edit'
else
action
end
end
def parent_resource(parent_object=nil)
if respond_to?('parent')
parent
#elsif respond_to? ('resource') # Need to figure out how to pass a manual path
# binding.pry # into the uploader. Possibly via a parameter
# resource # passed into the'asset_uploader' helper method.
else
nil
end
end
def position
@position ||= column_names.index 'position'
end
def td(object, attribute, options = {})
options[:length] ||= 20
attribute_value = object.public_send(attribute.gsub('_id', ''))
if attribute_value.respond_to? :strftime
attribute_value.strftime '%d %b %Y @ %I:%M%P'
else
attribute_value.to_s.truncate(options[:length])
end
end
def th(attribute)
sortable attribute, title: humanized_column_name(attribute.gsub('_at', '')), remote: true
end
private
def columns_hash
@columns_hash ||= resource_class.columns_hash.inject({}) { |memo, (key, value)| memo[key] = value.type; memo }
end
def humanized_column_name(attribute)
resource_class.human_attribute_name(attribute)
end
def remove_text_column_types(attributes)
remove_system_updated_fields(attributes).map do |attribute|
attribute unless columns_hash[attribute] == :text
end.compact
end
def remove_system_updated_fields(attributes)
attributes - %w(id position created_at updated_at)
end
end |
class CreateEventSaleCategories < ActiveRecord::Migration
def up
create_table :event_sale_categories do |t|
t.integer :event_id
t.string :name
t.integer :price
end
add_column :event_payments, :event_sale_category_id, :integer
end
def down
drop_table :event_sale_categories
end
end
|
class ChangeColumnCompanyToCostCenterFromPartWorker < ActiveRecord::Migration
def change
rename_column :part_workers, :company_id, :cost_center_id
end
end
|
Given(/^there are some questions$/) do
@questions = FactoryGirl.create_list :question, 3
end
When(/^I go to the homepage$/) do
visit ('/')
end
Then(/^I see all the questions$/) do
expect(page).to have_content('baldness or cancer')
end
Given(/^all questions are answered$/) do
@candidate = FactoryGirl.create :candidate
@questions.each {|question| candidate.give_answer(question, question.choices.first)}
end
Then(/^I do not see any questions$/) do
xpect(page).not_to have_content('baldness or cancer')
end |
class ProfilesController < ApplicationController
def new
if session[:id] != nil
@website = Website.find(session[:id])
else
redirect_to new_website_path
end
end
def create
if session[:id] != nil
@website = Website.find(session[:id])
@profile = @website.create_profile(profile_params)
@profile.save
redirect_to skill_path
else
redirect_to new_website_path
end
end
def destroy
end
private def profile_params
params.require(:profile).permit(:username, :email, :location, :profession, :phone, :image)
end
end
|
require 'dist_server/server/serial_object'
class ServerInfo
extend SerialObject
include SerialObject
attr_reader :name
attr_reader :type
attr_reader :klass
attr_reader :host
attr_reader :port
attr_reader :services
def initialize(name, type, klass, host, port, services)
@name = name
@type = type
@klass = klass
@host = host
@port = port
@services = services
end
end
|
# Simple Shell
#
# @author Justin Leavitt
#
# @since 0.0.1
module BixsbyShell
class Simple < Shell
READLINE_PROMPT = "bixsby > "
def initialize(server)
@server = server
run_simple_shell
end
def run_simple_shell
message = parse_response(@server.gets.chomp)
display_simple_response(message)
while buffer = Readline.readline("#{READLINE_PROMPT}", true)
line = buffer.chomp.strip
execute_command(line, :simple)
end
end
def display_simple_response(message)
puts self.blue "==\n#{message}\n=="
end
end
end
|
require 'test/test_helper'
require 'build_result'
require 'gruff_build_time_grapher'
require 'gruff_test_count_grapher'
class OutputSampleTest < Test::Unit::TestCase
def test_gruff_makes_a_nice_pretty_graph_of_build_times
File.delete(filename+".png") if File.exist?(filename+".png")
GruffBuildTimeGrapher.new(filename).graph [
BuildResult.new(:succeeded? => true, :minutes=>2, :seconds=>15),
BuildResult.new(:succeeded? => false, :minutes=>2, :seconds=>30),
BuildResult.new(:succeeded? => false, :minutes=>2, :seconds=>45),
BuildResult.new(:succeeded? => true, :minutes=>2, :seconds=>55),
BuildResult.new(:succeeded? => true, :minutes=>2, :seconds=>25),
BuildResult.new(:succeeded? => true, :minutes=>2, :seconds=>45),
BuildResult.new(:succeeded? => false, :minutes=>3, :seconds=>05),
BuildResult.new(:succeeded? => true, :minutes=>3, :seconds=>12),
BuildResult.new(:succeeded? => true, :minutes=>3, :seconds=>24),
BuildResult.new(:succeeded? => true, :minutes=>4, :seconds=>01)]
assert File.exist?(filename+".png")
end
def test_gruff_makes_a_nice_pretty_graph_of_test_counts
File.delete(filename+".png") if File.exist?(filename+".png")
GruffTestCountGrapher.new(filename).graph [
BuildResult.new(:test_counts => [54,12]),
BuildResult.new(:test_counts => [54,12]),
BuildResult.new(:test_counts => [55,13]),
BuildResult.new(:test_counts => [56,14]),
BuildResult.new(:test_counts => [63,14]),
BuildResult.new(:test_counts => [64,17,1]),
BuildResult.new(:test_counts => [61,19,5]),
BuildResult.new(:test_counts => [62,19,10]),
BuildResult.new(:test_counts => [64,19,20]),
BuildResult.new(:test_counts => [65,20,40])]
assert File.exist?(filename+".png")
end
private
def filename
"build/#{__method_name__(1)}"
end
end
|
require "./test/test_helper"
class TeamStatsTest < Minitest::Test
def setup
@game_path = './data/game_fixture.csv'
@team_path = './data/team_info.csv'
@game_teams_path = './data/game_team_stats_fixture_corey.csv'
@locations = {games: @game_path,
teams: @team_path,
game_teams: @game_teams_path}
@stat_tracker = StatTracker.from_csv(@locations)
end
def test_stat_tracker_exists
assert_instance_of StatTracker, @stat_tracker
end
def test_team_info_can_be_shown_in_a_hash_of_six_attributes
expected = {
"team_id" => "17",
"franchise_id" => "12",
"short_name" => "Detroit",
"team_name" => "Red Wings",
"abbreviation" => "DET",
"link" => "/api/v1/teams/17"
}
assert_equal expected, @stat_tracker.team_info("17")
end
def test_all_games_played_can_be_gathered
assert_equal 6, @stat_tracker.all_games_played("17").count
end
def test_all_wins_all_time_can_be_gathered_in_a_list
assert_instance_of Array, @stat_tracker.all_wins_by_team("17")
assert_equal 2, @stat_tracker.all_wins_by_team("17").count
end
def test_all_losses_all_time_can_be_gathered_in_a_list
assert_instance_of Array, @stat_tracker.all_losses_by_team("17")
assert_equal 4, @stat_tracker.all_losses_by_team("17").count
end
def test_teams_best_and_worst_season_based_on_win_percentage_can_be_shown
game_path = './data/game_fixture_opponent_testing.csv'
team_path = './data/team_info.csv'
game_teams_path = './data/game_team_stats_fixture_opponent_testing.csv'
locations = {games: game_path,
teams: team_path,
game_teams: game_teams_path}
st = StatTracker.from_csv(locations)
assert_equal "20112012", st.best_season("17")
assert_equal "20122013", st.worst_season("17")
end
def test_teams_average_win_percentage_of_all_games_is_shown
game_path = './data/game_fixture_opponent_testing.csv'
team_path = './data/team_info.csv'
game_teams_path = './data/game_team_stats_fixture_opponent_testing.csv'
locations = {games: game_path,
teams: team_path,
game_teams: game_teams_path}
st = StatTracker.from_csv(locations)
st.average_win_percentage("17")
assert_equal 0.60, st.average_win_percentage("17")
end
def test_teams_highest_and_lowest_number_of_goals_in_a_single_game_is_shown
assert_equal 4, @stat_tracker.most_goals_scored("17")
assert_equal 0, @stat_tracker.fewest_goals_scored("17")
end
def test_all_wins_and_losses_for_a_team_can_be_shown
assert_equal 2, @stat_tracker.all_wins_by_team("17").count
assert_equal 4, @stat_tracker.all_losses_by_team("17").count
end
def test_teams_biggest_blowout_win__and_worst_loss_by_goal_differential_is_shown
game_path = './data/game_fixture_manually_built.csv'
team_path = './data/team_info.csv'
game_teams_path = './data/game_team_stats_fixture_corey.csv'
locations = {games: game_path,
teams: team_path,
game_teams: game_teams_path}
st = StatTracker.from_csv(locations)
assert_equal 3, st.biggest_team_blowout("17")
assert_equal 5, st.worst_loss("17")
end
def test_teams_head_to_head_record_is_shown_versus_a_specific_opponent
game_path = './data/game_fixture_opponent_testing.csv'
team_path = './data/team_info.csv'
game_teams_path = './data/game_team_stats_fixture_opponent_testing.csv'
locations = {games: game_path,
teams: team_path,
game_teams: game_teams_path}
st = StatTracker.from_csv(locations)
expected = ({"Predators"=>0.67, "Maple Leafs"=>0.5})
assert_equal expected, st.head_to_head("17")
end
def test_all_wins_and_all_games_can_be_grouped_by_opponent
game_path = './data/game_fixture_opponent_testing.csv'
team_path = './data/team_info.csv'
game_teams_path = './data/game_team_stats_fixture_opponent_testing.csv'
locations = {games: game_path,
teams: team_path,
game_teams: game_teams_path}
st = StatTracker.from_csv(locations)
expected_1 = ({"18"=>2.0, "10"=>1.0})
expected_2 = ({"18"=>3.0, "10"=>2.0})
assert_equal expected_1, st.all_wins_vs_opponent("17")
assert_equal expected_2, st.all_games_vs_opponent("17")
end
def test_rival_and_favorite_opponent_can_be_shown
game_path = './data/game_fixture_opponent_testing.csv'
team_path = './data/team_info.csv'
game_teams_path = './data/game_team_stats_fixture_opponent_testing.csv'
locations = {games: game_path,
teams: team_path,
game_teams: game_teams_path}
st = StatTracker.from_csv(locations)
assert_equal "Predators", st.favorite_opponent("17")
assert_equal "Maple Leafs", st.rival("17")
end
def test_teams_seasonal_summary_is_shown_for_each_season_it_has_played
game_path = "./data/game_stats_w_reg.csv"
team_path = './data/team_info.csv'
game_teams_path = './data/game_team_stats_same_as_games.csv'
locations = {games: game_path,
teams: team_path,
game_teams: game_teams_path}
st = StatTracker.from_csv(locations)
assert_equal Hash, st.seasonal_summary("6").class
assert_equal Hash, st.seasonal_summary("6")["20122013"].class
assert_equal 2, st.seasonal_summary("6")["20122013"].count
end
end
|
class OrderImportProcessor
@queue = :normal
def self.perform
Rails.logger.info "start OrderImportProcessor::perform"
Client.order_importers.each do |client|
folder = client.abbreviation
Rails.logger.info "import orders from #{client.name} (#{folder})"
ORDER_IMPORT_FILE_PROVIDER.get_and_delete_files(folder) do |content, filename|
Rails.logger.info "importing order file #{filename}"
begin
client.import_orders(content)
rescue => e
Rails.logger.error "Error importing order #{filename} in folder #{folder}. #{e.class.name} #{e.message}\n #{e.backtrace.join("\n ")}"
end
Document.create source: '3DM', filename: filename, content: content
end
end
Rails.logger.info "end OrderImportProcessor::perform"
end
end
|
class Board
attr_accessor :grid, :colors
def initialize (colors)
@grid = Array.new(8){ Array.new(8, nil) }
@colors = colors # board can be created with initial colors b/c the board is going to create new peices with these colors; these can also be initialized in the game if we askt he players to choose thier colors
#colors is an array of two colors
end
def [] pos
row, col = pos
return self.grid[row][col]
end
def []= pos, piece
row, col = pos
grid[row][col] = piece
end
def display
end
def dup #ensure we create a deep copy
clone = Board.new(colors)
self.piece_pile.each do |piece|
duped_piece = piece.dup(clone)
clone.place_piece(piece.pos, duped_piece)
end
clone
end
def find_king color
canidates = piece_pile(color)
king = canidates.select{ |piece| piece.is_a?(King)}[0]
king
end
def in_check? color
king = find_king color
opponent = opponents(color)[0]
piece_pile(opponent).any? do |bad_guy|
bad_guy.moves.include?(king.pos)
end
end
def in_checkmate? color
#all_valid_moves
piece_pile(color).all? {|piece| piece.valid_moves.empty?} && in_check?(color)
end
def move start_pos, end_pos, turn
return false unless 0 <= start_pos[0] && start_pos[0] <= 7 #i.e. if the user gives us a square not on the board
return false unless 0 <= start_pos[1] && start_pos[1] <= 7
return false unless 0 <= end_pos[0] && end_pos[0] <= 7
return false unless 0 <= end_pos[1] && end_pos[1] <= 7
current_piece = self[start_pos]
return false unless current_piece && current_piece.color == turn
return false if !current_piece.valid_moves.include?(end_pos)
return false if self[end_pos] && self[end_pos].color == turn
if current_piece.move_into_check? end_pos
puts "But you are in check!"
return false
end
move! start_pos, end_pos
return true
end
def move! start_pos, end_pos
current_piece = self[start_pos]
self[end_pos] = current_piece
self[start_pos] = nil
current_piece.pos = end_pos
current_piece.is_moved = true
end
def opponents color
#okay this only returns one opponent ever but w/e, it kinda shouldn't be an array but I think this is slightly easier
colors.select { |a_color| a_color != color }
end
def piece_pile color = nil
pile = @grid.flatten()
pile = pile.select { |piece| !piece.nil?}
return pile.select { |piece| piece.color == color} if !color.nil?
pile
end
def place_piece pos, piece
self[pos] = piece
end
def setup_game
#initalizes a new board for a new game of chess! to be called by
#this is a default chess game with no special rules
#colors[0] will be on top, colors[1] will be on bottom
#set up pawns
@grid[1].each_with_index do |tile, index|
Pawn.new([1, index], colors[1], self, 1)
end
@grid[6].each_with_index do |tile, index|
Pawn.new([6, index], colors[0], self, -1)
end
Rook.new([0,0], colors[1], self)
Rook.new([0,7], colors[1], self)
Knight.new([0,1], colors[1], self)
Knight.new([0,6], colors[1], self)
Bishop.new([0,2], colors[1], self)
Bishop.new([0,5], colors[1], self)
Queen.new([0,3], colors[1], self)
King.new([0,4], colors[1], self)
Rook.new([7,0], colors[0], self)
Rook.new([7,7], colors[0], self)
Knight.new([7,1], colors[0], self)
Knight.new([7,6], colors[0], self)
Bishop.new([7,2], colors[0], self)
Bishop.new([7,5], colors[0], self)
Queen.new([7,3], colors[0], self)
King.new([7,4], colors[0], self)
end
end
|
class CreateCompanyLeadInterviews < ActiveRecord::Migration[5.1]
def change
create_table :company_lead_interviews do |t|
t.string :title, default: nil
t.integer :trainer_id, default: nil
t.string :date, default: nil
t.string :location, default: nil
t.integer :company_lead_id
t.text :notes, default: nil
t.string :hire, default: "N/A"
t.integer :interview_reference_id, default: nil
t.boolean :reference, default: false
t.timestamps
end
end
end
|
require "rails_helper"
RSpec.describe ActivityFormsController do
let(:user) { create(:partner_organisation_user, organisation: organisation) }
let(:organisation) { create(:partner_organisation) }
before do
allow(controller).to receive(:current_user).and_return(user)
end
describe "#show" do
context "when editing a programme" do
let(:user) { create(:beis_user) }
let(:fund) { create(:fund_activity) }
let(:activity) { create(:programme_activity, parent: fund) }
context "gcrf_challenge_area step" do
subject { get_step :gcrf_challenge_area }
it { is_expected.to skip_to_next_step }
context "when activity is the GCRF fund" do
let(:activity) { create(:programme_activity, :gcrf_funded) }
it { is_expected.to render_current_step }
end
end
context "gcrf_strategic_area step" do
subject { get_step :gcrf_strategic_area }
it { is_expected.to skip_to_next_step }
context "when activity is the GCRF fund" do
let(:activity) { create(:programme_activity, :gcrf_funded) }
it { is_expected.to render_current_step }
end
end
context "ispf_themes step" do
subject { get_step :ispf_themes }
it { is_expected.to skip_to_next_step }
context "when it's an ISPF activity" do
let(:activity) { create(:programme_activity, :ispf_funded) }
it { is_expected.to render_current_step }
end
end
context "ispf_oda_partner_countries step" do
subject { get_step :ispf_oda_partner_countries }
it { is_expected.to skip_to_next_step }
context "when it's an ISPF activity" do
let(:activity) { create(:programme_activity, :ispf_funded, is_oda: true) }
it { is_expected.to render_current_step }
end
end
context "ispf_non_oda_partner_countries step" do
subject { get_step :ispf_non_oda_partner_countries }
it { is_expected.to skip_to_next_step }
context "when it's an ISPF activity" do
let(:activity) { create(:programme_activity, :ispf_funded, is_oda: false) }
it { is_expected.to render_current_step }
end
end
context "linked_activity step" do
subject { get_step :linked_activity }
it { is_expected.to skip_to_next_step }
context "when the linked activity is editable" do
let(:policy) { double(:policy) }
before do
allow(controller).to receive(:policy).and_return(policy)
allow(policy).to receive(:update_linked_activity?).and_return(true)
end
it { is_expected.to render_current_step }
end
end
context "collaboration_type" do
subject { get_step :collaboration_type }
context "when the field is not editable" do
before do
allow(Activity::Inference.service).to receive(:editable?).with(activity, :collaboration_type).and_return(false)
end
it { is_expected.to skip_to_next_step }
end
context "when the field is editable" do
before do
allow(Activity::Inference.service).to receive(:editable?).with(activity, :collaboration_type).and_return(true)
end
it { is_expected.to render_current_step }
end
end
context "fstc_applies" do
subject { get_step :fstc_applies }
context "when the field is not editable" do
before do
allow(Activity::Inference.service).to receive(:editable?).with(activity, :fstc_applies).and_return(false)
end
it { is_expected.to skip_to_next_step }
end
context "when the field is editable" do
before do
allow(Activity::Inference.service).to receive(:editable?).with(activity, :fstc_applies).and_return(true)
end
it { is_expected.to render_current_step }
end
end
context "tags step" do
subject { get_step :tags }
it { is_expected.to skip_to_next_step }
context "when it's an ISPF activity" do
let(:activity) { create(:programme_activity, :ispf_funded) }
it { is_expected.to render_current_step }
end
end
end
context "when editing a project" do
let(:fund) { create(:fund_activity) }
let(:programme) { create(:programme_activity, parent: fund) }
let(:activity) { create(:project_activity, organisation: organisation, parent: programme) }
context "gcrf_challenge_area step" do
subject { get_step :gcrf_challenge_area }
it { is_expected.to skip_to_next_step }
context "when activity is associated with the GCRF fund" do
let(:activity) { create(:project_activity, organisation: organisation, parent: programme, source_fund_code: Fund.by_short_name("GCRF").id) }
it { is_expected.to render_current_step }
end
end
context "channel_of_delivery_code" do
subject { get_step :channel_of_delivery_code }
context "when the field is not editable" do
before do
allow(Activity::Inference.service).to receive(:editable?).with(activity, :channel_of_delivery_code).and_return(false)
end
it { is_expected.to skip_to_next_step }
end
context "when the field is editable" do
before do
allow(Activity::Inference.service).to receive(:editable?).with(activity, :channel_of_delivery_code).and_return(true)
end
it { is_expected.to render_current_step }
end
end
context "country_partner_organisations" do
subject { get_step :country_partner_organisations }
context "when the activity is newton funded" do
let(:activity) { create(:project_activity, :newton_funded, organisation: organisation, parent: programme) }
it { is_expected.to render_current_step }
end
context "when the activity is GCRF funded" do
let(:activity) { create(:project_activity, :gcrf_funded, organisation: organisation, parent: programme) }
it { is_expected.to skip_to_next_step }
end
end
context "implementing_organisation step" do
subject { get_step :implementing_organisation }
context "when the activity is GCRF funded" do
let(:activity) { create(:third_party_project_activity, :gcrf_funded, organisation: organisation) }
it "completes the activity without rendering the step" do
expect(activity.form_state).to eq("complete")
end
end
context "when the project is ISPF funded" do
let(:activity) { create(:third_party_project_activity, :ispf_funded, organisation: organisation) }
context "and doesn't have any implementing organisations set" do
before do
activity.implementing_organisations = []
end
it { is_expected.to render_current_step }
end
context "and it already has at least one implementing organisation set" do
it "completes the activity without rendering the step" do
expect(activity.form_state).to eq("complete")
end
end
end
end
context "linked_activity step" do
subject { get_step :linked_activity }
it { is_expected.to skip_to_next_step }
context "when the linked activity is editable" do
let(:policy) { double(:policy) }
before do
allow(controller).to receive(:policy).and_return(policy)
allow(policy).to receive(:update_linked_activity?).and_return(true)
end
it { is_expected.to render_current_step }
end
end
context "tags step" do
subject { get_step :tags }
it { is_expected.to skip_to_next_step }
context "when it's an ISPF activity" do
let(:activity) { create(:project_activity, :ispf_funded, organisation: organisation) }
it { is_expected.to render_current_step }
end
end
end
context "when editing a third-party project" do
let(:fund) { create(:fund_activity) }
let(:programme) { create(:programme_activity, parent: fund) }
let(:project) { create(:project_activity, parent: programme) }
let(:activity) { create(:third_party_project_activity, organisation: organisation, parent: project) }
context "gcrf_challenge_area step" do
subject { get_step :gcrf_challenge_area }
it { is_expected.to skip_to_next_step }
context "when activity is associated with the GCRF fund" do
let(:activity) { create(:project_activity, organisation: organisation, parent: programme, source_fund_code: Fund.by_short_name("GCRF").id) }
it { is_expected.to render_current_step }
end
end
context "linked_activity step" do
subject { get_step :linked_activity }
it { is_expected.to skip_to_next_step }
context "when the linked activity is editable" do
let(:policy) { double(:policy) }
before do
allow(controller).to receive(:policy).and_return(policy)
allow(policy).to receive(:update_linked_activity?).and_return(true)
end
it { is_expected.to render_current_step }
end
end
context "tags step" do
subject { get_step :tags }
it { is_expected.to skip_to_next_step }
context "when it's an ISPF activity" do
let(:activity) { create(:third_party_project_activity, :ispf_funded, organisation: organisation) }
it { is_expected.to render_current_step }
end
end
end
describe "commitment" do
let(:policy) { double(:policy, show?: true) }
let(:commitment) { create(:commitment, value: 1000) }
let(:activity) { create(:third_party_project_activity, commitment: commitment) }
before do
allow(ActivityPolicy).to receive(:new).and_return(policy)
allow(controller).to receive(:policy).and_return(policy)
end
context "when the commitment can be set" do
before do
allow(policy).to receive(:set_commitment?).and_return(true)
end
subject { get_step :commitment }
it { is_expected.to render_current_step }
context "when there is already a commitment" do
it "does not build a new commitment when rendering the edit page" do
subject { get_step :commitment }
expect(activity.commitment).to eq(commitment)
end
end
context "when there is no commitment" do
let!(:activity) { create(:third_party_project_activity) }
before do
stub_commitment_builder
end
it "builds a new, empty commitment when rendering the edit page" do
get_step :commitment
expect(Commitment).to have_received(:new)
end
end
end
context "when it cannot be set" do
before do
allow(policy).to receive(:set_commitment?).and_return(false)
end
subject { get_step :commitment }
it { is_expected.to skip_to_next_step }
end
end
end
describe "#update" do
let(:history_recorder) { instance_double(HistoryRecorder, call: true) }
let(:fund) { create(:fund_activity) }
let(:programme) { create(:programme_activity, parent: fund) }
let(:activity) do
create(
:project_activity,
title: "Original title",
description: "Original description",
organisation: organisation,
parent: programme
)
end
let(:report) { double("report") }
let(:policy) { instance_double(ActivityPolicy, update?: true, set_commitment?: true) }
before do
allow(ActivityPolicy).to receive(:new).and_return(policy)
allow(Report).to receive(:editable_for_activity).and_return(report)
allow(HistoryRecorder).to receive(:new).and_return(history_recorder)
end
context "when updating 'purpose' causes #title and #description to be updated" do
let(:expected_changes) do
{
"title" => ["Original title", "Updated title"],
"description" => ["Original description", "Updated description"]
}
end
it "finds the appropriate report to be associated with the changes" do
put_step(:purpose, {title: "Updated title", description: "Updated description"})
expect(Report).to have_received(:editable_for_activity).with(activity)
end
it "asks the HistoryRecorder to record the changes" do
put_step(:purpose, {title: "Updated title", description: "Updated description"})
expect(HistoryRecorder).to have_received(:new).with(user: user)
expect(history_recorder).to have_received(:call).with(
changes: expected_changes,
reference: "Update to Activity purpose",
activity: activity,
trackable: activity,
report: report
)
end
end
context "when setting non-ODA on a programme" do
let(:activity) { programme }
it "updates the RODA identifier to start with 'NODA'" do
put_step(:is_oda, {is_oda: false})
expect(programme.reload.roda_identifier).to start_with("NODA-")
end
end
context "when the activity is invalid" do
before do
allow(Activity).to receive(:find).and_return(activity)
allow(activity).to receive(:valid?).and_return(false)
end
subject { put_step(:purpose, {title: "Updated title", description: "Updated description"}) }
it { is_expected.to render_current_step }
end
context "when the activity is valid" do
before do
allow(Activity).to receive(:find).and_return(activity)
allow(activity).to receive(:valid?).and_return(true)
allow(activity).to receive(:form_steps_completed?).and_return(false)
end
subject { put_step(:purpose, {title: "Updated title", description: "Updated description"}) }
it { is_expected.to skip_to_next_step }
end
context "when updating a commitment" do
let(:activity) { programme }
it "checks whether the user has permission to specifically set the commitment" do
put_step(:commitment, {commitment: {value: "100"}})
expect(policy).not_to have_received(:update?)
expect(policy).to have_received(:set_commitment?)
end
context "with valid params" do
it "allows the user to set the commitment" do
put_step(:commitment, {commitment: {value: "100"}})
expect(programme.reload.commitment.value).to eq(100)
end
end
context "with invalid params" do
it "re-renders the commitment-setting page" do
expect(put_step(:commitment, {commitment: {value: "INVALID"}})).to render_current_step
end
end
end
end
private
def get_step(step)
get :show, params: {activity_id: activity.id, id: step}
end
def put_step(step, activity_params)
put :update, params: {activity_id: activity.id, id: step, activity: activity_params}
end
RSpec::Matchers.define :skip_to_next_step do
match do |actual|
expect(actual).to redirect_to(controller.next_wizard_path)
end
description do
"skip to the next step (#{controller.next_step})"
end
failure_message do |actual|
"expected to skip the next step (#{controller.step}), but didn't"
end
end
RSpec::Matchers.define :render_current_step do
match do |actual|
expect(actual).to render_template(controller.step)
end
description do
"render the current step"
end
failure_message do |actual|
"expected to render the current form step (#{controller.step}), but didn't"
end
end
def stub_commitment_builder
allow(Commitment).to receive(:new).and_call_original
end
end
|
# frozen_string_literal: true
require "song_pro/version"
require "song_pro/song"
require "song_pro/section"
require "song_pro/line"
require "song_pro/part"
require "song_pro/measure"
module SongPro
SECTION_REGEX = /#\s*([^$]*)/
ATTRIBUTE_REGEX = /@(\w*)=([^%]*)/
CUSTOM_ATTRIBUTE_REGEX = /!(\w*)=([^%]*)/
CHORDS_AND_LYRICS_REGEX = %r{(\[[\w#b+/]+\])?([^\[]*)}i
MEASURES_REGEX = %r{([\[[\w#b/]+\]\s]+)[|]*}i
CHORDS_REGEX = %r{\[([\w#b+/]+)\]?}i
COMMENT_REGEX = />\s*([^$]*)/
def self.parse(lines)
song = Song.new
current_section = nil
lines.split("\n").each do |text|
if text.start_with?("@")
process_attribute(song, text)
elsif text.start_with?("!")
process_custom_attribute(song, text)
elsif text.start_with?("#")
current_section = process_section(song, text)
else
process_lyrics_and_chords(song, current_section, text)
end
end
song
end
def self.process_section(song, text)
matches = SECTION_REGEX.match(text)
name = matches[1].strip
current_section = Section.new(name: name)
song.sections << current_section
current_section
end
def self.process_attribute(song, text)
matches = ATTRIBUTE_REGEX.match(text)
key = matches[1]
value = matches[2].strip
if song.respond_to?("#{key}=".to_sym)
song.send("#{key}=", value)
else
puts "WARNING: Unknown attribute '#{key}'"
end
end
def self.process_custom_attribute(song, text)
matches = CUSTOM_ATTRIBUTE_REGEX.match(text)
key = matches[1]
value = matches[2].strip
song.set_custom(key, value)
end
def self.process_lyrics_and_chords(song, current_section, text)
return if text == ""
if current_section.nil?
current_section = Section.new(name: "")
song.sections << current_section
end
line = Line.new
if text.start_with?("|-")
line.tablature = text
elsif text.start_with?("| ")
captures = text.scan(MEASURES_REGEX).flatten
measures = []
captures.each do |capture|
chords = capture.scan(CHORDS_REGEX).flatten
measure = Measure.new
measure.chords = chords
measures << measure
end
line.measures = measures
elsif text.start_with?(">")
matches = COMMENT_REGEX.match(text)
comment = matches[1].strip
line.comment = comment
else
captures = text.scan(CHORDS_AND_LYRICS_REGEX).flatten
captures.each_slice(2) do |pair|
part = Part.new
chord = pair[0]&.strip || ""
part.chord = chord.delete("[").delete("]")
part.lyric = pair[1] || ""
line.parts << part unless (part.chord == "") && (part.lyric == "")
end
end
current_section.lines << line
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.