text stringlengths 10 2.61M |
|---|
require 'rails_helper'
RSpec.describe "Healths", type: :request do
describe "GET /index" do
it "returns http success" do
# this will perform a GET request to the /health/index route
get "/health/index"
# 'response' is a special object which contain HTTP response received after a request is sent
# response.body is the body of the HTTP response, which here contain a JSON string
expect(response.body).to eq('{"status":"online"}')
# we can also check the http status of the response
expect(response.status).to eq(200)
end
end
end |
require 'csv'
require 'bigdecimal'
require_relative '../lib/invoice'
require_relative '../lib/modules/findable'
require_relative '../lib/modules/crudable'
class InvoiceRepository
include Findable
include Crudable
attr_reader :all
def initialize(path)
@all = []
create_objects(path)
end
def create_objects(path)
CSV.foreach(path, headers: true, header_converters: :symbol) do |row|
invoice = Invoice.new(row)
@all << invoice
end
end
def inspect
"#<#{self.class} #{@invoices.size} rows>"
end
def find_all_by_customer_id(id)
@all.find_all do |invoice|
invoice.customer_id == id
end
end
def find_all_by_merchant_id(id)
@all.find_all do |invoice|
invoice.merchant_id == id
end
end
def find_all_by_status(status)
@all.find_all do |invoice|
invoice.status == status.to_sym
end
end
def find_all_by_date(date)
@all.find_all do |invoice|
invoice.created_at == date
end
end
def create(attributes)
create_new(attributes, Invoice)
end
def update(id, attributes)
update_new(id, attributes)
end
def delete(id)
delete_new(id)
end
end
|
require 'test/unit'
require File.dirname(__FILE__) + '/../lib/string'
class StringTest < Test::Unit::TestCase
def test_interpolate_with_string
orig = "Hello! My name is ?"
interpolated = orig.interpolate("Nathan Hopkins")
expected = "Hello! My name is Nathan Hopkins"
assert_not_equal orig, interpolated, "Should not have mutated in place"
assert_equal expected, interpolated
interpolated = orig.interpolate("Nathan Hopkins", true)
assert_equal orig, interpolated, "Should have mutated in place"
assert_equal expected, interpolated
end
def test_interpolate_with_symbol
orig = "Hello! My name is ?"
interpolated = orig.interpolate(:Nathan)
expected = "Hello! My name is Nathan"
assert_not_equal orig, interpolated, "Should not have mutated in place"
assert_equal expected, interpolated
interpolated = orig.interpolate(:Nathan, true)
assert_equal orig, interpolated, "Should have mutated in place"
assert_equal expected, interpolated
end
def test_interpolate_with_array
orig = "Hello! My first name is ? and my last name is ?"
interpolated = orig.interpolate(["Nathan", :Hopkins])
expected = "Hello! My first name is Nathan and my last name is Hopkins"
assert_not_equal orig, interpolated, "Should not have mutated in place"
assert_equal expected, interpolated
interpolated = orig.interpolate(["Nathan", :Hopkins], true)
assert_equal orig, interpolated, "Should have mutated in place"
assert_equal expected, interpolated
end
def test_interpolate_with_hash
orig = 'Hello! My first name is {first_name} and my last name is {last_name}'
interpolated = orig.interpolate(:first_name => "Nathan", :last_name => :Hopkins)
expected = "Hello! My first name is Nathan and my last name is Hopkins"
assert_not_equal orig, interpolated, "Should not have mutated in place"
assert_equal expected, interpolated
interpolated = orig.interpolate({:first_name => "Nathan", :last_name => :Hopkins}, true)
assert_equal orig, interpolated, "Should have mutated in place"
assert_equal expected, interpolated
end
end
|
# Topic.where(name: 'aortic root')[0].id
FactoryBot.define do
factory :heart_measurement do
patient
time_ago 1
time_ago_scale 'years'
test_amount 3.3
test_unit_of_meas 'cm'
descriptors 'general anesthesia'
topic_id 100
end
end
|
# frozen_string_literal: true
module Structures
# +DynamicArray+ holds data and doubles it's size when limit is reached
class DynamicArray
attr_reader :capacity, :size
def initialize(initial_size = 16)
raise "Illegal capacity: #{initial_size}" if initial_size.negative?
@capacity = initial_size
@size = 0
@arr = Array.new(@capacity)
end
def empty?
@size.zero?
end
def get(index)
raise 'Out of Bounds' if index.negative? || index >= @size
@arr[index]
end
def set(index, value = 0)
raise 'Out of Bounds' if index.negative? || index >= @size
@arr[index] = value
end
def clear!
@size.times { |index| @arr[index] = nil }
@size = 0
end
def add(value)
if @size + 1 >= @capacity
@capacity = extend_capacity(@capacity)
new_arr = Array.new(@capacity)
@size.times { |index| new_arr[index] = @arr[index] }
@arr = new_arr
end
@arr[@size] = value
@size += 1
@arr
end
def extend_capacity(capacity)
capacity.zero? ? 1 : capacity * 2
end
def remove_at(rm_index)
raise 'Out of Bounds' if rm_index.negative? || rm_index >= @size
item = get(rm_index)
@arr = compose_new_container_without(rm_index, @arr, @capacity)
@size -= 1
item
end
def compose_new_container_without(rm_index, container, capacity)
new_container = Array.new(capacity)
new_index = 0
capacity.times do |index|
next if index == rm_index
new_container[new_index] = container[index]
new_index += 1
end
new_container
end
def remove(value)
removed = false
@size.times do |index|
if @arr[index] == value
remove_at(index)
removed = true
end
end
removed
end
def index_of(value)
@size.times do |index|
return index if @arr[index] == value
end
nil
end
def contains?(value)
index_of(value) != nil
end
alias containing? contains?
def to_string
return '[]' if @size.zero?
"[#{@arr.join(',')}]"
end
end
end
|
class ApplicationController < ActionController::Base
protect_from_forgery
helper_method :current_user
helper_method :current_cart
def redirect_to_back_or_root(options={})
if request.referer
redirect_to :back, options
else
redirect_to root_path, options
end
end
protected
def find_polymorphic_association
params.each do |name, value|
if name =~ /(.+)_id$/
return $1.classify.constantize.find(value)
end
end
nil
end
private
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
def current_cart
if session[:cart_id]
@current_cart ||= Cart.find(session[:cart_id])
session[:cart_id] = nil if @current_cart.purchased_at
end
if session[:cart_id].nil?
@current_cart = current_user.carts.find_or_create_by_purchased_at(nil)
session[:cart_id] ||= @current_cart.id
end
@current_cart
end
end
|
require 'spec_helper'
require 'pry-byebug'
describe ListMore::Repositories::UsersRepo do
let(:dbhelper) { ListMore::Repositories::DBHelper.new 'listmore_test' }
let(:user_1) { ListMore::Entities::User.new({:username => "Ramses", :password_digest => "pitbull"})}
let(:user_2) { ListMore::Entities::User.new({:username => "Daisy", :password_digest => "collie"})}
before(:each) do
dbhelper.drop_tables
dbhelper.create_tables
end
it "saves a user to the database" do
result = ListMore.users_repo.save user_1
expect(result.username).to eq "Ramses"
expect(result.password_digest).to eq "pitbull"
expect(result.id.to_i).to be_a Integer
end
it "gets all users" do
ListMore.users_repo.save user_1
ListMore.users_repo.save user_2
users = ListMore.users_repo.all
expect(users).to be_a Array
expect(users.count).to eq 2
end
it "gets a user by id" do
user = ListMore.users_repo.save user_1
result = ListMore.users_repo.find_by_id user.id
expect(result).to be_a ListMore::Entities::User
end
it "gets a user by username" do
user = ListMore.users_repo.save user_1
result = ListMore.users_repo.find_by_username user.username
expect(result).to be_a ListMore::Entities::User
end
it "can delete a user by id" do
user = ListMore.users_repo.save user_1
count = ListMore.users_repo.all.count
expect(count).to eq 1
ListMore.users_repo.destroy user
count = ListMore.users_repo.all.count
expect(count).to eq 0
end
end
|
class Curator
attr_reader :artists,
:photographs
def initialize
@artists = []
@photographs = []
end
def add_photograph(photo)
photographs << photo
end
def add_artist(artist)
artists << artist
end
def find_artist_by_id(id)
artists.find do |artist|
artist.id == id
end
end
def find_photograph_by_id(id)
photographs.find do |photo|
photo.id == id
end
end
def find_photographs_by_artist(artist)
@photographs.find_all do |photo|
photo.artist_id == artist.id
end
end
def artists_with_multiple_photographs
@artists.reject do |artist|
find_photographs_by_artist(artist).size <= 1
end
end
def artists_from(country)
@artists.reject do |artist|
artist.country != country
end
end
def photographs_taken_by_artist_from(country)
artists_from(country).map do |artist|
find_photographs_by_artist(artist)
end.flatten
end
def parse_csv(file)
CSV.open(file, headers: true, header_converters: :symbol)
end
def load_photographs(file)
photo_data = parse_csv(file)
photo_data.map do |photo|
photographs << Photograph.new(photo)
end
end
def load_artists(file)
artist_data = parse_csv(file)
artist_data.map do |artist|
artists << Artist.new(artist)
end
end
end
|
# frozen_string_literal: true
class PagesController < ApplicationController
def create
work = Work.find(params[:work_id])
page = Page.new(
work: work
)
page.save!
work.stages.each do |stage|
Progress.create(work: work, stage: stage, page: page)
end
redirect_to work,
notice: "ページを追加しました"
end
def destroy
work = Work.find(params[:work_id])
page = Page.find(params[:page_id])
page.destroy
redirect_to work,
notice: "ページを削除しました"
end
end
|
module WastebitsClient
class ForgotPassword < Base
attr_accessor :email, :url
def access_token
# NOOP
end
def send_instructions
return self.class.post(nil, '/users/forgot-password', :body => {
:email => @email,
:password_reset_url => @url
}, :headers => { 'Authorization' => WastebitsClient::Base.client_authorization(WastebitsClient::Base.api_key, WastebitsClient::Base.api_secret) })
end
end
end
|
require 'json'
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
Canvas.destroy_all
pixels = Array.new(32) {Array.new(32, '#FFFFFF')}
Canvas.create!({
singleton_guard: 0,
pixels: pixels.to_json
})
p "Created #{Canvas.count} Canvas" |
require 'spec_helper'
require 'helpers/unit_spec_helper'
describe Puppet::Type.type(:clc_server) do
let(:create_params) {
{
:name => 'name',
:group_id => 'group-id',
:source_server_id => 'server-id',
:cpu => 1,
:memory => 1,
}
}
[:name, :source_server_id].each do |field|
it_behaves_like "it has a non-empty string parameter", field
end
it_behaves_like "it has a read-only parameter", :id
it_behaves_like "it has custom fields"
[:group, :group_id].each do |field|
describe field do
it "should be invalid given non-string" do
create_params[field] = 1
expect { described_class.new(create_params) }.to raise_error(/#{field}/)
end
it "should be invalid given an empty string" do
create_params[field] = ' '
expect { described_class.new(create_params) }.to raise_error(/#{field}/)
end
end
end
describe 'cpu' do
it 'does not allow negatives' do
create_params[:cpu] = -1
expect { described_class.new(create_params) }.to raise_error(/cpu/)
end
it 'does not allow 0' do
create_params[:cpu] = 0
expect { described_class.new(create_params) }.to raise_error(/cpu/)
end
it 'does not allow > 16' do
create_params[:cpu] = 17
expect { described_class.new(create_params) }.to raise_error(/cpu/)
end
end
describe 'memory' do
it 'does not allow negatives' do
create_params[:memory] = -1
expect { described_class.new(create_params) }.to raise_error(/memory/)
end
it 'does not allow 0' do
create_params[:memory] = 0
expect { described_class.new(create_params) }.to raise_error(/memory/)
end
it 'does not allow > 128' do
create_params[:memory] = 129
expect { described_class.new(create_params) }.to raise_error(/memory/)
end
end
describe 'managed' do
it 'sets to false by default' do
expect(described_class.new(create_params)[:managed]).to be false
end
end
describe 'managed_backup' do
it 'sets to false by default' do
expect(described_class.new(create_params)[:managed_backup]).to be false
end
it 'does not allow to set to true when "managed" is false' do
create_params[:managed] = false
create_params[:managed_backup] = true
expect { described_class.new(create_params) }.to raise_error(/managed_backup/)
end
end
describe 'type' do
[:standard, :hyperscale, :bareMetal].each do |type|
it "allows #{type}" do
create_params[:type] = type
expect { described_class.new(create_params) }.to_not raise_error
end
end
specify do
create_params[:type] = 'invalid'
expect { described_class.new(create_params) }.to raise_error(/type/)
end
it 'sets "standard" by default' do
expect(described_class.new(create_params)[:type]).to eq :standard
end
end
describe 'ip_address' do
it 'validates value must be a valid IP' do
create_params[:ip_address] = 'invalid'
expect { described_class.new(create_params) }.to raise_error(/ip_address/)
end
end
describe 'public_ip_address' do
it 'validates value must be a hash' do
create_params[:public_ip_address] = 'invalid'
expect { described_class.new(create_params) }.to raise_error(/public_ip_address/)
end
describe 'ports' do
it 'validates ports is an array' do
create_params[:public_ip_address] = { ports: 'invalid' }
expect { described_class.new(create_params) }.to raise_error(/ports/)
end
it 'validates port entry is a hash' do
create_params[:public_ip_address] = { ports: ['invalid'] }
expect { described_class.new(create_params) }.to raise_error(/ports/)
end
end
describe 'source_restrictions' do
it 'validates source_restrictions is an array' do
create_params[:public_ip_address] = { ports: [], source_restrictions: 'invalid' }
expect { described_class.new(create_params) }.to raise_error(/source_restrictions/)
end
it 'validates source_restrictions entry is a hash' do
create_params[:public_ip_address] = { ports: [], source_restrictions: ['invalid'] }
expect { described_class.new(create_params) }.to raise_error(/source_restrictions/)
end
end
end
end
|
class Book < ActiveRecord::Base
validates :title, presence: true
validates :authorname, presence: true
validates :authorsurname, presence: true
end
|
require 'rails_helper'
RSpec.describe Micropost, type: :model do
context 'associations' do
it { is_expected.to belong_to(:user) }
it { is_expected.to belong_to(:source) }
it { is_expected.to have_many(:media) }
it { is_expected.to have_many(:targets) }
it { is_expected.to have_many(:trollers) }
end
context 'model validations' do
it { is_expected.to validate_presence_of(:text) }
it { is_expected.to validate_presence_of(:provider_id) }
it :status do
is_expected.to validate_presence_of(:status)
is_expected.to validate_inclusion_of(:status)
.in_array(MicropostStatus.list)
end
end
context 'table fields' do
it do
is_expected.to have_db_column(:provider_id).of_type(:string)
.with_options(null: false)
end
it do
is_expected.to have_db_column(:text).of_type(:text)
.with_options(null: false)
end
it do
is_expected.to have_db_column(:all_targets)
.of_type(:boolean).with_options(null: false, default: false)
end
it do
is_expected.to have_db_column(:all_trollers)
.of_type(:boolean).with_options(null: false, default: false)
end
it do
is_expected.to have_db_column(:is_shared)
.of_type(:boolean).with_options(default: false)
end
it do
is_expected.to have_db_column(:shared)
.of_type(:integer).with_options(default: 0)
end
it do
is_expected.to have_db_column(:status)
.of_type(:integer).with_options(default: 0)
end
it { is_expected.to have_db_column(:provider_url).of_type(:string) }
it { is_expected.to have_db_column(:title).of_type(:string) }
it { is_expected.to have_db_column(:user_id).of_type(:integer) }
it { is_expected.to have_db_column(:source_id).of_type(:integer) }
end
context 'table indexes' do
it { is_expected.to have_db_index(:status) }
it { is_expected.to have_db_index(:user_id) }
end
context 'factories' do
it { expect(build(:micropost)).to be_valid }
it { expect(build(:invalid_micropost)).to_not be_valid }
end
context 'scopes' do
let!(:club1) { create :club }
let!(:club2) { create :club }
let!(:nick1) { create :nickname_fan, club: club1 }
let!(:nick2) { create :nickname_fan, club: club2 }
describe '.troller_microposts_from_nick' do
let(:troller1) { create :troller, trollerable: club1 }
let(:troller11) { create :troller, trollerable: club1 }
let(:target1) { create :target, targetable: club1 }
let(:troller2) { create :troller, trollerable: club2 }
let(:target2) { create :target, targetable: club2 }
let!(:micropost) { create :micropost, trollers: [troller1] }
let!(:micropost2) { create :micropost, trollers: [troller11, troller2] }
it 'need to get right posts' do
list = described_class.troller_microposts_from_nick(nick1)
expect(list).to eq([micropost2, micropost])
end
end
describe '.target_microposts_from_nick' do
let(:troller1) { create :troller, trollerable: club1 }
let(:target1) { create :target, targetable: club1 }
let(:target11) { create :target, targetable: club1 }
let(:troller2) { create :troller, trollerable: club2 }
let(:target2) { create :target, targetable: club2 }
let!(:micropost) { create :micropost, targets: [target1] }
let!(:micropost2) { create :micropost, targets: [target11, target2] }
it 'need to get right posts' do
list = described_class.target_microposts_from_nick(nick1)
expect(list).to eq([micropost2, micropost])
end
end
describe '.versus_microposts_from_nicks' do
let(:troller1) { create :troller, trollerable: club1 }
let(:target1) { create :target, targetable: club1 }
let(:troller2) { create :troller, trollerable: club2 }
let(:target2) { create :target, targetable: club2 }
let!(:micropost) do
create :micropost, trollers: [troller1], targets: [target1, target2]
end
it 'need to get right posts' do
list = described_class.versus_microposts_from_nicks(nick1, nick2)
expect(list).to eq([micropost])
end
end
end
end
|
class Api::V1::SongsController < Api::ApiController
def index
singer_id = params[:singer_id]
@songs = Song.includes(:singer).where("singer_id = #{singer_id}").select("id,name,album_id,singer_id").order("id desc").paginate(:page => params[:page], :per_page => 30)
# render :json => @songs
end
def show
@song = Song.includes(:singer).select("id,name,album_id,lyric,singer_id").find(params[:id])
# render :json => song
end
def hot_songs
category_id = params[:category_id]
if category_id.to_i == 4
category_id = 5
elsif category_id.to_i == 5
category_id = 4
end
ships = HotSongShip.where("hot_song_ships.hot_song_category_id = #{category_id}").select("song_id").paginate(:page => params[:page], :per_page => 30)
ids = ships.map{|ship| ship.song_id}
@songs = Song.includes(:singer).where("id in (#{ids.join(',')})").select("id,name,album_id,singer_id").order("FIELD(id, #{ids.join(',')})")
end
def search_name
songs = Song.search_name(params)
if songs.present?
ids = songs.map{|item| item["id"]}.join(",")
@songs = Song.includes(:singer).where("id in (#{ids})").select("id,name,album_id,singer_id")
else
render :json => []
end
end
def search_lyric
songs = Song.search_lyric(params)
if songs.present?
ids = songs.map{|item| item["id"]}.join(",")
@songs = Song.includes(:singer).where("id in (#{ids})").select("id,name,album_id,singer_id")
else
render :json => []
end
end
def album_songs
album_id = params[:album_id]
@songs = Song.includes(:singer).where("album_id = #{album_id}").select("id,name,album_id,singer_id")
# render :json => songs
end
def top_list_songs
list_id = params[:list_id]
if list_id == "31"
@songs = Song.joins(:top_lists).includes(:singer).where("top_lists.id = #{list_id}").select("songs.id,songs.name,songs.album_id,songs.singer_id").order("song_top_list_relations.id ASC")
else
@songs = Song.joins(:top_lists).includes(:singer).where("top_lists.id = #{list_id}").select("songs.id,songs.name,songs.album_id,songs.singer_id").order("song_top_list_relations.id DESC")
end
end
def recommend_songs
@songs = Song.joins(:recommend_song_relations).includes(:singer).where("recommend_song_relations.song_id = songs.id")
# @songs=[Song.first]
end
end
|
#require_dependency "web_user"
module AuthSystem
include AuthHelper
# store current uri in the ccokies
# we can return to this location by calling return_location
def store_location
cookies[:return_to] = {:value => request.request_uri, :expires => nil }
end
protected
def del_location
cookies[:return_to] = {:value => nil, :expires => nil }
end
# move to the last store_location call or to the passed default one
def redirect_back_or_default(default)
if cookies[:return_to].nil?
redirect_to default
else
redirect_to_url cookies[:return_to]
cookies[:return_to] = nil
end
end
def require_auth(*options)
auth_intercept('login') unless web_user_logged_in?
access_granted = false
case options.first
when true || false
restrict_time, credentials = options.shift, options.first
else
credentials, restrict_time = options.shift, (options.first || false)
end
case credentials.class.to_s
when 'NilClass' # simple authentication
access_granted = restrict_time ? @web_user.acl?("USERS", restrict_time) : web_user_logged_in?
when 'Array' # check against any of the credentials
credentials.each { |cred|
if @web_user.access_granted_for?(cred, restrict_time); access_granted = true; break; end
}
else # check against all of the credentials
access_granted = @web_user.access_granted_for?(credentials, restrict_time)
end
auth_intercept('denied') unless access_granted == true
return access_granted
end
# insert interceptor action before current action
def auth_intercept(interceptor_action = 'login')
store_location
unless auth_app_interceptor(interceptor_action)
flash[:error] = "Byl jste automaticky odhlášen"
redirect_to auth_url(:action => 'denied')
end
throw :abort
end
# override auth_intercept behavior on authorization failures
# return true to override the default action, false otherwise
def auth_app_interceptor(interceptor_name)
# redirect_to "http://je.suis.perdu.com/"
# return true
return false
end
# override if you want to have special behavior in case the web_user is not authorized
# to access the current operation.
# the default action is to redirect to the login screen
# example use :
# a popup window might just close itself for instance
def access_denied
flash[:error] = "Nemáte oprávnění pro přístup do této sekce"
redirect_to auth_url(:action => 'denied')
end
def app_config
@app ||= YAML.load_file("#{RAILS_ROOT}/config/auth_generator.yml").symbolize_keys
WebUser.config @app
end
def ident
#require_dependency "web_user"
if cookies[:web_user]
# fromString may return nil!
@web_user = WebUser.fromString(cookies[:web_user])
end
if @web_user.nil?
@web_user = WebUser.new
@web_user.ident = false
end
# !!! Leave that true !!!
true
end
end
|
class Users::ChangeEmailsController < ApplicationController
before_action :correct_user, only: [:change_emails, :update]
def change_emails
@user = User.find_by(id: params[:id])
end
def update
@user = User.find(params[:id])
if user_params_change_email[:email_confirmation] == user_params_change_email[:email]
if @user.update_attributes(email: user_params_change_email[:email])
flash[:success] = "Email updated"
redirect_to @user
else
render 'change_emails'
end
else
flash.now[:danger] = "Email and email confirmation doesn't match"
render 'change_emails'
end
end
private
def user_params_change_email
params.require(:user).permit(:email, :email_confirmation)
end
def correct_user
user = User.find_by(id: params[:id])
redirect_to root_url unless current_user?(user)
end
#def logged_in_user
# unless logged_in?
# flash[:danger] = "Please log in"
# redirect_to root_url
# end
#end
end
|
class Bin < ActiveRecord::Base
belongs_to :event
has_many :documents
has_many :labels
validates_presence_of :event_id
validates_presence_of :title
end |
# -*- encoding: utf-8 -*-
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'boss-protocol/version'
Gem::Specification.new do |gem|
gem.name = "boss-protocol"
gem.version = Boss::VERSION
gem.authors = ["sergeych"]
gem.email = ["real.sergeych@gmail.com"]
gem.description = %q{Binary streamable bit-effective protocol to effectively store object tree hierarchies}
gem.summary = %q{Traversable and streamable to protocol supports lists, hashes, caching, datetime, texts,
unlimited integers, floats, compression and more}
gem.homepage = "https://github.com/sergeych/boss_protocol"
gem.licenses = ["MIT"]
gem.files = `git ls-files`.split($/)
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.require_paths = ["lib"]
#gem.add_dependency 'bzip2-ruby'
gem.add_development_dependency "rspec", '~> 2.14'
end
|
require 'rails_helper'
feature 'User remove recipe' do
scenario 'successfully' do
# create data
user = create(:user)
cuisine = create(:cuisine, name: 'Paulista')
recipe_type = create(:recipe_type, name: 'Massa')
recipe = create(:recipe, title: 'Miojo', recipe_type: recipe_type,
cuisine: cuisine, user: user)
another_recipe = create(:recipe, title: 'Macarrão',
recipe_type: recipe_type,
cuisine: cuisine, user: user)
# simulate interaction
login_as user
visit root_path
click_on recipe.title
click_on 'Remover'
expect(current_path). to eq(root_path)
expect(page).not_to have_content(recipe.title)
expect(page).to have_content(another_recipe.title)
expect(page).to have_content('Receita removida com sucesso')
end
end
|
require 'spec_helper'
describe Story do
it "should be valid" do
p = Story.make!
p.should be_valid
end
it "should be invalid without a category" do
e = Story.make(:category => nil)
e.should have(1).errors_on(:category)
end
end
|
require 'rails_helper'
describe 'Munchie' do
it 'exists and has attributes' do
city = "boulder,co"
distance = {
:route=>{
:hasTollRoad=>false,
:hasBridge=>true,
:boundingBox=>{:lr=>{:lng=>-104.605087, :lat=>38.265427}, :ul=>{:lng=>-104.98761, :lat=>39.738453}},
:distance=>111.38,
:hasTimedRestriction=>false,
:hasTunnel=>false,
:hasHighway=>true,
:computedWaypoints=>[],
:routeError=>{:errorCode=>-400, :message=>""},
:formattedTime=>"01:44:22",
:sessionId=>"6008f227-0263-5f21-02b4-33eb-06290d9a47e5",
:hasAccessRestriction=>false,
:realTime=>6507,
:hasSeasonalClosure=>false,
:hasCountryCross=>false,
:fuelUsed=>5.5
}
}
forecast = {
:lat=>38.2654,
:lon=>-104.6051,
:timezone=>"America/Denver",
:timezone_offset=>-25200,
:current=>
{:dt=>1611199015,
:sunrise=>1611151888,
:sunset=>1611187637,
:temp=>42.46,
:feels_like=>28.69,
:pressure=>1014,
:humidity=>34,
:dew_point=>17.85,
:uvi=>0,
:clouds=>1,
:visibility=>10000,
:wind_speed=>14.97,
:wind_deg=>280,
:weather=>[{:id=>800, :main=>"Clear", :description=>"clear sky", :icon=>"01n"}]}
}
food = {
:businesses=>
[{:id=>"kQxM1xlaZfQmXpKaqMTNnw",
:alias=>"wonderful-bistro-pueblo",
:name=>"Wonderful Bistro",
:image_url=>"https://s3-media1.fl.yelpcdn.com/bphoto/EIPRzs68vSrQ_2tCf5pQNw/o.jpg",
:is_closed=>false,
:url=>
"https://www.yelp.com/biz/wonderful-bistro-pueblo?adjust_creative=wSqNjyvd1Y1HmcN8kPANOA&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=wSqNjyvd1Y1HmcN8kPANOA",
:review_count=>64,
:categories=>[{:alias=>"chinese", :title=>"Chinese"}],
:rating=>4.0,
:coordinates=>{:latitude=>38.319366, :longitude=>-104.616623},
:transactions=>["delivery"],
:price=>"$$",
:location=>
{:address1=>"4602 N Elizabeth St",
:address2=>"Ste 120",
:address3=>"",
:city=>"Pueblo",
:zip_code=>"81008",
:country=>"US",
:state=>"CO",
:display_address=>["4602 N Elizabeth St", "Ste 120", "Pueblo, CO 81008"]},
:phone=>"+17195440233",
:display_phone=>"(719) 544-0233",
:distance=>6632.28027227077}],
:total=>1,
:region=>{:center=>{:longitude=>-104.5733642578125, :latitude=>38.27035217485165}}}
munchie = Munchie.new(city, distance, forecast, food)
expect(munchie).to be_a(Munchie)
expect(munchie.destination_city).to eq(city.gsub(",", ", ").capitalize)
expect(munchie.travel_time).to eq(distance[:route][:formattedTime])
expect(munchie.forecast).to eq({
summary: forecast[:current][:weather][0][:description],
temperature: forecast[:current][:temp].to_s
})
expect(munchie.restaurant).to eq({
name: food[:businesses][0][:name],
address: food[:businesses][0][:location][:display_address].join(" ")
})
end
end |
class RegisteredTeachersController < ApplicationController
before_action :require_student
before_action :remove_null_registered_teachers, only: [:register]
before_action :registered_teacher_rank_adjust, only: [:register]
def index
@q = Teacher.all.ransack(params[:q])
@teachers = @q.result(distinct: true).page(params[:page])
@registered_teacher_ids = current_user.registered_teachers.map{|rs| rs.teacher_id}
end
def show
@teacher = Teacher.find(params[:id])
end
def register
@registered_teachers = current_user.registered_teachers
@teachers = @registered_teachers.sort{ |a,b| a.rank <=> b.rank }.map { |rs| Teacher.find(rs.teacher_id) }
end
def create
registered_teacher = current_user.registered_teachers.new(registed_teacher_params)
registered_teacher.rank = current_user.registered_teachers.count + 1
registered_teacher.save!
redirect_to registered_teachers_path
end
def destroy
registered_teacher = current_user.registered_teachers.find(params[:id])
registered_teacher.delete
redirect_to registered_teachers_register_path
end
def rank_up
registered_teacher = current_user.registered_teachers.find_by(teacher_id: params[:id])
unless registered_teacher.rank == 1
target = current_user.registered_teachers.find_by(rank: (registered_teacher.rank - 1))
tmp = registered_teacher.rank
registered_teacher.update(rank: target.rank)
target.update(rank: tmp)
end
redirect_to registered_teachers_register_path
end
def rank_down
registered_teacher = current_user.registered_teachers.find_by(teacher_id: params[:id])
unless registered_teacher.rank == current_user.registered_teachers.count
target = current_user.registered_teachers.find_by(rank: (registered_teacher.rank + 1))
tmp = registered_teacher.rank
tmp = registered_teacher.rank
registered_teacher.update(rank: target.rank)
target.update(rank: tmp)
end
redirect_to registered_teachers_register_path
end
private
def registed_teacher_params
params.require(:registered_teacher).permit(:teacher_id)
end
def remove_null_registered_teachers
current_user.registered_teachers.each do |rs|
rs.delete unless Teacher.find_by(id: rs.teacher_id)
end
end
def registered_teacher_rank_adjust
current_user.registered_teachers.sort{ |a,b| a.rank <=> b.rank }.each.with_index(1) do |rs, i|
next if rs.rank == i
rs.rank = i
rs.save!
end
end
def require_student
redirect_to root_path unless current_user.student?
end
end
|
Gl2::Application.routes.draw do
# The priority is based upon order of creation:
# first created -> highest priority.
root :to=>"home#index"
#for user_sessions
get "sign_in" => "user_sessions#new"
post "sign_in" => "user_sessions#create"
match "sign_out" => "user_sessions#destroy"
get "actions/:user_id" => "user_actions#index"
resources :users do
collection do
get 'roles'
end
member do
post 'update_password'
end
end
resources :clients do
member do
get 'users'
get 'expeditor_in_requests'
get 'client_report'
get 'exp_report'
get 'pgk_report'
end
collection do
get 'get_total_report'
get 'autocomplete'
end
end
put "clients/:id/users/:user_id" => "clients#update_permission"
resources :client_transactions
resources :bills do
member do
get 'get_invoice'
end
collection do
post 'create_inbox'
end
end
resources :requests
resources :stations
resources :loads
resources :car_types
resources :places
resources :deltas do
collection do
get :total
end
end
end
|
class AddUserFields < ActiveRecord::Migration
def self.up
add_column :users, :name_title, :string
add_column :users, :language_id, :integer
add_column :users, :user_type_id, :integer
add_column :users, :country_name, :string
add_column :users, :skype, :string
# Paperclip
add_column :users, :avatar_file_name, :string
add_column :users, :avatar_content_type, :string
add_column :users, :avatar_file_size, :integer
add_column :users, :avatar_updated_at, :datetime
# Some indexes for search
add_index :users, :language_id
add_index :users, :user_type_id
end
def self.down
remove_column :users, :name_title
remove_column :users, :language_id
remove_column :users, :user_type_id
remove_column :users, :country_name
remove_column :users, :skype
# Paperclip
remove_column :users, :avatar_file_name
remove_column :users, :avatar_content_type
remove_column :users, :avatar_file_size
remove_column :users, :avatar_updated_at
end
end
|
require 'spec_helper'
require 'endpointer/response'
require 'rack/test'
describe Endpointer::AppCreator do
include Rack::Test::Methods
let(:url1) { "http://example.com/foo" }
let(:url2) { "http://example.com/bar" }
let(:invalidate) { true }
let(:resource1) { Endpointer::Resource.new("resource1", :get, url1, {'Authorization' => 'Bearer bar'}) }
let(:resource2) { Endpointer::Resource.new("resource2", :post, url2, {}) }
let(:resources) { [resource1, resource2] }
let(:config) { Endpointer::Configuration.new(invalidate) }
let(:resource_parser) { double(Endpointer::ResourceParser) }
before do
stub_const('Endpointer::ResourceExecutor', Endpointer::ResourceExecutorStub)
allow(Endpointer::ResourceParser).to receive(:new).and_return(resource_parser)
allow(resource_parser).to receive(:parse).with(config.resource_config).and_return(resources)
end
describe '#create' do
it 'creates a sinatra endpointer app with all configured resources' do
path = URI.parse(url1).path
get path
expect(last_response.body).to eq(path)
expect(last_response.headers['Authorization']).to eq(resource1.headers['Authorization'])
path = URI.parse(url2).path
post path
expect(last_response.body).to eq(path)
end
end
def app
subject.create(config)
end
end
class Endpointer::ResourceExecutorStub < Endpointer::ResourceExecutor
def perform(request, resource, options)
Endpointer::Response.new(200, request.path, resource.headers)
end
end
|
class Product < ActiveRecord::Base
validates :description,:name,:presence =>true
validates :price_in_cents,:numericality => {:only_integer=>true}
end
|
module GraphQL::Rails::ActiveReflection
class ValidationResult
@schema_name = "ActiveReflectionValidation"
attr_reader :valid
attr_reader :errors
def initialize(valid, errors)
@valid = valid
@errors = errors
end
class << self
attr_accessor :schema_name
end
end
end
|
class CreateVeranstaltungsart < ActiveRecord::Migration
def self.up
create_table(:Veranstaltungsart, :primary_key => :id) do |t|
# Veranstaltungsart-id PS
t.integer :id, :null => false, :uniqueness => true, :limit => 2
# VABezeichnung
t.string :vaBezeichnung, :limit => 30, :default => nil
end
end
def self.down
drop_table :Veranstaltungsart
end
end
|
require 'priority_queue'
require 'benchmark'
require './cartesian_points_helper'
class ClosestPair2D
include CartesianPointsHelper
attr_accessor :points
FIXNUM_MAX = (2**(0.size * 8 -2) -1)
def initialize
setup
end
def re_setup
setup
end
def brute_force
brute_force_sub_routine(points)
end
# Divide and Conquer (DAC) with only x coordinates sorted
def divide_and_conquer_sorted_x
points.sort_by!{ |point| point[0] }
dac_sorted_x_recursively(points)
end
# Divide and Conquer (DAC) with x and y coordinates sorted
def divide_and_conquer_sorted_xy
points.sort_by!{ |point| point[0] }
points_y_sorted = Hash.new
points.sort_by{ |point| point[1] }.each do |point|
points_y_sorted[point[0]] = [point, nil]
end
dac_sorted_xy_recursively(points, points_y_sorted)
end
def benchmarks
brute_force_time = Benchmark.measure { brute_force }
dac_sorted_x_time = Benchmark.measure { divide_and_conquer_sorted_x }
dac_sorted_xy_time = Benchmark.measure { divide_and_conquer_sorted_xy }
puts "Time taken brute forces: #{brute_force_time.real}"
puts "Time taken DAC with only x sorted: #{dac_sorted_x_time.real}"
puts "Time taken DAC with x and y sorted: #{dac_sorted_xy_time.real}"
end
private
def euclidean_distance(point_a, point_b)
Math.sqrt((point_a[0] - point_b[0]) ** 2 + (point_a[1] - point_b[1]) ** 2)
end
def brute_force_sub_routine(points)
result = FIXNUM_MAX
points.each_with_index do |point_a, index|
points[index + 1..-1].each do |point_b|
result = [euclidean_distance(point_a, point_b), result].min
end
end
result
end
## Divide and Conquer (DAC) procedures with only x coordinates sorted
def dac_sorted_x_recursively(points)
return brute_force_sub_routine(points) if points.length <= 3
delta = [
dac_sorted_x_recursively(points[0..points.length/2]),
dac_sorted_x_recursively(points[points.length/2 + 1..points.length - 1])
].min
dac_sorted_x_merge(points, delta)
end
def dac_sorted_x_merge(points, delta)
middle_line_x = points[points.length/2][0]
strip_points = points.select{ |point| point[0] - middle_line_x <= delta }
strip_points.sort_by!{ |point| point[1] }
dac_merge(strip_points, delta)
end
## Divide and Conquer (DAC) procedures with x and y coordinates sorted
def dac_sorted_xy_recursively(points, points_y_sorted)
return brute_force_sub_routine(points) if points.length <= 3
points[0..points.length/2].each do |point|
points_y_sorted[point[0]][1] = 'L'
end
points[points.length/2 + 1..points.length - 1].each do |point|
points_y_sorted[point[0]][1] = 'R'
end
points_y_sorted_left = points_y_sorted.select{ |x, point| point[1] == 'L' }
points_y_sorted_right = points_y_sorted.select{ |x, point| point[1] == 'R' }
delta = [
dac_sorted_xy_recursively(points[0..points.length/2], points_y_sorted_left),
dac_sorted_xy_recursively(points[points.length/2 + 1..points.length - 1], points_y_sorted_right)
].min
dac_sorted_xy_merge(points_y_sorted, delta, points[points.length/2][0])
end
def dac_sorted_xy_merge(points_y_sorted, delta, middle_line_x)
strip_points = []
points_y_sorted.each do |x, point|
strip_points << point[0] if x - middle_line_x <= delta
end
dac_merge(strip_points, delta)
end
## Compare delta (min of two divided parts) with strip points
def dac_merge(strip_points, delta)
result = delta
strip_points.each_with_index do |point_a, index|
# Maximum next points need to check is 7
# Proof: http://people.csail.mit.edu/indyk/6.838-old/handouts/lec17.pdf
end_bound = [strip_points.length, index + 7].min
strip_points[index+1..end_bound].each do |point_b|
result = [ euclidean_distance(point_a, point_b), result].min
end
end
result
end
end |
class Voucher
def self.all
vouchers = []
vouchers << Voucher.new(:id => 1, :name => "one", :amount => 1)
vouchers << Voucher.new(:id => 2, :name => "two", :amount => 2)
vouchers << Voucher.new(:id => 3, :name => "three", :amount => 3)
vouchers
end
def self.find(id)
Voucher.new(:id => id, :name => "found", :amount => id)
end
def initialize(arguments = {})
update_attributes! arguments
end
attr_accessor :id, :amount, :name
def save
self
end
def update_attributes!(attributes = {})
attributes.each { |key, value| send "#{key}=", value }
end
def to_json(options = {})
super options.merge(:only => [:id, :name, :amount])
end
end
|
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'colorbug/version'
Gem::Specification.new do |spec|
spec.name = "colorbug"
spec.version = Colorbug::VERSION
spec.authors = ["Michael Angelo"]
spec.email = ["yamikamisama@gmail.com"]
spec.summary = %q{Colors output based on Classes}
spec.description = %q{String, Array, Hash, and Fixnum are different colors}
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.7"
spec.add_development_dependency "rake", "~> 10.0"
end
|
json.array! @shops do |shop|
json.partial! 'api/shops/shop', shop: shop
end |
# encoding: utf-8
begin
require 'bones'
rescue LoadError
abort '### Please install the "bones" gem ###'
end
ensure_in_path 'lib'
proj = 'thumbo'
require "#{proj}/version"
Bones{
version Thumbo::VERSION
# ruby_opts [''] # silence warning, too many in addressable and/or dm-core
depend_on 'rmagick', :version => '>=2.6.0'
name proj
url "http://github.com/godfat/#{proj}"
authors 'Lin Jen-Shin (aka godfat 真常)'
email 'godfat (XD) godfat.org'
history_file 'CHANGES'
readme_file 'README.rdoc'
ignore_file '.gitignore'
rdoc.include ['\w+']
}
CLEAN.include Dir['**/*.rbc']
task :default do
Rake.application.options.show_task_pattern = /./
Rake.application.display_tasks_and_comments
end
|
# class Types::QueryType < Types::BaseObject
# graphql_name 'Query'
# ### TODO LIST QUERY
# field :todo_lists, [Types::TodoListType], null: true do
# description 'returns all todo lists'
# end
# field :todo_list, Types::TodoListType, null: true do
# description 'returns the queried todo list'
# argument :id, ID, required: true
# end
# def todo_lists
# TodoList.all
# end
# def todo_list(args)
# TodoList.find_by!(id: args[:id])
# end
# ### ITEM QUERY
# field :items, [Types::ItemType], null: true do
# description 'returns all items'
# end
# def items
# Item.all
# end
# end
module Types
QueryType = GraphQL::ObjectType.new.tap do |root_type|
root_type.name = 'Query'
root_type.description = 'The query root'
root_type.interfaces = []
root_type.fields = Util::FieldCombiner.combine([
QueryTypes::TodoListQueryType,
QueryTypes::ItemQueryType
])
end
end
# class Types::QueryType < GraphQL::Schema::Object
# field :projects, [Types::ProjectType], null: false do
# description 'Find all the projects'
# end
# field :project, Types::ProjectType, null: true do
# description 'Find a project by slug'
# argument :slug, String, required: true
# end
# def projects
# Project.all
# end
# def project(args)
# Project.find_by(slug: args[:slug])
# end
# end |
require 'active_support/concern'
module Returning
module ActiveRecord
module Returning
def save(options = {})
if r = options[:returning]
begin
old_returning, @_returning = @_returning, r
super
ensure
@_returning = old_returning
end
else
super
end
end
def create_or_update
if @_returning
raise ReadOnlyRecord if readonly?
if new_record?
create
self
elsif r = update
r = self.class.send(:instantiate, r[0])
r.readonly!
r
else
false
end
else
super
end
end
def destroy(options = {})
if r = options[:returning]
begin
old_returning, @_returning = @_returning, r
if r = super()
r = self.class.send(:instantiate, r[0])
r.readonly!
end
r
ensure
@_returning = old_returning
end
else
super()
end
end
end
end
end |
# frozen_string_literal: true
class UsersController < ApplicationController
PER_PAGE = 10
def index
@users = User.page(params[:page]).per(PER_PAGE)
end
def show
@user = User.find(params[:id])
end
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
hs2500 = Machine.find_or_create_by(name: 'HS2500')
hs2500_kits = %w(58c 66c 160c 168c 202c 210c 218c 266c 316c 508c 516c cBotV1)
hs2500_kits.each do |kit_name|
kit = Kit.find_or_create_by(name: kit_name)
MachineKitCompatibility.find_or_create_by(machine: hs2500, kit: kit)
end
hsx = Machine.find_or_create_by(name: 'HSX')
hsx_kits = %w(cBotV1 cBotV2 168c 310c 516c Rehyb_R1 PE_R2)
hsx_kits.each do |kit_name|
kit = Kit.find_or_create_by(name: kit_name)
MachineKitCompatibility.find_or_create_by(machine: hsx, kit: kit)
end
next_seq = Machine.find_or_create_by(name: "NextSeq")
next_seq_kits = %w(NEXTSEQ75 NEXTSEQ150 NEXSEQ300)
next_seq_kits.each do |kit_name|
kit = Kit.find_or_create_by(name:kit_name)
MachineKitCompatibility.find_or_create_by(machine: next_seq, kit: kit)
end
hs2000v3 = Machine.find_or_create_by(name: 'HS2000V3')
hs2000v3_kits = %w(cBotV1 44cSR 58c 160c 168c 202c 210c 218c Rehyb_R1Kit IndexPrimerBoxR1&PER2)
hs2000v3_kits.each do |kit_name|
kit = Kit.find_or_create_by(name:kit_name)
MachineKitCompatibility.find_or_create_by(machine: hs2000v3, kit: kit)
end
|
class Lead < ActiveRecord::Base
validates_presence_of :name, :tel, :email, :obs
def self.search(search)
if search
where('name LIKE ?', "%#{search}%")
else
scoped
end
end
end
|
class Anagram
attr_reader :word
def initialize(word)
@word = word.downcase
end
def match(possibles)
possibles.filter do |possible|
possible.downcase != word &&
possible.downcase.chars.sort == word.chars.sort
end
end
end
|
# frozen_string_literal: true
require_relative '../lib/rmk.rb'
require_relative '../plugins/github-release.rb'
include GithubRelease
describe GithubRelease do
around(:each) do |example|
EventMachine.run do
Fiber.new do
example.run
EventMachine.stop
end.resume
end
end
it 'returns last release' do
release = github_release('istio', 'istio')
expect(release[0].result.tag_name).to match(/\d+\.\d+\.\d+/)
end
end
|
class CreaturesController < ApplicationController
before_action :set_creature, only: [:show, :edit, :update, :destroy]
before_action :is_admin, only: [:edit, :update, :destroy]
def search_config
@search_config ||= {
path: "/creatures/search",
placeholder: "Search Creatures"
}
end
# GET /creatures
# GET /creatures.json
def index
@creatures = Creature.all
end
#Search
def search
logger.debug "[Creature] hit basic search"
@creatures = Creature.search({name: params[:query]})
j render :index, layout: false
end
# POST /creatures/advanced_search
def search2
logger.debug "[Creature] hit advanced search"
@creatures = Creature.search(search_params)
j render :index, layout: false
end
def advanced_search
render :search
end
# GET /creatures/1
# GET /creatures/1.json
def show
end
# GET /creatures/new
def new
@creature = Creature.new
end
# GET /creatures/1/edit
def edit
end
# POST /creatures
# POST /creatures.json
def create
@creature = Creature.new(creature_params)
respond_to do |format|
if @creature.save
format.html { redirect_to @creature, notice: 'Creature was successfully created.' }
format.json { render :show, status: :created, location: @creature }
else
format.html { render :new }
format.json { render json: @creature.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /creatures/1
# PATCH/PUT /creatures/1.json
def update
respond_to do |format|
if @creature.update(creature_params)
format.html { redirect_to @creature, notice: 'Creature was successfully updated.' }
format.json { render :show, status: :ok, location: @creature }
else
format.html { render :edit }
format.json { render json: @creature.errors, status: :unprocessable_entity }
end
end
end
# DELETE /creatures/1
# DELETE /creatures/1.json
def destroy
@creature.destroy
respond_to do |format|
format.html { redirect_to creatures_url, notice: 'Creature was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_creature
@creature = Creature.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def creature_params
params.require(:creature).permit(
:name,
:type,
:subtype,
:size,
:alignment,
:ac,
:ac_type,
:hp,
:hp_dice,
:speed,
:swim,
:burrow,
:climb,
:fly,
:strength,
:dexterity,
:constitution,
:intellect,
:wisdom,
:charisma,
:str_saving,
:dex_saving,
:con_saving,
:int_saving,
:wis_saving,
:chr_saving,
:perception,
:blindsight,
:darkvision,
:tremorsense,
:truesight,
:challenge,
creature_actions_attributes: [
:id,
:name,
:damage_dice,
:description,
:range,
:_destroy,
],
abilities_attributes: [:id, :name, :description, :_destroy],
skills_attributes: [:id, :name, :bonus, :_destroy],
spells_attributes: [:id, :name, :description, :level, :dice, :_destroy],
damage_immunities_attributes: [:id, :name, :_destroy],
damage_vulnerabilities_attributes: [:id, :name, :_destroy],
damage_resistances_attributes: [:id, :name, :_destroy],
condition_immunities_attributes: [:id, :name, :_destroy],
languages_attributes: [:id, :name, :_destroy],
)
end
end
|
class ChangeUserFullnameToFullName < ActiveRecord::Migration[6.1]
def change
rename_column :users, :fullname, :full_name
end
end
|
csc <<-EOL
public interface IDoFoo {
int Foo(string str);
int Foo(int i);
int Foo(string str, int i);
}
public interface IDoStuff {
int StuffFoo(int foo);
string StuffBar(int bar);
}
public class ConsumeIDoFoo {
public static int ConsumeFoo1(IDoFoo foo) {
return foo.Foo("hello");
}
public static int ConsumeFoo2(IDoFoo foo) {
return foo.Foo(1);
}
public static int ConsumeFoo3(IDoFoo foo) {
return foo.Foo("hello", 1);
}
}
public class ConsumeIDoStuff {
public static int ConsumeStuffFoo(IDoStuff stuff) {
return stuff.StuffFoo(1);
}
public static string ConsumeStuffBar(IDoStuff stuff) {
return stuff.StuffBar(2);
}
}
public interface IExposing {
event EventHandler<EventArgs> IsExposedChanged;
bool IsExposed {get; set;}
}
public partial class Klass {
public object AddEvent(IExposing arg) {
arg.IsExposedChanged += EH;
return arg;
}
public object RemoveEvent(IExposing arg) {
arg.IsExposedChanged -= EH;
return arg;
}
public void EH(object sender, EventArgs e) {
_foo += 1;
}
}
public interface IEmptyInterface {}
public interface IInterface { void m();}
public class ImplementsIInterface : IInterface {
public void m() {
return;
}
}
public interface I1 { string M(); }
public interface I2 { string M(); }
public interface I3<T> { string M(); }
public interface I4 { string M(int arg); }
public class ClassI1_1 : I1 {
string I1.M() { return "I1.M"; }
}
public class ClassI1_2 : I1 {
string I1.M() { return "I1.M"; }
public string M() { return "class M"; }
}
public class ClassI2I1 : I2, I1 {
string I1.M() { return "I1.M"; }
string I2.M() { return "I2.M"; }
}
public class ClassI3Obj : I3<object> {
string I3<object>.M() { return "I3<object>.M"; }
public string M() { return "class M"; }
}
public class ClassI1I2I3Obj : I1, I2, I3<object> {
string I1.M() { return "I1.M"; }
string I2.M() { return "I2.M"; }
string I3<object>.M() { return "I3<object>.M"; }
public string M() { return "class M"; }
}
public class ClassI3_1<T> : I3<T> {
string I3<T>.M() { return "I3<T>.M"; }
public string M() { return "class M"; }
}
public class ClassI3_2<T> : I3<T> {
string I3<T>.M() { return "I3<T>.M"; }
}
public class ClassI3ObjI3Int : I3<object>, I3<int> {
string I3<object>.M() { return "I3<object>.M";}
string I3<int>.M() { return "I3<int>.M";}
}
public class ClassI1I4 : I1, I4 {
string I1.M() { return "I1.M"; }
string I4.M(int arg) { return "I4.M"; }
}
public class PublicIPublicInterface : IPublicInterface {
public IPublicInterface Hello {
get { return this; }
set {}
}
public void Foo(IPublicInterface f) {
}
public IPublicInterface RetInterface() {
return this;
}
public event PublicDelegateType MyEvent;
public IPublicInterface FireEvent(PublicEventArgs args) {
return MyEvent(this, args);
}
public PublicEventArgs GetEventArgs() {
return new PublicEventArgs();
}
}
public class PublicEventArgs : EventArgs { }
class PrivateEventArgs : PublicEventArgs { }
public delegate IPublicInterface PublicDelegateType(IPublicInterface sender, PublicEventArgs args);
// Private class
class PrivateClass : IPublicInterface {
public IPublicInterface Hello {
get { return this; }
set { }
}
public void Foo(IPublicInterface f) {
}
public IPublicInterface RetInterface() {
return this;
}
public event PublicDelegateType MyEvent;
public IPublicInterface FireEvent(PublicEventArgs args) {
return MyEvent(this, args);
}
public PublicEventArgs GetEventArgs() {
return new PrivateEventArgs();
}
}
//Public class
public class PublicClass : IPublicInterface {
public IPublicInterface Hello {
get { return this; }
set { }
}
public void Foo(IPublicInterface f) {
}
public IPublicInterface RetInterface() {
return this;
}
public event PublicDelegateType MyEvent;
public IPublicInterface FireEvent(PublicEventArgs args) {
return MyEvent(this, args);
}
public PublicEventArgs GetEventArgs() {
return new PublicEventArgs();
}
}
// Public Interface
public interface IPublicInterface {
IPublicInterface Hello { get; set; }
void Foo(IPublicInterface f);
IPublicInterface RetInterface();
event PublicDelegateType MyEvent;
IPublicInterface FireEvent(PublicEventArgs args);
PublicEventArgs GetEventArgs();
}
// Access the private class via the public interface
public class InterfaceOnlyTest {
public static IPublicInterface PrivateClass {
get {
return new PrivateClass();
}
}
}
public interface IHaveGenerics {
T GenericsHere<T>(string arg1);
T MoreGenericsHere<T,S>(S x);
}
public class EatIHaveGenerics {
public static string TestGenericsHere(IHaveGenerics ihg){
return ihg.GenericsHere<string>("test");
}
public static string TestMoreGenericsHere(IHaveGenerics ihg){
return ihg.MoreGenericsHere<string, int>(1);
}
}
EOL
no_csc do
class RubyHasGenerics
include IHaveGenerics
def generics_here(arg)
"ruby generics here"
end
def more_generics_here(arg)
"ruby more generics here"
end
end
class RubyImplementsIInterface
include IInterface
def m; end
end
class RubyImplementsIDoFoo
include IDoFoo
def foo(str, i = 1)
i
end
end
class RubyImplementsIDoStuff
include IDoStuff
def stuff_foo(foo)
foo
end
def stuff_bar(bar)
bar.to_s
end
end
class RubyImplementsIDoFooDefaults
include IDoFoo
end
class RubyImplementsIDoStuffDefaults
include IDoStuff
end
class RubyImplementsIDoFooMM
include IDoFoo
attr_reader :tracker
def method_missing(meth, *args, &blk)
@tracker = "IDoFoo MM #{meth}(#{args})"
args.size
end
end
class RubyImplementsIDoStuffMM
include IDoStuff
def method_missing(meth, *args, &blk)
"IDoStuff MM #{meth}(#{args})"
end
end
module Events
attr_reader :handlers
def initialize
reset
end
def reset
@handlers = []
end
def trigger
@handlers.each {|e| e.invoke(self, nil)}
end
end
class RubyExposerDefault
include IExposing
end
class RubyExposerMM
include IExposing
include Events
def method_missing(meth, *args, &blk)
case meth.to_s
when /^add_/
@handlers << args[0]
"Method Missing add"
when /^remove_/
@handlers.delete args[0]
"Method Missing remove"
else raise NoMethodError.new(meth, *args, &block)
end
end
end
class RubyExposer
include IExposing
include Events
def add_IsExposedChanged(h)
@handlers << h
"Ruby add handler"
end
def remove_IsExposedChanged(h)
@handlers.delete h
"Ruby remove handler"
end
end
end
|
class TestSensuBase < TestCase
def test_read_config_files
base = Sensu::Base.new(@options)
settings = base.settings
assert(settings.mutator_exists?(:tag))
assert(settings.handler_exists?(:stdout))
assert(settings.check_exists?(:standalone))
done
end
def test_config_snippets
new_handler = {
:handlers => {
:new_handler => {
:type => 'pipe',
:command => 'cat'
}
}
}
merge_check = {
:checks => {
:merger => {
:interval => 60,
:auto_resolve => false
}
}
}
create_config_snippet('new_handler', new_handler)
create_config_snippet('merge_check', merge_check)
base = Sensu::Base.new(@options)
settings = base.settings
assert(settings.handler_exists?(:new_handler))
assert_equal('pipe', settings[:handlers][:new_handler][:type])
assert_equal('cat', settings[:handlers][:new_handler][:command])
assert(settings.check_exists?(:merger))
assert('exit', settings[:checks][:merger][:command])
assert_equal(60, settings[:checks][:merger][:interval])
assert_equal(false, settings[:checks][:merger][:auto_resolve])
done
end
def test_read_env
base = Sensu::Base.new(@options)
settings = base.settings
assert(settings[:rabbitmq].is_a?(Hash))
ENV['RABBITMQ_URL'] = 'amqp://guest:guest@localhost:5672/'
settings.load_env
assert(settings.loaded_env)
assert_equal(ENV['RABBITMQ_URL'], settings[:rabbitmq])
done
end
def test_set_env
create_config_snippet('snippet', Hash.new)
base = Sensu::Base.new(@options)
settings = base.settings
settings.set_env
expected = [@options[:config_file], @options[:config_dir] + '/snippet.tmp.json'].join(':')
assert_equal(expected, ENV['SENSU_CONFIG_FILES'])
done
end
def test_write_pid
pid_file = '/tmp/sensu_write_pid'
Sensu::Base.new(@options.merge(:pid_file => pid_file))
assert(File.exists?(pid_file), 'PID file does not exist')
assert_equal(Process.pid.to_s, File.read(pid_file).chomp)
done
end
end
|
module AuthHelpers
def current_user #=> User instance || nil
# Memoization
if @current_user
@current_user
else
@current_user = User.find_by(id: session[:user_id])
end
end
def is_logged_in?
if current_user
true
else
false
end
end
end
# class Auth
#
# def current_user
# @current_user
# end
#
# def current_user=(user)
# @current_user = user
# end
# end
#
# auth = Auth.new
# auth.current_user #=> nil
# auth.current_user = User.create(username: 'lukeghenco')
# auth.current_user #=> #<User id: 1, username: "lukeghenco">
|
module Skiima
module Dependency
class Reader
attr_accessor :scripts
attr_accessor :dependencies, :adapter, :version
def initialize(dependencies, adapter, opts = {})
@dependencies, @adapter = dependencies, adapter.to_sym
@version = opts[:version] || :current
end
def adapter
case @adapter.to_s
when 'mysql', 'mysql2' then :mysql
else @adapter
end
end
def get_group(g)
raise Skiima::SqlGroupNotFound unless dependencies.has_key?(g)
dependencies[g]
end
def get_adapter(grp)
grp.has_key?(adapter) ? (grp[adapter] || {}) : {}
end
def get_scripts(group, version_grp)
scr = (version_grp.has_key?(version) ? (version_grp[version] || {}) : {})
sc = scr.map {|s| Skiima::Dependency::Script.new(group, adapter, version, s)}
end
def get_load_order(*groups)
opts = groups.last.is_a?(Hash) ? groups.pop : {}
@scripts = groups.inject([]) do |memo, g|
grp = get_group(g)
scripts = if grp.is_a?(Hash) || (opts[:node] == :internal)
get_scripts(g, Skiima.symbolize_keys(read_script_group(grp)))
else
get_load_order(*(grp.map(&:to_sym)), node: :internal)
end
memo + scripts
end
end
private
def read_script_group(leaf_node)
get_adapter(Skiima.symbolize_keys(leaf_node))
end
end
end
end
|
class ProjectSolutionsController < ApplicationController
before_action :private_access
before_action :paid_access
before_action :set_project
# GET /subjects/:subject_id/projects/:project_id/project_solutions/:id
def show
@project_solution = ProjectSolution.find(params[:id])
if !current_user.is_admin? && !current_user.has_completed_project?(@project)
flash[:notice] = "Debes publicar tu solución para ver las soluciones de la comunidad."
redirect_to subject_project_path(@project.subject,@project)
end
end
# GET /subjects/:subject_id/projects/:project_id/project_solutions
def index
if current_user.is_admin? || current_user.has_completed_project?(@project)
@own_project_solution = @project.project_solutions.find_by_user_id(current_user.id)
@project_solutions = @project.project_solutions.where.not(user_id: current_user.id)
else
flash[:notice] = "Debes publicar tu solución para ver las soluciones de la comunidad."
redirect_to subject_project_path(@project.subject,@project)
end
end
# POST /subjects/:subject_id/projects/:project_id/project_solutions
def create
@project_solution = @project.project_solutions.build(project_solution_params)
@project_solution.user = current_user
if @project_solution.save
flash[:notice] = "Tu solución ha sido publicada, ahora ayuda a los demás con tu opinión"
redirect_to subject_project_project_solutions_path(@project.subject,@project)
else
render "projects/show"
end
end
def update
@project_solution = current_user.project_solutions.find(params[:id])
if @project_solution.update(project_solution_params)
flash[:notice] = "Tu solución ha sido actualizada"
redirect_to subject_project_project_solutions_path(@project.subject,@project)
else
render "projects/show"
end
end
def request_revision
@project_solution = ProjectSolution.find(params[:id])
@project_solution.pending_review!
redirect_to request.referer
end
protected
def set_project
@project = Project.find(params[:project_id])
end
def project_solution_params
params.require(:project_solution).permit(:repository,:url,:summary)
end
end
|
# This is the animal Class from classes 13 and 14
# The animal class takes in a name and a color, with the Zebra class creating a specific method for stripes and the Tiger class having a specific method for speaking that overrides the generic speak method in Animal
class Animal
attr_accessor :color, :name
def initialize( name, color )
@color = color
@name = name
end
def identify
return "I am a #{self.class}"
end
def speak
return "hello my name is #{@name}"
end
# Useful for if we want to write this to a file
def to_csv
return "#{@name}, #{@color}"
end
end
class Tiger < Animal
# We can use super to add on/inhereit from the class above
def speak
return super + " grrrr"
end
end
class Zebra < Animal
attr_reader :stripes
# Using super again to get name/color, and to add on stripes
def initialize( name, color, stripes )
@stripes = stripes
super(name, color)
end
def to_csv
return "#{@name}, #{@color}, #{@stripes}"
end
end
class Hyena < Animal
end
|
require 'spec_helper'
describe "opendata_licenses", type: :feature, dbscope: :example do
let(:site) { cms_site }
let(:node) { create_once :opendata_node_dataset, name: "opendata_dataset" }
let(:index_path) { opendata_licenses_path site.host, node }
let(:new_path) { new_opendata_license_path site.host, node }
it "without login" do
visit index_path
expect(current_path).to eq sns_login_path
end
it "without auth" do
login_ss_user
visit index_path
expect(status_code).to eq 403
end
context "with auth" do
before { login_cms_user }
describe "#index" do
it do
visit index_path
expect(current_path).not_to eq sns_login_path
end
end
describe "#new" do
it do
visit new_path
within "form#item-form" do
fill_in "item[name]", with: "sample"
attach_file "item[in_file]", "#{Rails.root}/spec/fixtures/ss/logo.png"
click_button "保存"
end
expect(status_code).to eq 200
expect(current_path).not_to eq new_path
expect(page).not_to have_css("form#item-form")
end
end
describe "#show" do
let(:license_logo_file_path) { Rails.root.join("spec", "fixtures", "ss", "logo.png") }
let(:license_logo_file) { Fs::UploadedFile.create_from_file(license_logo_file_path, basename: "spec") }
let(:item) { create(:opendata_license, site: site, file: license_logo_file) }
let(:show_path) { opendata_license_path site.host, node, item }
it do
visit show_path
expect(status_code).to eq 200
expect(current_path).not_to eq sns_login_path
end
end
describe "#edit" do
let(:license_logo_file_path) { Rails.root.join("spec", "fixtures", "ss", "logo.png") }
let(:license_logo_file) { Fs::UploadedFile.create_from_file(license_logo_file_path, basename: "spec") }
let(:item) { create(:opendata_license, site: site, file: license_logo_file) }
let(:edit_path) { edit_opendata_license_path site.host, node, item }
it do
visit edit_path
within "form#item-form" do
fill_in "item[name]", with: "modify"
click_button "保存"
end
expect(current_path).not_to eq sns_login_path
expect(page).not_to have_css("form#item-form")
end
end
describe "#delete" do
let(:license_logo_file_path) { Rails.root.join("spec", "fixtures", "ss", "logo.png") }
let(:license_logo_file) { Fs::UploadedFile.create_from_file(license_logo_file_path, basename: "spec") }
let(:item) { create(:opendata_license, site: site, file: license_logo_file) }
let(:delete_path) { delete_opendata_license_path site.host, node, item }
it do
visit delete_path
within "form" do
click_button "削除"
end
expect(current_path).to eq index_path
end
end
end
end
|
class RenameAddressBookTable < ActiveRecord::Migration[5.1]
def change
rename_table :address_books, :addresses
end
end
|
require 'sinatra/base'
require_relative 'redis_cache.rb'
module Sinatra
module FixerApi
API_URL = "http://data.fixer.io/api/".freeze
def get_exchange_rate(date, base_currency)
redis_key = date.to_s + base_currency
result_from_redis = RedisCache.execute_cache(redis_key) do
uri = URI("#{API_URL}#{date}")
params = {
access_key: ENV['ACCESS_TOKEN'],
base: base_currency,
symbols: "USD"
}
get_data_from_fixer(uri, params)
end
end
def get_data_from_fixer(uri, params)
uri.query = URI.encode_www_form(params)
res = Net::HTTP.get_response(uri)
res.body if res.is_a?(Net::HTTPSuccess)
end
end
helpers FixerApi
end
|
# top-reference
class AddStatusToEstimationSession < ActiveRecord::Migration[5.0]
def change
add_column :estimation_sessions, :status, :string
end
end
|
class RenameOperationalFiledToOperationalFieldActors < ActiveRecord::Migration
def change
rename_column :actors, :operational_filed, :operational_field
end
end
|
class User < ActiveRecord::Base
#before_create :set_default_roles
#before_update :set_default_roles
rolify
delegate :can?, :cannot?, :to => :ability
has_and_belongs_to_many :roles, :join_table => :users_roles
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :first_name, :last_name, :email, :password, :password_confirmation, :remember_me, :role_ids
validates :first_name, :presence => true
validates :last_name, :presence => true
validates :password,
:presence => true,
:length => {:within => 6..40},
:on => :create,
:confirmation => true,
:if => lambda{ new_record? || !password.nil? }
validates :password_confirmation, :presence => true, :on => :create
validates :email, :presence => true
validates_email_format_of :email
include PgSearch
pg_search_scope :search_by_full_name,
:against => [:first_name, :last_name],
:using => {
:tsearch => {:prefix => true}
}
def self.search(search)
if !search.blank? && search
self.search_by_full_name(search)
else
scoped
end
end
def current_ability
current_user.ability
end
def name
[first_name, last_name].join " "
end
def name_reversed
[last_name, first_name].join ", "
end
protected
def password_required?
false
end
private
def set_default_roles
if !Role.find_by_name('normal').nil?
self.roles << Role.find_by_name('normal')
end
end
end
|
#extra features
# Clear Board
def start_game
# Create initial conditions for while loop
game_over = false
#Create Board
board = [nil] * 9
#Assign Player value
player = "X"
while game_over != true
# run through all the steps in the game loop
#Print board
# To call function in the while loop
print_game_board(board)
#Tell user which turn: X or O
#Tell user to input move
#Get input
user_input = gets.chomp
space = user_input.to_i
#Convert the input to a board space :array
#Check if it is a valid move
if space_available?(board, space)
board[space] = player
#Check if game over: full or win
if game_over?(board)
#If it is: set Game Over to true
game_over = true
puts("Congratulations player #{player} wins")
else
#If it is not: switch players
player = switch_player(player)
end
else
puts("That was an invalid move. Please try again")
end
#If it is not: Ask user to give new input
#Else: Enter move into array
end
end
def start_game
#Create Board
board = [nil] * 9
#Assign Player value
player = "X"
loop do
#Print board
print_game_board(board)
#Tell user which turn: X or O
puts "Players turn: #{player}"
# Tell user to input move
# Get input
user_input = gets.chomp
space = user_input.to_i
# Check if it is a valid move
if !space_available?(board, space)
puts("That was an invalid move. Please try again")
next
end
board[space] = player
#Check if game over: full or win
if game_over?(board)
puts("Congratulations player #{player} wins")
break
end
player = switch_player(player)
end
end
# This is put in the same file below the other functions
def game_over?(board)
check_for_win(board) || all_spots_taken?(board)
end
def check_for_win(board)
# Check rows for win
row_win(board) ||
# Check columns for win
col_win(board) ||
# check diagonals for win
diag_win(board)
end
def row_win(board)
(board[0] && board[0] == board[1] && board[0] == board[2]) ||
(board[3] && board[3] == board[4] && board[3] == board[5]) ||
(board[6] && board[6] == board[7] && board[6] == board[8])
end
def col_win(board)
(board[0] && board[0] == board[3] && board[0] == board[6]) ||
(board[1] && board[1] == board[1] && board[4] == board[7]) ||
(board[2] && board[2] == board[5] && board[2] == board[8])
end
def diag_win(board)
(board[0] && board[0] == board[4] && board[0] == board[8]) ||
(board[2] && board[2] == board[4] && board[2] == board[6])
end
def all_spots_taken?(board)
# Check that all spots have been taken
!board.include?(nil)
end
def space_available?(board, space)
if board[space] == nil
return true
else
return false
end
end
def switch_player(player)
if player == "X"
player = "O"
else
player = "X"
end
return player
end
def get_value(value)
if value == nil
value = " "
else
value = " " + value + " "
end
return value
end
# Structure of function
def print_game_board(board)
# print first row of spaces
puts(get_value(board[0]) + "|" + get_value(board[1]) + "|" + get_value(board[2]))
# print divider
puts("-" * 11)
# print second row of spaces
puts(get_value(board[3]) + "|" + get_value(board[4]) + "|" + get_value(board[5]))
# print divider
puts("-" * 11)
# print third row of spaces
puts(get_value(board[6]) + "|" + get_value(board[7]) + "|" + get_value(board[8]))
end
board = [nil] * 9
#start_game # this starts the game. You can also call this in the repl interactive environment
|
class ReassociateSiteTypeWithSite < ActiveRecord::Migration[6.1]
def change
# Change site type from a many-to-one association with context (formerly
# site_phase) to a many-to-many association with site.
create_table :sites_site_types, id: false do |t|
t.belongs_to :site
t.belongs_to :site_type
end
# Migrate existing associations
execute %(
INSERT INTO sites_site_types
SELECT site_id, site_type_id FROM contexts
WHERE site_id IS NOT NULL AND site_type_id IS NOT NULL
)
# Drop old association
remove_reference :contexts, :site_type
end
end
|
class PropertyVideo < ActiveRecord::Base
attr_accessible :name, :youtube, :property_id
belongs_to :property
end
|
#!/usr/bin/env ruby
def create_machines_hash
return {} unless File.exist? '/etc/facter/facts.d/aws_environment.txt'
machines_names_hash = Hash.new
`/usr/local/bin/govuk_node_list --with-puppet-class`.each_line do |machine|
hostname, name = machine.chomp.split(":")
machines_names_hash[hostname] = name
end
return machines_names_hash
end
def hostname_with_node_name(hostname, machines_names_hash)
name = machines_names_hash[hostname]
if name
"%s with hostname: %s" % [name, hostname]
else
hostname
end
end
all_machines = `/usr/local/bin/govuk_node_list`.split("\n")
unsafe_machines = `/usr/local/bin/govuk_node_list --puppet-class govuk_safe_to_reboot::careful,govuk_safe_to_reboot::no`.split("\n")
safe_machines = `/usr/local/bin/govuk_node_list --puppet-class govuk_safe_to_reboot::yes,govuk_safe_to_reboot::overnight`.split("\n")
machines_names_hash = create_machines_hash
# Safety check that we haven't added other safe to reboot options
# that we don't account for here.
unchecked_machines = all_machines - (unsafe_machines + safe_machines)
if unchecked_machines.length > 0
puts "Some machines have a 'safe to reboot' class which isn't in check_reboots_required"
exit 3
end
[unsafe_machines, safe_machines].each do |host_list|
host_list.delete_if do |host|
`/usr/lib/nagios/plugins/check_nrpe -H #{host} -t 20 -c check_reboot_required -u`
$?.to_i == 0
end
end
if safe_machines.length + unsafe_machines.length == 0
puts 'No hosts need to be rebooted'
exit 0
else
puts 'Some hosts need to be rebooted to apply updates'
if unsafe_machines.length > 0
puts "\n"
puts 'These hosts need to be rebooted manually:'
unsafe_machines.sort.each do |hostname|
hydrated_name = hostname_with_node_name(hostname, machines_names_hash)
puts "- #{hydrated_name}"
end
end
if safe_machines.length > 0
puts "\n"
puts 'These hosts should reboot overnight:'
safe_machines.sort.each do |hostname|
hydrated_name = hostname_with_node_name(hostname, machines_names_hash)
puts "- #{hydrated_name}"
end
end
exit 1
end
|
source 'https://rubygems.org'
gemspec
rails_version = ENV['RAILS_VERSION'] || 'default'
rails = case rails_version
when 'default'
'4.2.1'
when '4.0'
{ github: 'rails/rails', branch: '4-0-stable' }
when '4.1'
{ github: 'rails/rails', branch: '4-1-stable' }
when '4.2'
{ github: 'rails/rails', branch: '4-2-stable' }
else
"~> #{rails_version}"
end
gem 'rails', rails
group :development, :test do
gem 'byebug'
gem 'ffaker'
gem 'rspec-rails'
gem 'factory_girl'
gem 'shoulda-matchers', require: false
gem 'codeclimate-test-reporter', require: false
gem 'rubocop'
gem 'spring'
gem 'generator_spec'
end
|
require 'Foursquare'
class Attraction < ActiveRecord::Base
has_many :pictures
has_many :votes
validates :name, presence: true
def self.import_foursquare_attractions(city, num_attractions = 50, trip_id = nil)
begin
response = JSON.parse(Foursquare.import_attractions(city, num_attractions))
attractions = response["response"]["groups"].first["items"]
if attractions.length == 0
return false
end
new_city = City.new(:name => city.titleize, :lat => response["response"]["geocode"]["center"]["lat"],
:lng => response["response"]["geocode"]["center"]["lng"])
new_city.save
for attraction in attractions
picture_path = attraction["venue"]["featuredPhotos"]["items"].first["prefix"] + "240x240" +
attraction["venue"]["featuredPhotos"]["items"].first["suffix"]
picture = Picture.new(:path => picture_path)
picture = picture.save ? picture : nil
new_attraction = self.new(:name => attraction["venue"]["name"],
:city => city,
:category => attraction["venue"]["categories"].first["name"],
:description => attraction["tips"].first["text"],
:address => attraction["venue"]["location"]["formattedAddress"].join(", "),
:latitude => attraction["venue"]["location"]["lat"],
:longitude => attraction["venue"]["location"]["lng"],
:rating => attraction["venue"]["rating"],
:url => attraction["venue"]["url"],
:picture_id => picture.present? ? picture.id : nil)
if new_attraction.save and picture
picture.update_attributes(:attraction_id => new_attraction)
picture.save
end
end
rescue StandardError
return false
end
return true
end
#day: int representing Mon-Sun as an int (1-7)
#start_time: int, e.g. 0800
#end_time: int, e.g. 1600
def is_open?(day, start_time, end_time)
in_timeframe? day, start_time, end_time, "hours"
end
def num_hours_popular(start_time)
count = 0
hour_minutes = start_time.hour * 100 + start_time.minute
if in_timeframe? start_time.wday, hour_minutes, hour_minutes + 100, "popular"
count += 1
end
if in_timeframe? start_time.wday, hour_minutes + 100, hour_minutes + 200, "popular"
count += 1
end
return count
end
def in_timeframe?(day, start_time, end_time, hours_type)
#hours_json format: https://developer.foursquare.com/docs/explore#req=venues/40a55d80f964a52020f31ee3/hours
if self.hours_json.nil?
self.import_hours_json
end
if self.hours_json[hours_type].nil?
if hours_type == "hours"
return true
else
return false
end
end
timeframes = self.hours_json[hours_type]["timeframes"]
if timeframes.nil?
if hours_type == "hours"
return true
else
return false
end
end
for timeframe in timeframes
if timeframe["days"].include? day
for open_time in timeframe["open"]
# is open all day
if open_time["start"] == "0000" and open_time["end"] == "+0000"
return true
end
frame_start = open_time["start"].to_i
frame_end = open_time["end"] == "+0000" ? 2400 : open_time["end"].to_i
if frame_start <= start_time and frame_end >= end_time
return true
end
end
end
end
return false
end
def import_hours_json
attraction_hours_response = JSON.parse(Foursquare.import_hours(self))["response"]
self.update_attributes(:hours_json => attraction_hours_response)
self.save
end
end
|
class Location < ActiveRecord::Base
include Coded
serialize :options
belongs_to :area
has_one :map, as: :parent
has_many :exits
has_many :actions, as: :actionable
def self.game_start
Location.lookup 'bar/common'
end
# === Location Seed ===
def self.manufacture_each data
data.flatten.each do |datum|
Location.manufacture datum
end
data.flatten.each do |datum|
if datum[:exits].present?
Location.manufacture_exits datum[:location][:code], datum[:exits]
end
end
end
def self.manufacture data
area_code = data[:location][:code].match(/^([^\/]+)/)[1]
location = Location.create data[:location]
location.update_attribute :area, Area.lookup(area_code)
if data[:options].present?
options = data[:options]
end
Map.manufacture location
Action.manufacture_each location, data[:actions]
end
def self.manufacture_exits location_code, exits
location = Location.lookup location_code
exits.each do |exit|
location.exits.create(
name: exit[:name],
key: exit[:key],
duration: (exit[:duration] || 0),
destination: Location.lookup(exit[:to])
)
end
end
end
|
class SchoolClassesController < ApplicationController
def index
@school_classes = SchoolClass.all
end
def new
@school_class = SchoolClass.new
end
def create
@school_class = SchoolClass.create(school_class_params)
redirect_to school_class_path(@school_class)
end
def show
@school_class = SchoolClass.find(params[:id])
render :show
end
def edit
@school_class = SchoolClass.find(params[:id])
end
def update
@school_class = SchoolClass.find(params[:id])
@school_class.update(school_class_params)
redirect_to school_class_path(@school_class)
end
private
# Using a private method to encapsulate the permissible parameters is
# a good pattern since you'll be able to reuse the same permit
# list between create and update. Also, you can specialize this method
# with per-user checking of permissible attributes.
def school_class_params
params.require(:school_class).permit(:title, :room_number)
end
end
|
# -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "ecology/version"
Gem::Specification.new do |s|
s.name = "ecology"
s.version = Ecology::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Noah Gibbs"]
s.email = ["noah@ooyala.com"]
s.homepage = "http://www.ooyala.com"
s.summary = %q{Ruby config variable management}
s.description = <<EOS
Ecology sets configuration data for an application based
on environment variables and other factors. It is meant
to unify configuration data for logging, testing, monitoring
and deployment.
EOS
s.rubyforge_project = "ecology"
ignores = File.readlines(".gitignore").grep(/\S+/).map {|pattern| pattern.chomp }
dotfiles = Dir[".*"]
s.files = Dir["**/*"].reject {|f| File.directory?(f) || ignores.any? {|i| File.fnmatch(i, f) } } + dotfiles
s.test_files = s.files.grep(/^test\//)
s.executables << "with_ecology"
s.bindir = "bin"
s.require_paths = ["lib"]
s.add_dependency "multi_json"
s.add_dependency "erubis"
s.add_development_dependency "bundler", "~> 1.0.10"
s.add_development_dependency "scope", "~> 0.2.1"
s.add_development_dependency "mocha"
s.add_development_dependency "rake"
end
|
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable, and :registerable
devise :database_authenticatable, :recoverable, :rememberable, :trackable, :validatable
attr_accessible :email, :password, :password_confirmation, :remember_me
has_many :problem_types, :foreign_key => "owner_id"
has_many :lessons, :foreign_key => "owner_id"
end
|
require 'csv'
# Строка данных для импорта
class ImportItem < ActiveRecord::Base
CSV_ATTRIBUTES = [ :fio, :email, :organization_name, :project_name, :group,
:login, :phone, :jsoned_directions, :jsoned_technologies, :jsoned_areas,
:jsoned_keys ]
belongs_to :cluster
validates :first_name, :last_name, :middle_name, :email, :organization_name,
:project_name, :group, :login, :keys, presence: true
attr_accessor :additional_email
attr_accessible :file, :first_name, :middle_name, :last_name,
:organization_name, :project_name, :group, :login, :email, :additional_email,
as: :admin
serialize :keys
serialize :directions
serialize :technologies
serialize :areas
def self.create_by_file_and_cluster(attributes)
cluster = Cluster.find(attributes[:cluster_id])
transaction do
attributes[:file].read.each_line do |line|
data = line.parse_csv(col_sep: ";", quote_char: "'")
create! do |item|
CSV_ATTRIBUTES.each_with_index do |attribute, index|
item.send "#{attribute}=", data[index].strip
end
item.cluster = cluster
end
end
end
end
def import(attributes, role)
if update_attributes(attributes, role)
transaction do
@user = create_user!
@org = create_organization!
@membership = create_membership!
@project = create_project!
@surety = create_surety!
@surety_member = create_surety_member!
@account = create_account!
@keys = create_credentials!
@request = create_request!
destroy
end
if @new_user
Mailer.welcome_imported_user(@user.id).deliver
end
true
end
end
def fio=(fio)
last, first, middle = fio.split(' ')
if middle.blank?
middle = '-'
end
self.first_name = first
self.middle_name = middle
self.last_name = last
end
def email=(email)
self[:email] = email.downcase.strip
end
def jsoned_keys=(json)
self.keys = JSON.parse(json).map(&:strip).uniq
end
def jsoned_directions=(json)
self.directions = JSON.parse(json).map(&:strip).uniq
end
def jsoned_technologies=(json)
self.technologies = JSON.parse(json).map(&:strip).uniq
end
def jsoned_areas=(json)
self.areas = JSON.parse(json).map(&:strip).uniq
end
def user_in_json(options)
User.new do |u|
u.first_name = first_name
u.middle_name = middle_name
u.last_name = last_name
u.email = email
end.to_json(options)
end
def similar_users
users = []
users.push *User.where("last_name = :name or first_name = :name or middle_name = :name", name: last_name)
users.push *User.where("email like ?", "%#{email[/^(.*)@/, 1]}%@%")
users.uniq!
users
end
def similar_organizations
Organization.find_similar(organization_name)
end
def organization_in_json(options)
Organization.new do |org|
org.name = organization_name
end.to_json(options)
end
private
def create_user!
user = User.find_by_email(email) || begin
u = User.to_generic_model.create! do |user|
user.first_name = first_name
user.middle_name = middle_name
user.last_name = last_name
user.email = email
user.state = 'sured'
user.activation_state = 'active'
user.token = Digest::SHA1.hexdigest(rand.to_s)
user.phone = phone
user.reset_password_token = SecureRandom.hex(16)
user.reset_password_email_sent_at = Time.now.in_time_zone
user.reset_password_token_expires_at = Time.now.in_time_zone + 1.year
end
@new_user = true
User.find(u.id)
end
user.valid? or raise user.errors.inspect # ActiveRecord::RecordInvalid.new(user)
user.tap do |user|
user.first_name = first_name
user.middle_name = middle_name
user.last_name = last_name
if additional_email.present?
user.additional_emails.build { |e| e.email = additional_email }
end
end.save!
user.send :setup_default_groups
user
end
def create_organization!
organization = Organization.find_by_name(organization_name) || begin
o = Organization.to_generic_model.create! do |org|
org.name = organization_name
org.state = 'active'
org.organization_kind_id = OrganizationKind.first.id
end
o = Organization.find(o.id)
end
organization.valid? or raise organization.errors.inspect
organization
end
def create_membership!
conditions = { organization_id: @org.id, user_id: @user.id }
membership = Membership.where(conditions).first || begin
m = Membership.to_generic_model.create! do |membership|
membership.user_id = @user.id
membership.organization_id = @org.id
membership.state = 'active'
end
end
membership.valid? or raise organization.errors.inspect
membership
end
def create_surety!
s = Surety.to_generic_model.create! do |surety|
surety.organization_id = @org.id
surety.boss_full_name = "Руководитель. И. О."
surety.boss_position = "Должность"
surety.project_id = @project.id
surety.state = 'active'
end
surety = Surety.find(s.id)
surety.valid? or raise surety.errors.inspect
surety
end
def create_surety_member!
s = SuretyMember.to_generic_model.create! do |member|
member.surety_id = @surety.id
member.email = email
member.full_name = @user.full_name
member.user_id = @user.id
end
sm = SuretyMember.find(s.id)
sm.valid? or raise sm.errors.inspect
sm
end
def create_project!
project = @user.projects.find_by_title(project_name) || begin
p = Project.to_generic_model.create! do |project|
project.user_id = @user.id
project.title = project_name
project.description = project_name
project.state = 'active'
project.organization_id = @org.id
project.username = group
end
project = Project.find(p.id)
project.direction_of_sciences = directions.map { |d| DirectionOfScience.find_or_create_by_name!(d) }
project.critical_technologies = technologies.map { |t| CriticalTechnology.find_or_create_by_name!(t) }
project.research_areas = areas.map do |a|
ResearchArea.find_or_create_by_name!(a) do |ra|
ra.group = "Без группы"
end
end
project
end
project.valid? or raise project.errors.inspect
project
end
def create_account!
conditions = { user_id: @user.id, project_id: @project.id }
account = Account.where(conditions).first || begin
a = Account.to_generic_model.create! do |account|
account.user_id = @user.id
account.project_id = @project.id
account.access_state = 'allowed'
account.cluster_state = 'active'
account.username = login
end
a = Account.find(a.id)
end
account.valid? or raise account.errors.inspect
account
end
def create_credentials!
keys.map do |key|
key = @user.credentials.where(public_key: key).first || begin
c = Credential.to_generic_model.create! do |c|
c.name = key[0..6]
c.state = 'active'
c.user_id = @user.id
c.public_key = key
end
Credential.find(c.id)
end
key.valid? or raise key.errors.inspect
key
end
end
def create_request!
@request = begin
r = Request.to_generic_model.create! do |r|
r.state = 'active'
r.user_id = @user.id
r.cluster_project_id = @group.id
r.cpu_hours = 0
r.gpu_hours = 0
r.size = 0
end
Request.find(r.id)
end
end
end
|
# @param {Integer} n
# @return {Integer}
def fib(n)
if n == 0
return 0
elsif n == 1
return 1
end
fib(n-1)+fib(n-2)
end
# @param {Integer[]} candies
# @return {Integer}
def distribute_candies(candies)
num_candies = candies.size
num_uniq_candies = 0
candies_set = Set.new()
candies.each do |candy|
num_uniq_candies += 1 unless candies_set.include?(candy)
candies_set.add(candy)
end
[num_candies/2,num_uniq_candies].min
end
def distribute_candies(candies)
[candies.uniq.size,(candies.size/2)].min
end
def last_stone_weight(stones)
sorted_stones = stones.sort
while sorted_stones.length > 1
last_stone = sorted_stones.pop
second_to_last_stone = sorted_stones[-1]
diff = (last_stone - second_to_last_stone).abs
diff == 0 ? sorted_stones.pop : sorted_stones[-1] = diff
sorted_stones.sort!
end
sorted_stones.empty? ? 0 : sorted_stones[0]
end
class TimeMap
attr_accessor :cache
def initialize
@cache = Hash.new { |h, k| h[k] = [] }
end
def set(key, value, timestamp)
cache[key][timestamp] = value
end
def get(key, timestamp)
return "" unless cache[key]
return cache[key][timestamp] if cache[key][timestamp]
timestamp.downto(0) do |n|
return cache[key][n] if cache[key][n]
end
""
end
end
# @param {String} s
# @return {Boolean}
def is_valid(s)
visited_left_brackets = []
left_brackets = "({["
s.each_char do |char|
if left_brackets.include?(char)
visited_left_brackets << char
elsif char == ')'
if visited_left_brackets[-1] == '('
visited_left_brackets.pop
else
return false
end
elsif char == '}'
if visited_left_brackets[-1] == '{'
visited_left_brackets.pop
else
return false
end
elsif char == ']'
if visited_left_brackets[-1] == '['
visited_left_brackets.pop
else
return false
end
end
end
visited_left_brackets.length == 0
end
class MinStack
attr_reader :min_stack
=begin
initialize your data structure here.
=end
def initialize()
@min_stack = []
@current_min = nil
end
=begin
:type x: Integer
:rtype: Void
=end
def push(x)
@min_stack << x
if !@current_min || x < @current_min
@current_min = x
end
end
=begin
:rtype: Void
=end
def pop()
last = @min_stack.pop
if @current_min == last
@current_min = @min_stack.min
end
end
=begin
:rtype: Integer
=end
def top()
@min_stack.last
end
=begin
:rtype: Integer
=end
def get_min()
@current_min
end
end
# Your MinStack object will be instantiated and called as such:
# obj = MinStack.new()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.get_min()
# @param {String[]} strs
# @return {String[][]}
def are_anagrams?(str1,str2)
str1.split('').sort == str2.split('').sort
end
def group_anagrams(strs)
grouped_anagrams = [[strs.shift]]
strs.each do |word|
pushed = false
(0...grouped_anagrams.length).each do |anagram_idx|
if are_anagrams?(grouped_anagrams[anagram_idx][0],word)
grouped_anagrams[anagram_idx] << word
pushed = true
end
end
grouped_anagrams << [word] unless pushed
end
grouped_anagrams
end
# Faster solution!
# @param {String[]} strs
# @return {String[][]}
def group_anagrams(strs)
anagram_hash = Hash.new {|hash,key| hash[key] = []}
strs.each do |word|
sorted_word = word.chars.sort
anagram_hash[sorted_word] << word
end
anagram_hash.values
end |
class SidebarsController < InheritedResources::Base
layout 'manager_cms'
def update
update! {edit_sidebar_path(@sidebar)}
end
def sort
@sidebar = @current_account.sidebars.find(params[:id])
unless params[:widget].blank?
@sidebar.widget_placements.delete_all
params[:widget].each_with_index do |widget_id, index|
@sidebar.widget_placements.create(:widget_id => widget_id, :index => index)
end
end
respond_to do |format|
if @sidebar.save
format.js {render :text => 'Success' }
else
# TODO: Handle error properly on server and on client
format.js {render :text => 'Fail' }
end
end
end
protected
# def collection
# @sidebars ||= end_of_association_chain.order('created_at ASC')
# end
def begin_of_association_chain
@current_account
end
end
|
class CreateAccountEmails < ActiveRecord::Migration
def change
create_table :account_emails do |t|
t.references :account
t.string :stripped_email
t.timestamps
end
add_index :account_emails, :account_id
end
end
|
require 'test_helper'
class CarTest < ActiveSupport::TestCase
test "closest_n returns results ordered closest first" do
results = Car.closest_n(2, [-36.849700, 174.776066])
assert_equal results.first.id, cars(:one).id
end
test "closest_n returns no more than n results" do
results = Car.closest_n(1, [-36.849700, 174.776066])
assert_equal results.length, 1
end
test "closest_n respects radius" do
results = Car.closest_n(1, [0, 0], 5)
assert_equal results.length, 0
end
end
|
require_relative('language_error')
class IdEvalAtCompilationError < LanguageError
def initialize(id)
super("Cannot eval identifier '#{id}' at compilation time")
end
end |
module Diffity
class RunDetails
class Jenkins
def branch
ENV.fetch('GIT_BRANCH').split('/').last
end
def author
'Jenkins'.freeze
end
end
class Travis
def branch
ENV.fetch('TRAVIS_BRANCH')
end
def author
'Travis'.freeze
end
end
class GitRepo
def branch
`git rev-parse --abbrev-ref HEAD`.strip
end
def author
`git config user.name`.strip
end
end
class Default
def branch
'HEAD'.freeze
end
def author
'None'.freeze
end
end
def details
if !!ENV['JENKINS_HOME']
Jenkins.new
elsif !!ENV['TRAVIS']
Travis.new
elsif system('git branch')
GitRepo.new
else
Default.new
end
end
end
end
|
class AddForeingKeyDepartaments < ActiveRecord::Migration
def change
add_column :mytickets, :customers_id, :integer
add_column :mytickets, :departaments_id, :integer
add_column :mytickets, :categories_id, :integer
end
end
|
class User < ActiveRecord::Base
def name
self.first_name + " " + self.last_name
end
def lifetime_value
# Calculation of lifetime value will depend on your transactional logic
# Adopting a pattern of a User having a Subscription and a Subscription
# having many Transactions, an example of this calculation is:
#
# total = Array.new
# self.subscription.transactions.each do |t|
# total << t.amount
# end
# total.inject{|sum,x| sum + x}
60
end
end
|
require 'rails_helper'
RSpec.describe 'PostDecorator' do
let(:post) { Post.new(title: 'Hello World') }
it 'does not have a name method' do
expect { post.name }.to raise_error(NoMethodError)
end
it 'does not have a hello method' do
expect { Post.hello }.to raise_error(NoMethodError)
end
end
|
require 'cells_helper'
RSpec.describe SpendingInfo::Cell::Table do
let(:account) { Account.new(monthly_spending_usd: 1000) }
let(:person) { Person.new(account: account) }
let(:info) do
person.build_spending_info(
credit_score: 350,
will_apply_for_loan: wafl,
business_spending_usd: business_spending,
has_business: has_business,
)
end
before { account.build_companion if couples_account }
let(:wafl) { false }
let(:business_spending) { 1500 }
let(:has_business) { 'with_ein' }
let(:couples_account) { false }
let(:rendered) { cell(info).() }
it '' do
expect(rendered).to have_content 'Credit score: 350'
expect(rendered).to have_content 'Will apply for loan in next 6 months: No'
expect(rendered).to have_content 'Business spending: $1,500.00'
expect(rendered).to have_content '(Has EIN)'
end
context 'for a solo account' do
let(:couples_account) { false }
specify 'spending is described as "personal spending"' do
expect(rendered).to have_content 'Personal spending:$1,000'
end
end
context 'for a couples account' do
let(:couples_account) { true }
specify 'spending is described as "shared spending"' do
expect(rendered).to have_content 'Shared spending:$1,000'
end
end
end
|
class Watcher
class << self
attr_accessor :stop
end
def self.run
Thread.new do
while !stop
while Player.playing?
sleep 0.1
end
next_track = Playlist.pop
next_track.play if next_track
sleep 0.1
end
end
end
end
|
require 'station'
describe Station do
it "expects station to hold print out name of a station" do
station = Station.new(:name, :zone)
expect(station.name).to eq(:name)
end
it "expects station to hold print out zone of a station" do
station = Station.new(:name, :zone)
expect(station.zone).to eq :zone
end
end
|
require "application_system_test_case"
class UsedUrlsTest < ApplicationSystemTestCase
setup do
@used_url = used_urls(:one)
end
test "visiting the index" do
visit used_urls_url
assert_selector "h1", text: "Used Urls"
end
test "creating a Used url" do
visit used_urls_url
click_on "New Used Url"
fill_in "Long name", with: @used_url.long_name
fill_in "Short name", with: @used_url.short_name
click_on "Create Used url"
assert_text "Used url was successfully created"
click_on "Back"
end
test "updating a Used url" do
visit used_urls_url
click_on "Edit", match: :first
fill_in "Long name", with: @used_url.long_name
fill_in "Short name", with: @used_url.short_name
click_on "Update Used url"
assert_text "Used url was successfully updated"
click_on "Back"
end
test "destroying a Used url" do
visit used_urls_url
page.accept_confirm do
click_on "Destroy", match: :first
end
assert_text "Used url was successfully destroyed"
end
end
|
class RemoveCategoryFromRecruitmentCategories < ActiveRecord::Migration[5.2]
def change
remove_reference :recruitment_categories, :category, index: true, foreign_key: true
end
end
|
class Hamming
def self.compute(first_strand, second_strand)
raise ArgumentError if first_strand.length != second_strand.length
first_strand.each_char.with_index.count do |nucleotide, i|
second_strand[i] != nucleotide
end
end
end
|
module Sluggable extend ActiveSupport::Concern
included do
acts_as_url :name, :sync_url => true, url_attribute: :url
end
def to_param
"#{id}-#{url}"
end
end |
class PushNotificationWorker
include Sidekiq::Worker
sidekiq_options queue: 'notification'
def perform(school_class_id, activity_name)
puts '***************************************'
puts "School class id: #{school_class_id}"
puts "activity name: #{activity_name}"
school_class = SchoolClass.find(school_class_id)
return unless school_class.present?
return unless school_class.member_device_tokens.present?
device_tokens = school_class.user.device_tokens.pluck(:token) + school_class.member_device_tokens.pluck(:token)
puts "Device tokens: #{device_tokens}"
puts "Activity name: #{activity_name}"
puts '***************************************\n'
server_key = ENV['FCM_KEY']
fcm = FCM.new(server_key)
options = {
notification: {
title: 'New activity!',
body: activity_name
}
}
fcm.send(device_tokens, options)
end
end
|
namespace :server do
desc "Restart mod_rails server"
task :restart do
`touch tmp/restart.txt`
end
end |
class ArticlesController < ApplicationController
def index
#show a list of record
@articles = Article.all.order("created_at DESC")
end
def show
# show a record
@article = Article.find(params[:id])
end
def new
# form to create
@article = Article.new
end
def create
# action for new record, executed by action 'new'
@article = Article.new(article_params)
@article.author_id = 1; # TODO: assignation auto, no manually
if @article.save
redirect_to action: 'show', id:@article.id
else
render action: "new"
end
end
def edit
# form to edit
end
def update
# action to update, executed by action 'edit'
end
def destroy
# action to delete
end
private
def article_params
params[:article].permit(:titulo, :contenido)
end
end
|
class Car
attr_reader :make,
:model,
:monthly_payment,
:loan_length,
:color
def initialize(type, monthly_payment, loan_length)
@make = type.split(" ").first
@model = type.split(" ").last
@monthly_payment = monthly_payment
@loan_length = loan_length
@color = nil
end
def total_cost
@monthly_payment * @loan_length
end
def paint!(new_color)
@color = new_color
end
end
|
module JsonStructure
class Array < Type
def initialize(elem_type = nil)
@elem_type = elem_type
end
def ===(value)
return false unless value.is_a?(::Array)
if @elem_type
return value.all? { |v| @elem_type === v }
end
true
end
end
end
|
class User < ActiveRecord::Base
has_secure_password
validates :name, :password, :email, :description, presence:true
validates_length_of :password, minimum: 8
validates_confirmation_of :password, message: "must match Password"
validates :email.downcase, uniqueness:true
validates_format_of :email, :with => /\A[^@\s]+@([^@\s]+\.)+[^@\s]+\z/
has_many :networks, :foreign_key => "user_id"
has_many :friends, :through => :networks
has_many :invites, :foreign_key => "user_id"
has_many :invitees, :through => :invites
end
|
class AddFieldToDeployment < ActiveRecord::Migration
def up
add_column :deployments, :description, :string
add_column :tasks, :description, :string
end
def down
add_column :deployments, :description
dd_column :tasks, :description
end
end
|
module Auth
extend ActiveSupport::Concern
included do
before_action :authenticate, only: [:create, :update, :destroy]
end
def authenticate
authenticate_or_request_with_http_basic do |user, pass|
user.present? && pass.present?
end
end
end |
class Idea < ApplicationRecord
belongs_to :user, dependent: :destroy
has_many :idea_images
has_many :images, through: :idea_images
belongs_to :category
end
|
class Board
attr_accessor :cups
def initialize(name1, name2)
@name1=name1
@name2=name2
@cups=Array.new(14){Array.new}
place_stones
end
def place_stones
# helper method to #initialize every non-store cup with four stones each
# (0..5).each do |i|
# @cups[i] = :stone
# end
# (7..12).each do |i|
# @cups[i] = :stone
# end
@cups.each_with_index do |arr,i|
next if i==6 || i==13
4.times do |i|
arr << :stone
end
end
end
def valid_move?(start_pos)
raise "Invalid starting cup" if start_pos > 13 || start_pos<=0
end
def make_move(start_pos, current_player_name)
arr=@cups[start_pos]
@cups[start_pos]=[]
idx=start_pos
until arr.empty?
idx+=1
idx=0 if idx > 13
if idx==13
@cups[13] << arr.pop if current_player_name== @name2
elsif idx==6
@cups[6] << arr.pop if current_player_name==@name1
else
@cups[idx] << arr.pop
end
end
render
next_turn(idx)
end
def next_turn(ending_cup_idx)
# helper method to determine what #make_move returns
if ending_cup_idx==13 || ending_cup_idx==6
:prompt
elsif @cups[ending_cup_idx].count==1
:switch
else
ending_cup_idx
end
end
def render
print " #{@cups[7..12].reverse.map { |cup| cup.count }} \n"
puts "#{@cups[13].count} -------------------------- #{@cups[6].count}"
print " #{@cups.take(6).map { |cup| cup.count }} \n"
puts ""
puts ""
end
def one_side_empty?
return true if @cups.dup.take(6).all? {|a| a.empty?}
return true if @cups.dup.drop(6).all?{|a| a.empty?}
return false
end
def winner
if @cups[6].count==@cups[13].count
return :draw
else
if @cups[6].count > @cups[13].count
return @name1
else
return @name2
end
end
end
end
|
# frozen_string_literal: true
require_relative "active_record_compat"
require_relative "exceptions"
module ActiveRecordWhereAssoc
module CoreLogic
# Arel table used for aliasing when handling recursive associations (such as parent/children)
ALIAS_TABLE = Arel::Table.new("_ar_where_assoc_alias_")
# Returns the SQL for checking if any of the received relation exists.
# Uses a OR if there are multiple relations.
# => "EXISTS (SELECT... *relation1*) OR EXISTS (SELECT... *relation2*)"
def self.sql_for_any_exists(relations)
relations = [relations] unless relations.is_a?(Array)
relations = relations.reject { |rel| ActiveRecordCompat.null_relation?(rel) }
sqls = relations.map { |rel| "EXISTS (#{rel.select('1').to_sql})" }
if sqls.size > 1
"(#{sqls.join(" OR ")})" # Parens needed when embedding the sql in a `where`, because the OR could make things wrong
elsif sqls.size == 1
sqls.first
else
"0=1"
end
end
# Block used when nesting associations for a where_assoc_[not_]exists
NestWithExistsBlock = lambda do |wrapping_scope, nested_scopes|
wrapping_scope.where(sql_for_any_exists(nested_scopes))
end
# Returns the SQL for getting the sum of of the received relations
# => "SUM((SELECT... *relation1*)) + SUM((SELECT... *relation2*))"
def self.sql_for_sum_of_counts(relations)
relations = [relations] unless relations.is_a?(Array)
relations = relations.reject { |rel| ActiveRecordCompat.null_relation?(rel) }
# Need the double parentheses
relations.map { |rel| "SUM((#{rel.to_sql}))" }.join(" + ").presence || "0"
end
# Block used when nesting associations for a where_assoc_count
NestWithSumBlock = lambda do |wrapping_scope, nested_scopes|
sql = sql_for_sum_of_counts(nested_scopes)
wrapping_scope.unscope(:select).select(sql)
end
# List of available options, used for validation purposes.
VALID_OPTIONS_KEYS = ActiveRecordWhereAssoc.default_options.keys.freeze
def self.validate_options(options)
invalid_keys = options.keys - VALID_OPTIONS_KEYS
raise ArgumentError, "Invalid option keys received: #{invalid_keys.join(', ')}" unless invalid_keys.empty?
end
# Gets the value from the options or fallback to default
def self.option_value(options, key)
options.fetch(key) { ActiveRecordWhereAssoc.default_options[key] }
end
# Returns the SQL condition to check if the specified association of the record_class exists (has records).
#
# See RelationReturningMethods#where_assoc_exists or SqlReturningMethods#assoc_exists_sql for usage details.
def self.assoc_exists_sql(record_class, association_names, given_conditions, options, &block)
nested_relations = relations_on_association(record_class, association_names, given_conditions, options, block, NestWithExistsBlock)
sql_for_any_exists(nested_relations)
end
# Returns the SQL condition to check if the specified association of the record_class doesn't exist (has no records).
#
# See RelationReturningMethods#where_assoc_not_exists or SqlReturningMethods#assoc_not_exists_sql for usage details.
def self.assoc_not_exists_sql(record_class, association_names, given_conditions, options, &block)
nested_relations = relations_on_association(record_class, association_names, given_conditions, options, block, NestWithExistsBlock)
"NOT #{sql_for_any_exists(nested_relations)}"
end
# This does not return an SQL condition. Instead, it returns only the SQL to count the number of records for the specified
# association.
#
# See SqlReturningMethods#only_assoc_count_sql for usage details.
def self.only_assoc_count_sql(record_class, association_names, given_conditions, options, &block)
deepest_scope_mod = lambda do |deepest_scope|
deepest_scope = apply_proc_scope(deepest_scope, block) if block
deepest_scope.unscope(:select).select("COUNT(*)")
end
nested_relations = relations_on_association(record_class, association_names, given_conditions, options, deepest_scope_mod, NestWithSumBlock)
nested_relations = nested_relations.reject { |rel| ActiveRecordCompat.null_relation?(rel) }
nested_relations.map { |nr| "COALESCE((#{nr.to_sql}), 0)" }.join(" + ").presence || "0"
end
# Returns the SQL condition to check if the specified association of the record_class has the desired number of records.
#
# See RelationReturningMethods#where_assoc_count or SqlReturningMethods#compare_assoc_count_sql for usage details.
def self.compare_assoc_count_sql(record_class, left_operand, operator, association_names, given_conditions, options, &block)
right_sql = only_assoc_count_sql(record_class, association_names, given_conditions, options, &block)
sql_for_count_operator(left_operand, operator, right_sql)
end
# Returns relations on the associated model meant to be embedded in a query
# Will only return more than one association when there are polymorphic belongs_to
# association_names: can be an array of association names or a single one
def self.relations_on_association(record_class, association_names, given_conditions, options, last_assoc_block, nest_assocs_block)
validate_options(options)
association_names = Array.wrap(association_names)
_relations_on_association_recurse(record_class, association_names, given_conditions, options, last_assoc_block, nest_assocs_block)
end
def self._relations_on_association_recurse(record_class, association_names, given_conditions, options, last_assoc_block, nest_assocs_block)
if association_names.size > 1
recursive_scope_block = lambda do |scope|
nested_scope = _relations_on_association_recurse(scope,
association_names[1..-1],
given_conditions,
options,
last_assoc_block,
nest_assocs_block)
nest_assocs_block.call(scope, nested_scope)
end
relations_on_one_association(record_class, association_names.first, nil, options, recursive_scope_block, nest_assocs_block)
else
relations_on_one_association(record_class, association_names.first, given_conditions, options, last_assoc_block, nest_assocs_block)
end
end
# Returns relations on the associated model meant to be embedded in a query
# Will return more than one association only for polymorphic belongs_to
def self.relations_on_one_association(record_class, association_name, given_conditions, options, last_assoc_block, nest_assocs_block)
final_reflection = fetch_reflection(record_class, association_name)
check_reflection_validity!(final_reflection)
nested_scopes = nil
current_scopes = nil
# Chain deals with through stuff
# We will start with the reflection that points on the final model, and slowly move back to the reflection
# that points on the model closest to self
# Each step, we get all of the scoping lambdas that were defined on associations that apply for
# the reflection's target
# Basically, we start from the deepest part of the query and wrap it up
reflection_chain, constraints_chain = ActiveRecordCompat.chained_reflection_and_chained_constraints(final_reflection)
skip_next = false
reflection_chain.each_with_index do |reflection, i|
if skip_next
skip_next = false
next
end
# the 2nd part of has_and_belongs_to_many is handled at the same time as the first.
skip_next = true if actually_has_and_belongs_to_many?(reflection)
init_scopes = initial_scopes_from_reflection(record_class, reflection_chain[i..-1], constraints_chain[i], options)
current_scopes = init_scopes.map do |alias_scope, current_scope, klass_scope|
current_scope = process_association_step_limits(current_scope, reflection, record_class, options)
if i.zero?
current_scope = current_scope.where(given_conditions) if given_conditions
if klass_scope
if klass_scope.respond_to?(:call)
current_scope = apply_proc_scope(current_scope, klass_scope)
else
current_scope = current_scope.where(klass_scope)
end
end
current_scope = apply_proc_scope(current_scope, last_assoc_block) if last_assoc_block
end
# Those make no sense since at this point, we are only limiting the value that would match using conditions
# Those could have been added by the received block, so just remove them
current_scope = current_scope.unscope(:limit, :order, :offset)
current_scope = nest_assocs_block.call(current_scope, nested_scopes) if nested_scopes
current_scope = nest_assocs_block.call(alias_scope, current_scope) if alias_scope
current_scope
end
nested_scopes = current_scopes
end
current_scopes
end
def self.fetch_reflection(relation_klass, association_name)
association_name = ActiveRecordCompat.normalize_association_name(association_name)
reflection = relation_klass._reflections[association_name]
if reflection.nil?
# Need to use build because this exception expects a record...
raise ActiveRecord::AssociationNotFoundError.new(relation_klass.new, association_name)
end
reflection
end
# Can return multiple pairs for polymorphic belongs_to, one per table to look into
def self.initial_scopes_from_reflection(record_class, reflection_chain, assoc_scopes, options)
reflection = reflection_chain.first
actual_source_reflection = user_defined_actual_source_reflection(reflection)
on_poly_belongs_to = option_value(options, :poly_belongs_to) if poly_belongs_to?(actual_source_reflection)
classes_with_scope = classes_with_scope_for_reflection(record_class, reflection, options)
assoc_scope_allowed_lim_off = assoc_scope_to_keep_lim_off_from(reflection)
classes_with_scope.map do |klass, klass_scope|
current_scope = klass.default_scoped
if actually_has_and_belongs_to_many?(actual_source_reflection)
# has_and_belongs_to_many, behind the scene has a secret model and uses a has_many through.
# This is the first of those two secret has_many through.
#
# In order to handle limit, offset, order correctly on has_and_belongs_to_many,
# we must do both this reflection and the next one at the same time.
# Think of it this way, if you have limit 3:
# Apply only on 1st step: You check that any of 2nd step for the first 3 of 1st step match
# Apply only on 2nd step: You check that any of the first 3 of second step match for any 1st step
# Apply over both (as we do): You check that only the first 3 of doing both step match,
# To create the join, simply using next_reflection.klass.default_scoped.joins(reflection.name)
# would be great, except we cannot add a given_conditions afterward because we are on the wrong "base class",
# and we can't do #merge because of the LEW crap.
# So we must do the joins ourself!
_wrapper, sub_join_contraints = wrapper_and_join_constraints(record_class, reflection)
next_reflection = reflection_chain[1]
current_scope = current_scope.joins(<<-SQL)
INNER JOIN #{next_reflection.klass.quoted_table_name} ON #{sub_join_contraints.to_sql}
SQL
alias_scope, join_constraints = wrapper_and_join_constraints(record_class, next_reflection, habtm_other_reflection: reflection)
elsif on_poly_belongs_to
alias_scope, join_constraints = wrapper_and_join_constraints(record_class, reflection, poly_belongs_to_klass: klass)
else
alias_scope, join_constraints = wrapper_and_join_constraints(record_class, reflection)
end
assoc_scopes.each do |callable|
relation = klass.unscoped.instance_exec(nil, &callable)
if callable != assoc_scope_allowed_lim_off
# I just want to remove the current values without screwing things in the merge below
# so we cannot use #unscope
relation.limit_value = nil
relation.offset_value = nil
relation.order_values = []
end
# Need to use merge to replicate the Last Equality Wins behavior of associations
# https://github.com/rails/rails/issues/7365
# See also the test/tests/wa_last_equality_wins_test.rb for an explanation
current_scope = current_scope.merge(relation)
end
[alias_scope, current_scope.where(join_constraints), klass_scope]
end
end
def self.assoc_scope_to_keep_lim_off_from(reflection)
# For :through associations, it's pretty hard/tricky to apply limit/offset/order of the
# whole has_* :through. For now, we only apply those of the direct associations from one model
# to another that the :through uses and we ignore the limit/offset/order from the scope of has_* :through.
#
# The exception is for has_and_belongs_to_many, which behind the scene, use a has_many :through.
# For those, since we know there is no limits on the internal has_many and the belongs_to,
# we can do a special case and handle their limit. This way, we can treat them the same way we treat
# the other macros, we only apply the limit/offset/order of the deepest user-define association.
user_defined_actual_source_reflection(reflection).scope
end
def self.classes_with_scope_for_reflection(record_class, reflection, options)
actual_source_reflection = user_defined_actual_source_reflection(reflection)
if poly_belongs_to?(actual_source_reflection)
on_poly_belongs_to = option_value(options, :poly_belongs_to)
if reflection.options[:source_type]
[reflection.options[:source_type].safe_constantize].compact
else
case on_poly_belongs_to
when :pluck
model_for_ids = actual_source_reflection.active_record
if model_for_ids.abstract_class
# When the reflection is defined on an abstract model, we fallback to the model
# on which this was called
model_for_ids = record_class
end
class_names = model_for_ids.distinct.pluck(actual_source_reflection.foreign_type)
class_names.compact.map!(&:safe_constantize).compact
when Array, Hash
array = on_poly_belongs_to.to_a
bad_class = array.detect { |c, _p| !c.is_a?(Class) || !(c < ActiveRecord::Base) }
if bad_class.is_a?(ActiveRecord::Base)
raise ArgumentError, "Must receive the Class of the model, not an instance. This is wrong: #{bad_class.inspect}"
elsif bad_class
raise ArgumentError, "Expected #{bad_class.inspect} to be a subclass of ActiveRecord::Base"
end
array
when :raise
msg = String.new
if actual_source_reflection == reflection
msg << "Association #{reflection.name.inspect} is a polymorphic belongs_to. "
else
msg << "Association #{reflection.name.inspect} is a :through relation that uses a polymorphic belongs_to"
msg << "#{actual_source_reflection.name.inspect} as source without without a source_type. "
end
msg << "This is not supported by ActiveRecord when doing joins, but it is by WhereAssoc. However, "
msg << "you must pass the :poly_belongs_to option to specify what to do in this case.\n"
msg << "See https://maxlap.github.io/activerecord_where_assoc/ActiveRecordWhereAssoc/RelationReturningMethods.html#module-ActiveRecordWhereAssoc::RelationReturningMethods-label-3Apoly_belongs_to+option"
raise ActiveRecordWhereAssoc::PolymorphicBelongsToWithoutClasses, msg
else
if on_poly_belongs_to.is_a?(Class) && on_poly_belongs_to < ActiveRecord::Base
[on_poly_belongs_to]
else
raise ArgumentError, "Received a bad value for :poly_belongs_to: #{on_poly_belongs_to.inspect}"
end
end
end
else
[reflection.klass]
end
end
# Creates a sub_query that the current_scope gets nested into if there is limit/offset to apply
def self.process_association_step_limits(current_scope, reflection, relation_klass, options)
if user_defined_actual_source_reflection(reflection).macro == :belongs_to || option_value(options, :ignore_limit)
return current_scope.unscope(:limit, :offset, :order)
end
# No need to do transformations if this is already a NullRelation
return current_scope if ActiveRecordCompat.null_relation?(current_scope)
current_scope = current_scope.limit(1) if reflection.macro == :has_one
# Order is useless without either limit or offset
current_scope = current_scope.unscope(:order) if !current_scope.limit_value && !current_scope.offset_value
return current_scope unless current_scope.limit_value || current_scope.offset_value
if %w(mysql mysql2).include?(relation_klass.connection.adapter_name.downcase)
msg = String.new
msg << "Associations and default_scopes with a limit or offset are not supported for MySQL (this includes has_many). "
msg << "Use ignore_limit: true to ignore both limit and offset, and treat has_one like has_many. "
msg << "See https://github.com/MaxLap/activerecord_where_assoc#mysql-doesnt-support-sub-limit for details."
raise MySQLDoesntSupportSubLimitError, msg
end
# We only check the records that would be returned by the associations if called on the model. If:
# * the association has a limit in its lambda
# * the default scope of the model has a limit
# * the association is a has_one
# Then not every records that match a naive join would be returned. So we first restrict the query to
# only the records that would be in the range of limit and offset.
#
# Note that if the #where_assoc_* block adds a limit or an offset, it has no effect. This is intended.
# An argument could be made for it to maybe make sense for #where_assoc_count, not sure why that would
# be useful.
if reflection.klass.table_name.include?(".") || option_value(options, :never_alias_limit)
# We use unscoped to avoid duplicating the conditions in the query, which is noise. (unless it
# could helps the query planner of the DB, if someone can show it to be worth it, then this can be changed.)
reflection.klass.unscoped.where(reflection.klass.primary_key.to_sym => current_scope)
else
# This works as long as the table_name doesn't have a schema/database, since we need to use an alias
# with the table name to make scopes and everything else work as expected.
# We use unscoped to avoid duplicating the conditions in the query, which is noise. (unless if it
# could helps the query planner of the DB, if someone can show it to be worth it, then this can be changed.)
reflection.klass.unscoped.from("(#{current_scope.to_sql}) #{reflection.klass.table_name}")
end
end
# Apply a proc used as scope
# If it can't receive arguments, call the proc with self set to the relation
# If it can receive arguments, call the proc the relation passed as argument
def self.apply_proc_scope(relation, proc_scope)
if proc_scope.arity == 0
relation.instance_exec(nil, &proc_scope) || relation
else
proc_scope.call(relation) || relation
end
end
def self.build_alias_scope_for_recursive_association(reflection, poly_belongs_to_klass)
klass = poly_belongs_to_klass || reflection.klass
table = klass.arel_table
primary_key = klass.primary_key
foreign_klass = reflection.send(:actual_source_reflection).active_record
alias_scope = foreign_klass.base_class.unscoped
alias_scope = alias_scope.from("#{table.name} #{ALIAS_TABLE.name}")
alias_scope = alias_scope.where(table[primary_key].eq(ALIAS_TABLE[primary_key]))
alias_scope
end
def self.wrapper_and_join_constraints(record_class, reflection, options = {})
poly_belongs_to_klass = options[:poly_belongs_to_klass]
join_keys = ActiveRecordCompat.join_keys(reflection, poly_belongs_to_klass)
key = join_keys.key
foreign_key = join_keys.foreign_key
table = (poly_belongs_to_klass || reflection.klass).arel_table
foreign_klass = reflection.send(:actual_source_reflection).active_record
if foreign_klass.abstract_class
# When the reflection is defined on an abstract model, we fallback to the model
# on which this was called
foreign_klass = record_class
end
foreign_table = foreign_klass.arel_table
habtm_other_reflection = options[:habtm_other_reflection]
habtm_other_table = habtm_other_reflection.klass.arel_table if habtm_other_reflection
if (habtm_other_table || table).name == foreign_table.name
alias_scope = build_alias_scope_for_recursive_association(habtm_other_reflection || reflection, poly_belongs_to_klass)
foreign_table = ALIAS_TABLE
end
constraints = table[key].eq(foreign_table[foreign_key])
if reflection.type
# Handling of the polymorphic has_many/has_one's type column
constraints = constraints.and(table[reflection.type].eq(foreign_klass.base_class.name))
end
if poly_belongs_to_klass
constraints = constraints.and(foreign_table[reflection.foreign_type].eq(poly_belongs_to_klass.base_class.name))
end
[alias_scope, constraints]
end
# Because we work using Model._reflections, we don't actually get the :has_and_belongs_to_many.
# Instead, we get a has_many :through, which is was ActiveRecord created behind the scene.
# This code detects that a :through is actually a has_and_belongs_to_many.
def self.has_and_belongs_to_many?(reflection) # rubocop:disable Naming/PredicateName
parent = ActiveRecordCompat.parent_reflection(reflection)
parent && parent.macro == :has_and_belongs_to_many
end
def self.poly_belongs_to?(reflection)
reflection.macro == :belongs_to && reflection.options[:polymorphic]
end
# Return true if #user_defined_actual_source_reflection is a has_and_belongs_to_many
def self.actually_has_and_belongs_to_many?(reflection)
has_and_belongs_to_many?(user_defined_actual_source_reflection(reflection))
end
# Returns the deepest user-defined reflection using source_reflection.
# This is different from #send(:actual_source_reflection) because it stops on
# has_and_belongs_to_many associations, where as actual_source_reflection would continue
# down to the belongs_to that is used internally.
def self.user_defined_actual_source_reflection(reflection)
loop do
return reflection if reflection == reflection.source_reflection
return reflection if has_and_belongs_to_many?(reflection)
reflection = reflection.source_reflection
end
end
def self.check_reflection_validity!(reflection)
if ActiveRecordCompat.through_reflection?(reflection)
# Copied from ActiveRecord
if reflection.through_reflection.polymorphic?
# Since deep_cover/builtin_takeover lacks some granularity,
# it can sometimes happen that it won't display 100% coverage while a regular would
# be 100%. This happens when multiple banches are on in a single line.
# For this reason, I split this condition in 2
if ActiveRecord.const_defined?(:HasOneAssociationPolymorphicThroughError)
if reflection.has_one?
raise ActiveRecord::HasOneAssociationPolymorphicThroughError.new(reflection.active_record.name, reflection)
end
end
raise ActiveRecord::HasManyThroughAssociationPolymorphicThroughError.new(reflection.active_record.name, reflection)
end
check_reflection_validity!(reflection.through_reflection)
check_reflection_validity!(reflection.source_reflection)
end
end
# Doing (SQL) BETWEEN v1 AND v2, where v2 is infinite means (SQL) >= v1. However,
# we place the SQL on the right side, so the operator is flipped to become v1 <= (SQL).
# Doing (SQL) NOT BETWEEN v1 AND v2 where v2 is infinite means (SQL) < v1. However,
# we place the SQL on the right side, so the operator is flipped to become v1 > (SQL).
RIGHT_INFINITE_RANGE_OPERATOR_MAP = { "=" => "<=", "<>" => ">" }.freeze
# We flip the operators to use when it's about the left-side of the range.
LEFT_INFINITE_RANGE_OPERATOR_MAP = Hash[RIGHT_INFINITE_RANGE_OPERATOR_MAP.map { |k, v| [k, v.tr("<>", "><")] }].freeze
RANGE_OPERATOR_MAP = { "=" => "BETWEEN", "<>" => "NOT BETWEEN" }.freeze
def self.sql_for_count_operator(left_operand, operator, right_sql)
operator = case operator.to_s
when "=="
"="
when "!="
"<>"
else
operator.to_s
end
return "(#{left_operand}) #{operator} #{right_sql}" unless left_operand.is_a?(Range)
unless %w(= <>).include?(operator)
raise ArgumentError, "Operator should be one of '==', '=', '<>' or '!=' when using a Range not: #{operator.inspect}"
end
v1 = left_operand.begin
v2 = left_operand.end || Float::INFINITY
# We are doing a count and summing them, the lowest possible is 0, so just use that instead of changing the SQL used.
v1 = 0 if v1 == -Float::INFINITY
return sql_for_count_operator(v1, RIGHT_INFINITE_RANGE_OPERATOR_MAP.fetch(operator), right_sql) if v2 == Float::INFINITY
# Its int or a rounded float. Since we are comparing to integer values (count), exclude_end? just means -1
v2 -= 1 if left_operand.exclude_end? && v2 % 1 == 0
"#{right_sql} #{RANGE_OPERATOR_MAP.fetch(operator)} #{v1} AND #{v2}"
end
end
end
|
class LeadTimesCounter
def generate_counts(cfd_data) # { dates: [...], started: [...], accepted: [...]}
return {} if cfd_data.blank?
result = {}
result[:dates] = cfd_data[:dates]
result[:accepted] = []
result[:itb] = []
result[:crt] = []
result[:accepted] = build_lead_times(data_field: :accepted, comparing_against: :started, cfd_data: cfd_data)
result[:itb] = build_lead_times(data_field: :itb, comparing_against: :accepted, cfd_data: cfd_data)
result[:crt] = build_lead_times(data_field: :crt, comparing_against: :itb, cfd_data: cfd_data)
result[:full] = build_lead_times(data_field: :crt, comparing_against: :started, cfd_data: cfd_data)
result
end
private
def build_lead_times(data_field:, comparing_against:, cfd_data:)
lead_times = []
cfd_data[data_field].each_with_index do |data_field_count, data_field_index|
if data_field_count == 0
lead_times[data_field_index] = 0
next
end
comparing_against_index = cfd_data[comparing_against].find_index{|x| x >= data_field_count }
data_field_date = Date.parse(cfd_data[:dates][data_field_index])
comparing_against_date = Date.parse(cfd_data[:dates][comparing_against_index])
days_difference = (data_field_date - comparing_against_date).to_i
lead_times[data_field_index] = days_difference
end
lead_times
end
end
|
class CategoryAttributeGrouping < ActiveRecord::Base
####
# MODEL ANNOTATIONS
####
####
# RELATIONSHIPS
####
belongs_to :category
has_many :attr_types, :class_name => 'CategoryAttribute'
####
# CONSTANTS
####
NAME_MIN_LENGTH = 1
NAME_MAX_LENGTH = 64
####
# VALIDATORS
####
validates_presence_of :category, :message => 'must be associated with a Category'
validates_length_of :name, :in => NAME_MIN_LENGTH..NAME_MAX_LENGTH
validates_uniqueness_of :name, :scope => :category_id
####
# PUBLIC INSTANCE METHODS
####
####
# PUBLIC CLASS METHODS
####
end
|
require "tasks/scripts/move_facility_data"
require "tasks/scripts/discard_invalid_appointments"
namespace :data_fixes do
desc "Move all data from a source facility to a destination facility"
task :move_data_from_source_to_destination_facility, [:source_facility_id, :destination_facility_id] => :environment do |_t, args|
source_facility = Facility.find(args.source_facility_id)
destination_facility = Facility.find(args.destination_facility_id)
results = MoveFacilityData.new(source_facility, destination_facility).move_data
puts "[DATA FIXED]"\
"source: #{source_facility.name}, destination: #{destination_facility.name}, "\
"#{results}"
end
desc "Move all data recorded by a user from a source facility to a destination facility"
task :move_user_data_from_source_to_destination_facility, [:user_id, :source_facility_id, :destination_facility_id] => :environment do |_t, args|
user = User.find(args.user_id)
source_facility = Facility.find(args.source_facility_id)
destination_facility = Facility.find(args.destination_facility_id)
results = MoveFacilityData.new(source_facility, destination_facility, user: user).move_data
puts "[DATA FIXED]"\
"user: #{user.full_name}, source: #{source_facility.name}, destination: #{destination_facility.name}, "\
"#{results}"
end
desc "Clean up invalid scheduled appointments (multiple scheduled appointments for a patient)"
task :discard_invalid_scheduled_appointments, [:dry_run] => :environment do |_t, args|
dry_run =
args.dry_run == "true"
puts "This is a dry run" if dry_run
patients_ids = Appointment.where(status: "scheduled").group(:patient_id).count.select { |_k, v| v > 1 }.keys
Patient.with_discarded.where(id: patients_ids).each do |patient|
DiscardInvalidAppointments.call(patient: patient, dry_run: dry_run)
end
end
end
|
require 'xirgo/device'
class Xirgo::CommandRequest < ActiveRecord::Base
establish_connection "gateway_xirgo_#{RAILS_ENV}"
set_table_name "configuration_requests"
belongs_to :device
def outbound_response
not_found_msg = "Unknown error (last_command_id=#{last_command_id.inspect})"
if last_command_id
data = connection.execute("select * from outbound where id = #{last_command_id}")
if data.num_rows == 1
row = data.fetch_hash
if row['response'] && row['response'].upcase == "MESSAGE DELIVERED"
if row['response_message_id'].nil? &&
response = "Response Timeout"
else
response = "Unknown error (response_message_id=#{row['response_message_id']})"
end
else
response = row['response']
end
else
response = not_found_msg
end
else
response = not_found_msg
end
response
end
end |
# frozen_string_literal: true
require_relative 'matrix_common'
require_relative 'matrix_exceptions'
require_relative 'tridiagonal_iterator'
# Tridiagonal Sparse Matrix
class TriDiagonalMatrix
include MatrixCommon
attr_reader(:rows, :cols)
def initialize(rows, cols: rows, val: 0)
raise NonSquareException unless rows == cols
# raise TypeError unless rows > 2 && cols > 2
if rows.positive?
@upper_dia = Array.new(rows-1, val)
@main_dia = Array.new(rows, val)
@lower_dia = Array.new(rows-1, val)
else
@upper_dia = []
@main_dia = []
@lower_dia = []
end
@rows = rows
@cols = cols
end
def initialize_clone(other)
super
@upper_dia = other.instance_variable_get(:@upper_dia).clone
@main_dia = other.instance_variable_get(:@main_dia).clone
@lower_dia = other.instance_variable_get(:@lower_dia).clone
@rows = other.rows
@cols = other.cols
end
class << self
include MatrixExceptions
def create(rows, cols: rows, val: 0)
TriDiagonalMatrix.new(rows, cols: cols, val: val)
end
def zero(rows, cols = rows)
TriDiagonalMatrix.new(rows, cols: cols)
end
def identity(n)
TriDiagonalMatrix.new(n).map_diagonal { 1 }
end
def [](*rows)
# 0x0 matrix
return TriDiagonalMatrix.new(rows.length) if rows.length.zero?
raise ArgumentError unless rows.length == 3 and
rows[0].length == rows[1].length - 1 and
rows[2].length == rows[1].length - 1
m = TriDiagonalMatrix.new(rows[1].length)
m.instance_variable_set(:@upper_dia, rows[0])
m.instance_variable_set(:@main_dia, rows[1])
m.instance_variable_set(:@lower_dia, rows[2])
m
end
def from_sparse_matrix(s)
raise NonSquareException unless s.square?
m = TriDiagonalMatrix.new(s.rows)
s.iterator.iterate do |r, c, v|
m.put(r, c, v) if r - c <= 1
end
m
end
alias I identity
end
def nnz
@upper_dia.count { |x| x != 0 } + @main_dia.count { |x| x != 0 } + @lower_dia.count { |x| x != 0 }
end
def set_zero
@upper_dia = Array.new(rows-1, 0)
@main_dia = Array.new(rows, 0)
@lower_dia = Array.new(rows-1, 0)
end
def set_identity
@upper_dia = Array.new(rows-1, 0)
@main_dia = Array.new(rows, 1)
@lower_dia = Array.new(rows-1, 0)
end
def resize!(size, _ = size)
if size > @rows
size_up!(@main_dia, size)
size_up!(@lower_dia, size - 1)
size_up!(@upper_dia, size - 1)
elsif size < @rows
size_down!(@main_dia, size)
size_down!(@lower_dia, size - 1)
size_down!(@upper_dia, size - 1)
end
@rows = @cols = size
self
end
def at(r, c)
return nil? unless r < @rows && c < @cols
diag, idx = get_index(r, c)
return 0 if diag.nil? || diag.length == 0
diag[idx]
end
def put(r, c, val)
unless on_band?(r, c)
# warn "Insertion at (#{r}, #{c}) would violate tri-diagonal structure. No element inserted."
return false
end
resize!([r, c].max + 1) unless [r, c].max + 1 <= @rows
diag, idx = get_index(r, c)
diag[idx] = val unless diag.nil?
true
end
# def +(o)
# o.is_a?(MatrixCommon) ? plus_matrix(o) : plus_scalar(o)
# end
#
# def -(o)
# o.is_a?(MatrixCommon) ? plus_matrix(o * -1) : plus_scalar(-o)
# end
#
# def *(o)
# o.is_a?(MatrixCommon) ? mul_matrix(o) : mul_scalar(o)
# end
def det
prev_det = 1 # det of a 0x0 is 1
det = @main_dia[0] # det of a 1x1 is the number itself
index = 1
while index < @rows
temp_prev = det
det = @main_dia[index] * det \
- @lower_dia[index - 1] * @upper_dia[index - 1] * prev_det
prev_det = temp_prev
index += 1
end
det
end
def diagonal
@main_dia.clone
end
def tridiagonal
clone
end
def nil?
@rows == 0 && @cols == 0
end
def iterator
TriDiagonalIterator.new(@lower_dia, @main_dia, @upper_dia)
end
def symmetric?
@lower_dia == @upper_dia
end
def transpose
m = clone
m.transpose!
m
end
def transpose!
temp = @lower_dia
@lower_dia = @upper_dia
@upper_dia = temp
end
def positive?
@upper_dia.find(&:negative?).nil? and
@main_dia.find(&:negative?).nil? and
@lower_dia.find(&:negative?).nil?
end
def lower_triangular?
@upper_dia.count { |x| x != 0 } == 0
end
def upper_triangular?
@lower_dia.count { |x| x != 0 } == 0
end
def lower_hessenberg?
true
end
def upper_hessenberg?
true
end
def on_band?(r, c)
(r - c).abs <= 1
end
def to_ruby_matrix
matrix_array = Array.new(@rows) { Array.new(@cols, 0) }
(0...@rows).each do |x|
(0...@cols).each do |y|
matrix_array[x][y] = at(x, y)
end
end
Matrix[*matrix_array]
end
# Method aliases
alias t transpose
alias tr trace
alias [] at
alias get at
alias set put
alias []= put
alias plus +
alias subtract -
alias multiply *
alias exp **
alias adjoint adjugate
private
def to_sparse_matrix
m = SparseMatrix.new(@rows, @cols)
iterator.iterate{|r, c, val| m.put(r, c, val)}
m
end
def plus_matrix(o)
to_sparse_matrix + o
end
def mul_matrix(o)
to_sparse_matrix * o
end
def size_up!(diag, len)
diag.concat(Array.new(len - diag.length, 0))
end
def size_down!(diag, len)
diag.slice!(len...diag.length) unless len >= diag.length
end
# Assumes that (r, c) is inside the matrix boundaries
def get_index(r, c)
return [nil, nil] unless on_band?(r, c)
idx = [r, c].min
if r == c
return [@main_dia, idx]
elsif
r < c
return [@upper_dia, idx]
end
[@lower_dia, idx]
end
end
|
require_relative 'train'
class CargoTrain < Train
def initialize (number)
super(number, "cargo")
validate!
end
end |
module Tinify
class Result < ResultMeta
attr_reader :data
def initialize(meta, data)
@meta, @data = meta.freeze, data.freeze
end
def to_file(path)
File.open(path, "wb") { |file| file.write(data) }
end
alias_method :to_buffer, :data
def size
@meta["Content-Length"].to_i.nonzero?
end
def media_type
@meta["Content-Type"]
end
alias_method :content_type, :media_type
def extension
if @meta['Content-Type']
parts = @meta["Content-Type"].split "/"
parts.last
end
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.