text stringlengths 10 2.61M |
|---|
class ProductsController < ApplicationController
before_filter :login_required, :except => :detail
before_filter :activate_tab, :set_current_item
before_filter :sell_navigation, :except => :detail
before_filter :shop_navigation, :only => :detail
before_filter :find_seller, :except => [:detail, :show]
before_filter :find_seller_product, :except => [:index, :new, :create, :detail, :show]
before_filter :show_menu, :except => [:detail]
# GET /products
# GET /products.xml
def index
store_location
@filter = params[:filter] || "title"
filter = (@filter != "id")? @filter.to_s + " ASC": @filter.to_s + " DESC"
@products = @seller.products.find(:all, :order => filter)
@products = @products.select {|p| p.sellable?}
respond_to do |format|
format.html # index.rhtml
format.xml { render :xml => @products.to_xml }
end
end
# GET /products/1
# GET /products/1.xml
def show
# special case for show - we'll be a little nicer and redirect
begin
@product = current_member.seller.products.find(params[:id])
rescue
end
respond_to do |format|
if @product.nil?
format.html {redirect_to detail_product_path(params[:id])}
else
format.html # show.rhtml
format.xml { render :xml => @product.to_xml }
end
end
end
# POST /products/new
def new
@current_list = "Not Available"
# for new stuff, parse out ASIN, then call load_from_amazon
# this will stuff it in the model
unless params[:product].nil? || params[:product][:isbn].blank?
isbn = params[:product][:isbn]
asin = isbn.gsub(/\W/,'')
@product = Product.load_from_amazon(asin, true)
if @product.title.blank? && (isbn.count("0-9") < 9)
@no_isbn = true
@product = Product.new(:title => isbn)
elsif @product.title.blank?
@product = Product.new(:isbn => isbn)
end
else
@product = Product.new
end
@media_mail = (@product.shipping_weight.blank?) ? nil : MediaMail.get_rate(@product.shipping_weight)
@statuses = [Status[:Available], Status['Currently Unavailable']]
end
# GET /products/1;edit
def edit
@statuses = Status.find(:all)
@media_mail = (@product.shipping_weight.blank?) ? nil : MediaMail.get_rate(@product.shipping_weight)
end
# POST /products
# POST /products.xml
def create
@product = Product.new(params[:product])
@product.seller_id = @seller.id
@product.published = true
@product.publish_at = Time.now.utc
@product.status = Status['Available'] if params[:product][:status_id].blank?
@product.offer_price = purefy_offer_price(params[:offer_price])
respond_to do |format|
if @product.save
flash[:notice] = 'Product was successfully created.'
path = (params[:go_to_images] == "true") ? new_product_product_image_path(@product) : product_path(@product)
format.html { redirect_to path }
format.xml do
headers["Location"] = product_url(@product)
render :nothing => true, :status => "201 Created"
end
else
@statuses = [Status[:Available], Status['Currently Unavailable']]
flash[:notice] = 'Oops! You made a slight mistake. Please check your form and try again.'
format.html { render :action => "new" }
format.xml { render :xml => @product.errors.to_xml }
end
end
end
# PUT /products/1
# PUT /products/1.xml
def update
@product = @seller.products.find(params[:id])
@product.offer_price = purefy_offer_price(params[:offer_price])
respond_to do |format|
if @product.update_attributes(params[:product])
flash[:notice] = 'Your product was sucessfully updated!'
format.html {
if params[:go_to_images] == "true"
redirect_to new_product_product_image_path(@product)
else
redirect_to @product
end
}
format.xml { render :nothing => true }
else
@statuses = Status.find(:all)
format.html { render :action => "edit" }
format.xml { render :xml => @product.errors.to_xml }
end
end
end
# DELETE /products/1
# DELETE /products/1.xml
def destroy
@product = @seller.products.find(params[:id])
@product.destroy
respond_to do |format|
format.html { redirect_to products_url }
format.js
format.xml { render :nothing => true }
end
end
# GET /products/1;details
# GET /products/1;details.xml
def detail
begin
@product = Product.available.find(params[:id])
rescue
@product = (@cart.blank?) ? nil : @cart.find_product(params[:id])
end
@active_tab = "shop_tab"
@current_item = "find_products"
respond_to do |format|
unless @product.nil?
format.html # detail.rhtml
format.xml { render :xml => @product.to_xml }
else
flash[:notice] = "That product is no longer available."
format.html {redirect_back_or_default(categories_path)}
format.xml { render :nothing => true }
end
end
end
def toggle_status
status = (@product.status == Status[:Available]) ? Status["Currently Unavailable"] : Status[:Available]
respond_to do |format|
if @product.update_attribute(:status, status)
flash[:notice] = "Your product is now #{status.name}"
format.js
else
flash[:notice] = "There was a problem updating this product's status."
format.js
end
end
end
def sort_product_images
unless @product.nil?
@product.product_images.each do |image|
image.position = params['product_images'].index(image.id.to_s) + 1
image.save
end
end
render :nothing => true
end
def toggle_default_image
@product = @seller.products.find(params[:id])
use_amazon = (@product.has_product_images? && (@product.product_images.empty? || !@product.use_amazon_image?)) ? true : false
respond_to do |format|
if @product.update_attribute(:use_amazon_image, use_amazon)
flash[:notice] = "Your successfully updated your default image for this product."
format.js
else
flash[:notice] = "There was a problem the default image for this product."
format.js
end
end
end
private
def activate_tab
@active_tab = "sell_tab"
end
def set_current_item
@current_item = "my_products"
end
def find_seller_product
begin
@product = current_member.seller.products.find(params[:id])
rescue
flash[:notice] = 'The product you attempted to access is not one of yours.'
redirect_to products_path
end
end
def purefy_offer_price(offer)
unless offer.blank?
offer_price = offer.strip
last_char = offer_price.reverse[0]
offer_price = offer_price.chop if last_char == 46
offer = offer_price.to_money
end
offer
end
end |
module LogStasher
class Railtie < ::Rails::Railtie
config.logstasher = ::ActiveSupport::OrderedOptions.new
config.logstasher.enabled = false
config.logstasher.include_parameters = true
config.logstasher.serialize_parameters = true
config.logstasher.silence_standard_logging = false
config.logstasher.silence_creation_message = true
config.logstasher.logger = nil
config.logstasher.log_level = ::Logger::INFO
config.logstasher.metadata = {}
config.before_initialize do
options = config.logstasher
::LogStasher.enabled = options.enabled
::LogStasher.include_parameters = options.include_parameters
::LogStasher.serialize_parameters = options.serialize_parameters
::LogStasher.silence_standard_logging = options.silence_standard_logging
::LogStasher.logger = options.logger || default_logger
::LogStasher.logger.level = options.log_level
::LogStasher.metadata = options.metadata
end
initializer 'logstasher.load' do
if ::LogStasher.enabled?
::ActiveSupport.on_load(:action_controller) do
require 'logstasher/log_subscriber'
require 'logstasher/context_wrapper'
include ::LogStasher::ContextWrapper
end
end
end
config.after_initialize do
if ::LogStasher.enabled? && ::LogStasher.silence_standard_logging?
require 'logstasher/silent_logger'
::Rails::Rack::Logger.send(:include, ::LogStasher::SilentLogger)
::ActiveSupport::LogSubscriber.log_subscribers.each do |subscriber|
if subscriber.is_a?(::ActiveSupport::LogSubscriber)
subscriber.class.send(:include, ::LogStasher::SilentLogger)
end
end
end
end
def default_logger
unless @default_logger
path = ::Rails.root.join('log', "logstash_#{::Rails.env}.log")
if config.logstasher.silence_creation_message
::FileUtils.touch(path) # prevent autocreate messages in log
end
@default_logger = ::Logger.new(path)
end
@default_logger
end
end
end
|
=begin
create_table "activities", :force => true do |t|
t.string "name"
t.text "description"
t.datetime "starts_at"
t.datetime "ends_at"
t.integer "venue_id"
t.integer "category_id"
t.integer "organizer_id"
t.datetime "created_at"
t.datetime "updated_at"
end
=end
class Activity < ActiveRecord::Base
attr_accessible :name, :description, :starts_at, :ends_at, :venue_id, :category_id, :organizer_id
belongs_to :organizer, :class_name => 'User'
belongs_to :venue
belongs_to :category
validates :organizer_id, :presence => true
validates :venue_id, :presence => true
validates :category_id, :presence => true
def self.contains_keyword(keyword)
if keyword.empty? || keyword.blank?
scoped
else
where("activities.name like ? OR activities.description like ?", "%#{keyword}%", "%#{keyword}%")
end
end
def self.in_category(category_id)
if category_id.empty? || category_id.blank?
scoped
else
joins(:category).where("categories.id = ?", category_id)
end
end
scope :near_location, lambda { |location| joins(:venues) & Venue.near(location, 50, :order => :distance) unless location.blank? }
scope :by_keyword, lambda { |keyword| where(:name => keyword) unless keyword.blank? }
=begin
scope :near_location, lambda {
joins(:venues) & Venue.near(lambda, 50, :order => :distance)
}
def self.near_location(location)
if location.empty? || location.blank?
scoped
else
Venue.near(location, 50, :order => :distance)
end
end
=end
end
|
require 'spec_helper'
describe "UserPages" do
subject{page}
describe "signup page" do
before {visit signup_path}
it {should have_content("国科大跳蚤市场")}
it {should have_content("主页")}
it {should have_content("注册")}
it {should have_content("登录")}
it {should have_title('注册')}
it {should have_content('名字')}
it {should have_content('学号')}
it {should have_content('学院')}
it {should have_content('密码')}
it {should have_content('密码确认')}
let(:submit){"注册"}
describe "with invalid information"do
it "should not create a user" do
expect{click_button submit}.not_to change(User,:count)
end
describe "after submission"do
before{click_button submit}
it{should have_title("注册")}
it{should have_content("error")}
end
end
describe "with valid information"do
before{
fill_in "user_name", with:"someone"
fill_in "user_number", with:"123145"
fill_in "user_academy", with:"computer"
fill_in "user_password", with:"12345678"
fill_in "user_password_confirmation",with:"12345678"
}
it "should create a user"do
expect{click_button submit}.to change(User,:count).by(1)
end
describe "after saving the user"do
before{click_button submit}
let(:user){User.find_by(name:'ssss')}
it{should have_link("退出")}
it{should have_title("someone")}
it{should have_selector('div.alert.alert-success',text:"欢迎访问国科大二手交易市场")}
end
end
end
describe "profile page"do
let(:user){FactoryGirl.create(:user)}
let!(:m1){FactoryGirl.create(:commodity,
user:user,
name:"book",
price:"123",
description:'good',
date:'2016.1.21', phonenumber:'13994826324'
)}
let!(:m2){FactoryGirl.create(:commodity,
user:user,
name:"computer",
price:'234',
description:'just so so',
date:'2016.1.20',
phonenumber:'18710324544'
)}
end
end
|
require_relative 'transaction'
class BankAccount
DEFAULT_BALANCE = 0
attr_reader :balance, :transactions
def initialize
@balance = DEFAULT_BALANCE
@transactions = []
end
def deposit(amount)
add_to_balance(amount)
submit_transaction(amount, 'deposit')
end
def withdraw(amount)
remove_from_balance(amount)
submit_transaction(amount, 'withdraw')
end
private
def negative?(amount)
amount < 0
end
def insufficient_funds?(amount)
amount > @balance
end
def submit_transaction(amount, type)
@transactions << Transaction.new(amount, @balance, type)
end
def add_to_balance(amount)
raise 'Enter an amount more than 0' if negative?(amount)
@balance += amount
end
def remove_from_balance(amount)
raise 'Insufficient funds' if insufficient_funds?(amount)
@balance -= amount
end
end
|
require 'test_helper'
class NebulosasControllerTest < ActionController::TestCase
setup do
@nebulosa = nebulosas(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:nebulosas)
end
test "should get new" do
get :new
assert_response :success
end
test "should create nebulosa" do
assert_difference('Nebulosa.count') do
post :create, nebulosa: { Nebulosa: @nebulosa.Nebulosa, TipoNebulosa: @nebulosa.TipoNebulosa }
end
assert_redirected_to nebulosa_path(assigns(:nebulosa))
end
test "should show nebulosa" do
get :show, id: @nebulosa
assert_response :success
end
test "should get edit" do
get :edit, id: @nebulosa
assert_response :success
end
test "should update nebulosa" do
patch :update, id: @nebulosa, nebulosa: { Nebulosa: @nebulosa.Nebulosa, TipoNebulosa: @nebulosa.TipoNebulosa }
assert_redirected_to nebulosa_path(assigns(:nebulosa))
end
test "should destroy nebulosa" do
assert_difference('Nebulosa.count', -1) do
delete :destroy, id: @nebulosa
end
assert_redirected_to nebulosas_path
end
end
|
class Api::V1::BooksController < ApplicationController
skip_before_action :verify_authenticity_token
def index
@books = Book.all
render json: @books
end
def show
@book = Book.find_by(id:book_params[:id])
render json: @book
end
def create
@book = Book.new(book_params)
@writer =Writer.new(writer_params)
if @book.valid?
@book.save
render json: @book
end
end
private
def book_params
params.require(:book).permit(:title, :poet, :image, :description, :publisher, :review)
end
def writer_params
params.permit(:name)
end
end
# {book: @book, writer: @book.writer}
|
class AddColumsDateBeginAndDateFinnihToPayslips < ActiveRecord::Migration
def change
add_column :payslips, :date_begin, :date
add_column :payslips, :date_end, :date
end
end
|
require 'rails_helper'
RSpec.describe User, type: :model do
let(:user){create(:user)}
let(:reload_user){User.find(user.id)}
let(:user_data){
user_data = {
data: {
name: "Obama",
gender: "male",
age: 55,
hobit: %w(guitar cat code coffee bear),
balance: 11000000,
status: "mad",
address: {
country: "Taiwan",
city: "Taipei",
region: "XinYi",
Street: "DaAnRoad"
},
got_job: true
},
family: {
father: 'papa',
mother: 'mama',
status: 'rich'
}
}
}
let(:user_load_data){
user.setting(value: user_data)
user.save
}
context 'model' do
it 'should create a user.' do
expect(user).to be_present
expect(user).to be_is_a User
end
it { should have_many(:settings) }
end
context 'setting save and load' do
it 'should save by hash and load success.' do
user.setting(value: user_data)
expect(user.data.name).to eq('Obama')
expect(user.family.father).to eq('papa')
user.save
expect(reload_user.data.name).to eq('Obama')
expect(reload_user.family.father).to eq('papa')
expect(reload_user.data.got_job?).to eq(true)
expect(reload_user.data.hobit).to eq(%w(guitar cat code coffee bear))
end
it 'should assign a hash to update.' do
user_load_data
expect(user.data.name).to eq('Obama')
expect(user.family.father).to eq('papa')
user.setting(value: {
data: {
name: 'Olivia',
gender: 'female',
hobit: %w(coffee work)
},
family: {
mother: 'mother'
}
})
user.save
expect(reload_user.data.name).to eq('Olivia')
expect(reload_user.data.gender).to eq('female')
expect(reload_user.data.hobit).to eq(%w(coffee work))
expect(reload_user.family.mother).to eq('mother')
expect(reload_user.family.father).to eq('papa')
end
it 'should update success.' do
user_load_data
expect(user.data.name).to eq('Obama')
expect(user.family.father).to eq('papa')
user.data.name = 'Olivia'
user.data.gender = 'female'
user.family.mother = 'mother'
user.save
expect(reload_user.data.name).to eq('Olivia')
expect(reload_user.data.gender).to eq('female')
expect(reload_user.family.mother).to eq('mother')
expect(reload_user.family.father).to eq('papa')
end
end
end
|
require 'sinatra'
require 'yaml'
module Rubysite
module Configuration
def self.set_configuration(parsed_args={}, defaults={}, conf_setter=Sinatra::Base)
raise "conf_setter must respond to set(key, val)" unless conf_setter.respond_to?(:set)
conf = Rubysite::Configuration.get_configuration(defaults, parsed_args).each { |key, val|
conf_setter.set(key, val)
}
if conf[:write_config_file] &&
conf.select { |key, _| ![:write_config_file, :config_file, :conf_output_file].include?(key) }.length > 0
Rubysite::Configuration.write_conf(conf[:conf_output_file], conf)
end
end
def self.get_defaults(root_path)
app_name = File.basename($0, ".*").split('_').map(&:capitalize).join
app_base_route = File.dirname(File.absolute_path($0))
{
port: '8080',
root: root_path,
public_folder: File.join(root_path, 'public'),
views: File.join(root_path, 'views'),
app_name: app_name,
readme: Dir.glob(File.absolute_path("#{$0}/../**/*readme*")).first,
logging: true,
log_ext: '.log',
log_commands: true,
logs_to_keep: 0,
log_dir: "#{app_base_route}/#{app_name}_logs",
conf_output_file: "#{app_base_route}/#{app_name}_config.yaml",
}
end
def self.get_configuration(defaults, parsed_args)
defaults.merge(parsed_args)
.merge(
if File.exists?(parsed_args[:config_file] || '')
YAML.load_file(parsed_args[:config_file]).map { |k, v| {k.to_s.to_sym => v} }.reduce(&:merge).select { |_, v| !v.nil? }
else
{}
end
)
end
def self.write_conf(conf_file_path, conf)
File.open(conf_file_path, 'w+') { |f|
f.write(conf.select { |key, _| ![:write_config_file, :write_config_file, :config_file].include?(key) }.to_yaml)
}
end
end
end
|
module BaseballReference
module Games
extend self
extend Download
CSS = "#team_schedule td"
SIZE = 19
def stats(season, team)
url = "http://www.baseball-reference.com/teams/#{team.abbr}/#{season.year}-schedule-scores.shtml"
doc = download_file(url)
data = table_data(doc, CSS)
slices = data.each_slice(SIZE)
game_data = slices.map do |slice|
date = slice[0].date
next unless date
away_team, home_team = away_home_teams(slice)
num = slice[0].num
{ date: date, away_team: away_team, home_team: home_team, num: num }
end
return game_data.compact
end
def away_home_teams(slice)
team = Team.find_by_abbr(slice[2].text)
opp = Team.find_by_abbr(slice[4].text)
return slice[3].text.empty? ? [opp, team] : [team, opp]
end
end
end
|
require_relative 'spec_helper'
require_relative '../lib/Cd'
describe Cd do
before(:context) do
#initialize item
@cd = Cd.new("Parade of the Athletes", 14.99)
end
#check initialization
#check that it is an extended from Item
#check that it is an instance of Cd
#check getters and setters
end
|
module QueryTypes
ItemQueryType = GraphQL::ObjectType.define do
name 'ItemQueryType'
description 'The item query type'
field :items, types[Types::ItemType], 'returns all items' do
resolve ->(_obj, _args, _ctx) { Item.all }
end
end
end |
class AddDisplayNameToDocument < ActiveRecord::Migration
def change
add_column :documents, :user_display_name, :string
end
end
|
class TirehistoriesController < ApplicationController
def new
@truck = Truck.find(params[:truck_id])
@index = params[:index]
@tirehistory = @truck.tirehistories.build(index: @index)
end
def create
@tirehistory = Tirehistory.new(tirehistory_params)
if (@tirehistory.save)
# 保存成功o
redirect_to tirerotation_truck_url(@tirehistory.truck)
else
# 保存失敗
end
end
def edit
@tirehistory = Tirehistory.find(params[:id])
@truck = @tirehistory.truck
@index = @tirehistory.index
end
def update
@tirehistory = Tirehistory.new(tirehistory_params)
if (@tirehistory.save)
flash[:success] = "Tire History updated"
redirect_to tirerotation_truck_url(@tirehistory.truck)
else
end
end
private
def tirehistory_params
params.require(:tirehistory).permit(:truck_id, :index, :serialno, :purchasedate)
end
end
|
class Userphoto < ApplicationRecord
self.table_name = 'userphoto'
has_many :usercomments
end
|
module Linkbucks
class AuthenticationFailed < StandardError; end
class ValidationFailed < StandardError; end
class OperationFailed < StandardError; end
end |
class AddDisplayNameToHtmlSitemaps < ActiveRecord::Migration[5.1]
def change
add_column :html_sitemaps, :display_name, :string
end
end
|
require 'byebug'
module Slideable
def diagonals(pos)
all_diags = self.top_right_to_left(pos) + top_left_to_right(pos) + bottom_right_to_left(pos) + bottom_left_to_right(pos)
all_diags
end
def top_right_to_left(pos) #
x, y = pos
top_right_to_left = []
i = 0
until y - i == 0 || x - i == 0
i += 1
top_right_to_left << [x-i,y-i]
end
top_right_to_left
end
def bottom_left_to_right(pos)#
x, y = pos
bottom_left_to_right = []
n = 0
until y + n == 7 || x + n == 7
n += 1
bottom_left_to_right << [y+n,x+n]
end
bottom_left_to_right
end
def top_left_to_right(pos) # top_left_right
x, y = pos
top_left_right = []
j = 0
until y - j == 0 || x + j == 7
j += 1
top_left_right << [y-j,x+j]
end
top_left_right
end
def bottom_right_to_left(pos) #bottom_right_to_left
x, y = pos
bottom_right_to_left = []
k = 0
# debugger
until y - k == 0 || x + k == 7
k += 1
bottom_right_to_left << [x+k,y-k]
end
bottom_right_to_left
end
def straights(pos)
x, y = pos
all_straights = []
(y-1).downto(0).each do |i|
all_straights << [x,i]
end
(y+1).upto(7).each do |j|
all_straights << [x,j]
end
(x-1).downto(0).each do |k|
all_straights << [k,y]
end
(x+1).upto(7).each do |n|
all_straights << [n,y]
end
all_straights
end
end
|
class AddPlanIdToEvents < ActiveRecord::Migration
def change
add_column :events, :plan_id, :integer
end
end
|
=begin <one line to give the program's name and a brief idea of what it does.>
Copyright (C) 2016 Alex Rankin, Lawrence Feng, Anish Jinka
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
=end
require cgi
data = cgi::
|
# 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)
#Image.delete_all
#Image.reset_pk_sequence
#Image.create([
#{name: 'P.-A. Renoir, Бал в Мулен де ла Галетт', file: 'dragonflay.jpg', theme_id: 2},
#{name: 'P.-A. Renoir, Букет', file: 'grass.jpg', theme_id: 2},
#{name: 'P. Picasso, Фабрика', file: 'painted-lady.jpg', theme_id: 3},
#{name: 'H. Matiss, Балерина', file: 'pig.jpg', theme_id: 4},
#])
#Theme.delete_all
#Theme.reset_pk_sequence
#Theme.create([
#{name: "-----"}, # 1 Нет темы
#{name: "Какое из произведений художника О.Ренуара наилучшим образом характеризует его творчество?"}, # 2
#{name: "Какое из произведений художника П.Пикассо наилучшим образом характеризует его творчество?"}, # 3
#{name: "Какое из произведений художника А.Матисса наилучшим образом характеризует его творчество?"}, # 4
#])
#User.delete_all
#User.reset_pk_sequence
#User.create([
#{name: "Example User", email: "example@railstutorial.org", password: "222222", password_confirmation: "222222"},
#])
#
Product.delete_all
Product.create(title:'Описание природы 1',
description:
'<p>
Описание природы 1
</p>',
image_url:'grass.jpg',
rate:10)
|
require 'pry'
WIN_COMBINATIONS = [
[0,1,2], # Top row, #had extra comma&deleted comma, #add comma to delineate element of array WIN_COMBINATIONS
[3,4,5], # Middle row, #add comma to delineate element of array WIN_COMBINATIONS
[6,7,8], # last row#add comma to delineate element of array WIN_COMBINATIONS
[0,3,6], #first columns#add comma to delineate element of array WIN_COMBINATIONS
[1,4,7], #second columns#add comma to delineate element of array WIN_COMBINATIONS
[2,5,8], # third columns#add comma to delineate element of array WIN_COMBINATIONS
[0,4,8], #diagnoal from nw to se#add comma to delineate element of array WIN_COMBINATIONS
[2,4,6], #diagnoal from ne to sw#add comma to delineate element of array WIN_COMBINATIONS
# ETC, an array for each win combination#add comma to delineate element of array WIN_COMBINATIONS
]
def input_to_index (user_input)
user_input.to_i-1 #converts user_input argument to integer w .to_i
#and to match board index position, subtracts 1 from converted user input integer
end
def display_board (board)
puts " #{board[0]} | #{board[1]} | #{board[2]} "
puts "-----------"
puts " #{board[3]} | #{board[4]} | #{board[5]} "
puts "-----------"
puts " #{board[6]} | #{board[7]} | #{board[8]} "
end
def position_taken? (board, index) # remember to check position_taken_spec.rb for syntax of the conditions
#board = ["", "","X", "", "", "", "", "", "" ]
if board[index] == "" || board[index] == " "|| board[index] == nil
#if board index values are not comparable, hence, "empty string", "empty space", or "nothingness" i.e. nil are not comparable == to "X" then return
false
else #board[index] == "X" || "O"; hence, if board[index] value is comparable to "X" or "O" then return "true"
true
end
end
#############code your input_to_index and #############move method here!
def input_to_index (user_input)
user_input.to_i-1 #converts user_input argument to integer w .to_i
#and to match board index position, subtracts 1 from converted user input integer
end
def move (board, index, current_player) # localized variables used = "board, index,current_player"
#Part of your #move method will mean updating the board array passed into it, which is
board[index] = current_player #updated board entries
#in one line w/ 3 arguments = placeholder for values in the bin/move file
#remove space btwn board and its array values
#rec'd error for not allowing default 3rd arguments
end
##################
# code your #valid_move? method here
def valid_move?(board, index)
# re-define your #position_taken? method here, so that you can use it in the #valid_move? method above.
# remember to check position_taken_spec.rb for syntax of the conditions
#binding.pry
#checks to see user entered "index" value is comparable to "", " ", or nil
if board[index] == " " && index.between?(0, 8)# index =>0 && index <=8 failed for short circuit evaluation
true#print true if user entered value is one of 3 conditions r met, i.e user entered "", or " ", or nil
elsif board[index] == "X" || board[index] == "O" #index <0
#binding.pry
false#print false if user has entered a position
else
false
end
end
#turn
#NEED TURN METHODS here#######################################################
#ask for input
#get input
#convert input to index
#if move is valid
# make the move for index and show board
#else
# ask for input again until you get a valid move
#end
#define turn_count
#require 'pry'
def turn_count (board)
#if only two occupied position, then player "o" made move
#if only one occupied position, then player "x" made move
counter = 0
#if board.each do |item| == "X", got sytax error, unexpected ==^ "X"
board.each do |item|#iterate through board array element and pass each value to local variable item
if item !=" "
#if item !=""
counter +=1
#elsif item == "O"; worked
#counter +=1; worked w/ line 23
end
end
#desired outcome is number of turns that have been made by
counter #why did this method missing an argument? when it's not here the each block returns the board array instead of a counter value
end
#define current_player
def current_player(board) # can't have a space b/f and use parenthesise to hold argument
if turn_count(board) % 2 == 0 #failed to include turn_count method's argument (board) 1st x; worked after argument inclusion
return "X"# is the correct line here for instructios states even #'s are to output string "X"'
#pry
#return "X"#, no comma is allowed after the value "X" #returns nil. same as print nor put command.
#instruction calls for X If the turn count is an even number, the `#current_player` method should return `"X"`, otherwise, it should return `"O"`.
elsif turn_count(board) % 2 == 1
#return "O" #1st x w/"X"-returned failure/error msg where it expected "X" & got "O"
return "O"#,no comma is allowed #return nil. same as print nor put command
end
#return "X" #1st x w/ "O"-returned failure/error msg where it expected "X" & got "O"
end
#define won?
def won?(board) WIN_COMBINATIONS.find do |win|
#FIND the 1 unique combination in the constant WIN_COMBINATIONS
#binding.pry
position_1 = board[win[0]]#assigns variables to board nested array
position_2 = board[win[1]]
position_3 = board[win[2]]
if position_1 == position_2 && position_2 == position_3 && position_1 != " "
#variable 1 is comparable to 2 and 2 is comparable to 3 &&
#varialbe 1 is not empty
return win # returns win which is the 1 win in the constant
#WIN_COMBINATIONS
#elsif position_1 == "X" && position_2 == "O" && position_3 == "X"
#return true
else
false
end
end
end
#define full?
def full?(board) #defines the full? method w/board array
board.all? { |elem| # iterate through ALL of the board array
elem == "X" || elem == "O" || elem != " "#value is comparable to X OR O OR is not empty
}
end
#define draw?
#accepts a board and returns true if the board has not been won and is full and false if the board is not won and the board is not full,
#and false if the board is won. You should be able to compose this method solely using the methods you used above with some ruby logic
def draw?(board)
if !won?(board) && full?(board) # if not won board and not full board then
true
else
false
end
end
#define over?
def over?(board)
if draw?(board) || won?(board) # if board is at draw or board is won
true # then return true.
else
false
end
end
#define winner
def winner(board)
win = won?(board) #sets variable to return value
return if win.nil? # solves for incident when win is nil, for when win is
#nil, win[0] does not pass the spec test
position_1 = board[win[0]] # assignment equality operator to extract
#from parent board array value, located at its' child array ,win array, index 0
position_2 = board[win[1]]
position_3 = board[win[2]]
#binding.pry
if position_1 == "X"
return "X"
elsif position_1 == "O"
return "O"
else
false
end
end
def turn(board)
#puts "Please enter 1-9:"
input= gets.strip
input= input_to_index(input) #missing input_to_index METHOD
if valid_move?(board,input)
#binding.pry
move(board,input, current_player(board))
# current_player argument inserted,
#2nd x = current player removed,
#3rd x = current_player(board)
#binding.pry
display_board (board)
elsif
turn(board) #here is the missing line for 9-12 pm (3 hrs) last nt and 9-11 am (2 hrs today), method calls itself is a new concept
end
end
#PLAY METHOD###############################
def play(board)
#input = gets.strip
while !over?(board)
# until the game is over = pseudocode
#!draw?(board) && !won?(board)
#for there is A draw OR A win
# try to be explicit with draw and win condition
#removed equiv to true as a condition per flatiron
# while board is NOT over, = !
#for there is no draw nor win
#current_player(board) # print current player (board)
turn(board)
#elsif over?(board) == true #
#current_player(board)
#turn(board)
#binding.pry
end
#if the game was won
#position_1 = board[win[0]] # assignment equality operator to extract
#from parent board array value, located at its' child array ,win array, index 0
#position_2 = board[win[1]]
#position_3 = board[win[2]]
if won?(board) && winner(board) == "X"
#winner(board)
#current_player(board) = "X"
##== true; worked to ensure its OutPUTString is evaluated by test
##&& winner(board) == "X"#&& position_1 == "X"
#won?(board) is a string, & according to IRB, if won?(board), puts
#print
#puts "Congratulations"
puts "Congratulations X!"
elsif won?(board) && winner(board) == "O" #
#!current_player == "X"
puts "Congratulations O!"
elsif draw?(board) == true
puts "Cats Game!"
#return "Cats Game!"; return was the error
else
puts " "#flatiron, else stmt for won? question mark is
#a truthy or false value, hence, it was missing a false value w/ else stmt.
#puts "Congratulations", it returned nil
end
end
|
class Item < ApplicationRecord
validates :name, presence: true, uniqueness: true, length: {maximum: 30}
validates :introduction, presence: true, length: {maximum: 100}
validates :price, presence: true, numericality: {only_integer: true}
validates :sales_status, inclusion: {in: [true, false]}
belongs_to :genre
has_many :cart_items
attachment :image
has_many :order_items
has_many :orders, through: :order_items
def price_with_tax
(BigDecimal(self.price) * BigDecimal("1.1")).ceil.to_s(:delimited)
end
def is_on_sale?
if self.sales_status == true
"販売中"
elsif self.sales_status == false
"売切れ"
end
end
end
|
require 'spec_helper'
module Alf
describe AttrList, 'to_a' do
it 'returns an array of symbols' do
expect(AttrList[:a, :b].to_a).to eq([:a, :b])
end
it 'works on empty list' do
expect(AttrList[].to_a).to eq([])
end
end
end
|
class MultipleSelect < Question
scope :multiple_selects, -> { where(type: 'MultipleSelect') }
def valid_attempt? attempt
# for MultipleSelect attempt, we have to use @attempt.answer_hash.
# It is guaranteed that the key "answer_ids" is in answer_hash,
# we need to check if there are any answer id(s) there.
attempt.answer_hash["answer_ids"].length != 0
end
def correct_answers
# return all the correct answers of this question
self.answers.where(:is_correct => 1)
end
def grade attempt
# assign 1 (correct) or (0) incorrect to attempt.score
# sanple attempt object:
# <Attempt id: nil, txt: nil, question_id: 46, user_id: 3, answer_id: 87, created_at: "2019-07-26 12:39:03", updated_at: nil, answer_hash: {}, score: nil>
# (please not that, the attempt object is not in DB yet)
correct_answer_ids = self.correct_answers.pluck(:id)
user_selected_answer_ids = attempt.answer_hash["answer_ids"]
if correct_answer_ids.size ==0 or user_selected_answer_ids.size ==0
false
elsif correct_answer_ids.size == user_selected_answer_ids.size and (correct_answer_ids.map(&:to_s) & user_selected_answer_ids).size == correct_answer_ids.size
attempt.score = 1
true
else
attempt.score = 0
true
end
end
def self.answer_as_html attempt
assembled_html = ""
attempt.answer_hash["answer_ids"].each do |answer_id|
assembled_html += "<li>" + Answer.find(answer_id).txt.html_safe + "</li>"
end
assembled_html
end
end |
class Article < ActiveRecord::Base
mount_uploader :image, ArticleImageUploader
has_many :article_tag_positions,
-> { order('article_tag_positions.position ASC') },
dependent: :delete_all
has_many :tags, through: :article_tag_positions
has_many :translated_articles, dependent: :delete_all
has_one :translated_article, -> {
merge(TranslatedArticle.localized(I18n.locale))
}
has_many :article_relations, dependent: :delete_all
has_many :related_articles,
-> { select("articles.*, article_relations.kind") },
through: :article_relations
has_one :article_relation
has_one :previous_article_relation, -> { previous },
class_name: ArticleRelation
has_one :previous_article, through: :previous_article_relation,
source: :related_article
has_one :next_article_relation, -> { merge(ArticleRelation.next) },
class_name: ArticleRelation
has_one :next_article, through: :next_article_relation,
source: :related_article
validates :slug, uniqueness: true, allow_nil: true
validates :slug, presence: true, if: :released?
scope :published, -> { where("published_at < ?", Time.current) }
scope :published_before, ->(time) { published.where("published_at < ?", time) }
scope :published_after, ->(time) { published.where("published_at > ?", time) }
scope :by_publishing, ->(order=:desc) { order(published_at: order) }
scope :by_creation, -> { order("#{table_name}.created_at ASC") }
scope :search, ->(term) {
return if term.blank?
joins(:translated_article)
.merge(TranslatedArticle.search(term))
}
scope :tagged, ->(tag_slug) {
joins(:tags).merge(Tag.slugged(tag_slug)) if tag_slug.present?
}
delegate :title, :text, :summary, to: :translated_article
def released?
published_at.present?
end
end
|
# == Route Map
#
# Prefix Verb URI Pattern Controller#Action
# home_index GET /home(.:format) home#index
# POST /home(.:format) home#create
# new_home GET /home/new(.:format) home#new
# edit_home GET /home/:id/edit(.:format) home#edit
# home GET /home/:id(.:format) home#show
# PATCH /home/:id(.:format) home#update
# PUT /home/:id(.:format) home#update
# DELETE /home/:id(.:format) home#destroy
# subscribe POST /subscribe(.:format) home#subscribe
# user_index GET /user(.:format) user#index
# POST /user(.:format) user#create
# new_user GET /user/new(.:format) user#new
# edit_user GET /user/:id/edit(.:format) user#edit
# user GET /user/:id(.:format) user#show
# PATCH /user/:id(.:format) user#update
# PUT /user/:id(.:format) user#update
# DELETE /user/:id(.:format) user#destroy
# login GET /login(.:format) sessions#new
# POST /login(.:format) sessions#create
# logout GET /logout(.:format) sessions#destroy
# root GET / home#index
#
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
resources :home
post "/subscribe", to: 'home#subscribe'
post "/rememberTheme", to: 'home#rememberTheme'
resources :user
get '/apply', to: 'user#application'
get '/application', to: 'user#application'
get '/login', to: 'sessions#new'
post '/login', to: 'sessions#create'
get '/logout', to: 'sessions#destroy'
root "home#index"
end
|
class UserInvitationsController < ApplicationController
active_tab "users"
no_login only: [:show, :update]
require_permission :can_invite_user?, except: [:show, :update]
def new
@user = User.new
@user = User.find params[:user] if params[:user]
end
def create
current_user.invite_user params
redirect_to users_path
rescue ActiveRecord::RecordInvalid => e
@user = e.record.user
@error_record = e.record
render :new
end
def index
@invites = UserInvitation.for_organization(current_user.organizations_with_permission_enabled(:can_invite_user_at?))
end
def show
@invite = UserInvitation.find_and_check(params)
end
def update
UserInvitation.convert_to_user(params)
redirect_to :root
end
end
|
class ToppagesController < ApplicationController
def index
#アプリケーションコントーラーでSessionHelperをincludeしているのでlogged_in?メソッドが使える
#そしてトップページコントローラーはアプリケーションコントーラーのクラスを継承している
if logged_in?
@micropost = current_user.microposts.build #microposts.newと同義、indexページにフォームを置く特殊なページなのでnewメソッドも併せ持つイメージ
@microposts = current_user.feed_microposts.order(id: :desc).page(params[:page]) #こちらは一覧表示用、feed_micropostはuser.rbのモデルで定義したインスタンスメソッド
#実はコントローラーのデフォルト機能としてアクションの最後にrender :自身のアクションをしてviewを呼び出す
#この場合はviewのindexを呼び出している
end
end
end
|
Rails.application.reloader.to_prepare do
RLS.configure do |config|
config.tenant_class = Tenant
config.user_class = User
config.tenant_fk = :tenant_id
config.policy_dir = 'db/policies'
end
end
|
require 'spec_helper'
describe BTCTicker::HTTPClient do
let(:ticker_uri) { 'https://www.bitstamp.net/api/v2/ticker/btcusd/' }
let(:not_found_uri) { 'https://www.bitstamp.net/api/v2' }
describe '.get_http_response(uri)' do
context 'When it makes a successful GET request' do
it 'should return 200' do
expect(BTCTicker::HTTPClient.get_http_response(ticker_uri).code).to eql 200
end
end
context 'When it makes an unsuccessful GET request' do
it 'should raise HTTPError error' do
expect{ BTCTicker::HTTPClient.get_http_response(not_found_uri) }.to raise_error(BTCTicker::Errors::HTTPError)
end
end
end
end
|
def roll_call_dwarves( dwarves )
dwarves.each_with_index { |dwarf,index| puts "#{index + 1}. #{dwarf}" }
end
def summon_captain_planet( planeteer_calls )
planeteer_calls.map { |planeteer| planeteer.capitalize + "!" }
end
def long_planeteer_calls( array_of_calls )
array_of_calls.any? {|call| call.length > 4 }
end
def find_the_cheese( array )
cheese_types = ["cheddar", "gouda", "camembert"]
array.detect{ |i| cheese_types.include?( "#{i}" ) }
end
|
class User < ApplicationRecord
after_create :welcome_send
def welcome_send
UserMailer.welcome_email(self).deliver_now
end
has_many :administrated_events, foreign_key: 'administrator_id', class_name: "Event"
has_many :attendances
has_many :attended_events, foreign_key: 'attended_id', class_name: "Event", through: :attendances
end
|
class GeneticAlgorithm
# path = '~/programming/genetic_algorithm/' #homepath
path = '~/coding/j_projects/genetic_algorithm/'
require path + 'os_path.rb'
requires = ['configs.rb', 'modules/evolution_helper.rb','modules/population_helper.rb','modules/recombination.rb','modules/mutator.rb','modules/gene_initializer.rb','modules/simple_array_maths.rb','modules/fitness.rb','evolution.rb','individual.rb','population.rb','family_tree.rb', 'population_monitor.rb', 'genome.rb']
requires.each do |item|
require OSPath.path(path + item)
end
$verbose = false
attr_accessor :population
def initialize config = Configs.new.binary_to_int
@config = config
reset
end
def reset
@population_monitor = PopulationMonitor.new
@population = Population.new(@config)
@evolution = Evolution.new(@config, @population,@population_monitor)
end
def run
@evolution.full_cycle
end
def tick
@evolution.process_generation
end
def population_monitor
@evolution.get_monitor
end
def examine
population_monitor.make
end
def results
examine.display_results
end
def population_tree
t = FamilyTree.new(examine.results[:best])
t.make_tree
t.pp_tree
end
alias tree population_tree
end
|
class MagazinePolicy < ApplicationPolicy
alias index? user_renewal_date_is_in_future?
end
|
require 'spec_helper'
RSpec.describe Api::V1::MessagesController, type: :controller do
describe '#index' do
let(:send_request) { get :index, format: :json }
specify 'returns unauthorized error' do
send_request
expect(response.status).to eq(401)
end
context 'with an authorized user' do
let(:user) { create :user, :authorized }
before do
expect(controller).to receive(:authenticate!).and_return true
expect(controller).to receive(:current_user).exactly(3).times.and_return user
end
specify 'basic json structure' do
send_request
expect(response.status).to eq(200)
expect(JSON.parse(response.body)).to eq({
'currentUser' => { 'id' => user.id.to_s,
'name' => user.name },
'myMessagesCount' => '0',
'subscriptionsCount' => '0',
'username' => user.username,
'email' => user.email,
'friends' => [],
'full_name' => nil,
'channel' => nil,
'myMessages' => [],
'messagesToMe' => []
})
end
end
end
end |
class CreatePerfilProfesores < ActiveRecord::Migration[5.0]
def change
create_table :perfil_profesores do |t|
t.belongs_to :user, foreign_key: true, index:{unique: true}
t.string :nss, index:{unique: true}
t.string :ap_paterno
t.string :ap_materno
t.string :nombre
t.date :fecha_de_nacimiento
t.belongs_to :genero, foreign_key: true
t.string :calle
t.string :numero_exterior
t.string :numero_interior
t.string :colonia
t.string :delegacion_municipio
t.string :codigo_postal
t.string :telefono_casa
t.string :telefono_celular
t.string :telefono_recados
t.string :extension_recados
t.timestamps
end
end
end
|
require 'open-uri'
require 'csv'
module Usurper
class Header
include Enumerable
extend Forwardable
def_delegators :@data, :[]
def initialize(data)
@data = process(data)
end
def inspect
"<Usurper::Header>"
end
def each(&block)
@data.each(&block)
end
private
def process(data)
hash = {}
data.each_with_index do |key, i|
hash[i] = key
end
hash.freeze
end
end
class Row
extend Forwardable
def_delegators :@data, :[]
def initialize(row, header)
@header = header
@data = process(row).freeze
end
def inspect
"<Usurper::Row name='#{@data['name']}'>"
end
def to_hash
@data
end
private
def process(row)
hash = {}
row.each_with_index do |value, i|
hash[ @header[i] ] = value
end
@header = nil
hash.freeze
end
end
class CSV
OPENEI_URL= 'http://en.openei.org/apps/USURDB/download/usurdb.csv'
def initialize(csv_path=OPENEI_URL)
@path = csv_path
end
def header
Header.new(data.first)
end
def rows
@rows ||= data[1..-1].map{|r| Row.new(r, header) }
end
private
def data
@data ||= ::CSV.parse( open(@path).read )
end
end
end
|
class U153 < PdfReport
def initialize(quote=[],account=[],policy_calculation=[],view)
super()
@quote = quote
@account = account
@policy_calculation = policy_calculation
@view = view
@group_fees =
if @quote.fees.nil?
0
else
@quote.fees
end
@current_date = DateTime.now.to_date
u_153
end
private
def u_153
current_cursor = cursor
bounding_box([0, current_cursor], :width => 250, height: 50) do
image "#{Rails.root}/app/assets/images/ohio7.png", height: 50
end
bounding_box([250, current_cursor], :width => 300, height: 50) do
text "Employer Statement for", style: :bold, align: :right, size: 12
text "Group-Retrospective-Rating Program", style: :bold, align: :right, size: 12
end
move_down 5
current_cursor = cursor
bounding_box([0, current_cursor], :width => 375, :height => 85) do
text "Instructions:", style: :bold, align: :left, size: 8
text "• Please print or type", align: :left, size: 8, inline_format: true
text "• Please return completed statement to the attention of the sponsoring organization you are joining.", align: :left, size: 8
text "• The Group Administrator’s third party administrator will submit your original U-153 to:", align: :left, size: 8
text "Ohio Bureau of Workers’ Compensation", align: :left, size: 8, indent_paragraphs: 15
text "Attn: employer programs unit", align: :left, size: 8, indent_paragraphs: 15
text "30 W. Spring St., 22nd floor", align: :left, size: 8, indent_paragraphs: 15
text "Columbus, OH 43215-2256", align: :left, size: 8, indent_paragraphs: 15
text "• If you have any group-experience-rating questions calls BWC at 614-466-6773", align: :left, size: 8
transparent(0) { stroke_bounds }
end
text "NOTE: The employer programs unit group underwriters must review and approve this application before it becomes effective.", style: :bold, size: 8, align: :center
current_cursor = cursor
bounding_box([0, current_cursor], :width => 275, :height => 25) do
text "Employer Name", style: :bold, size: 8
text "#{@account.name.titleize}", :indent_paragraphs => 10, size: 10
stroke_bounds
end
bounding_box([275, current_cursor], :width => 180, :height => 25) do
text "Telephone Number", style: :bold, size: 8
text "#{@account.business_phone_number}#{@account&.business_phone_extension.present? ? " Ext: #{@account&.business_phone_extension}" : ''}", :indent_paragraphs => 10, size: 10
stroke_bounds
end
bounding_box([455, current_cursor], :width => 85, :height => 25) do
text "Risk Number", style: :bold, size: 8
text "#{@account.policy_number_entered}-0", :indent_paragraphs => 10, size: 10
stroke_bounds
end
current_cursor = cursor
bounding_box([0, current_cursor], :width => 275, :height => 25) do
text "Address", style: :bold, size: 8
text "#{@account.street_address.titleize} #{@account.street_address_2}", :indent_paragraphs => 10, size: 10
stroke_bounds
end
bounding_box([275, current_cursor], :width => 90, :height => 25) do
text "City", style: :bold, size: 8
text "#{@account.city.titleize}", :indent_paragraphs => 10, size: 10
stroke_bounds
end
bounding_box([365, current_cursor], :width => 90, :height => 25) do
text "State", style: :bold, size: 8
text "#{@account.state.upcase}", :indent_paragraphs => 10, size: 10
stroke_bounds
end
bounding_box([455, current_cursor], :width => 85, :height => 25) do
text "9 Digit Zip Code", style: :bold, size: 8
text "#{@account.policy_calculation.mailing_zip_code}-#{@account.policy_calculation.mailing_zip_code_plus_4}", :indent_paragraphs => 10, size: 10
stroke_bounds
end
current_cursor = cursor
table([["Group-Retrospective-Rating Enrollment"]], :width => 540, :row_colors => ["EFEFEF"]) do
row(0).font_style = :bold
row(0).align = :center
self.cell_style = {:size => 14}
end
current_cursor = cursor
bounding_box([0, current_cursor], :width => 540, :height => 305) do
move_down 5
indent(5) do
text "I agree to comply with the Ohio Bureau of Workers’ Compensation Group-Retrospective-Rating Program rules (Ohio Administrative Rule 4123-17-73). I understand that my participation in the program is contingent on such compliance.", size: 9
move_down 10
text "This form supersedes any previously executed U-153.", size: 9
move_down 10
text "I understand that only a BWC Group-Retrospective-Rating Program certified sponsor can offer membership into the program. I also understand that if the sponsoring organization listed below, is not certified, this application is null and void.", size: 9
move_down 10
text "I am a member of the <b><u>NORTHEAST OHIO SAFETY COUNCIL</u></b> sponsoring organization or a certified affiliate organization and would like to be included in that Group-Retrospective-Rating Program that they sponsor for the policy year beginning <b><u>#{@account.representative.quote_year_lower_date.strftime("%B %e, %Y")}</u></b>. I understand that the employer roster submitted by the group will be the final, official determination of the group in which I will or will not participate. Submission of their form does not guarantee participation.", size: 9, inline_format: true
move_down 10
text "I understand that the organization’s representative <b><u>Trident Risk Advisors</b></u> (currently, as determined by the sponsoring organization) is the only representative I may have in risk-related matters while I remain a member of the group. I also understand that the representative for the group-experience-rating program will continue as my individual representative in the event that I no longer participate in the group rating plan. At the time, I am no longer a member of the program, I understand that I must file a Permanent Authorization (AC-2) to cancel or change individual representation. ", size: 9, inline_format: true
move_down 10
text "I understand that a new U-153 shall be filed each policy year I participate in the group-retrospective-rating plan.", size: 9
move_down 10
text "I am associated with the sponsoring organization or a certified affiliate sponsoring organization <u> X </u> Yes <u> </u> NO", size: 9, inline_format: true
move_down 5
current_cursor = cursor
bounding_box([50 , current_cursor], :width => 130, :height => 25) do
text "NEOSC", indent_paragraphs: 45
stroke_horizontal_rule
move_down 3
text "Name of sponsor or affiliate sponsor", size: 8
end
bounding_box([300 , current_cursor], :width => 200, :height => 25) do
text "#{@account.policy_number_entered}-0", indent_paragraphs: 75
stroke_horizontal_rule
move_down 3
text "Sponsor or affiliate sponsor policy number", size: 8, indent_paragraphs: 20
end
end
stroke_horizontal_rule
move_down 5
indent(5) do
text "Note: For injuries that occur during the period an employer is enrolled in the Group-Retrospective-Rating Program, employers may not utilize or participate in the Deductible Program, Group Rating, Retrospective Rating, Safety Council Discount Program, $15,000 Medical-Only Program, or the Drug-Free Safety Program.", size: 8
end
stroke_bounds
end
table([["Certification"]], :width => 540, :row_colors => ["EFEFEF"]) do
row(0).font_style = :bold
row(0).align = :center
self.cell_style = {:size => 10}
self.cell_style = {:height => 20}
end
current_cursor = cursor
bounding_box([0 , current_cursor], :width => 540, :height => 148) do
move_down 15
text "_<u> </u> certifies that he/she is the <u> </u> of", inline_format: true, indent_paragraphs: 10
text "(Officer Name) (Title)", indent_paragraphs: 65
move_down 10
text "_<u> </u>, the employer referred to above, and that all the information is", inline_format: true, indent_paragraphs: 10
text "(Employer Name)", indent_paragraphs: 65
move_down 10
text "true to the best of his/her knowledge, information, and belief, after careful investigation.", indent_paragraphs: 10
move_down 10
bounding_box([50 , 35], :width => 130, :height => 23) do
move_down 10
stroke_horizontal_rule
move_down 3
text "(OFFICER SIGNATURE)", size: 8, align: :center
end
bounding_box([350 , 35], :width => 130, :height => 23) do
move_down 10
stroke_horizontal_rule
move_down 3
text "(DATE)", size: 8, align: :center
end
stroke_bounds
end
move_down 3
text "BWC-7659 (Rev. 12/15/2010)", size: 8
text "U-153", size: 8, style: :bold
end
end
|
class ResourcesController < ApplicationController
def index
if params[:search]
search_term = "%#{params[:search][:term]}%".downcase
if params[:search][:term] && params[:search][:resource_type] != "Pick a type"
@resources = Resource.where('lower(title) LIKE ? or lower(description) LIKE ? AND resource_type = ?', search_term, search_term, params[:search][:resource_type])
elsif params[:search][:term].length > 0
@resources = Resource.where('lower(title) LIKE ? or lower(description) LIKE ?', search_term, search_term)
elsif params[:search][:resource_type] != "Pick a type"
@resources = Resource.where('resource_type = ?', params[:search][:resource_type])
elsif params[:search] && (params[:search][:term].length == 0 && params[:search][:resource_type] == "Pick a type")
redirect_to resources_path, notice: "Please enter a keyword or resource type and try again."
end
else
@videos = Resource.where(resource_type: "video").limit(3)
@snippets = Resource.where(resource_type: "snippet").limit(3)
@markdowns = Resource.where(resource_type: "markdown").limit(3)
end
end
def new
end
def show
@resource = Resource.find(params[:id])
end
private
def resource_params
params.require(:resource).permit(:term)
end
end
|
class CreateTweetedWords < ActiveRecord::Migration
def change
create_table :tweeted_words do |t|
t.string :word
t.float :lat
t.float :lon
t.timestamps
end
end
end
|
class AddUniqueEventIndex < ActiveRecord::Migration[5.2]
def change
add_index :events, [:subj_id, :obj_id, :source_id, :relation_type_id], unique: true, name: "index_events_on_multiple_columns"
remove_index :events, column: [:subj_id], name: "index_events_on_subj_id"
drop_table :sources
end
end
|
class Article < ActiveRecord::Base
require "net/http"
validates :name, presence: true
validates :url, presence: true
validates :user_id, presence: true
#validate :is_real
belongs_to :user
has_many :tags, dependent: :destroy
accepts_nested_attributes_for :tags
private
def prePend
unless self.url[/\Ahttp:\/\//] || self.url[/\Ahttps:\/\//]
self.url = "https://#{self.url}"
end
end
def is_real
prePend
uri = URI(self.url)
req = Net::HTTP.new(uri.host, uri.port)
req = Net::HTTP.get_response uri
if req.code.to_i != 200
errors.add(self.url, "Site did not return a valid response code")
end
end
end
|
puts 'What\'s your first name?'
first_name = gets.chomp
puts 'What\'s your middle name?'
mid_name = gets.chomp
puts 'What\'s your last name?'
last_name = gets.chomp
full_name = first_name + ' ' + mid_name + ' ' + last_name
puts 'Your name is ' + first_name + ' ' + mid_name + ' ' + last_name + '? What a lovely name!'
puts 'Pleased to meet you, ' + first_name + ' ' + mid_name + ' ' + last_name + '.'
puts 'What\'s your favorite number, ' + full_name + '?'
favnum = gets.chomp.to_i
better_num = favnum + 1
puts favnum.to_s + ' is a good number, but may I suggest ' + better_num.to_s + ' as your new, bigger, better favorite number?'
=begin
Address solution: https://github.com/sjones88/phase-0/blob/master/week-4/address/my_solution.rb
Define-method solution: https://github.com/sjones88/phase-0/blob/master/week-4/define-method/my_solution.rb
Math methods solution: https://github.com/sjones88/phase-0/blob/master/week-4/math/my_solution.rb
- How do you define a local variable?
You define a local variable by typing the name of the variable (e.g. variable_name)
followed by an equals (=) sign followed by the object to which you want the variable
to point. For example, typing:
var_name = 'String'
defines the local variable, 'var_name', and points it to the string, 'String'.
- How do you define a method?
You define a method by typing 'def', then typing the method name, followed by
the parameters that the method will take (if it takes any parameters). Always
finish defining a method by typing 'end' on a new line at the end of the method.
For example, typing:
def method_name (a, b)
end
defines a method called 'method_name' that accepts two arguments, 'a' and 'b'.
- What is the difference between a local variable and a method?
A local variable is an object, and a method is a message that can be sent
to an object, like a local variable, and can cause its object to do something.
- How do you run a ruby program from the command line?
You run a ruby program from the command line by typing 'ruby FILENAME', where
FILENAME is any file with the .rb extension.
- How do you run an RSpec file from the command line?
You type 'rspec FILENAME', where FILENAME is the name of the spec file ending
with the .rb extension.
- What was confusing about this material? What made sense?
I got confused when I tried to run my favorite number program and it returned
an error. I learned the importance of converting fixnums to strings when puts-ing
a combination of fixnums and strings.
=end |
source 'https://rubygems.org'
ruby '2.1.1'
gem 'rails', '4.1.0'
gem 'pg'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 4.0.1'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .js.coffee assets and views
gem 'coffee-rails', '~> 4.0.0'
gem 'jquery-rails'
gem 'bootstrap-sass'
gem 'redcarpet'
gem 'pygments.rb'
gem 'omniauth-github'
gem 'httparty'
gem 'sdoc', '~> 0.4.0', group: :doc
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring', group: :development
# To use ActiveModel has_secure_password
# gem 'bcrypt-ruby', '~> 3.1.2'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
# gem 'jbuilder'
# Use unicorn as the app server
gem 'unicorn'
gem 'rack-cache'
gem 'minitest'
# Deploy with Capistrano
# gem 'capistrano', group: :development
# To use debugger
# gem 'debugger'
gem 'newrelic_rpm' |
Rails.application.routes.draw do
root to: 'searches#new_search'
get '/new_search', to: 'searches#new_search', as: :new_search
get '/search_results', to: 'searches#search_results', as: :search_results
end
|
FactoryBot.define do
sequence :name do |n|
"MyName#{n}"
end
factory :user do
name { "MyName" }
end
end
|
class DurationByClassTemplateController < ApplicationController
before_action :find_class_template
def show
@duration = @class_template.try :duration
end
private
def find_class_template
@class_template = ClassTemplate.find_by id: params[:class_template_id]
end
end
|
require 'spec_helper'
describe Answer do
it_behaves_like "a votable object" do
let(:user){FactoryGirl.create(:user)}
let(:votable){FactoryGirl.create(:question)}
let(:votables){user.questions}
end
context "validations" do
it {should belong_to(:user)}
it {should belong_to(:question)}
it {should have_many(:responses)}
it {should have_many(:votes)}
it {should validate_presence_of(:body)}
end
end
#user can post a question and upvote it.
|
## 10 xp
# pad_left
# pad_right
# lines
# chars
def pad_left(str, target_size, padding = " ")
new_str = str.dup
if target_size > str.size
until new_str.size <= target_size
new_str = padding + new_str
end
end
new_str
end
def pad_right(str, target_size, padding = " ")
new_str = str
if target_size > str.size
until new_str.size <= target_size
new_str << padding
end
end
new_str
end
def get_lines(str)
A = ["\r\n", "\n", "\r"].freeze
str.split(/(\r\n)|(\n)|(\r)/).reject{|l|A.include? l}
end
def get_chars(str)
arr = []
str.each_char { |c| arr << c }
arr
end
|
class CreatePaymentGateways < ActiveRecord::Migration
def change
create_table :payment_gateways do |t|
t.integer :user_id
t.string :gateway_name, :default => "Stripe"
t.text :stripe_api_key
t.timestamps
end
add_index :payment_gateways, :user_id
add_column :users, :allow_cc_processing, :boolean, :default => false
end
end
|
Given /the following movies exist/ do |movies_table|
movies_table.hashes.each do |hash|
# each returned element will be a hash whose key is the table header.
movie= Movie.new
movie.title=hash[:title]
movie.rating=hash[:rating]
movie.release_date=hash[:release_date]
movie.description=hash[:description]
movie.validated_save
end
end
Then /I should (not )?see "(.*)" before "(.*)"/ do |not_see, e1, e2|
e1_position= /#{e1}/=~ page.body
e2_position= /#{e2}/=~ page.body
e1_position.should_not be_nil
e2_position.should_not be_nil
unless not_see
e1_position.should < e2_position
else
e1_position.should > e2_position
end
end
When /I (un)?check the following ratings: (.*)/ do |uncheck, rating_list|
rating_list.to_s.split(", ").each do |rating|
if uncheck
step "I uncheck \"#{rating}\""
else
step "I check \"#{rating}\""
end
end
end
Then /I should see exactly (.*) movies/ do |amount|
movies= Movie.all
visible_movies= 0
movies.each do |movie|
movie_position= /#{movie.title}/=~ page.body
unless movie_position== nil
visible_movies+= 1
end
end
visible_movies.should be amount.to_i
end
Then(/^I should (not )?see "(.*?)" and "(.*?)" rated movies$/) do |be_hidden, rating1, rating2|
ratings_selected=[rating1, rating2]
movies= Movie.all
ratings_selected.each do |rating|
movies.each do |movie|
movie_position= /#{movie.title}/=~ page.body
if movie.rating== rating
if be_hidden
movie_position.should be_nil
else
movie_position.should_not be_nil
end
end
end
end
end
|
require 'csv'
require 'pry'
desc "Import customers from csv file"
task :import => [:environment] do
file = "db/rales_engine_data/customers.csv"
CSV.foreach(file, :headers => true) do |row|
Customer.create(first_name: row[1],
last_name: row[2],
created_at: row[3],
updated_at: row[4]
)
end
end
desc "Import merchants from csv file"
task :import => [:environment] do
file = "db/rales_engine_data/merchants.csv"
CSV.foreach(file, :headers => true) do |row|
Merchant.create(name: row[1],
created_at: row[2],
updated_at: row[3]
)
end
end
desc "Import items from csv file"
task :import => [:environment] do
file = "db/rales_engine_data/items.csv"
CSV.foreach(file, :headers => true) do |row|
Item.create(name: row[1],
description: row[2],
unit_price: row[3],
merchant_id: row[4],
created_at: row[5],
updated_at: row[6]
)
end
end
desc "Import transactions from csv file"
task :import => [:environment] do
file = "db/rales_engine_data/transactions.csv"
CSV.foreach(file, :headers => true) do |row|
Transaction.create(invoice_id: row[1],
credit_card_number: row[2],
result: row[4],
created_at: row[5],
updated_at: row[6]
)
end
end
desc "Import invoices from csv file"
task :import => [:environment] do
file = "db/rales_engine_data/invoices.csv"
CSV.foreach(file, :headers => true) do |row|
Invoice.create(customer_id: row[1],
merchant_id: row[2],
status: row[3],
created_at: row[4],
updated_at: row[5]
)
end
end
desc "Import invoice_items from csv file"
task :import => [:environment] do
file = "db/rales_engine_data/invoice_items.csv"
CSV.foreach(file, :headers => true) do |row|
InvoiceItem.create(item_id: row[1],
invoice_id: row[2],
quantity: row[3],
unit_price: row[4],
created_at: row[5],
updated_at: row[6]
)
end
end
|
=begin
* ****************************************************************************
* BRSE-SCHOOL
* HOME - HomeController
*
* 処理概要 :
* 作成日 : 2017/07/27
* 作成者 : quypn – quypn@ans-asia.com
*
* 更新日 :
* 更新者 :
* 更新内容 :
*
* @package : HOME
* @copyright : Copyright (c) ANS-ASIA
* @version : 1.0.0
* ****************************************************************************
=end
module Home
class HomeController < ApplicationController
include ApplicationHelper #app/helpers/application_helper.rb
include HomeHelper #app/helpers/home/home_helper.rb
###
# getData
# -----------------------------------------------
# @author : quypn - 2017/08/10 - create
# @param : null
# @return : null
# @access : public
# @see : remark
###
def getData
@lang = Helper.getLang
@setting = Setting.find_by(:id => 1, :lang => @lang)
@dataSlide = HomePage.getDataSlide()
@dataDifferent = HomePage.getDataDifferent()
@dataMedia = HomePage.getDataMedia()
@dataCourses = HomePage.getDataCourses()
@dataEvent = HomePage.getDataEvent()
@dataCourseType = Helper.getLibraries(2, @lang)
@dataEducationlevel = Helper.getLibraries(6, @lang)
end
###
# getData index
# -----------------------------------------------
# @author : quypn - 2017/09/28 - create
# @param : null
# @return : null
# @access : public
# @see : remark
###
def getDataIndex
self.getData()
# Add by Daonx - ANS804 - 2017/08/22
# Edit by Daonx - ANS804 - 2017/08/25
@dataPopupEvent = HomePage.getBannerEvent
if @dataPopupEvent != nil && @dataPopupEvent[:event] != nil && @dataPopupEvent[:event][:image] != nil
# create direction
@direction = "#{Rails.public_path}" + @dataPopupEvent[:event][:image]
# check isset file
@dataPopupEvent = File.exist?(@direction) ? @dataPopupEvent : nil
end
# End - Add by Daonx - ANS804 - 2017/08/22
end
###
# index
# -----------------------------------------------
# @author : quypn - 2017/07/27 - create
# @param : null
# @return : null
# @access : public
# @see : remark
###
def index
begin
self.getDataIndex()
render 'home/index'
rescue
redirect_to error_path
end
end
###
# index of english
# -----------------------------------------------
# @author : quypn - 2017/09/28 - create
# @param : null
# @return : null
# @access : public
# @see : remark
###
def indexEn
begin
I18n.locale = 'en'
self.getDataIndex()
render 'home/index'
rescue
redirect_to error_path
end
end
###
# index
# -----------------------------------------------
# @author : quypn - 2017/09/28 - create
# @param : null
# @return : null
# @access : public
# @see : remark
###
def indexJa
begin
I18n.locale = 'ja'
self.getDataIndex()
render 'home/index'
rescue
redirect_to error_path
end
end
###
# return page with course deteils
# -----------------------------------------------
# @author : quypn - 2017/08/10 - create
# @param : null
# @return : null
# @access : public
# @see : remark
###
def courseDetail
begin
@idClass = HomePage.getIdClassByBeautyId(params[:beauty_id])
@verify = params[:verify]
self.getData()
render 'home/index'
rescue
redirect_to error_path
end
end
###
# return page with form apply
# -----------------------------------------------
# @author : quypn - 2017/08/10 - create
# @param : null
# @return : null
# @access : public
# @see : remark
###
def showApply
begin
if(params[:beauty_id] != nil)
@idClass = HomePage.getIdClassByBeautyId(params[:beauty_id])
end
@showApply = 1;
self.getData()
render 'home/index'
rescue
redirect_to error_path
end
end
###
# user regist course
# -----------------------------------------------
# @author : quypn - 2017/08/10 - create
# @param : null
# @return : null
# @access : public
# @see : remark
###
def registCourse
result = Hash.new
result['status'] = true
begin # try
regist = RegisterCourse.new(regist_params)
id = Helper.getID('register_courses')
regist.id = id
regist.status = 0
regist.token = Helper.generateToken(id)
regist.timeout = Time.now + 172800 # 48h
if regist.save
SubscribeMailer.mail_verify_regist_course(id).deliver_later
CourseClass.where(:id => regist_params['class_id']).update_all('view = view + 1')
result['status'] = true
else
result['status'] = false
end
rescue # catch
result['status'] = false
result['error'] = "#{$!}"
ensure # finally
render json: result
end
end
def regist_params
params.require(:regist).permit(:id, :class_id, :name, :profile, :address, :email, :phone, :message)
end
###
# veryfi regist course
# -----------------------------------------------
# @author : quypn - 2017/08/30 - create
# @param : null
# @return : null
# @access : public
# @see : remark
###
def verifyRegistCourse
begin
result = HomePage.verifyRegistCourse(params[:id], params[:token])
redirect_to :controller => 'home', :action => 'courseDetail', :beauty_id => params[:beauty_id], :verify => result, :lang => Helper.getLang
rescue
# byebug
redirect_to error_path
end
end
###
# refer info of class by id
# -----------------------------------------------
# @author : quypn - 2017/08/09 - create
# @param : null
# @return : null
# @access : public
# @see : remark
###
def referClass
result = Hash.new
result['status'] = true
begin # try
@lang = Helper.getLang
@class = HomePage.referClass(params[:id].to_i)
if @class != nil
result['status'] = true
result['html'] = render_to_string(partial: "home/course_details")
else
result['status'] = false
end
rescue # catch
result['status'] = false
result['error'] = "#{$!}"
ensure # finally
render json: result
end
end
###
# return page with form regist Advisory
# -----------------------------------------------
# @author : quypn - 2017/11/09 - create
# @param : null
# @return : null
# @access : public
# @see : remark
###
def showRegistAdvisory
begin
@showRegistAdvisory = 1
self.getData()
render 'home/index'
rescue
redirect_to error_path
end
end
###
# regist Advisory
# -----------------------------------------------
# @author : havv - 2017/08/10 - create
# @param : null
# @return : null
# @access : public
# @see : remark
###
def registAdvisory
result = Hash.new
result['status'] = true
begin # try
id = Helper.getID('register_advisories', 'id');
registerAdvisory = RegisterAdvisory.create(
id: id,
name: params[:name],
address: params[:address],
email: params[:email],
phone: params[:phone],
message: params[:message],
status: params[:status].to_i,
education_level: params[:education_level].to_i,
course_type: params[:course_type].to_i
)
if registerAdvisory.present?
# send mail for register
SubscribeMailer.mail_to_register_adviories(params[:email]).deliver_later
# regist success
result['status'] = true
else
result['status'] = false
end
rescue # catch
result['status'] = false
result['error'] = "#{$!}"
ensure # finally
render json: result
end
end
###
# Subscribe Email
# -----------------------------------------------
# @author : havv - 2017/08/11 - create
# @param : null
# @return : null
# @access : public
# @see : remark
###
def subscribeEmail
result = Hash.new
result['status'] = true
begin # try
# find email exist
subscribe = Subscribe.find_by(email: params[:email], deleted_at: nil)
if subscribe.nil?
# email not exist
# insert data
id = Helper.getID('subscribes', 'id');
subscribe = Subscribe.create(
id: id,
email: params[:email],
status: 1
)
end
if subscribe.present?
# send mail for subscriber
SubscribeMailer.mail_to_subscriber(params[:email]).deliver_later
# subscribe success
result['status'] = true
else
result['status'] = false
end
rescue # catch
result['status'] = false
result['error'] = "#{$!}"
ensure # finally
render json: result
end
end
###
# refer a event
# -----------------------------------------------
# @author : havv - 2017/08/14 - create
# @param : null
# @return : null
# @access : public
# @see : remark
###
def referEvent
result = Hash.new
result['status'] = true
begin # try
@lang = Helper.getLang
@event = HomePage.referEvent(params[:id].to_i)
@dataTest = Helper.getLibraries(7, @lang)
if @event.present?
result['status'] = true
result['html'] = render_to_string(partial: "home/regist_event")
else
result['status'] = false
end
rescue # catch
result['status'] = false
result['error'] = "#{$!}"
ensure # finally
render json: result
end
end
###
# regist event
# -----------------------------------------------
# @author : havv - 2017/08/15 - create
# @param : null
# @return : null
# @access : public
# @see : remark
###
def registEvent
result = Hash.new
result['status'] = true
begin # try
id = Helper.getID('register_events', 'id');
registerEvent = RegisterEvent.create(
id: id,
event_id: params[:event_id].to_i,
name: params[:name],
email: params[:email],
phone: params[:phone],
test_type: params[:test_type],
status: params[:status].to_i
)
if registerEvent.present?
# send mail for subscriber
SubscribeMailer.mail_to_register_event(params[:email], params[:event_id].to_i).deliver_later
result['status'] = true
else
result['status'] = false
end
rescue # catch
result['status'] = false
result['error'] = "#{$!}"
ensure # finally
render json: result
end
end
###
# return page with regist event
# -----------------------------------------------
# @author : havv - 2017/08/15 - create
# @param : null
# @return : null
# @access : public
# @see : remark
###
def showRegistEvent
begin
@idEvent = HomePage.getIdEventByBeautyId(params[:beauty_id])
self.getData()
render 'home/index'
rescue
redirect_to error_path
end
end
###
# refer a event detail
# -----------------------------------------------
# @author : Daonx - 2017/08/16 - create
# @param : null
# @return : null
# @access : public
# @see : remark
###
def referEventDetail
result = Hash.new
result['status'] = true
begin # try
@lang = Helper.getLang
@event = HomePage.referEventDetail(params[:event_id].to_i)
if @event.present?
result['status'] = true
result['html'] = render_to_string(partial: "home/event_detail")
else
result['status'] = false
end
rescue # catch
result['status'] = false
result['error'] = "#{$!}"
ensure # finally
render json: result
end
end
###
# showEventDetail
# -----------------------------------------------
# @author : Daonx - 2017/08/18 - create
# @param : null
# @return : null
# @access : public
# @see : remark
###
def showEventDetail
begin
@eventDetailId = HomePage.getIdEventByBeautyId(params[:beauty_id])
self.getData()
render 'home/index'
rescue
redirect_to error_path
end
end
###
# get data of event nearest
# -----------------------------------------------
# @author : Daonx - 2017/08/22 - create
# @param :
# @return :
# @access : public
# @see : remark
###
def referPopupEventNearest
result = Hash.new
result[:status] = true
begin
@lang = Helper.getLang
@dataEventNearest = Hash.new
@dataEventNearest = HomePage.getBannerEvent
if @dataEventNearest.present?
result[:status] = true
result[:html] = render_to_string(partial: "home/show_event_nearest")
else
result[:status] = false
end
rescue
result[:status] = false
result[:error] = "#{$!}"
ensure # finally
render json: result
end
end
###
# return page greeting
# -----------------------------------------------
# @author : dao - 2017/11/13 - create
# @param : null
# @return : null
# @access : public
# @see : remark
###
def greeting
begin
@showVideoAboutUs = 1
self.getData()
render 'home/index'
rescue
redirect_to error_path
end
end
###
# maintenance
# -----------------------------------------------
# @author : daonx - 2017/11/13 - create
# @param : null
# @return : null
# @access : public
# @see : remark
###
def maintenance
render 'error/maintenance', layout: false
end
end
end |
class ApplicationController < ActionController::Base
protect_from_forgery
def signed_in_user
if current_user.nil?
flash[:error] = "Please sign in to access your project information."
logger.debug 'current_user.nil, redirecting'
redirect_to root_path
else
load_projects
end
end
def load_projects
@project = Project.new
@project_items = current_user.projects
end
end
|
class MainController < ApplicationController
before_filter :authenticate_user!, only: [:show]
def index
@users = User.all
end
def show
@user = User.find(params[:id])
@profile = @user.profile
@location = @user.location
@photos = @user.photos
end
end
|
Dj::Application.routes.draw do
get '/login', to: 'sessions#new'
resources :sessions, only: [:new, :create, :destroy]
resources :users
resources :comments, except: [:new] do
end
resources :mixes
resources :artists
root to: 'home#home'
get '/permission_denied', to: 'home#warning', as: :warning
end
|
class ArticleBlogExtensions < ActiveRecord::Migration
def self.up
t = :article_categories
add_column t, :parent_id, :integer, :null => true
add_column t, :featured, :boolean, :null => false, :default => false
add_column t, :description, :text, :null => true, :limit => 4000
add_column t, :primary_author_id, :integer, :null => true
add_column t, :short_name, :string, :null => true
[ t, :article_instances ].each {|tbl| add_column tbl, :partner_key, :string, :null => true}
### Add partner_key idx
add_index t, :parent_id
### suggested products highlighted in a blog/article
create_table :articles_products, :id => false, :force => true do |t|
t.integer :article_id, :product_id
end
[:article_id, :product_id].each {|c| add_index :articles_products, c}
end
def self.down
[ :parent_id, :featured, :partner_key, :description, :primary_author_id, :short_name].each do |col|
remove_column :article_categories, col
end
remove_column :article_instances, :partner_key
remove_index :article_categories, :parent_id
drop_table :articles_products
end
end
|
module Embeddable::DataCollectorHelper
def javascript_probetype_to_axis_label_hash(probetypes)
out = "var probe_to_axis = Array();"
probetypes.each do |pt|
out << "probe_to_axis[#{pt.id}] = '#{pt.name}';"
end
return out
end
def javascript_probetype_to_units_hash(probetypes)
out = "var probe_to_unit = Array();"
probetypes.each do |pt|
out << "probe_to_unit[#{pt.id}] = '#{pt.unit}';"
end
return out
end
def update_label_and_units_script(probetypes, label_field_id, unit_field_id)
out = javascript_probetype_to_units_hash(probetypes)
out << javascript_probetype_to_axis_label_hash(probetypes)
out << "$('#{unit_field_id}').value = probe_to_unit[value]; $('#{label_field_id}').value = probe_to_axis[value];"
return out
end
end |
class Timer < ApplicationRecord
belongs_to :category
belongs_to :task
belongs_to :preference
end
|
class StandardCard
extend Memoizer
attr_accessor :multiverse_id, :page
def initialize(multiverse_id, page)
self.multiverse_id = multiverse_id
self.page = page
end
memo def parse_name
name_str = self.page.css('[id$="subtitleDisplay"]').text.strip.gsub("Æ", "Ae")
CARD_NAME_OVERRIDES[self.multiverse_id] || name_str
end
memo def parse_collector_num
COLLECTOR_NUM_OVERRIDES[self.multiverse_id] || labeled_row(:number)
end
memo def parse_types
Gatherer.translate_card_types labeled_row(:type)
end
memo def parse_set_name
SET_NAME_OVERRIDES[labeled_row(:set)] || labeled_row(:set)
end
memo def parse_mana_cost
container.css('[id$="manaRow"] .value img').map do |symbol|
Gatherer.translate_mana_symbol(symbol)
end.join
end
memo def parse_oracle_text
# Override oracle text for basic lands.
if parse_types[:supertypes].include?('Basic')
return ["({T}: Add #{BASIC_LAND_SYMBOLS[parse_name]}.)"]
end
textboxes = container.css('[id$="textRow"] .cardtextbox')
Gatherer.translate_oracle_text textboxes
end
memo def parse_flavor_text
return FLAVOR_TEXT_OVERRIDES[self.multiverse_id] if FLAVOR_TEXT_OVERRIDES[self.multiverse_id]
textboxes = container.css('[id$="flavorRow"] .flavortextbox')
textboxes.map{|t| t.text.strip}.select(&:present?).join("\n").presence
end
memo def parse_pt
if parse_types[:types].include?('Planeswalker')
{ loyalty: labeled_row(:pt).strip.presence }
elsif parse_types[:types].include?('Creature') ||
parse_types[:subtypes].include?('Vehicle')
{ power: labeled_row(:pt).split('/')[0].strip,
toughness: labeled_row(:pt).split('/')[1].strip }
else
{}
end
end
# Rather than overriding based on multiverse_id, correct any obvious typos
ILLUSTRATOR_REPLACEMENTS = {
"Brian Snoddy" => "Brian Snõddy",
"Parente & Brian Snoddy" => "Parente & Brian Snõddy",
"ROn Spencer" => "Ron Spencer",
"s/b Lie Tiu" => "Lie Tiu"
}
memo def parse_illustrator
artist_str = labeled_row(:artist)
ILLUSTRATOR_OVERRIDES[self.multiverse_id] ||
ILLUSTRATOR_REPLACEMENTS[artist_str] || artist_str
end
RARITY_REPLACEMENTS = {'Basic Land' => 'Land'}
memo def parse_rarity
rarity_str = labeled_row(:rarity)
RARITY_REPLACEMENTS[rarity_str] || rarity_str
end
def parse_color_indicator
color_indicator_str = labeled_row(:colorIndicator).presence
color_indicator_str.split(', ').join(' ') if color_indicator_str
end
def parse_rulings
container.css("tr.post").map do |post|
# "translate" text to parse <img> symbols into appropriate text shorthand
post_text = Gatherer.translate_oracle_text(post.css("[id$=\"rulingText\"]"))[0]
{ 'date' => post.css("[id$=\"rulingDate\"]").text.strip,
'text' => post_text }
end
end
CARD_NAME_REPLACEMENTS = {
'kongming, "sleeping dragon"' => 'Kongming, “Sleeping Dragon”',
'pang tong, "young phoenix"' => 'Pang Tong, “Young Phoenix”',
'will-o\'-the-wisp' => 'Will-o\'-the-Wisp'
}
def as_json(options={})
return if parse_types[:types].include?('Token') ||
parse_name.in?(EXCLUDED_TOKEN_NAMES)
{
'name' => CARD_NAME_REPLACEMENTS[parse_name.downcase] || parse_name,
'set_name' => parse_set_name,
'collector_num' => parse_collector_num,
'illustrator' => parse_illustrator,
'types' => parse_types[:types],
'supertypes' => parse_types[:supertypes],
'subtypes' => parse_types[:subtypes],
'rarity' => parse_rarity,
'mana_cost' => parse_mana_cost.presence,
'converted_mana_cost' => labeled_row(:cmc).to_i,
'oracle_text' => parse_oracle_text,
'flavor_text' => parse_flavor_text,
'power' => parse_pt[:power],
'toughness' => parse_pt[:toughness],
'loyalty' => parse_pt[:loyalty],
'multiverse_id' => self.multiverse_id,
'other_part' => nil, # only relevant for split, flip, etc.
'color_indicator' => parse_color_indicator,
'rulings' => parse_rulings,
}
end
# Grab the .cardComponentContainer that corresponds with this card. Flip,
# split, and transform cards override this method. It's possible we can
# replace the whole thing with `containers.first` for StandardCards?
def container
containers.find do |container|
subtitle_display = CARD_NAME_OVERRIDES[self.multiverse_id] ||
self.page.css('[id$="subtitleDisplay"]').text.strip
container.css('[id$="nameRow"] .value').text.strip == subtitle_display
end || containers.first
end
def containers
self.page.css('.cardComponentContainer')
end
memo def labeled_row(label)
container.css("[id$=\"#{label}Row\"] .value").text.strip
end
end
|
require 'RSA'
RSpec.describe RSA do
let(:rsa_values) { RSA.new 14, 5, 6 }
key_values = RSA.new_key
describe "testing return values of getters" do
it "checks n returning value" do
expect(rsa_values.n).to eq 14
end
it "checks e returning value" do
expect(rsa_values.e).to eq 5
end
it "checks d returning value" do
expect(rsa_values.d).to eq 6
end
end
describe "testing return types of new_key" do
it "checks first new_key returnig type" do
expect(key_values[0]).to be_a(Integer)
end
it "checks second new_key returnig type" do
expect(key_values[1]).to be_a(Integer)
end
it "checks third new_key returnig type" do
expect(key_values[2]).to be_a(Integer)
end
end
describe "testing return values of encrypt and decrypt" do
it "checks encrypting return type" do
expect(rsa_values.encrypt 'abcdef').to be_a(String)
end
it "cheks if encrypt input equals to decrypt return" do
msg = RSA.new key_values[0], key_values[1], key_values[2]
encrypted_msg = msg.encrypt 'abcdef'
expect(msg.decrypt encrypted_msg).to eq'abcdef'
end
end
end
|
class PlayersController < ApplicationController
def index
@players = Player.search(params[:search])
end
def show
@player = Player.find(params[:id])
end
def player_params
params.require(:player).permit(:player_id)
end
end
|
require_relative 'test_helper.rb'
require './lib/translator.rb'
class TranslatorTest < MiniTest::Test
include Translator
def test_translator_outputs_array
output = translate("A4")
assert_instance_of Array, output
end
def test_translator_output_gives_numeric_coordinates
output = translate("A4")
assert_equal 2, output.count
assert output.include?(0)
assert output.include?(3)
assert_equal [0,3], output
end
def test_pos_1_through_pos_4_are_fix_num
output = translate("A4 D1")
assert_equal 0, pos_1
assert_equal 3, pos_2
assert_equal 3, pos_3
assert_equal 0, pos_4
end
def test_out_of_bounds_output_is_nil
output = translate("A5")
assert 0, pos_1
assert_equal nil, pos_2
end
end |
class Brewery
attr_accessor :name, :location
@@all = []
def initialize(name, location)
@name = name
@location = location
Brewery.all << self
end
# get list of all breweries
def self.all
@@all
end
# # get list of all beers in a brewery (always write the method on the object of the instance you want to run it on!)
def beers
Beer.all.select { |beer| beer.brewery == self }
end
# get list of all names of beers in a brewery
def beers_names
beers.map {|beer| beer.name}
end
# get list of all types in a brewery
def types
beers.map {|beer| beer.type}
end
# average abv of all of the beers in a brewery
def average_abv
beers.map {|beer| beer.abv}.sum / beers.length
end
# given a beer, a type and an abv, make a new beer for a brewery
def new_beer(beer, type, abv)
Beer.new(self, beer, type, abv)
end
# get the total number of beers at a brewery
def total_beers
beers_names.count
end
end
|
class RemoveQuantidadeFromProduto < ActiveRecord::Migration[5.0]
def change
remove_column :produtos, :quantidade
end
end
|
class AddExpiryDateToMyrecipeingredientlinks < ActiveRecord::Migration[5.2]
def change
add_column :myrecipeingredientlinks, :expiry_date, :date
end
end
|
class Iframes::MembersController < ApplicationController
before_filter :load_conf
layout 'iframe'
# GET /iframes/members
# List all members HTML
# --------------------------------------------------------
def index
@members = Member.www_published.order('first_name ASC')
end
# POST /iframes/members/search
# Search for members HTML
# --------------------------------------------------------
def search
@members = Member.www_published.search_by(params[:category], params[:keywords], params[:is_active])
render :template => '/iframes/members/index'
end
# GET /iframes/members/:id
# Show member's profile HTML
# --------------------------------------------------------
def show
@member = Member.www_published.where(['members.id = ?', params[:id]]).first
raise ActiveRecord::RecordNotFound.new(:not_found) if !@member
end
end
|
class RemoveCompanyidFromOpinions < ActiveRecord::Migration
def up
remove_column :opinions, :company_id
end
def down
add_column :opinions, :company_id, :string
end
end
|
require "rails_helper"
RSpec.describe Reports::PatientVisit, {type: :model, reporting_spec: true} do
describe "Associations" do
it { should belong_to(:patient) }
end
around do |example|
Timecop.freeze("June 30 2021 5:30 UTC") do # June 30th 23:00 IST time
example.run
end
end
it "does not include deleted visit data" do
patient = create(:patient, recorded_at: june_2021[:long_ago])
bp = create(:bp_with_encounter, patient: patient, recorded_at: june_2021[:over_3_months_ago], deleted_at: june_2021[:now])
bp.encounter.update(deleted_at: june_2021[:now])
blood_sugar = create(:blood_sugar_with_encounter, patient: patient, recorded_at: june_2021[:over_3_months_ago], deleted_at: june_2021[:now])
blood_sugar.encounter.update(deleted_at: june_2021[:now])
_prescription_drug = create(:prescription_drug, patient: patient, recorded_at: june_2021[:over_3_months_ago], deleted_at: june_2021[:now])
_appointment = create(:appointment, patient: patient, recorded_at: june_2021[:over_3_months_ago], deleted_at: june_2021[:now])
described_class.refresh
with_reporting_time_zone do
expect(described_class.find_by(patient_id: patient.id, month_date: june_2021[:now]).visited_at).to be_nil
end
end
describe "visited_facility_ids" do
it "aggregates all the facilities visited in a given month, but uses only latest encounter" do
patient = create(:patient, recorded_at: june_2021[:now])
bp = create(:bp_with_encounter, patient: patient, recorded_at: june_2021[:now] + 1.minute)
blood_sugar = create(:blood_sugar_with_encounter, patient: patient, recorded_at: june_2021[:now])
prescription_drug = create(:prescription_drug, patient: patient, recorded_at: june_2021[:now])
appointment = create(:appointment, patient: patient, recorded_at: june_2021[:now])
described_class.refresh
with_reporting_time_zone do
visit = described_class.find_by(patient_id: patient.id, month_date: june_2021[:now])
expect(visit.visited_facility_ids).to match_array [bp.facility_id, prescription_drug.facility_id, appointment.creation_facility_id]
expect(visit.visited_facility_ids).not_to include(blood_sugar.facility_id)
end
end
end
describe "the visit definition" do
it "considers a BP measurement as a visit" do
bp = create(:blood_pressure, :with_encounter, recorded_at: june_2021[:now])
described_class.refresh
with_reporting_time_zone do
visit = described_class.find_by(patient_id: bp.patient_id, month_date: june_2021[:now])
expect(visit.encounter_facility_id).to eq bp.facility_id
expect(visit.visited_at).to eq bp.recorded_at
end
end
it "considers a Blood Sugar measurement as a visit" do
blood_sugar = create(:blood_sugar, :with_encounter, recorded_at: june_2021[:now])
described_class.refresh
with_reporting_time_zone do
visit = described_class.find_by(patient_id: blood_sugar.patient_id, month_date: june_2021[:now])
expect(visit.encounter_facility_id).to eq blood_sugar.facility_id
expect(visit.visited_at).to eq blood_sugar.recorded_at
end
end
it "considers a Prescription Drug creation as a visit" do
prescription_drug = create(:prescription_drug, recorded_at: june_2021[:now])
described_class.refresh
with_reporting_time_zone do
visit = described_class.find_by(patient_id: prescription_drug.patient_id, month_date: june_2021[:now])
expect(visit.visited_at).to eq prescription_drug.recorded_at
end
end
it "considers an Appointment creation as a visit" do
appointment = create(:appointment, recorded_at: june_2021[:now])
described_class.refresh
with_reporting_time_zone do
visit = described_class.find_by(patient_id: appointment.patient_id, month_date: june_2021[:now])
expect(visit.visited_at).to eq appointment.recorded_at
end
end
it "does not consider Teleconsultation as a visit" do
create(:teleconsultation, recorded_at: june_2021[:now])
described_class.refresh
with_reporting_time_zone do
expect(described_class.find_by(month_date: june_2021[:now]).visited_at).to be_nil
end
end
it "uses the latest visit information for a given month" do
patient = create(:patient, recorded_at: june_2021[:long_ago])
bp = create(:blood_pressure, :with_encounter, patient: patient, recorded_at: june_2021[:over_3_months_ago])
described_class.refresh
with_reporting_time_zone do
visit = described_class.find_by(patient_id: bp.patient_id, month_date: june_2021[:now])
expect(visit.encounter_facility_id).to eq bp.facility_id
expect(visit.visited_at).to eq bp.recorded_at
end
blood_sugar = create(:blood_sugar, :with_encounter, patient: patient, recorded_at: june_2021[:under_3_months_ago])
described_class.refresh
with_reporting_time_zone do
visit = described_class.find_by(patient_id: blood_sugar.patient_id, month_date: june_2021[:now])
expect(visit.encounter_facility_id).to eq blood_sugar.facility_id
expect(visit.visited_at).to eq blood_sugar.recorded_at
end
prescription_drug = create(:prescription_drug, patient: patient, recorded_at: june_2021[:now])
described_class.refresh
with_reporting_time_zone do
visit = described_class.find_by(patient_id: prescription_drug.patient_id, month_date: june_2021[:now])
expect(visit.visited_at).to eq prescription_drug.recorded_at
end
end
end
end
|
class Sub1LineItemsController < ApplicationController
before_action :set_sub1_line_item, only: [:show, :edit, :update, :destroy]
# GET /sub1_line_items
# GET /sub1_line_items.json
def index
@sub1_line_items = Sub1LineItem.all
end
# GET /sub1_line_items/1
# GET /sub1_line_items/1.json
def show
end
# GET /sub1_line_items/new
def new
@sub1_line_item = Sub1LineItem.new
end
# GET /sub1_line_items/1/edit
def edit
end
# POST /sub1_line_items
# POST /sub1_line_items.json
def create
@sub1_line_item = Sub1LineItem.new(sub1_line_item_params)
respond_to do |format|
if @sub1_line_item.save
format.html { redirect_to @sub1_line_item, notice: 'Sub1 line item was successfully created.' }
format.json { render :show, status: :created, location: @sub1_line_item }
else
format.html { render :new }
format.json { render json: @sub1_line_item.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /sub1_line_items/1
# PATCH/PUT /sub1_line_items/1.json
def update
respond_to do |format|
if @sub1_line_item.update(sub1_line_item_params)
format.html { redirect_to @sub1_line_item, notice: 'Sub1 line item was successfully updated.' }
format.json { render :show, status: :ok, location: @sub1_line_item }
else
format.html { render :edit }
format.json { render json: @sub1_line_item.errors, status: :unprocessable_entity }
end
end
end
# DELETE /sub1_line_items/1
# DELETE /sub1_line_items/1.json
def destroy
@sub1_line_item.destroy
respond_to do |format|
format.html { redirect_to sub1_line_items_url, notice: 'Sub1 line item was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_sub1_line_item
@sub1_line_item = Sub1LineItem.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def sub1_line_item_params
params.require(:sub1_line_item).permit(:product_id, :sub1_category_id)
end
end
|
# frozen_string_literal: true
# rubocop:disable Metrics/MethodLength, Metrics/AbcSize, Style/SignalException
# Before running the script change the following constants to what you require
require 'net/http'
HOST = 'http://localhost:3000'
LEAGUE_ID = 6
MATCH_NOTICE_TEMPLATE = "\
Foo
"
ACTIVE_MATCH_NOTICE_TEMPLATE = "\
Bar `%{connect_string}`
"
SSC_API_KEY = 'ABC'
SSC_ENDPOINT = 'http://127.0.0.1:8080/api/v1'
MAX_MATCH_LENGTH = 8
MAP = Map.first
MATCH_PARAMS = {
round_name: '#1',
has_winner: true,
rounds_attributes: [{ map: MAP }],
}.freeze
def match_s(match)
if match.bye?
"#{match.home_team.name} BYE"
else
"#{match.home_team.name} VS #{match.away_team.name}"
end
end
def match_url(match)
Rails.application.routes.url_helpers.match_url(match, host: HOST)
end
def strip_rcon(connect_string)
connect, password, = connect_string.split(';')
[connect, password].join(';')
end
# Book a server using SSC
def book_server(user)
query = {
key: SSC_API_KEY,
user: user,
hours: MAX_MATCH_LENGTH,
}
result = Net::HTTP.post_form(URI.parse(SSC_ENDPOINT + "/bookings/?#{query.to_query}"), {})
json = JSON.parse result.body
if result.code != '200'
puts "Error: Failed booking for #{user}, #{json['statusMessage']}"
return nil
end
json['server']['connect-string']
end
# Unbook a server using SSC
def unbook_server(user)
query = {
key: SSC_API_KEY,
}
user_encoded = ERB::Util.url_encode user
uri = URI.parse(SSC_ENDPOINT + "/bookings/#{user_encoded}/?#{query.to_query}")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = uri.port == 443
request = Net::HTTP::Delete.new(uri.to_s)
result = http.request(request)
return if result.code == '204'
json = JSON.parse result.body
if result.code == '404' && json['statusMessage'] == 'Booking not found'
puts "Warning: Booking was not found for #{user}, ignoring"
return
end
puts "Error: Failed to unbook for #{user}, #{json['statusMessage']}"
fail
end
def book_servers
league = League.find(LEAGUE_ID)
# Unbook servers for completed matches
completed_matches = league.matches.confirmed.where.not(script_state: nil)
puts "Unbooking Servers (#{completed_matches.size})" unless completed_matches.empty?
completed_matches.find_each do |match|
user = match.script_state
unbook_server(user)
match.update!(script_state: nil)
puts "Unbooked: #{user} for #{match_s(match)} ; #{match_url(match)}"
end
# Book servers for pending matches
unbooked_matches = league.matches.pending.where(script_state: nil)
puts "Booking Servers (#{unbooked_matches.size})" unless unbooked_matches.empty?
unbooked_matches.find_each do |match|
user = match_s(match).sub(%r{/}, '') # Replace / since they break ssc (vibe.d workaround)
connect_string = book_server(user)
unless connect_string
puts 'Warning: No more available servers, stopping'
break
end
connect_string = strip_rcon connect_string
notice = format(ACTIVE_MATCH_NOTICE_TEMPLATE, connect_string: connect_string)
match.update!(script_state: user, notice: notice)
notify_users(match, 'The server for your match is now available')
puts "Booked: #{user} for #{match_s(match)} ; #{match_url(match)}"
end
end
def notify_users(match, message)
url = match_url(match)
users = match.home_team.users.union(match.away_team.users)
users.find_each do |user|
Users::NotificationService.call(user, message: message, link: url)
end
end
def generate(round)
league = League.find(LEAGUE_ID)
# The round should not exist
if league.matches.round(round).exists?
puts 'Error, round already exists'
return
end
# There should be no incomplete matches
pending_matches = league.matches.where.not(status: :confirmed)
unless pending_matches.empty?
puts 'Error, the following matches are pending:'
pending_matches.each do |match|
puts "#{match_s(match)} ; #{match_url(match)}"
end
return
end
puts 'Generating Matches'
league.divisions.each do |division|
match_params = { round_number: round, notice: MATCH_NOTICE_TEMPLATE }.merge(MATCH_PARAMS)
invalid = Leagues::Matches::GenerationService.call(division, match_params, :single_elimination, round: round)
if invalid
p invalid.errors
fail
end
puts "Created Matches for #{division.name}:"
division.matches.round(round).find_each do |match|
puts "#{match_s(match)} ; #{match_url(match)}"
end
end
end
fail 'Invalid Arguments' if ARGV.empty?
ActiveRecord::Base.transaction do
case ARGV[0]
when 'generate'
generate(ARGV[1].to_i)
when 'book'
book_servers
else
fail 'Invalid Command'
end
end
# rubocop:enable Metrics/MethodLength, Metrics/AbcSize, Style/SignalException
|
class SalesController < ApplicationController
def show
end
def create
logger.debug ">>> #{params}"
@sale = SaleService.new(current_user).create!(params)
respond_to do |format|
if @sale.persisted?
format.json { render json: @sale.as_json, status: :created }
else
format.json { render json: @sale.errors, status: :unprocessable_entity }
end
end
end
def report
start_date = params[:start_date].to_date
end_date = params[:end_date].to_date
point_of_sale_id = params[:id].to_i
@sales = SaleService.new(current_user).report(start_date, end_date, point_of_sale_id)
end
def grouped_report
start_date = params[:start_date].to_date
end_date = params[:end_date].to_date
point_of_sale_id = params[:id].to_i
@sales_groups = SaleService.new(current_user).grouped_report(start_date, end_date, point_of_sale_id)
end
end
|
require 'json'
module LanguageHelper
def get_response_from uri
Net::HTTP.get_response(URI(uri))
end
def parse_response response
JSON.parse(response.body)
end
def get_repos uri
response = get_response_from uri
return parse_response response if !response.message.include? "Not Found"
false
end
def get_array_of_languages repos
languages = repos.map {|repo| repo['language'] }
languages.delete_if { |lang| lang.nil? }
end
def calculate_favourite languages
counter = Hash.new(0)
languages.each { |i| counter[i] += 1 }
favourite_languages = []
counter.each { |k, v| favourite_languages << k if v == counter.values.max }
favourite_languages.join(", ")
end
def get_favourite_language_of user
uri = "https://api.github.com/users/#{user}/repos"
user_repos = get_repos uri
return "not available because the user does not exist" if !user_repos
languages = get_array_of_languages user_repos
return "not able to be calculated" if languages.empty?
return calculate_favourite languages
end
end |
# encoding: utf-8
#
unsuccessful_attempts = attribute('unsuccessful_attempts', value: 3,
description: 'The account is denied access after the specified number of
consecutive failed logon attempts.')
fail_interval = attribute('fail_interval', value: 900,
description: 'The interval of time in which the consecutive failed logon
attempts must occur in order for the account to be locked out (in seconds).')
lockout_time = attribute('lockout_time', value: 604800,
description: 'The minimum amount of time that an account must be locked out
after the specified number of unsuccessful logon attempts (in seconds).
This attribute should never be set greater than 604800.')
control "V-71943" do
title "The Red Hat Enterprise Linux operating system must be configured to lock accounts for a minimum of 15 minutes after three unsuccessful logon attempts within a 15-minute timeframe."
desc "By limiting the number of failed logon attempts, the risk of
unauthorized system access via user password guessing, otherwise known as
brute-forcing, is reduced. Limits are imposed by locking the account."
impact 0.5
tag "check": 'Check that the system locks an account for a minimum of 15 minutes after three unsuccessful logon attempts within a period of 15 minutes with the following command:
# grep pam_faillock.so /etc/pam.d/password-auth
auth required pam_faillock.so preauth silent audit deny=3 even_deny_root fail_interval=900 unlock_time=900
auth [default=die] pam_faillock.so authfail audit deny=3 even_deny_root fail_interval=900 unlock_time=900
account required pam_faillock.so
If the "deny" parameter is set to "0" or a value less than "3" on both "auth" lines with the "pam_faillock.so" module, or is missing from these lines, this is a finding.
If the "even_deny_root" parameter is not set on both "auth" lines with the "pam_faillock.so" module, or is missing from these lines, this is a finding.
If the "fail_interval" parameter is set to "0" or is set to a value less than "900" on both "auth" lines with the "pam_faillock.so" module, or is missing from these lines, this is a finding.
If the "unlock_time" parameter is not set to "0", "never", or is set to a value less than "900" on both "auth" lines with the "pam_faillock.so" module, or is missing from these lines, this is a finding.
Note: The maximum configurable value for "unlock_time" is "604800".
If any line referencing the "pam_faillock.so" module is commented out, this is a finding.
# grep pam_faillock.so /etc/pam.d/system-auth
auth required pam_faillock.so preauth silent audit deny=3 even_deny_root fail_interval=900 unlock_time=900
auth [default=die] pam_faillock.so authfail audit deny=3 even_deny_root fail_interval=900 unlock_time=900
account required pam_faillock.so
If the "deny" parameter is set to "0" or a value less than "3" on both "auth" lines with the "pam_faillock.so" module, or is missing from these lines, this is a finding.
If the "even_deny_root" parameter is not set on both "auth" lines with the "pam_faillock.so" module, or is missing from these lines, this is a finding.
If the "fail_interval" parameter is set to "0" or is set to a value less than "900" on both "auth" lines with the "pam_faillock.so" module, or is missing from these lines, this is a finding.
If the "unlock_time" parameter is not set to "0", "never", or is set to a value less than "900" on both "auth" lines with the "pam_faillock.so" module or is missing from these lines, this is a finding.
Note: The maximum configurable value for "unlock_time" is "604800".
If any line referencing the "pam_faillock.so" module is commented out, this is a finding.'
tag "fix": "Configure the operating system to lock an account for the maximum
period when three unsuccessful logon attempts in 15 minutes are made.
Modify the first three lines of the auth section of the
\"/etc/pam.d/system-auth-ac\" and \"/etc/pam.d/password-auth-ac\" files to
match the following lines:
auth required pam_faillock.so preauth silent audit deny=3 even_deny_root fail_interval=900 unlock_time=604800
auth sufficient pam_unix.so try_first_pass
auth [default=die] pam_faillock.so authfail audit deny=3 even_deny_root fail_interval=900 unlock_time=604800
account required pam_faillock.so"
required_rules = [
'auth required pam_faillock.so unlock_time=.*',
'auth sufficient pam_unix.so try_first_pass',
'auth [default=die] pam_faillock.so unlock_time=.*'
]
alternate_rules = [
'auth required pam_faillock.so unlock_time=.*',
'auth sufficient pam_sss.so forward_pass',
'auth sufficient pam_unix.so try_first_pass',
'auth [default=die] pam_faillock.so unlock_time=.*'
]
describe pam('/etc/pam.d/password-auth') do
its('lines') {
should match_pam_rules(required_rules).exactly.or \
match_pam_rules(alternate_rules).exactly
}
its('lines') { should match_pam_rule('auth [default=die]|required pam_faillock.so').all_with_integer_arg('deny', '<=', unsuccessful_attempts) }
its('lines') { should match_pam_rule('auth [default=die]|required pam_faillock.so').all_with_integer_arg('fail_interval', '<=', fail_interval) }
its('lines') {
should match_pam_rule('auth [default=die]|required pam_faillock.so').all_with_args('unlock_time=(0|never)').or \
(match_pam_rule('auth [default=die]|required pam_faillock.so').all_with_integer_arg('unlock_time', '<=', 604800).and \
match_pam_rule('auth [default=die]|required pam_faillock.so').all_with_integer_arg('unlock_time', '>=', lockout_time))
}
end
describe pam('/etc/pam.d/system-auth') do
its('lines') {
should match_pam_rules(required_rules).exactly.or \
match_pam_rules(alternate_rules).exactly
}
its('lines') { should match_pam_rule('auth [default=die]|required pam_faillock.so').all_with_integer_arg('deny', '<=', unsuccessful_attempts) }
its('lines') { should match_pam_rule('auth [default=die]|required pam_faillock.so').all_with_integer_arg('fail_interval', '<=', fail_interval) }
its('lines') {
should match_pam_rule('auth [default=die]|required pam_faillock.so').all_with_args('unlock_time=(0|never)').or \
(match_pam_rule('auth [default=die]|required pam_faillock.so').all_with_integer_arg('unlock_time', '<=', 604800).and \
match_pam_rule('auth [default=die]|required pam_faillock.so').all_with_integer_arg('unlock_time', '>=', lockout_time))
}
end
end
|
require 'spec_helper'
describe RubyKong::Node do
before(:each) do
require 'webmock'
include WebMock::API
RubyKong.new(RubyKong.mockurl)
end
after(:each) do
RubyKong::Stub.reopen_real_connection!
end
it 'should have generic infomation (/)' do
# Mock with / path
url = RubyKong::Utils.endpoint_builder(RubyKong.paths[:node][:info])
RubyKong::Stub.request(
:method => :get,
:url => url,
:response => {
:body => {
'version' => '0.7.0',
'lua_version' => 'LuaJIT 2.1.0-beta1',
'tagline' => 'Welcome to Kong',
'hostname' => '8b173da56e6'
}.to_s
}
)
node_info = RubyKong::Node.info
expect(node_info.body).to include('version')
expect(node_info.code).to equal(200)
end
it 'should have usage information about this node (/status)' do
# Mock with /status path
url = RubyKong::Utils.endpoint_builder(RubyKong.paths[:node][:status])
RubyKong::Stub.request(
:method => :get,
:url => url,
:response => {
:body => {
"server" => {
"connections_handled" => 2757,
"connections_reading" => 0,
"connections_active" => 1,
"connections_waiting" => 0,
"connections_writing" => 1,
"total_requests" => 2757,
"connections_accepted" => 2757
},
"database" => {
"response_ratelimiting_metrics" => 0,
"keyauth_credentials" => 0,
"apis" => 0,
"consumers" => 0,
"plugins" => 0,
"nodes" => 1,
"basicauth_credentials" => 0,
"ratelimiting_metrics" => 0
}
}.to_s
}
)
node_status = RubyKong::Node.status
expect(node_status.body).to include('total_requests')
expect(node_status.code).to equal(200)
end
end
|
require 'pry'
class CashRegister
attr_accessor :total, :discount, :price, :items, :last_transaction, :title
def initialize(discount=0) #optionally takes an employee discount on initialization
@items = []
@total = 0 #sets an instance variable @total on initialization to zero
@discount = discount
end
def total
@total
end
def add_item(title,price,quantity=1)
@title = title
@price = price
@quantity = quantity
@total += price * quantity
@last_transaction = @total
if quantity > 1
counter = 0
while counter < quantity
@items << title
counter += 1
end
else
@items << title
end
@last_transaction = @total
@total
end
def apply_discount
if discount > 0
new_price = (price*discount)/100
@total -= new_price
"After the discount, the total comes to $#{@total}."
else
"There is no discount to apply."
end
end
def void_last_transaction
@total -= @price*@quantity
end
|
require 'rails_helper'
RSpec.describe UsersController, type: :request do
describe 'GET users#index' do
it 'shows list of all users' do
create_list(:random_user, 7)
visit users_path
expect(page).to have_selector('li', count: 7)
end
it 'sorts users by number of reviews' do
movie = create(:random_movie)
user_with_no_reviews = create(:random_user)
user_with_many_reviews = create(:random_user)
create_list(:random_review, 10, movie: movie, user: user_with_many_reviews)
visit users_path
expect(page).to have_selector('li:first-child', text: user_with_many_reviews.name)
end
end
describe 'GET users#show' do
before(:each) do
@user = create(:random_user)
@good_movie = create(:random_movie)
@bad_movie = create(:random_movie)
create(:random_review, rating: 5, user: @user, movie: @good_movie)
create(:random_review, rating: 1, user: @user, movie: @bad_movie)
visit user_path(@user)
end
it 'shows individual user' do
expect(page).to have_content(@user.name)
end
it "shows all user's reviews" do
expect(page).to have_selector('.review', count: 2)
end
it "shows user's favorite movies" do
expect(page).to have_selector('#favorite li:first-child', text: @good_movie.title)
end
it "shows user's least favorite movies" do
expect(page).to have_selector('#least_favorite li:first-child', text: @bad_movie.title)
end
end
end
|
class ReportPolicy < ApplicationPolicy
attr_reader :user, :record
def index?
true
end
def show?
return true if beis_user?
return true if record.organisation == user.organisation
false
end
def create?
beis_user?
end
def edit?
update?
end
def update?
beis_user?
end
def destroy?
false
end
def change_state?
case record.state
when "active"
partner_organisation_user? && record.organisation == user.organisation
when "submitted"
beis_user?
when "in_review"
beis_user?
when "awaiting_changes"
partner_organisation_user? && record.organisation == user.organisation
when "qa_completed"
beis_user?
when "approved"
false
end
end
def upload?
record.editable? && record.organisation == user.organisation
end
def upload_history?
return true if beis_user? && record.editable?
false
end
def download?
show?
end
def activate?
false
end
def submit?
return change_state? if record.editable?
end
def review?
return change_state? if record.state == "submitted"
end
def request_changes?
return change_state? if %w[in_review qa_completed].include?(record.state)
end
def mark_qa_completed?
return change_state? if record.state == "in_review"
end
def approve?
return change_state? if record.state == "qa_completed"
end
class Scope < Scope
def resolve
if user.organisation.service_owner?
scope.all
else
scope.where(organisation: user.organisation)
end
end
end
end
|
require_relative '../lib/huckleberry/log_duplicate_checker'
require_relative '../helpers/spec_helper'
RSpec.describe Huckleberry::LogDuplicateChecker do
dupe_lines_array = [
%q(41),
%q(I, [2015-08-10T09:23:43.019875 #72657] INFO -- : (0.000511s) INSERT INTO "users" ("email", "encrypted_password", "created_at", "identifier") VALUES ('superman@example.com', '$2a$10$3Rg.dbuPccSDJ/C3WkXH0OhlIAIY00/zoHINaSKIxrTzuYhd5Qf3C', '2015-08-10 09:23:43.017301-0700', 'd5ab2eef-4766-4f08-8efa-2a693d4bd522') RETURNING *),
%q(90),
%q(I, [2015-08-10T09:23:43.163084 #72657] INFO -- : (0.000267s) SELECT "roles".* FROM "roles" INNER JOIN "memberships" ON ("memberships"."role_id" = "roles"."id") WHERE ("memberships"."user_id" = 1)),
%q(172),
%q(I, [2015-08-10T09:23:43.347131 #72657] INFO -- : Started GET "/unauthenticated" for 127.0.0.1 at 2015-08-10 09:23:43 -0700)
]
let(:logfile_path) {'spec/fixtures/test.log'}
subject { Huckleberry::LogDuplicateChecker.new(logfile_path) }
it 'will create a LogDuplicateChecker object' do
expect(subject).to be_a_kind_of Huckleberry::LogDuplicateChecker
end
describe '#duplicate_check' do
let(:logfile_path) {'spec/fixtures/dupe_test.log'}
it 'will return all duplicated lines' do
expect(subject.duplicate_check).to eq(dupe_lines_array)
end
end
end
|
require 'active_support/concern'
module SmoochNewsletter
extend ActiveSupport::Concern
module ClassMethods
def user_is_subscribed_to_newsletter?(uid, language, team_id)
TiplineSubscription.where(uid: uid, language: language, team_id: team_id).exists?
end
def toggle_subscription(uid, language, team_id, platform, workflow)
s = TiplineSubscription.where(uid: uid, language: language, team_id: team_id).last
CheckStateMachine.new(uid).reset
if s.nil?
TiplineSubscription.create!(uid: uid, language: language, team_id: team_id, platform: platform)
self.send_final_message_to_user(uid, self.subscription_message(uid, language, true, false), workflow, language)
else
s.destroy!
self.send_final_message_to_user(uid, self.subscription_message(uid, language, false, false), workflow, language)
end
self.clear_user_bundled_messages(uid)
end
def get_newsletter(team_id, language)
TiplineNewsletter.where(team_id: team_id, language: language).last
end
end
end
|
#This is drop script, when you try to break something
#To use it first set id to anything you want like this (in event on map):
#Block.get(yourId)
#Now you have to configurate all your drops here in dropConfiguration
#And to make it work in class Main after line begin add Drop_Main.new
#And to run it from event on map use Block.get(yourId).mine
#Author Jatti
class Drop_Main
def initialize
dropConfiguration()
end
#To configurate drops you have to add new line like this:
#addDrop(whatCanMine, chance, isExp, item, blockId)
#whatCanMine - id of tool with which you can drop this
#chance - chance of drop
#isExp - if true, it will drop exp and next field #item will be amount of dropped exp
#item - what item will drop
#blockId - id which you set by using Block.get(id)
def dropConfiguration()
#This adds (for me) drop which can be mined by brone shield, with chance 20%,
#on block with id 1, and will drop potion
addDrop(1, 40, false, 1, 1)
addDrop(1, 40, true, 1, 1)
end
def addDrop(whatCanMine, chance, isExp, item, blockId)
Stone_Drop.new(whatCanMine, chance, isExp, item, blockId)
end
end |
class GameRoomsController < ApplicationController
def new
@gameroom = GameRoom.new
@roomcode = ""
numbers = %W[1 2 3 4 5 6 7 8 9 0]
5.times do
@roomcode += numbers.sample
end
end
def create
@gameroom = GameRoom.new(gameroom_params)
@gameroom.user_rooms.first.user = current_user
@gameroom.user_rooms.first.owner = true
@gameroom.save
redirect_to root_path
end
def show
@gameroom = GameRoom.find(params[:id])
swipes = Swipe.where(user: current_user, game_room: @gameroom)
@movies = Movie.where(genres: @gameroom.genres)
.where.not(id: swipes.pluck(:movie_id))
end
private
def gameroom_params
params.require(:game_room).permit(:roomcode, user_rooms_attributes: [
genre_ids: []
])
end
end
|
FactoryBot.define do
factory :food do
name { Faker::Name }
explain { 'aaa' }
association :user
association :shop
after(:build) do |food|
food.image.attach(io: File.open('public/images/test_img.png'), filename: 'test_img.png')
end
end
end
|
GraphQL::Field.accepts_definitions(
##
# Define how to get from an edge Active Record model to the node Active Record model
connection_properties: GraphQL::Define.assign_metadata_key(:connection_properties),
##
# Define a resolver for connection edges records
resolve_edges: GraphQL::Define.assign_metadata_key(:resolve_edges),
##
# Define a resolver for connection nodes records
resolve_nodes: GraphQL::Define.assign_metadata_key(:resolve_nodes),
##
# Internally used to mark a connection type that has a fetched edge
_includable_connection_marker: GraphQL::Define.assign_metadata_key(:_includable_connection_marker)
)
module GraphQLIncludable
module Relay
class EdgeWithNode < GraphQL::Relay::Edge
def initialize(node, connection)
@edge = node
@edge_to_node = ->() { connection.edge_to_node(@edge) }
super(nil, connection)
end
def node
@node ||= @edge_to_node.call
@node
end
def method_missing(method_name, *args, &block)
if @edge.respond_to?(method_name)
@edge.send(method_name, *args, &block)
else
super
end
end
def respond_to_missing?(method_name, include_private = false)
@edge.respond_to?(method_name) || super
end
end
end
end
|
require 'rspec'
require_relative '../r2point'
describe R2Point do
EPS = 1.0e-12
context "Расстояние dist" do
it "от точки до самой себя равно нулю" do
a = R2Point.new(1.0,1.0)
expect(a.dist(R2Point.new(1.0,1.0))).to be_within(EPS).of(0.0)
end
it "от одной точки до отличной от неё другой положительно" do
a = R2Point.new(1.0,1.0)
expect(a.dist(R2Point.new(1.0,0.0))).to be_within(EPS).of(1.0)
expect(a.dist(R2Point.new(0.0,0.0))).to be_within(EPS).of(Math.sqrt(2.0))
end
end
context "Площадь area" do
let(:a) { R2Point.new(0.0,0.0) }
let(:b) { R2Point.new(1.0,-1.0) }
let(:c) { R2Point.new(2.0,0.0) }
it "равна нулю, если все вершины совпадают" do
expect(R2Point.area(a,a,a)).to be_within(EPS).of(0.0)
end
it "равна нулю, если вершины лежат на одной прямой" do
b = R2Point.new(1.0,0.0)
expect(R2Point.area(a,b,c)).to be_within(EPS).of(0.0)
end
it "положительна, если обход вершин происходит против часовой стрелки" do
expect(R2Point.area(a,b,c)).to be_within(EPS).of(1.0)
end
it "отрицательна, если обход вершин происходит по часовой стрелки" do
expect(R2Point.area(a,c,b)).to be_within(EPS).of(-1.0)
end
end
context "inside? для прямоугольника с вершинами (0,0) и (2,1) утверждает:" do
let(:a) { R2Point.new(0.0,0.0) }
let(:b) { R2Point.new(2.0,1.0) }
it "точка (1,0.5) внутри" do
expect(R2Point.new(1.0,0.5).inside?(a,b)).to be true
end
it "точка (1,0.5) внутри" do
expect(R2Point.new(1.0,0.5).inside?(b,a)).to be true
end
it "точка (1,1.5) снаружи" do
expect(R2Point.new(1.0,1.5).inside?(a,b)).to be false
end
it "точка (1,1.5) снаружи" do
expect(R2Point.new(1.0,1.5).inside?(b,a)).to be false
end
end
context "light? для ребра с вершинами (0,0) и (1,0) утверждает:" do
let(:a) { R2Point.new(0.0,0.0) }
let(:b) { R2Point.new(1.0,0.0) }
it "из точки (0.5,0.0) оно не освещено" do
expect(R2Point.new(0.5,0.0).light?(a,b)).to be false
end
it "из точки (0.5,-0.5) оно освещено" do
expect(R2Point.new(0.5,-0.5).light?(a,b)).to be true
end
it "из точки (2.0,0.0) оно освещено" do
expect(R2Point.new(2.0,0.0).light?(a,b)).to be true
end
it "из точки (0.5,0.5) оно не освещено" do
expect(R2Point.new(0.5,0.5).light?(a,b)).to be false
end
it "из точки (-1.0,0.0) оно освещено" do
expect(R2Point.new(-1.0,0.0).light?(a,b)).to be true
end
end
end
|
class Wms::MapController < Wms::BaseController
def generate_wms
@map = Map.find(params[:id])
#status is additional query param to show the unwarped wms
status = params["STATUS"].to_s.downcase || "unwarped"
ows.setParameter("COVERAGE", "image")
rel_url_root = (ActionController::Base.relative_url_root.blank?)? '' : ActionController::Base.relative_url_root
map.setMetaData("wms_onlineresource",
"http://" + request.host_with_port + rel_url_root + "/maps/wms/#{@map.id}")
if status == "unwarped"
raster.data = @map.unwarped_filename
else #show the warped map
raster.data = @map.warped_filename
end
raster.status = Mapscript::MS_ON
raster.dump = Mapscript::MS_TRUE
raster.metadata.set('wcs_formats', 'GEOTIFF')
raster.metadata.set('wms_title', @map.title)
raster.metadata.set('wms_srs', 'EPSG:4326 EPSG:3857 EPSG:4269 EPSG:900913')
#raster.debug = Mapscript::MS_TRUE
raster.setProcessingKey("CLOSE_CONNECTION", "ALWAYS")
send_map_data map, ows
end
end
|
require File.join(File.dirname(__FILE__), 'spec_helper')
require 'barby/barcode/ean_13'
include Barby
describe EAN13, ' validations' do
before :each do
@valid = EAN13.new('123456789012')
end
it "should be valid with 12 digits" do
@valid.should be_valid
end
it "should not be valid with non-digit characters" do
@valid.data = "The shit apple doesn't fall far from the shit tree"
@valid.should_not be_valid
end
it "should not be valid with less than 12 digits" do
@valid.data = "12345678901"
@valid.should_not be_valid
end
it "should not be valid with more than 12 digits" do
@valid.data = "1234567890123"
@valid.should_not be_valid
end
it "should raise an exception when data is invalid" do
lambda{ EAN13.new('123') }.should raise_error(ArgumentError)
end
end
describe EAN13, ' data' do
before :each do
@data = '007567816412'
@code = EAN13.new(@data)
end
it "should have the same data as was passed to it" do
@code.data.should == @data
end
it "should have the expected characters" do
@code.characters.should == @data.split(//)
end
it "should have the expected numbers" do
@code.numbers.should == @data.split(//).map{|s| s.to_i }
end
it "should have the expected odd_and_even_numbers" do
@code.odd_and_even_numbers.should == [[2,4,1,7,5,0], [1,6,8,6,7,0]]
end
it "should have the expected left_numbers" do
#0=second number in number system code
@code.left_numbers.should == [0,7,5,6,7,8]
end
it "should have the expected right_numbers" do
@code.right_numbers.should == [1,6,4,1,2,5]#5=checksum
end
it "should have the expected numbers_with_checksum" do
@code.numbers_with_checksum.should == @data.split(//).map{|s| s.to_i } + [5]
end
it "should have the expected data_with_checksum" do
@code.data_with_checksum.should == @data+'5'
end
end
describe EAN13, ' checksum' do
before :each do
@code = EAN13.new('007567816412')
end
it "should have the expected weighted_sum" do
@code.weighted_sum.should == 85
@code.data = '007567816413'
@code.weighted_sum.should == 88
end
it "should have the correct checksum" do
@code.checksum.should == 5
@code.data = '007567816413'
@code.checksum.should == 2
end
it "should have the correct checksum_encoding" do
@code.checksum_encoding.should == '1001110'
end
end
describe EAN13, ' encoding' do
before :each do
@code = EAN13.new('750103131130')
end
it "should have the expected checksum" do
@code.checksum.should == 9
end
it "should have the expected checksum_encoding" do
@code.checksum_encoding.should == '1110100'
end
it "should have the expected left_parity_map" do
@code.left_parity_map.should == [:odd, :even, :odd, :even, :odd, :even]
end
it "should have the expected left_encodings" do
@code.left_encodings.should == %w(0110001 0100111 0011001 0100111 0111101 0110011)
end
it "should have the expected right_encodings" do
@code.right_encodings.should == %w(1000010 1100110 1100110 1000010 1110010 1110100)
end
it "should have the expected left_encoding" do
@code.left_encoding.should == '011000101001110011001010011101111010110011'
end
it "should have the expected right_encoding" do
@code.right_encoding.should == '100001011001101100110100001011100101110100'
end
it "should have the expected encoding" do
#Start Left Center Right Stop
@code.encoding.should == '101' + '011000101001110011001010011101111010110011' + '01010' + '100001011001101100110100001011100101110100' + '101'
end
end
describe EAN13, 'static data' do
before :each do
@code = EAN13.new('123456789012')
end
it "should have the expected start_encoding" do
@code.start_encoding.should == '101'
end
it "should have the expected stop_encoding" do
@code.stop_encoding.should == '101'
end
it "should have the expected center_encoding" do
@code.center_encoding.should == '01010'
end
end
|
class ApplicationController < ActionController::API
include DeviseTokenAuth::Concerns::SetUserByToken
include ActionController::Serialization
rescue_from ActiveRecord::RecordNotFound, with: :record_not_found_rescue
rescue_from ActiveRecord::RecordInvalid, with: :record_invalid_rescue
def record_not_found_rescue(exception)
logger.info("#{exception.class}: " + exception.message)
render json: {message: "Record not found."}, status: :not_found
end
def record_invalid_rescue(exception)
render json: {message: "The given data is incorrect."}, status: 422
end
end
|
require 'vanagon/engine/pooler'
require 'vanagon/platform'
describe 'Vanagon::Engine::Pooler' do
let (:platform) { double(Vanagon::Platform, :target_user => 'root', :ssh_port => 22) }
let (:platform_with_vcloud_name) {
plat = Vanagon::Platform::DSL.new('debian-6-i386')
plat.instance_eval("platform 'debian-6-i386' do |plat|
plat.vmpooler_template 'debian-6-i386'
end")
plat._platform
}
let (:platform_without_vcloud_name) {
plat = Vanagon::Platform::DSL.new('debian-6-i386')
plat.instance_eval("platform 'debian-6-i386' do |plat|
end")
plat._platform
}
before :each do
# suppress `#warn` output during tests
allow_any_instance_of(Vanagon::Platform::DSL).to receive(:warn)
# stubbing ENV doesn't actually intercept ENV because ENV
# is special and you aren't. So we have to mangle the value
# of ENV around each of these tests if we want to prevent
# actual user credentials from being loaded, or attempt to
# validate the way that credentials are read.
ENV['REAL_HOME'] = ENV.delete 'HOME'
ENV['REAL_VMPOOLER_TOKEN'] = ENV.delete 'VMPOOLER_TOKEN'
ENV['HOME'] = Dir.mktmpdir
# This should help maintain the ENV['HOME'] masquerade
allow(Dir).to receive(:home).and_return(ENV['HOME'])
end
after :each do
# Altering ENV directly is a legitimate code-smell.
# We should at least clean up after ourselves.
ENV['HOME'] = ENV.delete 'REAL_HOME'
ENV['VMPOOLER_TOKEN'] = ENV.delete 'REAL_VMPOOLER_TOKEN'
end
# We don't want to run the risk of reading legitimate user
# data from a user who is unfortunate enough to be running spec
# tests on their local machine. This means we have to intercept
# and stub out a very specific environment, where:
# 1) an environment variable exists
# 2) the env. var is unset, and only a ~/.vmpooler-token file exists
# 3) the env. var is unset, and only a ~/.vmfloaty.yml file exists
describe "#load_token" do
let(:environment_value) { 'cafebeef' }
let(:token_value) { 'decade' }
let(:pooler_token_file) { File.expand_path('~/.vanagon-token') }
let(:floaty_config) { File.expand_path('~/.vmfloaty.yml') }
it 'prefers the VMPOOLER_TOKEN environment variable to a config file' do
allow(ENV).to receive(:[])
.with('VMPOOLER_TOKEN')
.and_return(environment_value)
expect(Vanagon::Engine::Pooler.new(platform).token)
.to_not eq(token_value)
expect(Vanagon::Engine::Pooler.new(platform).token)
.to eq(environment_value)
end
it %(reads a token from '~/.vanagon-token' if the environment variable is not set) do
allow(File).to receive(:exist?)
.with(pooler_token_file)
.and_return(true)
allow(File).to receive(:read)
.with(pooler_token_file)
.and_return(token_value)
expect(Vanagon::Engine::Pooler.new(platform).token)
.to eq(token_value)
end
it %(reads a token from '~/.vmfloaty.yml' if '~/.vanagon-token' doesn't exist) do
allow(File).to receive(:exist?)
.with(pooler_token_file)
.and_return(false)
allow(File).to receive(:exist?)
.with(floaty_config)
.and_return(true)
allow(YAML).to receive(:load_file)
.with(floaty_config)
.and_return({'token' => token_value})
expect(Vanagon::Engine::Pooler.new(platform).token).to eq(token_value)
end
it %(returns 'nil' if no vmpooler token configuration exists) do
allow(File).to receive(:exist?)
.with(pooler_token_file)
.and_return(false)
allow(File).to receive(:exist?)
.with(floaty_config)
.and_return(false)
expect(Vanagon::Engine::Pooler.new(platform).token).to be_nil
end
end
describe "#validate_platform" do
it 'raises an error if the platform is missing a required attribute' do
expect{ Vanagon::Engine::Pooler.new(platform_without_vcloud_name).validate_platform }.to raise_error(Vanagon::Error)
end
it 'returns true if the platform has the required attributes' do
expect(Vanagon::Engine::Pooler.new(platform_with_vcloud_name).validate_platform).to be(true)
end
end
it 'returns "pooler" name' do
expect(Vanagon::Engine::Pooler.new(platform_with_vcloud_name).name).to eq('pooler')
end
end
|
require 'rails_helper'
describe "FilterOrganizations", type: :model do
it "returns all organizations when no eligibilities are passed" do
organization = FactoryGirl.create(:organization)
organizations = FilterOrganizations.new({organizations: [organization]}).call
expect(organizations.length).to be(1)
expect(organizations).to include(organization)
end
it "filter includes organizations with selected elegibilities" do
eligibility = FactoryGirl.create(:eligibility)
other_eligibility = FactoryGirl.create(:eligibility, :update_name)
organization = FactoryGirl.create(:organization, eligibilities: [eligibility])
other_organization = FactoryGirl.create(:organization, eligibilities: [other_eligibility])
excluded_organization = FactoryGirl.create(:organization)
organizations = FilterOrganizations.new({organizations: [organization, other_organization], eligibilities: [eligibility.name, other_eligibility.name], query_type: "inclusive"}).call
expect(organizations.length).to be(2)
expect(organizations).to include(organization)
expect(organizations).to include(other_organization)
expect(organizations).not_to include(excluded_organization)
end
it "filter excludes organizations without selected eligibilities" do
eligibility = FactoryGirl.create(:eligibility)
other_eligibility = FactoryGirl.create(:eligibility, :update_name)
organization = FactoryGirl.create(:organization, eligibilities: [eligibility, other_eligibility])
other_organization = FactoryGirl.create(:organization, eligibilities: [other_eligibility])
organizations = FilterOrganizations.new({organizations: [organization, other_organization], eligibilities: [eligibility.name, other_eligibility.name]}).call
expect(organizations.length).to be(1)
expect(organizations).to include(organization)
expect(organizations).not_to include(other_organization)
end
end
|
FactoryGirl.define do
factory :page_folder do
title 'Test folder'
name 'test-folder'
path '/test-folder'
root_folder_id 1
factory :root_page_folder do
id 1
title 'Site'
name '/'
path '/'
root_folder_id nil
end
end
end
|
module ApplicationHelper
def current_user
@current_user ||= User.find_by(session_token: session[:session_token])
end
def logged_in?
!!current_user
end
def csrf_token
"<input type=\"hidden\"
name=\"authenticity_token\"
value=\"#{form_authenticity_token}\" >".html_safe
end
end
|
namespace :cleanup do
task :move_files => :environment do
files = FileDocument.all
puts "#{files.length} file records to process."
saved = 0
files.each do |file|
saved +=1 if file.save_to_disk
end
puts "Processed #{files.length} records. Saved #{saved} files."
end
task :check_files_exist => :environment do
files = FileDocument.all
puts "#{files.length} file records to process."
found=0
files.each do |file|
if file.blank?
puts "file is blank. Shouldn't ever happen"
elsif file.file.blank?
puts "file model in FileDocument is empty. id: #{file.id}."
elsif file.file.path.blank?
puts "file path in FileDocument is empty. id: #{file.id}. file_file_name: #{file.file_file_name}."
elsif ! File.exist?(file.file.path)
puts "file does not exist. id: #{file.id}; name: #{file.file_file_name}"
else
found+=1
end
end
puts "Processed #{files.length} records. Found #{found} files."
end
end |
class AlbumsController < ApplicationController
def new
@album = Album.new
end
def create
@album = Album.new(album_params)
if @album.save
flash[:success] = "Genero inserido com sucesso!"
render 'new'
else
flash[:danger] = "Algo deu errado! Tente novamente"
render 'new'
end
end
def index
@albums=Album.find_each
end
private
def album_params
params.require(:albums).permit(:name, :ano,:artists_id)
end
end |
module Integrations
module AwardWallet
class Settings < Trailblazer::Operation
step :set_user
step :user_loaded?
failure :log_not_connected
step :set_owners_with_accounts
step :eager_load_people
private
def set_user(opts, current_account:, **)
opts['user'] = current_account.award_wallet_user
end
def user_loaded?(user:, **)
# Without the timeout, you sometimes get a weird bug where the BG job
# loads the user, the polling script redirects to the settings page,
# and this operation loads the user again... but the user is unloaded,
# so the operation fails and the user gets redirects to /balances
# without ever seeing the AW page. I suspect this is something to
# do with threading, but I don't know enough to investigate further.
#
# This crude approach using `sleep` works for now.
Timeout.timeout(5) do
sleep 1 until user.reload.loaded?
true
end
rescue Timeout::Error
false
end
def log_not_connected(opts)
opts['error'] = 'not connected'
end
def set_owners_with_accounts(opts, user:, **)
opts['owners'] = user.award_wallet_owners.includes(:person, award_wallet_accounts: :award_wallet_owner).order(name: :asc)
end
def eager_load_people(current_account:, **)
# Make sure people are loaded here so that the cell doesn't touch the
# DB. Note that in previous versions of Rails this would have been
# written as `current_account.people(true)`, but that's now deprecated.
current_account.people.reload
end
end
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)
puts "Populating Countries..."
Country.delete_all
open("db/seeds/countries.txt") do |countries|
countries.read.each_line do |country|
code, name = country.chomp.split("|")
Country.create!(:name => name, :code => code)
end
end
puts "Populating User types..."
UserType.delete_all
open("db/seeds/user_types.txt") do |types|
types.read.each_line do |t|
name, can_login = t.chomp.split("|")
UserType.create!(:name => name, :can_login => can_login)
end
end
|
#Question 32 -- find two missing number
#assumption -- array has size n, with numbers from 1..n
def missing_numbers(arr)
result = []
return result if arr == nil ||arr.empty?
1.upto(arr.length + 2) do |num|
result << num unless arr.include? num
end
return result
end
|
class Hand
def initialize
@cards = []
end
def add(*cards)
@cards += cards
end
def to_s
@cards.map { |card| card.to_s }.join(", ")
# or
# names = []
# @cards.each { |card| names << card.to_s }
# names.join(", ")
end
def showing
@cards[1..-1].map { |card| card.to_s }.join
end
def value
# Add up base values
total, aces = 0, 0
@cards.each do |card|
total += card.value
aces += 1 if card.rank == :A
end
# Now promote aces if we have any
while total <= 11 && aces > 0
total += 10
aces -= 1
end
total
end
def blackjack?
@cards.count == 2 && value == 21
end
def busted?
value > 21
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.