text stringlengths 10 2.61M |
|---|
# encoding: UTF-8
module Purgeable
version = nil
version_file = ::File.expand_path('../../../GEM_VERSION', __FILE__)
version = File.read(version_file) if version.nil? && ::File.exists?(version_file)
version = $1 if version.nil? && ::File.expand_path('../..', __FILE__) =~ /\/purgeable-(\d+(?:\.\d+)+)/
if version.nil? && ::File.exists?(::File.expand_path('../../../.git', __FILE__))
begin
require 'step-up'
version = ::StepUp::Driver::Git.new.last_version_tag("HEAD", true)
rescue
version = "v0.0.0"
end
::File.open(version_file, "w"){ |f| f.write version }
end
VERSION = version.gsub(/^v?([^\+]+)\+?\d*$/, '\1')
end
|
LABELS = INPUT.chars.map(&:to_i).freeze
class Cup
attr_reader :label
attr_accessor :next
def initialize(label)
@label = label
@next = self
end
def insert!(cup)
cup.next = @next
@next = cup
end
end
def move!(cups, current)
taken = [current.next, current.next.next, current.next.next.next]
current.next = taken[-1].next
target = current.label
loop do
target = (target == 1) ? cups.count : target - 1
break if taken.none? { |cup| cup.label == target }
end
taken[-1].next = cups[target].next
cups[target].next = taken[0]
end
def play(labels, moves)
current = nil
cups = labels.each_with_object({}) do |label, cups|
cups[label] = Cup.new(label)
current&.insert!(cups[label])
current = cups[label]
end
moves.times { move!(cups, current = current.next) }
cups
end
result = play(LABELS, 100)
current = result[1]
labels = (result.count - 1).times.map { (current = current.next).label }
solve!("The labels clockwise from 1 after 100 rounds are:", labels.join)
new_labels = LABELS + ((LABELS.count + 1)..1_000_000).to_a
result = play(new_labels, 10_000_000)
product = result[1].next.label * result[1].next.next.label
solve!("The product of the two labels clockwise from 1 is:", product)
|
# -*- coding: utf-8 -*-
module Procedural
module Adapters
module PostgreSQLAdapter
def create_procedure(*args)
options = args.extract_options!
procedure_name = args.shift
language = options.fetch(:language)
returns = options.fetch(:returns)
sql = options.fetch(:sql) { yield }
execute(<<-SQL)
CREATE OR REPLACE FUNCTION #{quote_column_name(procedure_name)}()
RETURNS #{returns}
LANGUAGE #{language}
AS $$
BEGIN
#{sql}
END
$$
SQL
end
def drop_procedure(*args)
procedure_name = args.shift
execute("DROP FUNCTION IF EXISTS #{quote_column_name(procedure_name)}()")
end
def create_trigger(*args)
options = args.extract_options!
table_name = args.shift
trigger_name = args.shift
procedure_name = args.shift
execute("CREATE TRIGGER #{quote_column_name(trigger_name)} BEFORE INSERT OR UPDATE ON #{quote_table_name(table_name)} FOR EACH ROW EXECUTE PROCEDURE #{quote_column_name(procedure_name)}()")
end
def drop_trigger(*args)
table_name = args.shift
trigger_name = args.shift
execute("DROP TRIGGER IF EXISTS #{quote_column_name(trigger_name)} ON #{quote_table_name(table_name)}")
end
end
end
end
|
module ListConcern
extend ActiveSupport::Concern
included do
has_many :lists, foreign_key: :superinformation_id, dependent: :destroy
has_many :list_items, through: :lists, dependent: :destroy
end
end
|
# frozen_string_literal: true
RSpec.describe 'Coaches' do
resource 'Admin coaches' do
let!(:coach1) { create(:coach, :featured) }
let!(:coach2) { create(:coach, :featured) }
let!(:coach3) { create(:coach) }
let!(:coach4) { create(:coach, :deleted) } # NOTE: Deleted records are not returned by default
let!(:video1) { create(:video, :with_category) }
let!(:coaches_video) { create(:coaches_video, video: video1, coach: coach1) }
route '/api/v1/admin/coaches', 'Admin Coaches endpoint' do
get 'All coaches' do
parameter :page
parameter :sort
parameter :filter
parameter :include, example: 'categories'
with_options scope: :page do
parameter :number, required: true
parameter :size, required: true
end
with_options scope: :filter do
parameter :fullname
parameter :featured
end
context 'not authenticated' do
example 'Responds with 401' do
do_request
expect(status).to eq(401)
end
end
context 'authenticated user', :authenticated_user do
example 'Responds with 403' do
do_request
expect(status).to eq(403)
end
end
context 'authenticated admin', :authenticated_admin do
example 'Responds with 200' do
do_request
expect(response_body).to match_response_schema('v1/coaches/index')
expect(parsed_body[:data].count).to eq 3
end
end
context 'with categories include', :authenticated_admin do
let(:include) { 'categories' }
example 'Responds with 200' do
do_request
expect(response_body).to match_response_schema('v1/videos/index')
expect(parsed_body[:data].count).to eq 3
expect(parsed_body[:included].count).to eq 1
expect(parsed_body[:included][0][:attributes][:name]).to eq video1.category.name
end
end
context 'paginated', :authenticated_admin do
let(:number) { 2 }
let(:size) { 1 }
example 'Responds with 200' do
do_request
expect(response_body).to match_response_schema('v1/coaches/index')
expect(parsed_body[:data].count).to eq 1
expect(parsed_body[:meta]).to be_paginated_resource_meta
expect(parsed_body[:meta]).to eq(
current_page: 2,
next_page: 3,
prev_page: 1,
page_count: 3,
record_count: 3
)
end
end
context 'sorted', :authenticated_admin do
let(:sort) { '-created_at' }
example 'Responds with 200' do
do_request
expect(response_body).to match_response_schema('v1/coaches/index')
expect(parsed_body[:data].count).to eq 3
end
end
context 'filtered by fullname', :authenticated_admin do
let(:fullname) { coach1.fullname }
example 'Responds with 200' do
do_request
expect(response_body).to match_response_schema('v1/coaches/index')
expect(parsed_body[:data].count).to eq 1
end
end
context 'filtered by featured', :authenticated_admin do
let(:featured) { {eq: true} }
example 'Responds with 200' do
do_request
expect(response_body).to match_response_schema('v1/coaches/index')
expect(parsed_body[:data].count).to eq 2
end
end
end
post 'Create coach' do
parameter :type, scope: :data, required: true
with_options scope: %i[data attributes] do
parameter :fullname, required: true
end
let(:type) { 'coaches' }
let(:fullname) { FFaker::Name.name }
context 'not authenticated' do
example 'Responds with 401' do
do_request
expect(status).to eq(401)
end
end
context 'authenticated user', :authenticated_user do
example 'Responds with 403' do
do_request
expect(status).to eq(403)
end
end
context 'authenticated admin', :authenticated_admin do
example 'Responds with 200' do
do_request
expect(response_body).to match_response_schema('v1/coaches/index')
expect(parsed_body[:data][:attributes][:fullname]).to eq fullname
end
end
context 'when params are invalid', :authenticated_admin do
let(:fullname) { nil }
example 'Responds with 422' do
do_request
expect(status).to eq(422)
expect(response_body).to match_response_schema('v1/error')
end
end
end
delete 'Destroy coach' do
parameter :data, type: :array, items: {type: :object}, required: true
let!(:coach1) { create(:coach) }
let!(:coach2) { create(:coach) }
let(:data) do
[
{type: 'coaches', id: coach1.id},
{type: 'coaches', id: coach2.id}
]
end
context 'not authenticated' do
example 'Responds with 401' do
do_request
expect(status).to eq(401)
end
end
context 'not admin', :authenticated_user do
example 'Responds with 403' do
do_request
expect(status).to eq(403)
end
end
context 'is admin', :authenticated_admin do
example 'Responds with 204' do
do_request
expect(status).to eq(204)
end
end
end
end
route '/api/v1/admin/coaches/:id', 'Admin Coach endpoint' do
get 'Single coach' do
let!(:coach) { create(:coach) }
let(:id) { coach.id }
context 'not authenticated' do
example 'Responds with 401' do
do_request
expect(status).to eq(401)
end
end
context 'authenticated user', :authenticated_user do
example 'Responds with 403' do
do_request
expect(status).to eq(403)
end
end
context 'coach was not found', :authenticated_admin do
let(:id) { 0 }
example 'Responds with 404' do
do_request
expect(status).to eq(404)
expect(response_body).to be_empty
end
end
context 'authenticated admin', :authenticated_admin do
example 'Responds with 200' do
do_request
expect(status).to eq(200)
expect(response_body).to match_response_schema('v1/coach')
end
end
end
put 'Update coach' do
parameter :type, scope: :data, required: true
with_options scope: %i[data attributes] do
parameter :fullname
parameter :featured
parameter :social_links
end
with_options scope: %i[data relationships videos] do
parameter :data, type: :array, items: {type: :object}, method: :videos_data, required: true
end
let(:type) { 'coaches' }
let!(:coach) { create(:coach) }
let(:id) { coach.id }
let(:fullname) { FFaker::Name.name }
let(:featured) { true }
context 'not authenticated' do
example 'Responds with 401' do
do_request
expect(status).to eq(401)
end
end
context 'not admin', :authenticated_user do
example 'Responds with 403' do
do_request
expect(status).to eq(403)
end
end
context 'params are invalid', :authenticated_admin do
let(:fullname) { nil }
example 'Responds with 422' do
do_request
expect(status).to eq(422)
expect(response_body).to match_response_schema('v1/error')
end
end
context 'params are valid', :authenticated_admin do
example 'Responds with 200' do
do_request
expect(status).to eq(200)
expect(response_body).to match_response_schema('v1/coach')
end
end
context 'coach can have social links', :authenticated_admin do
context 'passing all links at once' do
let(:social_links) { FFaker::Social.all }
example 'Responds with 200' do
do_request
expect(status).to eq(200)
expect(response_body).to match_response_schema('v1/coach')
expect(attribute(:socialLinks)).to eq(social_links)
end
end
context 'one link is overided' do
let(:original_facebook_link) { coach.social_links['facebook'] }
let(:social_links) do
{
website: FFaker::Social.website
}
end
example 'Responds with 200' do
do_request
expect(status).to eq(200)
expect(response_body).to match_response_schema('v1/coach')
expect(attribute(:socialLinks)[:website]).to eq(social_links[:website])
expect(attribute(:socialLinks)[:facebook]).to eq(original_facebook_link)
end
end
end
context 'coach can have multiple video', :authenticated_admin do
let!(:video1) { create(:video) }
let!(:video2) { create(:video) }
let(:videos_data) do
[
{type: 'videos', id: video1.id},
{type: 'videos', id: video2.id}
]
end
example 'Responds with 200' do
do_request
expect(status).to eq(200)
expect(response_body).to match_response_schema('v1/coach')
expect(video1.coach_pks).to eq [coach1.id, coach.id]
expect(video2.coach_pks).to eq [coach.id]
expect(coach.video_pks).to eq [video1.id, video2.id]
end
end
end
delete 'Destroy coach' do
let!(:coach) { create(:coach) }
let(:id) { coach.id }
context 'not authenticated' do
example 'Responds with 401' do
do_request
expect(status).to eq(401)
end
end
context 'not admin', :authenticated_user do
example 'Responds with 403' do
do_request
expect(status).to eq(403)
end
end
context 'is admin', :authenticated_admin do
example 'Responds with 204' do
do_request
expect(status).to eq(204)
end
end
end
end
end
end
|
require File.dirname(__FILE__) + '/spec_helper'
describe Smsinabox::Reply do
before(:each) do
xml = <<-EOF
<api_result>
<data>
<replyid>3903103</replyid>
<eventid>33368123</eventid>
<numfrom>27123456789</numfrom>
<receiveddata>Bar</receiveddata>
<sentid>339548269</sentid>
<sentdata>Foo</sentdata>
<sentcustomerid/>
<received>10/Aug/2009 00:09:46</received>
<sentdatetime>07/Aug/2009 13:51:48</sentdatetime>
</data>
</api_result>
EOF
@xml_reply = Nokogiri::XML( xml )
end
it "should parse from response data" do
reply = Smsinabox::Reply.from_response( @xml_reply.xpath('/api_result/data').first )
reply.id.should == 3903103
reply.event_id.should == 33368123
reply.from.should == '27123456789'
reply.message.should == 'Bar'
reply.sent_id.should == 339548269
reply.original.should == 'Foo'
reply.sent_customer_id.should == ''
reply.received.should == '10/Aug/2009 00:09:46'
reply.sent.should == '07/Aug/2009 13:51:48'
end
end
|
require 'rails_helper'
RSpec.describe UserSearchService do
describe '#find' do
before :each do
create :user, email: 'michael@email.com', full_name: 'Michael Scott', metadata: 'best, boss'
create :user, email: 'dwight@email.com', full_name: 'Dwight Shrute', metadata: 'beets, bears'
end
context 'search with query' do
it 'returns users where metadata contains query' do
users = UserSearchService.find 'beets'
expect(users.count).to eq 1
expect(users.first.metadata).to eq 'beets, bears'
end
it 'returns users where email contains query' do
users = UserSearchService.find 'dwight'
expect(users.count).to eq 1
expect(users.first.email).to eq 'dwight@email.com'
end
it 'returns users where full name contains query' do
users = UserSearchService.find 'Dwight'
expect(users.count).to eq 1
expect(users.first.full_name).to eq 'Dwight Shrute'
end
it 'returns empty array when no fields contain query' do
users = UserSearchService.find 'scranton'
expect(users).to eq []
end
end
context 'search without query' do
it 'returns all users' do
users = UserSearchService.find
expect(users.count).to eq 2
end
end
end
end |
#!/usr/bin/env ruby
# encoding: utf-8
# from http://rdoc.info/github/ruby-amqp/amqp/master/file/docs/GettingStarted.textile
require "bundler"
Bundler.setup
require "amqp"
AMQP.start do |connection|
channel = AMQP::Channel.new(connection)
exchange = channel.fanout("nba.scores")
channel.queue("joe").bind(exchange).subscribe do |payload|
puts "#{payload} => joe"
end
channel.queue("aaron").bind(exchange).subscribe do |payload|
puts "#{payload} => aaron"
end
channel.queue("bob").bind(exchange).subscribe do |payload|
puts "#{payload} => bob"
end
1.times do
exchange.publish("BOS 101, NYK 89").publish("ORL 85, ALT 88")
end
# disconnect & exit after 2 seconds
EventMachine.add_timer(2) do
exchange.delete
connection.close { EventMachine.stop }
end
end
|
module Campfire
class Manager
attr_reader :connection
def initialize(options)
@connection = Connection.new(options)
end
def rooms
find_rooms 'rooms'
end
def presence
find_rooms 'presence'
end
# TODO: validate blank search
def search(term)
@connection.get("/search/#{term}.json")["messages"].map do |message|
room = Room.new(self, "id" => message["room_id"])
Message.new(room, message)
end
end
def room(room_id)
Room.new(self, "id" => room_id)
end
def me
user = @connection.get("/users/me.json")
User.new(self, user["user"])
end
private
def find_rooms(path)
@connection.get("/#{path}.json")["rooms"].map do |room|
Room.new(self, room)
end
end
end
end
|
# nth_prime.rb
require 'prime'
class Prime
@@primes = [2, 3, 5, 7]
def self.is_prime(num)
return false if num == 1
return false if num.even? && num > 2
return false if (num % 3).zero?
return false if (num % 5).zero?
[*(7..(Math.sqrt(num).to_i))].each do |factor|
return false if (num % factor).zero?
end
num
end
def self.nth(num)
raise ArgumentError unless num.positive?
number = @@primes.last
while @@primes.size < num
@@primes << number + 1 if is_prime(number + 1)
number += 1
end
@@primes[num - 1]
end
end
module BookKeeping
VERSION = 1
end
|
FactoryBot.define do
factory :tweet do
text { Faker::Lorem.word }
user_id nil
end
end |
class Dealer
attr_accessor :cards, :scores, :bank
TOTAL_SCORE = 21
MAX_CARDS = 3
ACE = 1
def initialize
@bank = 100
@cards = []
end
def minus_cash(sum)
@bank -= sum
end
def sum_cards
sum = @cards.sum(&:value)
ace_correction(sum)
end
def ace_correction(sum)
@cards.each do |card|
sum -= ACE if sum > TOTAL_SCORE && card.ace?
end
sum
end
def take_card?
@cards.size < MAX_CARDS && sum_cards < 17
end
def full_hand?
@cards.size == MAX_CARDS
end
def add_cards(card)
@cards << card
end
end |
class AddLastLogoutUser < ActiveRecord::Migration
def change
add_column :users, :last_logout, :datetime
end
end
|
class Habit < ApplicationRecord
validates :name, presence: true
has_many :states
belongs_to :user
end
|
class AddFeeToEvents < ActiveRecord::Migration[5.1]
def change
add_column :tournaments, :fee, :decimal
add_column :tournaments, :url, :string
end
end
|
class CreateLicences < ActiveRecord::Migration
def change
create_table :licences do |t|
t.string :number, null: false, limit: 16
t.date :reg_date, null: false
t.string :type, null: false, limit: 32
t.text :name, null: false
t.date :expiration_date
t.string :req_number
t.text :req_author
t.text :req_object
t.string :req_status
t.string :reg_agency
t.date :req_priority
t.string :support
t.references :research_effort, index: true
t.string :creator_login
t.text :creator_data
t.timestamps
end
reversible do |dir|
dir.up do
'ALTER TABLE licences ADD FOREIGN KEY (research_effort_id) REFERENCES research_efforts(id)'
execute <<-SQL1
ALTER TABLE licences
ADD CONSTRAINT number_limit
CHECK (LENGTH(number) > 0 AND LENGTH(number) < 16);
SQL1
execute <<-SQL
ALTER TABLE licences
ADD CONSTRAINT type_limit
CHECK (LENGTH(type) > 0 AND LENGTH(type) < 32);
SQL
end
dir.down do
end
end
end
end
|
FactoryBot.define do
factory :order do
customer_id { 1 }
postage { 800 }
total_price { ((Item.find(1).price * 1.1).floor * CartItem.find(1).quantity) + 800 }
delivery_name { Gimei.kanji }
delivery_address { Gimei.address.kanji }
delivery_postcode { Faker::Address.postcode }
end
end
|
class Day03Solver < SolverBase
def call
color_plane(plane, claims)
plane
end
def claims
@claims ||= parse_to_claims @input
end
def plane
@plane ||= make_plane claims
end
def self.display_plane(plane)
plane.each do |row|
puts row.join('|')
end
end
def self.overlapping_count(plane)
plane.flatten.reduce(0) do |c, cell|
c + (cell > 1 ? 1 : 0)
end
end
def overlapped?(claim)
x, y, x_length, y_length = claim.x, claim.y, claim.x_length, claim.y_length
(0...x_length).each do |x_move|
(0...y_length).each do |y_move|
return true if plane[x + x_move][y + y_move] > 1
end
end
false
end
def self.data
DATA.each_line.map(&:strip).reject(&:empty?)
end
private
def parse_to_claims(lines)
lines.map do |line|
captures = /#(\d+) @ (\d+),(\d+): (\d+)x(\d+)/.match(line)
OpenStruct.new(
id: captures[1].to_i,
x: captures[2].to_i,
y: captures[3].to_i,
x_length: captures[4].to_i,
y_length: captures[5].to_i
)
end
end
def make_plane(claims)
max_x = claims.map { |f| f.x + f.x_length }.max + 1
max_y = claims.map { |f| f.y + f.y_length }.max + 1
Array.new(max_x) { Array.new(max_y, 0) }
end
def color_plane(plane, claims)
claims.each do |claim|
x, y, x_length, y_length = claim.x, claim.y, claim.x_length, claim.y_length
(0...x_length).each do |x_move|
(0...y_length).each do |y_move|
plane[x + x_move][y + y_move] += 1
end
end
end
end
end
|
# frozen_string_literal: true
module Blog
module Commands
class BecomeAwesomeSubscriber
attr_reader :logger, :service
def initialize(logger:, service:)
@logger = logger
@service = service
end
def call(email)
logger.call('starting subscription...')
service.call(email)
logger.call('subscribed to newsletter!')
end
end
end
end
|
require 'rails_helper'
RSpec.describe Services::CreateServiceTransaction do
let(:transaction_call) { transaction.call(vin) }
let(:transaction) do
described_class
.new
.with_step_args(
create_service: [
service: service
]
)
end
let(:service) { { start_date: Time.current } }
context 'when everything goes well' do
let(:car) { Factory[:car] }
let(:vin) { car.vin }
let(:services_relation) { ROM.env.relations[:services] }
it 'creates service' do
expect { transaction_call }.to change(services_relation, :count).by(1)
end
it 'returns success' do
expect(transaction_call.success?).to eq(true)
end
end
context 'when car is not found' do
let(:vin) { Faker::Lorem.word }
it 'fails on find_car step and raises ROM::TupleCountMismatchError' do
expect(transaction).to fail_on(:find_car).with(vin).and_raise(ROM::TupleCountMismatchError)
end
end
end
|
class CreateParticularDiscounts < ActiveRecord::Migration
def self.up
create_table :particular_discounts do |t|
t.decimal :discount, :precision =>15, :scale => 2
t.references :particular_payment
t.string :name
t.timestamps
end
end
def self.down
drop_table :particular_discounts
end
end
|
require_relative 'spec_helper'
describe "Block class" do
before do
@block = Hotel::Block.new(id: 1, dates: ["12 May", "13 May", "14 May"], open_rooms: [1, 2, 3], booked_rooms: [])
describe "initializer" do
it "is an instance of block" do
@block.must_be_kind_of Hotel::Block
end
it "is set up for specific attributes and data types" do
[:id, :dates, :open_rooms, :booked_rooms].each do |prop|
@block.must_respond_to prop
end
@block.id.must_be_kind_of Integer
@block.dates.must_be_kind_of Array
@block.dates.first.must_be_kind_of String
@block.open_rooms.must_be_kind_of Array
@block.open_rooms.first.must_be_kind_of Integer
@block.booked_rooms.must_be_kind_of Array
end
end
describe "book_room method" do
initial_open_rooms = @block.open_rooms
@block.book_room
@block.open_rooms.must_equal initial_open_rooms.first(2)
@block.booked_rooms.must_equal initial_open_rooms.last
end
end
end
|
class Game < ApplicationRecord
belongs_to :user
def user_attributes=(user_name)
self.user = User.find_or_create_by(name: user_name)
end
end
|
class FillInIssueTypes < ActiveRecord::Migration[5.0]
def change
issue_types = [
{name: "New Feature", icon_path: "new_feature.svg", display_order: 0},
{name: "Bug", icon_path: "bug.svg", display_order: 1},
{name: "Task", icon_path: "task.svg", display_order: 2},
{name: "Improvement", icon_path: "improvement.svg", display_order: 3},
{name: "Epic", icon_path: "epic.svg", display_order: 4},
{name: "Story", icon_path: "story.svg", display_order: 5},
{name: "IT Help", icon_path: "it_help.svg", display_order: 6},
{name: "Purchase", icon_path: "purchase.svg", display_order: 7},
{name: "Story", icon_path: "story.svg", display_order: 8},
{name: "Access", icon_path: "access.svg", display_order: 9}
]
issue_types.each { |type| IssueType.create(name: type[:name], icon_path: type[:icon_path], display_order: type[:display_order]) }
end
end
|
class Person
attr_accessor :name
attr_accessor :cash
def initialize(person_name, cash_on_hand)
@name = person_name
@cash = cash_on_hand
puts "Hi, #{name}. You have $#{@cash}!"
end
end
class Bank
attr_accessor :bank
attr_accessor :accounts
attr_accessor :amount
attr_accessor :withdraw
attr_accessor :cc_accounts
attr_accessor :cc_outstanding
def initialize(bank_name)
@bank = bank_name
puts "#{@bank} bank was just created."
@accounts = {} # person.name=>$
@cc_accounts = {} # person.name=>credit limit
@cc_outstanding = {} # person.name=>cc_charges, net cc_payments
end
def open_account(person)
puts "#{person.name}, thanks for opening an account at #{@bank}!"
@accounts[person.name] = 0 # push person into accounts hash; beginning value = 0
end
def deposit(person, amount)
if person.cash >= amount # max deposit is the amount of cash someone has on hand
person.cash -= amount # cash on hand is reduced about amount deposited into bank
@accounts[person.name] += amount # push deposit into person's account
puts "#{person.name} deposited $#{amount} to #{@bank}. #{person.name} has $#{person.cash}. #{person.name}'s account has $#{@accounts[person.name]}."
# elsif person.cash == 0 # evaluates NO Cash (vs. Insufficient Cash... see else)
# puts "#{person.name} has no cash on hand and cannot deposit any money."
else
puts "#{person.name} does not have enough cash to deposit $#{amount}."
# cash_on_hand = person.cash
# @accounts[person.name] += person.cash # deposit person.cash only
# person.cash = 0
# puts "#{person.name} deposited remaining $#{cash_on_hand} to #{@bank}. #{person.name} has $#{person.cash}. #{person.name}'s #{@bank} account has $#{@accounts[person.name]}."
end
end
def withdraw(person, amount)
if @accounts[person.name] >= amount
@accounts[person.name] -= amount # reduce money from bank account
person.cash += amount # increase money_on_hand by withdraw amount
puts "#{person.name} withdrew $#{amount} from #{@bank}. #{person.name} has $#{person.cash}. #{person.name}'s account has $#{@accounts[person.name]}."
else
puts "#{person.name} does not have enough money in the account to withdraw $#{amount}."
end
end
def transfer(person, to_bank, amount)
@accounts[person.name] -= amount # reduce transfer amount from from_bank
to_bank.accounts[person.name] += amount # increase transfer amount to to_bank
# person's cash_on_hand unchanged
puts "#{person.name} transfered $#{amount} from the #{@bank} account to the #{to_bank.bank} account. The #{@bank} account has $#{@accounts[person.name]} and the #{to_bank.bank} account has $#{to_bank.accounts[person.name]}."
end
def total_cash_in_bank # Extra Credit (level 2)
total = 0
@accounts.each_value { |value| total += value}
puts "#{@bank} has $#{total} in the bank."
end
def issue_card(person, credit_limit) # Extra Credit (level 5)
# @credit = credit_limit
@cc_accounts[person.name] = credit_limit
@cc_outstanding[person.name] = 0
puts "#{@bank} has issued #{person.name} a credit card with a $#{@credit} credit limit."
end
def cc_charge(person, amount) # Extra Credit (level 5)
if amount <= @cc_accounts[person.name]
@cc_outstanding[person.name] += amount
available_credit = @cc_accounts[person.name] - @cc_outstanding[person.name]
puts "#{person.name} charged $#{amount} to the #{@bank} credit card. #{person.name} has $#{available_credit} available credit remaining and $#{@cc_outstanding[person.name]} outstanding."
else
available_credit = @cc_accounts[person.name] - @cc_outstanding[person.name]
puts "#{person.name} does not have enough credit on the #{@bank} credit card to make a charge of $#{amount}. #{person.name} only has $#{available_credit} available credit."
end
end
def cc_payment(person, amount) # Extra Credit (level 5)
if amount < @cc_outstanding[person.name]
@cc_outstanding[person.name] -= amount
available_credit = @cc_accounts[person.name] - @cc_outstanding[person.name]
puts "#{person.name} made a payment of $#{amount} on the #{@bank} credit card. #{person.name} now has $#{available_credit} available credit and $#{@cc_outstanding[person.name]} outstanding."
elsif amount == @cc_outstanding[person.name]
@cc_outstanding[person.name] -= amount
available_credit = @cc_accounts[person.name] - @cc_outstanding[person.name]
puts "#{person.name} made a payment of $#{amount} and paid off the #{@bank} credit card balance in full. #{person.name} now has $#{available_credit} available credit and $#{@cc_outstanding[person.name]} outstanding."
else
puts "#{person.name} cannot make a payment of $#{amount}. #{person.name}'s #{@bank} credit card has a balance $#{@cc_outstanding[person.name]}."
end
end
end
# class CreditCard
# attr_accessor :bank_credit_card
# attr_accessor :credit_card_accounts
# def initialize(bank)
# @bank_credit_card = bank
# puts "#{@bank_credit_card} credit card was just created!"
# @credit_card_accounts = {}
# end
# def issue_card(person, credit_limit)
# @credit = credit_limit
# @credit_card_accounts[person] = @credit
# puts "#{@bank_credit_card} has issued #{person.name} a credit card with a limit of $#{@credit}"
# end
# def charge(person, amount)
# end
# end
=begin
# Credit Card System Notes
Option A: CreditCard system as new Class; transactions as methods
Option B: credit card transactions as methods of Bank
To include:
Hash {:account=>credit_limit}
Hash {:transaction=>amount}
Method cc_charge
Method cc_payment
=end
|
require 'chemistry/element'
Chemistry::Element.define "Sulfur" do
symbol "S"
atomic_number 16
atomic_weight 32.065
melting_point '388.51K'
end
|
# A Robut::Storage implementation is a simple key-value store
# accessible to all plugins. Plugins can access the global storage
# object with the method +store+. All storage implementations inherit
# from Robut::Storage::Base. All implementations must implement the class
# methods [] and []=.
class Robut::Storage::Base
class << self
# Sets the key +k+ to the value +v+ in the current storage system
def []=(k,v)
raise "Must be implemented"
end
# Returns the value at the key +k+.
def [](k)
raise "Must be implemented"
end
end
end
|
# frozen_string_literal: true
FactoryBot.define do
factory :mhv_account do
user_uuid { SecureRandom.uuid }
account_state 'unknown'
mhv_correlation_id nil
registered_at nil
upgraded_at nil
end
trait :upgraded do
account_state :upgraded
registered_at Time.current
upgraded_at Time.current
end
trait :registered do
account_state :registered
registered_at Time.current
end
end
|
class Building < ActiveRecord::Base
has_many :roomies, :class_name => 'Roomie'
validates_presence_of :name, :number
end
|
require 'active_model'
module LD4L
module OreRDF
class Aggregation < DoublyLinkedList
@@clear_first_callback = lambda { |aggregation| aggregation.first_proxy = nil }
@@clear_last_callback = lambda { |aggregation| aggregation.last_proxy = nil }
@@update_first_callback = lambda { |aggregation, proxies| aggregation.first_proxy = proxies.first }
@@update_last_callback = lambda { |aggregation, proxies| aggregation.last_proxy = proxies.last }
@@clear_next_callback = lambda { |proxies, idx| proxies[idx].next_proxy = nil }
@@clear_prev_callback = lambda { |proxies, idx| proxies[idx].prev_proxy = nil }
@@update_next_callback = lambda { |proxies, idx| proxies[idx].next_proxy = proxies[idx+1] }
@@update_prev_callback = lambda { |proxies, idx| proxies[idx].prev_proxy = proxies[idx-1] }
@@find_first_callback = lambda do |aggregation, proxies|
first_proxy = aggregation.first_proxy
return first_proxy unless first_proxy.nil?
# if first isn't set, try to figure out first by looking for an item with prev_proxy == nil
# NOTE: If multiple items have prev_proxy == nil, it will return the first one it finds.
first_idx = proxies.index { |proxy| proxy.prev_proxy.nil? }
first_idx ? proxies[first_idx] : nil
end
@@find_last_callback = lambda do |aggregation, proxies|
last_proxy = aggregation.last_proxy
return last_proxy unless last_proxy.nil?
# if last isn't set, try to figure out last by looking for an item with next_proxy == nil
# NOTE: If multiple items have next_proxy == nil, it will return the first one it finds.
last_idx = proxies.index { |proxy| proxy.next_proxy.nil? }
last_idx ? proxies[last_idx] : nil
end
@@find_next_callback = lambda { |proxies, current_proxy| current_proxy.next_proxy }
@@find_prev_callback = lambda { |proxies, current_proxy| current_proxy.prev_proxy }
def self.initialize
super
end
def initialize(*args)
new_args = args[0].dup unless args.empty?
unless args.empty?
new_args[:items] = new_args[:proxy_resources] if new_args.is_a?(Hash) && new_args.key?(:proxy_resources)
new_args[:list_info] = new_args[:aggregation_resource] if new_args.is_a?(Hash) && new_args.key?(:aggregation_resource)
new_args.delete(:proxy_resources)
new_args.delete(:aggregation_resource)
end
new_args = {} if args.empty?
# set callbacks
new_args[:clear_first_callback] = @@clear_first_callback
new_args[:clear_last_callback] = @@clear_last_callback
new_args[:update_first_callback] = @@update_first_callback
new_args[:update_last_callback] = @@update_last_callback
new_args[:clear_next_callback] = @@clear_next_callback
new_args[:clear_prev_callback] = @@clear_prev_callback
new_args[:update_next_callback] = @@update_next_callback
new_args[:update_prev_callback] = @@update_prev_callback
new_args[:find_first_callback] = @@find_first_callback
new_args[:find_last_callback] = @@find_last_callback
new_args[:find_next_callback] = @@find_next_callback
new_args[:find_prev_callback] = @@find_prev_callback
super(new_args)
end
def id
list_info.rdf_subject.to_s
end
def title
titles = list_info.title
titles = titles.to_a if Object::ActiveTriples.const_defined?("Relation") && titles.kind_of?(ActiveTriples::Relation)
titles.kind_of?(Array) && titles.size > 0 ? titles.first : ""
end
def description
descriptions = list_info.description
descriptions = descriptions.to_a if Object::ActiveTriples.const_defined?("Relation") && descriptions.kind_of?(ActiveTriples::Relation)
descriptions.kind_of?(Array) && descriptions.size > 0 ? descriptions.first : ""
end
def aggregation_resource
list_info
end
def proxy_resources
@list
end
# def self.model_name
# ActiveModel::Name.new(LD4L::OreRDF::Aggregation)
# end
private
def self.get_first_value source, value, as_subject=false
val = value
val = val.to_a if Object::ActiveTriples.const_defined?("Relation") && val.kind_of?(ActiveTriples::Relation)
return nil if val.nil? || val.size <= 0
val = val.first if val.is_a? Array
val = val.rdf_subject.to_s if as_subject && (val.is_a? ActiveTriples::Resource)
val
end
end
end
end
|
FactoryGirl.define do
factory :article do
title
lead { generate :string }
body
published_at { DateTime.now }
author_id { User.last&.id || create(:user).id }
photo { generate :file }
state { Article.state_machines[:state].states.map(&:name).first.to_s }
end
end
|
class Calendar < ActiveRecord::Base
acts_as_archive
belongs_to :user, :touch => true
validates_presence_of :uri, :title, :user
validates_format_of :uri, :with => /^https?:\/\/.+\..+/
validates_uniqueness_of :uri, :title, :scope => :user_id
after_save { |calendar| calendar.user.touch }
after_destroy { |calendar| calendar.user.touch }
def self.after_restore(calendar)
calendar.user.touch
end
end
Calendar::Archive.class_eval do
# Finds a deleted Calendar for the given user with the given ID.
#
# @param [User] user
# @param [Fixnum] id
# @return [Calendar::Archive] a deleted calendar
# @raise [ActiveRecord::RecordNotFound] if user has no such deleted calendar
def self.find_by_user_and_id!(user, id)
returning(find_by_user_id_and_id(user, id.to_i)) do |c|
raise ActiveRecord::RecordNotFound.new("User ##{user_id} has no deleted calendar ##{id}") unless c
end
end
def restore
Calendar.restore_all(['id = ?', id])
Calendar.find(id).tap { |c| Calendar.after_restore(c) }
end
end
|
require 'test_helper'
class SongTest < ActiveSupport::TestCase
setup do
@song = songs(:one)
@album = albums(:one)
end
test 'should not save empty song' do
song = Song.new
song.save
refute song.valid?
end
test 'should save valid song' do
song = Song.new
song.song_title = 'Song'
song.album = @album
song.genre = 'Pop'
song.length = 3
assert song.valid?
end
test 'should not save empty song title' do
song = Song.new
song.album = @album
song.genre = 'Pop'
song.length = 3
refute song.valid?
end
test 'should not save empty song length' do
song = Song.new
song.song_title = 'Song'
song.album = @album
song.genre = 'Pop'
refute song.valid?
end
test 'should not save non-integer song length' do
song = Song.new
song.song_title = 'Song'
song.album = @album
song.genre = 'Pop'
song.length = 3.4
refute song.valid?
end
test 'should not save negative song length' do
song = Song.new
song.song_title = 'Song'
song.album = @album
song.genre = 'Pop'
song.length = -4
refute song.valid?
end
end
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
# Specify the version of Sup
SUP_VER = ENV['SUP_VER'] || "v0.5"
$script = <<SCRIPT
sudo apt-get install -y curl
echo Fetching Sup $1 ...
cd /tmp/
curl -sSL https://github.com/pressly/sup/releases/download/$1/sup-linux64 -o sup
echo Installing Sup $1 ...
sudo chmod +x sup
sudo mv sup /usr/bin/sup
echo Installed Sup $1 successfully ...
SCRIPT
Vagrant.configure(2) do |config|
vmName = "sup-01"
config.vm.box = "bento/ubuntu-16.04"
config.vm.define vmName do |vmCfg|
vmCfg.vm.hostname = vmName
vmCfg.vm.network "private_network", type: "dhcp"
end
config.vm.provision "shell", inline: $script, privileged: false, args: SUP_VER
# Increase memory for Virtualbox
config.vm.provider "virtualbox" do |vb|
vb.memory = "1024"
vb.customize ["modifyvm", :id, "--cableconnected1", "on"]
end
end
|
class Beer < ActiveRecord::Base
validates :name, presence: true, length: { minimum: 2, maximum: 50 }, uniqueness: { case_sensitive: false }
validates :alcohol, numericality: true, length: { maximum: 6 }, allow_blank: true
validates :brewery, :brewery_url, :style, length: { minimum: 2, maximum: 200 }, allow_blank: true
validates :description, length: { minimum: 2 }, allow_blank: true
validate :picture_size
has_many :reviews, dependent: :destroy
has_and_belongs_to_many :meetings
before_save :correct_case_name
searchkick
mount_uploader :picture, PictureUploader
private
def correct_case_name
self.name = name.split.map(&:capitalize)*' '
end
# Validates the size of an uploaded picture.
def picture_size
if picture.size > 5.megabytes
errors.add(:picture, "should be less than 5MB")
end
end
end
|
class MoviesController < ApplicationController
def movie_params
params.require(:movie).permit(:title, :rating, :description, :release_date)
end
def show
id = params[:id] # retrieve movie ID from URI route
@movie = Movie.find(id) # look up movie by unique ID
# will render app/views/movies/show.<extension> by default
end
def index
@movies = Movie.all
@all_ratings=Movie.uniq.pluck(:rating).sort
if(params[:ratings]!=nil)
#@cur_ratings=params[:ratings].keys
# reference: https://stackoverflow.com/questions/28954500/activerecord-where-field-array-of-possible-values
if params[:ratings].keys.length>0
logger.debug params[:ratings].keys.length
@movies=Movie.where('rating IN (?)', params[:ratings].keys)
session[:cur_ratings]=params[:ratings].keys
end
else
logger.debug "no form"
end
if (params[:sortby]!=nil)
if session[:cur_ratings]==nil||session[:cur_ratings].empty?
@movies=Movie.order(params[:sortby])
else
@movies=Movie.where('rating IN (?)', session[:cur_ratings]).order(params[:sortby])
end
session[:sortby]=params[:sortby]
logger.debug session[:sortby]
elsif (session[:sortby]!=nil)
if session[:cur_ratings]==nil||session[:cur_ratings].empty?
@movies=Movie.order(session[:sortby])
else
@movies=Movie.where('rating IN (?)', session[:cur_ratings]).order(session[:sortby])
end
end
end
def new
# default: render 'new' template
end
def create
@movie = Movie.create!(movie_params)
flash[:notice] = "#{@movie.title} was successfully created."
flash.keep
redirect_to movies_path
end
def edit
@movie = Movie.find params[:id]
end
def update
@movie = Movie.find params[:id]
@movie.update_attributes!(movie_params)
@cur_ratings=[]
flash[:notice] = "#{@movie.title} was successfully updated."
flash.keep
redirect_to movie_path(@movie)
end
def destroy
@movie = Movie.find(params[:id])
@movie.destroy
flash[:notice] = "Movie '#{@movie.title}' deleted."
flash.keep
redirect_to movies_path
end
def sort
params[:title]
end
end
|
class GaugesController < ApplicationController
unloadable
helper :sort
include SortHelper
helper :queries
include QueriesHelper
helper :issues
include IssuesHelper
before_filter :find_project, :authorize, :only => :index
def index
@base_date = params.include?(:base_date) ? Date.strptime(params[:base_date]) : Date.today
@gauge_type = params.include?(:gauge_type) ? params[:gauge_type] : :by_amount
p @gauge_type
@members = Member.with_week_issues(@base_date)
retrieve_query
sort_init(@query.sort_criteria.empty? ? [['id', 'desc']] : @query.sort_criteria)
sort_update(@query.sortable_columns)
if @query.valid?
@issues = @query.issues(:include => [:assigned_to, :tracker, :priority, :category, :fixed_version],
:order => sort_clause)
respond_to do |format|
format.html { render :template => 'gauges/index.html.erb', :layout => !request.xhr? }
end
end
end
def move_issue
new_member_id = params[:where].split("_")[0]
new_date = params[:where].split("_")[1]
Issue.transaction do
params[:dropped].split(",").each do |element_id|
issue_id = element_id.split("_")[1]
issue = Issue.find_by_id(issue_id)
issue.assigned_to_id = new_member_id
issue.start_date = new_date
if !issue.save
flash[:error] = issue.errors
end
end
end
@base_date = Date.strptime(params[:base_date])
show_week
end
private
def find_project
@project = Project.find(params[:project_id])
end
end
|
module Roglew
class RenderbufferEXT
include Roglew::Contextual(RenderbufferContextEXT)
attr_reader :handle, :id
def initialize(handle)
@handle = handle
@id = handle.bind { |context| context.gen_renderbuffersEXT }
ObjectSpace.define_finalizer(self, self.class.finalize(@handle, @id))
end
def self.finalize(handle, id)
proc do
#puts "releasing renderbuffer #{id}"
handle.bind { |context| context.delete_renderbuffersEXT(id) }
end
end
def bind(deferred = nil, &block)
create_binding(deferred, &block)
end
end
end |
class Character
class Dead < RuntimeError; end
attr_accessor :attack, :armor, :mp, :mana_used
attr_reader :hp
def initialize(hp, attack, mp = 0)
@hp = hp
@mp = mp
@attack = attack
@armor = 0
@mana_used = 0
end
def hp=(value)
@hp = value
raise Dead if value < 0
end
def hit(power)
self.hp -= [(power - @armor), 1].max
end
def debuff
@armor = 0
end
end
class Skill
attr_reader :name, :cost
def initialize(name, cost, cooldown = 0, &callback)
@name = name
@cost = cost
@cooldown = cooldown
@effect = callback
@timer = 0
end
def cast(caster, enemy)
caster.mp -= cost
caster.mana_used += cost
if @cooldown > 0
@timer = @cooldown
else
@effect.call(caster, enemy)
end
end
def tick(caster, enemy)
return unless active?
@effect.call(caster, enemy)
@timer -= 1
end
def castable_by?(caster)
@timer <= 1 && @cost <= caster.mp
end
def active?
@timer > 0
end
end
SKILLS = [
# DRAIN is less efficient than MAGIC MISSILE, and only prolongs the battle
Skill.new("DRAIN", 73) { |hero, enemy| enemy.hit(2) && hero.hp += 2 },
Skill.new("MAGIC MISSILE", 53) { |_hero, enemy| enemy.hit(4) },
Skill.new("SHIELD", 113, 6) { |hero, _enemy| hero.armor = 7 },
Skill.new("POISON", 173, 6) { |_hero, enemy| enemy.hit(3) },
Skill.new("RECHARGE", 229, 5) { |hero, _enemy| hero.mp += 101 }
].freeze
class Battle
attr_reader :hero, :enemy, :skills
def initialize(hero, enemy, skills, hard_mode: false)
@hero = hero
@enemy = enemy
@skills = skills
@hard_mode = hard_mode
end
def optimal_strategy(minimum = 9999)
return minimum if hero.mana_used >= minimum
save_scum do |save_state, won|
minimum =
if won
[save_state.hero.mana_used, minimum].min
else
save_state.optimal_strategy(minimum)
end
end
minimum
end
def save_scum
skills.size.times do |i|
state = save_state
outcome = state.resolve(state.skills[i])
yield(state, outcome) unless outcome == false
end
end
def resolve(skill)
return false unless skill.castable_by?(hero)
# Hero's turn
hero.hp -= 1 if @hard_mode
resolve_effects
skill.cast(hero, enemy)
# Enemy's Turn
resolve_effects
hero.hit(enemy.attack)
nil
rescue Character::Dead
enemy.hp <= 0
end
private
def resolve_effects
hero.debuff
skills.each { |s| s.tick(hero, enemy) }
end
def save_state
Battle.new(hero.clone, enemy.clone, skills.map(&:clone), hard_mode: @hard_mode)
end
end
HERO_STATS ||= [50, 0, 500].freeze
enemy_stats = INPUT.split("\n").map { |i| i.scan(/\d+/).join.to_i }
enemy = Character.new(*enemy_stats)
hero = Character.new(*HERO_STATS)
best = Battle.new(hero, enemy, SKILLS).optimal_strategy
solve!("Cheapest strategy:", best)
best = Battle.new(hero, enemy, SKILLS, hard_mode: true).optimal_strategy
solve!("Cheapest strategy (hard mode):", best)
|
class ReserveMailer < ApplicationMailer
def submit_request(reserve, address, current_user)
@reserve = reserve
@current_user = current_user
mail(to: address, subject: "#{reserve.has_been_sent ? 'Updated' : 'New'} Reserve Form: #{reserve.cid}-#{reserve.sid} - #{reserve.term}")
end
end
|
# # create the method. print out that we're adding 2 numbers together and then return the sum.
# def add(a, b)
# puts "adding #{a} and #{b}: "
# return a + b
# end
# #call the method
# puts add(2, 3)
# puts add(10, 50)
# puts add(3,8)
# ##########SIMPLE METHODS############
# #saying hello
# def hello(name1, name2)
# puts "Hello #{name1}"
# puts "Hello #{name2}"
# end
# hello("Kyle", "Linh")
###class methods###
class BankAccount
###class << self (lets you remove the selfs)##
attr_reader :balance
attr_accessor :transations
def self.create_for(first_name, last_name)
@accounts ||= []
@accounts << BankAccount.new(first_name, last_name)
end
def self.find_for(first_name, last_name)
@accounts.find{|acount| account.full_name == "#{@first_name} #{@last_name}"}
end
def initialize(first_name, last_name)
@balance = 0
@first_name = first_name
@last_name = last_name
end
def full_name
"#{@first_name} #{@last_name}"
end
def deposit(amount)
@balance += amount
end
def withdraw(amount)
@balance -= amount
end
def reset!
@balance = 0
end
end
bank_account = BankAccount.new("Kyle", "Schwartz")
puts bank_account.inspect |
class CommentsController < ApplicationController
layout 'unpublic'
before_action :confirm_logged_in
before_action :privilege, :only => [:all]
before_action :check, :only => [:edit, :update, :delete, :destroy]
before_action :update_average_rating, :only => [:index]
def index
@shop = Shop.find(params[:shop_id])
@comments = @shop.comments
@average_rating
end
def show
@comment = Comment.find(params[:id])
end
def new
#@shop = Shop.find(params[:id])
#@user = User.find(session[:user_id])
@comment = Comment.new()
#@shops = Shop.visible
#@comment_count = Comment.count + 1
end
def create
@comme = Comment.new(comment_params)
@comme.shop_id = params[:shop_id]
if @comme.save
flash[:notice] = 'Comment added.'
#redirect_to(:action => 'index')
redirect_to :back
else
redirect_to(:action => 'index', :shop_id => @comme.shop_id)
end
end
def edit
@shop = Shop.find(params[:shop_id])
@comment = Comment.find(params[:id])
# @comment_count = Comment.count
end
def update
@comment = Comment.find(params[:id])
@shop = @comment.shop_id
#@user = User.find(session[:user_id])
if @comment.update_attributes(comment_params)
flash[:notice] = "Comment updated successfully."
redirect_to(:action => 'index', :shop_id => @shop)
end
end
def delete
@shop = Shop.find(params[:shop_id])
@comment = Comment.find(params[:id])
end
def destroy
comment = Comment.find(params[:id]).destroy
@shop = comment.shop_id
flash[:notice] = "Comment deleted successfully."
redirect_to(:action => 'index', :shop_id => @shop)
end
def all
@comments = Comment.all
end
private
def comment_params
@user = User.find(session[:user_id])
params.require(:comment).permit(:rate, :comments).merge(:user_id => @user.id)
end
def check
user = User.find(session[:user_id])
comment = Comment.find(params[:id])
if user == comment.user_id
return true
elsif user.privilege.present?
return true
else
flash[:notice] = "You can not edit this comment."
redirect_to :back
end
end
def update_average_rating
@shop = Shop.find(params[:shop_id])
@comments = @shop.comments
@value = 0
@comments.each do |comment|
@value = @value + comment.rate
end
@total = @comments.size
@average_rating = @value / @total.to_f
end
end
|
class AddCalToUltrasonics < ActiveRecord::Migration
def change
add_column :ultrasonics, :cal_block, :string
end
end
|
class User < ApplicationRecord
has_many :cuisine_preferences
has_many :matches
has_many :cuisines, through: :cuisine_preferences
has_secure_password
validates :email, presence: true
validates :email, uniqueness: true
end
|
# coding: utf-8
require 'rbconfig'
class TestMeCabNode < Minitest::Test
def setup
@host_os = RbConfig::CONFIG['host_os']
@arch = RbConfig::CONFIG['arch']
if @host_os =~ /mswin|mingw/i
@test_cmd = 'type "test\\natto\\test_sjis"'
else
@test_cmd = 'cat "test/natto/test_utf8"'
end
nm = Natto::MeCab.new
@nodes = []
nm.parse(`#{@test_cmd}`) { |n| @nodes << n }
nm = Natto::MeCab.new('-N2 -Oyomi')
@nb_nodes = []
nm.parse(`#{@test_cmd}`) { |n| @nb_nodes << n }
end
def teardown
@nodes = nil
@nb_nodes = nil
@host_os = nil
@arch = nil
@test_cmd = nil
end
def test_surface_and_feature_accessors
raw = `#{@test_cmd} | mecab`.lines.to_a
raw.delete_if {|e| e =~ /^(EOS|BOS|\t)/ }
raw.map!{|e| e.force_encoding(Encoding.default_external)} if @arch =~ /java/i && RUBY_VERSION.to_f >= 1.9
expected = {}
raw.each do |l|
tokens = l.split("\t")
expected[tokens[0]]=tokens[1].strip
end
actual = {}
@nodes.each do |n|
actual[n.surface]=n.feature if n.surface and (n.is_nor? || n.is_unk?)
end
assert_equal(expected, actual)
end
# Note: Object#id is deprecated in 1.9.n, but comes with a warning
# in 1.8.n
def test_mecabnode_accessors
node = @nodes[0]
[ :prev,
:next,
:enext,
:bnext,
:rpath,
:lpath,
:surface,
:feature,
:id,
:length,
:rlength,
:rcAttr,
:lcAttr,
:posid,
:char_type,
:stat,
:isbest,
:alpha,
:beta,
:prob,
:wcost,
:cost
].each do |nomme|
refute_nil(node.send nomme)
end
assert_raises NoMethodError do
node.send :unknown_attr
end
end
def test_is_eos
assert(@nodes.pop.is_eos?)
@nodes.each do |n|
assert(n.is_nor?)
end
end
def test_nbest_nodes
n1 = @nb_nodes[0]
n2 = @nb_nodes[8]
assert_equal(n1.surface, n2.surface)
refute_equal(n1.feature, n2.feature)
end
end
# Copyright (c) 2020, Brooke M. Fujita.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above
# copyright notice, this list of conditions and the
# following disclaimer.
#
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the
# following disclaimer in the documentation and/or other
# materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
require 'spec_helper'
describe Pusher do
describe ".push_message" do
let(:recipient1) { double('recipient1', user: double('user', id: 1, user_name: 'bob')) }
let(:recipient2) { double('recipient2', user: double('user', id: 2, user_name: 'jeff')) }
let(:recipients) { [recipient1, recipient2] }
let(:user) { double('User', recipients: recipients) }
let(:message) { double('Message', user: user) }
it "pushes the message to each recipient workstation" do
recipient_count = user.recipients.size
MessagePresenter.should_receive(:new).exactly(recipient_count).times
PrivatePub.should_receive(:publish_to).exactly(recipient_count).times
Pusher.push_message(message)
end
it "does not push a message more than once to a user working multiple jobs" do
user.stub(recipients: [recipient1, recipient1])
MessagePresenter.should_receive(:new).exactly(1).times
PrivatePub.should_receive(:publish_to).exactly(1).times
Pusher.push_message(message)
end
end
end
|
#encoding: utf-8
module Concerns::Admins::ImageUpload
def upload_cover_img file,path
if file.present? && file.original_filename.present? && file.size < 5 * 1024 * 1024 && file.size > 0
filename=get_file_name(file.original_filename)
url = "#{path}#{filename}"
File.open(url, "wb"){|f| f.write(file.read)}
url.gsub!("/opt/uploads","") #软链接到项目的public目录下,所以需要清理多余部分文件路径
end
url
end
def get_file_name(filename)
unless filename.blank?
Time.now.to_i.to_s+Random.rand(10000).to_s+File.extname(filename)
end
end
end |
# Source: https://launchschool.com/exercises/675bc8c9
def multisum(max_val)
valid_factor = []
(1..max_val).each do |x|
valid_factor << x if (x % 3).zero? || (x % 5).zero?
end
valid_factor.sum
end
# P:
# Question:
# Write a method that searches for all multiples of 3 or 5 that lie between
# 1 and some other number, and then computes the sum of those multiples.
# In/Out:
# In: One number
# Out: An integer sum
# Rules/Reqs:
# - You may assume that the number passed in is an integer greater than 1.
# Mental Model:
# Given a positive input integer greater than 1, create an array containing all
# multiples of 3 and 5 that exist in the range of 1..integer, then return the
# sum of the array.
# E:
puts multisum(3) == 3
puts multisum(5) == 8
puts multisum(10) == 33
puts multisum(1_000) == 234_168
# D:
# We should use an array that we can add to then reduce or sum at the end.
# A:
# Accept an input 'end_num' parameter in our method
# Create array 'valid'
# Create a range from 1 to end_num
# For each element in range, append to valid if 3 or 5 is a valid factor
# Return the sum of the array
|
require "spec_helper"
RSpec.describe "Day 12: JSAbacusFramework.io" do
let(:runner) { Runner.new("2015/12") }
describe "Part One" do
it "sums all numbers in the document" do
expect(runner.execute!("[1,2,3]", part: 1)).to eq(6)
expect(runner.execute!('{"a":2,"b":4}', part: 1)).to eq(6)
expect(runner.execute!("[[[3]]]", part: 1)).to eq(3)
expect(runner.execute!('{"a":{"b":4},"c":-1}', part: 1)).to eq(3)
expect(runner.execute!('{"a":[-1,1]}', part: 1)).to eq(0)
expect(runner.execute!('[-1,{"a":1}]', part: 1)).to eq(0)
expect(runner.execute!("[]", part: 1)).to eq(0)
expect(runner.execute!("{}", part: 1)).to eq(0)
end
end
describe "Part Two" do
it "ignores values in red" do
expect(runner.execute!("[1,2,3]", part: 2)).to eq(6)
expect(runner.execute!('[1,{"c":"red","b":2},3]', part: 2)).to eq(4)
expect(runner.execute!('{"d":"red","e":[1,2,3,4],"f":5}', part: 2)).to eq(0)
expect(runner.execute!('[1,"red",5]', part: 2)).to eq(6)
end
end
end
|
class MenuPagesController < ApplicationController
# GET /menu_pages
# GET /menu_pages.xml
def index
@menu_pages = MenuPage.all
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @menu_pages }
end
end
# GET /menu_pages/1
# GET /menu_pages/1.xml
def show
@menu_page = MenuPage.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @menu_page }
end
end
# GET /menu_pages/new
# GET /menu_pages/new.xml
def new
@menu_page = MenuPage.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @menu_page }
end
end
# GET /menu_pages/1/edit
def edit
@menu_page = MenuPage.find(params[:id])
end
# POST /menu_pages
# POST /menu_pages.xml
def create
@menu_page = MenuPage.new(params[:menu_page])
respond_to do |format|
if @menu_page.save
format.html { redirect_to(@menu_page, :notice => 'Menu page was successfully created.') }
format.xml { render :xml => @menu_page, :status => :created, :location => @menu_page }
else
format.html { render :action => "new" }
format.xml { render :xml => @menu_page.errors, :status => :unprocessable_entity }
end
end
end
# PUT /menu_pages/1
# PUT /menu_pages/1.xml
def update
@menu_page = MenuPage.find(params[:id])
respond_to do |format|
if @menu_page.update_attributes(params[:menu_page])
format.html { redirect_to(@menu_page, :notice => 'Menu page was successfully updated.') }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @menu_page.errors, :status => :unprocessable_entity }
end
end
end
# DELETE /menu_pages/1
# DELETE /menu_pages/1.xml
def destroy
@menu_page = MenuPage.find(params[:id])
@menu_page.destroy
respond_to do |format|
format.html { redirect_to(menu_pages_url) }
format.xml { head :ok }
end
end
end
|
# Practice Problem 5
# Given this nested Hash:
munsters = {
"Herman" => { "age" => 32, "gender" => "male" },
"Lily" => { "age" => 30, "gender" => "female" },
"Grandpa" => { "age" => 402, "gender" => "male" },
"Eddie" => { "age" => 10, "gender" => "male" },
"Marilyn" => { "age" => 23, "gender" => "female"}
}
# Goal: figure out the total age of just the male members of the family.
# Select the hashes that have a gender of male and save to males_hash
# variable as nested hash
males_hash = munsters.select do |_, value|
value['gender'] == 'male'
end
# => {
# "Herman"=>{"age"=>32, "gender"=>"male"},
# "Grandpa"=>{"age"=>402, "gender"=>"male"},
# "Eddie"=>{"age"=>10, "gender"=>"male"}
# }
# create empty array to hold return values
ages_array = []
males_hash.map do |sub_arr|
sub_arr[1].select do |k, v|
ages_array << v if v.to_s.to_i == v
end
end
# => [32, 402, 10]
# calling #map on a hash returns the hash as an array, the same thing as
# #to_a does but allows us to iterate over each inner array and target the
# index that holds the values (as hashes) we need. In this case index[1] from the
# sub_array will return each {"age"=>n, "gender"=>"male"}. So we run select
# over the index choosing to push only integers to the empty ages_array we
# declared earlier.
# call Array#sum from ages_array
p ages_array.sum
# => 444
|
class Project < ActiveRecord::Base
include Concerns::Removable, Concerns::Tokenable
has_many :project_user_relations, dependent: :destroy
has_many :users, through: :project_user_relations
has_many :invites
has_many :tasks, dependent: :destroy
has_many :milestones, dependent: :destroy
has_one :canvas, dependent: :destroy
belongs_to :administrator, class_name: 'User'
validates :name, presence: true, length: {within: 1..100}
# ユニークなランダム8文字のトークンを
# create時にセットする
before_create {
begin
self[:access_token] = generate_token(8)
end while Project.exists?(:access_token => self[:access_token])
}
end
|
module WordLadder
class Word
attr_reader :key, :dictionary
def initialize(word, dictionary)
@key = word.downcase
@dictionary = dictionary
dictionary.validate_word(word)
end
def next_words
@next_words ||= gen_next_words.sort { |a, b| a.key <=> b.key }
end
private
def gen_next_words
(0...key.length).each_with_object([]) do |i, arr|
arr.concat(valid_words(i).map { |w| self.class.new(w, dictionary) })
end
end
def valid_words(i)
words(i).keep_if { |w| dictionary.exists?(w) && w.downcase != key }
end
def words(i)
letters.map do |l|
word = key.clone
word[i] = l
word
end
end
def letters
("a".."z").to_a
end
end
end
|
require "ensembl/version"
require 'active_record'
require 'yaml'
require 'active_support/core_ext'
module Ensembl
# Load configuration from database.yml
ActiveRecord::Base.configurations = YAML::load(IO.read('config/database.yml'))
module TableNameOverrides
def table_name
self.name.split('::').last.underscore || ''
end
end
module PrimaryKeyOverrides
def primary_key
self.table_name + '_id'
end
end
# ConnectionPool implemented from:
# http://www.lucasallan.com/2014/05/26/fixing-concurrency-issues-with-active-record-in-a-rack-application.html
class ConnectionPooledBase < ActiveRecord::Base
self.abstract_class = true
singleton_class.send(:alias_method, :original_connection, :connection)
def self.connection
ActiveRecord::Base.connection_pool.with_connection do |conn|
conn
end
end
end
end
require File.dirname(__FILE__) + '/ensembl/helpers/like_search.rb'
require File.dirname(__FILE__) + '/ensembl/core/activerecord.rb'
require File.dirname(__FILE__) + '/ensembl/helpers/variation_position.rb'
require File.dirname(__FILE__) + '/ensembl/variation/activerecord.rb'
require File.dirname(__FILE__) + '/ensembl/variation/tableless.rb'
|
module XPash
class Base
def grep(*args)
# parse args
opts = optparse_grep!(args)
keyword = args[0]
if opts[:all]
query = ROOT_PATH
node_ary = [@doc]
elsif args[1]
query = getPath(@query, args[1])
node_ary = @doc.xpath(query, $xmlns)
return node_ary unless node_ary.kind_of? Nokogiri::XML::NodeSet
else
query = @query
node_ary = @list
end
@log.debug_var binding, :query, "node_ary.size"
matches = []
node_ary.each do |node|
nodeset = node.xpath(".//text()[contains(., '#{keyword}')]")
nodeset.each do |tnode|
matches << tnode
path = [tnode.ls({:long => opts[:long]})]
tnode.ancestors.each do |anc|
break if anc.eql? node
path << anc.ls
end
@log.debug_var binding, :path
puts getPath(query, path.reverse.join("/"))
end
end
@log.debug_var binding, :matches
return matches.size
end
def optparse_grep!(args)
unless @optparses[:grep]
o = CmdOptionParser.new(nil, 20)
o.banner = "Usage: grep [OPTION] KEYWORD [PATH]"
o.min_args = 1
o.separator("Options:")
o.on("-a", "--all", "Search from document root.")
o.on("-l", "--long", "Display elements with long format.")
@optparses[:grep] = o
end
opts = @optparses[:grep].parse!(args)
@log.debug_var binding, :args, :opts
return opts
end
end
end
|
class Tfl < ActiveRecord::Base
belongs_to :company
has_many :employees
validates_presence_of :name
end
|
# :nodoc:
class SettingsHandlerBase < YARD::Handlers::Ruby::Base
handles method_call :string_setting
handles method_call :number_setting
handles method_call :boolean_setting
namespace_only
def process
name = statement.parameters.first.jump(:tstring_content, :ident).source
object = YARD::CodeObjects::MethodObject.new(namespace, name)
register(object)
# Modify the code object for the new instance method
object.dynamic = true
# Add custom metadata to the object
object['custom_field'] = '(Found using method_missing)'
# Module-level configuration notes
hutch_config = YARD::CodeObjects::ModuleObject.new(:root, "Hutch::Config")
collection_name = statement.first.first
default_value = statement.parameters[1].jump(:tstring_content, :ident).source
(hutch_config['setting_rows'] ||= []) << {
name: name,
default_value: default_value,
type: collection_name.sub('_setting', '').capitalize,
description: object.docstring,
first_line_of_description: first_line_of_description(object)
}
end
def first_line_of_description(object)
return '' if object.docstring.blank?
object.docstring.lines.first
end
end
|
Rails.application.routes.draw do
resources :tasks
root "tasks/#index"
end
|
# frozen_string_literal: true
module Vedeu
module Colours
# The class represents one half (the other, can be found at
# {Vedeu::Colours::Foreground}) of a terminal colour escape
# sequence.
#
# @api private
#
class Background < Vedeu::Colours::Translator
# @return [Boolean]
def background?
present?(to_s)
end
# @return [String]
def to_ast
return '' unless background?
return ':bg' unless rgb?
":bg_#{colour.to_s.slice(1..-1)}"
end
# @return [Hash<Symbol => String>]
def to_h
{
background: colour.to_s,
}
end
alias to_hash to_h
# @param _options [Hash] Ignored.
# @return [String]
def to_html(_options = {})
return '' unless rgb?
"background-color:#{colour};"
end
private
# @return [String]
def prefix
"\e[48;"
end
# Returns an escape sequence for a named colour.
#
# @note
# Valid names can be found at
# {Vedeu::EscapeSequences::Esc#valid_codes}
#
# @return [String]
def named
Vedeu.esc.background_colour(colour)
end
# @return [Vedeu::Colours::Backgrounds]
def repository
Vedeu.background_colours
end
end # Background
end # Colours
end # Vedeu
|
class Tag < ActiveRecord::Base
has_many :dream_tags
has_many :dreams, through: :dream_tags
end
|
class TestExecutionsController < ApplicationController
before_filter :authorize_global
before_filter :find_execution, :only => [:show]
helper :tests
def show
end
private
def find_execution
@execution = TestExecution.find(params[:id], :include => {:logs => :case})
rescue ActiveRecord::RecordNotFound
render_404
end
end
|
module RougeHighlighter
class ViewHooks < Redmine::Hook::ViewListener
def view_layouts_base_html_head(context={})
val = %{
/************* Rouge styles *************/
/* generated by: pygmentize -f html -a .syntaxhl -S colorful */
.syntaxhl .hll { background-color: #ffffcc }
.syntaxhl { background: #fafafa; }
.syntaxhl .c { color: #888888 } /* Comment */
.syntaxhl .err { color: #FF0000; background-color: #FFAAAA } /* Error */
.syntaxhl .k { color: #008800; font-weight: bold } /* Keyword */
.syntaxhl .o { color: #333333 } /* Operator */
.syntaxhl .cm { color: #888888 } /* Comment.Multiline */
.syntaxhl .cp { color: #557799 } /* Comment.Preproc */
.syntaxhl .c1 { color: #888888 } /* Comment.Single */
.syntaxhl .cs { color: #cc0000; font-weight: bold } /* Comment.Special */
.syntaxhl .gd { color: #A00000 } /* Generic.Deleted */
.syntaxhl .ge { font-style: italic } /* Generic.Emph */
.syntaxhl .gr { color: #FF0000 } /* Generic.Error */
.syntaxhl .gh { color: #000080; font-weight: bold } /* Generic.Heading */
.syntaxhl .gi { color: #00A000 } /* Generic.Inserted */
.syntaxhl .go { color: #888888 } /* Generic.Output */
.syntaxhl .gp { color: #c65d09; font-weight: bold } /* Generic.Prompt */
.syntaxhl .gs { font-weight: bold } /* Generic.Strong */
.syntaxhl .gu { color: #800080; font-weight: bold } /* Generic.Subheading */
.syntaxhl .gt { color: #0044DD } /* Generic.Traceback */
.syntaxhl .kc { color: #008800; font-weight: bold } /* Keyword.Constant */
.syntaxhl .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */
.syntaxhl .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */
.syntaxhl .kp { color: #003388; font-weight: bold } /* Keyword.Pseudo */
.syntaxhl .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */
.syntaxhl .kt { color: #333399; font-weight: bold } /* Keyword.Type */
.syntaxhl .m { color: #6600EE; font-weight: bold } /* Literal.Number */
.syntaxhl .s { background-color: #fff0f0 } /* Literal.String */
.syntaxhl .na { color: #0000CC } /* Name.Attribute */
.syntaxhl .nb { color: #007020 } /* Name.Builtin */
.syntaxhl .nc { color: #BB0066; font-weight: bold } /* Name.Class */
.syntaxhl .no { color: #003366; font-weight: bold } /* Name.Constant */
.syntaxhl .nd { color: #555555; font-weight: bold } /* Name.Decorator */
.syntaxhl .ni { color: #880000; font-weight: bold } /* Name.Entity */
.syntaxhl .ne { color: #FF0000; font-weight: bold } /* Name.Exception */
.syntaxhl .nf { color: #0066BB; font-weight: bold } /* Name.Function */
.syntaxhl .nl { color: #997700; font-weight: bold } /* Name.Label */
.syntaxhl .nn { color: #0e84b5; font-weight: bold } /* Name.Namespace */
.syntaxhl .nt { color: #007700 } /* Name.Tag */
.syntaxhl .nv { color: #996633 } /* Name.Variable */
.syntaxhl .ow { color: #000000; font-weight: bold } /* Operator.Word */
.syntaxhl .w { color: #bbbbbb } /* Text.Whitespace */
.syntaxhl .mb { color: #6600EE; font-weight: bold } /* Literal.Number.Bin */
.syntaxhl .mf { color: #6600EE; font-weight: bold } /* Literal.Number.Float */
.syntaxhl .mh { color: #005588; font-weight: bold } /* Literal.Number.Hex */
.syntaxhl .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */
.syntaxhl .mo { color: #4400EE; font-weight: bold } /* Literal.Number.Oct */
.syntaxhl .sb { background-color: #fff0f0 } /* Literal.String.Backtick */
.syntaxhl .sc { color: #0044DD } /* Literal.String.Char */
.syntaxhl .sd { color: #DD4422 } /* Literal.String.Doc */
.syntaxhl .s2 { background-color: #fff0f0 } /* Literal.String.Double */
.syntaxhl .se { color: #666666; font-weight: bold; background-color: #fff0f0 } /* Literal.String.Escape */
.syntaxhl .sh { background-color: #fff0f0 } /* Literal.String.Heredoc */
.syntaxhl .si { background-color: #eeeeee } /* Literal.String.Interpol */
.syntaxhl .sx { color: #DD2200; background-color: #fff0f0 } /* Literal.String.Other */
.syntaxhl .sr { color: #000000; background-color: #fff0ff } /* Literal.String.Regex */
.syntaxhl .s1 { background-color: #fff0f0 } /* Literal.String.Single */
.syntaxhl .ss { color: #AA6600 } /* Literal.String.Symbol */
.syntaxhl .bp { color: #007020 } /* Name.Builtin.Pseudo */
.syntaxhl .vc { color: #336699 } /* Name.Variable.Class */
.syntaxhl .vg { color: #dd7700; font-weight: bold } /* Name.Variable.Global */
.syntaxhl .vi { color: #3333BB } /* Name.Variable.Instance */
.syntaxhl .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
}
content_tag(:style, val.html_safe, type: 'text/css')
end
end
end |
module Bitfinex
module WalletClient
# See your balances.
#
# @param params :type [string] “trading”, “deposit” or “exchange”.
# @param params :currency [string] currency
# @param params :amount [decimal] How much balance of this currency in this wallet
# @param params :available [decimal] How much X there is in this wallet that is available to trade
# @return [Array]
# @example:
# client.balances
def balances(params = {})
check_params(params, %i{type currency amount available})
authenticated_post("balances", params: params).body
end
# See your trading wallet information for margin trading.
#
# @return [Array]
# @example:
# client.margin_infos
def margin_infos
authenticated_post("margin_infos").body
end
# See a symmary of your trade volume, funding profits etc.
#
# @return [Hash]
# @example:
# client.summary
def summary
authenticated_post("summary").body
end
# Allow you to move available balances between your wallets.
#
# @param amount [decimal] Amount to transfer
# @param currency [string] Currency of funds to transfer
# @param wallet_from [string] Wallet to transfer from
# @param wallet_to [string] Wallet to transfer to
# @return [Array]
# @example:
# client.transfer(10, 'btc', "exchange", "deposit")
def transfer(amount, currency, wallet_from, wallet_to)
params = {
amount: amount.to_s,
currency: currency.upcase,
walletfrom: wallet_from.downcase,
walletto: wallet_to.downcase
}
authenticated_post("transfer", params: params).body
end
# Allow you to request a withdrawal from one of your wallet.
#
# @param withdraw_type [string] can be “bitcoin”, “litecoin” or “darkcoin” or “tether” or “wire”
# @param walletselected [string] The wallet to withdraw from, can be “trading”, “exchange”, or “deposit”.
# @param amount [decimal] Amount to withdraw
# For Cryptocurrencies (including tether):
# @param params :address [string] Destination address for withdrawal
# For wire withdrawals
# @param params :account_name [string] account name
# @param params :account_number [string] account number
# @param params :bank_name [string] bank name
# @param params :bank_address [string] bank address
# @param params :bank_city [string] bank city
# @param params :bank_country [string] bank country
# @param params :detail_payment [string] (optional) message to beneficiary
# @param params :intermediary_bank_name [string] (optional) intermediary bank name
# @param params :intermediary_bank_address [string] (optional) intermediary bank address
# @param params :intermediary_bank_city [string] (optional) intermediary bank city
# @param params :intermediary_bank_country [string] (optional) intermediary bank country
# @param params :intermediary_bank_account [string] (optional) intermediary bank account
# @param params :intermediary_bank_swift [string] (optional) intemediary bank swift
# @param params :expressWire [int] (optional). “1” to submit an express wire withdrawal, “0” or omit for a normal withdrawal
# @return [Array]
# @example:
# client.withdraw("bitcoin","deposit",1000, address: "1DKwqRhDmVyHJDL4FUYpDmQMYA3Rsxtvur")
def withdraw(withdraw_type, walletselected, amount, params={})
params.merge!({
withdraw_type: withdraw_type,
walletselected: walletselected.downcase,
amount: amount.to_s})
authenticated_post("withdraw", params: params).body
end
# Check the permissions of the key being used to generate this request
#
# @return [Hash]
# @example:
# client.key_info
def key_info
authenticated_post("key_info").body
end
end
end
|
class ChangeColumnInUsers2 < ActiveRecord::Migration[5.1]
def change
change_column :users, :income, :integer
end
end
|
require './spec_helper'
describe Robot do
before :each do
@robot = Robot.new
end
describe "#shield" do
it "should be 50" do
expect(@robot.shield_points).to eq(50)
end
end
describe "#charge" do
it "should charge battery if below 50" do
enemy = Robot.new
enemy.attack(@robot)
@robot.pick_up(Battery.new)
expect(@robot.shield_points).to eq(50)
end
end
describe "damage to health - shield from laser" do
it "should damage health after shield has been depleted" do
enemytank = Robot.new
enemytank.pick_up(Laser.new)
enemytank.attack(@robot)
expect(@robot.health).to eq(95)
end
end
end
|
FactoryBot.define do
factory :book do
title { Faker::Book.title }
author { Faker::Book.author }
image { Faker::Avatar.image }
end
end
|
# frozen_string_literal: true
class CreateIncidents < ActiveRecord::Migration[5.2]
def change
create_table :incidents do |t|
t.string :number
t.string :slug
t.string :title
t.text :description
t.references :user, foreign_key: true
t.integer :status
t.datetime :pending
t.references :group, foreign_key: true, default: 1
t.references :category, foreign_key: true, default: 1
t.string :attachment
t.text :comment
t.string :step, default: 'new'
t.integer :creator_id
t.integer :modifier_id
t.timestamps
end
add_index :incidents, :slug, unique: true
end
end
|
class CalculationSerializer < BaseSerializer
attributes :id, :result, :virtual
def id
object.id.to_s
end
def result
object.result * object.result
end
def virtual
'virtual'
end
end
|
class Product < ActiveRecord::Base
has_and_belongs_to_many :troves
def update_from_shopsense
attributes = Shopsense.find_by_shopsense_id(self.shopsense_id)
self.update(attributes)
end
end
|
Rails.application.routes.draw do
devise_for :users, controllers: { sessions: "users/sessions" }
get 'static_pages/home'
get '/profile', to: 'static_pages#profile'
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
root 'static_pages#home'
end
|
class Part < ActiveRecord::Base
belongs_to :project
belongs_to :user
has_many :comments, -> { where(:archived => false) }, :as => :commentable, :dependent => :destroy
has_many :all_comments, :as => :commentable, :dependent => :destroy, :class_name => "Comment"
has_many :suggestions, :dependent => :destroy
has_many :versions, :dependent => :destroy
validates :title, :presence => true
validates :user, :presence => true
def cut_version!
version = versions.create!(:content => content)
all_comments.where(:version_id => nil).update_all(:version_id => version)
version
end
end
|
module HttpAuthConcern
extend ActiveSupport::Concern
included do
before_action :http_authenticate
end
def http_authenticate
return true unless Rails.env == 'production'
authenticate_or_request_with_http_basic do |username, password|
username == 'username' && password == 'password'
end
end
end |
require './app/aircraft.rb'
describe Aircraft do
let(:aircraft){Aircraft.new(:name=>'Boeing737',
:number_of_seats=>787)}
let(:tiny_aircraft){Aircraft.new(:name=>'Tiny1',
:number_of_seats=>1)}
it 'should be able to initialize the aircraft' do
expect(aircraft.number_of_seats).to eq(787)
expect(aircraft.name).to eq("Boeing737")
end
it 'should be full after all seats are taken' do
tiny_aircraft.add_passanger
expect(tiny_aircraft.full?).to be(true)
end
end |
require 'spec_helper'
require 'belafonte/argument'
module Belafonte
describe Argument do
describe '.new' do
it 'requires a name' do
expect {described_class.new}.
to raise_error(Belafonte::Errors::NoName, "Arguments must be named")
expect {described_class.new(name: :jump)}.
not_to raise_error
end
it 'is one occurrence by default' do
argument = described_class.new(name: :jump)
expect(argument.times).to eql(1)
end
it 'can have an unlimited number of occurrences' do
argument = described_class.new(name: :jump, times: :unlimited)
expect(argument.times).to eql(-1)
end
it 'can have an explicit number of occurrences' do
argument = described_class.new(name: :jump, times: 2)
expect(argument.times).to eql(2)
end
it 'requires that explicit occurrences be at least 1' do
expect {described_class.new(name: :jump, times: 0)}.
to raise_error(
Belafonte::Errors::InvalidArgument,
"There must be at least one occurrence"
)
end
it 'normalizes an explicit occurrence count to integer' do
arg = described_class.new(name: :jump, times: '10')
expect(arg.times).to eql(10)
end
it 'stores its name as a symbol' do
arg = described_class.new(name: 'jump')
expect(arg.name.to_sym).to eql(arg.name)
end
end
describe '#process' do
let(:argv) {["my", "girl's", "name", "is", "senora"]}
context 'for an unlimited argument' do
let(:argument) {described_class.new(name: :jump, times: :unlimited)}
it 'is a copy of the entire argv passed in' do
expect(argument.process(argv)).to eql(argv)
expect(argument.process(argv).object_id).not_to eql(argv.object_id)
end
end
context 'for a limited argument' do
let(:jump1) {described_class.new(name: :jump)}
let(:jump2) {described_class.new(name: :jump, times: 2)}
let(:jump5) {described_class.new(name: :jump, times: 5)}
let(:jump6) {described_class.new(name: :jump, times: 6)}
it 'is the first "times" items from the provided argv' do
expect(jump1.process(argv)).to eql(['my'])
expect(jump2.process(argv)).to eql(["my", "girl's"])
end
it 'raises an error if there are not enough argv items' do
expect {jump6.process(argv)}.
to raise_error(
Belafonte::Errors::TooFewArguments,
'Not enough arguments were given'
)
expect {jump5.process(argv)}.not_to raise_error
end
end
end
describe '#unlimited?' do
it 'is false if the argument is limited' do
expect(described_class.new(name: :jump).unlimited?).to eql(false)
end
it 'is true if the argument is unlimited' do
expect(described_class.new(name: :jump, times: :unlimited).unlimited?).
to eql(true)
end
end
end
end
|
# Research Methods
# I spent [] hours on this challenge.
i_want_pets = ["I", "want", 3, "pets", "but", "only", "have", 2]
my_family_pets_ages = {"Evi" => 6, "Ditto" => 3, "Hoobie" => 3, "George" => 12, "Bogart" => 4, "Poly" => 4, "Annabelle" => 0}
# Person 1
def my_array_finding_method(source, thing_to_find)
arrayWithMatchingWords = []
for x in 0..(source.length - 1)
sourceString = source[x].to_s
thing_to_findString = thing_to_find.to_s
# puts sourceString
# puts thing_to_findString
if sourceString.include? thing_to_findString
# puts 'entered'
arrayWithMatchingWords[arrayWithMatchingWords.length] = sourceString
end
end
# p arrayWithMatchingWords
return arrayWithMatchingWords
end
# my_array_finding_method(i_want_pets, 't')
def my_hash_finding_method(source, thing_to_find)
outputArrayNamesWithAgeMatch = []
source.each do |key, value|
if value.to_i == thing_to_find.to_i
outputArrayNamesWithAgeMatch[outputArrayNamesWithAgeMatch.length] = key
end
end
# p outputArrayNamesWithAgeMatch
return outputArrayNamesWithAgeMatch
end
# my_hash_finding_method(my_family_pets_ages, 3)
# Identify and describe the Ruby method(s) you implemented.
#
#
#
# Person 2
def my_array_modification_method!(source, thing_to_modify)
for x in 0..(source.length - 1)
if source[x].to_s =~ /\A[-+]?[0-9]+\z/
source[x] = source[x].to_i + thing_to_modify.to_i
end
end
# p source
return source
end
# my_array_modification_method!(i_want_pets, 2)
def my_hash_modification_method!(source, thing_to_modify)
source.each do |key, value|
source[key] = value.to_i + thing_to_modify.to_i
end
# p source
return source
end
# my_hash_modification_method!(my_family_pets_ages, 2)
# Identify and describe the Ruby method(s) you implemented.
#
#
#
# Person 3
def my_array_sorting_method(source)
sourceDup = source.dup
# p sourceDup.sort_by{|word| word.to_s}
return sourceDup.sort_by{|word| word.to_s}
end
# my_array_sorting_method(i_want_pets)
def my_array_sorting_method_hard(source)
orderedArray = []
characterAlphabetOrder = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z''a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
# Loop through input array
for x in 0..(source.length - 1)
#If orderedArray is empty
if x == 0
orderedArray[0] = source[x].to_s
#If orderedArray has components that need to be referenced
else
#Loop through what is currently in orderedArray
for y in 0..(orderedArray.length - 1)
shouldBreak = 'false'
#Loop through each leter in current orderedArray entry
for z in 0..((orderedArray[y].to_s).length - 1)
#If letter in orderedArray is lower in alphabet than letter of source
if characterAlphabetOrder.index(orderedArray[y].to_s[z]) >characterAlphabetOrder.index(source[x].to_s[z])
#shift orderedArray from index y over 1
orderedArray[y + 1,orderedArray.length] = orderedArray[y,orderedArray.length]
orderedArray[y] = source[x]
shouldBreak = 'true'
break
#If letter in orderedArray is higher in alphabet than letter of source and we are at end of orderedArray
elsif characterAlphabetOrder.index(orderedArray[y].to_s[z]) < characterAlphabetOrder.index(source[x].to_s[z]) && (orderedArray.length - 1) == y
#add to end of array
orderedArray[y + 1] = source[x]
shouldBreak = 'true'
break
#If word in orderedArray is same as word in source or is the beginning of word in source
elsif z == ((orderedArray[y].to_s).length - 1) && characterAlphabetOrder.index(orderedArray[y].to_s[z]) == characterAlphabetOrder.index(source[x].to_s[z])
#shift orderedArray from index y over 1
orderedArray[y + 1,orderedArray.length] = orderedArray[y,orderedArray.length]
orderedArray[y] = source[x]
shouldBreak = 'true'
break
#If letter in orderedArray is higher in alphabet than letter of source, move on to next word for checking
elsif characterAlphabetOrder.index(orderedArray[y].to_s[z]) < characterAlphabetOrder.index(source[x].to_s[z])
break
end
end
if shouldBreak == 'true'
break
end
end
end
end
# p orderedArray
return orderedArray
end
# my_array_sorting_method_hard(i_want_pets)
def my_hash_sorting_method(source)
sourceDup = source.dup
# p sourceDup.sort_by{|key, value| value}
return sourceDup.sort_by{|key, value| value}
end
# my_hash_sorting_method(my_family_pets_ages)
# Identify and describe the Ruby method(s) you implemented.
# .sort_by (http://ruby-doc.org/core-2.2.3/Enumerable.html#method-i-sort_by)
# .length (http://ruby-doc.org/core-2.2.0/Array.html#method-i-length)
# .dup (http://ruby-doc.org/core-2.2.3/Object.html#method-i-dup)
# .to_s (http://ruby-doc.org/core-2.2.3/Fixnum.html#method-i-to_s)
# Person 4
def my_array_deletion_method!(source, thing_to_delete)
indexChange = 0
for x in 0..(source.length - 1)
sourceString = source[x - indexChange].to_s
if sourceString.include? thing_to_delete
source[x - indexChange,source.length] = source[x + 1 - indexChange, source.length]
indexChange = indexChange + 1
end
end
# p source
return source
end
# my_array_deletion_method!(i_want_pets,'a')
# my_array_deletion_method!(i_want_pets,'t')
def my_hash_deletion_method!(source, thing_to_delete)
source.delete(thing_to_delete)
# puts source
return source
end
# my_hash_deletion_method!(my_family_pets_ages,'George')
# Identify and describe the Ruby method(s) you implemented.
#
#
#
# Person 5
def my_array_splitting_method(source)
arrayInt = []
arrayStr = []
for x in 0..(source.length - 1)
if source[x].to_s =~ /\A[-+]?[0-9]+\z/
arrayInt[arrayInt.length] = source[x].to_i
else
arrayStr[arrayStr.length] = source[x]
end
end
outputArray = [arrayInt, arrayStr]
# p outputArray
return outputArray
end
# my_array_splitting_method(i_want_pets)
def my_hash_splitting_method(source, age)
arrayInside = []
arrayOutside = []
source.each do |key, value|
if value.to_i <= age.to_i
arrayInside[arrayInside.length] = [key, value]
else
arrayOutside[arrayOutside.length] = [key, value]
end
end
outputArray = [arrayInside, arrayOutside]
# p outputArray
return outputArray
end
# my_hash_splitting_method(my_family_pets_ages, 4)
# Identify and describe the Ruby method(s) you implemented.
#
#
#
# Release 1: Identify and describe the Ruby method you implemented. Teach your
# accountability group how to use the methods.
#
#
#
# Release 3: Reflect!
# What did you learn about researching and explaining your research to others?
#
#
#
# |
class CuratorialsController < ApplicationController
before_action :logged_in_user, except: [:show, :index]
before_action :set_curatorial, only: [:show, :edit, :update, :destroy]
before_action :get_curatorial_years
before_action :get_writing_years
def new
@user = current_user
@curatorial = @user.curatorials.build if logged_in?
@curatorial_attachment = @curatorial.post_attachments.build
end
def admin
@user = current_user
@curatorials = @user.curatorials.page(params[:page]).per(20)
end
def index
if params[:upcoming]
filtered_curatorials = Curatorial.unscoped.where('start_date > ?', Date.today)
.order(start_date: :asc)
@page_title = "Upcoming Exhibitions"
elsif params[:year]
filtered_curatorials = Curatorial.where('cast(start_date as text) LIKE ? OR cast(end_date as text) LIKE ?',"%#{params[:year]}%","%#{params[:year]}%")
@page_title = "Exhibitions in #{params[:year]}"
else
filtered_curatorials = Curatorial.where('start_date <= ? AND end_date >= ?',
Date.today, Date.today)
@page_title = "Current Exhibitions"
end
@filtered_curatorials = filtered_curatorials.page(params[:page]).per(20)
end
def show
end
def create
@curatorial = current_user.curatorials.build(curatorial_params)
if @curatorial.save
unless params[:artists].empty?
params[:artists].each do |a|
artist = Artist.find_or_create_by(name: a)
@curatorial.exhibitions.create(artist_id: artist.id)
end
end
unless params[:post_attachments]['image'].nil?
params[:post_attachments]['image'].each do |a|
@curatorial_attachment = @curatorial.post_attachments.create!(image: a,
description: params[:post_attachments][:description])
end
end
flash[:success] = "Saved."
redirect_to new_news_item_path
else
flash.now[:alert] = "Error saving post."
render 'new'
end
end
def edit
@edit_artists = @curatorial.artists
end
def update
if @curatorial.update_attributes(curatorial_params)
unless params[:artists].empty?
params[:artists].each do |a|
artist = Artist.find_or_create_by(name: a)
@curatorial.exhibitions.create(artist_id: artist.id)
end
end
flash[:success] = "Post updated"
redirect_to admin_curatorials_path
else
render 'edit'
end
end
def destroy
@curatorial.destroy
redirect_to admin_curatorials_path
end
private
def curatorial_params
params.require(:curatorial).permit(:slug, :project_name, :artists, :artist_name, :venue, :start_date, :end_date, :genericize_date, :link, :about, post_attachments: [:id, :curatorial_id, :image, :description])
end
def set_curatorial
@curatorial = Curatorial.find_by_slug(params[:id])
end
end
|
class ChangeSaleAdjustedPagesToInteger < ActiveRecord::Migration
def change
change_column :sales, :adjusted_page_count, :integer
end
end
|
module Twine
module Formatters
class JQuery < Abstract
def format_name
'jquery'
end
def extension
'.json'
end
def default_file_name
'localize.json'
end
def determine_language_given_path(path)
match = /^.+-([^-]{2})\.json$/.match File.basename(path)
return match[1] if match
return super
end
def set_translation_for_key_recursive(key, lang, value)
if value.is_a?(Hash)
value.each do |key2, value2|
set_translation_for_key_recursive(key+"."+key2, lang, value2)
end
else
set_translation_for_key(key, lang, value)
end
end
def read(io, lang)
begin
require "json"
rescue LoadError
raise Twine::Error.new "You must run `gem install json` in order to read or write jquery-localize files."
end
json = JSON.load(io)
json.each do |key, value|
set_translation_for_key_recursive(key, lang, value)
end
end
def format_file(lang)
result = super
return result unless result
"{\n#{super}\n}\n"
end
def format_sections(twine_file, lang)
sections = twine_file.sections.map { |section| format_section(section, lang) }
sections.delete_if(&:empty?)
sections.join(",\n\n")
end
def format_section_header(section)
end
def format_section(section, lang)
definitions = section.definitions.dup
definitions.map! { |definition| format_definition(definition, lang) }
definitions.compact! # remove nil definitions
definitions.join(",\n")
end
def key_value_pattern
"\"%{key}\":\"%{value}\""
end
def format_key(key)
escape_quotes(key)
end
def format_value(value)
escape_quotes(value)
end
end
end
end
Twine::Formatters.formatters << Twine::Formatters::JQuery.new
|
require 'rails_helper'
RSpec.describe 'Weapons', type: :request do
describe 'GET /show' do
it 'show attributes' do
attributes = FactoryBot.attributes_for(:weapon, name: 'textweapon', description: 'descweapon')
post(weapons_path, params: { weapon: attributes })
get weapon_path(Weapon.last)
expect(response.body).to include('textweapon', 'descweapon')
end
end
describe 'DELETE /destroy' do
it 'delete weapon' do
weap = build(:weapon)
weap.save
expect do
delete "/weapons/#{weap.id}"
end.to change(Weapon, :count)
end
end
describe 'GET /index' do
it 'should display the names correctly' do
name = Faker::Name.first_name
weap = build(:weapon, name: name)
weap.save
get weapons_path
expect(response.body).to include(name)
end
it 'should display the current_power correctly' do
weap = build(:weapon, power_base: 3000, level: 1)
weap.save
get weapons_path
expect(response.body).to include('3000')
end
it 'should display the titles correctly' do
weap = build(:weapon, name: 'excalibur', level: 1)
weap.save
get weapons_path
expect(response.body).to include('excalibur #1')
end
end
describe 'POST /create' do
it 'correct parameters create' do
attributes = FactoryBot.attributes_for(:weapon)
expect do
post(weapons_path, params: { weapon: attributes })
end.to change(Weapon, :count)
end
it 'invalid parameters does not create' do
attributes = FactoryBot.attributes_for(:weapon, name: '12')
expect do
post(weapons_path, params: { weapon: attributes })
end.to_not change(Weapon, :count)
end
end
end
RSpec.describe 'Weapons', type: :routing do
it 'should display the links correctly' do
weap = build(:weapon)
weap.save
expect(get: weapons_path).to route_to("controller": 'weapons', "action": 'index')
end
end
|
class UsersController < ApplicationController
before_action :confirm_logged_in, only: [:edit, :update, :show]
before_action :find_user_from_session, only: [:edit, :update, :show]
layout 'dashboard', only: [:show]
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
session[:id] = @user.id
redirect_to dashboard_path, notice: new_user
else
flash.now[:notice] = sign_up_error
render 'new'
end
end
def show
@link = Link.find_by(id: params[:link_id])
@links = @user.links
end
private
def user_params
params.require(:user).permit(:first_name, :last_name, :email,
:password, :password_confirmation)
end
def find_user_from_session
@user = User.find(session[:id])
end
end
|
module Yito
module Model
module Booking
module ActivityQueries
def self.extended(model)
model.extend ClassMethods
end
module ClassMethods
#
# Search booking by text (customer surname, phone, email)
#
def text_search(search_text, offset_order_query={})
if DataMapper::Adapters.const_defined?(:PostgresAdapter) and repository.adapter.is_a?DataMapper::Adapters::PostgresAdapter
[query_strategy.count_text_search(search_text),
query_strategy.text_search(search_text, offset_order_query)]
else
conditions = Conditions::JoinComparison.new('$or',
[Conditions::Comparison.new(:id, '$eq', search_text.to_i),
Conditions::Comparison.new(:customer_name, '$like', "%#{search_text}%"),
Conditions::Comparison.new(:customer_surname, '$like', "%#{search_text}%"),
Conditions::Comparison.new(:customer_email, '$eq', search_text),
Conditions::Comparison.new(:customer_phone, '$eq', search_text),
Conditions::Comparison.new(:customer_mobile_phone, '$eq', search_text)])
total = conditions.build_datamapper(::Yito::Model::Order::Order).all.count
data = conditions.build_datamapper(::Yito::Model::Order::Order).all(offset_order_query)
[total, data]
end
end
def count_start(date)
sql = <<-SQL
select count(distinct oi.date, oi.time, oi.item_id)
from orderds_orders o
join orderds_order_items oi on oi.order_id = o.id
join bookds_activities a on a.code = oi.item_id
where o.status in (2) and oi.date = ?
group by oi.date, oi.time, oi.date_to, oi.time_to, oi.item_id, oi.item_description, a.schedule_color, a.duration_days, a.duration_hours
order by oi.date desc, oi.time desc, oi.item_id
SQL
programmed_activities = repository.adapter.select(sql, date).first || 0
end
def count_received_orders(year)
query_strategy.count_received_orders(year)
end
def count_pending_confirmation_orders(year)
query_strategy.count_pending_confirmation_orders(year)
end
def count_confirmed_orders(year)
query_strategy.count_confirmed_orders(year)
end
def activities_by_category(year)
data = query_strategy.activities_by_category(year)
result = data.inject({}) do |result, value|
result.store(value.item_id, {value: value.count,
color: "#%06x" % (rand * 0xffffff),
highlight: "#%06x" % (rand * 0xffffff),
label: value.item_id})
result
end
result
end
def activities_by_status(year)
data = query_strategy.activities_by_status(year)
result = data.inject({}) do |result, value|
status = case value.status
when 1
BookingDataSystem.r18n.t.booking_status.pending_confirmation
when 2
BookingDataSystem.r18n.t.booking_status.confirmed
when 3
BookingDataSystem.r18n.t.booking_status.cancelled
end
color = case value.status
when 1
'yellow'
when 2
'green'
when 3
'red'
end
result.store(status, {value: value.count,
color: color,
highlight: "#%06x" % (rand * 0xffffff),
label: status})
result
end
result
end
def activities_by_weekday(year)
data = query_strategy.activities_by_weekday(year)
result = data.inject({}) do |result, value|
result.store(value.day.to_i.to_s, value.count)
result
end
(0..6).each do |item|
result.store(item.to_s, 0) unless result.has_key?(item.to_s)
end
result
end
def last_30_days_activities
months = ['E','F','M','A','My','J','Jl','A','S','O','N','D']
result = {}
(0..29).reverse_each do |item|
today = Date.today - item
key = "#{today.day}#{months[today.month-1]}"
result.store(key, 0)
end
data = query_strategy.last_30_days_activities
data.each do |item|
today = Date.today - item.period
key = "#{today.day}#{months[today.month-1]}"
result.store(key, item.occurrences) if result.has_key?(key)
result
end
result
end
#
# Get the products total billing
#
def activities_billing_total(year)
query_strategy.activities_billing_total(year).first
end
#
# Total amount
#
def total_should_charged(date_from, date_to)
query = <<-QUERY
select sum(o.total_cost)
from orderds_orders o
join orderds_order_items oi on oi.order_id = o.id
WHERE oi.date >= ? and date <= ? and
o.status NOT IN (1,3)
QUERY
repository.adapter.select(query, date_from, date_to).first
end
#
# Get the total charged amount for a year
#
def total_charged(year)
data = query_strategy.total_charged(year)
detail = data.inject({}) do |result, value|
result.store(value.payment_method, {value: value.total,
color: "#%06x" % (rand * 0xffffff),
highlight: "#%06x" % (rand * 0xffffff),
label: Payments.r18n.t.payment_methods[value.payment_method.to_sym]})
result
end
result = {total: 0, detail: detail}
data.each { |item| result[:total] += item.total}
return result
end
#
# Get the forecast charged for a period
#
def forecast_charged(date_from, date_to)
result = {total: 0, detail: {}}
month = date_from.month
year = date_from.year
last_month = date_to.month
last_year = date_to.year
until (month == last_month && year == last_year) do
result[:detail].store("#{year}-#{month.to_s.rjust(2, '0')}", 0)
if month == 12
month = 1
year += 1
else
month += 1
end
end
data = query_strategy.forecast_charged(date_from, date_to)
data.each do |item|
result[:total] += item.total
result[:detail][item.period] += item.total
end
return result
end
#
# Get the activity detail
#
def activity_detail(date, time, item_id)
sql =<<-SQL
select o_i.id, o_i.date, o_i.time, o_i.item_id, o_i.item_description,
o_i.item_price_description,
o_i.quantity, o_i.item_unit_cost, o_i.item_cost, o_i.item_price_type,
o_i.comments, o_i.notes, o_i.custom_customers_pickup_place, o_i.customers_pickup_place,
o.id as order_id, o.customer_name, o.customer_surname, o.customer_email,
o.customer_phone, o.comments as order_comments,
case o.status
when 1 then 'pending_confirmation'
when 2 then 'confirmed'
when 3 then 'cancelled'
end as status,
a.capacity
from orderds_order_items o_i
join orderds_orders o on o.id = o_i.order_id
join bookds_activities a on a.code = o_i.item_id
where o_i.date = ? and o_i.time = ? and o_i.item_id = ? and o.status not in (3)
order by o_i.date, o_i.time, o_i.item_id, o.customer_surname, o.customer_name
SQL
orders = repository.adapter.select(sql, date, time, item_id)
return orders
end
#
# Get the activities that start on one date
#
def activities(date)
sql =<<-SQL
select o_i.id, o_i.date, o_i.time, o_i.item_id, o_i.item_description,
o_i.item_price_description,
o_i.quantity, o_i.item_unit_cost, o_i.item_cost, o_i.item_price_type,
o_i.comments, o_i.notes, o_i.customers_pickup_place,
o.id as order_id, o.customer_name, o.customer_surname, o.customer_email,
o.customer_phone, o.comments as order_comments,
case o.status
when 1 then 'pending_confirmation'
when 2 then 'confirmed'
when 3 then 'cancelled'
end as status,
a.capacity
from orderds_order_items o_i
join orderds_orders o on o.id = o_i.order_id
join bookds_activities a on a.code = o_i.item_id
where o.status NOT IN (3) and o_i.date = ?
order by o_i.date, o_i.time, o_i.item_id, o.customer_surname, o.customer_name
SQL
orders = repository.adapter.select(sql, date)
end
#
# Get the activities summary between two dates
#
def activities_summary(date_from, date_to)
sql =<<-SQL
select o_i.id, o_i.date, o_i.time, o_i.item_id, o_i.item_description,
o_i.item_price_description,
o_i.quantity, o_i.item_unit_cost, o_i.item_cost, o_i.item_price_type,
o_i.comments,
o.id as order_id, o.customer_name, o.customer_surname, o.customer_email,
o.customer_phone, o.comments as order_comments,
case o.status
when 1 then 'pending_confirmation'
when 2 then 'confirmed'
when 3 then 'cancelled'
end as status,
a.capacity
from orderds_order_items o_i
join orderds_orders o on o.id = o_i.order_id
join bookds_activities a on a.code = o_i.item_id
where o.status NOT IN (1,3) and o_i.date >= ? and o_i.date <= ?
order by o_i.date, o_i.time, o_i.item_id, o.customer_surname, o.customer_name
SQL
orders = repository.adapter.select(sql, date_from, date_to)
end
#
# Get programmed activities between two dates.
#
# They represent the activities that have any confirmation
#
def programmed_activities_plus_pending(date_from, date_to)
sql = <<-SQL
select oi.date, oi.time, oi.date_to, oi.time_to, oi.item_id, CAST (oi.status as UNSIGNED) as status,
oi.item_description, sum(oi.quantity) as occupation,
a.schedule_color, a.duration_days, a.duration_hours
from orderds_orders o
join orderds_order_items oi on oi.order_id = o.id
join bookds_activities a on a.code = oi.item_id
where o.status in (1,2) and oi.date >= ? and oi.date <= ?
group by oi.date, oi.time, oi.date_to, oi.time_to, oi.item_id, oi.item_description, a.schedule_color, a.duration_days, a.duration_hours, oi.status
order by oi.date asc, oi.time asc, oi.item_id
SQL
activities = repository.adapter.select(sql, date_from, date_to).inject([]) do |result, value|
index = result.index { |x| x.date == value.date and x.time == value.time and
x.date_to == value.date_to and x.time_to == value.time_to and
x.item_id == value.item_id and x.schedule_color == value.schedule_color and
x.duration_days == value.duration_days and x.duration_hours == value.duration_hours
}
if index
if value.status == 1
result[index].pending_confirmation = value.occupation
elsif value.status == 2
result[index].confirmed = value.occupation
end
else
data = {date: value.date,
time: value.time,
date_to: value.date_to,
time_to: value.time_to,
item_id: value.item_id,
item_description: value.item_description,
schedule_color: value.schedule_color,
duration_days: value.duration_days,
duration_hours: value.duration_hours,
pending_confirmation: (value.status == 1 ? value.occupation : 0),
confirmed: (value.status == 2 ? value.occupation : 0),
}
result << OpenStruct.new(data)
end
result
end
end
#
# Get programmed activities between two dates.
#
# They represent the activities that have any confirmation
#
def programmed_activities(date_from, date_to)
sql = <<-SQL
select oi.date, oi.time, oi.date_to, oi.time_to, oi.item_id,
oi.item_description, sum(oi.quantity) as occupation,
a.schedule_color, a.duration_days, a.duration_hours
from orderds_orders o
join orderds_order_items oi on oi.order_id = o.id
join bookds_activities a on a.code = oi.item_id
where o.status in (2) and oi.date >= ? and oi.date <= ?
group by oi.date, oi.time, oi.date_to, oi.time_to, oi.item_id, oi.item_description, a.schedule_color, a.duration_days, a.duration_hours
order by oi.date asc, oi.time asc, oi.item_id
SQL
programmed_activities = repository.adapter.select(sql, date_from, date_to)
end
#
# Get the public active programmed activities
#
def public_programmed_activities(date_from)
sql = <<-SQL
select oi.date, oi.time, oi.date_to, oi.time_to, oi.item_id,
oi.item_description, sum(oi.quantity) as occupation
from orderds_orders o
join orderds_order_items oi on oi.order_id = o.id
join bookds_activities a on a.code = oi.item_id
where o.status in (2) and oi.date > ?
group by oi.date, oi.time, oi.date_to, oi.time_to, oi.item_id,
oi.item_description
order by oi.date asc, oi.time asc, oi.item_id
SQL
programmed_activities = repository.adapter.select(sql, date_from)
end
#
# Get the occupation detail of activities that occurs once
#
def one_time_occupation_detail(month, year)
date_from = Date.civil(year, month, 1)
date_to = Date.civil(year, month, -1)
result = {}
# Get planned activities
condition = Conditions::JoinComparison.new('$and',
[Conditions::Comparison.new(:date,'$gte', date_from),
Conditions::Comparison.new(:date,'$lte', date_to)
])
planned_activities = condition.build_datamapper(::Yito::Model::Booking::PlannedActivity).all(
:order => [:date, :time, :activity_code]
)
# Build the structure
activities = ::Yito::Model::Booking::Activity.all(#:active => true,
:occurence => :one_time,
:date_from.gte => date_from,
:date_from.lte => date_to)
activities.each do |activity|
# Build item prices hash
item_prices = {}
if activity.number_of_item_price > 0
(1..activity.number_of_item_price).each do |item_price|
item_prices.store(item_price, 0)
end
end
# Fill with the activity turns
activity_detail = {}
activity.one_time_timetable.each do |turn|
# Build days hash
days = {}
(1..(date_to.day)).each do |day|
date = Date.civil(year, month, day)
modified_capacity = planned_activities.select do |item|
item.date.strftime('%Y-%m-%d') == date.strftime('%Y-%m-%d') and
item.time == turn and
item.activity_code == activity.code
end
real_capacity = modified_capacity.size > 0 ? modified_capacity.first.capacity : activity.capacity
if activity.start_date?(date)
days.store(day, {quantity: (item_prices.empty? ? 0 : item_prices.clone),
pending_confirmation: (item_prices.empty? ? 0 : item_prices.clone),
capacity: real_capacity,
planned: true})
else
days.store(day, {quantity: '-',
pending_confirmation: (item_prices.empty? ? 0 : item_prices.clone),
capacity: real_capacity,
planned: false})
end
end
activity_detail.store(turn, days)
end
# Store the item
result.store(activity.code, {name: activity.name,
capacity: activity.capacity,
price_literals: activity.price_definition_detail,
number_of_item_price: activity.number_of_item_price,
occupation: activity_detail})
end
sql =<<-SQL
select o_i.item_id, o_i.date, o_i.time, o_i.item_price_type, CAST (o_i.status AS UNSIGNED) as status, sum(quantity) as quantity
from orderds_order_items o_i
join orderds_orders o on o.id = o_i.order_id
join bookds_activities a on a.code = o_i.item_id
where o.status NOT IN (3) and o_i.date >= ? and o_i.date <= ? and
a.occurence IN (1)
group by o_i.item_id, o_i.date, o_i.time, o_i.item_price_type, o_i.status
SQL
# Fill with the orders
orders = repository.adapter.select(sql, date_from, date_to)
orders.each do |order|
if result[order.item_id] and
result[order.item_id][:occupation] and
result[order.item_id][:occupation][order.time] and
result[order.item_id][:occupation][order.time][order.date.day] and
result[order.item_id][:occupation][order.time][order.date.day][:quantity][order.item_price_type] and
result[order.item_id][:occupation][order.time][order.date.day][:pending_confirmation][order.item_price_type]
result[order.item_id][:occupation][order.time][order.date.day][:pending_confirmation][order.item_price_type] += order.quantity if order.status == 1
result[order.item_id][:occupation][order.time][order.date.day][:quantity][order.item_price_type] += order.quantity if order.status == 2
end
end
return result
end
#
# Get the occupation detail of activities that occurs multiple dates
#
def multiple_dates_occupation_detail(month, year)
date_from = Date.civil(year, month, 1)
date_to = Date.civil(year, month, -1)
result = {}
# Get planned activities
condition = Conditions::JoinComparison.new('$and',
[Conditions::Comparison.new(:date,'$gte', date_from),
Conditions::Comparison.new(:date,'$lte', date_to)
])
planned_activities = condition.build_datamapper(::Yito::Model::Booking::PlannedActivity).all(
:order => [:date, :time, :activity_code]
)
# Build the structure
activities = ::Yito::Model::Booking::Activity.all(#:active => true,
:occurence => :multiple_dates,
'activity_dates.date_from.gte'.to_sym => date_from,
'activity_dates.date_from.lte'.to_sym => date_to)
activities.each do |activity|
# Build item prices hash
item_prices = {}
if activity.number_of_item_price > 0
(1..activity.number_of_item_price).each do |item_price|
item_prices.store(item_price, 0)
end
end
# Fill with the activity turns
activity_detail = {}
activity.multiple_dates_timetable.each do |turn|
# Build days hash
days = {}
(1..(date_to.day)).each do |day|
date = Date.civil(year, month, day)
modified_capacity = planned_activities.select do |item|
item.date.strftime('%Y-%m-%d') == date.strftime('%Y-%m-%d') and
item.time == turn and
item.activity_code == activity.code
end
real_capacity = modified_capacity.size > 0 ? modified_capacity.first.capacity : activity.capacity
if activity.start_date?(date)
days.store(day, {quantity: (item_prices.empty? ? 0 : item_prices.clone),
pending_confirmation: (item_prices.empty? ? 0 : item_prices.clone),
capacity: real_capacity,
planned: true})
else
days.store(day, {quantity: '-',
pending_confirmation: (item_prices.empty? ? 0 : item_prices.clone),
capacity: real_capacity,
planned: false})
end
end
activity_detail.store(turn, days)
end
# Store the item
result.store(activity.code, {name: activity.name,
capacity: activity.capacity,
price_literals: activity.price_definition_detail,
number_of_item_price: activity.number_of_item_price,
occupation: activity_detail})
end
sql =<<-SQL
select o_i.item_id, o_i.date, o_i.time, o_i.item_price_type, CAST (o_i.status AS UNSIGNED) as status, sum(quantity) as quantity
from orderds_order_items o_i
join orderds_orders o on o.id = o_i.order_id
join bookds_activities a on a.code = o_i.item_id
where o.status NOT IN (3) and o_i.date >= ? and o_i.date <= ? and
a.occurence IN (2)
group by o_i.item_id, o_i.date, o_i.time, o_i.item_price_type, o_i.status
SQL
# Fill with the orders
orders = repository.adapter.select(sql, date_from, date_to)
orders.each do |order|
if result[order.item_id] and
result[order.item_id][:occupation] and
result[order.item_id][:occupation][order.time] and
result[order.item_id][:occupation][order.time][order.date.day] and
result[order.item_id][:occupation][order.time][order.date.day][:quantity][order.item_price_type] and
result[order.item_id][:occupation][order.time][order.date.day][:pending_confirmation][order.item_price_type]
result[order.item_id][:occupation][order.time][order.date.day][:pending_confirmation][order.item_price_type] += order.quantity if order.status == 1
result[order.item_id][:occupation][order.time][order.date.day][:quantity][order.item_price_type] += order.quantity if order.status == 2
end
end
return result
end
#
# Get the occupation detail of cyclic activities
#
def cyclic_occupation_detail(month, year)
date_from = Date.civil(year, month, 1)
date_to = Date.civil(year, month, -1)
result = {}
# Get planned activities
condition = Conditions::JoinComparison.new('$and',
[Conditions::Comparison.new(:date,'$gte', date_from),
Conditions::Comparison.new(:date,'$lte', date_to)
])
planned_activities = condition.build_datamapper(::Yito::Model::Booking::PlannedActivity).all(
:order => [:date, :time, :activity_code]
)
# Build the structure
activities = ::Yito::Model::Booking::Activity.all(active: true, occurence: :cyclic)
activities.each do |activity|
# Build item prices hash
item_prices = {}
if activity.number_of_item_price > 0
(1..activity.number_of_item_price).each do |item_price|
item_prices.store(item_price, 0)
end
end
# Fill with the activity turns
activity_detail = {}
activity.cyclic_turns_summary.each do |turn|
# Build days hash
days = {}
(1..(date_to.day)).each do |day|
date = Date.civil(year, month, day)
modified_capacity = planned_activities.select do |item|
item.date.strftime('%Y-%m-%d') == date.strftime('%Y-%m-%d') and
item.time == turn and
item.activity_code == activity.code
end
real_capacity = modified_capacity.size > 0 ? modified_capacity.first.capacity : activity.capacity
if activity.cyclic_planned?(date.wday)
days.store(day, {quantity: (item_prices.empty? ? 0 : item_prices.clone),
pending_confirmation: (item_prices.empty? ? 0 : item_prices.clone),
capacity: real_capacity,
planned: true})
else
days.store(day, {quantity: '-',
pending_confirmation: (item_prices.empty? ? 0 : item_prices.clone),
capacity: real_capacity,
planned: false})
end
end
activity_detail.store(turn, days)
end
# Store the item
result.store(activity.code, {name: activity.name,
capacity: activity.capacity,
price_literals: activity.price_definition_detail,
number_of_item_price: activity.number_of_item_price,
occupation: activity_detail})
end
# Fill with the orders
sql =<<-SQL
select o_i.item_id, o_i.date, o_i.time, o_i.item_price_type, CAST (o_i.status AS UNSIGNED) as status, sum(quantity) as quantity
from orderds_order_items o_i
join orderds_orders o on o.id = o_i.order_id
join bookds_activities a on a.code = o_i.item_id
where o.status NOT IN (3) and o_i.date >= ? and o_i.date <= ? and
a.occurence IN (3)
group by o_i.item_id, o_i.date, o_i.time, o_i.item_price_type, o_i.status
SQL
orders = repository.adapter.select(sql, date_from, date_to)
orders.each do |order|
if result[order.item_id] and
result[order.item_id][:occupation] and
result[order.item_id][:occupation][order.time] and
result[order.item_id][:occupation][order.time][order.date.day]
# Prepare not planned activities that have been ordered
if result[order.item_id][:occupation][order.time][order.date.day][:quantity] == '-'
activity = ::Yito::Model::Booking::Activity.first(code: order.item_id)
item_prices = {}
if activity.number_of_item_price > 0
(1..activity.number_of_item_price).each do |item_price|
item_prices.store(item_price, 0)
end
end
result[order.item_id][:occupation][order.time][order.date.day][:quantity] = item_prices
end
if result[order.item_id][:occupation][order.time][order.date.day][:quantity][order.item_price_type] and
result[order.item_id][:occupation][order.time][order.date.day][:pending_confirmation][order.item_price_type]
result[order.item_id][:occupation][order.time][order.date.day][:pending_confirmation][order.item_price_type] += order.quantity if order.status == 1
result[order.item_id][:occupation][order.time][order.date.day][:quantity][order.item_price_type] += order.quantity if order.status == 2
end
end
end
# Result
result
end
end
def pending_of_confirmation(opts={})
orders = ::Yito::Model::Order::Order.by_sql { |o| select_pending_confirmation(o) }.all({order: :creation_date}.merge(opts))
end
def start_on_date(date, opts={})
orders = ::Yito::Model::Order::Order.by_sql { |o| select_start_on_date(o, date) }.all({order: :creation_date}.merge(opts))
end
private
def query_strategy
# Removed for multi-tenant solution
#@query_strategy ||=
if DataMapper::Adapters.const_defined?(:PostgresAdapter) and repository.adapter.is_a?DataMapper::Adapters::PostgresAdapter
PostgresqlActivityQueries.new(repository)
else
if DataMapper::Adapters.const_defined?(:MysqlAdapter) and repository.adapter.is_a?DataMapper::Adapters::MysqlAdapter
MySQLActivityQueries.new(repository)
else
if DataMapper::Adapters.const_defined?(:SqliteAdapter) and repository.adapter.is_a?DataMapper::Adapters::SqliteAdapter
SQLiteActivityQueries.new(repository)
end
end
end
end
def select_pending_confirmation(o)
sql = <<-QUERY
select #{o.*}
FROM #{o}
where #{o.status} = 1 and #{o.id} in (select order_id from orderds_order_items oi where oi.date >= '#{Date.today.strftime("%Y-%m-%d")}')
QUERY
end
def select_start_on_date(o, date)
sql = <<-QUERY
select #{o.*}
FROM #{o}
where #{o.status} = 2 and #{o.id} in (select order_id from orderds_order_items oi where oi.date = '#{date.strftime("%Y-%m-%d")}')
QUERY
end
end
end
end
end |
require 'capybara/cucumber'
require 'capybara-screenshot/cucumber'
require 'base64'
Before do |scenario|
Capybara::Screenshot.final_session_name = nil
end
After do |scenario|
if Capybara::Screenshot.autosave_on_failure && scenario.failed?
Capybara.using_session(Capybara::Screenshot.final_session_name) do
filename_prefix = Capybara::Screenshot.filename_prefix_for(:cucumber, scenario)
saver = Capybara::Screenshot::Saver.new(Capybara, Capybara.page, true, filename_prefix)
saver.save
# Embed screenshot into report
if File.exist?(saver.screenshot_path)
image = open(saver.screenshot_path, 'rb') {|io|io.read}
encoded_img = Base64.encode64(image)
embed(encoded_img, 'image/png;base64', "#{filename_prefix}")
end
end
end
# Close all web browser windows
page.driver.browser.window_handles.each do |handle|
page.driver.browser.switch_to.window(handle)
page.execute_script 'window.close()'
end
end
|
require File.join(File.dirname(__FILE__), 'BaiduPage')
module SearchBehavior
def visit_Baidu
@page = BaiduPage.new(@browser)
end
def user_text user_str
@page.send_key user_str
end
def user_click
@page.click_search
end
def assert_text_exist title_text
@page.has_text title_text
end
end |
class ProductAsset < ActiveRecord::Base
belongs_to :product
validates :photo,
attachment_content_type: { content_type: /\Aimage\/.*\Z/ },
attachment_size: { less_than: 5.megabytes }
has_attached_file :photo, styles: {
thumb: '100x100>',
square: '200x200#',
medium: '300x300>'
}
end
|
module JobsCrawler::Robots
class Base
attr_reader :url
def initialize(url)
@url = url
@engine = Mechanize.new
end
def crawl
set_html
to_json
end
def extract_content(css_selector)
@html.css(css_selector).text
end
def to_json
raise NotImplemetedError, 'You need to provide a concrete implemetatioen'
end
def set_html
@html = Nokogiri::HTML(body)
end
private
def body
@engine.get(url).body
end
end
end
|
class TrustUpdateService
def update_trusts(last_update: nil)
# look at the trusts that have changed since the last update
last_update ||= DataStage::DataUpdateRecord.last_update_for(:trusts)
# create new trusts
create_trusts
# simple updates for trusts that are open
update_open_trusts(last_update)
# auto close trusts that have no schools
# skip and notify sentry when a trust is closed and still has schools - needs investigation
close_trusts
DataStage::DataUpdateRecord.updated!(:trusts)
end
private
def create_trusts
existing_trust_ids = Trust.pluck(:companies_house_number)
DataStage::Trust.gias_status_open.where.not(companies_house_number: existing_trust_ids).find_each do |staged_trust|
create_trust(staged_trust)
end
end
def update_open_trusts(last_update)
DataStage::Trust.updated_since(last_update).gias_status_open.each do |staged_trust|
trust = Trust.find_by(companies_house_number: staged_trust.companies_house_number)
next unless trust
update_trust(trust, staged_trust)
end
end
def close_trusts
trusts_with_schools = []
DataStage::Trust.gias_status_closed.each do |staged_trust|
trust = Trust.find_by(companies_house_number: staged_trust.companies_house_number)
next if !trust || trust.status == 'closed'
if trust.schools.any?
trusts_with_schools << trust.id
else
close_trust(trust)
end
end
return if trusts_with_schools.empty?
Sentry.configure_scope do |scope|
scope.set_context('TrustUpdateService#close_trusts', { trust_ids: trusts_with_schools })
Sentry.capture_message('Skipped auto-closing Trusts as schools.size > 0')
end
end
def update_trust(trust, staged_trust)
attrs = staged_attributes(staged_trust)
trust.update!(attrs)
rescue ActiveRecord::RecordInvalid => e
Rails.logger.error(e.record.errors)
end
def create_trust(staged_trust)
attrs = staged_attributes(staged_trust)
Trust.create!(attrs)
rescue ActiveRecord::RecordInvalid => e
Rails.logger.error(e.record.errors)
end
def close_trust(trust)
trust.update!({ status: 'closed', computacenter_change: 'closed' })
rescue ActiveRecord::RecordInvalid => e
Rails.logger.error(e.record.errors)
end
def staged_attributes(staged_trust)
staged_trust.attributes.except('id', 'created_at', 'updated_at')
end
end
|
# frozen_string_literal: true
module EMIS
module Models
class GuardReserveServicePeriod
include Virtus.model
attribute :segment_identifier, String
attribute :begin_date, Date
attribute :end_date, Date
attribute :termination_reason, String
attribute :character_of_service_code, String
attribute :narrative_reason_for_separation_code, String
attribute :statute_code, String
attribute :project_code, String
attribute :post_911_gibill_loss_category_code, String
attribute :training_indicator_code, String
end
end
end
|
require 'anniversary_checker'
require 'git_interface'
class App
DEFAULT_COMMITS_BETWEEN_ADIVS = 1000
def self.run(config)
Dir.chdir config[:git_path]
git_interface = config[:git_interface] || default_git_interface
persistence = config[:persistence] || default_persistence
notifier = config[:notifier] || default_notifier
commits_between_anivs =
config[:commits_between_anivs] || DEFAULT_COMMITS_BETWEEN_ADIVS
checker = AnniversaryChecker.new(
git_interface, persistence, notifier, commits_between_anivs)
checker.check
end
def self.default_git_interface
GitInterface.new(OSCommandExecuter.new)
end
def self.default_persistence
FilePersistence.new
end
def self.default_notifier
ConsoleNotifier.new
end
end
|
require_relative 'piece.rb'
class Queen < Piece
def initialize(color)
@color = color
end
public
def possible_moves
moves = []
column = self.get_column
row = self.get_row
moves << get_right_diags(column, row)
moves << get_left_diags(column, row)
moves << get_verticals(column, row)
moves << get_horizontals(column, row)
moves.flatten!
end
def display
if @color == "white"
"\u265B"
elsif @color == "black"
"\u2655"
end
end
end |
class Message < ActiveRecord::Base
has_many :notifications
belongs_to :messageable, polymorphic: true, counter_cache: true
belongs_to :user
after_create :track_notification
before_create :convert_content
validates :content, presence: true, length: { maximum: 400 }
validates :messageable_type, inclusion: { in: %w(Product Evaluate),
message: "%{value} is not a valid type" }
TYPE_NAME = {"Product"=>"产品", "Evaluate"=>"评测"}
def messageable_cn
TYPE_NAME[self.messageable_type]
end
def messageable_name
case self.messageable_type
when "Product"
self.messageable.try(:name)
when "Evaluate"
self.messageable.try(:title)
end
end
def evaluate_author? notification
notification.user == notification.message.messageable.try(:user)
end
def self.per_page
10
end
def self.search this_params
message = self.all
message = message.where("content LIKE ?", "%#{this_params[:content]}%") if this_params[:content].present?
message = message.where(messageable: Product.where("products.name Like ?", "%#{this_params[:product]}%")) if this_params[:product].present?
message = message.where(messageable: Evaluate.where("products.name Like ?", "%#{this_params[:evaluate]}%")) if this_params[:evaluate].present?
message = message.joins(:user).where("users.name LIKE ?", "%#{this_params[:user]}%") if this_params[:user].present?
message = message.where(messageable_type: this_params[:messageable_type]) if this_params[:messageable_type].present?
message.paginate(page: this_params[:page])
end
private
def convert_content
if self.content.include?("@")
users = find_user_in_content
users.each do |user|
url = "[@#{user.name}](/users/#{user.id})"
self.content.gsub!(/(@#{user.name})/, url)
end
end
self.content = markdown(self.content)
true
end
def track_notification
track_users = []
track_users << self.messageable.user if self.messageable.try(:user).present?
track_users += find_user_in_content
track_users.delete(self.user)
track_users.uniq.each do |user|
Notification.create! user_id: user.id, message_id: self.id
end
end
def format_user_in_content
self.content.scan(/@([\w\u4e00-\u9fa5]{2,20})/).flatten
end
def find_user_in_content
User.where(name: format_user_in_content)
end
def markdown(text)
markdown_render = Redcarpet::Render::HTML.new(hard_wrap: true, no_styles: true)
markdown = Redcarpet::Markdown.new(markdown_render, autolink: true, no_intro_emphasis: true)
markdown.render(text).html_safe
end
end
|
class ApplicationController < ActionController::Base
before_action :authenticate_user!, unless: :devise_controller?
rescue_from ActionController::InvalidAuthenticityToken, with: :redirect_and_prompt_for_sign_in
protected
def redirect_and_prompt_for_sign_in
redirect_to(new_user_session_path, alert: 'Please sign in.')
end
private
def restrict_unless_admin
redirect_to(root_url, alert: 'Access denied.') unless current_user.admin?
end
def after_sign_in_path_for(user)
if user.admin?
admin_energy_applications_url
else
energy_applications_url
end
end
def after_sign_out_path_for(user)
root_url
end
end
|
class Dog
attr_reader :name ,:raza ,:color
def initialize args
@nombre = args[:nombre]
@raza = args[:raza]
@color = args[:color]
end
def ladrar
puts "#{@nombre} esta ladrando"
end
end
propiedades= {nombre:'Beethoven', raza:'San Bernardo', color:'Café'}
dog = Dog.new(propiedades)
dog.ladrar
|
# Copyright 2007-2014 Greg Hurrell. All rights reserved.
# Licensed under the terms of the BSD 2-clause license.
require 'walrat'
module Walrat
class ProcParslet < Parslet
attr_reader :hash
def initialize proc
raise ArgumentError, 'nil proc' if proc.nil?
self.expected_proc = proc
end
def parse string, options = {}
raise ArgumentError, 'nil string' if string.nil?
@expected_proc.call string, options
end
def eql?(other)
other.instance_of? ProcParslet and other.expected_proc == @expected_proc
end
protected
# For equality comparisons.
attr_reader :expected_proc
private
def expected_proc=(proc)
@expected_proc = (proc.clone rescue proc)
update_hash
end
def update_hash
# fixed offset to avoid collisions with @parseable objects
@hash = @expected_proc.hash + 105
end
end # class ProcParslet
end # module Walrat
|
if @book
json.id @book['_id'].to_s
json.image request.protocol + request.host_with_port + @book.image.url
json.author @book.author
json.title @book.title
json.description @book.description
json.status @book.status
json.rating @book.rating
json.vote_count @book.votes_count
json.taken_count @book.taken_count
json.popularity @book.popularity
end |
# == Schema Information
#
# Table name: pictures
#
# id :integer not null, primary key
# name :string
# imageable_id :integer
# imageable_type :string
# created_at :datetime not null
# updated_at :datetime not null
# description :string
#
class Picture < ActiveRecord::Base
include PictureConcern
has_paper_trail
belongs_to :imageable, polymorphic: true
mount_uploader :name, PictureUploader
def description
attributes["description"] || "Изображение без описания"
end
end
|
class SubcollectionJoin < ApplicationRecord
belongs_to :parent_collection, class_name: 'Collection'
belongs_to :child_collection, class_name: 'Collection'
validates_presence_of :parent_collection_id
validates_presence_of :child_collection_id
validates_uniqueness_of :child_collection_id, scope: :parent_collection_id
validates_each :child_collection_id do |record, attr, value|
#this is a little bit funny to get the tests to pass for uniqueness validation. I don't think there is harm,
# since another validation will pick up the case where one of the repositories is not present
child_repository = record.child_collection.try(:repository)
parent_repository = record.parent_collection.try(:repository)
record.errors.add attr, 'Collection cannot be a child collection of itself' if value == record.parent_collection_id
record.errors.add attr, 'Parent and child collection must be in the same repository' unless child_repository.present? and parent_repository.present? and child_repository == parent_repository
end
end |
class Book < ActiveRecord::Base
belongs_to :person
has_many :insurances, :dependent => :destroy
has_many :riders, :dependent => :destroy
has_many :pas, :dependent => :destroy
belongs_to :assured_person, class_name: "Person", foreign_key: "assured_person_id"
belongs_to :payer_person, class_name: "Person", foreign_key: "payer_person_id"
default_scope { order(created_at: 'ASC') }
validates :number, presence: true
# main_insurance return the insurance associated with this book.
# main insurance must contain only one element.
def main_insurance
self.insurances.main.limit(1).first
end
# main_insurances list all the main insurances
# it is used internally to find the existing main insurances
def main_insurances
self.insurances.where(is_main: true)
end
# reverse of main_insurance
def rider_insurances
self.insurances.rider
end
# check if the book has main insurance
def has_main_insurance?
self.insurances.main.limit(1).first != nil
end
def begin_age
delta = (self.begin_at - self.person.date_of_birth) / 365
delta.to_i
end
def end_age
return nil if self.end_at == nil
delta = (self.end_at - self.person.date_of_birth) / 365
delta.to_i
end
def sum_insurance_premium
self.insurances.inject(0) { |sum, i| sum + i.premium }
end
def sum_insurance_amount
self.insurances.inject(0) { |sum, i| sum + i.amount }
end
def sum_rider_premium
self.riders.inject(0) { |sum, i| sum + i.premium }
end
def sum_rider_amount
self.riders.inject(0) { |sum, i| sum + i.amount }
end
def get_rider_names
self.riders.pluck("name").join(", ")
end
end
|
Rails.application.routes.draw do
devise_for :users
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
root to: 'page#home'
get 'location', to: 'restaurant#info'
resources :post
resources :restaurant
end
|
require 'rails_helper'
describe Access do
before(:each) do
team = Team.create(name: "test_team")
@user = User.create(name: "test_user", team_id:team.id)
@project = Project.create(name: "test_project", team_id:team.id)
end
it "is valid with both user and project" do
expect(Access.new(user_id: @user.id, project_id: @project.id)).to be_valid
end
it "is invalid without user" do
access = Access.new(user_id: nil, project_id: @project.id)
access.valid?
expect(access.errors[:user_id]).to include "can't be blank"
end
it "is invalid without project" do
access = Access.new(user_id: @user.id, project_id: nil)
access.valid?
expect(access.errors[:project_id]).to include "can't be blank"
end
end |
require_relative 'robot_command'
# Represents the Robot Command for Place Instruction
class PlaceCommand < RobotCommand
attr_accessor :x, :y, :face_name
def initialize(robot = nil)
@robot = robot
end
def robot=(robot)
@robot=robot
end
def execute
@robot.place(self.x, self.y, self.face_name)
end
def command_name
'PLACE'
end
def parse_command(command_str)
command_items = command_str.split(' ')
command = nil
if command_items.size == 2 && command_items[0]==self.command_name then
command_args = command_items[1].split(',')
if command_args.size == 3 then
begin
self.x= Integer(command_args[0])
self.y= Integer(command_args[1])
self.face_name=command_args[2]
command = self
rescue ArgumentError
#TODO log warning
end
end
end
command
end
end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.