text stringlengths 10 2.61M |
|---|
class EssayDetail::Header
include RailsHelpers
delegate :title, :author, to: :essay
attr_accessor :essay
def self.render(essay)
self.new(essay).render
end
def initialize(essay)
@essay = essay
end
def author
helpers.raw "By #{helpers.link_to(@essay.author, "#author_biography")}"
end
def issue_link
helpers.link_to(essay.issue.title, routes.issue_path(essay.issue.friendly_id))
end
def essay_style_link
helpers.link_to(essay.essay_style.title, routes.issue_essay_style_path(essay.issue.friendly_id, essay.essay_style.friendly_id))
end
def render
render_to_string('/essays/header', { object: self })
end
end
|
class Api::PasswordsController < ApplicationController
respond_to :json
def create
@user = User.send_reset_password_instructions(password_params)
respond_with(:api, @user)
end
private
def password_params
params.require(:user).permit(:email)
end
end |
require "goon_model_gen"
require "goon_model_gen/converter/abstract_conv"
module GoonModelGen
module Converter
class ResultConv < AbstractConv
class << self
# @return [String, boolean, boolean] func, requires_context, returns_error
def load_func(props)
if f = props['filter']
return f, false, false
elsif f = props['writer']
return f, false, true
else
return nil, nil, nil
end
end
end
end
end
end
|
module Api
module V1
class PostsController < ApplicationController
def index
if user_signed_in?
render json: current_user.posts
else
render json: {}, status: 401
end
end
def create
if user_signed_in?
if post = current_user.posts.create(post_params)
render json: post, status: :created
else
render json: post.errors, status: 400
end
else
render json: {}, status: 401
end
end
private
def post_params
params.require(:post).permit(:title, :content)
end
end
end
end |
require 'test_helper'
module AuthForum
class LineItemsControllerTest < ActionController::TestCase
setup do
@routes = Engine.routes
@user = FactoryGirl.create(:user, :name => 'nazrul')
sign_in @user
@cart = FactoryGirl.create(:cart)
@product = FactoryGirl.create(:product, :price => 25)
@line_item = FactoryGirl.create(:line_item, :cart_id => @cart.id, :product_id => @product.id)
session[:cart_id] = @cart.id
end
test "should get new" do
get :new
assert_response :success
end
test "should create line_item" do
assert_difference('LineItem.count') do
post :create, line_item: { cart_id: @line_item.cart_id, product_id: @line_item.product_id }
end
assert_redirected_to products_path
end
test "should update line_item" do
xhr :patch, :update, id: @line_item, :quantity => 2 ,format: 'js'
assert_response :success
end
test "should destroy line_item" do
assert_difference('LineItem.count', -1) do
delete :destroy, id: @line_item
end
assert_redirected_to carts_path
end
end
end
|
# Stack - a stack has a last in first out structure
class Stack
def initialize()
@stack = Array.new
end
#this method adds an item to the stack
def add(value)
@stack.push(value)
end
# this method removes and item from the stack.
def remove
@stack.pop
end
end
my_stack = Stack.new()
p "Adding values to the stack!"
p "Just added #{my_stack.add(3)}"
p "Just added #{my_stack.add(4)}"
p "Just added #{my_stack.add(5)}"
p "Just added #{my_stack.add(7)}"
p "Just added #{my_stack.add(20)}"
p my_stack
p "With a stack elements are removed based on a last in first out structure. This means I will remove elements starting from the end."
p "The element I just revomed was #{my_stack.remove}"
p "The element I just revomed was #{my_stack.remove}"
p my_stack
p "-------------------------------------------------------------------------------------"
# Queue - a queue has a first in first out structure
class Queue
def initialize()
@queue = []
end
# this method will add values to the end of the queue
def add(value)
@queue.push(value)
end
# this method will remove values from the queue starting with the first one added.
def remove
@queue.shift
end
end
my_queue = Queue.new()
p "Adding values to the queue!"
p "Just added #{my_queue.add(34)}"
p "Just added #{my_queue.add(42)}"
p "Just added #{my_queue.add(54)}"
p "Just added #{my_queue.add(73)}"
p "Just added #{my_queue.add(2)}"
p my_queue
p "With a queue elements are removed based on a first in first out structure. This means I will remove elements starting from the front."
p "The element I just revomed was #{my_queue.remove}"
p "The element I just revomed was #{my_queue.remove}"
p my_queue
|
require 'spec_helper'
describe Immutable::Set do
[
[:sort, ->(left, right) { left.length <=> right.length }],
[:sort_by, ->(item) { item.length }],
].each do |method, comparator|
describe "##{method}" do
[
[[], []],
[['A'], ['A']],
[%w[Ichi Ni San], %w[Ni San Ichi]],
].each do |values, expected|
describe "on #{values.inspect}" do
let(:set) { S[*values] }
describe 'with a block' do
let(:result) { set.send(method, &comparator) }
it "returns #{expected.inspect}" do
result.should eql(SS.new(expected, &comparator))
result.to_a.should == expected
end
it "doesn't change the original Set" do
result
set.should eql(S.new(values))
end
end
describe 'without a block' do
let(:result) { set.send(method) }
it "returns #{expected.sort.inspect}" do
result.should eql(SS[*expected])
result.to_a.should == expected.sort
end
it "doesn't change the original Set" do
result
set.should eql(S.new(values))
end
end
end
end
end
end
describe '#sort_by' do
# originally this test checked that #sort_by only called the block once
# for each item
# however, when initializing a SortedSet, we need to make sure that it
# does not include any duplicates, and we use the block when checking that
# the real point here is that the block should not be called an excessive
# number of times, degrading performance
it 'calls the passed block no more than twice for each item' do
count = 0
fn = lambda { |x| count += 1; -x }
items = 100.times.collect { rand(10000) }.uniq
S[*items].sort_by(&fn).to_a.should == items.sort.reverse
count.should <= (items.length * 2)
end
end
end
|
class FilterTypesController < ApplicationController
layout 'admin'
# GET /filter_types
# GET /filter_types.json
def index
@filter_types = FilterType.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @filter_types }
end
end
# GET /filter_types/1
# GET /filter_types/1.json
def show
@filter_type = FilterType.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @filter_type }
end
end
# GET /filter_types/new
# GET /filter_types/new.json
def new
@filter_type = FilterType.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @filter_type }
end
end
# GET /filter_types/1/edit
def edit
@filter_type = FilterType.find(params[:id])
end
# POST /filter_types
# POST /filter_types.json
def create
@filter_type = FilterType.new(params[:filter_type])
respond_to do |format|
if @filter_type.save
format.html { redirect_to @filter_type, notice: 'Filter type was successfully created.' }
format.json { render json: @filter_type, status: :created, location: @filter_type }
else
format.html { render action: "new" }
format.json { render json: @filter_type.errors, status: :unprocessable_entity }
end
end
end
# PUT /filter_types/1
# PUT /filter_types/1.json
def update
@filter_type = FilterType.find(params[:id])
respond_to do |format|
if @filter_type.update_attributes(params[:filter_type])
format.html { redirect_to @filter_type, notice: 'Filter type was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @filter_type.errors, status: :unprocessable_entity }
end
end
end
# DELETE /filter_types/1
# DELETE /filter_types/1.json
def destroy
@filter_type = FilterType.find(params[:id])
@filter_type.destroy
respond_to do |format|
format.html { redirect_to filter_types_url }
format.json { head :no_content }
end
end
end
|
require 'rspec'
class Foo
def nico
"nico"
end
end
class String
def ellipsify(number)
'hola m...'
end
end
describe 'Extender strings con ellipsify' do
it 'extender string' do
"hola mundo".ellipsify(6).should == "hola m..."
end
it 'instanciar nico' do
foo = Foo.new
foo.nico.should == 'nico'
class Foo
def nico
"hacer quilombo"
end
end
foo.nico.should == 'hacer quilombo'
end
end
|
# encoding: utf-8
MONTHNAMES_IN_PORTUGUESE = [nil] + %w{Janeiro Fevereiro Março Abril Maio Junho Julho Agosto Setembro Outubro Novembro Dezembro}
Date::DATE_FORMATS[:portuguese] = lambda{|date| date.strftime("%Y, %d de #{MONTHNAMES_IN_PORTUGUESE[date.month]}")}
|
Pod::Spec.new do |spec|
spec.name = 'PendingBusinessCore'
spec.version = '0.1.0'
spec.homepage = 'https://github.com/AMoraga/PendingBusinessCore'
spec.authors = { 'amoraga' => 'hello@albertomoraga.com' }
spec.summary = 'Core of PendingBusiness.'
spec.source = { :git => 'https://github.com/AMoraga/PendingBusinessCore.git', :tag => 'v0.1.0' }
spec.source_files = './**/*.{h,m,swift}'
spec.framework = ''
end |
class BillAnalyzer
def self.calculate_balance(bills)
not_deleted_bills = bills.select { |bill| !bill.is_deleted }
balance = 0
not_deleted_bills.each do |bill|
if bill.is_expense
balance -= bill.amount
else
balance += bill.amount
end
end
balance
end
#Return a hash that looks like:
#{'2015-07-28': { bills: bills_happened_on_key_day, balance: -40.0}}
def self.sort_bills_by_date(bills)
time_to_bills = {}
bills.each do |bill|
key = Time.parse(bill.date).strftime "%Y-%m-%d"
if time_to_bills[key].nil?
time_to_bills[key] = { bills: [bill] }
else
time_to_bills[key][:bills] << bill
end
end
time_to_bills.each do |key, bills_hash|
bill_id_note_hash_array = bills_hash[:bills].collect { |bill| { bill_id: bill.bill_id, note: bill.note } }
time_to_bills[key] = bills_hash.merge!({ bills: bill_id_note_hash_array, balance: calculate_balance(bills_hash[:bills]), count: bills_hash[:bills].size})
end
time_to_bills
end
end |
require 'oauth2'
module Gateway
class Quickbook < Result
attr_reader :api
attr_accessor :consumer, :access_token, :company_id
module HTTP
JSON = "application/json"
end
module ENVIRONMENT
SANDBOX = "sandbox"
PRODUCTION = "production"
end
module API
VERSION = "v3"
COMPANY = "company/?" #replace ? with company ID
QUERY = "query"
end
private
def api=(value)
@api = value
end
public
#Connect to QuickBook online API gateway
#Options are as follow
# String: Environment ENVIRONMENT::SANDBOX or ENVIRONMENT::PRODUCTION. AutoLoad QuickBook key, secret, access token, access secret, company ID from config/quickbook.yml corresponding to environment given.
# Hash:
# :client_id => QuickBook App Client ID,
# :client_secret => QuickBook App Client Secret,
# :refresh_token => Can generate from playground https://developer.intuit.com/app/developer/playground, validate for 100 days
# :company_id => QuickBook Company ID,
# :environment => ENVIRONMENT::SANDBOX or ENVIRONMENT::PRODUCTION
def self.connect(options)
if(options.class == String)
configuration = YAML.load_file("config/quickbook.yml")
environment = options
options = Hash.new
options[:client_id] = configuration[environment]["client_id"]
options[:client_secret] = configuration[environment]["client_secret"]
options[:refresh_token] = configuration[environment]["refresh_token"]
options[:company_id] = configuration[environment]["company_id"]
options[:environment] = environment
end
gateway = new
gateway.consumer = OAuth2::Client.new(options[:client_id], options[:client_secret], {:token_url => 'https://oauth.platform.intuit.com/oauth2/v1/tokens/bearer', auth_scheme: :basic_auth})
gateway.access_token = OAuth2::AccessToken.new(gateway.consumer, nil, {refresh_token: options[:refresh_token]})
gateway.access_token = gateway.access_token.refresh!
gateway.company_id = options[:company_id]
case options[:environment]
when ENVIRONMENT::PRODUCTION
gateway.send("api=", "https://quickbooks.api.intuit.com")
else
gateway.send("api=", "https://sandbox-quickbooks.api.intuit.com")
end
Service::Record.quickbook_gateway = gateway
end
private
def url(path, params = {})
url = File.join(self.api, API::VERSION, API::COMPANY.gsub("?", self.company_id.to_s), path)
return "#{url}?minorversion=4&#{params.to_uri_query}"
end
public
def get(path, parameters = {})
return handle_query_result(self.access_token.get(url(path, parameters), {headers: {"Accept" => HTTP::JSON}}))
end
def query_data(query)
return get(API::QUERY, {:query => query})
end
def post(path, parameters, body)
return handle_query_result(self.access_token.post(url(path, parameters), {body: body, headers: {"Content-Type" => HTTP::JSON, "Accept" => HTTP::JSON}}))
end
end
end |
# frozen_string_literal: true
Class.new(Nanoc::DataSource) do
identifier :release_notes
def items
return [] unless defined?(Bundler)
# content
path = Bundler.rubygems.find_name('nanoc').first.full_gem_path
raw_content = File.read("#{path}/NEWS.md")
content = raw_content.sub(/^#.*$/, '') # remove h1
# attributes
attributes = {
title: 'Release notes',
markdown: 'basic',
extension: 'md',
}
# identifier
identifier = Nanoc::Identifier.new('/release-notes.md')
item = new_item(content, attributes, identifier)
[item]
end
end
|
require "net/http"
require "json"
class Events
attr_reader :state, :city, :events
def initialize(geolocation)
@state = geolocation.region_code
@city = geolocation.city
@events = get_events
end
def uri
uri = URI("https://api.seatgeek.com/2/events?venue.state=#{@state}&venue.city=#{@city}")
end
def get_events
response = Net::HTTP.get_response(uri)
summary = JSON.parse(response.body)
# binding.pry
@events = []
summary["events"].each do |event|
@events << "#{event["title"]} at Venue: #{event["venue"]["name"]} Time: #{event["datetime_local"]}"
end
@events
end
end
|
require 'set'
require 'cassandra_object/log_subscriber'
require 'cassandra_object/types'
module CassandraObject
class Base
class << self
def column_family=(column_family)
@column_family = column_family
end
def column_family
@column_family ||= base_class.name.pluralize
end
def base_class
class_of_active_record_descendant(self)
end
def config=(config)
@@config = config.is_a?(Hash) ? CassandraObject::Config.new(config) : config
end
def config
@@config
end
private
# Returns the class descending directly from ActiveRecord::Base or an
# abstract class, if any, in the inheritance hierarchy.
def class_of_active_record_descendant(klass)
if klass == Base || klass.superclass == Base
klass
elsif klass.superclass.nil?
raise "#{name} doesn't belong in a hierarchy descending from CassandraObject"
else
class_of_active_record_descendant(klass.superclass)
end
end
end
extend ActiveModel::Naming
include ActiveModel::Conversion
extend ActiveSupport::DescendantsTracker
include Connection
include Consistency
include Identity
include Inspect
include Persistence
include AttributeMethods
include Validations
include AttributeMethods::Dirty
include AttributeMethods::PrimaryKey
include AttributeMethods::Typecasting
include BelongsTo
include Callbacks
include Timestamps
include Savepoints
include Scoping
include Core
include Serialization
end
end
ActiveSupport.run_load_hooks(:cassandra_object, CassandraObject::Base)
|
require_relative '../test_helper'
class LoginActivityTest < ActiveSupport::TestCase
def setup
super
require 'sidekiq/testing'
Sidekiq::Testing.inline!
end
test "should create login activity" do
assert_difference 'LoginActivity.count' do
create_login_activity
end
end
test "should get user" do
u = create_user
la = create_login_activity user: u
assert_equal la.user_id, u.id
assert_equal la.get_user.id, u.id
la = create_login_activity user: nil, identity: u.email
assert_nil la.user_id
assert_equal la.get_user.id, u.id
end
test "should notify" do
u = create_user
la = create_login_activity user: u
assert la.should_notify?(u, 'success')
assert la.should_notify?(u, 'failed')
u.settings = {send_successful_login_notifications: false, send_failed_login_notifications: false}
u.save!
assert_not la.should_notify?(u, 'success')
assert_not la.should_notify?(u, 'failed')
u.settings = {send_successful_login_notifications: true, send_failed_login_notifications: true}
u.save!
assert la.should_notify?(u, 'success')
assert la.should_notify?(u, 'failed')
# should not notify unconfirmed user
u.email = 'test@local.com';u.save!
u = u.reload
assert_not u.is_confirmed?
assert_not la.should_notify?(u, 'success')
assert_not la.should_notify?(u, 'failed')
end
test "should send security notification for device change" do
user = create_user
create_login_activity user_agent: 'test', user: user, success: true
assert_no_difference 'ActionMailer::Base.deliveries.size' do
create_login_activity user: user, success: false
end
assert_difference 'ActionMailer::Base.deliveries.size', 1 do
create_login_activity user: user, success: true
end
la = user.login_activities.last
assert_no_difference 'ActionMailer::Base.deliveries.size' do
create_login_activity ip: la.ip, user_agent: la.user_agent, user: user, success: true
end
end
test "should send security notification for ip change" do
user = create_user
create_login_activity user: user, success: true
assert_no_difference 'ActionMailer::Base.deliveries.size' do
create_login_activity user: user, success: false
end
assert_difference 'ActionMailer::Base.deliveries.size', 1 do
create_login_activity user: user, success: true
end
la = user.login_activities.last
assert_no_difference 'ActionMailer::Base.deliveries.size' do
create_login_activity ip: la.ip, user_agent: la.user_agent, user: user, success: true
end
end
test "should send one successfull email if both ip and device changed" do
user = create_user
create_login_activity user_agent: 'test', user: user, success: true
assert_difference 'ActionMailer::Base.deliveries.size', 1 do
create_login_activity user: user, success: true
end
end
test "should send security notification for failed attempts" do
user = create_user
stub_configs({'failed_attempts' => 4}) do
3.times do
create_login_activity user: nil, identity: user.email, success: false
end
assert_no_difference 'ActionMailer::Base.deliveries.size' do
create_login_activity user: user, identity: user.email, success: true
end
assert_difference 'ActionMailer::Base.deliveries.size', 1 do
create_login_activity user: nil, identity: user.email, success: false
end
assert_no_difference 'ActionMailer::Base.deliveries.size' do
3.times do
create_login_activity user: nil, identity: user.email, success: false
end
end
assert_difference 'ActionMailer::Base.deliveries.size', 1 do
create_login_activity user: nil, identity: user.email, success: false
end
end
end
test "should store original ip" do
user = create_user
original_ip = random_ip
ip = "#{original_ip}, #{random_ip}, #{random_ip}"
RequestStore.stubs(:[]).with(:request).returns(OpenStruct.new({ headers: { 'X-Forwarded-For' => ip } }))
la = create_login_activity user: user, success: true
assert_equal original_ip, la.ip
# security notification should based on original ip
assert_no_difference 'ActionMailer::Base.deliveries.size' do
create_login_activity user: user, success: true
end
RequestStore.unstub(:[])
end
end
|
#!/usr/bin/env ruby
require 'spec_ovz'
require "test/unit"
module OpenNebula
class IMOpenVZTest < Test::Unit::TestCase
def test_parse_cpu_power
text = File.read("test/resources/vzcpucheck.txt")
current_cpu_utilization, node_cpu_power = IMOpenVZParser.parse_cpu_power(text)
assert_equal "4000", current_cpu_utilization
assert_equal "109946", node_cpu_power
end
def test_parse_memcheck
text = File.read("test/resources/vzmemcheck.txt")
alloc_util, alloc_commit, alloc_limit = IMOpenVZParser.parse_memcheck(text)
assert_equal "1.95", alloc_util
assert_equal "3922547387167512.00", alloc_commit
assert_equal "3922547387167512.00", alloc_limit
end
#TODO decide if or where this test should be moved
#def test_cpu_power
# skip "Non unit test"
# assert_nothing_raised do
# puts IMOpenVZDriver.print
# end
#end
end
end
|
Rails.application.routes.draw do
get '/sign_up' => 'users#new', as: 'sign_up'
get '/sign_in' => 'sessions#new', as: 'sign_in'
delete '/sign_out' => 'sessions#destroy', as: 'sign_out'
root 'home#welcome'
resources :users
resources :sessions
resources :password_resets
end
|
class RawMaterialsController < ApplicationController
# GET /raw_materials
# GET /raw_materials.xml
def index
@raw_materials = RawMaterial.all
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @raw_materials }
end
end
# GET /raw_materials/1
# GET /raw_materials/1.xml
def show
@raw_material = RawMaterial.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @raw_material }
end
end
# GET /raw_materials/new
# GET /raw_materials/new.xml
def new
@raw_material = RawMaterial.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @raw_material }
end
end
# GET /raw_materials/1/edit
def edit
@raw_material = RawMaterial.find(params[:id])
end
# POST /raw_materials
# POST /raw_materials.xml
def create
@raw_material = RawMaterial.new(params[:raw_material])
respond_to do |format|
if @raw_material.save
format.html { redirect_to(@raw_material, :notice => 'RawMaterial was successfully created.') }
format.xml { render :xml => @raw_material, :status => :created, :location => @raw_material }
else
format.html { render :action => "new" }
format.xml { render :xml => @raw_material.errors, :status => :unprocessable_entity }
end
end
end
# PUT /raw_materials/1
# PUT /raw_materials/1.xml
def update
@raw_material = RawMaterial.find(params[:id])
respond_to do |format|
if @raw_material.update_attributes(params[:raw_material])
format.html { redirect_to(@raw_material, :notice => 'RawMaterial was successfully updated.') }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @raw_material.errors, :status => :unprocessable_entity }
end
end
end
# DELETE /raw_materials/1
# DELETE /raw_materials/1.xml
def destroy
@raw_material = RawMaterial.find(params[:id])
@raw_material.destroy
respond_to do |format|
format.html { redirect_to(raw_materials_url) }
format.xml { head :ok }
end
end
end
|
class Entry
attr_reader :name, :size
def initialize(name, size)
@name = name
@size = size
end
def add(entry)
end
def print_list(prefix)
end
def to_string
"#{name} (#{size})"
end
end
|
require 'spec_helper'
describe SysModule do
it "should be OK" do
m = FactoryGirl.build(:sys_module)
m.should be_valid
end
it "should reject nil module name" do
m = FactoryGirl.build(:sys_module, :module_name => nil)
m.should_not be_valid
end
it "should reject nil module group name" do
m = FactoryGirl.build(:sys_module, :module_group_name => nil)
m.should_not be_valid
end
end
|
require 'test_helper'
class HotelsControllerTest < ActionDispatch::IntegrationTest
setup do
@hotel = hotels(:one)
end
test "should get index" do
get hotels_url, as: :json
assert_response :success
end
test "should create hotel" do
assert_difference('Hotel.count') do
post hotels_url, params: { hotel: { created_by: @hotel.created_by, hotel_contact_person: @hotel.hotel_contact_person, hotel_email: @hotel.hotel_email, hotel_id: @hotel.hotel_id, hotel_mobile: @hotel.hotel_mobile, hotel_name: @hotel.hotel_name, hotel_status: @hotel.hotel_status, hotel_type_id: @hotel.hotel_type_id, parent_hotel_id: @hotel.parent_hotel_id, updated_by: @hotel.updated_by } }, as: :json
end
assert_response 201
end
test "should show hotel" do
get hotel_url(@hotel), as: :json
assert_response :success
end
test "should update hotel" do
patch hotel_url(@hotel), params: { hotel: { created_by: @hotel.created_by, hotel_contact_person: @hotel.hotel_contact_person, hotel_email: @hotel.hotel_email, hotel_id: @hotel.hotel_id, hotel_mobile: @hotel.hotel_mobile, hotel_name: @hotel.hotel_name, hotel_status: @hotel.hotel_status, hotel_type_id: @hotel.hotel_type_id, parent_hotel_id: @hotel.parent_hotel_id, updated_by: @hotel.updated_by } }, as: :json
assert_response 200
end
test "should destroy hotel" do
assert_difference('Hotel.count', -1) do
delete hotel_url(@hotel), as: :json
end
assert_response 204
end
end
|
require 'send_recover_link'
describe SendRecoverLink do
let(:user){double :user, email: "test@test.com", token: "12345678"}
let(:mail_gun_client){double :mail_gun_client}
before do
allow(Mailgun::Client).to receive(:new).and_return(mail_gun_client)
end
it "sends a message to mailgun when it is called" do
params = {from: "bookmarkmanager@mail.com",
to: user.email,
subject: "reset your password",
text: "click here to reset your password http://yourherokuapp.com/reset_password?token=#{user.token}" }
expect(mail_gun_client).to receive(:send_message).with("sandbox_domain_name_for_your_account.mailgun.org", params)
described_class.call(user)
end
end |
# frozen_string_literal: true
require 'test_helper'
class UserLogoutTest < ActionDispatch::IntegrationTest
test 'users get logged the fuck out when they want' do
@user = users(:michael)
get login_path
post login_path, params: { session: { email: @user.email, password: 'password' } }
delete logout_path
follow_redirect!
assert !is_logged_in?
end
end
|
class Importers::TXT::Mapper::TopicQ < Importers::TXT::Mapper::Instrument
def import(options = {})
cc_question_ids_to_delete = @object.cc_questions.pluck(:id)
set_import_to_running
@doc.each do |q, t|
log :input, "#{q},#{t}"
qc = @object.cc_questions.find_by_label q
topic = Topic.find_by_code t
log :matches, "matched to QuestionContruct(#{qc}) AND Topic (#{topic})"
if qc.nil? || topic.nil?
@errors = true
log :outcome, "Record Invalid as QuestionContruct and Topic where not found"
else
qc.topic = topic
if qc.save
log :outcome, "Record Saved"
cc_question_ids_to_delete.delete(qc.id)
else
@errors = true
log :outcome, "Record Invalid : #{qc.errors.full_messages.to_sentence}"
end
end
write_to_log
end
Link.where(target_type: 'CcQuestion', target_id: cc_question_ids_to_delete).delete_all
set_import_to_finished
end
end
|
class BankAccount
@@account_count = 0
def initialize
@account_no = random_string(8)
@savings_balance = 0
@checking_balance = 0
@@account_count += 2
@interest_rate = 0.01
end
def self.show_account_count
puts "Total number of accounts: #{@@account_count}"
end
def total_balance
@savings_balance + @checking_balance
end
def show_accounts
puts "Account no: #{@account_no}"
puts "Savings account:"
puts " balance: #{@savings_balance}, interest rate: #{@interest_rate}"
puts "Checking account:"
puts " balance: #{@checking_balance}, interest rate: #{@interest_rate}"
total_balance()
end
def savings_balance
@savings_balance
end
def checking_balance
@checking_balance
end
def savings_deposit(num)
@savings_balance += num
end
def checking_deposit(num)
@checking_balance += num
end
def savings_withdrawal(num)
if num > @savings_balance
puts "Insufficient funds for this withdrawal. Balance: #{@savings_balance}"
else
@savings_balance -= num
end
end
def checking_withdrawal(num)
if num > @checking_balance
puts "Insufficient funds for this withdrawal. Balance: #{@checking_balance}"
else
@checking_balance -= num
end
end
private
def random_string(num)
Array.new(num){((65 + rand(26)).chr)}.join
end
end
|
class RenameEffectiveOn < ActiveRecord::Migration
def self.up
rename_column :notes, :effective_on, :related_date
end
def self.down
rename_column :notes, :related_date, :effective_on
end
end
|
require 'spec_helper'
module Dbmanager
module Adapters
module Mysql
describe Dumper do
before { Dbmanager.stub :output => STDStub.new }
let :source do
Environment.new(
:username => 'root',
:ignoretables => ['a_view', 'another_view'],
:database => 'database',
:password => 'secret',
:port => 42,
:host => '0.0.0.0'
)
end
subject { Dumper.new(source, '/tmp/dump_file.sql') }
describe '#ignoretables' do
context 'when there are tables to be ignored' do
it 'returns a string containing ignore-table flags' do
string = '--ignore-table=database.a_view --ignore-table=database.another_view'
subject.ignoretables.should == string
end
end
context 'when there are no tables to be ignored' do
it 'returns nil' do
source.stub(:ignoretables => nil)
subject.ignoretables.should be_nil
end
end
end
describe '#dump_command' do
it 'returns expected command' do
[
'mysqldump --ignore-table=database.a_view',
'--ignore-table=database.another_view',
'-uroot -psecret -h0.0.0.0 -P42 database',
'> \'/tmp/dump_file.sql\''
].each do |command_part|
subject.dump_command.should include command_part
end
end
context 'when mysqldump version is >= than 5.6' do
before do
version = 'mysqldump Ver 10.13 Distrib 5.6.0, for osx10.8 (i386)'
Dbmanager.should_receive(:execute).with('mysqldump --version').and_return(version)
end
it {subject.mysqldump_version.should == 5.6 }
it 'adds a flag that sets off gtid-purged' do
subject.dump_command.should include '--set-gtid-purged=OFF'
end
end
context 'when mysqldump version is < than 5.6' do
before do
version = 'mysqldump Ver 10.13 Distrib 5.5.28, for osx10.8 (i386)'
Dbmanager.should_receive(:execute).with('mysqldump --version').and_return(version)
end
it {subject.mysqldump_version.should == 5.5 }
it 'adds a flag that sets off gtid-purged' do
subject.dump_command.should_not include '--set-gtid-purged=OFF'
end
end
end
end
describe Loader do
before { Dbmanager.stub :output => STDStub.new }
describe 'an importer instance' do
before { Time.stub :now => Time.parse('2012/03/23 12:30:32') }
let(:source) { Environment.new :protected => false, :name => 'development', :username => 'root' }
let(:target) { Environment.new :protected => false, :name => 'beta', :username => 'beta_user' }
let(:tmp_file) { '/some/arbitrary/path' }
subject { Loader.new target, tmp_file }
it 'has target and tmp_file attribute methods' do
%w[target tmp_file].each { |m| subject.should respond_to m }
end
describe '#load_command' do
it 'returns expected command' do
subject.load_command.should == 'mysql -ubeta_user < \'/some/arbitrary/path\''
end
end
describe '#create_db_if_missing_command' do
it 'returns expected command' do
subject.create_db_if_missing_command.should == 'bundle exec rake db:create RAILS_ENV=beta'
end
end
describe '#run' do
it 'creates the db if missing and then imports the db' do
subject.stub(:load => nil, :remove_tmp_file => true)
Dbmanager.should_receive(:execute!).with(subject.create_db_if_missing_command)
subject.run
end
end
end
end
describe Importer do
def environment(opts={})
opts = {:protected => false}.merge(opts)
Environment.new opts
end
before { Dbmanager.stub :output => STDStub.new }
describe 'an importer instance' do
before { Time.stub :now => Time.parse('2012/03/23 12:30:32') }
subject { Importer.new source, target, tmp_file }
let(:source) { environment(:name => 'development', :username => 'root') }
let(:target) { environment(:name => 'beta', :username => 'beta_user') }
let(:tmp_file) { '/some/arbitrary/path' }
it 'has target, source and tmp_file attribute methods' do
%w[source target tmp_file].each { |m| subject.should respond_to m }
end
describe '#remove_tmp_file' do
it 'tries to remove the temporary file' do
Dbmanager.should_receive(:execute).with('rm \'/some/arbitrary/path\'')
subject.remove_tmp_file
end
end
describe '#run' do
it 'create ad Dumper that will dump the db' do
Dbmanager.stub(:execute! => nil)
Dumper.should_receive(:new).and_return(mock.as_null_object)
subject.run
end
it 'create ad Loader that will dump the db' do
Dbmanager.stub(:execute! => nil)
Loader.should_receive(:new).and_return(mock.as_null_object)
subject.run
end
end
end
end
end
end
end
|
class VictimZombie < ActiveRecord::Base
belongs_to :victim
belongs_to :zombie
end |
require_dependency "fastengine/application_controller"
module Fastengine
class ParticlesController < ApplicationController
before_action :set_particle, only: [:show, :edit, :update, :destroy]
# GET /particles
def index
@particles = Particle.all
end
# GET /particles/1
def show
end
# GET /particles/new
def new
@particle = Particle.new
end
# GET /particles/1/edit
def edit
end
# POST /particles
def create
@particle = Particle.new(particle_params)
if @particle.save
redirect_to @particle, notice: 'Particle was successfully created.'
else
render :new
end
end
# PATCH/PUT /particles/1
def update
if @particle.update(particle_params)
redirect_to @particle, notice: 'Particle was successfully updated.'
else
render :edit
end
end
# DELETE /particles/1
def destroy
@particle.destroy
redirect_to particles_url, notice: 'Particle was successfully destroyed.'
end
private
# Use callbacks to share common setup or constraints between actions.
def set_particle
@particle = Particle.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def particle_params
params.require(:particle).permit(:name, :speed)
end
end
end
|
require "uri"
class InputProcessing::StreamProxy
def initialize(input_string)
@input_string = input_string
@ios = nil
determine_source
end
def get_line
@ios.gets
end
private
def determine_source
if input_is_file_path?
@ios = InputProcessing::FileStream.new(format_file_path).get_ios
elsif input_is_url?
@ios = InputProcessing::UrlStream.new(@input_string).get_ios
else
@ios = InputProcessing::StringStream.new(@input_string).get_ios
end
end
def input_is_url?
begin
uri = URI.parse(@input_string)
uri.kind_of?(URI::HTTP) or uri.kind_of?(URI::HTTPS)
rescue URI::InvalidURIError => e
false
end
end
def input_is_file_path?
File.exist?(format_file_path)
end
def format_file_path
"#{Rails.root}/public/uploads/#{@input_string}"
end
end
|
require 'rails_helper'
describe TwilioService do
describe 'proxy configuration' do
it 'ignores the proxy configuration if not set' do
expect(Figaro.env).to receive(:proxy_addr).and_return(nil)
expect(Twilio::REST::Client).to receive(:new).with('sid', 'token')
TwilioService.new
end
it 'passes the proxy configuration if set' do
expect(Figaro.env).to receive(:proxy_addr).at_least(:once).and_return('123.456.789')
expect(Figaro.env).to receive(:proxy_port).and_return('6000')
expect(Twilio::REST::Client).to receive(:new).with(
'sid',
'token',
proxy_addr: '123.456.789',
proxy_port: '6000'
)
TwilioService.new
end
end
describe 'performance testing mode' do
let(:user) { build_stubbed(:user, otp_secret_key: 'lzmh6ekrnc5i6aaq') }
it 'uses NullTwilioClient when pt_mode is on' do
expect(FeatureManagement).to receive(:pt_mode?).and_return(true)
expect(NullTwilioClient).to receive(:new)
expect(Twilio::REST::Client).to_not receive(:new)
TwilioService.new
end
it 'uses NullTwilioClient when pt_mode is true and proxy is set' do
expect(FeatureManagement).to receive(:pt_mode?).and_return(true)
allow(Figaro.env).to receive(:proxy_addr).and_return('123.456.789')
expect(NullTwilioClient).to receive(:new)
expect(Twilio::REST::Client).to_not receive(:new)
TwilioService.new
end
it 'uses a real Twilio client when pt_mode is false' do
expect(FeatureManagement).to receive(:pt_mode?).and_return(false)
expect(Twilio::REST::Client).to receive(:new).with('sid', 'token')
TwilioService.new
end
it 'does not send any OTP when pt_mode is true', sms: true do
expect(FeatureManagement).to receive(:pt_mode?).at_least(:once).and_return(true)
SmsSenderOtpJob.perform_now(user)
expect(messages.size).to eq 0
end
it 'sends an OTP from the real number when pt_mode is false', sms: true do
expect(FeatureManagement).to receive(:pt_mode?).at_least(:once).and_return(false)
SmsSenderOtpJob.perform_now(user)
expect(messages.first.from).to eq '+19999999999'
end
it 'does not send a number change SMS when pt_mode is true', sms: true do
expect(FeatureManagement).to receive(:pt_mode?).at_least(:once).and_return(true)
SmsSenderNumberChangeJob.perform_now(user)
expect(messages.size).to eq 0
end
it 'sends number change SMS from real # when pt_mode is false', sms: true do
expect(FeatureManagement).to receive(:pt_mode?).at_least(:once).and_return(false)
SmsSenderNumberChangeJob.perform_now(user)
expect(messages.first.from).to eq '+19999999999'
end
end
describe '#send_sms' do
it 'uses the same account for every call in a single instance', sms: true do
expect(Rails.application.secrets).to receive(:twilio_accounts).
and_return(
[
{
'sid' => 'sid1',
'auth_token' => 'token1',
'number' => '1111111111'
}
]
)
expect(Twilio::REST::Client).to receive(:new).with('sid1', 'token1').and_call_original
twilio = TwilioService.new
twilio.send_sms(
to: '5555555555',
body: '!!CODE1!!'
)
twilio.send_sms(
to: '6666666666',
body: '!!CODE2!!'
)
expect(messages.size).to eq(2)
messages.each do |msg|
expect(msg.from).to eq('+11111111111')
end
end
it 'uses a different Twilio account for different instances', sms: true do
expect(Rails.application.secrets).to receive(:twilio_accounts).
and_return(
[{
'sid' => 'sid1',
'auth_token' => 'token1',
'number' => '1111111111'
}],
[{
'sid' => 'sid2',
'auth_token' => 'token2',
'number' => '2222222222'
}])
expect(Twilio::REST::Client).to receive(:new).with('sid1', 'token1').and_call_original
TwilioService.new.send_sms(
to: '5555555555',
body: '!!CODE1!!'
)
expect(messages.size).to eq(1)
msg1 = messages.first
expect(msg1.from).to eq('+11111111111')
clear_messages
expect(Twilio::REST::Client).to receive(:new).with('sid2', 'token2').and_call_original
TwilioService.new.send_sms(
to: '6666666666',
body: '!!CODE2!!'
)
expect(messages.size).to eq(1)
msg2 = messages.first
expect(msg2.from).to eq('+12222222222')
end
end
describe '.random_account' do
context 'twilio_accounts has multiple entries' do
it 'randomly samples one of the accounts' do
expect(Rails.application.secrets.twilio_accounts).to receive(:sample)
TwilioService.random_account
end
end
end
end
|
require 'rails_helper'
require 'users_helper'
include SessionsHelper
# Specs in this file have access to a helper object that includes
# the UsersHelper. For example:
#
# describe UsersHelper do
# describe "string concat" do
# it "concats two strings with spaces" do
# expect(helper.concat_strings("this","that")).to eq("this that")
# end
# end
# end
RSpec.describe UsersHelper, type: :helper do
let(:my_user) { create(:user) }
describe "is_user_posts_not_zero" do
it "should not have any posts" do
expect( my_user.posts.count).to eq(0)
end
end
describe "is_user_comments_not_zero" do
it "should not have any comments" do
expect( my_user.comments.count).to eq(0)
end
end
describe "is_user_favorites_not_zero" do
it "should not have any favorites" do
expect( my_user.favorites.count).to eq(0)
end
end
end
|
require 'test_helper'
class EmployeesControllerTest < ActionDispatch::IntegrationTest
def setup
@employee = employees(:one)
end
test "should redirect update when not logged in" do
patch employee_path(@employee), params: { employee:
{ first_name: @employee.first_name, last_name: @employee.last_name } }
assert_not flash.empty?
assert_redirected_to login_url
end
test "should redirect destroy when not logged in" do
assert_no_difference 'Employee.count' do
delete employee_path(@employee)
end
assert_redirected_to login_url
end
end |
require_relative '../../test_helper'
class SmoochCapiTest < ActiveSupport::TestCase
def setup
WebMock.disable_net_connect! allow: /#{CheckConfig.get('storage_endpoint')}/
RequestStore.store[:smooch_bot_provider] = 'CAPI'
@config = {
smooch_template_namespace: 'abcdef',
capi_verify_token: '123456',
capi_whatsapp_business_account_id: '123456',
capi_permanent_token: '123456',
capi_phone_number_id: '123456',
capi_phone_number: '123456'
}.with_indifferent_access
RequestStore.store[:smooch_bot_settings] = @config
@uid = '123456:654321'
@incoming_text_message_payload = {
object: 'whatsapp_business_account',
entry: [
{
id: '987654',
changes: [
{
value: {
messaging_product: 'whatsapp',
metadata: {
display_phone_number: '123456',
phone_number_id: '012345'
},
contacts: [
{
profile: {
name: 'John'
},
wa_id: '654321'
}
],
messages: [
{
from: '654321',
id: '456789',
timestamp: Time.now.to_i.to_s,
text: {
body: 'Hello'
},
type: 'text'
}
]
},
field: 'messages'
}
]
}
]
}.to_json
@message_delivery_payload = {
object: 'whatsapp_business_account',
entry: [{
id: '987654',
changes: [{
value: {
messaging_product: 'whatsapp',
metadata: {
display_phone_number: '123456',
phone_number_id: '012345'
},
statuses: [{
id: 'wamid.123456',
recipient_id: '654321',
status: 'delivered',
timestamp: Time.now.to_i.to_s,
conversation: {
id: '987654',
expiration_timestamp: Time.now.tomorrow.to_i.to_s,
origin: {
type: 'user_initiated'
}
},
pricing: {
pricing_model: 'CBP',
billable: true,
category: 'user_initiated'
}
}]
},
field: 'messages'
}]
}]
}.to_json
@message_delivery_error_payload = {
object: 'whatsapp_business_account',
entry: [
{
id: '987654',
changes: [
{
value: {
messaging_product: 'whatsapp',
metadata: {
display_phone_number: '123456',
phone_number_id: '012345'
},
statuses: [
{
id: 'wamid.123456',
status: 'failed',
timestamp: Time.now.to_i.to_s,
recipient_id: '654321',
errors: [
{
code: 131047,
title: 'Message failed to send because more than 24 hours have passed since the customer last replied to this number.',
href: 'https://developers.facebook.com/docs/whatsapp/cloud-api/support/error-codes/'
}
]
}
]
},
field: 'messages'
}
]
}
]
}.to_json
end
def teardown
end
test 'should format template message' do
assert_kind_of Hash, Bot::Smooch.format_template_message('template_name', ['foo', 'bar'], nil, 'fallback', 'en')
end
test 'should process verification request' do
assert_equal 'capi:verification', Bot::Smooch.run(nil)
end
test 'should get user data' do
user_data = Bot::Smooch.api_get_user_data(@uid, @incoming_text_message_payload)
assert_equal @uid, user_data.dig(:clients, 0, :displayName)
end
test 'should preprocess incoming text message' do
preprocessed_message = Bot::Smooch.preprocess_message(@incoming_text_message_payload)
assert_equal @uid, preprocessed_message.dig('appUser', '_id')
assert_equal 'message:appUser', preprocessed_message[:trigger]
end
test 'should preprocess message delivery event' do
preprocessed_message = Bot::Smooch.preprocess_message(@message_delivery_payload)
assert_equal @uid, preprocessed_message.dig('appUser', '_id')
assert_equal 'message:delivery:channel', preprocessed_message[:trigger]
end
test 'should preprocess failed message delivery event' do
preprocessed_message = Bot::Smooch.preprocess_message(@message_delivery_error_payload)
assert_equal @uid, preprocessed_message.dig('appUser', '_id')
assert_equal 'message:delivery:failure', preprocessed_message[:trigger]
end
test 'should preprocess fallback message' do
preprocessed_message = Bot::Smooch.preprocess_message({ foo: 'bar' }.to_json)
assert_equal 'message:other', preprocessed_message[:trigger]
end
test 'should get app name' do
assert_equal 'CAPI', Bot::Smooch.api_get_app_name('app_id')
end
test 'should send text message' do
WebMock.stub_request(:post, 'https://graph.facebook.com/v15.0/123456/messages').to_return(status: 200, body: { id: '123456' }.to_json)
assert_equal 200, Bot::Smooch.send_message_to_user(@uid, 'Test').code.to_i
end
test 'should send interactive message to user' do
WebMock.stub_request(:post, 'https://graph.facebook.com/v15.0/123456/messages').to_return(status: 200, body: { id: '123456' }.to_json)
assert_equal 200, Bot::Smooch.send_message_to_user(@uid, { type: 'interactive' }).code.to_i
end
test 'should send image message to user' do
WebMock.stub_request(:post, 'https://graph.facebook.com/v15.0/123456/messages').to_return(status: 200, body: { id: '123456' }.to_json)
assert_equal 200, Bot::Smooch.send_message_to_user(@uid, 'Test', { 'type' => 'image', 'mediaUrl' => 'https://test.test/image.png' }).code.to_i
end
test 'should report delivery error to Sentry' do
CheckSentry.expects(:notify).once
WebMock.stub_request(:post, 'https://graph.facebook.com/v15.0/123456/messages').to_return(status: 400, body: { error: 'Error' }.to_json)
Bot::Smooch.send_message_to_user(@uid, 'Test')
end
test 'should store media' do
WebMock.stub_request(:get, 'https://graph.facebook.com/v15.0/123456').to_return(status: 200, body: { url: 'https://wa.test/media' }.to_json)
WebMock.stub_request(:get, 'https://wa.test/media').to_return(status: 200, body: File.read(File.join(Rails.root, 'test', 'data', 'rails.png')))
assert_match /capi\/123456/, Bot::Smooch.store_media('123456', 'image/png')
end
test 'should validate Cloud API request' do
b = BotUser.smooch_user || create_team_bot(name: 'Smooch', login: 'smooch', set_approved: true)
create_team_bot_installation user_id: b.id, settings: @config
request = OpenStruct.new(params: { 'hub.mode' => 'subscribe', 'hub.verify_token' => '123456' })
assert Bot::Smooch.valid_capi_request?(request)
request = OpenStruct.new(params: { 'token' => '123456', 'entry' => [{ 'id' => '123456' }] })
assert Bot::Smooch.valid_capi_request?(request)
request = OpenStruct.new(params: { 'token' => '654321', 'entry' => [{ 'id' => '654321' }] })
assert !Bot::Smooch.valid_capi_request?(request)
end
test 'should return empty string if Cloud API payload is not supported' do
assert_equal '', Bot::Smooch.get_capi_message_text(nil)
end
test 'should report failed statuses to Sentry' do
message = {
object: 'whatsapp_business_account',
entry: [
{
id: '987654',
changes: [
{
value: {
messaging_product: 'whatsapp',
metadata: {
display_phone_number: '123456',
phone_number_id: '012345'
},
statuses: [
{
id: 'wamid.123456',
status: 'failed',
timestamp: Time.now.to_i.to_s,
recipient_id: '654321',
errors: [
{
code: 131026,
title: 'Receiver is incapable of receiving this message'
}
]
}
]
},
field: 'messages'
}
]
}
]
}.to_json
CheckSentry.expects(:notify).once
assert Bot::Smooch.run(message)
end
test 'should report to Sentry if payload is not handled' do
message = {
object: 'whatsapp_business_account',
entry: [
{
foo: 'bar'
}
]
}.to_json
CheckSentry.expects(:notify).once
assert !Bot::Smooch.run(message)
end
end
|
require "optparse"
module RPCBench
class Options
MODE_VALUES = ['rabbitmq', 'stomp', 'zeromq', 'grpc', 'nats']
OPT_DEFAULT = {
:host => 'localhost',
:port => 5672,
:mode => 'rabbitmq',
}
def initialize
def sets(key, short, long, desc)
@opt.on(short, long, desc) {|v| @options[key] = v}
end
def setn(key, short, long, desc)
@opt.on(short, long, desc) {|v| @options[key] = v.to_i}
end
@options = OPT_DEFAULT
@opt = OptionParser.new
sets(:mode, '-m', '--mode m',
'specify benchmark mode {rabbitmq|stomp|newtmq|zeromq|grpc|nats} [default: rabbitmq]')
sets(:host, '-s', '--server s',
'specify server to send request')
setn(:port, '-p', '--port p',
'specify port number on which server listens')
end
def parse
@opt.parse!(ARGV)
raise OptionParser::InvalidOption.new('validation failed') unless validated?
@options
end
def usage
@opt.help
end
private
def validated?
ret = true
ret &= MODE_VALUES.include? @options[:mode]
ret &= @options[:conc].is_a? Integer
ret &= @options[:num].is_a? Integer
end
end
class ServerOptions < Options
def initialize
super
end
end
class ClientOptions < Options
OPT_DEFAULT.merge!({
:conc => 10,
:num => 100,
})
def initialize
super
setn(:conc, '-c', '--concurrency c',
'specify concurrent level [default: 10]')
setn(:num, '-n', '--number n',
'specify request number per thread [default: 100]')
end
end
end
|
class RemoveAnnotatableFromAnnotation < ActiveRecord::Migration[5.0]
def change
remove_reference(:annotations, :annotatable, index: true)
end
end
|
require 'rtlog'
require 'erb'
require 'fileutils'
module Rtlog
class Page
include ERB::Util
attr_reader :config
attr_reader :log
attr_writer :logger
def initialize config, log
@config = config
@log = log
end
def logger
defined?(@logger) ? @logger : Rtlog.logger
end
def config_dir
File.expand_path( config['config_dir'] )
end
def parse file_name
# logger.debug("Template parsing: #{file_name}")
open(file_name) { |io| ERB.new( io.read ) }.result(binding)
rescue => ex
"<p>#{h(ex.to_s)}</p><pre class='error'>#{ex.backtrace.map{|m| h(m) }.join('<br />')}</pre>"
end
def generate options={}
options = { :layout => 'layout.html.erb' }.merge(options)
template = nil
if options[:layout]
template = File.join( config_dir, options[:layout] )
template = File.join( Rtlog.root, 'lib', 'rtlog', 'example', 'config', 'layout.html.erb' ) unless File.exist?(template)
end
template = template_path unless template
FileUtils.mkdir_p( File.dirname(file_path) ) unless File.exist?( File.dirname(file_path) )
open(file_path, "w") do |io|
io.write(parse(template))
end
logger.debug("#{self.class} is generated: #{file_path}")
end
def size
config['pages'][page_name]['size'] || 7
rescue
7
end
def template_path
unless defined?(@template_path)
@template_path = nil
if config['pages'] && config['pages'][page_name] && config['pages'][page_name]['template']
@template_path = ::File.join(config_dir, config['pages'][page_name]['template'])
end
unless @template_path && File.exist?(@template_path)
@template_path = File.join( Rtlog.root, 'lib', 'rtlog', 'example', 'config', template_file_name )
end
end
@template_path
end
def template_file_name
class_name = self.class.name.split('::').last.gsub('Page', '').downcase
"#{class_name}.html.erb"
end
def month_pages
unless defined?(@month_pages)
@month_pages = []
log.year_entries.each do |y|
y.month_entries.each do |m|
@month_pages << MonthPage.new(config, log, m)
end
end
end
@month_pages
end
def index_url
config['url_prefix']
end
end
class IndexPage < Page
def title
'Index'
end
def file_path
File.expand_path( File.join(config['target_dir'], 'index.html') )
end
def url
config['url_prefix']
end
def page_name
'index'
end
def recent_day_pages size
recent_day_pages = []
log.recent_day_entries(size).each do |d|
recent_day_pages << DayPage.new( config, log, d )
end
recent_day_pages
end
end
class RssPage < IndexPage
def url
config['url_prefix'] + '/feed/rss'
end
def file_path
File.expand_path( File.join(config['target_dir'], 'feed', 'rss.xml') )
end
def page_name
'rss'
end
def generate
super(:layout => nil)
end
def template_file_name
'rss.xml.erb'
end
end
class MonthPage < Page
attr_reader :month_entry
attr_accessor :current_page
def initialize config, log, month_entry
@config = config
@log = log
@month_entry = month_entry
@current_page = 1
end
def title
date.strftime('%Y-%m')
end
def date
@month_entry.date
end
def current_day_pages
current_day_pages = []
month_entry.day_entries[(current_page - 1) * per_page, per_page].each do |d|
current_day_pages << DayPage.new( config, log, d )
end
current_day_pages
end
def per_page
size
end
def total_entries
@total_entries ||= month_entry.day_entries.size
@total_entries
end
def total_tweets
month_entry.size
end
def total_pages
(Float.induced_from(total_entries)/Float.induced_from(per_page)).ceil
end
def previous
return false if current_page == 1
previous_page = self.clone
previous_page.current_page -= 1
previous_page
end
def next
return false if current_page == total_pages
next_page = self.clone
next_page.current_page += 1
next_page
end
def next_month_page
unless defined?(@next_month_page)
month = log.next_month_entry(self.month_entry)
return nil unless month
@next_month_page = MonthPage.new(config, log, month)
end
@next_month_page
end
def previous_month_page
unless defined?(@previous_month_page)
month = log.previous_month_entry(self.month_entry)
return nil unless month
@previous_month_page = MonthPage.new(config, log, month)
end
@previous_month_page
end
def file_path
page = current_page == 1 ? '' : "_#{current_page}"
File.expand_path( File.join(config['target_dir'], path, "index#{page}.html") )
end
def url(page=current_page)
page = page == 1 ? '' : "index_#{page}"
config['url_prefix'] + '/' + path + '/' + page
end
protected
def page_name
'month'
end
def path
month_entry.date.strftime('%Y/%m')
end
end
class DayPage < Page
attr_reader :day_entry
def initialize config, log, day_entry
@config = config
@log = log
@day_entry = day_entry
end
def title
date.strftime('%Y-%m-%d')
end
def date
@day_entry.date
end
def tweets
@day_entry.tweets do |tw|
yield tw
end
end
def file_path
File.expand_path( File.join(config['target_dir'], path, 'index.html') )
end
def url
config['url_prefix'] + '/' + path
end
protected
def page_name
'day'
end
def path
day_entry.date.strftime('%Y/%m/%d')
end
end
end
|
require 'active_support/concern'
module SimpleMachinable
extend ActiveSupport::Concern
class SimpleBlueprint < Machinist::Blueprint
def make!(attributes={})
make(attributes).tap(&:save!)
end
end
included do
extend Machinist::Machinable
# ClassMethods is included *before* the included block, so blueprint_class
# would be overriden by the extend if it were in the ClassMethods module
class_eval do
def self.blueprint_class
SimpleBlueprint
end
end
end
def self.ensure_machinable(*klasses)
klasses.each do |klass|
next if klass.respond_to?(:blueprint)
klass.send(:include, SimpleMachinable)
end
end
end
|
class UnitTestSetup
def initialize
@name = "Test::Spec"
super
end
VERSION = '0.10.0'
def require_files
if defined?(RUBY_ENGINE) && RUBY_ENGINE == 'ironruby'
require 'test/ispec'
else
require 'rubygems'
gem 'test-spec', "=#{VERSION}"
end
end
def gather_files
@lib_tests_dir = File.expand_path("Languages/Ruby/Tests/Libraries/test-spec-#{VERSION}", ENV["DLR_ROOT"])
@all_test_files = Dir.glob("#{@lib_tests_dir}/test/test*.rb") + Dir.glob("#{@lib_tests_dir}/test/spec*.rb")
end
def sanity
# Some tests load data assuming the current folder
Dir.chdir(@lib_tests_dir)
end
def exclude_critical_files
@all_test_files = @all_test_files.delete_if{|i| i =~ /spec_mocha/}
end
def disable_mri_failures
# disable_spec "mocha",
# "works with test/spec",
# "works with test/spec and Enterprise example"
#
# disable_spec "stubba",
# "works with test/spec and instance method stubbing",
# "works with test/spec and class method stubbing",
# "works with test/spec and global instance method stubbing"
disable_spec 'should.output',
'works with readline',
'works for puts',
'works for print'
disable_spec 'flexmock', 'should handle failures during use'
end
end
|
# -*- encoding : utf-8 -*-
require "rubygems"
require 'bundler/setup'
require "yaml"
require_relative "irc_connector"
require_relative "module_handler"
YAML::ENGINE.yamler = 'syck'
class Bot
attr_accessor :nick, :connected, :base_path, :module_config
def initialize(config_file, module_handler)
@config_file = config_file
@module_handler = module_handler
@connected = false
@own_msgs = []
reload_config
end
def connect
@connector = create_connector(@server, @port, @nick, @username, @realname, @channels)
@connector.connect
@connected = true
end
def handle_state
connect if @connected == false
msg = @connector.read_input
case msg.msg_type
when IrcMsg::DISCONNECTED
@connected = false
when IrcMsg::UNHANDLED
puts "<-- #{msg.raw_msg}"
when IrcMsg::PRIVMSG
if msg.text == "!reload"
reload_config
else
@module_handler.handle_privmsg(msg.from, msg.target, msg.text)
end
@own_msgs.each { |m|
@module_handler.handle_botmsg(m["target"], m["msg"])
}
@own_msgs = []
else
end
end
def send_raw(msg) @connector.send(msg) end
def send_privmsg(target, msg)
@connector.privmsg(target, msg)
@own_msgs.push({ "target" => target, "msg" => msg })
end
private
def reload_config
config = YAML.load_file(@config_file)
@server = config["server"]
@port = config["port"]
@nick = config["nick"]
@username = config["username"]
@realname = config["realname"]
@channels = config["channels"]
@modules_dir = config["modules_dir"]
@excluded_modules = config["excluded_modules"]
@module_config = config["module_config"]
$LOAD_PATH << @modules_dir
@module_handler.reload(self, @modules_dir, @excluded_modules)
end
def create_connector(server, port, nick, username, realname, channels)
IrcConnector.new(server, port, nick, username, realname, channels)
end
end
|
class DrugsController < ApplicationController
skip_before_action :authenticate_user!, only: [:index,:show, :search]
def index
if params[:query].present?
@response = DrugService.all_drugs(params[:query])
@drugs = []
@response.each { |drug| @drugs << { codeCIS: drug["codeCIS"], denomination: drug["denomination"]} }
favorites = Favorite.where(user: current_user)
@codes_cis = favorites.collect { |favorite| favorite.code_cis} #array avec la liste des codes
else
@reviews = Review.all.last(10).reverse
end
end
def show
favorites = Favorite.where(user: current_user)
@codes_cis = favorites.collect { |favorite| favorite.code_cis} #array avec la liste des codes
@reviews = Review.where(code_cis: params[:code_cis])
@drug = DrugService.drug(params[:code_cis])
end
def search
results = DrugService.all_drugs(params[:query])
render json: results
end
end
|
class NavigationBar
include PageObject
include PageFactory
include DataMagic
include FooterPanel
include ErrorCatching
include WaitingMethods
link(:home_button, :id => 'home_link')
link(:transaction_detail, :id => 'transactionsLink0')
def go_to(page_name)
DataMagic.load 'navigation.yml'
@number_of_tries = 0
@navigation_successful = false
page = page_name.downcase.gsub(' ', '_').gsub('_page', '')
navigation_rtm_failure
# ajax_wait
while @number_of_tries < 5
if @number_of_tries > 0
sleep 1
end
if is_voyager?
use_voyager_nav page
else
use_tetris_nav page
end
end
unless @navigation_successful
raise "Navigation Failed, Tried #{@number_of_tries} times"
end
DataMagic.load 'default.yml'
end
def is_voyager?
if @browser.url.include? 'intqa'
true
elsif @browser.url.include? 'func'
true
end
end
private
def menu_hover(page, platform)
sub_menu_item = data_for(:menu_group)[page]
valid_page_name_check(sub_menu_item, page, platform)
hover_over_menu_item(sub_menu_item, platform)
end
def hover_over_menu_item(page, platform)
page = platform.downcase+"_"+page
list_item_element(:id => data_for(:menu_ids)[page]).when_present.hover
end
def navigation_success
@navigation_successful = true
@number_of_tries = 5
end
def use_voyager_nav(page)
menu_hover(page, 'Voyager')
#ajax_wait
benefits_link = list_item_element(:text => 'Card Benefits')
benefits_rewards_link = div_element(:id => 'Benefits_hover').span_element(:id => 'RewardsSummary')
if page.include? 'card_benefits'
navigation_success
benefits_link.when_present.hover
benefits_link.click
elsif page.include? 'benefits_rewards_summary'
navigation_success
benefits_rewards_link.when_present.hover
benefits_rewards_link.click
elsif span_element(:id => data_for(:voyager_sub_menu_ids)[page]).visible?
navigation_success
span_element(:id => data_for(:voyager_sub_menu_ids)[page]).click
end
@number_of_tries += 1
end
def use_tetris_nav(page)
menu_hover(page, 'Tetris')
# ajax_wait
if link_element(:id => data_for(:sub_menu_ids)[page]).visible?
navigation_success
link_element(:id => data_for(:sub_menu_ids)[page]).click
end
@number_of_tries += 1
end
def valid_page_name_check(menu_item, page, platform)
if menu_item.nil?
raise "++++UN-RECOGNIZED PAGE NAME (#{page}) in (#{platform}) Navigation++++
++++Please check the format of your page name++++"
end
end
end
|
#
# Cookbook Name:: virtualmonkey
# Attribute:: default
#
# Copyright (C) 2013 RightScale, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Required attributes
#
# Fog Credentials
# AWS Access Key ID
default[:virtualmonkey][:fog][:aws_access_key_id] = ""
# AWS Secret Access Key
default[:virtualmonkey][:fog][:aws_secret_access_key] = ""
# AWS Publish Access Key ID
default[:virtualmonkey][:fog][:aws_publish_key] = ""
# AWS Publish Secret Key
default[:virtualmonkey][:fog][:aws_publish_secret_key] = ""
# AWS Access Key ID for Test Account
default[:virtualmonkey][:fog][:aws_access_key_id_test] = ""
# AWS Secret Access Key for Test Account
default[:virtualmonkey][:fog][:aws_secret_access_key_test] = ""
# Rackspace API Key
default[:virtualmonkey][:fog][:rackspace_api_key] = ""
# Rackspace Username
default[:virtualmonkey][:fog][:rackspace_username] = ""
# Rackspace UK API Key for Test Account
default[:virtualmonkey][:fog][:rackspace_api_uk_key_test] = ""
# Rackspace UK Username for Test Account
default[:virtualmonkey][:fog][:rackspace_uk_username_test] = ""
# AWS Access Key ID for RS ServerTemplates Account
default[:virtualmonkey][:fog][:aws_access_key_id_rstemp] = ""
# AWS Secret Access Key for RS ServerTemplates Account
default[:virtualmonkey][:fog][:aws_secret_access_key_rstemp] = ""
# Softlayer API Key
default[:virtualmonkey][:fog][:softlayer_api_key] = ""
# Softlayer Username
default[:virtualmonkey][:fog][:softlayer_username] = ""
# Rackspace Managed Auth Key
default[:virtualmonkey][:fog][:rackspace_managed_auth_key] = ""
# Rackspace Managed Username
default[:virtualmonkey][:fog][:rackspace_managed_username] = ""
# Rackspace Managed UK Auth Key for Test Account
default[:virtualmonkey][:fog][:rackspace_managed_uk_auth_key] = ""
# Rackspace Managed UK Username for Test Accounr
default[:virtualmonkey][:fog][:rackspace_managed_uk_username] = ""
# Rackspace UK Auth URL for Test Account
default[:virtualmonkey][:fog][:rackspace_auth_url_uk_test] = ""
# Google Access Key ID
default[:virtualmonkey][:fog][:google_access_key_id] = ""
# Google Secret Access Key
default[:virtualmonkey][:fog][:google_secret_access_key] = ""
# Azure Access Key ID
default[:virtualmonkey][:fog][:azure_access_key_id] = ""
# Azure Secret Access Key
default[:virtualmonkey][:fog][:azure_secret_access_key] = ""
# S3 Bucket Name for Reports Storage
default[:virtualmonkey][:fog][:s3_bucket] = ""
# Openstack Folsom Access Key ID
default[:virtualmonkey][:fog][:openstack_access_key_id] = ""
# Openstack Folsom Secret Access Key
default[:virtualmonkey][:fog][:openstack_secret_access_key] = ""
# Openstack Auth URL
default[:virtualmonkey][:fog][:openstack_auth_url] = ""
# Rackspace Private Access Key ID
default[:virtualmonkey][:fog][:raxprivatev3_access_key_id] = ""
# Rackspace Private Secret Access Key
default[:virtualmonkey][:fog][:raxprivatev3_secret_access_key] = ""
# Rackspace Private Auth URL
default[:virtualmonkey][:fog][:raxprivatev3_auth_url] = ""
# HP Access Key ID
default[:virtualmonkey][:fog][:hp_access_key_id] = ""
# HP Secret Access Key
default[:virtualmonkey][:fog][:hp_secret_access_key] = ""
# HP Auth URL
default[:virtualmonkey][:fog][:hp_auth_url] = ""
# silver_cred settings
default[:virtualmonkey][:silver_creds][:aws_access_key_id] = ""
default[:virtualmonkey][:silver_creds][:aws_secret_access_key] = ""
default[:virtualmonkey][:silver_creds][:silver_qa_admin_password] = ""
default[:virtualmonkey][:silver_creds][:silver_qa_user_password] = ""
default[:virtualmonkey][:silver_creds][:silver_qa_db_password] = ""
default[:virtualmonkey][:silver_creds][:dnsmadeeasy_test_password] = ""
default[:virtualmonkey][:silver_creds][:dnsmadeeasy_test_user] = ""
default[:virtualmonkey][:silver_creds][:rackspace_auth_key] = ""
default[:virtualmonkey][:silver_creds][:rackspace_username] = ""
default[:virtualmonkey][:silver_creds][:rackspace_auth_key_uk] = ""
default[:virtualmonkey][:silver_creds][:rackspace_username_uk] = ""
default[:virtualmonkey][:silver_creds][:rackspace_rackconnect_auth_key] = ""
default[:virtualmonkey][:silver_creds][:rackspace_rackconnect_username] = ""
default[:virtualmonkey][:silver_creds][:silver_was_acct_name] = ""
default[:virtualmonkey][:silver_creds][:silver_was_acct_key] = ""
default[:virtualmonkey][:silver_creds][:softlayer_access_key_id] = ""
default[:virtualmonkey][:silver_creds][:softlayer_secret_access_key] = ""
default[:virtualmonkey][:silver_creds][:openstack_folsom_access_key_id] = ""
default[:virtualmonkey][:silver_creds][:openstack_folsom_secret_access_key] = ""
default[:virtualmonkey][:silver_creds][:openstack_auth_url] = ""
default[:virtualmonkey][:silver_creds][:publish_test_user] = ""
default[:virtualmonkey][:silver_creds][:publish_test_password] = ""
# dns_provider settings
default[:virtualmonkey][:dns_provider][:api_key] = ""
default[:virtualmonkey][:dns_provider][:secret_key] = ""
# Git Settings
# Git Username
default[:virtualmonkey][:git][:user] = ""
# Git Email
default[:virtualmonkey][:git][:email] = ""
# Git SSH Key
default[:virtualmonkey][:git][:ssh_key] = ""
# Git Hostname
default[:virtualmonkey][:git][:host_name] = ""
# Rest Connection Settings
# RightScale Password
default[:virtualmonkey][:rest][:right_passwd] = ""
# RightScale Email
default[:virtualmonkey][:rest][:right_email] = ""
# RightScale Account ID
default[:virtualmonkey][:rest][:right_acct_id] = ""
# RightScale Subdomain
default[:virtualmonkey][:rest][:right_subdomain] = ""
# SSH Key Used by Rest Connection
default[:virtualmonkey][:rest][:ssh_key] = ""
# Public Key for allowing connections from
default[:virtualmonkey][:rest][:ssh_pub_key] = ""
# Rest Connection Repository URL
default[:virtualmonkey][:rest][:repo_url] = ""
# Rest Connection Repository Branch
default[:virtualmonkey][:rest][:repo_branch] = ""
# Test Specific Configuration Settings
# Knife PEM Key used by Chef Client Tests
default[:virtualmonkey][:test_config][:knife_pem_key] = ""
# VirtualMonkey Settings
# VirtualMonkey Repository URL
default[:virtualmonkey][:virtualmonkey][:monkey_repo_url] = ""
# VirtualMonkey Repository Branch
default[:virtualmonkey][:virtualmonkey][:monkey_repo_branch] = ""
# Collateral Repository URL
default[:virtualmonkey][:virtualmonkey][:collateral_repo_url] = ""
# Collateral Repository Branch
default[:virtualmonkey][:virtualmonkey][:collateral_repo_branch] = ""
# Right API Objects Repository URL
default[:virtualmonkey][:virtualmonkey][:right_api_objects_repo_url] = ""
# Right API Objects Repository Branch
default[:virtualmonkey][:virtualmonkey][:right_api_objects_repo_branch] = ""
# RocketMonkey Settings
# RocketMonkey Repository URL
default[:virtualmonkey][:rocketmonkey][:repo_url] = ""
# RocketMonkey Repository Branch
default[:virtualmonkey][:rocketmonkey][:repo_branch] = ""
# Recommended attributes
#
# Gems required for rest_connection
default[:virtualmonkey][:rest][:gem_packages] = {
"rake" => "10.0.3",
"bundler" => "1.2.3",
"ruby-debug" => "0.10.4",
"gemedit" => "1.0.1",
"diff-lcs" => "1.1.3",
"rspec" => "2.12.0",
"json" => "1.7.7"
}
# Monkey user
default[:virtualmonkey][:user] = "root"
# Monkey user's home directory
default[:virtualmonkey][:user_home] = "/root"
# Monkey group
default[:virtualmonkey][:group] = "root"
# Rest connection path
default[:virtualmonkey][:rest_connection_path] =
"#{node[:virtualmonkey][:user_home]}/rest_connection"
# Virtualmonkey path
default[:virtualmonkey][:virtualmonkey_path] =
"#{node[:virtualmonkey][:user_home]}/virtualmonkey"
# Rocketmonkey path
default[:virtualmonkey][:rocketmonkey_path] =
"#{node[:virtualmonkey][:user_home]}/rocketmonkey"
# The version for the rubygems-update gem
default[:virtualmonkey][:rubygems_update_version] = "1.8.24"
# The version of right_cloud_api rubygem to install
default[:virtualmonkey][:right_cloud_api_version] = "0.0.1"
# Optional Attributes
# Azure Hack on/off
default[:virtualmonkey][:rest][:azure_hack_on] = ""
# Azure Hack Retry Count
default[:virtualmonkey][:rest][:azure_hack_retry_count] = ""
# Azure Hack Sleep Seconds
default[:virtualmonkey][:rest][:azure_hack_sleep_seconds] = ""
# API Logging on/off
default[:virtualmonkey][:rest][:api_logging] = ""
# legacy shard setting
default['virtualmonkey']['rest']['legacy_shard'] = 'false'
# Calculated Attributes
# Azure Endpoint is calculated from the Access Key ID
default[:virtualmonkey][:fog][:azure_endpoint] = "https://" +
"#{node[:virtualmonkey][:fog][:azure_access_key_id]}.blob.core.windows.net"
# AWS Default SSH Keys
default['virtualmonkey']['aws_default_ssh_key_ids']['east'] = '20578'
default['virtualmonkey']['aws_default_ssh_key_ids']['eu'] = '324202'
default['virtualmonkey']['aws_default_ssh_key_ids']['us_west'] = '173773'
default['virtualmonkey']['aws_default_ssh_key_ids']['ap_singapore'] = '324203'
default['virtualmonkey']['aws_default_ssh_key_ids']['ap_tokyo'] = '324190'
default['virtualmonkey']['aws_default_ssh_key_ids']['us_oregon'] = '255379001'
default['virtualmonkey']['aws_default_ssh_key_ids']['sa_sao_paolo'] = '216453001'
default['virtualmonkey']['aws_default_ssh_key_ids']['ap_sydney'] = '323389001'
# ruby version
default['virtualmonkey']['ruby']['version'] = '1.9'
|
Pod::Spec.new do |s|
s.name = 'Mask'
s.version = '0.1.0'
s.summary = 'A short description of Mask.'
s.description = <<-DESC
TODO: Add long description of the pod here.
DESC
s.homepage = 'https://github.com/Huuush/Mask'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'Huuush' => '609742482@qq.com' }
s.source = { :git => 'https://github.com/Huuush/Mask-GPUImage.git', :tag => s.version.to_s }
s.ios.deployment_target = '9.0'
s.source_files = 'Mask/Classes/**/*'
# s.public_header_files = 'Pod/Classes/**/*.h'
# s.frameworks = 'UIKit', 'MapKit'
s.dependency 'Masonry','1.1.0'
s.dependency 'MJRefresh', '3.1.12'
s.dependency 'YYModel', '1.0.4'
s.dependency 'MJExtension'
s.dependency 'AFNetworking'
s.dependency 'GPUImage','0.1.7'
s.dependency 'YBImageBrowser'
end
|
class Division < ActiveRecord::Base
paginates_per 50
has_many :votes
has_many :mps, through: :votes
has_one :division_info
has_many :whips
def find_mp(id)
find_by(deputy_id: id )
end
end
|
module AcquiaToolbelt
class CLI
class Environments < AcquiaToolbelt::Thor
# Public: List environments on a subscription.
#
# Output environment information.
#
# Returns enviroment data.
desc 'list', 'List all environment data.'
def list
if options[:subscription]
subscription = options[:subscription]
else
subscription = AcquiaToolbelt::CLI::API.default_subscription
end
environment = options[:environment]
# If the environment option is set, just fetch a single environment.
if environment
environments = [environment]
else
environments = AcquiaToolbelt::CLI::API.environments
end
ui.say
rows = []
headings = [
'Host',
'Environment',
'Current release',
'Live development',
'DB clusters',
'Default domain'
]
environments.each do |env|
env_info = AcquiaToolbelt::CLI::API.request "sites/#{subscription}/envs/#{env}"
row_data = []
row_data << env_info['ssh_host']
row_data << env_info['name']
row_data << env_info['vcs_path']
row_data << env_info['livedev'].capitalize
row_data << env_info['db_clusters'].join(', ')
row_data << env_info['default_domain']
rows << row_data
end
ui.output_table('', headings, rows)
end
# Public: Toggle whether live development is enabled on an environment.
#
# Valid actions are enable or disable.
#
# Returns a status message.
desc 'live-development', 'Enable/disbale live development on an environment.'
method_option :action, :type => :string, :aliases => %w(-a),
:required => true, :enum => ['enable', 'disable'],
:desc => 'Status of live development (enable/disable).'
def live_development
if options[:environment].nil?
ui.say "No value provided for required options '--environment'"
return
end
if options[:subscription]
subscription = options[:subscription]
else
subscription = AcquiaToolbelt::CLI::API.default_subscription
end
action = options[:action]
environment = options[:environment]
live_development_set = AcquiaToolbelt::CLI::API.request "sites/#{subscription}/envs/#{environment}/livedev/#{action}", 'POST'
if live_development_set['id']
ui.success "Live development has been successfully #{action}d on #{environment}."
else
ui.fail AcquiaToolbelt::CLI::API.display_error(live_development_set)
end
end
end
end
end
|
# -*- encoding: utf-8 -*-
# stub: rib 1.6.1 ruby lib
Gem::Specification.new do |s|
s.name = "rib".freeze
s.version = "1.6.1"
s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib".freeze]
s.authors = ["Lin Jen-Shin (godfat)".freeze]
s.date = "2022-12-30"
s.description = "Ruby-Interactive-ruBy -- Yet another interactive Ruby shell\n\nRib is based on the design of [ripl][] and the work of [ripl-rc][], some of\nthe features are also inspired by [pry][]. The aim of Rib is to be fully\nfeatured and yet very easy to opt-out or opt-in other features. It shall\nbe simple, lightweight and modular so that everyone could customize Rib.\n\n[ripl]: https://github.com/cldwalker/ripl\n[ripl-rc]: https://github.com/godfat/ripl-rc\n[pry]: https://github.com/pry/pry".freeze
s.email = ["godfat (XD) godfat.org".freeze]
s.executables = [
"rib".freeze,
"rib-all".freeze,
"rib-auto".freeze,
"rib-min".freeze,
"rib-rack".freeze,
"rib-rails".freeze]
s.files = [
".gitignore".freeze,
".gitlab-ci.yml".freeze,
".gitmodules".freeze,
"CHANGES.md".freeze,
"Gemfile".freeze,
"LICENSE".freeze,
"README.md".freeze,
"Rakefile".freeze,
"TODO.md".freeze,
"bin/rib".freeze,
"bin/rib-all".freeze,
"bin/rib-auto".freeze,
"bin/rib-min".freeze,
"bin/rib-rack".freeze,
"bin/rib-rails".freeze,
"lib/rib.rb".freeze,
"lib/rib/all.rb".freeze,
"lib/rib/api.rb".freeze,
"lib/rib/app/auto.rb".freeze,
"lib/rib/app/rack.rb".freeze,
"lib/rib/app/rails.rb".freeze,
"lib/rib/config.rb".freeze,
"lib/rib/core.rb".freeze,
"lib/rib/core/completion.rb".freeze,
"lib/rib/core/history.rb".freeze,
"lib/rib/core/last_value.rb".freeze,
"lib/rib/core/multiline.rb".freeze,
"lib/rib/core/readline.rb".freeze,
"lib/rib/core/squeeze_history.rb".freeze,
"lib/rib/core/strip_backtrace.rb".freeze,
"lib/rib/debug.rb".freeze,
"lib/rib/extra/autoindent.rb".freeze,
"lib/rib/extra/byebug.rb".freeze,
"lib/rib/extra/hirb.rb".freeze,
"lib/rib/extra/paging.rb".freeze,
"lib/rib/extra/spring.rb".freeze,
"lib/rib/more.rb".freeze,
"lib/rib/more/anchor.rb".freeze,
"lib/rib/more/beep.rb".freeze,
"lib/rib/more/bottomup_backtrace.rb".freeze,
"lib/rib/more/caller.rb".freeze,
"lib/rib/more/color.rb".freeze,
"lib/rib/more/edit.rb".freeze,
"lib/rib/more/multiline_history.rb".freeze,
"lib/rib/more/multiline_history_file.rb".freeze,
"lib/rib/plugin.rb".freeze,
"lib/rib/runner.rb".freeze,
"lib/rib/shell.rb".freeze,
"lib/rib/test.rb".freeze,
"lib/rib/test/history.rb".freeze,
"lib/rib/test/multiline.rb".freeze,
"lib/rib/version.rb".freeze,
"rib.gemspec".freeze,
"task/README.md".freeze,
"task/gemgem.rb".freeze,
"test/core/test_completion.rb".freeze,
"test/core/test_history.rb".freeze,
"test/core/test_last_value.rb".freeze,
"test/core/test_multiline.rb".freeze,
"test/core/test_readline.rb".freeze,
"test/core/test_squeeze_history.rb".freeze,
"test/core/test_strip_backtrace.rb".freeze,
"test/extra/test_autoindent.rb".freeze,
"test/more/test_anchor.rb".freeze,
"test/more/test_beep.rb".freeze,
"test/more/test_caller.rb".freeze,
"test/more/test_color.rb".freeze,
"test/more/test_multiline_history.rb".freeze,
"test/test_api.rb".freeze,
"test/test_plugin.rb".freeze,
"test/test_runner.rb".freeze,
"test/test_shell.rb".freeze]
s.homepage = "https://github.com/godfat/rib".freeze
s.licenses = ["Apache-2.0".freeze]
s.rubygems_version = "3.4.1".freeze
s.summary = "Ruby-Interactive-ruBy -- Yet another interactive Ruby shell".freeze
s.test_files = [
"test/core/test_completion.rb".freeze,
"test/core/test_history.rb".freeze,
"test/core/test_last_value.rb".freeze,
"test/core/test_multiline.rb".freeze,
"test/core/test_readline.rb".freeze,
"test/core/test_squeeze_history.rb".freeze,
"test/core/test_strip_backtrace.rb".freeze,
"test/extra/test_autoindent.rb".freeze,
"test/more/test_anchor.rb".freeze,
"test/more/test_beep.rb".freeze,
"test/more/test_caller.rb".freeze,
"test/more/test_color.rb".freeze,
"test/more/test_multiline_history.rb".freeze,
"test/test_api.rb".freeze,
"test/test_plugin.rb".freeze,
"test/test_runner.rb".freeze,
"test/test_shell.rb".freeze]
end
|
class RenameTables < ActiveRecord::Migration
def change
rename_table(:shoes, :brands)
rename_table(:shoes_stores, :brands_stores)
rename_column(:brands, :brand, :name)
end
end
|
FactoryGirl.define do
factory :locker do
name %w(S M L).sample + (1..1000).to_a.sample.to_s
size %w(Small Medium Large).sample
available true
end
end |
# frozen_string_literal: true
require 'rails_admin/config/fields/types/numeric'
module RailsAdmin
module Config
module Fields
module Types
class Integer < RailsAdmin::Config::Fields::Types::Numeric
# Register field type for the type loader
RailsAdmin::Config::Fields::Types.register(self)
register_instance_option :sort_reverse? do
serial?
end
end
end
end
end
end
|
require 'spec_helper'
require 'rails_helper'
describe Channel do
it "should make channel" do
c = Channel.new(:name => "Seinfeld", :image_url => "google.com", :network => "NBC", :api_id => 35)
expect(c.save).to be(true)
end
it "should fail channel" do
c = Channel.new(:image_url => "google.com")
expect(c.save).to be(false)
end
it "should fail channel unique id" do
c = Channel.new(:name => "Seinfeld", :image_url => "google.com", :network => "NBC", :api_id => 35)
expect(c.save).to be(true)
c = Channel.new(:name => "Friends", :image_url => "google.com", :network => "NBC", :api_id => 35)
expect(c.save).to be(false)
end
it "should parse show details properly" do
show = JSON.parse('{"backdrop_path":"/3yLECa8OqWys9yl7vE53apjoDsO.jpg","id": 4385,"original_name":"The Colbert Report","first_air_date":"2005-10-17","origin_country":["US"],"poster_path":"/7mwErPneNN2BUAODW2gldnhL8Oe.jpg","popularity":1.88902176650493,"name":"The Colbert Report","vote_average":8.0,"vote_count":2,"networks": [{"id": 88,"name": "FX"}]}')
j = Channel.parse_detail(show)
expect(j[:id]).to eq(4385)
expect(j[:name]).to eq("The Colbert Report")
expect(j[:poster_path]).to eq('/7mwErPneNN2BUAODW2gldnhL8Oe.jpg')
end
it "should follow correctly" do
c = Channel.create(:name => "Seinfeld", :image_url => "google.com", :network => "NBC", :api_id => 35)
u = User.new(:email => "q@q.com", :password => "password", username: 'joe')
u.skip_confirmation!
u.save!
params = {:cid => c.id}
Channel.follow(params, u, nil)
fav = Favorite.where(:user_id => u.id, :channel_id => c.id)
expect(fav.empty?).to be(false)
end
it "should follow correctly api_id and get correct following method" do
c = Channel.create(:name => "Seinfeld", :image_url => "google.com", :network => "NBC", :api_id => "35")
u = User.new(:email => "q@q.com", :password => "password", username: 'joe')
u.skip_confirmation!
u.save!
params = {:api_id => c.api_id}
Channel.follow(params, u, nil)
fav = Favorite.where(:user_id => u.id, :channel_id => c.id)
expect(fav.empty?).to be(false)
params = {:id => c.api_id}
following = Channel.following(params, u)
expect(following).to be(true)
end
it "should unfollow correctly" do
c = Channel.create(:name => "Seinfeld", :image_url => "google.com", :network => "NBC", :api_id => 35)
u = User.new(:email => "q@q.com", :password => "password", username: 'joe')
u.skip_confirmation!
u.save!
params = {:cid => c.id}
Channel.follow(params, u, nil)
fav = Favorite.where(:user_id => u.id, :channel_id => c.id)
expect(fav.empty?).to be(false)
Channel.unfollow(params, u)
fav = Favorite.where(:user_id => u.id, :channel_id => c.id)
expect(fav).to eq([])
end
it "should correctly add to active user list" do
c = Channel.create(:name => "Seinfeld", :image_url => "google.com", :network => "NBC", :api_id => 35)
u = User.new(:email => "q@q.com", :password => "password", username: 'joe')
u.skip_confirmation!
u.save!
params = {:cid => c.id}
Channel.active_add(params, u)
act = Active.where(:user_id => u.id, :channel_id => c.id)
expect(act.empty?).to be(false)
end
it "should correctly add to active user list and update" do
c = Channel.create(:name => "Seinfeld", :image_url => "google.com", :network => "NBC", :api_id => 35)
u = User.new(:email => "q@q.com", :password => "password", username: 'joe')
u.skip_confirmation!
u.save!
params = {:cid => c.id.to_i}
Channel.active_add(params, u)
act = Active.where(:user_id => u.id, :channel_id => c.id)
expect(act.empty?).to be(false)
before = act[0].updated
Channel.active_update(params, u)
act = Active.where(:user_id => u.id, :channel_id => c.id)
expect(act.empty?).to be(false)
after = act[0].updated
expect(after >= before).to be(true)
end
it "should correctly add to active user list and delete" do
c = Channel.create(:name => "Seinfeld", :image_url => "google.com", :network => "NBC", :api_id => 35)
u = User.new(:email => "q@q.com", :password => "password", username: 'joe')
u.skip_confirmation!
u.save!
params = {:cid => c.id}
Channel.active_add(params, u)
act = Active.where(:user_id => u.id, :channel_id => c.id)
expect(act.empty?).to be(false)
Channel.active_delete(params, u)
act = Active.where(:user_id => u.id, :channel_id => c.id)
expect(act).to eq([])
end
context 'getting messages' do
it 'should return the messages for the channel' do
c = Channel.create(:name => "Seinfeld", :image_url => "google.com", :network => "NBC", :api_id => 35)
u = User.new(:email => "q@q.com", :password => "password", username: 'joe')
u.skip_confirmation!
u.save!
Message.create!(user_id: u.id, channel_id: c.id, body: 'huh, does this work?')
expect(Channel.get_messages(c.id)).to eq [{user: 'joe', body: 'huh, does this work?', id: 4}]
end
end
### Topics ###
it 'should create main topic by default works' do
c = Channel.create(:name => "Seinfeld", :image_url => "google.com", :network => "NBC", :api_id => 35)
expect(Topic.find_by(channel_id: c.id, name: "Main")).to_not be(nil)
end
it 'should create new topic works' do
c = Channel.create(:name => "Seinfeld", :image_url => "google.com", :network => "NBC", :api_id => 35)
t = c.topics.create(:name => "awesome")
expect(Topic.find_by(channel_id: c.id, name: "awesome")).to_not be(nil)
end
it 'should create new topic and message and they both link with each other' do
c = Channel.create(:name => "Seinfeld", :image_url => "google.com", :network => "NBC", :api_id => 35)
t = c.topics.create(:name => "awesome")
expect(Topic.find_by(channel_id: c.id, name: "awesome")).to_not be(nil)
u = User.new(:email => "q@q.com", :password => "password", username: 'joe')
u.skip_confirmation!
u.save!
m = Message.create!(user_id: u.id, channel_id: c.id, body: '#awesome does this work?', topic_id: t.id)
expect(m.topic.name).to eq("awesome")
end
it 'should return correct active' do
c = Channel.create(:name => "Seinfeld", :image_url => "google.com", :network => "NBC", :api_id => 35)
t = c.topics.create(:name => "awesome")
expect(Topic.find_by(channel_id: c.id, name: "awesome")).to_not be(nil)
u = User.new(:email => "q@q.com", :password => "password", username: 'joe')
u.skip_confirmation!
u.save!
a = c.actives.create(user_id: u.id, updated: DateTime.now)
expect(Active.where(:channel_id => c.id).where("updated > ?", DateTime.now-5.seconds)).to_not be_empty
end
it 'should return correct active user list' do
c = Channel.create(:name => "Seinfeld", :image_url => "google.com", :network => "NBC", :api_id => 35)
t = c.topics.create(:name => "awesome")
expect(Topic.find_by(channel_id: c.id, name: "awesome")).to_not be(nil)
u = User.new(:email => "q@q.com", :password => "password", username: 'joe')
u.skip_confirmation!
u.save!
a = c.actives.create(user_id: u.id, updated: DateTime.now)
expect(Active.where(:channel_id => c.id).where("updated > ?", DateTime.now-5.seconds)).to_not be_empty
userlist = Channel.active_user_list({id: c.id}, u)
expect(userlist).to eq(['joe'])
end
it 'should create topic using channel controller' do
c = Channel.create(:name => "Seinfeld", :image_url => "google.com", :network => "NBC", :api_id => 35)
u = User.new(:email => "q@q.com", :password => "password", username: 'joe')
u.skip_confirmation!
t = c.create_topic(:name => "awesome")
expect(Topic.find_by(channel_id: c.id, name: "awesome")).to_not be(nil)
end
it 'should get correct message list for topic' do
c = Channel.create(:name => "Seinfeld", :image_url => "google.com", :network => "NBC", :api_id => 35)
u = User.new(:email => "q@q.com", :password => "password", username: 'joe')
u.skip_confirmation!
t = c.create_topic(:name => "awesome")
u.save!
Message.create!(user_id: u.id, channel_id: c.id, body: '#awesome yo', topic_id: t.id)
expect(Channel.get_messages_for_topic(c.id, "awesome")).to eq [{user: 'joe', body: '#awesome yo', id: 3}]
end
# it 'should get all users for channel' do
# c = Channel.create(:name => "Seinfeld", :image_url => "google.com", :network => "NBC", :api_id => 35)
# t = c.topics.create(:name => "awesome")
# expect(Topic.find_by(channel_id: c.id, name: "awesome")).to_not be(nil)
# u = User.new(:email => "q@q.com", :password => "password", username: 'joe')
# u.skip_confirmation!
# u.save!
# a = c.actives.create(user_id: u.id, updated: DateTime.now)
# expect(Active.where(:channel_id => c.id).where("updated > ?", DateTime.now-5.seconds)).to_not be_empty
# userlist = c.get_users()
# expect(userlist).to_be not_empty
# end
it 'should get right no user count' do
c = Channel.create(:name => "Seinfeld", :image_url => "google.com", :network => "NBC", :api_id => 35)
count = c.get_user_count(c.id, "Main")
expect(count).to eq 0
end
it 'should get right user count' do
c = Channel.create(:name => "Seinfeld", :image_url => "google.com", :network => "NBC", :api_id => 35)
t = c.topics.create(:name => "awesome")
expect(Topic.find_by(channel_id: c.id, name: "awesome")).to_not be(nil)
u = User.new(:email => "q@q.com", :password => "password", username: 'joe')
u.skip_confirmation!
u.save!
a = c.actives.create(user_id: u.id, updated: DateTime.now)
expect(Active.where(:channel_id => c.id).where("updated > ?", DateTime.now-5.seconds)).to_not be_empty
count = c.get_user_count(c.id, "Main")
expect(count).to eq 1
end
end |
module Bridge
# Class representing bridge deal
class Deal
include Comparable
attr_reader :n, :e, :s, :w
# Returns cards of given direction
def [](direction)
must_be_direction!(direction)
send("#{direction.to_s.downcase}")
end
# Compares the deal with given deal
def <=>(other)
id <=> other.id
end
# Creates new deal object with cards given in hash of directions
#
# ==== Example
# Bridge::Deal.new(:n => ["HA", ...], :s => ["SA"], ...)
def initialize(hands)
hands.each do |hand, cards|
self[hand] = cards.map { |c| Card.new(c) }
end
end
# Converts given id to deal
def self.from_id(id)
raise ArgumentError, "invalid deal id: #{id}" unless Bridge.deal_id?(id)
n = []; e = []; s = []; w = []; k = DEALS
DECK.each_with_index do |card, i|
card = Card.new(card)
x = k * (13 - n.size) / (52 - i)
if id < x
n << card
else
id -= x
x = k * (13 - e.size) / (52 - i)
if id < x
e << card
else
id -= x
x = k * (13 - s.size) / (52 - i)
if id < x
s << card
else
id -= x
x = k * (13 - w.size) / (52 - i)
w << card
end
end
end
k = x
end
new(:n => n, :e => e, :s => s, :w => w)
end
# Converts given deal (hash) to id
def id
k = DEALS; id = 0; n = self.n.dup; e = self.e.dup; s = self.s.dup; w = self.w.dup
DECK.each_with_index do |card, i|
x = k * n.size / (52 - i)
unless n.delete(card)
id += x
x = k * e.size / (52 - i)
unless e.delete(card)
id += x
x = k * s.size / (52 - i)
unless s.delete(card)
id += x
x = k * w.size / (52 - i)
w.delete(card)
end
end
end
k = x
end
id
end
# Returns the direction that owns the card
def owner(card)
DIRECTIONS.find { |direction| self[direction].include?(card) }
end
# Returns a random deal id
def self.random_id
rand(DEALS)
end
# Returns a random deal
def self.random
from_id(random_id)
end
# Checks if the deal is a valid deal
def valid?
if DIRECTIONS.all? { |d| self[d] && self[d].size == 13 }
cards = (n + e + s + w).uniq
if cards.size == 52
cards.all? { |card| Bridge.card?(card.to_s) }
else
false
end
else
false
end
end
# Returns hash with hands
def to_hash
{"N" => n.map(&:to_s), "E" => e.map(&:to_s), "S" => s.map(&:to_s), "W" => w.map(&:to_s)}
end
def inspect
to_hash.inspect
end
def honour_card_points(side = nil)
hash = DIRECTIONS.each_with_object({}) do |direction, h|
h[direction] = self[direction].inject(0) { |sum, card| sum += card.honour_card_points }
end
if side
side.to_s.upcase.split("").inject(0) { |sum, direction| sum += hash[direction] }
else
hash
end
end
alias :hcp :honour_card_points
def sort_by_color!(trump = nil)
sort_by_color(trump).each do |direction, hand|
self[direction] = hand
end
self
end
def sort_by_color(trump = nil)
DIRECTIONS.each_with_object({}) do |direction, sorted|
splitted_colors = cards_for(direction)
splitted_colors.reject! { |color, cards| cards.empty? }
sorted_colors = sort_colors(splitted_colors.keys, trump)
sorted[direction] = sorted_colors.map { |color| splitted_colors.delete(color) }.flatten
end
end
def cards_for(direction)
TRUMPS.each_with_object({}) do |trump, colors|
cards = self[direction].select { |card| card.suit == trump }
colors[trump] = cards
end
end
private
def must_be_direction!(string)
raise ArgumentError, "invalid direction: #{string}" unless Bridge.direction?(string.to_s.upcase)
end
def []=(direction, cards)
must_be_direction!(direction)
instance_variable_set("@#{direction.to_s.downcase}", cards)
end
def sort_colors(colors, trump = nil)
black = ["S", "C"] & colors
red = ["H", "D"] & colors
sorted = if black.delete(trump)
[trump] << red.shift << black.shift << red.shift
elsif red.delete(trump)
[trump] << black.shift << red.shift << black.shift
elsif black.size >= red.size
[black.shift] << red.shift << black.shift << red.shift
else
[red.shift] << black.shift << red.shift << black.shift
end
sorted.compact
end
end
end
|
class Follower
attr_accessor :name, :age, :life_motto
@@all = []
def initialize(name, age, life_motto)
@name = name
@age = age
@life_motto = life_motto
@@all << self
end
def oaths
BloodOath.all.select do |oath|
oath.follower == self
end
end
def cults
oaths.map(&:cult)
end
def join_cult(cult, current_date)
if @age < cult.minimum_age
puts "Sorry buddy, you're a bit young for the culting business."
else
new_oath = BloodOath.new(self, cult, current_date)
end
end
def self.all
@@all
end
def self.of_a_certain_age(age)
@@all.select do |follower|
follower.age >= age
end
end
def my_cults_slogans
cults.collect(&:slogan)
end
def self.most_active
@@all.max_by do |flwr|
flwr.cults.length
end
end
def self.top_ten
@@all.sort_by do |flwr|
flwr.cults.length
end.reverse[0..9]
end
def fellow_cult_members
cults.collect do |cult|
cult.oaths.collect(&:follower)
end.flatten.uniq
end
end
|
class PostsController < ApplicationController
before_action :require_user
def home
@posts = if params[:term]
Post.where('title LIKE ? or location LIKE ? or description LIKE ? or requirements LIKE ? or category LIKE ?', "%#{params[:term]}%", "%#{params[:term]}%", "%#{params[:term]}%", "%#{params[:term]}%", "%#{params[:term]}%").order('id DESC')
else
@posts = Post.all.order('id DESC')
end
end
def show
@post = Post.find(params[:id])
end
def destroy
@post = Post.find(params[:id])
if Interest.find_by(post_id: @post.id).present?
@interests = Interest.where(post_id: @post.id).all
for interest in @interests do
interest.destroy
end
end
@post.destroy
redirect_to posts_path
end
def decline
@interest = Interest.find(params[:id])
@interest.destroy
redirect_to sharedwithme_path
end
def edit
@post = Post.find(params[:id])
end
def update
@post = Post.find(params[:id])
if @post.update(post_params)
redirect_to @post
else
render 'edit'
end
end
def new
if Profile.where(:user_id => current_user.id).present?
@post = Post.new
else
redirect_to profile_path
end
end
def create
@post = Post.new(post_params)
@post.user_id = current_user.id
if @post.save
redirect_to posts_path
else
render 'new'
end
end
def myposts
@posts = current_user.posts.all
end
def sharedwithme
@posts = current_user.posts.all
@interests = Interest.where(post_id: @posts.ids).all
for interest in @interests do
puts interest.id
interest.update_attributes(:seen => true)
interest.save
end
end
private
def post_params
params.require(:post).permit(:title, :location, :description, :requirements, :category, :term)
end
end
|
# Configure your routes here
# See: http://hanamirb.org/guides/routing/overview/
root to: 'home#index'
resources :books, only: %i[index new create]
|
include_recipe 'consul::install_binary'
include_recipe 'consul::ui'
include_recipe 'consul-template::default'
include_recipe 'haproxy::default'
file '/etc/haproxy/haproxy.cfg' do
action :delete
end
consul_service_def 'codequest' do
id 'codequest1'
port 5050
# address '192.168.1.3'
tags ['http']
# check(
# interval: '10s',
# http: 'http://localhost:5050/health'
# )
notifies :reload, 'service[consul]'
end
http_request 'haproxy-max-connections' do
url 'http://localhost:8500/v1/kv/service/haproxy/maxconn'
action :put
message '4000'
end
http_request 'haproxy-mode' do
url 'http://localhost:8500/v1/kv/service/haproxy/mode'
action :put
message 'http'
end
http_request 'haproxy-timeouts-connect' do
url 'http://localhost:8500/v1/kv/service/haproxy/timeouts/connect'
action :put
message '10000'
end
http_request 'haproxy-timeouts-client' do
url 'http://localhost:8500/v1/kv/service/haproxy/timeouts/client'
action :put
message '300000'
end
cookbook_file '/etc/haproxy/haproxy.cfg.ctmpl' do
source 'haproxy.cfg.ctmpl'
action :create
end
consul_template_config 'haproxy' do
templates [{
source: '/etc/haproxy/haproxy.cfg.ctmpl',
destination: '/etc/haproxy/haproxy.cfg',
command: 'service haproxy restart'
}]
notifies :reload, 'service[consul-template]', :delayed
end
|
# This is a modified version of Daniel Berger's Getopt::ong class,
# licensed under Ruby's license.
require 'set'
class Thor
class Options
class Error < StandardError; end
LONG_RE = /^(--\w+[-\w+]*)$/
SHORT_RE = /^(-\w)$/
LONG_EQ_RE = /^(--\w+[-\w+]*)=(.*?)$|(-\w?)=(.*?)$/
SHORT_SQ_RE = /^-(\w\S+?)$/ # Allow either -x -v or -xv style for single char args
attr_accessor :args
def initialize(args, switches)
@args = args
switches = switches.map do |names, type|
type = :boolean if type == true
if names.is_a?(String)
if names =~ LONG_RE
names = [names, "-" + names[2].chr]
else
names = [names]
end
end
[names, type]
end
@valid = switches.map {|s| s.first}.flatten.to_set
@types = switches.inject({}) do |h, (forms,v)|
forms.each {|f| h[f] ||= v}
h
end
@syns = switches.inject({}) do |h, (forms,_)|
forms.each {|f| h[f] ||= forms}
h
end
end
def skip_non_opts
non_opts = []
non_opts << pop until looking_at_opt? || @args.empty?
non_opts
end
# Takes an array of switches. Each array consists of up to three
# elements that indicate the name and type of switch. Returns a hash
# containing each switch name, minus the '-', as a key. The value
# for each key depends on the type of switch and/or the value provided
# by the user.
#
# The long switch _must_ be provided. The short switch defaults to the
# first letter of the short switch. The default type is :boolean.
#
# Example:
#
# opts = Thor::Options.new(args,
# "--debug" => true,
# ["--verbose", "-v"] => true,
# ["--level", "-l"] => :numeric
# ).getopts
#
def getopts
hash = {}
while looking_at_opt?
case pop
when SHORT_SQ_RE
push(*$1.split("").map {|s| s = "-#{s}"})
next
when LONG_EQ_RE
push($1, $2)
next
when LONG_RE, SHORT_RE
switch = $1
end
case @types[switch]
when :required
raise Error, "no value provided for required argument '#{switch}'" if peek.nil?
raise Error, "cannot pass switch '#{peek}' as an argument" if @valid.include?(peek)
hash[switch] = pop
when :boolean
hash[switch] = true
when :optional
# For optional arguments, there may be an argument. If so, it
# cannot be another switch. If not, it is set to true.
hash[switch] = @valid.include?(peek) || peek.nil? || pop
end
end
check_required_args hash
normalize_hash hash
end
private
def peek
@args.first
end
def pop
arg = peek
@args = @args[1..-1] || []
arg
end
def push(*args)
@args = args + @args
end
def looking_at_opt?
case peek
when LONG_RE, SHORT_RE, LONG_EQ_RE
@valid.include? $1
when SHORT_SQ_RE
$1.split("").any? {|f| @valid.include? "-#{f}"}
end
end
def check_required_args(hash)
@types.select {|k,v| v == :required}.map {|k,v| @syns[k]}.uniq.each do |syns|
raise Error, "no value provided for required argument '#{syns.first}'" unless syns.any? {|s| hash[s]}
end
end
# Set synonymous switches to the same value, e.g. if -t is a synonym
# for --test, and the user passes "--test", then set "-t" to the same
# value that "--test" was set to.
#
# This allows users to refer to the long or short switch and get
# the same value
def normalize_hash(hash)
hash.map do |switch, val|
@syns[switch].map {|key| [key, val]}
end.inject([]) {|a, v| a + v}.map do |key, value|
[key.sub(/^-+/, ''), value]
end.inject({}) {|h, (k,v)| h[k] = v; h}
end
end
end
|
require "benchmark"
time = Benchmark.measure do
num = File.read("string_8.dat").delete("\n").each_char.map(&:to_i) # converts the number (loaded from a file) into an integer array
cur_first_i = 0 # index of the currently-checked first char, [0, 12] -> [1, 13] -> ...
largest_product = 0
while cur_first_i <= num.length - 12 do
test = num[cur_first_i..cur_first_i+12].inject(1) { |result, digit| result = result * digit }
largest_product = test if test > largest_product
cur_first_i += 1
end
puts "Largest consecutive 13-digit product: #{largest_product}"
end
puts "Time elapsed (in seconds): #{time}"
|
#
# Cookbook Name:: stackdriver
# Recipe:: default
# License:: MIT License
#
# Copyright 2013, Stackdriver
#
# All rights reserved
#
include_recipe "stackdriver::repo"
# Install the stack driver agent
package "stackdriver-agent" do
action :install
end
# Create or update the stackdriver-agent config
template "/etc/sysconfig/stackdriver" do
source "stackdriver.sysconfig.erb"
mode "0644"
owner "root"
group "root"
action :create
end
# Enable and start the service
service "stackdriver-agent" do
supports :status => true, :restart => true, :reload => true
action [ :enable, :start ]
end
|
# -*- coding: utf-8 -*-
# topword.rb
# ver7
# 特別なことをやっていないように見えるのだけれど実はそうでもなくて、
# ここでは、Enumerableモジュールをハッシュクラスと配列クラスにインクルードしている。
# Enumerableモジュールとはクラスの亜種。
# オブジェクトを生成できないクラス。
module Enumerable
def take_by(nth)
sort_by { |elem| yield elem } .take(nth)
end
end
words = ARGF.read.downcase.scan(/\p{Word}+/)
dictionary = words.inject(Hash.new(0)) { |dic, word| dic[word] += 1 ; dic }
p dictionary.take_by(30) { |key, val| -val }
puts "------"
p words.take_by(30) { |word| -word.length }
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'shelter index page', type: :feature do
it 'has links to edit and delete each shelter' do
visit '/shelters'
expect(page).to have_link('Edit')
expect(page).to have_link('Delete')
end
end
|
module Node
class Node < ApplicationRecord
has_one :led, dependent: :destroy
accepts_nested_attributes_for :led
has_one :button, dependent: :destroy
accepts_nested_attributes_for :button
has_one :neo_pixel_stick_eight, dependent: :destroy
accepts_nested_attributes_for :neo_pixel_stick_eight
def getCurrentColor(light_index)
sql = <<~SQL
SELECT c.led_color
FROM node_neo_pixel_stick_eight_led_index_logs i
INNER JOIN node_neo_pixel_stick_eight_led_color_logs c ON c.id = i.id
AND c.neo_pixel_stick_eight_id = i.neo_pixel_stick_eight_id
JOIN node_nodes n ON n.id = c.neo_pixel_stick_eight_id
WHERE i.led_index = #{light_index}
AND n.apiotics_instance = \"#{self.apiotics_instance}\"
ORDER BY i.id DESC
LIMIT 1
SQL
color = Node.find_by_sql(sql).first.try(:led_color)
return color
end
def Rainbow
array = {
0 => [148, 0, 211],
1 => [75, 0, 130],
2 => [0, 0, 255],
3 => [0, 255, 0],
4 => [255, 255, 0],
5 => [255, 127, 0],
6 => [255,0,0]
}
(0..50).each do |j|
x = j%7
y = j%8
self.neo_pixel_stick_eight.led_index = y
self.neo_pixel_stick_eight.led_color = ((array[x][0] * 256**2) + (array[x][1] * 256) + (array[x][2]))
self.save
sleep(0.1)
end
end
end
end |
class TunitsController < ApplicationController
before_action :set_tunit, only: [:show, :edit, :update, :destroy]
# GET /tunits
# GET /tunits.json
def index
@tunits = Tunit.all
end
# GET /tunits/1
# GET /tunits/1.json
def show
end
# GET /tunits/new
def new
@tunit = Tunit.new
end
# GET /tunits/1/edit
def edit
end
# POST /tunits
# POST /tunits.json
def create
@tunit = Tunit.new(tunit_params)
respond_to do |format|
if @tunit.save
format.html { redirect_to @tunit, notice: 'Tunit was successfully created.' }
format.json { render :show, status: :created, location: @tunit }
else
format.html { render :new }
format.json { render json: @tunit.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /tunits/1
# PATCH/PUT /tunits/1.json
def update
respond_to do |format|
if @tunit.update(tunit_params)
format.html { redirect_to @tunit, notice: 'Tunit was successfully updated.' }
format.json { render :show, status: :ok, location: @tunit }
else
format.html { render :edit }
format.json { render json: @tunit.errors, status: :unprocessable_entity }
end
end
end
# DELETE /tunits/1
# DELETE /tunits/1.json
def destroy
@tunit.destroy
respond_to do |format|
format.html { redirect_to tunits_url, notice: 'Tunit was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_tunit
@tunit = Tunit.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def tunit_params
params.require(:tunit).permit(:source, :target)
end
end
|
# frozen_string_literal: true
require_dependency "think_feel_do_dashboard/application_controller"
module ThinkFeelDoDashboard
# Allows for the creation, updating, and deletion of arms
class ArmsController < ApplicationController
rescue_from ActiveRecord::RecordNotFound, with: :arm_not_found
# GET /think_feel_do_dashboard/arms
def index
authorize! :index, Arm
@arms = Arm.includes(:groups)
end
# POST /think_feel_do_dashboard/arms
def create
authorize! :create, Arm
@arm = Arm.new(arm_params)
if @arm.save
redirect_to @arm,
notice: "Arm was successfully created."
else
render :new
end
end
# GET /think_feel_do_dashboard/arms/new
def new
authorize! :new, Arm
@arm = Arm.new
end
# GET /think_feel_do_dashboard/arms/1
def show
@arm = Arm.find(params[:id])
authorize! :show, @arm
@lesson = @arm.bit_core_tools.find_by_type("Tools::Learn")
end
# GET /think_feel_do_dashboard/arms/1/edit
def edit
@arm = Arm.find(params[:id])
authorize! :edit, @arm
end
# PATCH/PUT /think_feel_do_dashboard/arms/1
def update
@arm = Arm.find(params[:id])
authorize! :update, @arm
if @arm.update(arm_params)
redirect_to arm_path(@arm),
notice: "Arm was successfully updated.",
only: true
else
render :edit
end
end
# DELETE /think_feel_do_dashboard/arms/1
def destroy
@arm = Arm.find(params[:id])
authorize! :destroy, @arm
redirect_to arm_path(@arm),
notice: "You do not have privileges to delete an arm. "\
"Please contact the site administrator to remove this arm."
end
private
def arm_params
params
.require(:arm)
.permit(
:title, :is_social, :has_woz, :can_message_after_membership_complete
)
end
def arm_not_found
redirect_to arms_path,
alert: "The arm you were looking for no longer exists."
end
end
end
|
insert_into_file 'app/controllers/application_controller.rb', before: /^end/ do
<<-'RUBY'
rescue_from Exceptions::DefaultError do |e|
puts e.message if Rails.env.development?
flash[:error] = e.message
redirect_back(fallback_location: root_path)
end
RUBY
end |
require 'wsdl_mapper/dom/name'
require 'wsdl_mapper/naming/type_name'
require 'wsdl_mapper/naming/property_name'
require 'wsdl_mapper/naming/enumeration_value_name'
require 'wsdl_mapper/naming/namer_base'
module WsdlMapper
module Naming
# This is the default Namer implementation. It provides the de-facto standard of organizing and naming
# classes in ruby:
#
# 1. Class/Module names are CamelCase (e.g. `SomeType`)
# 2. File names are under_score (e.g. `some_type.rb`)
# 3. Each class in its own file
# 4. (De)Serializers are put within the same module as XSD Types
class DefaultNamer < NamerBase
include WsdlMapper::Dom
class InlineType < Struct.new(:name)
end
# Initializes a new {DefaultNamer} instance.
#
# @param [Array<String>] module_path the root module for the generated classes, e.g. `['MyApi', 'Types']` => `MyApi::Types::SomeClass` in `my_api/types/some_class.rb`
# @param [String] content_attribute_name the accessor name for {file:concepts/wrapping_types.md wrapping types} (complex _type with simple content and simple types with restrictions)
def initialize(module_path: [],
content_attribute_name: 'content',
soap_array_item_name: 'item')
super module_path: module_path
@content_attribute_name = content_attribute_name
@soap_array_item_name = soap_array_item_name
end
# Returns a _type name for the given _type (simple or complex).
#
# @param [WsdlMapper::Dom::ComplexType, WsdlMapper::Dom::SimpleType] type
# @return [TypeName]
def get_type_name(type)
type_name = TypeName.new get_class_name(type), get_class_module_path(type), get_class_file_name(type), get_class_file_path(type)
type_name.parent = make_parents get_class_module_path(type)
type_name
end
# @param [String] name
# @return [TypeName]
def get_support_name(name)
type_name = TypeName.new get_support_class_name(name), get_support_module_path(name), get_support_file_name(name), get_support_file_path(name)
type_name.parent = make_parents get_support_module_path(name)
type_name
end
def get_s8r_type_directory_name
get_support_name 'S8rTypeDirectory'
end
def get_global_s8r_name
get_support_name 'Serializer'
end
def get_d10r_type_directory_name
get_support_name 'D10rTypeDirectory'
end
def get_d10r_element_directory_name
get_support_name 'D10rElementDirectory'
end
def get_global_d10r_name
get_support_name 'Deserializer'
end
# @param [WsdlMapper::Dom::ComplexType, WsdlMapper::Dom::SimpleType] type
# @return [TypeName]
def get_s8r_name(type)
type_name = TypeName.new get_s8r_class_name(type), get_s8r_module_path(type), get_s8r_file_name(type), get_s8r_file_path(type)
type_name.parent = make_parents get_s8r_module_path(type)
type_name
end
# @param [WsdlMapper::Dom::ComplexType, WsdlMapper::Dom::SimpleType] type
# @return [TypeName]
def get_d10r_name(type)
type_name = TypeName.new get_d10r_class_name(type), get_d10r_module_path(type), get_d10r_file_name(type), get_d10r_file_path(type)
type_name.parent = make_parents get_d10r_module_path(type)
type_name
end
# @param [WsdlMapper::Dom::Property] property
# @return [PropertyName]
def get_property_name(property)
PropertyName.new get_accessor_name(property.name.name), get_var_name(property.name.name)
end
# @param [WsdlMapper::Dom::Attribute] attribute
# @return [PropertyName]
def get_attribute_name(attribute)
PropertyName.new get_accessor_name(attribute.name.name), get_var_name(attribute.name.name)
end
# @param [WsdlMapper::Dom::SimpleType] _type
# @param [WsdlMapper::Dom::EnumerationValue] enum_value
# @return [EnumerationValueName]
def get_enumeration_value_name(_type, enum_value)
EnumerationValueName.new get_constant_name(enum_value.value), get_key_name(enum_value.value)
end
# @param [WsdlMapper::Dom::ComplexType, WsdlMapper::Dom::SimpleType] _type
# @return [PropertyName]
def get_content_name(_type)
@content_name ||= PropertyName.new get_accessor_name(@content_attribute_name), get_var_name(@content_attribute_name)
end
# @param [WsdlMapper::Dom::Property, WsdlMapper::Dom::Element] element
# @return [InlineType]
def get_inline_type(element)
name = element.name.name + 'InlineType'
InlineType.new WsdlMapper::Dom::Name.get(element.name.ns, name)
end
# @param [WsdlMapper::Dom::ComplexType] _type
# @return [String]
def get_soap_array_item_name(_type)
@soap_array_item_name
end
protected
def get_class_name(type)
camelize type.name.name
end
def get_class_file_name(type)
underscore(type.name.name) + '.rb'
end
def get_class_module_path(type)
@module_path
end
alias_method :get_s8r_module_path, :get_class_module_path
alias_method :get_d10r_module_path, :get_class_module_path
def get_class_file_path(type)
get_file_path get_class_module_path type
end
alias_method :get_s8r_file_path, :get_class_file_path
alias_method :get_d10r_file_path, :get_class_file_path
def get_d10r_file_name(type)
underscore(type.name.name) + '_deserializer.rb'
end
def get_d10r_class_name(type)
camelize type.name.name + 'Deserializer'
end
def get_s8r_file_name(type)
underscore(type.name.name) + '_serializer.rb'
end
def get_s8r_class_name(type)
camelize type.name.name + 'Serializer'
end
def get_support_class_name(name)
camelize name
end
def get_support_module_path(_name)
@module_path
end
def get_support_file_path(name)
get_file_path get_support_module_path name
end
def get_support_file_name(name)
get_file_name name
end
end
end
end
|
class Product < ApplicationRecord
has_many :cart_products
default_scope { where(active: true) }
end
|
class UpdateCollaboratorsTable < ActiveRecord::Migration
def change
rename_table :collaborators, :listusers
end
def change
rename_table :foodlists, :listeditems
end
end
|
#BooksContrololerにApplicationControllerを継承している
#ApplicationControllerという変数をBooksControllerに渡し定義している
class BooksController < ApplicationController
#indexアクションを実行するための処理
def index
#全ての家計簿データを@booksというインスタンス変数に値を格納している
@books = Book.all
end
#showアクションを実行するための処理
def show
#コントローラーの中ではparams[:id]で:idに入った値を受け取れる
#findメソッドでparams[:id]と等しい:idを持つデータを検索している。見つかれば1件のみを取得する
#単数系の変数@bookへ検索結果を代入する
@book = Book.find(params[:id])
end
#新規画面登録表示するための処理
def new
#@bookに空っぽのインスタンスを入れている
@book = Book.new
@book.year = 2019
end
def create
#paramsにはたくさんのデータが入っているので登録に必要なデータだけ取り出す処理を行っている
book_params = params.require(:book).permit(:year, :month, :inout, :category, :amount)
#Bookモデルを新しくインスタンス化し、book_paramsをつけることで新しくデータを入れている
@book = Book.new(book_params)
#データをデータベースに保存するための処理
#ifで@book.saveが成功(true)の時はリダイレクトする
if @book.save
#books_path(一覧画面)に移りなさいというリダイレクト命令をブラウザへ返却している
#リダイレクトを利用することで登録完了したら自動的に一覧画面に戻れる
redirect_to books_path
else
#renderはビューファイルを指示するメソッド
#登録画面をもう一度表示したい時に登録画面を表示する指示をrenderメソッドを使って出す
render :new
end
end
#editアクションを実行する処理。登録したデータを更新する画面の処理
def edit
@book = Book.find(params[:id])
end
def update
@book = Book.find(params[:id])
book_params = params.require(:book).permit(:year, :month, :inout, :category, :amount)
if @book.update(book_params)
#更新した家計簿の詳細画面へリダイレクトしている
redirect_to books_path
else
#登録に失敗した場合renderメソッドによりedit.html.erbに画面に移る
render :edit
end
end
end |
#!/usr/bin/env ruby
#
# a simple database backup-script
require 'optparse'
require 'ostruct'
require 'date'
class BackupJob
VERSION = 0.1
# expects pgpass set for effektive userid
#
def initialize(argv)
op = option_parser
op.parse!(argv)
check_options
end
def run
process
end
private
def process
puts "running version: #{VERSION}"
system dump_cmd
end
def create_db_backup_filename
ds = Date.today.to_s
f_name = "#{ds}-#{@options.database}.dump"
end
def dump_cmd
cmd = if @options.no_password
"pg_dump -U #{@options.user} #{@options.database} -f #{File.join(target_dir, create_db_backup_filename)}"
else
"pg_dump -U #{@options.user} -h localhost #{@options.database} -f #{File.join(target_dir, create_db_backup_filename)}"
end
puts cmd
cmd
end
def option_parser
@options = OpenStruct.new
op = OptionParser.new do |opts|
opts.banner = "Usage: backupjob.rb [options]"
opts.on("-d DATABASE", "--database DATABASE",
"The mandatory database-name") do |d|
@options.database = d
end
opts.on("-u USER", "--user USER",
"The mandatory username") do |u|
@options.user = u
end
opts.on("-t TARGET", "--target TARGET",
"The optional target-dir") do |t|
@options.target_dir = t
end
opts.on("-n", "--no-password",
"use no password") do |n|
@options.no_password = true
end
opts.on_tail("-h", "--help", "Show this message") do
puts opts
exit
end
end
@options.op = op
op
end
def check_options
if @options.database.nil? || @options.user.nil?
puts @options.op
puts @options
exit 1
else
puts "options okay"
end
end
def target_dir
@options.target_dir || "~/"
end
end
job = BackupJob.new(ARGV)
job.run
|
require 'rails_helper'
RSpec.describe BattleService do
let(:combat) { create :combat }
let(:player1) { create :player }
let(:player2) { create :player }
describe "validation" do
it "no errors, 'cause everything's correct" do
described_class.new(combat, {"player1_id" => player1.id.to_s,
"player2_id" => player2.id.to_s})
expect( combat ).to be_valid
end
it "nobody shallt fight herself" do
described_class.new(combat, {"player1_id" => player1.id.to_s,
"player2_id" => player1.id.to_s})
expect( combat.custom_errors ).to eq(["player #{player1.player_name} must not fight herself"])
end
it "both players need to exist" do
described_class.new(combat, {"player1_id" => player1.id.to_s,
"player2_id" => player1.id.succ.to_s})
expect( combat.custom_errors ).to eq(["player2 does not exist"])
end
it "both players need to exist, both, really" do
described_class.new(combat, {"player1_id" => player1.id.succ.to_s,
"player2_id" => player1.id.to_s})
expect( combat.custom_errors ).to eq(["player1 does not exist"])
end
end
describe "to the death" do
let(:player1) { create :player }
let(:player2) { create :player }
before do
@combat = create(:combat)
# bs stands for BattleService, really, no kidding!!!
@bs = BattleService.new combat, "player1_id" => player1.id, "player2_id" => player2.id
@bs.run
end
context "recorded turns" do
it "first attacker was player1" do
expect(combat.turns.first.attacker_name).to eq(player1.player_name)
end
it "last turn's defender's health was not too good" do
expect(combat.turns.last.hitpoints_left ).to be_zero
end
end
end
describe "usage of weapons" do
let(:player1) { create :player }
let(:player2) { create :player }
let(:weapon1) { create :weapon }
let(:weapon2) { create :weapon }
before do
@combat = create(:combat)
# bs stands for BattleService, really, no kidding!!!
@bs = BattleService.new combat,
"player1_id" => player1.id,
"player2_id" => player2.id,
"weapon1_id" => weapon1.id,
"weapon2_id" => weapon2.id
@bs.run
end
context "recorded turns" do
it "first attacker was player1" do
expect(combat.turns.first.attacker_name).to eq(player1.player_name)
end
it "first attacker's weapon was weapon1" do
expect(combat.turns.first.weapon_name).to eq(weapon1.equipment_name)
end
it "last turn's defender's health was not too good" do
expect(combat.turns.last.hitpoints_left ).to be_zero
end
end
end
end
|
# frozen_string_literal: true
module Dynflow
module Stateful
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def states
raise NotImplementedError
end
def state_transitions
raise NotImplementedError
end
end
def states
self.class.states
end
def state_transitions
self.class.state_transitions
end
attr_reader :state
def state=(state)
set_state state, false
end
def set_state(state, skip_transition_check)
state = state.to_sym if state.is_a?(String) && states.map(&:to_s).include?(state)
raise "unknown state #{state}" unless states.include? state
unless self.state.nil? || skip_transition_check || state_transitions.fetch(self.state).include?(state)
raise "invalid state transition #{self.state} >> #{state} in #{self}"
end
@state = state
end
end
end
|
class AddEvents < ActiveRecord::Migration
def change
create_table :events do |t|
t.string :name
t.date :date
t.integer :num_user
t.float :reg_price
t.float :disc_price
t.integer :min_required
t.string :image_url
t.string :location
t.timestamps
end
end
end
|
class AddPromotionPdfToGlobalSetting < ActiveRecord::Migration
def self.up
add_attachment :global_settings, :promotions_pdf
end
def self.down
remove_attachment :global_settings, :promotions_pdf
end
end
|
require 'spec_helper'
describe Admin::IssueDetail do
let(:markdown_editor_functions) { double(Admin::MarkdownEditorFunctions, issue_content_status: 'Done', issue_content_link: '/admin/volumes/test') }
let(:issue) { double(Issue, id: 1, title: 'title', published?: true, is_pdf?: true, essays: [1,2,3])}
subject { Admin::IssueDetail.new(issue, markdown_editor_functions) }
context "Issue Detail Attributes" do
it "has an attached issue" do
expect(subject.issue).to eq(issue)
end
it "has a title" do
expect(subject.title).to eq("title")
end
it "#volume_title" do
expect(subject.volume_title).to eq("title")
end
it "#essays" do
# expect(subject.essays.count).to eq 3
end
it "#issue_id" do
expect(subject.issue_id).to eq 1
end
end
it "displays an edit button for the issue" do
expect(subject.edit_button).to eq("<a class=\"btn btn-primary\" href=\"/admin/volumes/1/edit\">Edit</a>")
end
context "Content Edit Routing" do
describe "#edit_content_status" do
it "returns the status for content" do
expect(subject.edit_content_status('test')).to eq("Done")
end
end
describe "#edit_content_link" do
it "returns the issue content link" do
expect(subject.edit_content_link('test')).to eq("/admin/volumes/test")
end
end
end
describe "#published" do
it "shows the published status when it is published" do
expect(subject.issue_status).to eq("<span class=\"glyphicon glyphicon-eye-open\"></span> Published")
end
it "shows the unpublished status when it is unpublished" do
issue.stub(:published?).and_return(false)
expect(subject.issue_status).to eq("<span class=\"glyphicon glyphicon-eye-close\"></span> Unpublished")
end
end
describe "#file_icon" do
it "shows the file icon when there the issue is a file type" do
expect(subject.file_icon).to eq("<span class=\"pdf glyphicon glyphicon-file\" title=\"PDF Only\"></span>")
end
it "shows nothing when the issues is not a file type" do
issue.stub(:is_pdf?).and_return(false)
expect(subject.file_icon).to eq(nil)
end
end
end
|
class OrderSerializer < ActiveModel::Serializer
attributes :id, :status, :user, :credentials, :address
def user
{
id: object.user.id,
mail: object.user.email
}
end
def credentials
{
id: object.user.credential.id,
title: object.user.credential.title,
name: object.user.credential.name,
first_name: object.user.credential.last_name,
last_name: object.user.credential.last_name,
}
end
def address
{
street: object.user.credential.adress,
city: object.user.credential.city,
zip: object.user.credential.postcode,
country: object.user.credential.country,
phone: object.user.credential.phone
}
end
end
|
#
# Author:: Edward Nunez(edward.nunez@cyberark.com)
# Author:: CyberArk Business Development (<business_development@cyberark.com>)
# Cookbook:: cyberark
# Resource:: cyberark_credential
#
# Copyright:: 2017, CyberArk Software
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'cyberark_credential'
resource_name :cyberark_credential
property :name, String, name_property: true
property :app_id, String
property :query, String
property :base_url, String, default: "http://__PLEASE_SET_BASE_URL__"
property :use_ssl, [true, false], default: true
action :read do
begin
# Retrieve credential using cyberark_credential rubygem
req = CyberArk::Credential.new(new_resource.base_url, new_resource.use_ssl)
account = req.get(new_resource.app_id, new_resource.query)
if account.nil?
raise "Could not find credential matching query: #{new_resource.query}!"
end
# Persist the secret in-memory for the rest of this Chef run.
node.run_state[new_resource.name] = account
# Tell notifications to fire.
new_resource.updated_by_last_action(true)
rescue
raise "Could not find credential matching query: #{new_resource.query}!"
end
end
|
require 'byebug'
module SlidingPiece
def moves
result = []
directions = move_dirs
directions.each do |dir|
result += grow_unblocked_moves_in_dir(dir[0], dir[1])
end
result
end
private
def move_dirs
end
def horizontal_dirs
[
[ 1, 0],
[-1, 0],
[ 0, 1],
[ 0, -1]
]
end
def diagonal_dirs
[
[-1, -1],
[ 1, -1],
[ 1, 1],
[-1, 1]
]
end
def grow_unblocked_moves_in_dir(dy, dx)
# three condtions: blocked by same color,
# into enemy color,
# blocked by @board edge.
results = [pos]
until blocked?(results.last) || has_enemy?(results.last)
results << [results.last[0] + dy, results.last[1] + dx]
end
results.pop if blocked?(results.last)
results.drop(1)
end
end
|
class AddTownToSlope < ActiveRecord::Migration
def change
add_column :slopes, :town, :string
end
end
|
require 'rails_helper'
RSpec.describe AttachmentsController, type: :controller do
let(:user) { create(:user) }
describe "DELETE#destroy" do
let(:answer) { create(:answer_with_attached_file) }
let(:question) { create(:question_with_attached_file) }
context 'An author of answer deletes attached file' do
before do
login(answer.author)
delete :destroy, params: { id: answer.files.first }, format: :js
end
it 'deletes the attached file' do
expect(answer.reload.files).to_not be_attached
end
it 'renders delete_attachment view' do
expect(response).to render_template :destroy
end
end
context "User tries to delete file attached to another user's answer" do
before do
login(user)
delete :destroy, params: { id: answer.files.first }, format: :js
end
it 'does not delete the attached file' do
expect(answer.reload.files).to be_attached
end
it 'responds with status forbidden' do
expect(response).to have_http_status :forbidden
end
end
context 'An author of the question deletes attached file' do
before do
login(question.author)
delete :destroy, params: { id: question.files.first }, format: :js
end
it 'deletes the attached file' do
expect(question.reload.files).to_not be_attached
end
it 'renders delete_attachment view' do
expect(response).to render_template :destroy
end
end
context "User tries to delete file attached to another user's question" do
before do
login(user)
delete :destroy, params: { id: question.files.first }, format: :js
end
it 'does not delete the attached file' do
expect(question.reload.files).to be_attached
end
it 'responds with status forbidden' do
expect(response).to have_http_status :forbidden
end
end
end
end
|
class Station
include InstanceCounter
attr_reader :name
attr_accessor :trains
REGEXP = /[a-z]/i
@@list = []
def initialize(name)
@name = name
@trains = []
validate!
@@list << self
register_instance
end
def self.all
@@list
end
def valid?
validate!
true
rescue
false
end
def add_train(train)
@trains << train
end
def send_train(train)
@trains.delete(train)
end
private
def validate!
raise "Только латинские буквы!" if name !~ REGEXP
end
end
|
class AdminMailer < ActionMailer::Base
default from: 'Happy Dining <no-reply@happydining.fr>'
def new_reservation reservation
@reservation = reservation
@time = reservation.time.strftime("%d/%m/%Y, at %H:%M")
@user = reservation.user
@restaurant = reservation.restaurant
@user_contribution = @reservation.user_contribution
@phone = reservation.phone
@email = 'admin@happydining.fr'
mail to: @email, subject: "Nouvelle réservation"
end
def validation_email_sent booking_name, restaurant_name
@restaurant_name = restaurant_name
@booking_name = booking_name
@email = 'admin@happydining.fr'
mail to: @email, subject: "Reservation Validation Email Sent"
end
def invoice_email invoice
params = {}
params[:start_date] = invoice.start_date
params[:end_date] = invoice.end_date
params[:restaurant_id] = invoice.restaurant_id
params[:commission_only] = invoice.commission_only
restaurant_name = Restaurant.find(invoice.restaurant_id).name
@invoice = Restaurant.calculate_information_for_invoice params
@email = 'admin@happydining.fr'
mail to: @email, subject: "Test Facture Email for #{restaurant_name}"
end
end
|
class Post < ActiveRecord::Base
belongs_to :user
has_many :comments, :dependent => :destroy
#validations
validates :title, presence: true, uniqueness: true
validates :body, length: {maximum: 150}, presence: true
end
|
require 'pry'
require 'io/wait'
#A one player blackjack game.
#Follows rules at:
#http://www.cs.bu.edu/~hwxi/academic/courses/CS320/Spring02/assignments/06/blackjack.html
#The game logic is contained in the do_action method
#A card is represented as a hash of form #
#{:rank => string, :suit => "string"}
#The game state is represented by a hash of form
#{
# status: symbol, A status to describe the game state
# Allowed status values:
# {:deal_to_player, :deal_to_dealer, :player_won, :dealer_won,
# :push, :tally}
# message: string, A message to print describing the game state
# player_hand: [cards], The player's hand
# dealer_hand: [cards], The dealer's hand
# game_cards: [cards], The cards left in the shoe
# discard: [cards] The discard pile
#}
# Each action in the game is is represented by a hash of form
#{
# string: "string" Tells a user how which key to press
# char: 'c' Character to compare to user input
#}
#-------------------------------------------------------------------------------
#Constants and shortcuts for later reference
#-------------------------------------------------------------------------------
NDECKS = 1 #number of decks in the game
SUITS = ["Hearts","Spades","Diamonds","Clubs"]
RANKS = ["2", "3", "4", "5", "6", "7", "8",
"9", "10", "Jack", "Queen", "King", "Ace"]
#A hash of allowed user actions
USER_ACTIONS = { quit: {string: "'q' to quit", char: 'q'},
hit: {string: "'h' to hit", char: 'h'},
stay: {string:"'s' to stay", char: 's'},
new_game: {string: "'n' for new game", char: 'n'},
new_hand: {string: "'e' for new hand", char: 'e'} }
STATUS_MESSAGES = { dealer_won: "Dealer Won!", player_won: "Player Won!",
deal_to_player: "Dealing to player.", push: "Push."}
# These strings are used when printing hands
PLAYERS = {player_hand: "Player ", dealer_hand: "Dealer "}
#translation from face values to points
POINTS = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 1]
RANK_TO_POINTS = Hash[ RANKS.zip(POINTS) ]
#-----------------------------------------------------------------------
#Helper methods
#-----------------------------------------------------------------------
def product_hash(hsh)
#given several keys and several possible values of each key,
#generates all possible possible hashes
#Method is similar similar to array product method.
#hsh is of form {key1: [key1_val1, key2_val2,...],
# key2: [key2_val1, key2_val2,...], etc }
#returns a hash
#[ {key1: key1_val1, key2: key2_val1, ...},
#{key1: key1_val1, key2: key2_val2, ...} ,...]
attrs = hsh.values
keys = hsh.keys
#Generate all possible value combinations
product = attrs[0].product(*attrs[1..-1])
#Combine the values in each combination with appropriate keys
product.map{ |p| Hash[keys.zip p] }
end
#Totals the points for a hand
def hand_total(hand)
#hand is an array of hashes, each hash corresponding to a card
#the hashes are of form {rank: "string", suit: 'char'}
#A flag to see if the hand contains an ace
have_ace = ! ( hand.select{|card| card[:rank] == "Ace"}.empty? )
total = 0
#Look up the point value of each card in the hand
hand.each do |card|
total += RANK_TO_POINTS[ card[:rank]]
end
#Convert from hard (ace=1) to a soft (ace=11)
#score if hand contains an ace
#and it won't cause the hand to bust
if (total <= 11 && have_ace) then total += 10 end
return total
end
#A method that checks if the specified hand is a blackjack
def blackjack?(game, hand)
# game is a hash representing the current game state
# hand == :dealer_hand or hand == :player_hand
if hand_total( game[hand] ) == 21 and game[hand].length == 2
game[:message].concat( "#{PLAYERS[hand]} blackjack. ")
return true
else return false
end
end
#a method that checks if the specify hand busted
def bust?(game, hand)
# game is a hash representing the current game state
# hand == :dealer_hand or hand == :player_hand
if hand_total( game[hand] ) > 21
game[:message] = "#{PLAYERS[hand]} bust."
return true
else return false
end
end
#-----------------------------------------------------------------------------
#IO methods
#-----------------------------------------------------------------------------
#Clears the standard input stream
def clear_stdin
$stdin.getc while $stdin.ready?
end
#Given a hash of form {rank: "string", suit: "string"}
#prints the corresponding card to the screen
def show_card(card)
puts"%-6s of %-6s" %[ card[:rank], card[:suit] ]
end
#Print all the cards in the hand
def show_hand(game, hand)
#hand == :player_hand or hand == :dealer_hand
#game is a hash representing the game state
#handle wrong symbol error
if (hand != :dealer_hand and hand != :player_hand)
raise "Illegal player"
end
#handle an empty hand
if game[hand].empty?
raise "No cards dealt yet, but printing to screen"
end
#Make a copy of the hand to display
copy = game[hand].dup
#Hide the first card in the dealer's hand from the player
#if it's her turn
if ( game[:status] == :deal_to_player && hand == :dealer_hand)
copy[0] = {rank: "******", suit: "******"}
end
#A string to print, identifying the who the hand belongs to
owner = (hand == :player_hand) ? "PLAYER" : "DEALER"
puts " " + owner + ":\n"
#Print a heading
puts "%-6s %-6s" %["Card", "Suit"]
puts "==========================="
#Iterate over the cards, printing each
copy.each {|card| show_card(card)}
puts "==========================="
total_string = nil #a string to hold the total value for the hand
#Hide the dealer's score from the player if it's her turn
if (hand == :dealer_hand and game[:status] == :deal_to_player)
total_string = "**"
else
total_string = "#{hand_total( game[hand] )}"
end
puts "Total: #{ total_string}"
puts ""
end
#Prints the game state to the screen
def print_game(game)
system("clear")
puts "Blackjack: #{game[:message]} #{ STATUS_MESSAGES[ game[:status] ]}\n\n"
#Show the hands
show_hand(game, :player_hand)
show_hand(game, :dealer_hand)
puts "Cards left: #{ game[:game_cards].length }\n\n"
end
#Takes in an array of symbols, each corresponding
#to a possible game action.
#Give user a choice of options and reads her input
#Returns the symbol corresponding to the selected action
def request_user_action(game, options)
#Handle empty request error
if options.empty?
raise "Request action called without allowed actions"
end
selected_action = []
while (selected_action.empty? )
#Loop until user selects a valid action
print_game(game)
#Give user her options
print "Enter ( "
options.each_with_index do |possible_action, index|
print USER_ACTIONS[possible_action][:string]
if (index != options.length - 1)
print ", "
else
print " ): "
end
end
#Read the first character of user's input
in_char = STDIN.getc
clear_stdin
#Select the action that corresponds to user action
#or nil if invalid input
#Choose action that corresponds to player input. statement returns empty
#array if input is invalid
selected_action = options.select { |possible_action | USER_ACTIONS[possible_action][:char] == in_char }
end
return selected_action
end
#--------------------------------------------------------------------------
#Game action methods
#-------------------------------------------------------------------------
#deals a card to the specified player
def deal_card(game, hand)
#game_cards and hand are arrays of hashes of form {rank: "string", suit: "string"}
#hand is an array containing the player's cards. It can be empty
#game_cards is an array of all the cards in the deck that haven't been dealt
#Method moves a card from game_card to hand
#Check for an empty deck and reshuffle if necessary
if (game[:game_cards].length == 0)
game[:game_cards] = game[:discard]
game[:game_cards].shuffle!
game[:discard] = []
game[:message].concat("Shuffled deck.")
end
game[hand] << game[:game_cards].pop
end
#Creates and returns a fresh game state object
def create_game()
#declare the object
game = {
:dealer_hand => [],
:player_hand => [],
:discard => [],
:game_cards => [],
:status => :deal_to_player,
:message => "",
}
#NDECKS is the number of cards in the game
#For each deck, create all possible {:rank, :suit} combos
deck = { rank: RANKS, suit: SUITS }
NDECKS.times do product_hash(deck)
game[:game_cards].concat( product_hash(deck) )
end
#Shuffle the game cards
game[:game_cards].shuffle!
return game
end
#Deal a hand
def deal_hand(game)
#game is the game state object
#Discard dealer's old hand
if !game[:dealer_hand].empty?
game[:discard] = game[:discard] | game[:dealer_hand]
game[:dealer_hand] = []
end
#Discard player's old hand
if !game[:player_hand].empty?
game[:discard] = game[:discard] | game[:player_hand]
game[:player_hand] = []
end
#Deal the cards
2.times do
deal_card(game, :player_hand)
deal_card(game, :dealer_hand)
end
end
#Plays out the dealer's hand
def play_dealer(game)
#game is the game state object
#Hit until dealer gets 17
while hand_total( game[:dealer_hand] ) < 17 do
deal_card(game,:dealer_hand)
end
end
#----------------------------------------------------------------
#The game logic is contained in the following method
#----------------------------------------------------------------
#Performs the action requested by the main script
def do_action(game, action)
case action
#User asked for a new game
when :new_game
game = create_game()
game[:message] = "Created new game"
game[:status] = :deal_to_player
deal_hand(game)
#User asked for a new hand
when :new_hand
deal_hand(game)
game[:status] = :deal_to_player
#Check for player blackjack
if blackjack?(game, :player_hand)
game[:status] = :deal_to_dealer
end
#User asked to hig
when :hit
deal_card(game, :player_hand)
#Check for a player bust
if bust?( game, :player_hand )
game[:status] = :dealer_won
end
#Check for player 21
if hand_total(game[ :player_hand]) == 21
game[:status] = :deal_to_dealer
end
#User asked to stay
when :stay
game[:status] = :deal_to_dealer
#Main script asked to play out the dealer's hand
when :play_dealer
play_dealer(game)
game[:status] = :tally
#Check for a dealer bust
if bust?( game, :dealer_hand )
game[:status] = :player_won
end
#Main script asked to count the cards and see who wom
when :tally
player_diff = 21 - hand_total( game[:player_hand] )
dealer_diff = 21 - hand_total( game[:dealer_hand] )
#Both player and dealer have blackjacks
if blackjack?(game, :player_hand ) and blackjack?(game, :dealer_hand)
game[:status]=:push
#Dealer has a blackjack
elsif blackjack?(game, :dealer_hand)
game[:status] = :dealer_won
#Player has a blackjack
elsif blackjack?(game, :player_hand)
game[:status] = :dealer_won
#Check for winner or push
else
if (player_diff > dealer_diff)
game[:status] = :dealer_won
elsif (player_diff < dealer_diff)
game[:status] = :player_won
else
game[:status] = :push
end
end
else raise "Unknown action requested"
end
return game
end
#Main game script
#Generate and shuffle the deck
game = {}
game = create_game()
deal_hand(game)
#The driver loop
while (true) do
# 1. Update the screen display
print_game(game)
#2. Set the next action to perform according to the current
# game status
# For some game statuses, this involves querying the user
possible_actions=[]
case game[:status]
when :dealer_won
possible_actions = [:new_hand, :new_game, :quit]
action = request_user_action(game, possible_actions)
when :player_won
possible_actions = [:new_hand, :new_game, :quit]
action = request_user_action(game, possible_actions)
when :push
possible_actions = [:new_hand, :new_game, :quit]
action = request_user_action(game, possible_actions)
when :deal_to_player
possible_actions = [:hit,:stay,:new_game,:quit]
action = request_user_action(game, possible_actions)
#The next action should be to play out the dealer's hand
when :deal_to_dealer
action = [:play_dealer]
#The next action should be to tally up the scores
when :tally
action = [:tally]
else
p game[:status]
raise "Main game loop: Illegal status #{game[:status]}"
end
#Quit the game if the user asked
if (action[0] == :quit) then break
#Otherwise, do the action
else
game[:message] = "" #Clear the message buffer
#Do desired action
game = do_action(game, action[0])
end
end
puts "Goodybe"
|
require '~/ruby_libs/solea/solea'
class HTMLElement
attr_reader :tagname, :attributes, :children
attr_accessor :content
def initialize tagname, content = nil, attrs = {}, &block
@tagname = tagname
@attributes = attrs
@content = [content].compact
block.call(@content) if block_given?
end
def to_s indent = 0
attributes = @attributes.map do |name, val|
name.to_s.gsub(/attr/, '') + "=\"#{val}\""
end.join(" ") if @attributes.any?
opening_tag = "<" + [@tagname, attributes].compact.join(" ") + ">"
closing_tag = "</#{@tagname}>"
if @content.any?
content = @content.map do |c|
c.is_a?(HTMLElement) ? c.to_s(indent + 2) : " " * (indent + 2) + c
end
["#{" " * indent}#{opening_tag}", content, "#{" " * indent}#{closing_tag}"].join("\n")
else
"#{" " * indent}#{opening_tag}#{closing_tag}"
end
end
end
%w(Body P Title Div Link).each do |tag_name|
Object.const_set tag_name, Class.new(HTMLElement)
Object.const_get(tag_name).module_exec do
define_method :initialize do |content = nil, attrs = {}, &block|
super tag_name.downcase, content, attrs, &block
end
end
end
class Head < HTMLElement
attr_reader :title
def initialize title = nil, stylesheet = nil
super "head"
@content = [@title = Title.new(title)]
@content << StyleLink.new(href: stylesheet) if stylesheet
end
end
class StyleLink < Link
def initialize(href:)
super nil, rel: "stylesheet", type: "text/css", href: href
end
end
class HTML < HTMLElement
attr_accessor :title, :head, :body
def initialize title = nil, stylesheet = nil, &block
super "html"
@content = [@head = Head.new(title, stylesheet), @body = Body.new(&block)]
end
end
class Page
attr_reader :doctype, :head, :body
attr_writer :doctype, :stylesheets, :scripts
def initialize title: nil, stylesheet: nil, &block
@doctype = "<!DOCTYPE html>"
@html = HTML.new title, stylesheet, &block
end
def to_s
@doctype + "\n" + @html.to_s
end
def title= str
@html.head.title.content = [str]
end
def title
@html.head.title.content[0]
end
end
|
module LiquidTags
class NeiUsageSummary < Liquid::Tag
include ActionView::Helpers::NumberHelper
include Memoizer # rubocop:disable Wego/ImplicitMemoizer
attr_reader :audit_report,
:audit_report_calculator
ENERGY_FIELDS = [
:annual_energy_usage_existing,
:annual_energy_savings,
:annual_gas_savings,
:annual_gas_usage_existing,
:annual_oil_savings,
:annual_oil_usage_existing,
:annual_electric_savings,
:annual_electric_usage_existing
]
TEMPLATE = <<-ERB.strip_heredoc
<table>
<thead>
<tr>
<th></th>
<th>Current Consumption</th>
<th>Projected Savings</th>
<th>% Savings Against Total</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Total Water (gallons)</strong></td>
<td><%= summary[:annual_water_usage_existing] %></td>
<td><%= summary[:annual_water_savings] %></td>
<td><%= percentage_reduction[:water] %></td>
</tr>
<tr>
<td><strong>Total Energy (million Btus)</strong></td>
<td><%= summary[:annual_energy_usage_existing] %></td>
<td><%= summary[:annual_energy_savings] %></td>
<td><%= percentage_reduction[:energy] %></td>
</tr>
<tr>
<td>Electricity</td>
<td><%= summary[:annual_electric_usage_existing] %></td>
<td><%= summary[:annual_electric_savings] %></td>
<td><%= percentage_reduction[:electric] %></td>
</tr>
<tr>
<td>Natural Gas</td>
<td><%= summary[:annual_gas_usage_existing] %></td>
<td><%= summary[:annual_gas_savings] %></td>
<td><%= percentage_reduction[:gas] %></td>
</tr>
<tr>
<td>Heating Oil</td>
<td><%= summary[:annual_oil_usage_existing] %></td>
<td><%= summary[:annual_oil_savings] %></td>
<td><%= percentage_reduction[:oil] %></td>
</tr>
</tbody>
</table>
ERB
def render(context)
@audit_report = context.registers[:audit_report]
@audit_report_calculator = context.registers[:audit_report_calculator]
ERB.new(TEMPLATE).result(binding)
end
private
def calculations
energy_calculations.merge(water_calculations)
end
memoize :calculations
def energy_calculations
ENERGY_FIELDS.each_with_object({}) do |field, hash|
value = audit_report_calculator.summary[field]
if value.is_a?(Numeric)
if [:annual_gas_usage_existing, :annual_gas_savings].include?(field)
value = value.to_f * Retrocalc::THERMS_TO_BTU_COEFFICIENT
elsif [:annual_electric_usage_existing,
:annual_electric_savings].include?(field)
value = value.to_f * Retrocalc::KWH_TO_BTU_COEFFICIENT
end
value /= 1_000_000.0
hash[field] = value
end
end
end
def percentage_reduction
[:energy, :water, :electric, :gas, :oil]
.each_with_object({}) do |data_type, hash|
if data_type == :water
total_value =
audit_report_calculator.summary[:annual_water_usage_existing]
savings =
audit_report_calculator.summary[:annual_water_savings]
else
total_value = calculations[:annual_energy_usage_existing]
savings = calculations["annual_#{data_type}_savings".to_sym]
end
unless total_value.is_a?(Numeric) && savings.is_a?(Numeric)
hash[data_type] = '—'
next
end
value = (savings / total_value) * 100
value = number_with_precision(value, precision: 2)
value = "#{value}%"
hash[data_type] = value
end
end
memoize :percentage_reduction
def precision_for(value)
[0, 2 - Math.log10([value, 0.01].max).floor].max
end
def summary
calculations.each_with_object({}) do |(field, value), hash|
if value.is_a?(Numeric)
value = number_with_precision(
value,
precision: precision_for(value),
delimiter: ',')
else
value = '—'
end
hash[field] = value
end
end
memoize :summary
def water_calculations
hash = {}
[:annual_water_usage_existing, :annual_water_savings].each do |field|
hash[field] = audit_report_calculator.summary[field]
end
hash
end
end
end
|
class CreatePayments < ActiveRecord::Migration
def change
create_table :payments do |t|
t.integer :order_id, null: false
t.decimal :amount, null: false, precision: 9, scale: 2
t.string :state, null: false, limit: 20
t.string :external_id, limit: 100
t.decimal :external_fee, precision: 9, scale: 2
t.timestamps null: false
t.index :order_id
t.index :external_fee, unique: true
end
end
end
|
class Importers::DishForm < Importers::BaseForm
attr_accessor(
:id,
:name,
:description,
:menus_appeared,
:times_appeared,
:first_appeared,
:last_appeared,
:lowest_price,
:highest_price,
)
validates :id, :name, presence: true
validates :id, numericality: true
end
|
class AddSlugToDiscountType < ActiveRecord::Migration[5.1]
def change
add_column :discount_types, :slug, :string
end
end
|
module ApiHelper
def auth_header(token)
ActionController::HttpAuthentication::Token.encode_credentials(token)
end
def api_user(user)
allow(user).to receive(:to_sgid).and_return('test.user')
session = Givdo::TokenAuth::Session.new(user, false)
request.env['HTTP_AUTHORIZATION'] = auth_header(session.token)
allow(Givdo::TokenAuth).to receive(:recover).with(session.token).and_return(session)
allow(BetaAccess).to receive(:granted?).and_return(true)
end
def api_logout
allow(Givdo::TokenAuth).to receive(:recover).and_return(nil)
end
def serialize(object, serializer_klass, options={})
if object.respond_to?(:each)
options = options.merge({:serializer => serializer_klass})
serializer_klass = ActiveModel::Serializer::CollectionSerializer
end
serializer = serializer_klass.new(object, options)
adapter = ActiveModelSerializers::Adapter.create(serializer, options)
adapter.as_json
end
def json
JSON.parse(response.body)
end
end
|
# license
require 'json'
module Darknet
class Results < Array
def self.parse(rows)
# rows of data like:
# RV: 94% (left_x: 925 top_y: 587 width: 34 height: 21)
# RV: 100% (left_x: 1148 top_y: 600 width: 37 height: 28)
rows = rows.split("\n").collect do |line|
line.match(/(.*):[\s]*([\d]+)%[\s]*\(left_x:[\s]*([\d]+)[\s]*top_y:[\s]*([\d]+)[\s]*width:[\s]*([\d]+)[\s]*height:[\s]*([\d]+)\)/) do |match|
Result.new(
label: match[1],
confidence: match[2].to_f / 100,
left: match[3].to_i,
top: match[4].to_i,
width: match[5].to_i,
height: match[6].to_i,
)
end
end
# and return result
self.new rows.compact
end
# just limit to labels we want
def limit_to(labels)
self.select { |row| labels.include?(row.label).any? }
end
end
class Result
attr_accessor :label
attr_accessor :confidence
attr_accessor :left
attr_accessor :top
attr_accessor :width
attr_accessor :height
def initialize(label:, confidence:, left:, top:, width:, height:)
@label = label
@confidence = confidence
@left = left
@top = top
@width = width
@height = height
end
end
end
|
class PayrollsController < ApplicationController
before_filter :payroll_owner
layout 'application-admin'
def show
@payroll = Payroll.find(params[:id])
end
def create
current_user.payrolls.find_by_draft(true).try(:destroy)
@payroll = current_user.payrolls.build(:start_date => Time.zone.parse(params[:date_range][:from]).beginning_of_day, :end_date => Time.zone.parse(params[:date_range][:to]).end_of_day)
if @payroll.populate_draft_payroll
redirect_to @payroll
else
redirect_to payrolls_path, :notice => "There are no available appointments for the selected date range. Some appointments may already be linked to approved payrolls"
end
end
def index
@draft_payroll = current_user.payrolls.find_by_draft(true)
@payrolls = current_user.payrolls.order('payroll_number DESC')
if params[:date_range].present?
@to = Time.zone.parse(params[:date_range][:to]).end_of_day
@from = Time.zone.parse(params[:date_range][:from]).beginning_of_day
@payrolls = @payrolls.where(:end_date => @from..@to).where(:draft => false)
end
end
def destroy
@payroll = current_user.payrolls.find(params[:id]).destroy
redirect_to payrolls_path, :notice => "Payroll ##{@payroll.payroll_number} has been successfully destroyed"
end
def approve
@payroll = current_user.payrolls.find(params[:id])
@payroll.approve!
redirect_to @payroll, :notice => "Payroll has been approved!"
end
def recalculate
@payroll = current_user.payrolls.find(params[:id])
if not @payroll.draft?
redirect_to @payroll, :notice => "Payroll has already been approved!"
else
@payroll.appointments.update_all(:payroll_id => nil)
# Payroll total pay is not refreshed after destroy callbacks on payroll entries,
# leading it to be erroneously set to 0 and reported unchanged when payroll is recalculated
# Using a delete here bypasses the callbacks and restores desired behavior (shouldn't lead to orphaned assignment records within the context of recalculate)
PayrollEntry.delete_all(:payroll_id => @payroll.id)
@payroll.payroll_entries_count = 0
@payroll.populate_draft_payroll
@payroll.out_of_date = false
redirect_to @payroll, :notice => "Payroll has been recalculated"
end
end
def report
@payroll = current_user.payrolls.find(params[:id])
@payroll.payroll_entries.each do |entry|
entry.calculate_totals_for_report
end
respond_to do |format|
format.pdf do
render :pdf => "payroll_report_#{@payroll.payroll_number}",
:layout => 'layouts/application-pdf.pdf',
:margin => {
:top => 20,
:bottom => 25,
:left => 20,
:right => 20
}
end
end
end
def payroll_owner
if current_user.blank? || (params[:id].present? && current_user != Payroll.find_by_id(params[:id]).user)
redirect_to user_root_path, notice: "Please sign into the account which owns this payroll record to edit it"
end
end
end
|
class AddAgencyIdToAgencyArtist < ActiveRecord::Migration[6.0]
def change
add_column :agency_artists, :agency_id, :integer
end
end
|
# Asks user to type required information in
# Defining a method because its prior to caesar_cipher
def main
puts "Please, enter a string which you want to cipher!"
user_string = gets.chomp
puts "Please, enter positive number"
user_number = gets.chomp.to_i
caesar_cipher(user_string, user_number)
end
# Caesar cipher iterates through each symbol passing it to wrapper
def caesar_cipher(text, step)
text.length.times do |number|
current_symbol = text[number]
text[number] = caesar_wrapper(current_symbol, step)
end
puts text
end
# Checks if we have to wrap from 'Z' to 'A' / 'z' to 'a'
# "A" ASCII value is 65 / "a" ASCII value is 97
# "Z" ASCII value is 90 / "z" ASCII value is 122
def caesar_wrapper(symbol, step)
upcase_range = (65..90)
downcase_range = (97..122)
if (upcase_range === symbol.ord)
if (symbol.ord + step > upcase_range.end)
new_ascii_value = upcase_range.begin + (symbol.ord + step - 1) % upcase_range.end
return new_ascii_value.chr
else
return (symbol.ord + step).chr
end
end
if (downcase_range === symbol.ord)
if (symbol.ord + step > downcase_range.end)
new_ascii_value = downcase_range.begin + (symbol.ord + step - 1) % downcase_range.end
return new_ascii_value.chr
else
return (symbol.ord + step).chr
end
end
return symbol
end
main |
require 'CSV'
require 'bigdecimal'
require_relative 'sales_engine'
class SalesAnalyst
attr_reader :engine
def initialize(engine)
@engine = engine
end
def average(data)
data.sum / data.size.to_f
end
def standard_deviation(sample_size)
Math.sqrt(sample_size.sum do |sample|
(sample - average(sample_size)) ** 2 / (sample_size.size - 1)
end).round(2)
end
def items_per_merchant
all_items = @engine.items
all_merchants = @engine.merchants
all_merchants.all.map do |merchant|
all_items.find_all_by_merchant_id(merchant.id).count
end
end
def average_items_per_merchant
average(items_per_merchant).round(2)
end
def average_items_per_merchant_standard_deviation
standard_deviation(items_per_merchant)
end
def high_item_count
standard_deviation(items_per_merchant) + average_items_per_merchant
end
def merchants_with_high_item_count
all_items = @engine.items
all_merchants = @engine.merchants.all
all_merchants.map do |merchant|
if all_items.find_all_by_merchant_id(merchant.id).count >= high_item_count
merchant
end
end.compact
end
def average_item_price_for_merchant(merchant_id)
all_items = @engine.items
unit_prices = all_items.find_all_by_merchant_id(merchant_id).map do |item|
item.unit_price
end
average(unit_prices).round(2)
end
def average_average_price_per_merchant
all_merchants = @engine.merchants.all
all_merchant_averages = all_merchants.map do |merchant|
average_item_price_for_merchant(merchant.id)
end
average(all_merchant_averages).round(2)
end
def golden_items
all_items_unit_prices = @engine.items.all.map { |item| item.unit_price }
stan_div = standard_deviation(all_items_unit_prices) * 2
avg = average(all_items_unit_prices)
@engine.items.all.find_all do |item|
item.unit_price >= (stan_div + avg)
end
end
def invoices_per_merchant
all_invoices = @engine.invoices
all_merchants = @engine.merchants
all_merchants.all.map do |merchant|
all_invoices.find_all_by_merchant_id(merchant.id).count
end
end
def average_invoices_per_merchant
average(invoices_per_merchant).round(2)
end
def average_invoices_per_merchant_standard_deviation
standard_deviation(invoices_per_merchant).round(2)
end
def high_invoice_count
(standard_deviation(invoices_per_merchant) * 2) + average_invoices_per_merchant
end
def top_merchants_by_invoice_count
all_invoices = @engine.invoices
all_merchants = @engine.merchants.all
all_merchants.map do |merchant|
if all_invoices.find_all_by_merchant_id(merchant.id).count >= high_invoice_count
merchant
end
end.compact
end
def low_invoice_count
lv = average_invoices_per_merchant - (standard_deviation(invoices_per_merchant) * 2)
lv.round(2)
end
def bottom_merchants_by_invoice_count
all_invoices = @engine.invoices
all_merchants = @engine.merchants.all
all_merchants.map do |merchant|
if all_invoices.find_all_by_merchant_id(merchant.id).count <= low_invoice_count
merchant
end
end.compact
end
def assign_invoice_day
all_invoices = @engine.invoices.all
vars = all_invoices.map do |invoice|
Time.parse(invoice.created_at.to_s)
end
day = vars.map do |var|
var.strftime('%A')
end
end
def tally_the_days
assign_invoice_day.tally
end
def mean_number_of_invoices_per_day
total = tally_the_days.values.sum
total.fdiv(7).round(2)
end
def standard_deviation_of_days
array = []
tally_the_days.values.each do |value|
array << value
end
standard_deviation(array)
end
def top_days_by_invoice_count
result = (standard_deviation_of_days) + average(tally_the_days.values) # (mean_number_of_invoices_per_day)
total =tally_the_days.find_all do |day, amount|
day if amount > result
end
total.flatten!.pop
total
end
def invoice_status(status)
all_invoices = @engine.invoices.all
all_stats = []
all_invoices.each do |invoice|
if invoice.status.to_sym == status
all_stats << invoice.status.to_sym
end
end
amount_of_stat = all_stats.count
(amount_of_stat.fdiv(all_invoices.count) * 100).round(2)
end
def invoice_paid_in_full?(invoice_id)
successful_transactions = []
all_transactions = @engine.transactions.all
all_transactions.find_all do |transaction|
if transaction.result == :success
successful_transactions << transaction.invoice_id
end
end
successful_transactions.include?(invoice_id)
end
def invoice_total(invoice_id)
ii = @engine.invoice_items.all
matches = []
total_amounts = []
ii.each do |invoiceitem|
if invoiceitem.invoice_id == invoice_id
matches << invoiceitem
end
matches.each do |match|
total_amounts << (match.unit_price * match.quantity)
end
end
total_amounts.uniq.sum
end
def get_date(date)
if date.class == String
date = Date.parse(date)
elsif date.class == Time
date = date.to_date
end
end
def total_revenue_by_date(date)
date1 = get_date(date)
ii = @engine.invoice_items.all
matches = []
total_amounts = []
bigd_amounts = []
final= []
ii.each do |invoiceitem|
if invoiceitem.created_at.to_s.include?(date1.to_s)
matches << invoiceitem
end
end
matches.each do |match|
total_amounts << match
end
total_amounts.each do |amount|
bigd_amounts << (amount.unit_price * amount.quantity)
end
bigd_amounts.each do |amount|
final << amount
end
final.sum.round(2)
end
def revenue_by_invoice_id(invoice_id)
array = []
rii = {}
rev_acc = @engine.invoice_items.find_all_by_invoice_id(invoice_id)
result = rev_acc.each do |iii|
array << (iii.unit_price * iii.quantity)
end
value = array.sum.to_f
rii[invoice_id] = value
end
def invoice_ids_by_merchant(merchant_id)
array = []
invoices = @engine.invoices.all
var = @engine.invoices.find_all_by_merchant_id(merchant_id)
var.each do |invoice|
array << invoice.id
end
array
end
def revenue_by_merchant(merchant_id)
all_invoice_ids = invoice_ids_by_merchant(merchant_id)
revenue = all_invoice_ids.map do |invoice_id|
revenue_by_invoice_id(invoice_id)
end
revenue.sum
end
def all_earners(merchant_id)
all_earners = {}
merchants = @engine.merchants.all
merchants.find do |merchant|
if merchant.id == merchant_id
return merchant
all_earners[merchant] = revenue_by_merchant(merchant_id)
end
def top_revenue_earners(x)
end
end
|
require "spec_helper"
describe "#double" do
let(:fake_object) { double("fake_object", fake_function: "fake function") }
it "is mock object with the RSpec::Mocks::Double class " do
expect(fake_object.class).to eq(RSpec::Mocks::Double)
end
it "can have stubbed functions" do
expect(fake_object.fake_function).to eq("fake function")
end
it "acts a lot like a struct, but require less code" do
struct = Struct.new(:fake_function).new("fake function")
expect(fake_object.fake_function).to eq(struct.fake_function)
end
end
describe "#allow" do
let(:object) do
klass = Class.new do
def no_arguments()
raise "not implemented"
end
def multiple_arguments(arg1, arg2)
raise "not implemented"
end
end
klass.new
end
it "can stub a function with no arguments" do
allow(object).to receive(:no_arguments) { "no arguments" }
expect(object.no_arguments).to eq("no arguments")
end
it "can stub a function with multiple arguments" do
allow(object).to receive(:multiple_arguments).with("fake arg 1", "fake arg 2") do
"multiple arguments"
end
expect(object.multiple_arguments("fake arg 1", "fake arg 2"))
.to eq("multiple arguments")
end
end |
# encoding: utf-8
$LOAD_PATH.unshift File.expand_path("../lib", __dir__)
require "rbmisc"
require "minitest/autorun"
require "minitest/spec"
# require 'simplecov'
# SimpleCov.start
require 'yaml'
require 'fileutils'
# Helper methods and utilities for testing.
# Helper method to allow temporary redirection of $stdout.
#
# @example
# silence do
# # your noisey code here
# end
#
# @param A code block to execute.
# @return Original $stdout value.
def silence(&block)
original_stdout = $stdout
original_stderr = $stderr
$stdout = $stderr = File.new('/dev/null', 'w')
yield block
ensure
$stdout = original_stdout
$stderr = original_stderr
end
|
class GameSession < ActiveRecord::Base
has_many :games
has_many :decks
has_many :cards, through: :decks
belongs_to :user
after_create :create_decks
NUMBER_OF_DECKS = 6
def number_of_decks
NUMBER_OF_DECKS
end
def create_decks
NUMBER_OF_DECKS.times do
Deck.create!(game_session_id: id)
end
end
def play_card
card = decks.map { |deck| deck.deck_cards.where(played: false) }.flatten.sample
card.played = true
card.save!
card.card
end
def played_cards
cards.references(:deck_cards).where(deck_cards: {played: true}).pluck(:value)
end
def penetration_level
played_cards = 0
decks.each do |deck|
played_cards += deck.played_cards.count
end
1 - (played_cards / (decks.count * Card.count.to_f))
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.