text stringlengths 10 2.61M |
|---|
require 'sinatra/base'
module Sinatra
##
# Helpers for Tweet controller
module TweetHelpers
##
# do an action (favorite, retweet) with a tweet
def action_tweet(action)
must_login
if action == :retweet
model = Retweet
elsif action == :favorite
model = Favorite
end
result = model.new(tweet_id: params[:id], user_id: session[:user_id])
if result.save
redirect "/users/#{session[:user_id]}/#{action}s"
else
"Error"
end
end
##
# returns cache key for an user's timeline
def timeline_cache_key(u)
"timeline/#{u.cache_key}"
end
##
# return cache key for 100 recent tweets list
# if empty, return "list/empty"
def recent_tweets_list_cache_key
t = Tweet.most_recent_updated
if t.blank?
"list/empty"
else
"list/#{t.cache_key}"
end
end
##
# return cache key for tweet list created by user
def user_tweets_list_cache_key
"list/#{user.cache_key}"
end
##
# return cache key for retweets list by user
def retweets_list_cache_key
"retweet/#{user.cache_key}"
end
##
# return cache key for favorites list by user
def favorites_list_cache_key
"favorite/#{user.cache_key}"
end
end
end
|
require "yaml"
MESSAGES = YAML.load_file("./loan_calculator_messages.yaml")
LANGUAGE = "en"
def prompt(message, after = nil)
main_message = MESSAGES[message] ? MESSAGES[message][LANGUAGE] : message
suffix = after ? " #{after}" : ""
puts("=> #{main_message}#{suffix}")
end
def valid_number?(number)
(number.to_i.to_s == number || number.to_f.to_s == number) && number.to_i > 0
end
def number_input(message)
number = ""
prompt(message)
loop do
number = gets.chomp
if valid_number?(number)
number = number.to_f
break
else
prompt("invalid_number")
end
end
number
end
loop do
# main loop
prompt("welcome")
amount = number_input("enter_loan_amount")
apr = number_input("enter_apr_amount")
months = number_input("enter_loan_duration").to_i * 12
monthly_apr = apr / 12 / 100
monthly_payment = amount * (monthly_apr / (1 - (1 + monthly_apr)**(-months)))
prompt("loan_amount", amount)
prompt("apr_amount", apr)
prompt("loan_duration", months / 12)
prompt("result_prefix", monthly_payment)
prompt("calculate_again?")
answer = gets.chomp
break unless answer.downcase.start_with?("y")
end
prompt("goodbye")
|
include_recipe 'unicorn'
Chef::Log.info "-" * 70
Chef::Log.info "Unicorn Config"
template "#{node['errbit']['deploy_to']}/shared/config/unicorn.conf" do
source "unicorn.conf.erb"
owner node['errbit']['user']
group node['errbit']['group']
mode 00644
end
template "/etc/init.d/unicorn_#{node['errbit']['name']}" do
source "unicorn.service.erb"
owner "root"
group "root"
mode 00755
end
service "unicorn_#{node['errbit']['name']}" do
provider Chef::Provider::Service::Init::Debian
start_command "/etc/init.d/unicorn_#{node['errbit']['name']} start"
stop_command "/etc/init.d/unicorn_#{node['errbit']['name']} stop"
restart_command "/etc/init.d/unicorn_#{node['errbit']['name']} restart"
status_command "/etc/init.d/unicorn_#{node['errbit']['name']} status"
supports :start => true, :stop => true, :restart => true, :status => true
action :nothing
end
# Restarting the unicorn
service "unicorn_#{node['errbit']['name']}" do
action :restart
end
|
class Card
attr_reader :number, :kind
def initialize(number, kind)
@kind = kind
@number = number
end
def color
if [:hearts, :diamonds].include? @kind
:red
else
:black
end
end
end
class Game
attr_reader :play, :name
@@deck = []
def initialize(name)
@play = []
5.times do
@play.append(@@deck.delete(@@deck.sample))
end
end
def reveal
@play.each do |card|
puts "#{card.number} of #{card.kind}"
end
end
def Game.start
[:clover, :hearts, :diamonds, :spades].each do |kind|
(1..13).each do |number|
@@deck.append(Card.new(number,kind))
end
end
end
def Game.deck
@@deck
end
end |
class Trabalho < ApplicationRecord
belongs_to :disciplina
validates :descricao, presence: true
end
|
Rails.application.routes.draw do
root to: 'portfolios#index'
resources :portfolios, only: :index
resources :experiences, only: :index
resources :skills, only: :index
resources :productions, only: :index
end |
require 'rails_helper'
RSpec.describe Event, :type => :model do
describe ".sum_enrollment_time" do
subject { Event.sum_enrollment_time Event.all }
let!(:user) { Fabricate(:user) }
context "総在籍時間が59秒以下" do
context "レコードが1件のとき" do
before do
datetime = DateTime.new(2017, 3, 1)
Fabricate(:event, checkin_at: datetime, checkout_at: datetime + 59.seconds, user_id: user.id, felica_id: user.felica.id)
end
it { expect(subject).to eql "0時間0分" }
end
context "レコードが複数件のとき" do
before do
datetime = DateTime.new(2017, 3, 1)
Fabricate(:event, checkin_at: datetime, checkout_at: datetime + 29.seconds, user_id: user.id, felica_id: user.felica.id)
datetime = DateTime.new(2017, 3, 2)
Fabricate(:event, checkin_at: datetime, checkout_at: datetime + 30.seconds, user_id: user.id, felica_id: user.felica.id)
end
it { expect(subject).to eql "0時間0分" }
end
end
context "総在籍時間が60秒以上" do
context "レコードが1件のとき" do
before do
datetime = DateTime.new(2017, 3, 1)
Fabricate(:event, checkin_at: datetime, checkout_at: datetime + 60.seconds, user_id: user.id, felica_id: user.felica.id)
end
it { expect(subject).to eql "0時間1分" }
end
context "レコードが複数件のとき" do
before do
datetime = DateTime.new(2017, 3, 1)
Fabricate(:event, checkin_at: datetime, checkout_at: datetime + 30.seconds, user_id: user.id, felica_id: user.felica.id)
datetime = DateTime.new(2017, 3, 2)
Fabricate(:event, checkin_at: datetime, checkout_at: datetime + 30.seconds, user_id: user.id, felica_id: user.felica.id)
end
it { expect(subject).to eql "0時間1分" }
end
end
context "総在籍時間が59分未満" do
before do
datetime = DateTime.new(2017, 3, 1)
Fabricate(:event, checkin_at: datetime, checkout_at: datetime + 49.minutes, user_id: user.id, felica_id: user.felica.id)
datetime = DateTime.new(2017, 3, 2)
Fabricate(:event, checkin_at: datetime, checkout_at: datetime + 10.minutes, user_id: user.id, felica_id: user.felica.id)
end
it { expect(subject).to eql "0時間59分" }
end
context "総在籍時間が1時間以上" do
before do
datetime = DateTime.new(2017, 3, 1)
Fabricate(:event, checkin_at: datetime, checkout_at: datetime + 50.minutes, user_id: user.id, felica_id: user.felica.id)
datetime = DateTime.new(2017, 3, 2)
Fabricate(:event, checkin_at: datetime, checkout_at: datetime + 10.minutes, user_id: user.id, felica_id: user.felica.id)
end
it { expect(subject).to eql "1時間0分" }
end
context "総在籍時間が23時間59分以下" do
before do
datetime = DateTime.new(2017, 3, 1)
Fabricate(:event, checkin_at: datetime, checkout_at: datetime + 23.hours, user_id: user.id, felica_id: user.felica.id)
datetime = DateTime.new(2017, 3, 2)
Fabricate(:event, checkin_at: datetime, checkout_at: datetime + 59.minutes, user_id: user.id, felica_id: user.felica.id)
end
it { expect(subject).to eql "23時間59分" }
end
context "総在籍時間が24時間以上" do
before do
datetime = DateTime.new(2017, 3, 1)
Fabricate(:event, checkin_at: datetime, checkout_at: datetime + 23.hours, user_id: user.id, felica_id: user.felica.id)
datetime = DateTime.new(2017, 3, 2)
Fabricate(:event, checkin_at: datetime, checkout_at: datetime + 60.minutes, user_id: user.id, felica_id: user.felica.id)
end
it { expect(subject).to eql "24時間0分" }
end
end
describe "#calculate_enrollment_time" do
let(:user) { Fabricate(:user) }
let(:event) { Fabricate(:event, felica: user.felica, user: user, checkin_at: checkin_at, checkout_at: checkout_at) }
before do
event.calculate_enrollment_seccond
end
context "1分間在籍しているとき" do
let(:checkin_at) { DateTime.now }
let(:checkout_at) { checkin_at + 1.minutes }
it { expect(event.enrollment_time).to eql "00時間01分" }
end
context "1時間在籍しているとき" do
let(:checkin_at) { DateTime.now }
let(:checkout_at) { checkin_at + 1.hour }
it { expect(event.enrollment_time).to eql "01時間00分" }
end
context "1時間30分在籍しているとき" do
let(:checkin_at) { DateTime.now }
let(:checkout_at) { checkin_at + 1.hour + 30.minutes}
it { expect(event.enrollment_time).to eql "01時間30分" }
end
context "24時間以上在籍しているとき" do
let(:checkin_at) { DateTime.now }
let(:checkout_at) { checkin_at + 24.hours + 30.minutes }
it { expect(event.enrollment_time).to eql "チェックアウトをしていません。" }
end
end
describe "#fetch_at" do
let(:now) { DateTime.now }
let!(:next_month) { DateTime.now + 1.month }
let!(:prev_month) { DateTime.now - 1.month }
let!(:user) { Fabricate(:user) }
let(:event) { Fabricate(:event, felica: user.felica, user: user, checkin_at: now, checkout_at: now + 2.hours) }
let(:event_next_month) { Fabricate(:event, felica: user.felica, user: user, checkin_at: next_month, checkout_at: next_month + 2.hours) }
let(:event_prev_month) { Fabricate(:event, felica: user.felica, user: user, checkin_at: prev_month, checkout_at: prev_month + 2.hours) }
it "should return events in this month" do
expect(Event.fetch_at(now)).to match_array event
expect(Event.fetch_at(now)).to_not match_array event_next_month
expect(Event.fetch_at(now)).to_not match_array event_prev_month
end
it "should return events in enxt month" do
# after_createでcheckin_atを更新しているので対処両方的にテストの中でcheckin_atを更新する
event_next_month.update(checkin_at: next_month)
travel_to next_month do
expect(Event.fetch_at(next_month)).to match_array event_next_month
end
end
it "should return events in prev month" do
event_prev_month.update(checkin_at: prev_month)
travel_to prev_month do
expect(Event.fetch_at(prev_month)).to match_array event_prev_month
end
end
end
end
|
module Stradivari
module Concerns
module CssFriendly
extend ActiveSupport::Concern
def css_friendly dom_id
dom_id.gsub( /[\[\]:.,]/, '_' )
end
end
end
end
|
module ReportsKit
class RelativeTime
LETTERS_DURATION_METHODS = {
'y' => :years,
'M' => :months,
'w' => :weeks,
'd' => :days,
'h' => :hours,
'm' => :minutes,
's' => :seconds
}
LETTERS = LETTERS_DURATION_METHODS.keys.join
def self.parse(string, prevent_exceptions: false)
return Time.zone.now if string == 'now'
original_string = string
string = string.to_s.strip
is_negative = string[0, 1] == '-'
string = string[1..-1] if is_negative
result_string = is_negative ? '-' : ''
result_durations = []
string.scan(/(\d+)([#{LETTERS}]?)/) do |number, letter|
result_string += "#{number}#{letter}"
duration_method = LETTERS_DURATION_METHODS[letter]
unless duration_method
return if prevent_exceptions
raise ArgumentError.new("Invalid duration letter: #{letter.inspect}")
end
result_durations << number.to_i.public_send(duration_method)
end
if result_string == '-' || result_string != original_string.to_s.strip
return if prevent_exceptions
raise ArgumentError.new("Invalid time duration: #{original_string.inspect}")
end
duration = result_durations.reduce(&:+)
is_negative ? duration.ago : duration.from_now
end
end
end
|
module Neo4j
module ActiveRel
module Callbacks #:nodoc:
extend ActiveSupport::Concern
include Neo4j::Shared::Callbacks
def save(*args)
unless _persisted_obj || (from_node.respond_to?(:neo_id) && to_node.respond_to?(:neo_id))
fail Neo4j::ActiveRel::Persistence::RelInvalidError, 'from_node and to_node must be node objects'
end
super(*args)
end
end
end
end
|
module Steam
class Hero
attr_reader :raw_hero
def initialize(raw_hero)
@raw_hero = raw_hero
end
def id
@raw_hero['id']
end
def name
@raw_hero['name'].split('_')[3..-1].join(' ').capitalize
end
end
end |
require 'spec_helper'
describe Admin::DiscountsController do
let(:discount) {FactoryGirl.create(:discount)}
context "with user" do
before do
@request.env["devise.mapping"] = Devise.mappings[:user]
sign_in user
end
let(:user) {FactoryGirl.create(:user, :username => 'kat')}
describe "GET 'index'" do
it "should be successful" do
get 'index'
response.should be_success
end
end
describe "GET 'show'" do
it "should be successful" do
get 'show', :id => discount.id
response.should be_success
end
end
describe "GET 'edit'" do
it "should be successful" do
get 'edit', :id => discount.id
response.should be_success
end
end
describe "PUT 'update'" do
it "should be successful" do
put 'update', :id => discount.id
response.should be_success
end
end
describe "GET 'new'" do
it "should be successful" do
get 'new'
response.should be_success
end
end
describe "POST 'create'" do
it "should be successful" do
post 'create'
response.should be_success
end
end
end
context "when anonimous" do
let(:user) {FactoryGirl.create(:user)}
it "should redirect on get index" do
get :index
response.should redirect_to(root_path)
end
it "should redirect on get show" do
get :show, :id => discount.id
response.should redirect_to(root_path)
end
it "should redirect on get new" do
get :new
response.should redirect_to(root_path)
end
it "should redirect on get edit" do
get :edit, :id => discount.id
response.should redirect_to(root_path)
end
it "should redirect on post create" do
post :create, :id => discount.id
response.should redirect_to(root_path)
end
it "should redirect on put update" do
put :update, :id => discount.id
response.should redirect_to(root_path)
end
end
end
|
class Admin::BaseController < ApplicationController
before_action :require_admin
def require_admin
return if current_user.admin?
redirect_to root_path
end
end
|
class MergeConsultantIdIntoFacilitatorId < ActiveRecord::Migration
def change
Review.with_deleted.where.not(consultant_id: nil).find_each do |r|
r.update_column(:facilitator_id, r.consultant_id)
end
remove_column :reviews, :consultant_id
end
end
|
module EasyPatch
module WikiFormattingPatch
def self.included(base)
base.extend(ClassMethods)
base.send(:include, InstanceMethods)
base.class_eval do
alias_method_chain :wikitoolbar_for, :easy_extensions
end
end
module InstanceMethods
# after_submit: html_fragment removes charcters '<' and '>' and everything after
# if js editor is textile => replace < to "<"
# > to ">"
#
def wikitoolbar_for_with_easy_extensions(field_id, options={})
wiki_toolbar = wikitoolbar_for_without_easy_extensions(field_id)
return nil if wiki_toolbar.nil?
after_submit = %{}
if Setting.text_formatting == 'textile'
js_field_id = "_#{field_id.gsub('-', '_')}_val"
after_submit << %{
var form = $("##{field_id}").parents("form");
form.on('submit', function(){
var prev = $("##{field_id}").val();
var modified = prev;
modified = modified.replace(/\</g, "<");
modified = modified.replace(/\>/g, ">");
$("##{field_id}").val(modified);
return true;
});
var #{js_field_id} = $("##{field_id}").val();
#{js_field_id} = #{js_field_id}.replace(/</g, "<");
#{js_field_id} = #{js_field_id}.replace(/>/g, ">");
$("##{field_id}").val(#{js_field_id});
}
end
reminder_confirm = options[:attachment_reminder_message] ? options[:attachment_reminder_message] : l(:text_easy_attachment_reminder_confirm)
reminderjs = options[:attachment_reminder] ? "$('##{field_id}').addClass('set_attachment_reminder').data('ck', false).data('reminder_words', \"#{j(Attachment.attachment_reminder_words)}\").data('reminder_confirm', '#{j(reminder_confirm)}');; " : ''
wiki_toolbar + javascript_tag(after_submit) + javascript_tag(reminderjs)
end
end
module ClassMethods
end
end
end
EasyExtensions::PatchManager.register_other_patch ['Redmine::WikiFormatting::NullFormatter::Helper', 'Redmine::WikiFormatting::Textile::Helper'], 'EasyPatch::WikiFormattingPatch'
|
Capistrano::Configuration.instance.load do
set_default(:resque_user) { user }
set_default(:resque_pid) { "#{current_path}/tmp/pids/resque.pid" }
set_default(:resque_log) { "#{shared_path}/log/resque.log" }
set_default(:resque_workers, 2)
set_default(:resque_queue, "*")
set(:resque_env){ unicorn_env }
set(:resque_name) do
queue = resque_queue.gsub /[^a-z0-9]/i, '_'
"#{safe_application_path}_resque_#{queue}"
end
namespace :resque do
desc "Setup resque initializer and app configuration"
task :setup, roles: :resque do
end
after "deploy:setup", "resque:setup"
after "monit:services", "monit:resque"
%w[start stop restart].each do |command|
desc "#{command} resque"
task command, roles: :resque do
run "#{sudo} monit #{command} -g #{resque_name}_workers"
end
after "deploy:#{command}", "resque:#{command}"
end
end
end |
class User < ActiveRecord::Base
# attr_accessible :title, :body
validates_presence_of :name
validates_presence_of :email
validates_presence_of :password
#validates_uniqueness_of :email
attr_accessible :email, :password
before_save do |record|
unless self.unique then
raise "An user with that email already exist."
end
return true
end
before_create { generate_token(:auth_token) }
after_create do |record|
#UserLog.add_action('create_user')
return true
end
def self.authenticate(email, password)
find(:first, :conditions => ["email = ? and password = ?", "#{email}", "#{password}"])
end
def unique
count = User.where("email = ?", self.email).count
if count > 0
return false
end
return true
end
def generate_token(column)
begin
self[column] = SecureRandom.urlsafe_base64
end while User.exists?(column => self[column])
end
end
|
require 'rails_helper'
RSpec.describe StringDate, type: :model do
describe 'method' do
describe 'to_date' do
it 'for date' do
expect(described_class.new('2000-1-1').to_date).to eq Date.new 2000, 1, 1
end
it 'handles empty' do
expect(described_class.new('').to_date).to be_nil
end
it 'handles malformed date' do
expect(described_class.new('2012-x').to_date).to be_nil
end
end
end
end
|
class CreateTransactions < ActiveRecord::Migration
def change
create_table :transactions do |t|
t.string :street
t.string :city
t.integer :zip
t.string :state
t.integer :beds
t.integer :sq_feet
t.string :category
t.datetime :sale_date
t.float :price
t.float :lat
t.float :lng
t.timestamps null: false
end
end
end
|
class AddAttachmentAttachmentToIncidentattachments < ActiveRecord::Migration[6.0]
def self.up
change_table :incidentattachments do |t|
t.attachment :attachment
end
end
def self.down
remove_attachment :incidentattachments, :attachment
end
end
|
require 'deck'
require 'spec_helper'
describe 'deck' do
let(:deck) { Deck.new }
it 'should have 52 cards' do
expect(deck.count).to eq(52)
end
it 'should deal out cards' do
taken_cards = deck.take(5)
expect(deck.count).to eq(47)
expect(taken_cards.count).to eq(5)
end
it "should be able to take cards back" do
taken_cards = deck.take(5)
deck.take_back(taken_cards)
expect(deck.count).to eq(52)
expect(taken_cards.count).to eq(0)
end
end |
# -*- encoding : utf-8 -*-
require 'spec_helper'
require 'bitcoin_reward_era/version'
Module BitcoinRewardEra do
it 'has a constant VERSION' do
BitcoinRewardEra::VERSION.must_equal '0.0.2'
end
end
|
# require "rails_helper"
#
#
# let(:team) { Team.find_by(name: "Tropics") }
#
# it "creates a team" do
# expect(team).to_not be_nil
# end
#
# it "redirects to the new team's page" do
# expect(current_path).to eq(team_path(team))
# end
# describe TeamsController, type: :controller do
# let(:attributes) do
# {
# name: "Elite",
# city: "Laurel, MD",
# mascot: "Blue Crab",
#
# }
# end
#
# it "renders the show template" do
# team = Team.create!(attributes)
# get :show, id: team.id
# expect(response).to render_template(:show)
# end
# end
|
require "minitest/autorun"
require_relative '../../lib/action/place.rb'
require_relative './robot_maker.rb'
class TestPlace < Minitest::Test
def test_act_place
place = Game::Place.new
robot = RobotMaker::create(1, 3, "WEST")
x, y, direction = place.act(robot, "PLACE 1,3,WEST")
assert_equal 1, x
assert_equal 3, y
assert_equal "WEST", direction
end
end |
class MoveDeliveryTimeFromChannelToAssignment < ActiveRecord::Migration[6.0]
def change
remove_column :channels, :delivery_time, :time, null: false, default: '07:00:00'
add_column :book_assignments, :delivery_time, :time, null: false, default: '07:00:00'
end
end
|
namespace :db do
desc "Fill database with sample data"
task populate: :environment do
admin = User.create!(name:"Sarah",email:"dow213@lehigh.edu",password:"123456",password_confirmation:"123456")
admin.toggle!(:admin)
98.times do |n|
name = Faker::Name.name
email = "test-#{n+1}@lehigh.edu"
password = "123456"
User.create!(name: name, email: email, password: password, password_confirmation: password)
end
users = User.all(limit: 6)
30.times do
content = Faker::Lorem.sentence(5)
users.each {|user| user.microposts.create!(content: content)}
end
end
end |
module YesOrNo
def yes_or_no?(string)
string = string.dup.chomp.downcase.strip
['yes', 'no', 'y', 'n'].include?(string)
end
def yes?(string)
string = string.dup.chomp.downcase.strip
return true if string == 'yes' || string == 'y'
false
end
def no?(string)
string = string.dup.chomp.downcase.strip
return true if string == 'no' || string == 'n'
false
end
def verify(value)
have_answer = false
until have_answer
puts "I have #{value}. Is that correct?"
answer = gets.chomp
have_answer = yes_or_no?(answer)
end
return yes?(answer)
end
end
class Hangman
include YesOrNo
def initialize()
@judge = nil
@guesser = nil
@guesses_left = nil
@board = nil
end
def play
start_game
until over?
guess = @guesser.guess_letter(@board)
letter_locations = @judge.judge_letter(guess, @guesser.name)
if letter_locations.length == 0
@guesses -= 1
else
@board.update(letter_locations, guess )
end
puts
puts "#{@guesser.name} has #{@guesses} wrong guesses left"
puts
end
closing_remarks
end
private
def closing_remarks
if won?
puts "#{@guesser.name} guessed the secret word! There will be no hanging. "
elsif lost?
puts "#{@guesser.name} hangs."
puts "The word was #{@judge.say_word}"
end
play_again
end
def play_again
have_answer = false
until have_answer
puts "Would you like to play again?"
answer = gets.chomp
have_answer = yes_or_no?(answer)
end
if yes?(answer)
self.play
end
end
def over?
won? || lost?
end
def won?
@board.won?
end
def lost?
@guesses == 0
end
def get_player(player)
player_type = player_type(player)
player_name = player_name(player)
if player_type == 'computer'
player = ComputerPlayer.new(player_name)
elsif
player = HumanPlayer.new(player_name)
end
player
end
def player_name(player)
have_player_name = false
until have_player_name
puts "What is #{player}'s name?"
player_name = gets.chomp.strip
have_player_name = verify(player_name)
end
player_name
end
def player_type(player)
have_player_type = false
until have_player_type
puts "Is #{player} a human or a computer?"
player_type = gets.chomp.strip.downcase
if ['human', 'computer'].include?(player_type)
have_player_type = true
end
end
player_type
end
def start_game( options = {} )
defaults = {
:guesses => 10
}
options = defaults.merge(options)
@judge = get_player('the judge')
@guesser = get_player('the hangman')
@guesses = options[:guesses]
letters = @judge.reset_word.word_length
@board = Board.new(letters)
end
end
class Board
attr_reader :current
def initialize(num)
@current = []
num.times { @current << nil }
end
def display
board = @current.map { |spot| spot.nil? ? "_" : spot }
puts "Secret Word: #{board.join(' ')}"
@current
end
def length
@current.length
end
def update(indices, letter)
indices.each do |index|
@current[index] = letter
end
end
def won?
!@current.include?(nil)
end
end
class ComputerPlayer
@@computers = 0
def self.computers
@@computers
end
def self.computers=(num)
@@computers = num
end
attr_accessor(:name)
def initialize(name = nil, dictionary = 'dictionary.txt')
ComputerPlayer.computers += 1
name = "Computer #{ComputerPlayer.computers}" if name.nil?
@name = name
@dictionary = load_dictionary(dictionary)
@remaining_dictionary = nil
@guessed_letters = []
@word = nil
end
def reset_word
@word = @dictionary.keys.sample
self
end
def word_length
reset_word if @word.nil?
@word.length
end
def guess_letter(board)
board.display
@guessed_letters << get_next_best_letter(board)
@guessed_letters[-1]
end
def remaining_dictionary(board)
if @remaining_dictionary == nil
@remaining_dictionary = @dictionary.select do |word, t|
word.length == board.length
end
end
@remaining_dictionary = @remaining_dictionary.select { |wrd, t| word_possible?(wrd, board) }
@remaining_dictionary
end
def word_possible?(word, board)
possible = true
board.current.each_with_index do |spot, index|
if spot.nil?
possible = false if @guessed_letters.include?(word[index])
else
possible = false if word[index] != spot
end
end
possible
end
def get_next_best_letter(board)
remaining_dictionary = self.remaining_dictionary(board)
letters = Hash.new(0)
remaining_dictionary.each do |word, t|
word.each_char do |char|
letters[char] +=1 unless @guessed_letters.include?(char)
end
end
letters.sort_by { |letter, count| count }.pop[0]
end
def judge_letter(letter, name = nil )
indices = []
@word.split('').each_with_index do |l, index|
indices << index if l == letter
end
indices
end
def say_word
@word
end
private
def load_dictionary(dictionary)
Hash[File.readlines(dictionary).map{ |word| [word.chomp, true] }]
end
end
class HumanPlayer
@@humans = 0
def self.humans
@@humans
end
def self.humans=(num)
@@humans = num
end
include YesOrNo
attr_accessor(:name)
def initialize(name = nil)
HumanPlayer.humans += 1
name = "Human #{HumanPlayer.humans}" if name.nil?
@name = name
end
def say_word
puts "What was your word?"
gets.chomp.strip
end
def reset_word
print "#{self.name} think of a word. "
self
end
def word_length
have_len = false
until have_len
puts "How many letters does your word have?"
len = gets.chomp.to_i
have_len = len.to_s.length > 0
end
len
end
def guess_letter(board)
board.display
have_letter = false
until have_letter
puts "#{self.name} guess a letter"
letter = gets.chomp.downcase
have_letter = letter.between?("a", "z")
end
letter
end
def judge_letter(letter, name = "The other player")
return [] unless letter_in_word?(letter, name)
have_spots = false
until have_spots
puts "#{self.name}, at what indices does '#{letter}' occur in your word? (please separate multiple values by commas (eg '0, 4, 5')"
spots = gets.chomp.split(',').map {|index| index.strip.to_i }
have_spots = verify(spots.map(&:to_s).join(', '))
end
spots
end
private
def letter_in_word?(letter, name = "The other player")
have_answer = false
until have_answer
puts "#{self.name}, #{name} picked #{letter}. Is #{letter} in your word?"
answer = gets.chomp
have_answer = yes_or_no?(answer)
end
yes?(answer)
end
end
a = Hangman.new.play |
#!/usr/bin/env ruby
require 'pp'
require 'pathname'
require 'fileutils'
require_relative '../lib/osgeo/termbase.rb'
# require 'pry'
filepath = ARGV[0]
if filepath.nil?
puts 'Error: no filepath given as first argument.'
exit 1
end
if Pathname.new(filepath).extname != ".csv"
puts 'Error: filepath given must have extension .csv.'
exit 1
end
table_config = Osgeo::Termbase::Csv::Config.new(
header_row_index: 2, term_preferred_column: 1, term_admitted_column: 2,
term_abbrev_column: 3, definition_column: 4, source_column: 11,
example1_column: 5, example2_column: 7, example3_column: 9,
note1_column: 6, note2_column: 8, note3_column: 10,
)
concepts = Osgeo::Termbase::Csv.new(filepath, table_config).concepts
# registries = {
# "eng" => {
# metadata: {},
# terms: table.to_concept_collection
# }
# }
output_dir = Dir.pwd
# metadata = {
# 'header' => workbook.glossary_info.metadata_section.to_hash["metadata"]
# }
# # Write registry metadata
# metadata['languages'] = registries.inject({}) do |acc, (lang, data)|
# acc.merge({lang => data[:metadata]})
# end
# File.open(File.join(output_dir, Pathname.new(filepath).basename.sub_ext(".meta.yaml")),"w") do |file|
# file.write(metadata.to_yaml)
# end
# Merge concept arrays
merged_terms = concepts
merged_terms.sort_by! { |t| t.default_designation.downcase }
merged_terms.each.with_index { |t, i| t.id = i + 1 } # Re-calculate ids
collection = Osgeo::Termbase::ConceptCollection.new
merged_terms.each { |t| collection.add_term(t) }
# Aggregated YAML
# collection.to_file(File.join(output_dir, Pathname.new(filepath).basename.sub_ext(".yaml")))
collection_output_dir = File.join(output_dir, "concepts")
FileUtils.mkdir_p(collection_output_dir)
collection.keys.each do |id|
collection[id].to_file(File.join(collection_output_dir, "concept-#{id}.yaml"))
end
|
class CreateGeneralUseRegistersCpus < ActiveRecord::Migration
def change
create_table :general_use_registers_cpus do |t|
t.string :pc
t.string :ir
t.string :mar
t.string :mbr
t.string :r1
t.string :r2
t.string :r3
t.string :r4
t.string :r5
t.string :r6
t.string :data_bus
t.string :dir_bus
t.timestamps
end
end
end
|
class Card
RANKS = (2..10).to_a + [:J, :Q, :K, :A]
SUITS = [:S, :D, :H, :C]
include Comparable
attr_reader :rank, :suit
def initialize(rank, suit)
@rank = rank
@suit = suit
end
def value
case rank
when :K
13
when :Q
12
when :J
11
when :A
1
else
rank
end
end
def <=>(other)
self.value <=> other.value
end
end
class Deck
include Enumerable
def initialize
@cards = []
Card::RANKS.each do |rank|
Card::SUITS.each do |suit|
@cards.push Card.new(rank, suit)
end
end
end
# cards.each do |card|
# names << card.to_s
# end
def each
@cards.each { |card| yield card }
end
end
|
class Transaction::InternalTransfer::InactivityFee < Transaction::InternalTransfer
FEE_PERCENTAGE = 10
FIXED_FEE = 10
def self.charge_person(person)
from_account = person.account
balance = from_account.balance
return if balance <= 0
if balance <= 10
fee = balance
else
fee = ((balance - 10) * (FEE_PERCENTAGE / 100.0)) + 10
fee = fee.round(2, BigDecimal::ROUND_DOWN)
end
txn = nil
ApplicationRecord.transaction do
txn = create!(
audited: true,
description: "InactivityFee for Person#{person.id} #{Date::MONTHNAMES[Time.zone.now.month]}"
)
txn.splits.create!(
amount: -1 * fee,
account: from_account,
item: person
)
txn.splits.create!(
amount: fee,
account: Account::InactivityFee.instance
)
end
txn
end
end
|
require 'spec_helper'
describe DeploymentTargetMetadata do
it { should belong_to(:deployment_target) }
it { should validate_presence_of(:agent_version) }
it { should validate_presence_of(:adapter_version) }
it { should validate_presence_of(:adapter_type) }
end
|
require 'test_helper'
class AnswersControllerTest < ActionController::TestCase
setup do
@answer = answers(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:answers)
end
test "should get new" do
get :new
assert_response :success
end
test "should create answer" do
assert_difference('Answer.count') do
post :create, answer: { amount: @answer.amount, command_id: @answer.command_id, nickname: @answer.nickname, order: @answer.order, payed: @answer.payed }
end
assert_redirected_to command_answers_path(assigns(:answer))
end
test "should show answer" do
get :show, id: @answer
assert_response :success
end
test "should get edit" do
get :edit, id: @answer
assert_response :success
end
test "should update answer" do
patch :update, id: @answer, answer: { amount: @answer.amount, command_id: @answer.command_id, nickname: @answer.nickname, order: @answer.order, payed: @answer.payed }
assert_redirected_to command_answers_path(assigns(:answer))
end
test "should destroy answer" do
assert_difference('Answer.count', -1) do
delete :destroy, id: @answer
end
assert_redirected_to command_answers_path
end
end
|
require 'socket'
module Bitcourier
module Network
class Server
attr_reader :port
def initialize(context, options = {})
@context = context
@port = options.fetch(:port, Bitcourier::CONFIG[:default_port])
end
def run
@server = TCPServer.new port
puts "Started server on port #{port}"
@thread = Thread.new do
loop do
socket = @server.accept
@context.node_manager.add_socket socket, false
end
end
end
def ip_string
end
end
end
end
|
require 'spec_helper'
require 'street_address'
describe Locuser do
before(:context) do
Locuser.config.parser_class = ::StreetAddress::US
end
after(:context) do
Locuser.config.parser_class = nil
end
context 'parsing addresses with StreetAddress gem' do
let(:addr) { Locuser.config.parser_class = ::StreetAddress::US; build(:uwmc) }
it 'appropriately parsed street' do
expect(addr[:street]).to eq('Pacific')
end
it 'appropriately parsed city' do
expect(addr[:city]).to eq('Seattle')
end
it 'appropriately parsed state' do
expect(addr[:state]).to eq('WA')
end
it 'appropriately parsed postal_code' do
expect(addr[:postal_code]).to eq('98195')
end
it 'appropriately parsed and prints address using StreetAddress::US' do
expect(addr.address).to eq("1959 NE Pacific Ave, Seattle, WA 98195")
end
end
# context 'address formatting' do
#
# it 'formats an empty address approrpriately without error' do
# end
#
# end
shared_examples "an address" do
it 'allows creation of an empty address' do
expect(addr.nil?).not_to eq(true)
end
it 'allows access to the address storage' do
expect { addr }.not_to raise_error
end
it 'allows getting of non-existant address components without exception, returning nil' do
expect { addr[:foo] }.not_to raise_error
end
it 'allows setting of appropriate address components' do
expect { addr[:street] = 'street' }.not_to raise_error
expect { addr[:city] = 'city' }.not_to raise_error
expect { addr[:state] = 'state' }.not_to raise_error
expect { addr[:postal_code] = 'postal_code' }.not_to raise_error
expect(addr[:street]).to eq('street')
expect(addr[:city]).to eq('city')
expect(addr[:state]).to eq('state')
expect(addr[:postal_code]).to eq('postal_code')
end
end # Rspec.shared_examples
describe Locuser::HashedAddress do
it_behaves_like "an address" do
let (:addr) { create(:hashed_address) }
end
end
describe Locuser::OwnerStreetAddress do
it_behaves_like "an address" do
let (:addr) { create(:owned_address) }
end
it 'allows explicit creation of the entity-node relationship' do
a = Locuser::TestAddressOwner.new
a.taxonomy_node = Locuser::TestOwnerAddress.new
expect(a.taxonomy_node).not_to eq(nil)
expect(a.taxonomy_node.owner).to eq(a)
end
end
end
|
class ListContainer
attr_accessor :lists, :block
def initialize(&block)
@lists = []
@block = block
end
def add(list_id, list = nil, text = nil, options = {}, &block)
text, options, list = list, text, block if block_given?
options, text = text, options if Hash === text
if list and (Proc === list or list.any?)
@lists << [list_id, list, text, options]
end
end
end
module EntityRESTHelpers
def list_container_render(container)
partial_render('entity_partials/list_container', :container => container)
end
end
|
require 'spec_helper'
describe 'openstacklib::db::mysql::host_access' do
let :pre_condition do
"include mysql::server\n" +
"openstacklib::db::mysql { 'nova':\n" +
" password_hash => 'AA1420F182E88B9E5F874F6FBE7459291E8F4601'}"
end
shared_examples 'openstacklib::db::mysql::host_access examples' do
context 'with required parameters' do
let (:title) { 'nova_10.0.0.1' }
let :params do
{
:user => 'foobar',
:password_hash => 'AA1420F182E88B9E5F874F6FBE7459291E8F4601',
:database => 'nova',
:privileges => 'ALL'
}
end
it { should contain_mysql_user("#{params[:user]}@10.0.0.1").with(
:plugin => nil,
:password_hash => params[:password_hash],
:tls_options => ['NONE']
)}
it { should contain_mysql_grant("#{params[:user]}@10.0.0.1/#{params[:database]}.*").with(
:user => "#{params[:user]}@10.0.0.1",
:privileges => 'ALL',
:table => "#{params[:database]}.*"
)}
end
context 'with overriding authentication plugin' do
let (:title) { 'nova_10.0.0.1' }
let :params do
{
:user => 'foobar',
:plugin => 'mysql_native_password',
:password_hash => 'AA1420F182E88B9E5F874F6FBE7459291E8F4601',
:database => 'nova',
:privileges => 'ALL'
}
end
it { should contain_mysql_user("#{params[:user]}@10.0.0.1").with(
:plugin => params[:plugin],
:password_hash => params[:password_hash],
:tls_options => ['NONE']
)}
it { should contain_mysql_grant("#{params[:user]}@10.0.0.1/#{params[:database]}.*").with(
:user => "#{params[:user]}@10.0.0.1",
:privileges => 'ALL',
:table => "#{params[:database]}.*"
)}
end
context 'with skipping user creation' do
let (:title) { 'nova_10.0.0.1' }
let :params do
{
:user => 'foobar',
:password_hash => 'AA1420F182E88B9E5F874F6FBE7459291E8F4601',
:database => 'nova',
:privileges => 'ALL',
:create_user => false,
}
end
it { should_not contain_mysql_user("#{params[:user]}@10.0.0.1") }
it { should contain_mysql_grant("#{params[:user]}@10.0.0.1/#{params[:database]}.*").with(
:user => "#{params[:user]}@10.0.0.1",
:privileges => 'ALL',
:table => "#{params[:database]}.*"
)}
end
context 'with skipping grant creation' do
let (:title) { 'nova_10.0.0.1' }
let :params do
{
:user => 'foobar',
:password_hash => 'AA1420F182E88B9E5F874F6FBE7459291E8F4601',
:database => 'nova',
:privileges => 'ALL',
:create_grant => false,
}
end
it { should contain_mysql_user("#{params[:user]}@10.0.0.1").with(
:plugin => nil,
:password_hash => params[:password_hash]
)}
it { should_not contain_mysql_grant("#{params[:user]}@10.0.0.1/#{params[:database]}.*") }
end
context 'with skipping user and grant creation' do
let (:title) { 'nova_10.0.0.1' }
let :params do
{
:user => 'foobar',
:password_hash => 'AA1420F182E88B9E5F874F6FBE7459291E8F4601',
:database => 'nova',
:privileges => 'ALL',
:create_user => false,
:create_grant => false,
}
end
it { should_not contain_mysql_user("#{params[:user]}@10.0.0.1") }
it { should_not contain_mysql_grant("#{params[:user]}@10.0.0.1/#{params[:database]}.*") }
end
end
on_supported_os({
:supported_os => OSDefaults.get_supported_os
}).each do |os,facts|
context "on #{os}" do
let (:facts) do
facts.merge!(OSDefaults.get_facts())
end
it_behaves_like 'openstacklib::db::mysql::host_access examples'
end
end
end
|
class GamesController < ApplicationController
before_action :authenticate_user!, only: [:new, :create, :edit, :update, :destroy]
def index
@games = Game.all
end
def new
@game = Game.new
end
def create
@game = current_user.games.create(game_params)
if @game.valid?
redirect_to root_path
else
render :new, status: :uprocessable_entity
end
end
def show
@game = Game.find_by_id(params[:id])
return render_not_found if @game.blank?
end
def edit
@game = Game.find_by_id(params[:id])
return render_not_found if @game.blank?
return render_not_found(:forbidden) if @game.user != current_user
end
def update
@game = Game.find_by_id(params[:id])
return render_not_found if @game.blank?
return render_not_found(:forbidden) if @game.user != current_user
@game.update_attributes(game_params)
if @game.valid?
redirect_to root_path
else
return render :edit, status: :uprocessable_entity
end
end
def destroy
@game = Game.find_by_id(params[:id])
return render_not_found if @game.blank?
return render_not_found(:forbidden) if @game.user != current_user
@game.destroy
redirect_to root_path
end
private
def game_params
params.require(:game).permit(:name, :rating, :description, :picture)
end
def render_not_found(status=:not_found)
render plain: "#{status.to_s.titleize}", status: status
end
end
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
# A Vagrantfile to set up three VMs, a webserver, a database server
# and a admin webserver, connected together using an internal
# network with manually-assigned IP addresses for the VMs.
# Original author: David Eyers (COSC349 Lab06)
# Modified by: Jakob Harvey
Vagrant.configure("2") do |config|
config.vm.box = "ubuntu/xenial64"
# A VM to run the web server.
config.vm.define "webserver" do |webserver|
webserver.vm.hostname = "webserver"
# Host computer can connect to IP address 127.0.0.1 port 8080,
# and that network request will reach our webserver VM's port 80.
webserver.vm.network "forwarded_port", guest: 80, host: 8080, host_ip: "127.0.0.1"
# Set up a private network that our VMs will use to communicate
# with each other.
webserver.vm.network "private_network", ip: "192.168.2.11"
# This following line is only necessary in the CS Labs.
webserver.vm.synced_folder ".", "/vagrant", owner: "vagrant", group: "vagrant", mount_options: ["dmode=775,fmode=777"]
# Now we have a section specifying the shell commands to provision
# the webserver VM. Note that the file test-website.conf is copied
# from this host to the VM through the shared folder mounted in
# the VM at /vagrant
webserver.vm.provision "shell", inline: <<-SHELL
apt-get update
apt-get install -y apache2 php libapache2-mod-php php-mysql
# Change VM's webserver's configuration to use shared folder.
# (Look inside userWebsite.conf for specifics.)
cp /vagrant/userWebsite.conf /etc/apache2/sites-available/
# activate our website configuration ...
a2ensite userWebsite
# ... and disable the default website provided with Apache
a2dissite 000-default
# Reload the webserver configuration, to pick up our changes
service apache2 reload
SHELL
end
# A second VM to run the admin web server.
config.vm.define "adminserver" do |adminserver|
adminserver.vm.hostname = "adminserver"
# Host computer can connect to IP address
# 127.0.0.1 port 8080, and that network
# request will reach our webserver VM's port 80.
adminserver.vm.network "forwarded_port", guest: 80, host: 8081, host_ip: "127.0.0.1"
# Set up a private network that our VMs will use to communicate
# with each other.
adminserver.vm.network "private_network", ip: "192.168.2.13"
# This following line is only necessary in the CS Labs.
adminserver.vm.synced_folder ".", "/vagrant", owner: "vagrant", group: "vagrant", mount_options: ["dmode=775,fmode=777"]
# Now we have a section specifying the shell commands to provision
# the webserver VM. Note that the file test-website.conf is copied
# from this host to the VM through the shared folder mounted in
# the VM at /vagrant
adminserver.vm.provision "shell", inline: <<-SHELL
apt-get update
apt-get install -y apache2 php libapache2-mod-php php-mysql
# Change VM's webserver's configuration to use shared folder.
# (Look inside adminWebsite.conf for specifics.)
cp /vagrant/adminWebsite.conf /etc/apache2/sites-available/
# activate our website configuration ...
a2ensite adminWebsite
# ... and disable the default website provided with Apache
a2dissite 000-default
# Reload the webserver configuration, to pick up our changes
service apache2 reload
SHELL
end
# Section for defining the database server.
config.vm.define "dbserver" do |dbserver|
dbserver.vm.hostname = "dbserver"
# It is important that no two VMs attempt to use the same
# IP address on the private_network.
dbserver.vm.network "private_network", ip: "192.168.2.12"
dbserver.vm.synced_folder ".", "/vagrant", owner: "vagrant", group: "vagrant", mount_options: ["dmode=775,fmode=777"]
dbserver.vm.provision "shell", inline: <<-SHELL
# Update Ubuntu software packages.
apt-get update
# Create a shell variable MYSQL_PWD that contains the MySQL root password
export MYSQL_PWD='insecure_mysqlroot_pw'
# If you run the `apt-get install mysql-server` command
# manually, it will prompt you to enter a MySQL root
# password. The next two lines set up answers to the questions
# the package installer would otherwise ask ahead of it asking,
# so our automated provisioning script does not get stopped by
# the software package management system attempting to ask the
# user for configuration information.
echo "mysql-server mysql-server/root_password password $MYSQL_PWD" | debconf-set-selections
echo "mysql-server mysql-server/root_password_again password $MYSQL_PWD" | debconf-set-selections
# Install the MySQL database server.
apt-get -y install mysql-server
# Run some setup commands to get the database ready to use.
# First create a database.
echo "CREATE DATABASE fvision;" | mysql
# Then create a database user "webuser" with the given password.
echo "CREATE USER 'webuser'@'%' IDENTIFIED BY 'insecure_db_pw';" | mysql
# Grant all permissions to the database user "webuser" regarding
# the "fvision" database that we just created, above.
echo "GRANT ALL PRIVILEGES ON fvision.* TO 'webuser'@'%'" | mysql
# Set the MYSQL_PWD shell variable that the mysql command will
# try to use as the database password ...
export MYSQL_PWD='insecure_db_pw'
# ... and run all of the SQL within the setup-database.sql file,
# which is part of the repository containing this Vagrantfile, so you
# can look at the file on your host. The mysql command specifies both
# the user to connect as (webuser) and the database to use (fvision).
cat /vagrant/setup-database.sql | mysql -u webuser fvision
# By default, MySQL only listens for local network requests,
# i.e., that originate from within the dbserver VM. We need to
# change this so that the webserver VM can connect to the
# database on the dbserver VM. Use of `sed` is pretty obscure,
# but the net effect of the command is to find the line
# containing "bind-address" within the given `mysqld.cnf`
# configuration file and then to change "127.0.0.1" (meaning
# local only) to "0.0.0.0" (meaning accept connections from any
# network interface).
sed -i'' -e '/bind-address/s/127.0.0.1/0.0.0.0/' /etc/mysql/mysql.conf.d/mysqld.cnf
# We then restart the MySQL server to ensure that it picks up
# our configuration changes.
service mysql restart
SHELL
end
end
# LocalWords: webserver xenial64
|
class User < ApplicationRecord
authenticates_with_sorcery!
has_many :book_assignments, dependent: :destroy
has_many :subscriptions, dependent: :destroy
scope :activated_in_stripe, -> (active_emails) { where(plan: :free).where(email: active_emails) } # stripeで購読したけどまだDBの支払いステータスに反映されていないuser
scope :canceled_in_stripe, -> (active_emails) { where(plan: :basic).where.not(email: active_emails) } # stripeで解約したけどまだDBの支払いステータスに反映されていないuser
enum plan: { free_plan: "free", basic_plan: "basic" }
validates :email, presence: true, uniqueness: true
# activation実行に必要なのでダミーのパスワードを設定
## before_validateでcryptedの作成処理が走るので、それより先に用意できるようにafter_initializeを使用
after_initialize do
self.password = SecureRandom.hex(10)
end
# 新規作成時(未activation): EmailDigest作成
after_create do
EmailDigest.find_or_create_by!(digest: digest) # 退会済みユーザーの場合はEmailDigestが存在する
end
# Email変更後にEmailDigestも変更
after_update do
if saved_change_to_email?
ed = EmailDigest.find_by(digest: Digest::SHA256.hexdigest(email_before_last_save))
ed.update(digest: digest)
end
end
after_destroy do
EmailDigest.find_by(digest: digest).update(canceled_at: Time.current)
end
def admin?
email == "info@notsobad.jp"
end
def digest
Digest::SHA256.hexdigest(email)
end
def subscribe(book_assignment, delivery_method: "email")
subscriptions.create!(book_assignment: book_assignment, delivery_method: delivery_method)
end
def trialing?
trial_start_date && trial_start_date <= Date.current && Date.current <= trial_end_date
end
def trial_scheduled?
trial_start_date && Date.current <= trial_start_date
end
class << self
# stripeで支払い中のメールアドレス一覧
def active_emails_in_stripe
emails = []
subscriptions = Stripe::Subscription.list({limit: 100, expand: ['data.customer']})
subscriptions.auto_paging_each do |sub|
emails << sub.customer.email
end
raise 'Email duplicated!' if emails.length != emails.uniq.length
emails
end
end
end
|
require_relative '../../test_helper'
class ImageTest < Minitest::Test
def setup
@printer = Escpos::Printer.new
end
def test_image
image_path = File.join(__dir__, '../../fixtures/tux_mono.png')
image_file = File.new image_path
image = Escpos::Image.new image_file,
processor: "MiniMagick"
image_file.close
@printer << image
@printer << "\n" * 10
@printer.cut!
image.processor.image.write(File.join(__dir__, "../../results/#{__method__}.png"))
file = File.join(__dir__, "../../results/#{__method__}.txt")
#@printer.save file
assert_equal IO.binread(file), @printer.to_escpos
end
def test_image_conversion
image_path = File.join(__dir__, '../../fixtures/tux_alpha.png')
image = Escpos::Image.new image_path, grayscale: true,
compose_alpha: true, extent: true,
processor: "ChunkyPng"
@printer << image.to_escpos
@printer << "\n" * 10
@printer.cut!
image.processor.image.metadata = {}
image.processor.image.save(File.join(__dir__, "../../results/#{__method__}.png"))
file = File.join(__dir__, "../../results/#{__method__}.txt")
#@printer.save file
assert_equal IO.binread(file), @printer.to_escpos
end
end
|
require 'spec_helper'
describe Vote do
subject(:vote) { build(:vote) }
describe "#sum_unique_candidate" do
let(:candidate) { create(:candidate) }
let!(:votes) { create_list(:vote, 2, candidate: candidate) }
before :each do
votes.each { |vote| vote.active! vote.email_hash }
end
it "increments the number of candidate votes" do
expect(candidate.number_of_unique_votes).to eq 2
end
end
describe "#generate_validator!" do
subject(:vote) { create(:vote) }
it { expect(vote.email_hash).to_not be_nil }
end
describe "#active!" do
subject(:vote) { create(:vote, candidate: candidate) }
let!(:candidate) { create(:candidate) }
let!(:candidate_votes) { candidate.number_of_unique_votes }
context "when secret key is valid" do
before :each do
Timecop.freeze
vote.active! vote.email_hash
end
it "expects status be truthy" do
expect(vote.status).to be_truthy
end
it "expects incremente candidate votes" do
expect(candidate.number_of_unique_votes).to eq(candidate_votes+1)
end
it "expects be time.now" do
expect(vote.activeted_at).to eq Time.now
end
end
context "when secret key is invalid" do
it { expect{ vote.active! "hashfusuhhsu" }.to raise_error(ArgumentError) }
end
end
describe "#confirmation!" do
subject(:vote) { create(:vote) }
before :each do
Timecop.freeze
vote.active! vote.email_hash
end
it { expect(subject.confirmation).to be_truthy }
it { expect(subject.confirmation_at).to eq Time.now }
# send mail by sendmail
xit { expect(ActionMailer::Base.deliveries.last).to eq [vote.email] }
end
end |
class AddDisplayOption < ActiveRecord::Migration
def change
add_column :peer_allies, :display, :boolean
end
end
|
# frozen_string_literal: true
require_relative 'test_helper'
module Dynflow
class ExecutionPlan
describe Hooks do
include PlanAssertions
let(:world) { WorldFactory.create_world }
class Flag
class << self
attr_accessor :raised_count
def raise!
self.raised_count ||= 0
self.raised_count += 1
end
def raised?
raised_count > 0
end
def lower!
self.raised_count = 0
end
end
end
module FlagHook
def raise_flag(_execution_plan)
Flag.raise!
end
def controlled_failure(_execution_plan)
Flag.raise!
raise "A controlled failure"
end
def raise_flag_root_only(_execution_plan)
Flag.raise! if root_action?
end
end
class ActionWithHooks < ::Dynflow::Action
include FlagHook
execution_plan_hooks.use :raise_flag, :on => :success
end
class ActionOnStop < ::Dynflow::Action
include FlagHook
execution_plan_hooks.use :controlled_failure, :on => :stopped
end
class RootOnlyAction < ::Dynflow::Action
include FlagHook
execution_plan_hooks.use :raise_flag_root_only, :on => :stopped
end
class PendingAction < ::Dynflow::Action
include FlagHook
execution_plan_hooks.use :raise_flag, :on => :pending
end
class AllTransitionsAction < ::Dynflow::Action
include FlagHook
execution_plan_hooks.use :raise_flag
end
class ComposedAction < RootOnlyAction
def plan
plan_action(RootOnlyAction)
plan_action(RootOnlyAction)
end
end
class ActionOnFailure < ::Dynflow::Action
include FlagHook
execution_plan_hooks.use :raise_flag, :on => :failure
end
class ActionOnPause < ::Dynflow::Action
include FlagHook
def run
error!("pause")
end
def rescue_strategy
Dynflow::Action::Rescue::Pause
end
execution_plan_hooks.use :raise_flag, :on => :paused
end
class Inherited < ActionWithHooks; end
class Overriden < ActionWithHooks
execution_plan_hooks.do_not_use :raise_flag
end
before { Flag.lower! }
after { world.persistence.delete_delayed_plans({}) }
it 'runs the on_success hook' do
refute Flag.raised?
plan = world.trigger(ActionWithHooks)
plan.finished.wait!
assert Flag.raised?
end
it 'runs the on_pause hook' do
refute Flag.raised?
plan = world.trigger(ActionOnPause)
plan.finished.wait!
assert Flag.raised?
end
describe 'with auto_rescue' do
let(:world) do
WorldFactory.create_world do |config|
config.auto_rescue = true
end
end
it 'runs the on_pause hook' do
refute Flag.raised?
plan = world.trigger(ActionOnPause)
plan.finished.wait!
assert Flag.raised?
end
end
it 'runs the on_failure hook on cancel' do
refute Flag.raised?
@start_at = Time.now.utc + 180
delay = world.delay(ActionOnFailure, { :start_at => @start_at })
delayed_plan = world.persistence.load_delayed_plan(delay.execution_plan_id)
delayed_plan.execution_plan.cancel.each(&:wait)
assert Flag.raised?
end
it 'does not alter the execution plan when exception happens in the hook' do
refute Flag.raised?
plan = world.plan(ActionOnStop)
plan = world.execute(plan.id).wait!.value
assert Flag.raised?
_(plan.result).must_equal :success
end
it 'inherits the hooks when subclassing' do
refute Flag.raised?
plan = world.trigger(Inherited)
plan.finished.wait!
assert Flag.raised?
end
it 'can override the hooks from the child' do
refute Flag.raised?
plan = world.trigger(Overriden)
plan.finished.wait!
refute Flag.raised?
end
it 'can determine in side the hook, whether the hook is running for root action or sub-action' do
refute Flag.raised?
plan = world.trigger(ComposedAction)
plan.finished.wait!
_(Flag.raised_count).must_equal 1
end
it 'runs the pending hooks when execution plan is created' do
refute Flag.raised?
plan = world.trigger(PendingAction)
plan.finished.wait!
_(Flag.raised_count).must_equal 1
end
it 'runs the pending hooks when execution plan is created' do
refute Flag.raised?
delay = world.delay(PendingAction, { :start_at => Time.now.utc + 180 })
delayed_plan = world.persistence.load_delayed_plan(delay.execution_plan_id)
delayed_plan.execution_plan.cancel.each(&:wait)
_(Flag.raised_count).must_equal 1
end
it 'runs the hook on every state transition' do
refute Flag.raised?
plan = world.trigger(AllTransitionsAction)
plan.finished.wait!
# There should be 5 transitions
# nothing -> pending -> planning -> planned -> running -> stopped
_(Flag.raised_count).must_equal 5
end
end
end
end
|
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :find_root_categories, :initialize_cart
private
def initialize_cart
@cart = session[:cart] ||= Cart.new
end
def find_root_categories
@root_categories = Category.roots.order(:position)
end
end
|
require 'test_helper'
class SaleTest < ActiveSupport::TestCase
def setup
@voucher = products(:voucher)
@tshirt = products(:tshirt)
@mug = products(:mug)
end
# test method get_discount_product(product,sale_quantity)
test "get_discount_product without params c0" do
discount = Sale.get_discount_product()
assert_equal({quantity_free: 0, discount: 0}, discount)
end
test "get_discount_product product without discount c1" do
discount = Sale.get_discount_product(@mug,0)
assert_equal({quantity_free: 0, discount: 0}, discount)
end
test "get_discount_product product without discount c2" do
discount = Sale.get_discount_product(@mug,10)
assert_equal({quantity_free: 0, discount: 0}, discount)
end
test "get_discount_product product with get-free discount c0" do
discount = Sale.get_discount_product(@voucher,0)
assert_equal({quantity_free: 0, discount: 0}, discount)
end
test "get_discount_product product with get-free discount c1" do
discount = Sale.get_discount_product(@voucher,1)
assert_equal({quantity_free: 0, discount: 0}, discount)
end
test "get_discount_product product with get-free discount c2" do
discount = Sale.get_discount_product(@voucher,2)
assert_equal({quantity_free: 1, discount: 0}, discount)
end
#
test "get_discount_product product with price-reduce discount c0" do
discount = Sale.get_discount_product(@tshirt,0)
assert_equal({quantity_free: 0, discount: 0}, discount)
end
test "get_discount_product product with price-reduce discount c1" do
discount = Sale.get_discount_product(@tshirt,2)
assert_equal({quantity_free: 0, discount: 0}, discount)
end
test "get_discount_product product with price-reduce discount c2" do
discount = Sale.get_discount_product(@tshirt,3)
assert_equal(0,discount[:quantity_free].to_i)
assert_equal(3,discount[:discount].to_i)
end
test "get_discount_product product with price-reduce discount c3" do
discount = Sale.get_discount_product(@tshirt,4)
assert_equal(0,discount[:quantity_free])
assert_equal(4,discount[:discount].to_i)
end
# test method get_sale_totals(products), by_id = true
test "get_sale_totals without params c0" do
totals = Sale.get_sale_totals()
assert_equal({total: 0, total_discount: 0, net: 0,total_quantity: 0, total_quantity_free: 0 }, totals)
end
test "get_sale_totals with params c1" do
products = [{product_id: @voucher.id,quantity: 1},{product_id: @tshirt.id, quantity: 2}]
totals = Sale.get_sale_totals(products,true)
assert_equal(45,totals[:total].to_i)
assert_equal(0,totals[:total_discount].to_i)
assert_equal(45,totals[:net].to_i)
assert_equal(3,totals[:total_quantity])
assert_equal(0,totals[:total_quantity_free])
end
test "get_sale_totals with params c2" do
products = [{product_id: @voucher.id,quantity: 2},{product_id: @tshirt.id, quantity: 3}]
totals = Sale.get_sale_totals(products,true)
assert_equal(70,totals[:total].to_i)
assert_equal(8,totals[:total_discount].to_i)
assert_equal(62,totals[:net].to_i)
assert_equal(5,totals[:total_quantity])
assert_equal(1,totals[:total_quantity_free])
end
test "get_sale_totals with params c3" do
products = [{product_id: @voucher.id,quantity: 5},{product_id: @tshirt.id, quantity: 5}]
totals = Sale.get_sale_totals(products,true)
assert_equal(125,totals[:total].to_i)
assert_equal(15,totals[:total_discount].to_i)
assert_equal(110,totals[:net].to_i)
assert_equal(10,totals[:total_quantity])
assert_equal(2,totals[:total_quantity_free])
end
test "get_sale_totals with params c4" do
products = [{product_id: @voucher.id,quantity: 1},{product_id: @tshirt.id, quantity: 1},
{product_id: @voucher.id,quantity: 1},{product_id: @tshirt.id, quantity: 1},
{product_id: @voucher.id,quantity: 2},{product_id: @tshirt.id, quantity: 1},
{product_id: @mug.id,quantity: 1},{product_id: @mug.id, quantity: 1}]
totals = Sale.get_sale_totals(products,true)
assert_equal(95,totals[:total].to_i)
assert_equal(13,totals[:total_discount].to_i)
assert_equal(82,totals[:net].to_i)
assert_equal(9,totals[:total_quantity])
assert_equal(2,totals[:total_quantity_free])
end
# test method get_sale_totals(products), by_id = false
test "get_sale_totals with params c5" do
products = [{product_code: @voucher.code,quantity: 5},{product_code: @tshirt.code, quantity: 5}]
totals = Sale.get_sale_totals(products,false)
assert_equal(125,totals[:total].to_i)
assert_equal(15,totals[:total_discount].to_i)
assert_equal(110,totals[:net].to_i)
assert_equal(10,totals[:total_quantity])
assert_equal(2,totals[:total_quantity_free])
end
end
|
class AddSubtotalToEntries < ActiveRecord::Migration
def change
add_money :entries, :subtotal, amount: { null: true, default: nil }
end
end
|
class SessionsController < ApplicationController
def new
end
def create
# find the user using the email
user = User.find_by_email params[:email]
# if the user is found and the user's password authenticates
if user && user.authenticate(params[:password])
# store the user_id in the session
session[:user_id]= user.id
# otherwise redirect them to login
redirect_to users_path(current_user)
else
flash.now.notice = "Invalid email or password"
render "new"
end
# use the user_id in the session to load the user when login_required
session[:user_id] = params[:user_id]
session[:email] = params[:email]
end
def destroy
reset_session
redirect_to root_url, :notice => "Logged out!"
end
private
def create_user_session(user, opts= {})
back_to = session[:back_to] || opts[:reidrect] || root_url
log_in(user)
redirect_to back_to, :notice => "Logged in!"
end
end
|
class ChangeMessagesEnabledToDefaultToTrueOnIdea < ActiveRecord::Migration
def self.up
change_column_default :ideas, :messages_enabled, true
end
def self.down
change_column_default :ideas, :messages_enabled, false
end
end
|
World(Rack::Test::Methods)
Given /^I sent a valid json order data with one product$/ do
header 'Accept', 'application/json'
header 'Content-Type', 'application/json'
post '/api/order.json',{
:customer => { :first_name => 'Calvin', :last_name => 'Tee', :email => 'calvin@example.com'},
:products => [{ :id => 1, :quantity => 1 }]
}.to_json
end
Then /^I should receive the created order in json$/ do
data = ActiveSupport::JSON.decode(last_response.body)
order_data = data["order"]
order_data.nil?.should == false
order_data["id"].nil?.should == false
order_data["order_lines"].count.should == 1
end
Given /^I sent a valid json order data with two products$/ do
header 'Accept', 'application/json'
header 'Content-Type', 'application/json'
post '/api/order.json',{
:customer => { :first_name => 'Calvin', :last_name => 'Tee', :email => 'calvin@example.com'},
:products => [{ :id => 1, :quantity => 1 },{ :id => 2, :quantity => 1 }]
}.to_json
end
Then /^I should receive the created order data with two products in json$/ do
data = ActiveSupport::JSON.decode(last_response.body)
order_data = data["order"]
order_data.nil?.should == false
order_data["id"].nil?.should == false
order_data["order_lines"].count.should > 1
end
Then /^I send payment details to complete the order$/ do
data = ActiveSupport::JSON.decode(last_response.body)
order_data = data["order"]
put "/api/order/#{order_data["id"]}.json",{
:billing_address => { :first_name => 'Calvin',
:last_name => 'Tee',
:email => 'calvin@example.com',
:address1 => '2323,
:test land',
:address2 => 'me test',
:city => 'Awesome city',
:state_name => 'Plain Awesomeness',
:state_id => nil,
:country => { :id => 1 } },
:payment => { :payment_method=>'creditcard',
:payment_data =>{
:credit_card_number => '4111111111111111',
:expiry_date => '04/15',
:cvv => '132',
}
},
}.to_json
end
Then /^I should receive the updated order in json$/ do
data = ActiveSupport::JSON.decode(last_response.body)
order_data = data["order"]
puts order_data.to_yaml
end
Then /^I should not receive the updated order in json$/ do
pending # express the regexp above with the code you wish you had
end
|
require File.dirname(__FILE__) + '/test_helper'
context "StructoUrlGen" do
test "It can generate a correct CREATE query with NO attributes" do
resource = StructoUrlGen.create_query "app_name", "Person", "11111", "22222"
assert resource.url == "app_name.structoapp.com/api/person.json?public_key=11111&private_key=22222"
end
test "It can generate a correct CREATE query with attributes" do
resource = StructoUrlGen.create_query "app_name", "Person", "11111", "22222", {"name" => "john"}
assert resource.url == "app_name.structoapp.com/api/person.json?public_key=11111&private_key=22222&person[name]=john"
end
test "It can generate a correct RETRIEVE query" do
resource = StructoUrlGen.retrieve_query "app_name", "Person", "11111", "22222", "1"
assert resource.url == "app_name.structoapp.com/api/person/1.json?public_key=11111&private_key=22222"
end
test "It can generate a correct UPDATE query" do
resource = StructoUrlGen.update_query "app_name", "Person", "11111", "22222", "1", {"place" => "home"}
assert resource.url == "app_name.structoapp.com/api/person/1.json?public_key=11111&private_key=22222&person[place]=home"
end
test "It can generate a correct DELETE query" do
resource = StructoUrlGen.delete_query "app_name", "Person", "11111", "22222", "1"
assert resource == "app_name.structoapp.com/api/person/1.json?public_key=11111&private_key=22222"
end
test "It can genereate a corret SEARCH query" do
resource = StructoUrlGen.search_query "app_name", "Person", "11111", "22222", {"name" => "john", "place" => "home"}
assert resource.url == "app_name.structoapp.com/api/person.json?public_key=11111&private_key=22222&name=john&place=home"
end
test "It can generate a correct LIST query" do
resource = StructoUrlGen.search_query "app_name", "Person", "11111", "22222"
assert resource.url == "app_name.structoapp.com/api/person.json?public_key=11111&private_key=22222"
end
end
|
#encoding: utf-8
require_relative '../lib/pdist'
require 'test/unit'
class TestPDist < Test::Unit::TestCase
def setup
@a = %w(a b c d)
@b = @a.reverse
@c = %w(b d c a)
end
def test_distances
assert_equal([0,0,0,0], PDist.distances(@a,@a))
assert_equal([3,1,1,3], PDist.distances(@a,@b))
assert_equal([3,1,0,2], PDist.distances(@a,@c))
end
def test_deviation
assert_equal(0, PDist.deviation(@a,@a))
assert_equal(1, PDist.deviation(@a,@b))
assert_equal(6.0/8.0, PDist.deviation(@a,@c))
end
def test_square
assert_equal(0, PDist.square(@a,@a))
assert_equal(1, PDist.square(@a,@b))
assert_equal(4.2/6.0, PDist.square(@a,@c))
end
def test_hamming
assert_equal(0, PDist.hamming(@a,@a))
assert_equal(1, PDist.hamming(@a,@b))
assert_equal(0.75, PDist.hamming(@a,@c))
end
def test_rdist
assert_equal(0, PDist.rdist(@a,@a))
assert_equal(1, PDist.rdist(@a,@b))
assert_equal(1, PDist.rdist(@a,@c))
assert_equal(2.0/3.0, PDist.rdist(@a,%w(a b d c)))
end
def test_lcs
assert_equal(0, PDist.lcs(@a,@a))
assert_equal(1, PDist.lcs(@a,@b))
assert_equal(2.0/3.0, PDist.lcs(@a,@c))
end
def test_kendalls_tau
assert_equal(0, PDist.kendalls_tau(@a,@a))
assert_equal(1, PDist.kendalls_tau(@a,@b))
assert_equal(2.0/3.0, PDist.kendalls_tau(@a,@c))
end
end |
require 'rails_helper'
RSpec.feature "visitor can search for spaces" do
scenario "they enter a valid search query into the homepage search" do
planet = create(:planet)
user = create(:user)
spaces = create_list(:space, 4, planet: planet, approved: true)
user.spaces << spaces
# unmatching_space_1 = create(:space, planet: planets[1], approved: true)
# unmatching_space_2 = create(:space, planet: planets[0], approved: true)
# create(:reservation, space: unmatching_space_2)
visit '/'
fill_in "planet", with: planet.name
fill_in "occupancy", with: 0
fill_in "start_date", with: "2016/07/15"
fill_in "end_date", with: "2016/07/18"
click_button "search"
expect(current_path).to eq '/spaces'
expect(page).to have_content(spaces[0].name)
expect(page).to have_content(spaces[1].name)
expect(page).to have_content(spaces[2].name)
expect(page).to have_content(spaces[3].name)
# expect(page).to_not have_content(unmatching_space_1.name)
# expect(page).to_not have_content(unmatching_space_2.name)
end
scenario "They enter a search that invalidates a space by planet" do
planet_1 = create(:planet)
planet_2 = create(:planet)
user = create(:user)
valid_space = create(:space, planet: planet_1, approved: true)
invalid_space = create(:space, planet: planet_2, approved: true)
user.spaces << valid_space << invalid_space
visit '/'
fill_in "planet", with: planet_1.name
fill_in "occupancy", with: 0
fill_in "start_date", with: "2016/07/15"
fill_in "end_date", with: "2016/07/18"
click_button "search"
expect(current_path).to eq '/spaces'
expect(page).to have_content(valid_space.name)
expect(page).to_not have_content(invalid_space.name)
end
scenario "They enter a search that invalidates a space by reservation" do
planet = create(:planet)
user = create(:user)
valid_space = create(:space, planet: planet, approved: true)
invalid_space = create(:space, planet: planet, approved: true)
user.spaces << valid_space << invalid_space
create(:reservation, space: invalid_space)
visit '/'
fill_in "planet", with: planet.name
fill_in "occupancy", with: 0
fill_in "start_date", with: "2016/07/15"
fill_in "end_date", with: "2016/07/18"
click_button "search"
expect(current_path).to eq '/spaces'
expect(page).to have_content(valid_space.name)
expect(page).to_not have_content(invalid_space.name)
end
scenario "They enter a search that has no results" do
planet = create(:planet)
visit '/'
fill_in "planet", with: planet.name
fill_in "occupancy", with: 0
fill_in "start_date", with: "2016/07/15"
fill_in "end_date", with: "2016/07/18"
click_button "search"
expect(current_path).to eq '/'
expect(page).to have_content("There were no valid search results.")
end
end
|
#require_relative '~/BearReps/project3/app/helpers/scraper.rb'
require 'faker'
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
# generate 20 users
# # Via - https://dev.to/debosthefirst/how-to-seed-your-rails-database-with-faker-1be3
User.destroy_all
User.create!(
# each user is assigned an id from 1-20
id: 21,
fname: "Brutus",
email: "buckeye.1@osu.edu",
lname: "Buckeye",
nameDotNumber: "buckeye.1",
year: %w[Freshman, Sophomore Junior Senior].sample,
# issue each user the same password
password: "password",
# a user can have only one of these roles
user_type: "admin",
verified: "true"
)
User.create!(
# each user is assigned an id from 1-20
id: 22,
fname: "Developer",
email: "buckeye.2@osu.edu",
lname: "Buckeye",
nameDotNumber: "buckeye.2",
year: %w[Freshman, Sophomore Junior Senior].sample,
# issue each user the same password
password: "password!",
# a user can have only one of these roles
user_type: "dev",
verified: "true"
)
(1..20).each do |id|
User.create!(
# each user is assigned an id from 1-20
id: id,
fname: Faker::Name.first_name,
email: Faker::Internet.email,
lname: Faker::Name.last_name,
nameDotNumber: Faker::Name.last_name,
year: %w[Freshman, Sophomore Junior Senior].sample,
# issue each user the same password
password: "password",
# a user can have only one of these roles
user_type: %w[student admin teacher].sample,
#verified: %w[true false].sample
)
end
# courses = Scraper.scrape('cse 3901', Scraper.get_terms, Scraper.get_campuses)
|
class ProblemsController < ApplicationController
before_action :authenticate_user!
before_action :set_problem, only: %i[show edit update destroy]
before_action :authorize_user!, only: %i[edit update destroy]
def index
#Query searches category column of problem table for full/partial matches from user entered data
@problems = if params[:search].present?
@problems = Problem.where('category ILIKE ?', "%#{params[:search][:category]}%")
else
Problem.all
end
end
def new
@problem = Problem.new
end
def create
@problem = current_user.problems.new(problem_params)
if @problem.save
redirect_to problem_path(@problem.id)
else
render 'new'
end
end
def show; end
def edit; end
def update
@problem.update(problem_params)
redirect_to problem_path(@problem[:id])
end
def destroy
@problem.destroy
redirect_to problems_path
end
private
def set_problem
@problem = Problem.includes(solutions: [image_attachment: :blob]).find(params[:id])
end
def problem_params
params.require(:problem).permit(:title, :body, :category, :image)
end
def authorize_user!
redirect_to problems_path(params[:problem_id]) unless @problem.user == current_user
end
end
|
# Given a string of words separated by spaces, write a method that takes this
# string of words and returns a string in which the first and last letters of
# every word is swapped.
# You may assume that every word contains at least one letter, and that the
# string will always contain at least one word. You may also assume that each
# string contains nothing but words and spaces
def swap_letters(word)
word[0], word[-1] = word[-1], word[0]
word
end
def swap(str)
result = str.split(' ').map {
|word| swap_letters(word)
}
result.join(' ')
end
p swap('Oh what a wonderful day it is') == 'hO thaw a londerfuw yad ti si'
p swap('Abcde') == 'ebcdA'
p swap('a') == 'a' |
require_relative 'pixel'
class Screen
attr_accessor :width
attr_accessor :height
attr_accessor :matrix
def initialize(width, height)
self.width = width
self.height = height
self.matrix = []
row = []
for var in 1..width do
row.push(nil)
end
for var in 1..height do
matrix.push(row)
end
# each element in matrix is a row array
# (x,y) -> self.matrix[y][x]
end
# Insert a Pixel at x, y
def insert(pixel, x, y)
if inbounds(x,y)
self.matrix[y][x] = pixel
else
return nil
end
end
def at(x, y)
self.matrix[y][x]
end
private
def inbounds(x, y)
if (x >= 0 && x <= width)
if (y >= 0 && y <= height)
return true
end
end
return false
end
end |
FactoryBot.define do
factory :user do
first_name { FFaker::Name.first_name }
last_name { FFaker::Name.last_name }
email { FFaker::Internet.email }
password 'password'
trait :with_motherboard do
before(:create) do |user|
user.motherboards.build
end
end
end
end
|
class AddBoostCountToUsers < ActiveRecord::Migration[5.2]
def change
add_column :users, :boost_count, :integer, default: 0
add_column :users, :priority_count, :integer, default: 0
add_column :users, :post_requests_count, :integer, default: 0
end
end
|
class ModerationController < ApplicationController
skip_before_action :require_token
before_action :require_secure_request
def callback
# Try to find the given ActiveRecord or Redis object
model_class = params[:model_class].to_s.constantize
@model = if params[:model_id].present?
if model_class.respond_to?(:find)
model_class.find(params[:model_id])
elsif model_class.ancestors.include?(Peanut::RedisModel)
model_class.new(id: params[:model_id])
end
end
if @model
if params[:passed] && params[:passed].include?('video_approval') && @model.is_a?(Story)
notify_approved
@model.approve!
elsif params[:failed] && params[:failed].include?('video_approval') && @model.is_a?(Story)
video_rejection = VideoRejection.create! do |vr|
vr.story_id = @model.id
vr.video_moderation_reject_reason_id = params[:reject_reason_id]
vr.custom_message_to_user = params[:message_to_user]
end
notify_censored(video_rejection)
@model.censor!
end
render_success
else
render_error("Could not find a record for the given model_class and model_id.")
end
end
private
def notify_approved
if @model.review? && !@model.deleted?
@model.user.send_approved_story_notifications
end
end
def notify_censored(video_rejection)
message = video_rejection.message_to_user
if @model.review? && !@model.deleted?
@model.user.send_censored_story_notifications(message)
end
end
end
|
require 'spec_helper'
describe Analyst::Entities::Class do
let(:parser) { Analyst.for_file("./spec/fixtures/music/music.rb") }
let(:artist) { parser.classes.detect { |klass| klass.full_name == "Artist" } }
let(:singer) { parser.classes.detect { |klass| klass.full_name == "Singer" } }
let(:amp) { parser.classes.detect { |klass| klass.full_name == "Performances::Equipment::Amp" }}
describe "#method_calls" do
it "lists all method invocations within a class definition" do
macro_names = artist.macros.map(&:name)
expect(macro_names).to match_array ["attr_accessor"]
end
end
describe "#imethods" do
it "returns a list of instance methods" do
method_names = artist.imethods.map(&:name)
expect(method_names).to match_array ["initialize", "starve"]
end
end
describe "#cmethods" do
it "returns a list of class methods" do
class_method_names = singer.cmethods.map(&:name)
expect(class_method_names).to match_array ["superstar", "sellouts"]
end
end
describe "#constants" do
it "returns a list of constants" do
constants = amp.constants.map(&:name)
expect(constants).to match_array ["Interfaces::Basic", "Performances::Equipment::Microphone", "Performances::Equipment::MicStand"]
end
end
end
|
require 'ffwd/plugin/datadog/utils'
describe FFWD::Plugin::Datadog::Utils do
describe "#safe_string" do
it "should escape unsafe characters" do
expect(described_class.safe_string("foo bar")).to eq("foo_bar")
expect(described_class.safe_string("foo:bar")).to eq("foo_bar")
end
end
describe "#make_tags" do
it "should build safe tags" do
tags = {:foo => "bar baz"}
ref = ["foo:bar_baz"]
expect(described_class.safe_tags(tags)).to eq(ref)
end
end
describe "#safe_entry" do
it "should escape parts of entries" do
entry = {:name => :name, :host => :host, :attributes => {:foo => "bar baz"}}
ref = {:metric=>"name", :host => :host, :tags=>["foo:bar_baz"]}
expect(described_class.safe_entry(entry)).to eq(ref)
end
it "should use 'what' attribute as the datadog metric name" do
entry = {:name => :name, :host => :host, :attributes => {:foo => "bar baz"}, :what => "thing"}
ref = {:metric=>"thing", :host => :host, :tags=>["foo:bar_baz", "ffwd_key:#{:name}"]}
expect(described_class.safe_entry(entry)).to eq(ref)
end
end
end
|
class Kid < ActiveRecord::Base
has_and_belongs_to_many :candies
end
|
# Suppose a hash representing a directory. All keys are strings with names for either folders or files.
# Keys that are folders point to nested hashes. Keys that are files point to "true".
# Write a function that takes such a hash and returns an array of strings with the path to each file in the hash.
# file_list(files) # => ['a/b/c/d/e', 'a/b/c/f']
# hash = {
# 'file' => true,
# 'folder' => {}
# }
def file_list(hash)
# return if hash.empty?
res = []
path = ''
keys = hash.keys
# keys.each do |key|
# path += key
# end
hash.each do |key, val|
if val.keys.length == 1
path += key
elsif
else
res << path
end
end
res
end
hash = {
'folder' => {},
'file' => true
}
p file_list(hash)
|
require_relative 'actionable.rb'
module Game
class Move < Game::Actionable
SPEED = 1
MOVE_FROM = {
"WEST" => lambda { |x,y| return x -= Game::Move::SPEED, y },
"EAST" => lambda { |x,y| return x += Game::Move::SPEED, y },
"NORTH" => lambda { |x,y| return x, y += Game::Move::SPEED },
"SOUTH" => lambda { |x,y| return x, y -= Game::Move::SPEED }
}
private
def execute_command(x, y, direction)
return Game::Move::MOVE_FROM[direction].call(x,y) << direction
end
end
end |
# == Schema Information
#
# Table name: projects
#
# id :integer not null, primary key
# position :integer
# title :string(255)
# description :text
# url :string(255)
# user_id :integer
# client_id :integer
# created_at :datetime
# updated_at :datetime
#
class Project < ActiveRecord::Base
acts_as_list
# Accessors
attr_accessible :position, :title, :description, :url, :client_id, :images_attributes
# Associations
belongs_to :user
belongs_to :client
has_many :images, :as => :attachable, :dependent => :destroy
# Nested Models
accepts_nested_attributes_for :images, :reject_if => :all_blank, :allow_destroy => true
# Scopes
default_scope order: 'position'
end
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.require_version ">= 1.7.0"
Vagrant.configure("2") do |config|
provisioner = Vagrant::Util::Platform.windows? ? "ansible_local" : "ansible"
hostsFile = Vagrant::Util::Platform.windows? ? "ansible/hosts/hosts_windows.txt" : "ansible/hosts/hosts_linux.txt"
config.vm.box = "ubuntu/xenial64"
config.vm.network "private_network", ip: "10.0.12.44"
config.ssh.forward_agent = true
config.vm.boot_timeout = 600
if provisioner == "ansible"
config.vm.synced_folder ".", "/var/www/gravity-float", type: "nfs"
end
if provisioner == "ansible_local"
config.vm.synced_folder ".", "/vagrant"
config.vm.synced_folder ".", "/var/www/gravity-float"
end
config.vm.provider :virtualbox do |v|
v.customize ["modifyvm", :id, "--natdnshostresolver1", "on"]
v.customize ["modifyvm", :id, "--memory", 2048]
v.customize ["modifyvm", :id, "--cpus", 2]
end
config.vm.provision provisioner do |ansible|
ansible.verbose = "v"
ansible.playbook = "ansible/site.yml"
ansible.limit = "all"
ansible.inventory_path = "ansible/inventories/local"
end
end
|
class Game < ApplicationRecord
validates :player1, :player2, :point1, :point2, presence: true
after_initialize :increase_win_loss
def increase_win_loss
if (point1 > point2)
winner = player1
loser = player2
else
winner = player2
loser = player1
end
won_user = User.find(winner)
lost_user = User.find(loser)
won_user_win = won_user.win.next
lost_user_loss = lost_user.loss.next
won_user.win = won_user_win
lost_user.loss = lost_user_loss
end
end
|
class EventsController < ApplicationController
protect_from_forgery
def index
@in_state_events = Event.where(state: current_user.state).includes(:host, :users)
@out_of_state_events = Event.where.not(state: current_user.state).includes(:host, :users, :state)
end
def create
event = Event.create(
event_params.merge({
state: State.find(event_params[:state]),
host: current_user
})
)
redirect_to '/events'
end
def attend
@event.attendees << current_user
@event.save
end
def show
@event = Event.find(params[:id])
@comments = @event.comments
# @attendees = EventRoster.@event
end
def edit
@event = Event.find(params[:id])
@states = get_states
end
def update
event = Event.find(params[:id])
event.update(
event_params.merge(
state: State.find(event_params[:state])
)
)
# event.update(name: event_params[:name], date: event_params[:date], city: event_params[:city], state: event_params[:state])
redirect_to '/events'
end
def destroy
event = Event.find(params[:id])
event.destroy
redirect_to "/events"
end
private
def event_params
params.require(:event).permit(:name, :date, :city, :state)
end
end
|
class Question < ActiveRecord::Base
has_many :choices
belongs_to :questionaire
validates :content, presence: true
validates :questionaire_id, presence: true
end
|
# frozen_string_literal: true
require 'journey'
describe Journey do
let(:journey) { double :journey }
let(:station) { double :station }
let(:station_name) { double :station_name }
# let(:journey){ {entry_station: entry_station, exit_station: exit_station} }
describe '#touch_in' do
it 'Commences a journey' do
# subject.top_up 1
allow(journey).to receive(:touch_in).and_return true
expect(journey.touch_in(station_name)).to eq true
end
it 'raises an error if user has already tapped in' do
subject.touch_in(station_name)
expect{subject.touch_in(station_name)}.to raise_error("You have already tapped in!")
end
end
it "allows a user to know where they've travelled from" do
# subject.top_up 5
allow(journey).to receive(:touch_in).and_return true
# journey.touch_in("Kings Cross")
expect(journey.touch_in(station_name)).to eq true
end
describe '#touch_out' do
it 'Ends a journey' do
# subject.top_up 5
allow(journey).to receive(:touch_in).and_return true
allow(journey).to receive(:touch_out).and_return false
allow(journey).to receive(:in_journey).and_return false
journey.touch_in(station_name)
journey.touch_out station_name
expect(journey.in_journey).to eq false
end
it 'has an empty list of journeys by default' do
allow(journey).to receive(:all_journeys).and_return []
expect(journey.all_journeys).to be_empty
end
it 'raises an error if user has already tapped out' do
subject.touch_in(station_name)
subject.touch_out(station_name)
expect{subject.touch_out(station_name)}.to raise_error("You have already tapped out!")
end
# it 'stores a journey' do
# journey.touch_in(entry_station)
# journey.touch_out(exit_station)
# expect(journey.all_journeys).to include one_journey
# end
end
describe '#fare' do
it 'Should return minimum fare or penalty fare' do
subject.touch_in(station_name)
expect(subject.entry_station).not_to be(nil)
end
it 'Should return minimum fare or penalty fare' do
subject.touch_in(station_name)
subject.touch_out(station_name)
expect(subject.exit_station).not_to be(nil)
end
it 'Should return minimum fare' do
subject.touch_in(station_name)
subject.touch_out(station_name)
expect(subject.fare).to eq(Journey::MINIMUM_FARE)
end
end
end
|
class CreateMatches < ActiveRecord::Migration
def change
create_table :matches do |t|
t.integer :team1_id
t.integer :team2_id
t.integer :team1_results
t.string :team2_results
t.boolean :confirmed
t.datetime :dateted_to
t.string :place
t.string :map_latlng
t.string :map_zoom
t.string :is_cancel, default: false
t.integer :tournament_id
t.integer :parent_id
t.timestamps
end
end
end
|
namespace :easyproject do
desc <<-END_DESC
EasyProject installer
Example:
bundle exec rake easyproject:install RAILS_ENV=production
END_DESC
task :install_with_environment => :environment do
unless EasyProjectLoader.can_start?
puts "The Easy Project cannot start because the Redmine is not migrated!"
puts "Please run `bundle exec rake db:migrate RAILS_ENV=production`"
puts "and than `bundle exec rake easyproject:install RAILS_ENV=production`"
exit 1
end
puts 'Invoking db:migrate...'
Rake::Task['db:migrate'].invoke
puts 'Invoking redmine:plugins:migrate...'
Rake::Task['redmine:plugins:migrate'].invoke
puts 'Invoking easyproject:service_tasks:data_migrate...'
Rake::Task['easyproject:service_tasks:data_migrate'].invoke
puts 'Invoking redmine:plugins:assets...'
Rake::Task['redmine:plugins:assets'].invoke
# puts 'Invoking easyproject:service_tasks:delete_orphans...'
# Rake::Task['easyproject:service_tasks:delete_orphans'].invoke
puts 'Invoking easyproject:service_tasks:clear_cache...'
Rake::Task['easyproject:service_tasks:clear_cache'].invoke
puts 'Invoking easyproject:service_tasks:invoking_cache...'
Rake::Task['easyproject:service_tasks:invoking_cache'].invoke
EasyExtensions.additional_installer_rake_tasks.each do |t|
puts 'Invoking ' + t.to_s
Rake::Task[t].invoke
end
end
task :install_without_environment do
puts 'Invoking generate_secret_token...'
Rake::Task['generate_secret_token'].invoke
puts 'Invoking change_plugins_order...'
Rake::Task['easyproject:change_plugins_order'].invoke
puts 'Invoking clearing session...'
Rake::Task['tmp:sessions:clear'].invoke
end
task :install do
Rake::Task['easyproject:install_without_environment'].invoke
Rake::Task['easyproject:install_with_environment'].invoke
end
end
|
RSpec.describe Actual::Export do
let(:partner_organisation) { create(:partner_organisation) }
let(:activities) { Activity.where(organisation: partner_organisation) }
let(:export) { Actual::Export.new(activities) }
let(:quarter_headers) { export.headers.drop(2) }
let(:actual_data) { export.rows }
let!(:project) { create(:project_activity, organisation: partner_organisation, beis_identifier: SecureRandom.uuid) }
it "exports an empty data set" do
expect(quarter_headers).to eq []
expect(actual_data).to eq([
[project.roda_identifier, project.beis_identifier]
])
end
it "exports one quarter of spend for a single project" do
create(:actual, parent_activity: project, financial_year: 2014, financial_quarter: 1, value: 10)
create(:actual, parent_activity: project, financial_year: 2014, financial_quarter: 1, value: 20)
expect(quarter_headers).to eq ["FQ1 2014-2015"]
expect(actual_data).to eq([
[project.roda_identifier, project.beis_identifier, "30.00"]
])
end
it "exports two quarters of spend for a single project with zeros for intervening quarters" do
create(:actual, parent_activity: project, financial_year: 2014, financial_quarter: 1, value: 10)
create(:actual, parent_activity: project, financial_year: 2014, financial_quarter: 4, value: 20)
expect(quarter_headers).to eq ["FQ1 2014-2015", "FQ2 2014-2015", "FQ3 2014-2015", "FQ4 2014-2015"]
expect(actual_data).to eq([
[project.roda_identifier, project.beis_identifier, "10.00", "0.00", "0.00", "20.00"]
])
end
it "exports actual spend for two activities across different quarters" do
third_party_project = create(:third_party_project_activity, organisation: partner_organisation, beis_identifier: SecureRandom.uuid)
create(:actual, parent_activity: project, financial_year: 2014, financial_quarter: 1, value: 10)
create(:actual, parent_activity: third_party_project, financial_year: 2015, financial_quarter: 2, value: 20)
expect(quarter_headers).to eq ["FQ1 2014-2015", "FQ2 2014-2015", "FQ3 2014-2015", "FQ4 2014-2015", "FQ1 2015-2016", "FQ2 2015-2016"]
expect(actual_data).to match_array([
[project.roda_identifier, project.beis_identifier, "10.00", "0.00", "0.00", "0.00", "0.00", "0.00"],
[third_party_project.roda_identifier, third_party_project.beis_identifier, "0.00", "0.00", "0.00", "0.00", "0.00", "20.00"]
])
end
it "includes activities that do not have any actuals recorded" do
third_party_project = create(:third_party_project_activity, organisation: partner_organisation, beis_identifier: SecureRandom.uuid)
create(:actual, parent_activity: project, financial_year: 2014, financial_quarter: 1, value: 10)
expect(quarter_headers).to eq ["FQ1 2014-2015"]
expect(actual_data).to match_array([
[project.roda_identifier, project.beis_identifier, "10.00"],
[third_party_project.roda_identifier, third_party_project.beis_identifier, "0.00"]
])
end
end
|
class BuildsController < ApplicationController
def index
@builds = scope.paginated_by_date(params[:page], 50)
respond_to do |format|
format.html
format.json { render :json => @builds }
end
end
def show
@build = scope.find(params[:id])
respond_to do |format|
format.html
format.json { render :json => @build }
end
end
def create
@project = Project.find_by_jenkins_id(params[:project_id])
unless @project
flash[:error] = 'You must specify a project'
redirect_to projects_path
return
end
build = @project.builds.build(:sha => Github.current_sha_for(@project),
:repo => @project.repo)
BuildCreator.new(build).create!
redirect_to(project_builds_path(@project))
end
def destroy
@build = scope.find(params[:id])
@build.destroy
respond_to do |format|
format.html do
if params[:project_id]
redirect_to project_builds_path(@project)
else
redirect_to builds_path
end
end
format.json { head :no_content }
end
end
protected
def scope
if params[:project_id]
@project = Project.find_by_jenkins_id(params[:project_id])
@project.builds
else
Build
end
end
end
|
class Customer
attr_reader(:name, :wallet, :age, :drunkenness)
def initialize(name, cash, age)
@name = name
@wallet = cash
@drunkenness = 0
@drinks = []
@foods = []
@age = age
end
def drink_count()
return @drinks.count()
end
def add_drink(drink)
@drinks.push(drink)
end
def add_food(food)
@foods.push(food)
end
def drunkenness_level
return @drunkenness
end
def too_drunk
if @drunkenness > 16
return "To Drunk!"
end
end
def increase_drunk_level(drink)
@drunkenness += drink.alcohol
end
def decrease_drunk_level(food)
@drunkenness -= food.rejuvenation_level
end
def decrease_wallet(amount)
@wallet -= amount
end
def check_age
if @age >= 18
return @age
else
return "To Young!"
end
end
def get_total_drunkenness()
total = 0
for alcohol in @drinks
total += alcohol.alcohol
end
return total
end
end
|
require_relative 'questions_database.rb'
class QuestionLike
def self.all
results = QuestionsDatabase.instance.execute('SELECT * FROM question_likes')
results.map { |result| QuestionLike.new(result) }
end
def self.find_by_question_id(question_id)
result = QuestionsDatabase.instance.execute(<<-SQL, question_id)
SELECT
*
FROM
question_likes
WHERE
question_id = ?
SQL
QuestionLike.new(result[0])
end
def self.find_by_user_id(user_id)
result = QuestionsDatabase.instance.execute(<<-SQL, user_id)
SELECT
*
FROM
question_likes
WHERE
user_id = ?
SQL
QuestionLike.new(result[0])
end
def self.likers_for_question_id(question_id)
results = QuestionsDatabase.instance.execute(<<-SQL, question_id)
SELECT
users.fname, users.lname, users.id
FROM
question_likes
INNER JOIN
users ON question_likes.user_id = users.id
WHERE
question_likes.question_id = ?
SQL
results.map { |result| User.new(result) }
end
def self.num_likes_for_question_id(question_id)
results = QuestionsDatabase.instance.execute(<<-SQL, question_id)
SELECT
COUNT(user_id)
FROM
question_likes
GROUP BY
question_id
SQL
results[0]
end
def self.liked_questions_for_user_id(user_id)
results = QuestionsDatabase.instance.execute(<<-SQL, user_id)
SELECT
questions.title, questions.body, questions.author_id, questions.id
FROM
question_likes
INNER JOIN
questions ON question_likes.question_id = questions.id
WHERE
question_likes.user_id = ?
SQL
results.map{ |result| Question.new(result)}
end
def self.most_liked_questions(n)
results = QuestionsDatabase.instance.execute(<<-SQL)
SELECT
questions.title, questions.id, questions.body, questions.author_id
FROM
question_likes
INNER JOIN
questions ON question_likes.question_id = questions.id
GROUP BY
question_id
ORDER BY
COUNT(question_likes.user_id) DESC
LIMIT n
SQL
end
def initialize(options = {})
@question_id = options['question_id']
@user_id = options['user_id']
end
end
|
class ProjectsController < ApplicationController
include CurrentUser
before_action :current_user
before_action :set_project, only: [:show, :edit, :update, :destroy, :success]
before_action :logged_in_user, only: [:edit, :update, :destroy, :index, :show]
# GET /projects
# GET /projects.json
def index
if @current_user.is_admin?
@projects = Project.all
else
@projects = @current_user.projects
end
end
# GET /projects/1
# GET /projects/1.json
def show
end
# GET /projects/new
def new
@project = Project.new
@project.email = @current_user != nil ? @current_user.email : ""
@project.name = @current_user != nil && @current_user.subcontractor != nil ? @current_user.subcontractor.name : ""
@project.location = @current_user != nil && @current_user.subcontractor != nil ? @current_user.subcontractor.location : ""
end
# GET /projects/1/edit
def edit
end
def success
end
# POST /projects
# POST /projects.json
def create
@project = Project.new(project_params)
@project.created_at = DateTime.now
if @current_user == nil
if @project.password == nil || @project.password.empty?
@project.errors.add :password
end
if @project.email == nil || @project.email.empty?
@project.errors.add :email
end
if @project.errors.any?
respond_to do |format|
format.html { render :new }
end
return
end
elsif @current_user != nil
@project.password = "a"
end
user_params = {
email: @project.email,
password: @project.password
}
get_create_current_user(user_params)
if @current_user == nil
@project.errors.add :email
respond_to do |format|
format.html { render :new }
end
return
end
@project.user = @current_user
respond_to do |format|
if @project.save
ProjectMailer.welcome_email(@project).deliver
format.html { redirect_to :controller => :projects, :action => :success, id: @project.id, notice: 'Project was successfully created.' }
format.json { render :show, status: :created, location: @project }
else
format.html { render :new }
format.json { render json: @project.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /projects/1
# PATCH/PUT /projects/1.json
def update
respond_to do |format|
if @project.update(project_params)
format.html { redirect_to @project, notice: 'Project was successfully updated.' }
format.json { render :show, status: :ok, location: @project }
else
format.html { render :edit }
format.json { render json: @project.errors, status: :unprocessable_entity }
end
end
end
# DELETE /projects/1
# DELETE /projects/1.json
def destroy
@project.destroy
respond_to do |format|
format.html { redirect_to projects_url, notice: 'Project was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_project
@project = Project.find(params[:id])
if !@current_user.is_admin? && @project.user != @current_user
redirect_to not_found_path
end
end
# Never trust parameters from the scary internet, only allow the white list through.
def project_params
params.require(:project).permit(:name, :email, :description, :location, :created_at, :password)
end
end
|
require 'test_helper'
class SomethingsControllerTest < ActionDispatch::IntegrationTest
setup do
@something = somethings(:one)
end
test "should get index" do
get somethings_url
assert_response :success
end
test "should get new" do
get new_something_url
assert_response :success
end
test "should create something" do
assert_difference('Something.count') do
post somethings_url, params: { something: { } }
end
assert_redirected_to something_url(Something.last)
end
test "should show something" do
get something_url(@something)
assert_response :success
end
test "should get edit" do
get edit_something_url(@something)
assert_response :success
end
test "should update something" do
patch something_url(@something), params: { something: { } }
assert_redirected_to something_url(@something)
end
test "should destroy something" do
assert_difference('Something.count', -1) do
delete something_url(@something)
end
assert_redirected_to somethings_url
end
end
|
class Route
attr_accessor :first, :last
def initialize(first, last)
@list = []
@list << first.name
@list << last.name
end
def add_station(station)
raise "Неверный тип станции #{station.class}" unless station.is_a?(RailwayStation)
@list.insert(-2, station.name)
end
def remove_station(station)
@list.delete(station.name) if @list.include?(station.name)
end
def show_stations
# puts "Маршрут #{@list.first} -> #{@list.last}"
@list.each_with_index { |station, index| puts "#{index + 1}. #{station}" }
end
def route_list
@list
end
end
|
# frozen_string_literal: true
# link_titling.rb
# Author: William Woodruff
# ------------------------
# A Cinch plugin that autotitles any links sniffed by yossarian-bot.
# ------------------------
# This code is licensed by William Woodruff under the MIT License.
# http://opensource.org/licenses/MIT
require "uri"
require "open-uri"
require "open_uri_redirections"
require "nokogiri"
require "timeout"
require_relative "yossarian_plugin"
class LinkTitling < YossarianPlugin
include Cinch::Plugin
use_blacklist
YOUTUBE_KEY = ENV["YOUTUBE_API_KEY"]
YOUTUBE_URL = "https://www.googleapis.com/youtube/v3/videos?part=snippet,statistics,contentDetails&id=%{id}&key=%{key}"
match /(#{URI.regexp(['http', 'https'])})/, use_prefix: false, method: :link_title
def link_title(m, link)
uri = URI(link)
case uri.host
when /youtube.com/, /youtu.be/
title = youtube_title(uri)
else
title = generic_title(uri)
end
m.reply "Title: #{title}" if title && !title.empty?
end
def generic_title(uri)
Timeout.timeout(5) do
html = Nokogiri::HTML(URI.open(uri, allow_redirections: :safe))
html.css("title").text.normalize_whitespace
end
rescue Exception
"Unknown"
end
def youtube_title(uri)
query = uri.query || ""
id = URI.decode_www_form(query).to_h["v"]
if id.nil?
generic_title(uri)
else
api_url = YOUTUBE_URL % { id: id, key: YOUTUBE_KEY }
begin
hash = JSON.parse(URI.open(api_url).read)["items"].first
hash["snippet"]["title"]
rescue Exception => e
"Unknown"
end
end
end
end
|
require "./lib/dictionary"
class NightReader
attr_reader :file_in,
:file_out,
:incoming_text
def initialize
@file_in = ARGV[0]
@file_out = ARGV[1]
@dictionary = Dictionary.new
end
def orchestrate_english_conversion
read_file
write_file
puts display_message
end
def read_file
handle = File.open(@file_in, "r")
@incoming_text = handle.readlines(chomp: true)
handle.close
@incoming_text
end
def prepare_conversion
text_from_arr = []
text_for_conversoin = []
@incoming_text.map do |line|
element = line.slice!(0..1)
text_from_arr << element
end
text_for_conversoin << text_from_arr
text_for_conversoin
end
def convert
converted_text = []
prepare_conversion.each do |line|
converted_text << @dictionary.english_dictionary[line]
end
converted_text.join
end
def write_file
writer = File.open(@file_out, "w")
writer.write(convert)
writer.write("\n")
writer.close
end
def display_message
"Created #{@file_out} containing #{read_file.join.length} characters."
end
end |
module Api
module V1
class UsersController < ApplicationController
include ApiHelper
after_filter :cors_set_access_control_headers
# before_filter :authenticate_user_from_token!
# before_filter :authenticate_api_v1_user!
def index
#Show all users
@users = User.all
render json: @users.as_json(only: [:id, :first_name, :last_name, :email, :created_at, :sign_in_count, :current_sign_in_at, :last_sign_in_at])
end
def show
#Show single user
@user = User.find(params[:id])
render json: @user.as_json(only: [:id, :first_name, :last_name, :email, :created_at, :sign_in_count, :current_sign_in_at, :last_sign_in_at])
end
def dummy
@user = User.create!(first_name: Faker::Name.first_name,
last_name: Faker::Name.last_name,
email: Faker::Internet.email,
password: Faker::Internet.password(min_length = 8)
)
sign_in @user
render :json=> {:success=>true, :auth_token=>@user.authentication_token, :email=>@user.email}
end
def data_summary
@user = current_api_v1_user
render :json => {:articles=>@user.article_summary, :videos=>@user.video_summary}
end
def update_api_data
@user = current_api_v1_user
if @user.pocket_access_token
update_pocket
end
if @user.google_access_token
update_youtube
end
render :json=>{:success=>true, :message=>"Article and video data updated"}
end
def update
#Update single user
@user = User.find(params[:id])
if @user.update_attributes(user_params)
render json: @user.as_json(only: [:id, :first_name, :last_name, :email, :created_at, :sign_in_count, :current_sign_in_at, :last_sign_in_at, :authentication_token])
sign_in @user
else
render json: @user.errors, status: :unprocessable_entity
end
end
def destroy
@user = User.find(params[:id])
if @user.destroy
render :json=>{:success=>true, :message=>"User deleted"}
end
end
private
def user_params
params.require(:user).permit(:first_name, :last_name, :email, :password)
end
def authenticate_user_from_token!
user_token = request.headers['user-token']
user = user_token && User.find_by_authentication_token(user_token.to_s)
if user
# Notice we are passing store false, so the user is not
# actually stored in the session and a token is needed
# for every request. If you want the token to work as a
# sign in token, you can simply remove store: false.
sign_in user, store: false
end
end
end
end
end |
module OHOLFamilyTrees
module NotableObjects
def self.read_notable_objects(filesystem, path, others = [])
notable = others.clone
filesystem.read(path) do |f|
while line = f.gets
notable << line.to_i
end
end
return notable
end
end
end
|
require 'test_helper'
class RegistrationTest < ActiveSupport::TestCase
test "it is valid when user and account are valid" do
registration = Registration.new(
nickname: 'dave',
email: 'dave@example.com',
password: 'secret',
password_confirmation: 'secret'
)
assert registration.valid?
end
test "it is invalid when user is invalid" do
registration = Registration.new(
nickname: 'dave',
email: 'dave@example.com',
password: 'secret',
)
assert !registration.valid?
assert !registration.user.valid?
end
test "it is invalid when account is invalid" do
registration = Registration.new(
nickname: 'dave',
password: 'secret',
password_confirmation: 'secret'
)
assert !registration.valid?
assert !registration.account.valid?
end
end
|
require 'rails_helper'
describe Purchase, type: :model do
describe 'Validations' do
it 'is invalid without a purchase date' do
purchase = Purchase.new(transaction_date: '12/18/2018',
description: 'zebra pens, bic pens',
amount: 50.1)
expect(purchase).to be_invalid
end
it 'is invalid without a payment date' do
purchase = Purchase.new(transaction_date: '12/16/2017',
description: 'zebra pens, bic pens',
amount: 50.1)
expect(purchase).to be_invalid
end
it 'is invalid without a description' do
purchase = Purchase.new(transaction_date: '12/16/2017',
payment_date: '12/18/2018',
amount: 50.1)
expect(purchase).to be_invalid
end
it 'is invalid without an amount' do
purchase = Purchase.new(transaction_date: '12/16/2017',
payment_date: '12/18/2018',
description: 'zebra pens, bic pens')
expect(purchase).to be_invalid
end
it 'is valid w/ a purchase date, payment date, description, & amount' do
purchase = Purchase.new(transaction_date: '12/16/2017',
payment_date: '12/18/2018',
description: 'zebra pens, bic pens',
amount: 50.1)
expect(purchase).to be_valid
end
end
describe 'Relationships' do
it { should have_many(:vendors) }
it { should have_many(:programs) }
end
describe 'Methods' do
it '.show_vendor' do
vendor = Vendor.new(name: 'Benny Blancos', state: 'CO')
program = Program.new(name: 'Denver Fire Department')
purchase = Purchase.new(transaction_date: '4/16/2017',
payment_date: '4/18/2018',
description: 'Calzones',
amount: 50.1)
ProgramVendorPurchase.create!(program: program, vendor: vendor, purchase: purchase)
expect(purchase.show_vendor).to eq(vendor)
end
it '.show_program' do
vendor = Vendor.new(name: 'Benny Blancos', state: 'CO')
program = Program.new(name: 'Denver Fire Department')
purchase = Purchase.new(transaction_date: '4/16/2017',
payment_date: '4/18/2018',
description: 'Calzones',
amount: 50.1)
ProgramVendorPurchase.create!(program: program, vendor: vendor, purchase: purchase)
expect(purchase.show_program).to eq(program)
end
end
end
|
# Analyze the Errors
# I worked on this challenge [by myself, with: ].
# I spent [#] hours on this challenge.
# --- error -------------------------------------------------------
cartmans_phrase= "Screw you guys " + "I'm going home."
# This error was analyzed in the README file.
# --- error -------------------------------------------------------
def cartman_hates(thing)
while true
puts "What's there to hate about #{thing}?"
end
end
# This is a tricky error. The line number may throw you off.
# 1. What is the name of the file with the error?
# errors.rb
# 2. What is the line number where the error occurs?
# 173, but really line 17
# 3. What is the type of error message?
# syntax error
# 4. What additional information does the interpreter provide about this type of error?
# unexpected end-of-input expecting keyword_end
# 5. Where is the error in the code?
# the end of the method (missing end)
#
#
# 6. Why did the interpreter give you this error?
# two ends were required for this method, one for the method and the other for the while.
# --- error -------------------------------------------------------
#south_park
# 1. What is the line number where the error occurs?
# 38
# 2. What is the type of error message?
#undefined local variable or method
# 3. What additional information does the interpreter provide about this type of error?
# that the error is with 'south_park'
# 4. Where is the error in the code?
# 'main'
# 5. Why did the interpreter give you this error?
# there's no value associated with this string. It should be commented out, or given a value (I'm going to comment it out)
# --- error -------------------------------------------------------
def cartman(this)
while true
puts "What's there to hate about #{thing}?"
end
end
# 1. What is the line number where the error occurs?
# 53
# 2. What is the type of error message?
# undefined method
# 3. What additional information does the interpreter provide about this type of error?
# No method defined
# 4. Where is the error in the code?
# line 53 column 9
# 5. Why did the interpreter give you this error?
# there needs to be a values in the method
# --- error -------------------------------------------------------
def cartmans_phrase(a)
puts "I'm not fat; I'm big-boned!"
end
cartmans_phrase('I hate Kyle')
# 1. What is the line number where the error occurs?
#72
# 2. What is the type of error message?
#wrong number of arguments
# 3. What additional information does the interpreter provide about this type of error?
# (1 for 0)
# 4. Where is the error in the code?
# there needs to be an argument in the parentheses
# 5. Why did the interpreter give you this error?
#
# --- error -------------------------------------------------------
def cartman_says(offensive_message)
puts offensive_message
end
cartman_says ("adsf")
# 1. What is the line number where the error occurs?
# 91
# 2. What is the type of error message?
# wrong number of arguments
# 3. What additional information does the interpreter provide about this type of error?
#0 for 1) (ArgumentError)
# from errors.rb:95:in `<main>'
# 4. Where is the error in the code?
# line 95
# 5. Why did the interpreter give you this error?
# there is no argument where the method is called
# --- error -------------------------------------------------------
def cartmans_lie(lie, name)
puts "#{lie}, #{name}!"
end
cartmans_lie('A meteor the size of the earth is about to hit Wyoming!', "Dick")
# 1. What is the line number where the error occurs?
# 114
# 2. What is the type of error message?
# wrong number of arguments
# 3. What additional information does the interpreter provide about this type of error?
#(1 for 2)
# 4. Where is the error in the code?
# 118
# 5. Why did the interpreter give you this error?
# there needs to be another argument in the defined method
# --- error -------------------------------------------------------
"Respect my authoritay!" * 5
# 1. What is the line number where the error occurs?
# 133
# 2. What is the type of error message?
# String can't be coerced into Fixnum
# 3. What additional information does the interpreter provide about this type of error?
#TypeError
# 4. Where is the error in the code?
# 133:in `*'
# 5. Why did the interpreter give you this error?
# when multiplying strings, the string has to come first (the computer takes it all rather literally)
# --- error -------------------------------------------------------
amount_of_kfc_left = 0/20
# 1. What is the line number where the error occurs?
# 148
# 2. What is the type of error message?
# divide by 0 error
# 3. What additional information does the interpreter provide about this type of error?
# (ZeroDivisionError)
# 4. Where is the error in the code?
#148:in `/'
# 5. Why did the interpreter give you this error?
# you can never divide by 0
# --- error -------------------------------------------------------
require_relative "cartmans_essay.md"
# 1. What is the line number where the error occurs?
# 164
# 2. What is the type of error message?
#LoadError
# 3. What additional information does the interpreter provide about this type of error?
# cannot load such file -- /Users/Reuben/Desktop/DBC/Phase-0/week-4/cartmans_essay.md
# 4. Where is the error in the code?
# `require_relative'
# 5. Why did the interpreter give you this error?
# The interpreter is trying to load a file that I haven't create, thus can't be loaded.
# --- REFLECTION -------------------------------------------------------
# Write your reflection below as a comment.
#Which error was the most difficult to read?
#- I think the first one was the most challenging because the error didn't really point to where the error really was.
#How did you figure out what the issue with the error was?
# I knew and 'end' had to be placed somewhere, based on the error, so once I figured that out, the rest came fairly easily.
#Were you able to determine why each error message happened based on the code?
#yes
#When you encounter errors in your future code, what process will you follow to help you debug?
#I will definitely read the error code and try to determine the cause from that code. If I still can't figure it out, I have a great friend Google, I can ask any time. |
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# name :string(255)
# email :string(255)
# created_at :datetime not null
# updated_at :datetime not null
# encrypted_password :string(255)
# salt :string(255)
# admin :boolean default(FALSE)
# teacher :boolean default(FALSE)
#
class User < ActiveRecord::Base
attr_accessor :password
attr_accessible :email, :name, :password, :password_confirmation, :teacher
has_many :posts, dependent: :destroy
has_many :relationships, dependent: :destroy,
foreign_key: "follower_id"
has_many :reverse_relationships, dependent: :destroy,
foreign_key: "followed_id",
class_name: "Relationship"
has_many :following, through: :relationships,
source: :followed
has_many :followers, through: :reverse_relationships,
source: :follower
has_many :lessons, foreign_key: "student_id",
class_name: "Appointment",
dependent: :destroy
has_many :appointments, foreign_key: "teacher_id",
dependent: :destroy
email_regex = /\A[\w+\-.]+@[a-z0-9]\w*(\.\w+)+\z/i
validates :name, presence: true,
length: { maximum: 100 }
validates :email, presence: true,
format: { with: email_regex },
uniqueness: { case_sensitive: false }
validates :password, presence: true,
confirmation: true,
length: { within: 6..50 }
before_save :encrypt_password
def has_password?(submitted_password)
encrypt(submitted_password) == encrypted_password
end
def feed
Post.from_users_followed_by(self)
end
def following?(other_user)
relationships.find_by_followed_id(other_user)
end
def follow!(other_user)
relationships.create!(followed_id: other_user.id)
end
def unfollow!(other_user)
relationships.find_by_followed_id(other_user).destroy
end
def add_appointment!(time, description)
appointments.create(start_time: time, description: description)
end
def appointments_between(start_date, end_date)
appts = Appointment.where(%((teacher_id = :user_id OR student_id = :user_id) AND (
(repeating AND from_date <= :end_datetime AND to_date >= :start_datetime)
OR
((NOT repeating) AND start_time >= :start_datetime AND start_time < :end_datetime)
)), user_id: self, start_datetime: start_date, end_datetime: end_date)
appts.map { |appt| appt.occurrences }.flatten.
select { |appt| appt.start_time >= start_date && appt.start_time <= end_date.end_of_day }.sort_by(&:start_time)
end
def free_slots()
slots = []
if teacher?
this_monday = Time.current.monday.beginning_of_day
all_appts = appointments_between(this_monday, this_monday+7.days)
all_appts.select {|appt| appt.teaching_slot }.each do |appt|
slots << appt
end
all_appts.select {|appt| !(appt.teaching_slot) }.each do |appt|
slots = filter_out_appt(slots, appt)
end
end
slots
end
class << self
def authenticate(email, submitted_password)
user = find_by_email(email)
(user && user.has_password?(submitted_password)) ? user : nil
end
def authenticate_with_salt(id, cookie_salt)
user = find_by_id(id)
(user && user.salt == cookie_salt) ? user : nil
end
end
private
def encrypt_password
self.salt = generate_salt if new_record?
self.encrypted_password = encrypt(password)
end
def generate_salt
encrypt("#{Time.now.utc}--#{password}")
end
def encrypt(string)
secure_hash("#{salt}--#{string}")
end
def secure_hash(string)
Digest::SHA2.hexdigest(string)
end
def filter_out_appt(slots, appt)
new_slots = []
slots.each do |slot|
if appt.end_time > slot.start_time || appt.start_time < slot.end_time
if appt.start_time > slot.start_time
before_appt = slot.dup
before_appt.duration = appt.start_time - slot.start_time
new_slots << before_appt
end
if appt.end_time < slot.end_time
after_appt = slot.dup
after_appt.start_time = appt.end_time
after_appt.duration = slot.end_time - after_appt.start_time
new_slots << after_appt
end
else
new_slots << slot
end
end
new_slots
end
end
|
class Disc < Product
attr_accessor :year, :genre
def self.from_file(path)
lines = File.readlines(path, chomp: true, encoding: 'UTF-8')
data = {
title: lines[0],
creator: lines[1],
genre: lines[2],
year: lines[3],
price: lines[4],
amount: lines[5]
}
self.new(data)
end
def initialize(data)
super
@genre = data[:genre]
@year = data[:year]
end
def to_s
"Альбом #{@creator} - \"#{@title}\", #{@genre}, #{@year}, " \
"#{price_and_amount_to_s}"
end
end
|
require 'rails_helper'
RSpec.describe PaymentsController, type: :controller do
let (:user) { FactoryGirl.create :user }
let (:payment) { FactoryGirl.create :payment }
context 'for an authenticated user' do
before(:each) { sign_in user }
describe "GET #index" do
it "returns http success" do
get :index
expect(response).to have_http_status(:success)
end
end
describe "GET #show" do
it "returns http success" do
get :show, id: payment
expect(response).to have_http_status(:success)
end
end
end
context 'for an unauthenticated user' do
describe 'GET #index' do
it 'redirects to the sign in page' do
get :index
expect(response).to redirect_to new_user_session_path
end
end
describe 'GET #show' do
it 'redirects to the sign in page' do
get :show, id: payment
expect(response).to redirect_to new_user_session_path
end
end
end
end
|
class CreateLeagueMatchCommEdits < ActiveRecord::Migration[5.0]
def change
create_table :league_match_comm_edits do |t|
t.belongs_to :created_by, null: false, index: true, foreign_key: true
t.integer :comm_id, null: false, index: true
t.text :content, null: false
t.timestamps null: false
end
add_foreign_key :league_match_comm_edits, :league_match_comms, column: :comm_id
reversible do |dir|
dir.up do
League::Match::Comm.find_each do |comm|
comm.edits.create!(created_by: comm.created_by, content: comm.content)
end
end
end
end
end
|
# frozen_string_literal: true
require 'ruby2d'
require 'colorize'
require_relative 'components/utilities'
require_relative 'truncator/truncator'
# Main Countdown game.
#
# @author Zach Baruch
module Countdown
MAX_CONSONANTS = 6
MAX_VOWELS = 5
# The "gameplay" part of the game. The Countdown Clock music will be played
# while the user is guessing words. After the song ends (~30 seconds), the
# user's latest guess will be submitted.
def self.countdown_clock
guess = String.new
t_input = Thread.new { initialize_input_thread guess }
t_song = Thread.new { initialize_song_thread t_input }
t_song.join # Join threads for execution
t_input.join
guess # Return the most recent guess
end
# Prompts the user to select consonants or vowels nine times, and returns the
# +TileSet+ containing the nine letters pulled from the respective `LetterStack`s.
#
# @return [TileSet] the letters selected by the user, as pulled by the letter stacks
def self.letters_in_play
# LetterStacks for consonants and vowels
consonants = Letters::LetterStack.new :consonants
vowels = Letters::LetterStack.new :vowels
# The letters to be selected
letters = Letters::TileSet.new
9.times do
choice = letter_choice(consonants.num_drawn, vowels.num_drawn) # Get choice of consonant or vowel
# Add selected type of letter to selected_letters
letters << (choice == 'C' ? consonants.draw : vowels.draw)
display_tile_set letters
end
letters
end
# Checks if +guess+ can be formed from +letters+ and is in +valid_words+,
# and displays the result to the user.
#
# @param valid_words [Array<String>] the list of valid words that +guess+ can be
# @param letters [TileSet] the set of letters that +guess+ must belong to
# @param guess [String] the user's guess to check
def self.judge(valid_words, letters, guess)
if !letters.include? guess
puts "Sorry, #{guess} uses letters not on the board.".red
elsif !valid_words.include? guess
puts "Sorry, #{guess} is not a valid word.".red
else
puts "Yes! #{guess} is a valid word!".green
puts "You earned #{(guess.length if guess.length < 9) || 18} points!".green
end
puts
end
# Prompts the user if they want to see all possible solutions for +letters+
# (i.e. each combination of +letters+ that is included in +valid_words+),
# and if so, displays them to the console.
#
# @param valid_words [Array<String>] the list of valid words that +letters+ can be
# @param letters [TileSet] the set of letters to possibly search for solutions for
def self.prompt_for_solutions(valid_words, letters)
# Prompt user for choice, if it is not 'Y' return
return unless prompt_user('Do you want to see all possible solutions? [Y/N] ', 'Y', 'N').upcase == 'Y'
# Display all possible solutions
puts(valid_words.select { |w| letters.include? w }.sort { |a, b| b.length <=> a.length })
end
# Plays a round of Countdown.
#
# @param valid_words [Array<String>] list of valid words to be used in the game
def self.play_round(valid_words)
letters = letters_in_play # Obtain letter set
display_instructions
guess = countdown_clock # Run the clock!
puts "\n\nYour guess is: #{guess}"
judge valid_words, letters, guess # Check the user's guess
prompt_for_solutions valid_words, letters # Ask the user if they want to see all solutions
end
# Main method.
display_title # Title screen
valid_words = word_list
# Prompt user to play again after each round
loop do
play_round valid_words
break if prompt_user('Do you want to play another round? [Y/N] ', 'Y', 'N').upcase == 'N'
end
puts 'Thanks for playing!'
end
|
require 'rules/base'
require 'util/time_adjuster'
module Rules
class IsOutsideRegularSchedule < Base
DEFAULTS = { minimum_daily_hours: 0.0,
maximum_daily_hours: 0.0,
minimum_weekly_hours: 0.0,
maximum_weekly_hours: 0.0,
overtime_days: ["saturday", "sunday"],
saturdays_overtime: true,
sundays_overtime: true,
holidays_overtime: true,
decimal_place: 2,
billable_hour: 0.25,
closest_minute: 8.0,
scheduled_shift: nil
}
attr_reader :criteria, :activity, :processed_activity, :base
def initialize(base, activity=nil, criteria=nil)
if base
@activity = base.activity
@criteria = base.criteria
@processed_activity = base.processed_activity
@partial_overtime_time_field = nil
@base = base
else
super(activity, criteria)
end
new_dates = Util::TimeAdjuster.new(@activity.from, @activity.to).process_dates
@from = new_dates.from
@to = new_dates.to
assign_partial_field
end
def check
!@partial_overtime_time_field.nil?
end
def calculate_seconds
@from = @activity.from
@to = @activity.to
assign_partial_field
started_at = scheduled_shift.started_at
ended_at = scheduled_shift.ended_at
hours = OpenStruct.new({regular: 0.0, overtime: 0.0})
if @partial_overtime_time_field == "both_started_at"
hours[:overtime] = @activity.total_hours
elsif @partial_overtime_time_field == "from_started_at"
hours[:regular] = ((@to.to_i - started_at.to_i) / 3600.0).round(decimal_place)
hours[:overtime] = ((started_at.to_i - @from.to_i) / 3600.0).round(decimal_place)
elsif @partial_overtime_time_field == "both_ended_at"
hours[:overtime] = @activity.total_hours
elsif @partial_overtime_time_field == "to_ended_at"
hours[:regular] = ((ended_at.to_i - @from.to_i) / 3600.0).round(decimal_place)
hours[:overtime] = ((@to.to_i - ended_at.to_i) / 3600.0).round(decimal_place)
end
hours
end
def calculate_hours
started_at = scheduled_shift.started_at
ended_at = scheduled_shift.ended_at
hours = OpenStruct.new({regular: 0.0, overtime: 0.0})
if @partial_overtime_time_field == "both_started_at"
hours[:overtime] = @activity.total_hours
elsif @partial_overtime_time_field == "from_started_at"
hours[:regular] = ((@to.to_i - started_at.to_i) / 3600.0).round(decimal_place)
hours[:overtime] = ((started_at.to_i - @from.to_i) / 3600.0).round(decimal_place)
elsif @partial_overtime_time_field == "both_ended_at"
hours[:overtime] = @activity.total_hours
elsif @partial_overtime_time_field == "to_ended_at"
hours[:regular] = ((ended_at.to_i - @from.to_i) / 3600.0).round(decimal_place)
hours[:overtime] = ((@to.to_i - ended_at.to_i) / 3600.0).round(decimal_place)
end
hours
end
def process_activity
if check && @processed_activity[:overtime] == 0.0
hours = calculate_hours
@processed_activity[:regular] = hours.regular
@processed_activity[:overtime] = hours.overtime
seconds = calculate_seconds
@processed_activity[:raw_regular] = seconds.regular * 3600.0
@processed_activity[:raw_overtime] = seconds.overtime * 3600.0
end
@processed_activity
end
private
def assign_partial_field
started_at = scheduled_shift.started_at
ended_at = scheduled_shift.ended_at
if @to < started_at
@partial_overtime_time_field = "both_started_at"
elsif @from < started_at
@partial_overtime_time_field = "from_started_at"
elsif @from > ended_at
@partial_overtime_time_field = "both_ended_at"
elsif @to > ended_at
@partial_overtime_time_field = "to_ended_at"
end
end
end
end |
FactoryGirl.define do
factory :user, class: User do
sequence(:email){ |n| "user-#{n}@iuvare.mx" }
first_name 'Test'
last_name 'User'
password '12345678'
roles {[FactoryGirl.create(:role)]}
trait :inactive do
active false
end
end
factory :premier, class: Premier do
sequence(:email){ |n| "premier-#{n}@iuvare.mx" }
first_name 'Premier'
last_name 'User'
password '12345678'
roles {[FactoryGirl.create(:role_premier)]}
end
end
|
module API
class EndpointController < ApplicationController
def self.errors_to_rescue
[
AirMonitor::UnauthorizedAccessError,
ActiveRecord::RecordNotFound,
ActionController::RoutingError,
ActionController::ParameterMissing
]
end
rescue_from(*errors_to_rescue, with: :render_error)
def render_error(error)
render json: error,
adapter: :json,
root: 'error',
serializer: ErrorSerializer,
status: AirMonitor::Error.http_status_for(error)
end
def endpoint_not_found
raise ActionController::RoutingError, 'Endpoint not found'
end
end
end
|
class EndDateAfterStartDateValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
return unless value
unless end_date_after_start_date(record.planned_start_date, record.planned_end_date)
record.errors.add :planned_end_date, :not_before_start_date
end
end
private def end_date_after_start_date(start_date, end_date)
end_date >= start_date
end
end
|
require 'test_helper'
class UserTest < ActiveSupport::TestCase
def setup
@user = User.new(name: "Example User", email: "user@example.com",
password: "foobar", password_confirmation: "foobar")
@user.save
@found_user = User.find_by(email: @user.email)
@user_for_invalid_password = @found_user.authenticate("invalid")
end
def teardown
@user.destroy!
end
test "it has an auto-generated remember token" do
@user.remember_token.wont_equal(nil)
end
test "it authenticates with a correct password" do
@user.must_equal(@found_user.authenticate(@user.password))
end
test "does not authenticate with an incorrect password" do
@user.wont_equal(@user_for_invalid_password)
end
end
|
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
helper_method :current_user
before_action :require_login, except: [:new,:create]
def current_user
@current_user ||= User.find_by_id(session[:user_id])
end
def require_login
if session.has_key?(:user_id)
else
redirect_to new_session_path
end
end
end
|
module Users
class OwnersController < ApplicationController
def create
result = create_owner_and_room
if result.success?
redirect_to room_path(
room_secret_id: result.room.secret_id,
user_secret_id: result.owner.secret_id
)
else
flash[:error] = 'Invalid params!'
redirect_to root_path
end
end
private
def create_owner_and_room
CreateOwnerAndRoom.call(
user_params: { login: params[:user_login] },
room_name: params[:room_name]
)
end
end
end
|
Vagrant.configure(2) do |config|
config.vm.box = "ubuntu/trusty64"
config.vm.define "mongod" do |mongod|
mongod.vm.provider "virtualbox" do |v|
v.customize ["modifyvm", :id, "--cpus", "2", "--memory", "3072"]
end
mongod.vm.network :private_network, ip: "192.168.19.100"
mongod.vm.hostname = "mongodb.vagrant.dev"
mongod.vm.provision :shell, path: "provision-mongod", args: ENV['ARGS']
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.