text stringlengths 10 2.61M |
|---|
class CreateUserInks < ActiveRecord::Migration
def change
create_table :user_inks do |t|
t.belongs_to :ink, null: false
t.belongs_to :user, null: false
t.string :color_family
t.boolean :is_cartridge, null: false, default: false
t.boolean :is_bottled, null: false, default: false
t.string :cartridge_size
t.integer :bottle_size
t.text :notes
end
end
end
|
module Rooms
class FindGuests
include Interactor
delegate :room, to: :context
def call
context.guests = context.room.guests
end
end
end
|
Given /^a spec file named "([^"]*)" with:$/ do |file_name, string|
steps %Q{
Given a file named "#{file_name}" with:
"""ruby
require 'rock_candy'
#{string}
"""
}
end
When /^I set environment variable "(.*?)" to "(.*?)"$/ do |variable, value|
set_env(variable, value)
end
Then /^the examples?(?: all)? pass(?:es)?$/ do
step %q{the output should contain "0 failures"}
step %q{the output should not contain "0 examples"}
step %q{the exit status should be 0}
end
|
Sagashi::Engine.routes.draw do
root "tokens#index"
end
|
require 'simplecov'
SimpleCov.start do
# Code groupings
add_filter '/spec/'
add_group 'Algorithms', 'lib/algorithm'
add_group 'Utilities', 'lib/ants'
add_group 'Agents', 'lib/colony'
add_group 'Simulations', 'lib/sims'
# Simplecov config
minimum_coverage 90
end
|
require 'rails_helper'
RSpec.describe ConversationsController, type: :controller do
login_user
describe "GET #index" do
it "returns http success" do
get :index
expect(response).to have_http_status(:success)
end
it "renders the index template" do
get :index
expect(response).to render_template("index")
expect(response.body).to eq ""
end
it "renders the show template" do
conversations = [create(:conversation)]
get :index
expect(assigns(:conversations)).to eq(conversations)
end
end
describe "GET #show" do
it "returns http success" do
conversation = create(:conversation)
get :show, id: conversation
expect(response).to have_http_status(:success)
end
it "renders the show template" do
conversation = create(:conversation)
get :show, id: conversation
expect(response).to render_template("show")
expect(response.body).to eq ""
end
it "renders the show template" do
conversation = create(:conversation)
chat_messages = [create(:chat_message, conversation_id: conversation.id)]
get :show, id: conversation
expect(assigns(:conversation)).to eq(conversation)
expect(assigns(:chat_messages)).to eq(chat_messages)
end
end
end
|
class MailTemplatesController < ApplicationController
before_filter :require_user
before_filter :obtain_parameters, :only => :show
inherit_resources
actions :all, :except => :index
respond_to :html, :xml, :json
belongs_to :project
def index
redirect_to project_path(params[:project_id])
end
private
def obtain_parameters
@test = params[:test]
end
end
|
module Services
module State
class AwaitingContactConfirmation < Base
def process(user_input)
store_answer(body: user_input, user: conversation.user)
case user_input
when User::CONFIRM_YES
conversation_strategy.confirm_choise
when User::CONFIRM_WRONG_EMAIL
conversation_strategy.wrong_email
when User::CONFIRM_WRONG_PHONE
conversation_strategy.wrong_phone
end
end
def state_options
options = [User::CONFIRM_YES]
options.push(User::CONFIRM_WRONG_EMAIL) if conversation.user.email
options.push(User::CONFIRM_WRONG_PHONE) if conversation.user.phone
options
end
end
end
end
|
class Account < Account.superclass
module Cell
module MonthlySpending
class TableRow < Abroaders::Cell::Base
property :couples?
property :monthly_spending_usd
def show
content_tag :tr do
content_tag(:td, label) << content_tag(:td, value)
end
end
private
def value
number_to_currency(monthly_spending_usd)
end
def label
"#{couples? ? 'Shared' : 'Personal'} spending:"
end
end
end
end
end
|
class LogbooksController < ApplicationController
before_action :set_logbook, only: [:show, :edit, :update, :destroy]
respond_to :html
def index
@logbooks = Logbook.all
@customers = Customer.all
respond_with(@customers, @logbooks)
end
def manage
@logbooks = Logbook.all.paginate(:per_page => 10, :page => params[:page])
respond_with(@logbooks)
end
def show
respond_with(@logbook)
end
def new
@logbook = Logbook.new
respond_with(@logbook)
end
def edit
end
def create
@logbook = Logbook.new(logbook_params)
@logbook.save
respond_with(@logbook)
end
def update
@logbook.update(logbook_params)
respond_with(@logbook)
end
def destroy
@logbook.destroy
respond_with(@logbook)
end
private
def set_logbook
@logbook = Logbook.find(params[:id])
end
def logbook_params
params.require(:logbook).permit(:content, :user_id, :customer_id, :status, :equipment, :place)
end
end
|
require 'ap'
require 'persistent_spec_helper'
require 'rack/test'
require_relative '../../api'
require_relative 'shared'
module DiceOfDebt
shared_context 'api test' do
include Rack::Test::Methods
before do
insert_data :games, id: 1, score: 0
end
after do
delete_all_data :rolls
delete_data :iterations, game_id: 1
delete_data :games, id: 1
end
def symbolize_keys(object)
case object
when Hash
object.each_with_object({}) { |(key, value), memo| memo[key.to_sym] = symbolize_keys(value) }
when Array
object.each_with_object([]) { |value, memo| memo << symbolize_keys(value) }
else
object
end
end
def app
API
end
def expect_data(expected_status)
expect_status(expected_status)
expect_response(:data)
end
def expect_error(expected_status)
expect_status(expected_status)
expect_response(:errors)
end
def expect_status(expected_status)
ap json if status != expected_status && expected_status != 500
expect(status).to eq expected_status
end
def expect_response(*types)
expect(headers['Content-Type']).to eq 'application/vnd.api+json'
expect(json.keys).to eq types # if json.keys != types # Output full json to help diagnose failure
end
let(:data) { json[:data] }
let(:errors) { json[:errors] }
let(:error) { errors.first }
# Don't use let() in case the spec invokes multiple requests
# in which case we don't want the last response memoized.
def headers
last_response.headers
end
def status
last_response.status
end
def body
last_response.body
end
def json
symbolize_keys(JSON.parse(last_response.body))
rescue
puts body
raise
end
subject { last_response }
end
end
|
require 'selenium-webdriver'
class SeleniumWrapper
def initialize(browser = :firefox, mobile = false)
profile = Selenium::WebDriver::Firefox::Profile.new
profile["network.proxy.type"] = 1
profile["network.proxy.http"] = "127.0.0.1"
profile["network.proxy.http_port"] = 9999
profile["network.proxy.no_proxies_on"] = "localhost, 127.0.0.1, *awful-valentine.com"
profile["general.useragent.override"] = "iPhone" if mobile
@selenium = Selenium::WebDriver.for(browser, :profile => profile)
end
def quit
@selenium.quit
end
def wait_for_ajax
Selenium::WebDriver::Wait.new(:timeout => 60).until do
sleep 1
@selenium.execute_script("return jQuery.active") == 0
end
end
def wait_for_animation
Selenium::WebDriver::Wait.new(:timeout => 60).until do
sleep 1
@selenium.execute_script("return jQuery(':animated').length") == 0
end
end
def wait_for_ajax_and_animation
if jQuery_defined?
wait_for_ajax
wait_for_animation
end
end
def type_text(text, element, strategy=:css)
begin
bring_current_window_to_front
clear(element, strategy)
find_element(element, strategy).send_keys(text)
wait_for_ajax_and_animation
rescue Exception => e
puts "Attempt to type '#{text}' into '#{element}' with strategy '#{strategy}' has failed"
screenshot
raise e
end
end
def click(element, strategy=:css)
begin
bring_current_window_to_front
find_element(element, strategy).click
wait_for_ajax_and_animation
rescue Exception => e
puts "Attempt to click the #{element} with strategy '#{strategy}' has failed"
screenshot
raise e
end
end
def get_inner_text(element, strategy=:css)
find_element(element, strategy).text
end
def clear(element, strategy=:css)
begin
find_element(element, strategy).clear
rescue Exception => e
puts "Attempt to clear the #{element} has failed"
screenshot
raise e
end
end
def find_element(element, strategy=:css)
@selenium.find_element(strategy, element)
end
def find_elements(element, strategy=:css)
@selenium.find_elements(strategy, element)
end
def bring_current_window_to_front
@selenium.switch_to.window(@selenium.window_handles.first)
end
def screenshot
screenshot_location = "images/#{Time.now.to_i}.png"
puts "Screnshot of the WebPage can be found here #{screenshot_location}"
@selenium.save_screenshot(screenshot_location)
end
def current_url
@selenium.current_url
end
def get(url)
@selenium.get(url)
end
def jQuery_defined?
@selenium.execute_script("return typeof jQuery == 'function'")
end
end |
class Product < ActiveRecord::Base
attr_accessible :name, :price
validates :name, presence: true, length: {minimum:5}
end
|
class Mutations::UpdateOrganizationRole < Mutations::BaseMutation
field :organization_role, Types::OrganizationRoleType, null: false
argument :id, Integer, required: true, camelize: false
argument :organization_role, Types::OrganizationRoleInputType, required: true, camelize: false
argument :add_user_ids, [Integer], required: false, camelize: false
argument :remove_user_ids, [Integer], required: false, camelize: false
argument :add_permissions, [Types::PermissionInputType], required: false, camelize: false
argument :remove_permission_ids, [Integer], required: false, camelize: false
load_and_authorize_model_with_id OrganizationRole, :id, :update
def resolve(**args)
organization_role.update!(
user_ids: organization_role.user_ids + args[:add_user_ids] - args[:remove_user_ids],
**(args[:organization_role].to_h)
)
args[:add_permissions].each do |permission|
organization_role.permissions.create!(permission.to_h)
end
organization_role.permissions.where(id: args[:remove_permission_ids]).destroy_all
# not sure why, but if I don't do this it seems like permissions get returned twice
organization_role.reload
{ organization_role: organization_role }
end
end
|
module BreweryDB
module Webhooks
class Beer < Base
def process
@beer = ::Beer.find_or_initialize_by(brewerydb_id: @brewerydb_id)
self.send(@action)
end
private
def insert(attributes = nil)
params = {
withBreweries: 'Y',
withSocialAccounts: 'Y',
withIngredients: 'Y'
}
attributes ||= @client.get("/beer/#{@brewerydb_id}", params).body['data']
@beer.assign_attributes(
name: attributes['name'],
description: attributes['description'],
abv: attributes['abv'],
ibu: attributes['ibu'],
original_gravity: attributes['originalGravity'],
organic: attributes['isOrganic'] == 'Y',
serving_temperature: attributes['servingTemperatureDisplay'],
availability: attributes['available'].try(:[], 'name'),
glassware: attributes['glass'].try(:[], 'name'),
created_at: attributes['createDate'],
updated_at: attributes['updateDate']
)
# Handle images
if attributes['labels']
@beer.image_id = attributes['labels']['icon'].match(/upload_(\w+)-icon/)[1]
end
# Assign Style
@beer.style = ::Style.find(attributes['styleId']) if attributes['styleId']
@beer.save!
# Handle associations
unless @action == 'edit'
brewery_insert(Array(attributes['breweries']))
socialaccount_insert(Array(attributes['socialAccounts']))
ingredient_insert(attributes['ingredients'] || {})
end
end
def edit
if @sub_action
self.send(@sub_action)
else
insert
end
end
def delete
@beer.destroy!
end
def brewery_insert(breweries = nil)
breweries ||= @client.get("/beer/#{@brewerydb_id}/breweries").body['data']
brewery_ids = Array(breweries).map { |b| b['id'] }
@beer.breweries = ::Brewery.where(brewerydb_id: brewery_ids)
end
alias :brewery_delete :brewery_insert
# This is a no-op; we get the same information in a Brewery hook.
def brewery_edit
true
end
def event_insert(events = nil)
events ||= @client.get("/beer/#{@brewerydb_id}/events").body['data']
event_ids = Array(events).map { |e| e['id'] }
@beer.events = ::Event.where(brewerydb_id: event_ids)
end
alias :event_delete :event_insert
# This is a no-op; we get the same information in an Event hook.
def event_edit
true
end
def ingredient_insert(attributes = nil)
attributes ||= @client.get("/beer/#{@brewerydb_id}/ingredients").body['data']
attributes = attributes.flat_map { |_, i| i } if attributes.is_a?(Hash)
return if attributes.empty?
# Because there is no Ingredient webhook, ingredients pulled from
# BreweryDB may not be in the local database yet. As such, we must
# initialize and/or update ingredients here.
ingredients = attributes.map do |attrs|
ingredient = ::Ingredient.find_or_initialize_by(id: attrs['id'])
ingredient.assign_attributes(
name: attrs['name'],
category: attrs['categoryDisplay'],
created_at: attrs['createDate'],
updated_at: attrs['updateDate']
)
ingredient.save!
ingredient
end
@beer.ingredients = ingredients
end
alias :ingredient_delete :ingredient_insert
def socialaccount_insert(attributes = nil)
attributes ||= @client.get("/beer/#{@brewerydb_id}/socialaccounts").body['data']
Array(attributes).each do |account|
social_account = @beer.social_media_accounts.find_or_initialize_by(website: account['socialMedia']['name'])
social_account.assign_attributes(
handle: account['handle'],
created_at: account['createDate'],
updated_at: account['updateDate']
)
social_account.save!
end
end
alias :socialaccount_edit :socialaccount_insert
def socialaccount_delete(attributes = nil)
attributes ||= @client.get("/beer/#{@brewerydb_id}/socialaccounts").body['data']
websites = attributes.map { |a| a['socialMedia']['name'] }
@beer.social_media_accounts.where.not(website: websites).destroy_all
end
end
end
end
|
# frozen_string_literal: true
Class.new(Nanoc::Filter) do
identifier :remove_lang_from_pre
def run(content, _params = {})
content.lines.reject { |l| l =~ /^\s+#!/ }.join
end
end
|
class User < ActiveRecord::Base
after_initialize :default_values
has_many :armies, :dependent => :destroy
before_save { email.downcase! }
before_create :create_remember_token
has_secure_password
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(?:\.[a-z\d\-]+)*\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false }
validates :password, length: { minimum: 6 }
def User.new_remember_token
SecureRandom.urlsafe_base64
end
def User.digest(token)
Digest::SHA1.hexdigest(token.to_s)
end
# needs error checking!!!
=begin
when no army exists for user_id, monster_id pair -> army count increases
when army exists "" -> army count stays the same increment monster_amount
monster_amount is a reasonable number
=end
def recruit(monster, army, army_params, num_monsters)
if num_monsters <= 0
return false
end
new_gold = self.gold - (monster.cost * num_monsters)
if new_gold < 0
return false
end
self.assign_attributes({ :gold => new_gold })
if army.nil?
army = Army.new(user_id: army_params[:user_id],
monster_id: army_params[:monster_id],
monster_amount: army_params[:monster_amount],
ai_controlled: false)
else
new_num_monsters = army.monster_amount + num_monsters
army.assign_attributes({ :monster_amount => new_num_monsters })
end
ActiveRecord::Base.transaction do
army.save!
self.save!(:validate => false)
end
return true
end
private
def create_remember_token
self.remember_token = User.digest(User.new_remember_token)
end
def default_values
self.gold ||= 5000
end
end
|
class LocationsController < ApplicationController
before_action :authenticate_user!
before_action :set_location, except: [:create]
def create
@new_location = current_user.create_location(location_params[:name])
@new_location.update(location_params)
unless @new_location.errors.any?
@location = @new_location
@new_location = Location.new(user: current_user)
end
flash.now[:list] = "Location Created"
end
def update
@location.update(location_params)
unless @location.errors.any?
flash[:list] = "Location Updated"
end
end
def destroy
@location_id = @location.id
@location.destroy
flash.now[:list] = "Location Deleted"
end
private
def location_params
params.require(:location).permit(:name, :street, :city, :state, :zip_code, :latitude, :longitude)
end
def set_location
@location = current_user.get_locations.find_by(id: params[:id])
# Check that location exists.
unless @location
respond_to do |format|
format.js { render status: 404 }
end
end
end
end
|
Pod::Spec.new do |s|
s.name = "Ready4AirPlayer"
s.homepage = "http://valtech.com"
s.license = 'Commercial'
s.author = { "Jeffrey Thompson" => "jeffrey.thompson@neonstingray.com" }
s.summary = "Ready4Air Player Component"
s.version = "1.0.0.002"
s.source = { :http => "http://repository.neonstingray.com/service/local/repositories/thirdparty/content/com/valtech/r4a/ios/player/1.0.0.002/player-1.0.0.002.zip" }
s.preserve_paths = 'libReady4AirPlayer.a'
s.source_files = '*.h'
s.platform = :ios, '7.0'
s.requires_arc = true
s.xcconfig = { 'LIBRARY_SEARCH_PATHS' => '"/Ready4AirPlayer"' }
s.dependency 'AFNetworking', '2.6.0'
s.dependency 'MSPlayReady', '2.3.2000sfa'
s.dependency 'GoogleCast', '2.5.2'
s.dependency 'SDWebImage'
s.dependency 'Typhoon'
end
|
require 'spec_helper'
RSpec.describe Smite::GodStats do
let(:agni) { Smite::Game.god('agni') }
let(:smite_obj) { agni.stats }
let(:items) do
[
Smite::Game.item('Soul Reaver'),
Smite::Game.item('Sovereignty')
]
end
describe '#initialize' do
it 'bounds the level between 1 and 20' do
expect(smite_obj.at_level(300).level).to eq(19)
expect(smite_obj.at_level(-300).level).to eq(0)
end
end
describe '#at_level' do
it 'returns a new instance of GodStats at the given level' do
new_stats = smite_obj.at_level(10)
expect(new_stats.level).to eq(9)
expect(new_stats.items).to eq(smite_obj.items)
end
end
describe '#with_items' do
it 'returns a new instance of GodStats with the given items' do
new_stats = smite_obj.with_items(items)
expect(new_stats.items).to eq(items)
expect(new_stats.level).to eq(smite_obj.level)
end
end
def scaling_calc(stats, attribute)
flat_from_items = stats.bonus_from_items[:flat][attribute.to_sym]
perc_from_items = stats.bonus_from_items[:perc][attribute.to_sym]
base = stats.data[attribute]
scaling = stats.send("#{attribute}_per_level".to_sym).to_f
scaling *= stats.level.to_f
ret = ((flat_from_items + base + scaling) * (1 + perc_from_items)).round(2)
attribute =~ /5|attack/ ? ret : ret.round
end
%w[ movement_speed health mana
mp5 hp5 attack_speed magical_power
magic_protection physical_power physical_protection ].each do |attr|
describe "##{attr}" do
it 'returns the base stats at level 0' do
scaling = scaling_calc(smite_obj, attr)
expect(smite_obj.send(attr.to_sym)).to eq(scaling)
end
it 'returns the scaled stats with items' do
new_obj = smite_obj.at_level(20).with_items(items)
scaling = scaling_calc(new_obj, attr)
expect(new_obj.send(attr.to_sym)).to eq(scaling)
end
end
end
it_behaves_like 'a Smite::Object'
end |
require 'spec_helper'
describe Book do
it { should validate_presence_of :title}
it { should validate_presence_of :author}
it { should validate_numericality_of :rating}
it { should have_valid(:rating).when(0, 20, 100) }
it { should_not have_valid(:rating).when(-1, "ten", 101) }
it { should have_many(:checkouts) }
it { should have_many(:genres).through(:categorizations) }
end
|
class AddAccumulatedMeasuredToValorizationitems < ActiveRecord::Migration
def change
add_column :valorizationitems, :accumulated_measured, :float
end
end
|
# frozen_string_literal: true
module NotificationMailerPatch
def event_received(event, event_class_name, resource, user, extra)
if extra[:template]
send_custom_email(event, event_class_name, resource, user, extra)
else
with_user(user) do
@organization = resource.organization
event_class = event_class_name.constantize
@event_instance = event_class.new(resource: resource, event_name: event, user: user, extra: extra)
subject = @event_instance.email_subject
mail(to: user.email, subject: subject)
end
end
end
def send_custom_email(event, event_class_name, resource, user, extra)
with_user(user) do
@organization = resource.organization
event_class = event_class_name.constantize
@event_instance = event_class.new(resource: resource, event_name: event, user: user, extra: extra)
subject = @event_instance.email_subject
mail(to: user.email, subject: subject, template_name: extra[:template])
end
end
end
Decidim::NotificationMailer.class_eval do
prepend(NotificationMailerPatch)
end
|
module Reservable
module ClassMethods
def highest_ratio_res_to_listings
all.max { |a, b| a.res_to_listings <=> b.res_to_listings }
end
def most_res
all.max { |a, b| a.reservations.count <=> b.reservations.count }
end
end
module InstanceMethods
def res_to_listings
return 0 if listings.blank?
reservations.count.to_f / listings.count.to_f
end
def openings(start_date, end_date)
listings.available(start_date, end_date)
end
end
end
|
require 'support/number_helper'
require 'fileutils'
require 'tempfile'
class Restaurant
include NumberHelper
@@filepath = nil
def self.filepath=(path=nil)
@@filepath = File.join(APP_ROOT,path)
end
def self.file_exists?
# class should know if the restaurant files file exists
if @@filepath && File.exists?(@@filepath)
return true
else
return false
end
end
def self.file_usable?
return false unless @@filepath
return false unless File.exists?(@@filepath)
return false unless File.readable?(@@filepath)
return false unless File.writable?(@@filepath)
return true
end
def self.create_file
# create the restaurant file
File.open(@@filepath, 'w') unless file_exists?
return file_usable?
end
def self.saved_restaurants
# read the restaurant file
restaurants = []
if file_usable?
file = File.new(@@filepath, 'r')
file.each_line do |line|
restaurants << line.split("\t")
end
file.close
end
return restaurants
# return instances of restaurant
end
def self.build_from_questions
print "Restaurant name: "
name = gets.chomp.strip
print "Cuisine type: "
cuisine = gets.chomp.strip
price = -1
until price > 0
puts "\nPlease enter the average price as a number.\n" if price == 0
print "Average price: "
price = gets.chomp.strip.to_i
end
return self.new(name, cuisine, price)
end
def self.delete(delete_name)
return false unless Restaurant.file_usable?
tmp = Tempfile.new("extract")
lines_deleted = 0
open(@@filepath, 'r').each do |l|
if l.split("\t")[0].downcase != (delete_name)
tmp << l
else
lines_deleted += 1
end
end
tmp.close
FileUtils.mv(tmp.path, @@filepath) unless lines_deleted == 0
return false unless lines_deleted > 0
return true
end
attr_accessor :name, :cuisine, :price
def initialize(name="",cuisine="",price="")
@name = name
@cuisine = cuisine
@price = price
end
def save
return false unless Restaurant.file_usable?
File.open(@@filepath, 'a') do |file|
file.puts "#{[@name, @cuisine, @price].join("\t")}\n"
end
return true
end
end
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
#
#
@ansible_home = "/home/vagrant/.ansible"
Vagrant.configure("2") do |config|
config.vm.box = 'ubuntu/bionic64'
config.vm.box_url = 'https://cloud-images.ubuntu.com/bionic/current/bionic-server-cloudimg-amd64-vagrant.box'
config.vm.hostname = "ansible-test"
config.vm.provision "shell" do |s|
s.inline = 'if [ ! -f /tmp/initial_config ] ; then sudo service ssh restart && sudo apt update && sudo apt -y install python python-dev python-pip python-jinja2 python-markupsafe git && sudo pip install --upgrade pip && sudo pip install ansible > /dev/null 2>&1 && touch /tmp/initial_config ; fi '
end
config.vm.provision "shell", inline: "chown vagrant:vagrant #{@ansible_home}"
config.vm.synced_folder "../", "#{@ansible_home}/roles/shokunin.ansible-cloud-consul", type: 'rsync'
config.vm.provision "ansible_local" do |ansible|
ansible.playbook = "test.yml"
end
end
|
class User < ActiveRecord::Base
has_many :articles
before_save {self.email = email.downcase}
validates :username,presence: true, uniqueness:{case_sensitive:false},length:{minimum: 3, maximum: 25}
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence:true, uniqueness:{case_sensitive:false},length:{maximum:105},format:{with:VALID_EMAIL_REGEX}
has_secure_password
end |
class Song <ActiveRecord::Base
belongs_to :artist
has_many :genres, through: :song_genres
has_many :song_genres
extend Slugger::ClassMethods
include Slugger::InstanceMethods
end
|
class Admin::ItemsController < ApplicationController
def index
@items=Item.all
end
def new
@item=Item.new
@genres=Genre.all
end
def create
@item=Item.new(item_params)
if @item.save
flash[:notice] = "商品の登録に成功しました"
redirect_to admin_item_path(@item)
else
render :new
end
end
def show
@item=Item.find(params[:id])
end
def edit
@item=Item.find(params[:id])
end
def update
@item=Item.find(params[:id])
if @item.update(item_params)
redirect_to admin_item_path(@item)
flash[:notice]="商品情報を更新しました"
else
render :edit
end
end
def search
@items=Item.search(params[:keyword])
@keyword = params[:keyword]
render "index"
end
private
def item_params
params.require(:item).permit(:name,:genre_id,:explanation,:image,:price,:is_sold)
end
end
|
# encoding: UTF-8
# Copyright 2011-2013 innoQ Deutschland GmbH
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
class ImportsController < ApplicationController
before_action do
authorize! :import, Concept::Base
end
def index
@import = Import.new
@imports = Import.order('id DESC')
end
def show
@import = Import.find(params[:id])
end
def create
@import = Import.new(import_params)
@import.user = current_user
if @import.save
job = ImportJob.new(@import, @import.import_file.current_path, current_user,
@import.default_namespace, @import.publish)
Delayed::Job.enqueue(job)
flash[:success] = t('txt.views.import.success')
redirect_to imports_path
else
@imports = Import.order('id DESC')
flash[:error] = t('txt.views.import.error')
render :index
end
end
private
def import_params
params.require(:import).permit(:import_file, :default_namespace, :publish)
end
end
|
class Parcial < ActiveRecord::Base
has_many :actividads
belongs_to :materia_alumno
end
|
# == Schema Information
#
# Table name: bill_items
#
# id :integer not null, primary key
# label :string
# amount :decimal(19, 4)
# type :string
# account_id :integer
# bill_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_bill_items_on_account_id (account_id)
# index_bill_items_on_bill_id (bill_id)
#
class BillItem < ActiveRecord::Base
include Observable
belongs_to :bill
after_initialize :register_observers
def save!
super
changed
notify_observers
end
private
def register_observers
add_observer(bill, :update_total)
end
end
|
class Equipment < ApplicationRecord
belongs_to :organization, optional: true
enum kind: { laptop: 0, desktop: 1 }
end
|
################################
# Client Page
#
# Encapsulates the Client Page (new and edit)
#
# The layer hides the Capybara calls to make the functional RSpec tests that
# use this class simpler.
#
# rubocop: disable Metrics/ParameterLists
#
class ClientPage
include Capybara::DSL
def load id: nil
if id.nil?
visit '/clients/new'
else
visit "/clients/#{id}/edit"
end
self
end
def button action
click_on "#{action} Client", exact: true
self
end
def click choice
click_on choice, exact: true
end
def fill_in_client_id client_id
fill_in 'Client ID', with: client_id
end
def fill_in_entity(order:, title: '', initials: '', name:)
id_stem = "client_entities_attributes_#{order}"
fill_in "#{id_stem}_title", with: title
fill_in "#{id_stem}_initials", with: initials
fill_in "#{id_stem}_name", with: name
end
def fill_in_address(flat_no:, house_name:, road_no:, road:,
town:, district:, county:, postcode:)
fill_in 'Flat no', with: flat_no
fill_in 'House name', with: house_name
fill_in 'Road no', with: road_no
fill_in 'Road', with: road
fill_in 'Town', with: town
fill_in 'District', with: district
fill_in 'County', with: county
fill_in 'Postcode', with: postcode
end
def ref
find_field('Client ID').value.to_i
end
def entity(order:)
id_stem = "client_entities_attributes_#{order}"
"#{find_field("#{id_stem}_title").value} " \
"#{find_field("#{id_stem}_initials").value} " \
"#{find_field("#{id_stem}_name").value}".strip
end
def town
find_field('Town').value
end
def successful?
has_content? /created|updated/i
end
end
|
class StaticPagesController < ApplicationController
before_action :authenticate_user!
before_action :check_admin
before_action :check_trial, only: :create
def home
@books = Book.book_actived(current_user.id).select(:id, :name, :code, :bookcover, :book_type, :role)
end
def create
@number_book = params[:number_book]
trial_book(@number_book)
redirect_to root_path
end
private
def check_trial
redirect_to root_path if current_user.books.any?
end
end
|
#
# Copyright:: Copyright (c) 2015 Chef Software, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
module DeliverySugar
#
# This class is our interface to execute push jobs against a push jobs server.
#
class PushJob
attr_reader :server_url, :command, :nodes, :rest, :job_uri, :job
# Variables for the Job itself
attr_reader :id, :status, :created_at, :updated_at, :results
# How long to wait between each refresh during #wait
PAUSE_SECONDS = 5
#
# Create a new PushJob object
#
# @param server_url [String]
# The hostname for the server where the push jobs server is installed.
# The most common value for this will be Chef::Config[:chef_server_url]
# @param command [String]
# The white-listed command to execute via push jobs
# @param nodes [Array#String]
# An array of node names to run the push job against
# @param timeout [Integer]
# How long to wait before timing out
#
# @return [DeliverySugar::PushJob]
#
def initialize(server_url, command, nodes, timeout)
@server_url = server_url
@command = command
@nodes = nodes.map { |n| n.name }
@timeout = timeout
::Chef_Delivery::ClientHelper.enter_client_mode_as_delivery
@rest = Chef::REST.new(Chef::Config[:chef_server_url])
::Chef_Delivery::ClientHelper.leave_client_mode_as_delivery
end
#
# Trigger the push job
#
def dispatch
body = {
'command' => @command,
'nodes' => @nodes,
'run_timeout' => @timeout
}
::Chef_Delivery::ClientHelper.enter_client_mode_as_delivery
resp = @rest.post_rest('/pushy/jobs', body)
::Chef_Delivery::ClientHelper.leave_client_mode_as_delivery
@job_uri = resp['uri']
refresh
end
#
# Loop until the push job succeeds, errors, or times out.
#
def wait
loop do
refresh
fail Exceptions::PushJobFailed, @job if timed_out?
fail Exceptions::PushJobFailed, @job if failed?
break if successful?
pause
end
end
#
# Return whether or not a push job has completed or not
#
# @return [TrueClass, FalseClass]
#
def complete?
case @status
when 'new', 'voting', 'running'
false
when 'complete'
true
else
fail Exceptions::PushJobError, @job
end
end
#
# Return whether or not the completed push job was successful.
#
# @return [TrueClass, FalseClass]
#
def successful?
complete? && all_nodes_succeeded?
end
#
# Return whether or not the completed push job failed.
#
# @return [TrueClass, FalseClass]
#
def failed?
complete? && !all_nodes_succeeded?
end
#
# Determine if the push job has been running longer than the timeout
# would otherwise allow. We do this as a backup to the timeout in the
# Push Job API itself.
#
# @return [TrueClass, FalseClass]
#
def timed_out?
@status == 'timed_out' || (@created_at + @timeout < current_time)
end
#
# Poll the API for an update on the Job data.
#
def refresh
::Chef_Delivery::ClientHelper.enter_client_mode_as_delivery
@job = @rest.get_rest(@job_uri)
::Chef_Delivery::ClientHelper.leave_client_mode_as_delivery
@id ||= job['id']
@status = job['status']
@created_at = DateTime.parse(job['created_at'])
@updated_at = DateTime.parse(job['updated_at'])
@results = job['nodes']
end
private
#
# Return the current time
#
# @return [DateTime]
#
def current_time
DateTime.now
end
#
# Return whether or not all nodes are marked as successful.
#
# @return [TrueClass, FalseClass]
#
def all_nodes_succeeded?
@results['succeeded'] && @results['succeeded'].length == @nodes.length
end
#
# Implement our method of pausing before we get the status of the
# push job again.
#
def pause
sleep PAUSE_SECONDS
end
end
end
|
# Creates a follow of an target for a user. If one already exists, it
# is returned. Expects to work idempotently.
class CreateFollow
def initialize(user, target, options={})
@user = user
@target = target
@options = options.symbolize_keys
end
def call()
@follow = @user.follows.find_by target: @target
@follow ||= @user.follows.new target: @target
@follow.active = true unless @follow.active
@follow.save!
@follow
end
end
|
Gem::Specification.new do |s|
s.name = 'rpmbuild'
s.version = '0.6.6'
s.date = '2014-02-10'
s.summary = "Create RPMs"
s.description = "A wrapper around rpmbuild for generating custom RPMs"
s.authors = ["Albert Dixon"]
s.email = "adixon415n@gmail.com"
s.license = "GPLv3"
s.files = ["lib/rpmbuild.rb"]
s.executables << 'gen_rpm'
s.add_runtime_dependency 'trollop', '~> 2.0'
s.add_runtime_dependency 'psych', '~> 2.0.2'
s.requirements << 'rpmbuild >= 4.8.0'
end
|
class CreateBikeWheelSizes < ActiveRecord::Migration
def up
create_table(:bike_wheel_sizes) do |t|
t.integer :twmm
t.integer :rdmm
t.string :twin
t.string :rdin
t.string :twfr
t.string :rdfr
t.string :description
t.string :tire_common_score
end
end
def down
drop_table :bike_wheel_sizes
end
end
|
module Refinery
module NewsItems
class Engine < Rails::Engine
include Refinery::Engine
isolate_namespace Refinery::NewsItems
engine_name :refinery_news_items
initializer "register refinerycms_news_items plugin" do
Refinery::Plugin.register do |plugin|
plugin.name = "news_items"
plugin.url = proc { Refinery::Core::Engine.routes.url_helpers.news_items_admin_news_items_path }
plugin.pathname = root
plugin.activity = {
:class_name => :'refinery/news_items/news_item'
}
end
end
config.after_initialize do
Refinery.register_extension(Refinery::NewsItems)
end
end
end
end
|
class Vacation < ActiveRecord::Base
def vacations_with_desc
vacaciones = fill_zeros("#{period}")
"#{vacaciones}/#{year}"
end
def fill_zeros(vacaciones)
"#{vacaciones}".to_s.rjust(2, '0')
end
end
|
class Recipe < ApplicationRecord
has_many :foodables
has_many :foods, through: :foodables
has_many :favorites
# validates_uniqueness_of :recipe
end
|
require 'light_remote'
class LightRemote::Flame
def initialize(light, loop_callback=nil)
@light = light
@loop_callback = loop_callback ? loop_callback.to_proc : nil
end
# This loop makes a smooth-fading fire. (A bit too smooth.)
# TODO: Add some flicker.
def run(initial_rgb=nil)
cur = initial_rgb || [0.5, 0.1, 0]
while true do
# Mostly red with some green to move towards orange and yellow.
r = 1
g = 0.15 * rand
# Amplitude factor (min 0.1, max 1) dims r and g keeping their relative proportions.
f = 0.1 + 0.9 * rand
nxt = [r * f, g * f, 0]
# Vary the transition speed. Very slow with an occasional flick.
x = rand(10) + 1
steps = x > 3 ? 10*x : x
@light.fade(*(cur + nxt + [steps]))
#STDIN.readline # uncomment this to pause each iteration.
cur = nxt
break if @loop_callback && ! @loop_callback.call(*cur)
end
end
end |
require('minitest/autorun')
require('minitest/rg')
require_relative('../person')
# Duck Test inherets from MiniTest :: Test is the module
class PersonTest < MiniTest::Test
def setup
@person = Person.new("Adrian", "Tuckwell")
end
def test_person_first_name
assert_equal("Adrian", @person.first_name)
end
def test_person_last_name
assert_equal("Tuckwell", @person.last_name)
end
def test_talk
assert_equal("Adrian Tuckwell", @person.talk)
end
end |
class ChangeEventsLogPayloadColumn < ActiveRecord::Migration
def up
change_column :'denormalization.events_log', :payload, :text
end
def down
change_column :'denormalization.events_log', :payload, :string, limit: 512
end
end
|
require 'spec_helper'
require 'turnip_formatter/step_template/exception'
describe TurnipFormatter::StepTemplate::Exception do
after do
TurnipFormatter.step_templates.pop
end
let!(:template) do
described_class.new
end
describe '#build_failed' do
subject { template.build_failed(failed_example) }
it do
expect(subject).to have_tag 'div.step_exception' do
with_tag 'pre'
with_tag 'ol > li'
end
end
end
describe '#build_pending' do
subject { template.build_pending(pending_example) }
it do
expect(subject).to have_tag 'div.step_exception' do
with_tag 'pre', text: 'No such step(0): '
with_tag 'ol > li'
end
end
end
end
|
require 'spec_helper'
require 'yt/constants/geography'
describe 'Yt::COUNTRIES' do
it 'returns all country codes and names' do
expect(Yt::COUNTRIES[:US]).to eq 'United States'
expect(Yt::COUNTRIES['IT']).to eq 'Italy'
end
end
describe 'Yt::US_STATES' do
it 'returns all U.S. state codes and names' do
expect(Yt::US_STATES[:CA]).to eq 'California'
expect(Yt::US_STATES['CO']).to eq 'Colorado'
end
end
|
class Review < ApplicationRecord
belongs_to :product
validates :rating, presence: true
validates :rating, :inclusion => {:in => 1..5, :message => " %{value} is not a valid rating " }
validates :comment, presence: true, length: {maximum: 255}, on: :create, allow_nil: false
end
|
module Mastermind
class Code
attr_accessor :code
attr_reader :min_digit, :max_digit, :code_size, :valid
def initialize
@code = ""
@min_digit = 1
@max_digit = 6
@code_size = 4
@valid = Validate.new(@code_size, @min_digit, @max_digit)
end
end
end |
class Package < ApplicationRecord
has_many :contacts
belongs_to :type, optional: true
end
|
require File.join(Dir.pwd, 'spec', 'spec_helper')
describe 'Experian::DataDictionary 313HH' do
context 'valid lookup' do
it { expect( Experian::DataDictionary.lookup('313HH','A01') ).to eq('American Royalty') }
it { expect( Experian::DataDictionary.lookup('313HH','B07') ).to eq('Generational Soup') }
it { expect( Experian::DataDictionary.lookup('313HH','D15') ).to eq('Sports Utility Families') }
it { expect( Experian::DataDictionary.lookup('313HH','J34') ).to eq('Aging in Place') }
end
context 'invalid lookup' do
it { expect( Experian::DataDictionary.lookup('313HH','TAA1') ).to be_nil }
it { expect( Experian::DataDictionary.lookup('313HH','A') ).to be_nil }
it { expect( Experian::DataDictionary.lookup('313HH','R') ).to be_nil }
end
end
|
require 'rails_helper'
RSpec.describe BuyerAddress, type: :model do
before do
@user = FactoryBot.create(:user)
@item = FactoryBot.create(:item)
@buyer_address = FactoryBot.build(:buyer_address, user_id: @user.id, item_id: @item.id)
end
describe '購入者情報の保存' do
context '購入者情報の保存がうまくいくとき' do
it 'すべての値が正しく入力されていれば保存できる' do
expect(@buyer_address).to be_valid
end
it '建物名が空でも保存できる' do
@buyer_address.building = nil
expect(@buyer_address).to be_valid
end
end
context '購入者情報の保存がうまくいかないとき' do
it '郵便番号が空だと保存できないこと' do
@buyer_address.postal_code = nil
@buyer_address.valid?
expect(@buyer_address.errors.full_messages).to include("Postal code can't be blank", 'Postal code is invalid. Include hyphen(-)')
end
it 'prefecture_idが1だと保存できないこと' do
@buyer_address.prefecture_id = 1
@buyer_address.valid?
expect(@buyer_address.errors.full_messages).to include('Prefecture must be other than 1')
end
it '市町村が空だと保存できないこと' do
@buyer_address.city = nil
@buyer_address.valid?
expect(@buyer_address.errors.full_messages).to include("City can't be blank")
end
it '番地が空だと保存できないこと' do
@buyer_address.number = nil
@buyer_address.valid?
expect(@buyer_address.errors.full_messages).to include("Number can't be blank")
end
it '電話番号が空だと保存できないこと' do
@buyer_address.tel = nil
@buyer_address.valid?
expect(@buyer_address.errors.full_messages).to include("Tel can't be blank")
end
it '郵便番号にはハイフンがなければ保存できない' do
@buyer_address.postal_code = 1_234_567
@buyer_address.valid?
expect(@buyer_address.errors.full_messages).to include('Postal code is invalid. Include hyphen(-)')
end
it '電話番号に-が入っていると保存できないこと' do
@buyer_address.tel = '090-7852-5875'
@buyer_address.valid?
expect(@buyer_address.errors.full_messages).to include('Tel is invalid')
end
it 'tokenが空だと保存できないこと' do
@buyer_address.token = nil
@buyer_address.valid?
expect(@buyer_address.errors.full_messages).to include("Token can't be blank")
end
it '電話番号は11桁以内でないと保存できないこと' do
@buyer_address.tel = '090617368264'
@buyer_address.valid?
expect(@buyer_address.errors.full_messages).to include("Tel is invalid")
end
end
end
end
|
class CreateUsers < ActiveRecord::Migration
def self.up
create_table :users, :id => false, :primary_key => 'id' do |t|
# 客户管理系统同步数据
t.integer :id
t.string :username
t.string :email
t.string :encrypted_password
# 密码和令牌
t.string :crypted_password
t.string :password_salt
t.string :persistence_token
t.string :single_access_token
# 临时令牌,供找回密码或确认注册使用
t.string :perishable_token
t.datetime :perishable_token_at
# 用户角色
t.integer :role_id
t.string :role_names
# 登录记录
t.integer :login_count, :default => 0
t.integer :failed_login_count, :default => 0
t.datetime :last_request_at
t.datetime :current_login_at
t.datetime :last_login_at
t.string :current_login_ip
t.string :last_login_ip
# 用户状态
t.boolean :active, :default => true
t.boolean :approved, :default => true
t.boolean :confirmed, :default => true
# 用户禁止状态
t.boolean :disabled, :default => false
t.boolean :deleted, :default => false
t.integer :lock_version, :default => 0
# 用户注册IP
t.string :register_ip
t.timestamps
end
# 建立索引
change_table :users do |t|
t.index :id
t.index :username
t.index :email
t.index :persistence_token
t.index :perishable_token
t.index :single_access_token
end
end
def self.down
drop_table :users
end
end
|
class IssueHeader
include RailsHelpers
def self.render(issue, show_full_image)
self.new(issue, show_full_image).render
end
attr_accessor :issue
def initialize(issue, show_full_image)
@issue = issue
@show_full_image = show_full_image
end
def css_class
'home'
end
def image
helpers.image_tag issue.large_cover_image.url(:large), alt: issue.cover_image_alt
end
def title
helpers.link_to(issue.title, routes.issue_path(issue.friendly_id), class: 'vtitle')
end
def header_image
helpers.link_to(image, routes.issue_path(issue.friendly_id))
end
def image_credit
issue.cover_image_credit.to_s.scan(/.{1,100}\b/m).first
end
def image_full_credit
issue.cover_image_credit
end
def editorial_notes
helpers.link_to("Note from the Editors", routes.editorial_notes_issue_path(issue.friendly_id), class: 'editor-note')
end
def image_credit_too_long?
issue.cover_image_credit.to_s.scan(/.{1,100}\b/m).size > 1
end
def render
return @show_full_image ? render_to_string('/issues/header', { object: self }) : nil
end
end
|
require "securerandom"
class AuthController < ApplicationController
skip_before_action :require_login
skip_before_action :require_setup
def signup
render(status: 200)
end
def create_user
user = User.new
user.name = params[:name]
user.email = params[:email]
user.password = params[:password]
user.password_confirmation = params[:password_confirmation]
user.locale = current_locale
user.activation_token = SecureRandom.hex(64)
if user.invalid?
flash[:error] = user.errors.full_messages.first
return redirect_to signup_path
end
user.save!
UserMailer.activation_email(user, url_for(activate_email_url(user.activation_token))).deliver_now
flash[:success] = I18n.t("pages.signup.success_message")
redirect_to login_path
end
def login
render(status: 200)
end
def authenticate
user = User.find_by(email: params[:email])
if user && user.authenticate(params[:password])
session[:user_id] = user.id
return redirect_to home_path
end
flash[:error] = I18n.t("pages.login.error_message")
redirect_to login_path
end
def logout
session[:user_id] = nil
redirect_to login_path
end
def forgot_password
render(status: 200)
end
def request_password_link
unless params[:email].present?
flash[:error] = I18n.t("pages.forgot_password.validation")
return redirect_to forgot_password_path
end
user = User.find_by(email: params[:email])
if user
user.forgot_token = SecureRandom.hex(64)
user.save!(validate: false)
UserMailer.forgot_password_email(user, url_for(new_password_url(user.forgot_token))).deliver_now
end
flash[:success] = I18n.t("pages.forgot_password.sent_message")
redirect_to forgot_password_path
end
def new_password
@token = params[:token]
user = User.find_by(forgot_token: @token)
unless user
flash[:error] = I18n.t("pages.forgot_password.error_message")
return redirect_to forgot_password_path
end
render(status: 200)
end
def reset_password
user = User.find_by(forgot_token: params[:token])
if user
user.forgot_token = nil
user.password = params[:password]
user.password_confirmation = params[:password_confirmation]
if user.invalid?
flash[:error] = user.errors.full_messages.first
return redirect_to new_password_path(params[:token])
end
user.save!
flash[:success] = I18n.t("pages.forgot_password.success_message")
return redirect_to login_path
end
flash[:error] = I18n.t("pages.forgot_password.error_message")
redirect_to forgot_password_path
end
def activate_email
user = User.find_by(activation_token: params[:token])
if user
user.email_activated = true
user.activation_token = nil
user.email = user.unconfirmed_email if user.unconfirmed_email
user.unconfirmed_email = nil
user.save!(validate: false)
session[:user_id] = nil
flash[:success] = I18n.t("pages.activation.success_message")
return redirect_to login_path
end
flash[:error] = I18n.t("pages.activation.error_message")
redirect_to login_path
end
end
|
require "helper"
describe Bridge::Points::Chicago do
it "raises ArgumentError when invalid honour card points provided" do
assert_raises(ArgumentError) do
Bridge::Points::Chicago.new(:hcp => 15, :points => 100)
end
end
it "set default vulnerable to false" do
imp = Bridge::Points::Chicago.new(:hcp => 40, :points => -100)
refute imp.vulnerable
end
it "return vulnerable boolean" do
imp = Bridge::Points::Chicago.new(:hcp => 20, :points => 100, :vulnerable => true)
assert imp.vulnerable?
end
it "return points to make when vulnerable" do
imp = Bridge::Points::Chicago.new(:hcp => 23, :points => 100, :vulnerable => true)
assert_equal 110, imp.points_to_make
end
it "return nil when points are not in range" do
imp = Bridge::Points::Chicago.new(:hcp => 20, :points => 45)
assert_equal nil, imp.imps
end
it "return high value of imp range" do
imp = Bridge::Points::Chicago.new(:hcp => 22, :points => 110)
assert_equal 1, imp.imps
end
it "return points to make when not vulnerable" do
imp = Bridge::Points::Chicago.new(:hcp => 23, :points => 100, :vulnerable => false)
assert_equal 110, imp.points_to_make
end
it "return positive imps" do
imp = Bridge::Points::Chicago.new(:hcp => 21, :points => 100)
assert_equal 2, imp.imps
end
it "return negative imps" do
imp = Bridge::Points::Chicago.new(:hcp => 21, :points => -100)
assert_equal -4, imp.imps
end
end
|
require "keg"
module StickyLink
def self.link(kegs, mode, options)
linked_kegs = []
kegs.each do |keg|
keg_only = Homebrew.keg_only?(keg.rack)
if HOMEBREW_PREFIX.to_s == "/usr/local" && keg_only &&
keg.name.start_with?("openssl", "libressl")
opoo <<-EOS.undent
Refusing to link: #{keg.name}
Linking keg-only #{keg.name} means you may end up linking against the insecure,
deprecated system OpenSSL while using the headers from Homebrew's #{keg.name}.
Instead, pass the full include/library paths to your compiler e.g.:
-I#{HOMEBREW_PREFIX}/opt/#{keg.name}/include -L#{HOMEBREW_PREFIX}/opt/#{keg.name}/lib
EOS
next
elsif keg.linked?
opoo "Already linked: #{keg}"
puts "To relink: brew unlink #{keg.name} && brew link #{keg.name}"
linked_kegs << keg
next
elsif keg_only && !options[:force]
opoo "#{keg.name} is keg-only and must be linked with --force"
puts "Note that doing so can interfere with building software."
Homebrew.puts_keg_only_path_message(keg)
next
elsif mode.dry_run && mode.overwrite
puts "Would remove:"
keg.link(mode)
next
elsif mode.dry_run
puts "Would link:"
keg.link(mode)
Homebrew.puts_keg_only_path_message(keg) if keg_only
next
end
keg.lock do
print "Linking #{keg}... "
puts if options[:verbose]
begin
n = keg.link(mode)
linked_kegs << keg
rescue Keg::LinkError
puts
raise
else
puts "#{n} symlinks created"
end
if keg_only && !options[:homebrew_developer]
Homebrew.puts_keg_only_path_message(keg)
end
end
end
linked_kegs
end
def self.keg_for(name)
raise UsageError if name.empty?
rack = Formulary.to_rack(name.downcase)
dirs = rack.directory? ? rack.subdirs : []
raise NoSuchKegError, rack.basename if dirs.empty?
linked_keg_ref = HOMEBREW_LINKED_KEGS/rack.basename
opt_prefix = HOMEBREW_PREFIX/"opt/#{rack.basename}"
begin
if opt_prefix.symlink? && opt_prefix.directory?
Keg.new(opt_prefix.resolved_path)
elsif linked_keg_ref.symlink? && linked_keg_ref.directory?
Keg.new(linked_keg_ref.resolved_path)
elsif dirs.length == 1
Keg.new(dirs.first)
else
f = if name.include?("/") || File.exist?(name)
Formulary.factory(name)
else
Formulary.from_rack(rack)
end
unless (prefix = f.installed_prefix).directory?
raise MultipleVersionsInstalledError, rack.basename
end
Keg.new(prefix)
end
rescue FormulaUnavailableError
raise <<-EOS.undent
Multiple kegs installed to #{rack}
However we don't know which one you refer to.
Please delete (with rm -rf!) all but one and then try again.
EOS
end
end
end
|
Given /^Opening Home Page$/ do
visit root_path
end
When /^I click on Group Menu$/ do
page.should have_selector 'h1', text: 'Organization Information System'
within("#group") do
click_link 'grp'
end
end
When /^I click on View Users Under Group sub Menu$/ do
within("#grpusers") do
click_link 'usersgrp'
end
end
Then /^I should see a select box$/ do
page.should have_content('Choose Group:')
end
When /^I choose Group Id and click on Search Button$/ do
select 'org: 1 grp: 1 G1', :from => 'grpsel'
click_button 'Search'
end
Then /^I can view users under group$/ do |table|
within('table') do
page.should have_content('Group Id')
end
table.hashes.each do |columns|
columns.keys.each do |k|
within('table') do
page.should have_content(columns[k])
end
end
end
end
|
module AdminLte
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
# before_action :configure_permitted_parameters, if: :devise_controller?
before_action :authenticate_user!
before_action :check_admin_user
layout :layout_by_resource
# def index
# if !current_user.admin?
# redirect_to home_path
# end
# end
private
def check_admin_user
begin
if !current_user.admin?
redirect_to home_path
end
rescue
redirect_to home_path
end
end
def layout_by_resource
if devise_controller?
'layouts/devise'
else
'admin_lte/layouts/admin'
end
end
end
end
|
class SubscribersController < ApplicationController
before_action :authenticate_user!
before_filter :load_catalog, only: [:new, :create]
def new
@subscriber = Subscriber.new
end
def create
@subscriber = @catalog.
subscribers.
find_or_initialize_by(email: params[:email])
if @subscriber.update(subscriber_params)
SubscriberMailer.delay.invitation(@subscriber, current_user)
analytics.track_shared_catalog(@subscriber)
flash[:notice] = I18n.t("subscribers.flash.success")
redirect_to @catalog
else
flash.now[:error] = I18n.t("subscribers.flash.error")
render :new
end
end
private
def load_catalog
@catalog = current_user.catalogs.find_by(id: params[:catalog_id])
end
def subscriber_params
params.require(:subscriber).permit(:email, :first_name, :message)
end
end
|
class RatingsController < ApplicationController
before_action :authenticate_user!
def update
@rating = Rating.find(params[:id])
@coach = @rating.coach
if @rating.update_attributes(rating: params[:rating])
respond_to do |format|
format.js
end
end
end
private
def rating_params
params.require(:rating).permit(:learner_id, :coach_id, :rating)
end
end |
class Rule < ApplicationRecord
TYPES = %i[level category score attempts].freeze
belongs_to :badge
def self.values_by_type(type)
send "#{type}_values"
end
def self.level_values
Quiz.all.pluck(:level).uniq.map { |level| [level, level] }
end
def self.category_values
Category.all.map { |category| [category.id, category.title] }
end
def self.attempts_values
[[1, 1], [3, 3], [5, 5]]
end
def self.score_values
[[75, 75], [90, 90], [100, 100]]
end
def text
"#{I18n.t(attr, scope: 'admin.rules')}: #{value}"
end
end
|
require_relative '../aws_helper'
require_relative '../aws_stubs'
require_relative '../aws_refresher_spec_common'
describe ManageIQ::Providers::Amazon::NetworkManager::Refresher do
include AwsRefresherSpecCommon
include AwsStubs
describe "refresh" do
before do
_guid, _server, zone = EvmSpecHelper.create_guid_miq_server_zone
@ems = FactoryBot.create(:ems_amazon, :zone => zone)
@ems.update_authentication(:default => {:userid => "0123456789", :password => "ABCDEFGHIJKL345678efghijklmno"})
EvmSpecHelper.local_miq_server(:zone => Zone.seed)
end
# Test all kinds of refreshes, DTO refresh, DTO with batch saving and the original refresh
AwsRefresherSpecCommon::ALL_GRAPH_REFRESH_SETTINGS.each do |settings|
context "with settings #{settings}" do
before :each do
stub_refresh_settings(settings)
end
it "2 refreshes, first creates all entities, second updates all entitites" do
2.times do
# Make sure we don't do any delete&create instead of update
assert_do_not_delete
refresh_spec
end
end
it "2 refreshes, first creates all entities, second updates exiting and deletes missing entitites" do
@data_scaling = 2
2.times do
refresh_spec
@data_scaling -= 1
end
end
it "2 refreshes, first creates all entities, second updates existing and creates new entitites" do
@data_scaling = 1
2.times do
# Make sure we don't do any delete&create instead of update
assert_do_not_delete
refresh_spec
@data_scaling += 1
end
end
it "2 refreshes, first creates all entities, second deletes all entitites" do
@data_scaling = 1
2.times do
refresh_spec
@data_scaling -= 1
end
end
end
end
end
def refresh_spec
@ems.reload
with_aws_stubbed(stub_responses) do
EmsRefresh.refresh(@ems.network_manager)
end
@ems.reload
assert_table_counts
assert_ems
end
def stub_responses
{
:elasticloadbalancing => {
:describe_load_balancers => {
:load_balancer_descriptions => mocked_load_balancers
},
:describe_instance_health => {
:instance_states => mocked_instance_health
}
},
:ec2 => {
:describe_regions => {
:regions => [
{:region_name => 'us-east-1'},
{:region_name => 'us-west-1'},
]
},
:describe_instances => mocked_instances,
:describe_vpcs => mocked_vpcs,
:describe_subnets => mocked_subnets,
:describe_security_groups => mocked_security_groups,
:describe_network_interfaces => mocked_network_ports,
:describe_addresses => mocked_floating_ips
}
}
end
def expected_table_counts
firewall_rule_count = test_counts[:security_group_count] *
(test_counts[:outbound_firewall_rule_per_security_group_count] +
test_counts[:outbound_firewall_rule_per_security_group_count])
floating_ip_count = test_counts[:floating_ip_count] + test_counts[:network_port_count] +
test_counts[:instance_ec2_count] + test_counts[:load_balancer_count]
network_port_count = test_counts[:instance_ec2_count] + test_counts[:network_port_count] +
test_counts[:load_balancer_count]
{
:auth_private_key => 0,
:ext_management_system => expected_ext_management_systems_count,
:flavor => 0,
:availability_zone => 0,
:vm_or_template => 0,
:vm => 0,
:miq_template => 0,
:disk => 0,
:guest_device => 0,
:hardware => 0,
:network => 0,
:operating_system => 0,
:snapshot => 0,
:system_service => 0,
# :relationship => 0,
# :miq_queue => 2,
# :orchestration_template => 0,
:orchestration_stack => 0,
:orchestration_stack_parameter => 0,
:orchestration_stack_output => 0,
:orchestration_stack_resource => 0,
:security_group => test_counts[:security_group_count],
:firewall_rule => firewall_rule_count,
:network_port => network_port_count,
:cloud_network => test_counts[:vpc_count],
:floating_ip => floating_ip_count,
:network_router => 0,
:cloud_subnet => test_counts[:subnet_count],
:custom_attribute => 0,
:load_balancer => test_counts[:load_balancer_count],
:load_balancer_pool => test_counts[:load_balancer_count],
:load_balancer_pool_member => test_counts[:load_balancer_instances_count],
:load_balancer_pool_member_pool => test_counts[:load_balancer_count] * test_counts[:load_balancer_instances_count],
:load_balancer_listener => test_counts[:load_balancer_count],
:load_balancer_listener_pool => test_counts[:load_balancer_count],
:load_balancer_health_check => test_counts[:load_balancer_count],
:load_balancer_health_check_member => test_counts[:load_balancer_count] * test_counts[:load_balancer_instances_count],
:cloud_volume => 0,
:cloud_volume_snapshot => 0,
}
end
def assert_table_counts
actual = {
:auth_private_key => ManageIQ::Providers::CloudManager::AuthKeyPair.count,
:ext_management_system => ExtManagementSystem.count,
:flavor => Flavor.count,
:availability_zone => AvailabilityZone.count,
:vm_or_template => VmOrTemplate.count,
:vm => Vm.count,
:miq_template => MiqTemplate.count,
:disk => Disk.count,
:guest_device => GuestDevice.count,
:hardware => Hardware.count,
:network => Network.count,
:operating_system => OperatingSystem.count,
:snapshot => Snapshot.count,
:system_service => SystemService.count,
# :relationship => Relationship.count,
# :miq_queue => MiqQueue.count,
# :orchestration_template => OrchestrationTemplate.count,
:orchestration_stack => OrchestrationStack.count,
:orchestration_stack_parameter => OrchestrationStackParameter.count,
:orchestration_stack_output => OrchestrationStackOutput.count,
:orchestration_stack_resource => OrchestrationStackResource.count,
:security_group => SecurityGroup.count,
:firewall_rule => FirewallRule.count,
:network_port => NetworkPort.count,
:cloud_network => CloudNetwork.count,
:floating_ip => FloatingIp.count,
:network_router => NetworkRouter.count,
:cloud_subnet => CloudSubnet.count,
:custom_attribute => CustomAttribute.count,
:load_balancer => LoadBalancer.count,
:load_balancer_pool => LoadBalancerPool.count,
:load_balancer_pool_member => LoadBalancerPoolMember.count,
:load_balancer_pool_member_pool => LoadBalancerPoolMemberPool.count,
:load_balancer_listener => LoadBalancerListener.count,
:load_balancer_listener_pool => LoadBalancerListenerPool.count,
:load_balancer_health_check => LoadBalancerHealthCheck.count,
:load_balancer_health_check_member => LoadBalancerHealthCheckMember.count,
:cloud_volume => CloudVolume.count,
:cloud_volume_snapshot => CloudVolumeSnapshot.count,
}
expect(actual).to eq expected_table_counts
end
def assert_ems
ems = @ems.network_manager
expect(ems).to have_attributes(
:api_version => nil, # TODO: Should be 3.0
:uid_ems => nil
)
expect(ems.flavors.size).to eql(expected_table_counts[:flavor])
expect(ems.availability_zones.size).to eql(expected_table_counts[:availability_zone])
expect(ems.vms_and_templates.size).to eql(expected_table_counts[:vm_or_template])
expect(ems.security_groups.size).to eql(expected_table_counts[:security_group])
expect(ems.network_ports.size).to eql(expected_table_counts[:network_port])
expect(ems.cloud_networks.size).to eql(expected_table_counts[:cloud_network])
expect(ems.floating_ips.size).to eql(expected_table_counts[:floating_ip])
expect(ems.network_routers.size).to eql(expected_table_counts[:network_router])
expect(ems.cloud_subnets.size).to eql(expected_table_counts[:cloud_subnet])
expect(ems.miq_templates.size).to eq(expected_table_counts[:miq_template])
expect(ems.orchestration_stacks.size).to eql(expected_table_counts[:orchestration_stack])
expect(ems.load_balancers.size).to eql(expected_table_counts[:load_balancer])
end
end
|
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
describe "Img2Vid Configuration" do
before(:all) do
@configuration = Img2Vid.configure do |config|
config.video_file = 'results.mpg'
config.temp_path = '/tmp'
config.ffmpeg_command = '/usr/local/bin/ffmpeg'
end
end
subject { @configuration }
it "video_file is valid" do
@configuration.video_file.should == 'results.mpg'
end
it "temp_path is valid" do
@configuration.temp_path.should == '/tmp'
end
it "ffmpeg_command is valid" do
@configuration.ffmpeg_command.should == '/usr/local/bin/ffmpeg'
end
it "initializes properly with a bad option" do
Img2Vid.configure :nonexistant => true
end
end
|
class Admin::BaseController < ApplicationController
layout "admin_layout"
before_action :require_admin
private
def require_admin
unless current_user.role_name == Settings.role_admin
redirect_to root_path
flash[:notice] = t "admin_only"
end
end
end
|
require 'rails_helper'
describe 'PasswordReset', type: :request do
describe '#new' do
before { get new_password_reset_url }
it { expect(response).to be_success }
it { expect(response).to render_template 'new' }
end
describe '#create' do
subject { response }
let(:user) { create(:user) }
context "when correct email" do
before do
post password_resets_url, params: { password_reset: { email: user.email } }
user.reload
end
it { is_expected.to redirect_to root_path }
it { expect(user.reset_digest).not_to be_nil }
it { expect(flash[:info]).not_to be_nil }
end
context "when incorrect email" do
let(:wrong_email) { "wrong@wrong.com" }
before do
post password_resets_url, params: { password_reset: { email: wrong_email } }
end
it { is_expected.to render_template 'new' }
it { expect(user.reset_digest).to be_nil }
it { expect(flash[:info]).to be_nil }
end
end
describe '#update' do
let(:user) { create(:user, :activated) }
let(:assigns_user) { assigns(:user) }
let(:token) { assigns_user.reset_token }
before do
post password_resets_url, params: { password_reset: { email: user.email } }
patch password_reset_url(token), params: { user: { password: change_password, password_confirmation: change_password_confirmation }, email: user.email }
user.reload
end
context "when correct reset password" do
let(:change_password) { "hogehoge" }
let(:change_password_confirmation) { "hogehoge" }
it { is_expected.to redirect_to user_path user }
it { expect(user.reset_digest).to be_nil }
it { expect(flash[:success]).not_to be_nil }
end
context "when incorrect reset password" do
let(:change_password) { "hoge" }
let(:change_password_confirmation) { "hoge" }
it { is_expected.to render_template 'edit' }
end
context "when params password empty" do
let(:change_password) { "" }
let(:change_password_confirmation) { "" }
it { is_expected.to render_template 'edit' }
end
context "when unactive user" do
let(:user) { create(:user) }
let(:change_password) { "hogehoge" }
let(:change_password_confirmation) { "hogehoge" }
it { is_expected.to redirect_to root_path }
end
context "when invalid token" do
let(:token) { "invalid" }
let(:change_password) { "hogehoge" }
let(:change_password_confirmation) { "hogehoge" }
it { is_expected.to redirect_to root_path }
end
# context "when over expiration" do
# let(:change_password) { "hogehoge" }
# let(:change_password_confirmation) { "hogehoge" }
# before do
# user.update_attributes(reset_digest: User.digest(user.reset_token), reset_sent_at: Time.zone.now - 5.hours)
# binding.pry
# patch password_reset_url(token), params: { user: { password: change_password, password_confirmation: change_password_confirmation }, email: user.email }
# end
# it { is_expected.to redirect_to new_password_reset_url}
# end
end
end
|
class HObject
def initialize(data={})
@data = data
end
def to_json(options={})
data.to_json
end
end
|
module Rfm
# The Record object represents a single FileMaker record. You typically get them from ResultSet objects.
# For example, you might use a Layout object to find some records:
#
# results = myLayout.find({"First Name" => "Bill"})
#
# The +results+ variable in this example now contains a ResultSet object. ResultSets are really just arrays of
# Record objects (with a little extra added in). So you can get a record object just like you would access any
# typical array element:
#
# first_record = results[0]
#
# You can find out how many record were returned:
#
# record_count = results.size
#
# And you can of course iterate:
#
# results.each (|record|
# // you can work with the record here
# )
#
# =Accessing Field Data
#
# You can access field data in the Record object in two ways. Typically, you simply treat Record like a hash
# (because it _is_ a hash...I love OOP). Keys are field names:
#
# first = myRecord["First Name"]
# last = myRecord["Last Name"]
#
# If your field naming conventions mean that your field names are also valid Ruby symbol named (ie: they contain only
# letters, numbers, and underscores) then you can treat them like attributes of the record. For example, if your fields
# are called "first_name" and "last_name" you can do this:
#
# first = myRecord.first_name
# last = myRecord.last_name
#
# Note: This shortcut will fail (in a rather mysterious way) if your field name happens to match any real attribute
# name of a Record object. For instance, you may have a field called "server". If you try this:
#
# server_name = myRecord.server
#
# you'll actually set +server_name+ to the Rfm::Server object this Record came from. This won't fail until you try
# to treat it as a String somewhere else in your code. It is also possible a future version of Rfm will include
# new attributes on the Record class which may clash with your field names. This will cause perfectly valid code
# today to fail later when you upgrade. If you can't stomach this kind of insanity, stick with the hash-like
# method of field access, which has none of these limitations. Also note that the +myRecord[]+ method is probably
# somewhat faster since it doesn't go through +method_missing+.
#
# =Accessing Repeating Fields
#
# If you have a repeating field, RFM simply returns an array:
#
# val1 = myRecord["Price"][0]
# val2 = myRecord["Price"][1]
#
# In the above example, the Price field is a repeating field. The code puts the first repetition in a variable called
# +val1+ and the second in a variable called +val2+.
#
# It is not currently possible to create or edit a record's repeating fields beyond the first repitition, using Rfm.
#
# =Accessing Portals
#
# If the ResultSet includes portals (because the layout it comes from has portals on it) you can access them
# using the Record::portals attribute. It is a hash with table occurrence names for keys, and arrays of Record
# objects for values. In other words, you can do this:
#
# myRecord.portals["Orders"].each {|record|
# puts record["Order Number"]
# }
#
# This code iterates through the rows of the _Orders_ portal.
#
# As a convenience, you can call a specific portal as a method on your record, if the table occurrence name does
# not have any characters that are prohibited in ruby method names, just as you can call a field with a method:
#
# myRecord.orders.each {|portal_row|
# puts portal_row["Order Number"]
# }
#
# =Field Types and Ruby Types
#
# RFM automatically converts data from FileMaker into a Ruby object with the most reasonable type possible. The
# type are mapped thusly:
#
# * *Text* fields are converted to Ruby String objects
#
# * *Number* fields are converted to Ruby BigDecimal objects (the basic Ruby numeric types have
# much less precision and range than FileMaker number fields)
#
# * *Date* fields are converted to Ruby Date objects
#
# * *Time* fields are converted to Ruby DateTime objects (you can ignore the date component)
#
# * *Timestamp* fields are converted to Ruby DateTime objects
#
# * *Container* fields are converted to Ruby URI objects
#
# =Attributes
#
# In addition to +portals+, the Record object has these useful attributes:
#
# * *record_id* is FileMaker's internal identifier for this record (_not_ any ID field you might have
# in your table); you need a +record_id+ to edit or delete a record
#
# * *mod_id* is the modification identifier for the record; whenever a record is modified, its +mod_id+
# changes so you can tell if the Record object you're looking at is up-to-date as compared to another
# copy of the same record
class Record < Rfm::CaseInsensitiveHash
attr_accessor :layout #, :resultset
attr_reader :record_id, :mod_id, :portals
def_delegators :layout, :db, :database, :server, :field_meta, :portal_meta, :field_names, :portal_names
# This is called during the parsing process, but only to allow creation of the correct type of model instance.
# This is also called by the end-user when constructing a new empty record, but it is called from the model subclass.
def self.new(*args) # resultset
record = case
# Get model from layout, then allocate record.
# This should only use model class if the class already exists,
# since we don't want to create classes that aren't defined by the user - they won't be persistant.
when args[0].is_a?(Resultset) && args[0].layout && args[0].layout.model
args[0].layout.modelize.allocate
# Allocate instance of Rfm::Record.
else
self.allocate
end
record.send(:initialize, *args)
record
# rescue
# puts "Record.new bombed and is defaulting to super.new. Error: #{$!}"
# super
end
def initialize(*args) # resultset, attributes
@mods ||= {}
@portals ||= Rfm::CaseInsensitiveHash.new
options = args.rfm_extract_options!
if args[0].is_a?(Resultset)
@layout = args[0].layout
elsif self.is_a?(Base)
@layout = self.class.layout
@layout.field_keys.each do |field|
self[field] = nil
end
self.update_attributes(options) unless options == {}
self.merge!(@mods) unless @mods == {}
@loaded = true
end
_attach_as_instance_variables(args[1]) if args[1].is_a? Hash
#@loaded = true
self
end
# Saves local changes to the Record object back to Filemaker. For example:
#
# myLayout.find({"First Name" => "Bill"}).each(|record|
# record["First Name"] = "Steve"
# record.save
# )
#
# This code finds every record with _Bill_ in the First Name field, then changes the first name to
# Steve.
#
# Note: This method is smart enough to not bother saving if nothing has changed. So there's no need
# to optimize on your end. Just save, and if you've changed the record it will be saved. If not, no
# server hit is incurred.
def save
# self.merge!(layout.edit(self.record_id, @mods)[0]) if @mods.size > 0
self.replace_with_fresh_data(layout.edit(self.record_id, @mods)[0]) if @mods.size > 0
@mods.clear
end
# Like Record::save, except it fails (and raises an error) if the underlying record in FileMaker was
# modified after the record was fetched but before it was saved. In other words, prevents you from
# accidentally overwriting changes someone else made to the record.
def save_if_not_modified
# self.merge!(layout.edit(@record_id, @mods, {:modification_id => @mod_id})[0]) if @mods.size > 0
self.replace_with_fresh_data(layout.edit(@record_id, @mods, {:modification_id => @mod_id})[0]) if @mods.size > 0
@mods.clear
end
# Gets the value of a field from the record. For example:
#
# first = myRecord["First Name"]
# last = myRecord["Last Name"]
#
# This sample puts the first and last name from the record into Ruby variables.
#
# You can also update a field:
#
# myRecord["First Name"] = "Sophia"
#
# When you do, the change is noted, but *the data is not updated in FileMaker*. You must call
# Record::save or Record::save_if_not_modified to actually save the data.
def [](key)
# Added by wbr, 2013-03-31
return super unless @loaded
return fetch(key.to_s.downcase)
rescue IndexError
raise Rfm::ParameterError, "#{key} does not exists as a field in the current Filemaker layout." unless key.to_s == '' #unless (!layout or self.key?(key_string))
end
def respond_to?(symbol, include_private = false)
return true if self.include?(symbol.to_s)
super
end
def []=(key, val)
key_string = key.to_s.downcase
key_string_base = key_string.split('.')[0]
return super unless @loaded # is this needed? yes, for loading fresh records.
unless self.key?(key_string) || (layout.field_keys.include?(key_string_base) rescue nil)
raise Rfm::ParameterError, "You attempted to modify a field (#{key_string}) that does not exist in the current Filemaker layout."
end
# @mods[key_string] = val
# TODO: This needs cleaning up.
# TODO: can we get field_type from record instead?
@mods[key_string] = if [Date, Time, DateTime].member?(val.class)
field_type = layout.field_meta[key_string.to_sym].result
case field_type
when 'time'
val.strftime(layout.time_format)
when 'date'
val.strftime(layout.date_format)
when 'timestamp'
val.strftime(layout.timestamp_format)
else
val
end
else
val
end
super(key, val)
end
def field_names
layout.field_names
end
def replace_with_fresh_data(record)
self.replace record
[:@mod_id, :@record_id, :@portals, :@mods].each do |var|
self.instance_variable_set var, record.instance_variable_get(var) || {}
end
self
end
private
def method_missing (symbol, *attrs, &block)
method = symbol.to_s
return self[method] if self.key?(method)
return @portals[method] if @portals and @portals.key?(method)
if method =~ /(=)$/
return self[$`] = attrs.first if self.key?($`)
end
super
end
end # Record
end # Rfm
|
# encoding: utf-8
require 'csv'
module ApplicationHelper
include DataFormat
include DateHelper
def period_label action_name = :report
if action_name.to_s == 'report'
'报告起止日期'
elsif action_name.to_s == 'bill'
'账单起止日期'
else
'交易起止日期'
end
end
def period_values obj,action_name = :report
begin_at = obj.try :begin_at
end_at = obj.try :end_at
created_at = obj.try :created_at
if action_name.to_s == 'report'
if created_at.present?
if obj.merchant?
"#{time_to_sstr(created_at - 6.months)} 至 #{time_to_sstr(created_at-1.month)}"
else
"#{time_to_sstr(created_at - 12.months)} 至 #{time_to_sstr(created_at-1.month)}"
end
end
else
"#{time_to_pstr(begin_at)} 至 #{time_to_pstr(end_at)}"
end
end
def truncate_id str
_str = str.blank? ? "" : "cmp@".include?(str[0]) ? str[1..-1] : str;
return _str if _str.length <= 9
_str[0...4] + "**" + _str[_str.length-4..._str.length]
end
def grad_icon v
return '' if v.nil?
html = '<span class="grad_ico">'
v = v.to_i
if v== 0
html << image_tag('shuju_main_15.png')
elsif v > 0
html << image_tag('shuju_main_11.png')
else
html << image_tag('shuju_main_18.png')
end
raw html
end
def parse_str str
str.present? ? CSV.parse_line(str) : []
end
def mani_array count,array,row,column,category
_array = [].concat(array)
comsume_sum_array = []
array1= _array.select { |item|
item[row].blank?||item[row]==''||item[row]==category
}
_array.select!{ |item|
item[row].present? && item[row] !='' && item[row] !=category
}
_array.sort! {|a,b| b[column].to_f <=> a[column].to_f}
_array[0...count].each_with_index do |item,index|
a=[]
a << item[row]||''
a << item[column].to_f
comsume_sum_array << a
end
if count < _array.size
comsume_sum_array << [category,(_array[count..._array.size].concat array1).map {|a| a[column].to_i}.reduce(&:+)]
else
if array1.size>0
comsume_sum_array << [category,array1.map{|a| a[column].to_i}.reduce(&:+)]
else
comsume_sum_array
end
end
end
def percent_str v
if v%5 !=0
v = ((v + 4)/5).to_i * 5;
elsif v==0
v=5
end
if v.to_i >= 55
"后#{105 - v.to_i}%"
else
"前#{v.to_i}%"
end
end
def tr v
items = (v||'').split ','
raw(items.size > 1 ? "#{items.first}等#{items.size}个" : items[0])
end
def trans_field_helper fields
fields=(fields||'').split(",")
[].tap do |result|
fields.each do |field|
result << TRANS_MAPPING[field.to_sym]
end
end
end
def trans_field_header type=:merchant
[].tap do |result|
trans_field_keys(type).each do |field|
result << TRANS_MAPPING[field.to_sym]
end
end
end
def trans_field_keys type=:merchant
@trans_field_keys ||= (RulePush.fields(current_user.account,type)||'').split(',')
end
def get_card_remark value
end
def query_code query_code,report_code
if query_code && query_code[1...2] == 'U'
report_code
else
query_code || report_code
end
end
def current_user
session[:user]||User.new
end
def search_module_name
case action_name
when 'index'
'查询'
when 'bill'
'账单'
when 'data'
'报告'
end
end
def error
flash[:error]
end
def g h, *args
return nil if h.nil?
item = h
args.each do |key|
break if item.nil?
item = item[key.to_s]
end
item
end
def e obj
[].tap do |a|
obj.each do |v|
a << ["#{raw v[0]}", v[1]]
end
end
end
def n_to_ten_days num
TEN_DAYS[num]
end
def c data, i, m_k, o = REPORT_MAPPING
i = i.to_s
m_k = m_k.to_s
result = {
"customerType" => [],
"amountProp" => [],
"countProp" => [],
"personProp" => [],
"pieChartData" => []
}
o[i][m_k].each do |t|
item = data.select {|v| v[m_k] == t}
result.each do |k, v|
v << (item.length > 0 ? item[0][k] : (k==m_k ? t : 0)) if k!="pieChartData"
end
end
result["customerTypeCount"] = o[i]["customerTypeCount"] if i == "indexLoyalty"
result
end
def get_one array
if array.present?
if array.size>1
"#{array[0]}等"
else
array[0]
end
else
""
end
end
def short_s data, placement = "top"
result = []
(data.is_a?(Array) ? data : data.split(",")).each do |item|
result << "<span class='string_tooltip' data-toggle='tooltip' data-placement='#{placement}' title='#{item}'>#{truncate_id item}</span>"
end
result.join "<br/>"
rescue => e
""
end
end
|
class Adminpanel::KrowspacesController < ApplicationController
before_action :authenticate_user!
before_action :admin_only
before_action :set_krowspace , only: [:createseats,:show, :edit, :update, :destroy]
# GET /krowspaces
# GET /krowspaces.json
def createseats
end
def index
@krowspaces = Krowspace.all
end
# GET /krowspaces/1
# GET /krowspaces/1.json
def show
end
# GET /krowspaces/new
def new
@krowspace = Krowspace.new
end
# GET /krowspaces/1/edit
def edit
end
# POST /krowspaces
# POST /krowspaces.json
def create
@krowspace = Krowspace.new(krowspace_params)
respond_to do |format|
if @krowspace.save
@krowspace.seat_number.times do |i|
s = Seat.new
s.seat_number = i
s.krowspace_id = @krowspace.id
s.save
end
format.html { redirect_to adminpanel_krowspace_path(@krowspace), notice: 'Krowspace was successfully created.' }
format.json { render :show, status: :created, location: @krowspace }
else
format.html { render :new }
format.json { render json: @krowspace.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /krowspaces/1
# PATCH/PUT /krowspaces/1.json
def update
respond_to do |format|
if @krowspace.update(krowspace_params)
format.html { redirect_to adminpanel_krowspace_path(@krowspace), notice: 'Krowspace was successfully updated.' }
format.json { render :show, status: :ok, location: @krowspace }
else
format.html { render :edit }
format.json { render json: @krowspace.errors, status: :unprocessable_entity }
end
end
end
# DELETE /krowspaces/1
# DELETE /krowspaces/1.json
def destroy
@krowspace.destroy
respond_to do |format|
format.html { redirect_to krowspaces_url, notice: 'Krowspace was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_krowspace
@krowspace = Krowspace.find(params[:id])
end
def admin_only
unless current_user.admin?
redirect_to root_path, :alert => "Access denied."
end
end
def krowspace_params
params.require(:krowspace).permit(:name, :description, :active, :street, :city, :state, :zip, seats_attributes: [:id, :description, :done, :_destroy])
end
# Never trust parameters from the scary internet, only allow the white list through.
end
|
require 'spec_helper'
describe AppJournal do
subject do
Class.new do
include AppJournal
def services
[
Service.new(name: 's1'),
Service.new(name: 's2')
]
end
end.new
end
describe '#journal' do
let(:journal) { hash_from_fixture('journal') }
let(:journal_client) do
# Note that the journal_client has already been stubbed in the
# spec helper. Retrieving here just so we can test expectations.
PanamaxAgent.journal_client
end
it 'invokes get_entries_by_fields on journal client' do
service_names = subject.services.map(&:unit_name)
expect(journal_client).to receive(:list_journal_entries)
.with(service_names, nil)
subject.journal
end
it 'returns the service journal' do
expect(subject.journal).to eq journal
end
context 'when a cursor is supplied' do
let(:cursor) { 'c2' }
it 'passes the cursor to the journal_client' do
service_names = subject.services.map(&:unit_name)
expect(journal_client).to receive(:list_journal_entries)
.with(service_names, cursor)
subject.journal(cursor)
end
end
end
end
|
#coding: utf-8
class Book < ActiveRecord::Base
# attr_accessible :user_id, :user, :name, :book_file, :book_file_path
has_attached_file :book_file, url: ":rails_root/books/:year/:month/:day/:id.book", path: ":rails_root/books/:year/:month/:day/:id.book"
do_not_validate_attachment_file_type :book_file
validates :book_file, presence: false
validates :name, presence: true
validates :user_id, presence: true
belongs_to :user
has_many :study_lists, dependent: :nullify
after_create :save_file_path
after_create :clean_book
def save_file_path
self.book_file_path = book_file.path
save
end
def clean_book
f = File.open(book_file.path,"r:UTF-8")
text = f.read
f.close
text.gsub!(/ /," ")
f = File.open(book_file.path,"w")
f.puts(text)
f.close
end
def partial
end
end
|
# Instead of using spec_helper, I'm using the twice as fast custom helper
# for active record objects.
require 'spec_active_record_helper'
require 'hydramata/works/predicates/storage'
require 'hydramata/works/linters/implement_predicate_interface_matcher'
module Hydramata
module Works
module Predicates
describe Storage do
subject { described_class.new }
let(:identity) { 'http://hello.com/world' }
let(:name_for_application_usage) { 'hello-world' }
let(:predicate) do
described_class.create(
identity: identity,
name_for_application_usage: name_for_application_usage,
datastream_name: 'descMetadata',
value_parser_name: 'SimpleParser',
indexing_strategy: 'dsti',
validations: '{ "presence": { "on": "create" } }'
)
end
it { should implement_predicate_interface }
context '#to_predicate' do
it 'coerces itself to a predicate' do
expect(subject.to_predicate).to implement_predicate_interface
end
end
context '.find_by_identity!' do
it 'returns a Predicate object when identity exists' do
predicate # creating the object
expect(described_class.find_by_identity!(identity)).to implement_predicate_interface
end
it 'returns a Predicate object when finding by name_for_application_usage' do
predicate # creating the object
expect(described_class.find_by_identity!(name_for_application_usage)).to implement_predicate_interface
end
it 'returns nil when identity is missing' do
# @TODO - Should this be a NullPredicate?
expect { described_class.find_by_identity!(identity) }.to raise_error
end
end
context '.existing_attributes_for' do
it 'returns the existing predicate attributes' do
predicate
keys = [
:id,
:identity,
:name_for_application_usage,
:datastream_name,
:value_parser_name,
:indexing_strategy
]
actual_values = described_class.existing_attributes_for(identity).values_at(keys)
# Because date comparisons are a bit wonky
expect(actual_values).to eq(predicate.attributes.values_at(keys))
end
it 'returns the identity if a matching predicate was not found' do
expect(described_class.existing_attributes_for(identity)).to eq(identity: identity)
end
it 'handles connection failed' do
expect(described_class).to receive(:find_by_identity!).and_raise(ActiveRecord::ConnectionNotEstablished)
expect(described_class.existing_attributes_for(identity)).to eq(identity: identity)
end
it 'has many work types' do
expect(subject.work_types).to eq([])
end
it 'has many predicate_sets' do
expect(subject.predicate_sets).to eq([])
end
it 'has many predicate_set_presentations' do
expect(subject.predicate_set_presentations).to eq([])
end
end
end
end
end
end
|
class Membership < ApplicationRecord
belongs_to :beerclub
belongs_to :user
end
|
Rails.application.routes.draw do
resources :patients
resources :doctors
resources :appointments, only: [:show]
end
|
class Sponsor < ApplicationRecord
has_many :menus
end
|
module Hoarder
class Storage
def initialize(path)
@absolute_path = path
@config = load_config("#{@absolute_path}/hoarder.yml")
@public = @config['public'] || true
@connection = set_connection(@config['provider'], @config)
@locker = set_locker(@config['container'], @public)
end
def absolute_path
@absolute_path
end
def locker
@locker
end
def public
@public
end
def load_config(config_file)
if FileTest.exist?(config_file)
begin
config = File.open(config_file) {|yf| YAML::load(yf)} || {}
validate_config(config)
rescue
raise "Unable to load config file #{config_file}."
end
else
raise "Missing config file #{config_file}."
end
config
end
private :load_config
def set_connection(provider, options = {})
Fog::Storage.new({
:provider => 'Rackspace',
:rackspace_api_key => options['rackspace_api_key'],
:rackspace_username => options['rackspace_username']
})
end
private :set_connection
def set_locker(name, make_public)
locker = @connection.directories.get(name)
locker.nil? ? @connection.directories.create(:key => name, :public => make_public) : locker
end
private :set_locker
def validate_config(config)
raise if config.empty?
end
private :validate_config
end
end
|
class CommentSerializer < ActiveModel::Serializer
attributes :id, :text, :rating, :created_at
belongs_to :meme
end
|
# encoding: utf-8
control "V-54031" do
title "Procedures and restrictions for import of production data to development databases must be documented, implemented, and followed."
desc "Data export from production databases may include sensitive data. Application developers may not be cleared for or have need-to-know to sensitive data. Any access they may have to production data would be considered unauthorized access and subject the sensitive data to unlawful or unauthorized disclosure.false"
impact 0.5
tag "check": "If the database being reviewed is not a production database or does not contain sensitive data, this check is Not a Finding.
Review documented policy, procedures and proof of implementation for restrictions placed on data exports from the production database.
Policy and procedures should include that only authorized users have access to DBMS export utilities and that export data is properly sanitized prior to import to a development database.
Policy and procedures may also include that developers be granted the necessary clearance and need-to-know prior to import of production data.
If documented policy, procedures and proof of implementation are not present or complete, this is a Finding.
If methods to sanitize sensitive data are required and not documented or followed, this is a Finding."
tag "fix": "Develop, document and implement policy and procedures that provide restrictions for production data export.
Require users and administrators assigned privileges that allow the export of production data from a production database to acknowledge understanding of export restrictions.
Restrict permissions allowing use or access to database export procedures or functions to authorized users.
Ensure sensitive data from production is sanitized prior to import to a development database (O112-BP-023300).
Grant access and need-to-know to developers where allowed by policy."
# Write Check Logic Here
end |
require 'func/call_instance'
require 'func/callable'
require 'func/init_ivars'
require 'func/version'
class Func
extend CallInstance
include InitIvars
include Callable
def call
raise NotImplementedError, 'Func must be subclassed with a no-arg `call` method'
end
end
|
require 'vanagon/engine/base'
describe 'Vanagon::Engine::Base' do
let (:platform_without_ssh_port) {
plat = Vanagon::Platform::DSL.new('debian-6-i386')
plat.instance_eval("platform 'debian-6-i386' do |plat|
plat.ssh_port nil
end")
plat._platform
}
let (:platform) {
plat = Vanagon::Platform::DSL.new('debian-6-i386')
plat.instance_eval("platform 'debian-6-i386' do |plat|
end")
plat._platform
}
describe '#select_target' do
it 'raises an error without a target' do
base = Vanagon::Engine::Base.new(platform)
expect { base.select_target }.to raise_error(Vanagon::Error)
end
it 'returns a target if one is set' do
base = Vanagon::Engine::Base.new(platform, 'abcd')
expect(base.select_target).to eq('abcd')
end
end
describe '#validate_platform' do
it 'raises an error if the platform is missing a required attribute' do
expect{ Vanagon::Engine::Base.new(platform_without_ssh_port).validate_platform }.to raise_error(Vanagon::Error)
end
it 'returns true if the platform has the required attributes' do
expect(Vanagon::Engine::Base.new(platform).validate_platform).to be(true)
end
end
describe "#retrieve_built_artifact" do
it 'creates a new output dir' do
base = Vanagon::Engine::Base.new(platform)
allow(Vanagon::Utilities).to receive(:rsync_from)
expect(FileUtils).to receive(:mkdir_p)
base.retrieve_built_artifact([], false)
end
it 'rsync uses normal output dir when no_package param is false' do
base = Vanagon::Engine::Base.new(platform, 'abcd')
allow(FileUtils).to receive(:mkdir_p)
expect(Vanagon::Utilities).to receive(:rsync_from).with('/output/*', 'root@abcd', 'output/', 22)
base.retrieve_built_artifact([], false)
end
it 'rsync only contents of parameter if no_package is true' do
base = Vanagon::Engine::Base.new(platform, 'abcd')
allow(FileUtils).to receive(:mkdir_p)
expect(Vanagon::Utilities).to receive(:rsync_from).with('foo/bar/baz.file', 'root@abcd', 'output/', 22)
base.retrieve_built_artifact(['foo/bar/baz.file'], true)
end
it 'rsync only contents of parameter with multiple entries if no_package param is true' do
base = Vanagon::Engine::Base.new(platform, 'abcd')
allow(FileUtils).to receive(:mkdir_p)
expect(Vanagon::Utilities).to receive(:rsync_from).with('foo/bar/baz.file', 'root@abcd', 'output/', 22)
expect(Vanagon::Utilities).to receive(:rsync_from).with('foo/foobar/foobarbaz.file', 'root@abcd', 'output/', 22)
base.retrieve_built_artifact(['foo/bar/baz.file', 'foo/foobar/foobarbaz.file'], true)
end
end
end
|
# frozen_string_literal: true
require 'stats_console_writer'
describe StatsConsoleWriter do
before do
@stats_service = PageStatsService.new
log_reader = LogFileReader.new
@visits = log_reader.read(path: "#{RSPEC_ROOT}/fixtures/webserver.log")
end
describe 'write_total_visits' do
it 'prints total visits' do
expect do
StatsConsoleWriter.new.write_total_visits(
pages_stats: @stats_service.ranked_total_visits(visits: @visits)
)
end.to output(
<<~HEREDOC
Total page views:
/help_page/1 6 visits
/about/2 3 visits
/contact 3 visits
/home 3 visits
/index 3 visits
/about 2 visits
HEREDOC
).to_stdout
end
end
describe 'write_unique_visits' do
it 'prints unique visits' do
expect do
StatsConsoleWriter.new.write_unique_visits(
pages_stats: @stats_service.ranked_unique_visits(visits: @visits)
)
end.to output(
<<~HEREDOC
Unique page views:
/help_page/1 5 unique views
/home 3 unique views
/index 3 unique views
/about 2 unique views
/about/2 2 unique views
/contact 2 unique views
HEREDOC
).to_stdout
end
end
end
|
class Post < ApplicationRecord
has_one_attached :image, dependent: :destroy
validates_presence_of :title, :content
validates_uniqueness_of :title
before_validation :set_slug
private
def set_slug
self.slug = title.downcase.strip.gsub(' ', '-').gsub(/[^0-9a-z- ]/i, '')
end
end
|
namespace :dummy do
desc "Hydrate the database with some dummy data to make it easier to develop"
task :reset => :environment do
# Write some Ruby to quickly create some records in your tables.
# If it's helpful, you can use methods from the Faker gem for random data:
# https://github.com/stympy/faker
end
end
|
class ProMonitor
class_attribute :current_aggregation
def self.handle_action(action, model)
begin
return unless enabled?
change = ProMonitor::Change.create(action, model)
if ProMonitor.aggregating?
ProMonitor.current_aggregation << change
else
publish_changes(ProMonitor::Aggregation.new([change]))
end
rescue StandardError => e
ProMonitor.logger.error "ProMonitor.handle_action error: #{e.message}"
ProMonitor.logger.error e.backtrace.join("\n")
raise e
end
end
def self.aggregate_changes(options = {})
previous_aggregation = self.current_aggregation
self.current_aggregation = aggregation = ProMonitor::Aggregation.new
begin
yield
ensure
self.current_aggregation = previous_aggregation
end
aggregation
end
def self.publish_changes(aggregation)
ProMonitor.config.publisher_classes.each do |publisher_class|
publisher_class.new(aggregation).publish
end
end
def self.aggregate_and_publish
aggregation = aggregate_changes do
yield
end
publish_changes(aggregation)
aggregation
end
def self.aggregating?
!!current_aggregation
end
def self.config
@config ||= ProMonitor::Config.new
end
def self.configure
yield(self.config) if block_given?
end
def self.logger
Rails.logger
end
def self.enabled?
true # TODO: put this in config
end
end |
class AddFieldsFromRrhh < ActiveRecord::Migration
def change
[:especialidades_medicas_cantidad_cad, :cirugia_general_cantidad_cad, :medicina_emergencia_cantidad_cad].each do |meta|
add_column :providers, meta, :decimal unless column_exists?(:providers, meta)
end
end
end
|
require "usersession"
require "userdata"
require "userids"
require "userlogindata"
require "configdata"
require "participant"
require "controller"
require "connections"
include Datasave
##############################################################################
class AgeismExperiment
##############################################################################
# This is the experiment class for the Ageism experiment.
# It contains all control and collected data during an experiment.
attr_reader :running, :allow_connections, :can_start, :completed
attr_reader :usersonline, :usercomputerid, :userstatus, :userscreen
attr_reader :phase, :state, :guesscomplete
attr_reader :userids, :userdata, :interactions, :allinteractions
attr_reader :userconnections, :sessions
attr_reader :guessindex, :activities, :validactivities
attr_reader :activeindex, :totalsactivities
attr_reader :resultscompletecount, :resultscreen
attr_reader :completedexperiment, :completedexperimentcount
##############################################################################
def resetabledata()
##############################################################################
# Rails.logger.debug("def " + __method__.to_s)
@activities = Array.new(2){|jj| Array.new(3){|kk| Array.new(41){|mm| Hash.new()}}}
@totalsactivities = Array.new(2){|jjj| Array.new(3){|fff| Hash[:flip2 => 0, :flip4 => 0, :split2 => 0, :split4 => 0, :accept => 0, :challenge => 0, :lies => 0, :score => 0]}}
@validactivities = Hash.new()
@interactions = Array.new(41){|pp| Array.new(2){|ii| Array.new(6){|jj| Array.new(6,0)}}}
@allinteractions = Array.new(41){|pp| Array.new(2){|ii| Array.new}}
@guesscomplete = Array.new(2){|rr| Array.new(41,false)}
@guesscompletecount = Array.new(2,0)
@sendcomplete = Array.new(2){|rr| Array.new(41,false)}
@sendcompletecount = Array.new(2,0)
@receivecomplete = Array.new(2){|rr| Array.new(41,false)}
@receivecompletecount = Array.new(2,0)
@resultscompletecount = Array.new(2,0)
@resultscomplete = Array.new(2){|rr| Array.new(41,false)}
@resultsexitcount = Array.new(2,0)
@resultsexit = Array.new(2){|rr| Array.new(41,false)}
@completedexperiment = Array.new(41,false)
@completedexperimentcount = 0
@activeindex = 0
@guessindex = 0
@numberguess = 0
@running = false
@completed = false
@phase = 0
@state = 0
@resultscreen = 0
@lies = Array.new(3)
@challenges = Array.new(3)
# Rails.logger.debug("@totalsactivities = " + @totalsactivities.inspect)
end
##############################################################################
def cleanuserdata()
##############################################################################
@can_start = false
@usersonline.fill(false)
@usercomputerid.fill("")
@userstatus.fill("Not Connected")
@userscreen.fill(0)
@userdata.fill(nil)
@allow_connections = false
@usercount = 0
@userids = UserIds.new()
@userconnections = Connections.new()
@sessions = UserSession.new()
for i in 1..40 do
@userdata[i] = UserData.new(i)
end
initinteractions()
end
##############################################################################
def initialize()
##############################################################################
# Rails.logger.debug("def " + __method__.to_s + " Called by : " + __callee__.to_s)
resetabledata()
@usersonline = Array.new(41)
@usercomputerid = Array.new(41)
@userstatus = Array.new(41)
@userscreen = Array.new(41)
@userdata = Array.new(41)
cleanuserdata()
end
##############################################################################
def start()
##############################################################################
@running = true if @can_start
generatebasefilename() if @running
@state = 1 if @running
@phase = 1 if @running
return @running
end
##############################################################################
def reset()
##############################################################################
@running = false
@state = 0
@phase = 0
resetabledata()
initinteractions()
for i in 1..40 do
@userdata[i].reset()
end
end
##############################################################################
def shouldexitresults(uid)
##############################################################################
returnvalue = false
returnvalue = true if @resultscompletecount[@activeindex] == $gUserCount
userexited(uid,returnvalue)
return returnvalue
end
##############################################################################
def userexited(uid,exitflag)
##############################################################################
if exitflag
@resultsexit[@activeindex][uid] = true
@resultsexitcount[@activeindex] = @resultsexit[@activeindex].count(true)
end
end
def genuserexit(uid)
@resultsexit[@activeindex][uid] = true
@resultsexitcount[@activeindex] = @resultsexit[@activeindex].count(true)
end
##############################################################################
def activestate()
##############################################################################
returnvalue = $gExperiment.state == Constants::StateSend1 || $gExperiment.state == Constants::StateSend2 ? true:false
return returnvalue
end
##############################################################################
def logoffalluser()
##############################################################################
cleanuserdata()
end
##############################################################################
def reguser(userid, computerid)
# This information is displayed on the controller screen. When the
# "useronline" is set to true the green indicator is turned on and the
# ip address is displayed.
##############################################################################
@usersonline[userid] = true
@usercomputerid[userid] = computerid.to_s
@usercount = @usersonline.count(true)
canstart()
Rails.logger.debug("reguser - userid = " + userid.to_s)
Rails.logger.debug("reguser - usercount = " + @usercount.to_s)
end
##############################################################################
def updateuserstatus(uid, statusmsg)
# Update the status message that is displayed on the controller screen.
##############################################################################
@userstatus[uid] = statusmsg.to_s
end
##############################################################################
def newuser(mysessionid, computerid, group)
##############################################################################
newsession = nil
if @userconnections.add(mysessionid, computerid)
newsession = @sessions.newuser(mysessionid, computerid)
newsession[:group] = group
if $gExperiment.userids.adduser(newsession)
# newsession[:mydata] = @userdata[newsession[:myuserid].to_i]
# Rails.logger.debug("newsession = " + newsession.to_yaml)
else
newsession = nil
end
end
return newsession
end
##############################################################################
def canstart()
##############################################################################
returnvalue = @usercount >= $gRequiredUsers ? true:false
@can_start = returnvalue
return returnvalue
end
def endexperiment()
@completed = true
end
def candisablelogins()
returnvalue = @usercount == 0 ? true : false
return returnvalue
end
##############################################################################
def controllerupdate()
##############################################################################
if @running
# Rails.logger.debug("controllerupdate - @state = " + @state.to_s)
case @state
when Constants::StateStart
# Do nothing
Rails.logger.info("Entering StateGuess1")
@state = Constants::StateGuess1
when Constants::StateGuess1
@activeindex = 0
@guessindex = 0
if @guesscompletecount[@guessindex] == $gUserCount
Rails.logger.info("Entering StateSend1")
@state = Constants::StateSend1
@phase = 1
end
when Constants::StateSend1
# Rails.logger.debug("controllerupdate - @sendcompletecount[@activeindex] = " + @sendcompletecount[@activeindex].to_s)
if @sendcompletecount[@activeindex] == $gUserCount
Rails.logger.info("Entering StateRec1")
@state = Constants::StateRec1
@phase = 2
end
when Constants::StateRec1
# Rails.logger.debug("controllerupdate - @receivecompletecount[@activeindex] = " + @receivecompletecount[@activeindex].to_s)
if @receivecompletecount[@activeindex] == $gUserCount
Rails.logger.info("Entering StateResults1")
updateusertotals()
@state = Constants::StateResults1
@resultscreen = 1
@phase = 2
@guessindex = 1
end
when Constants::StateResults1
# Rails.logger.debug("@activeindex = " + @activeindex.inspect)
# Rails.logger.debug("@resultsexitcount = " + @resultsexitcount.inspect)
if @resultsexitcount[@activeindex] == $gUserCount
@state = Constants::StateGuess2
@activeindex = 1
Rails.logger.info("Entering StateGuess2")
end
when Constants::StateGuess2
if @guesscompletecount[@guessindex] == $gUserCount
Rails.logger.info("Entering StateSend2")
@state = Constants::StateSend2
@phase = 3
end
when Constants::StateSend2
if @sendcompletecount[@activeindex] == $gUserCount
Rails.logger.info("Entering StateRec2")
@state = Constants::StateRec2
@phase = 4
end
when Constants::StateRec2
if @receivecompletecount[@activeindex] == $gUserCount
updateusertotals()
saveguessdata()
Rails.logger.info("Entering StateResults2")
@state = Constants::StateResults2
@resultscreen = 2
@phase = 4
end
when Constants::StateResults2
if @resultscompletecount[@activeindex] == $gUserCount
@state = Constants::StateFinal
@phase = 4
end
when Constants::StateFinal
saveactivitydata()
@state = Constants::StatePayout
when Constants::StatePayout
if @completedexperimentcount == $gUserCount
savepayoutdata()
endexperiment()
@state = Constants::Completed
end
when Constants::Completed
else
end
end
end
##############################################################################
def guessok(uid)
##############################################################################
@guesscomplete[@guessindex][uid] = true
@guesscompletecount[@guessindex] = @guesscomplete[@guessindex].count(true)
end
##############################################################################
def senddone(uid)
##############################################################################
# Rails.logger.debug("def " + __method__.to_s + " Called by : " + __callee__.to_s)
@sendcomplete[@activeindex][uid] = true
@sendcompletecount[@activeindex] = @sendcomplete[@activeindex].count(true)
end
##############################################################################
def recdone(uid)
##############################################################################
# Rails.logger.debug("def " + __method__.to_s + " Called by : " + __callee__.to_s)
# Rails.logger.debug("User ID = " + uid.to_s)
@receivecomplete[@activeindex][uid] = true
@receivecompletecount[@activeindex] = @receivecomplete[@activeindex].count(true)
end
##############################################################################
def resultsdone(uid)
##############################################################################
# Rails.logger.debug("def " + __method__.to_s + " Called by : " + __callee__.to_s)
# Rails.logger.debug("User ID = " + uid.to_s)
@resultscomplete[@activeindex][uid] = true
@resultscompletecount[@activeindex] = @resultscomplete[@activeindex].count(true)
end
def finished(uid)
@completedexperiment[uid] = true
@completedexperimentcount = @completedexperiment.count(true)
end
##############################################################################
def experimentcontol(sendhash)
##############################################################################
unless @running
if $gAllowLogins == "Yes"
unless sendhash[:controller] == "wait"
sendhash[:redirect] = true
sendhash[:path] = "wait"
end
elsif
sendhash[:redirect] = true
sendhash[:path] = "login"
end
end
if $gAutoplay == "On"
sendhash[:autoplay] = true
else
sendhash[:autoplay] = false
end
end
##############################################################################
def redirectme(sendhash, contoller)
##############################################################################
sendhash[:redirect] = true
sendhash[:path] = contoller
end
##############################################################################
def getgroup(id)
##############################################################################
groupid = @userdata[id.to_i].group
# Rails.logger.debug("groupid from getgroup = " + groupid.to_s)
return groupid
end
##############################################################################
def recordsenddata(sid,rid,flip,split,grouping)
##############################################################################
sg = getgroup(sid)
rg = getgroup(rid)
gidx = Constants::Grouping[grouping]
@activities[@activeindex][gidx][sid][rid] = Hash.new()
@activities[@activeindex][gidx][sid][rid][:sid] = sid
@activities[@activeindex][gidx][sid][rid][:rid] = rid
@activities[@activeindex][gidx][sid][rid][:grouping] = grouping
@activities[@activeindex][gidx][sid][rid][:sg] = sg
@activities[@activeindex][gidx][sid][rid][:rg] = rg
@activities[@activeindex][gidx][sid][rid][:flip] = flip
@activities[@activeindex][gidx][sid][rid][:split] = split
@activities[@activeindex][gidx][sid][rid][:accept] = 0
@activities[@activeindex][gidx][sid][rid][:challenge] = 0
Rails.logger.debug(">>> recordsenddata - sid = " + sid.to_s + " rid = " + rid.to_s + " flip = " + flip.to_s + " split = " + split.to_s + " grouping = " + grouping.inspect + " sg = " + sg.to_s + " rg = " + rg.to_s)
@allinteractions[rid][@activeindex].push(sid) unless @allinteractions[rid][@activeindex].include?(sid)
@allinteractions[sid][@activeindex].push(rid) unless @allinteractions[sid][@activeindex].include?(rid)
@userdata[rid.to_i].addreceivedaction(@activeindex,gidx, @activities[@activeindex][gidx][sid][rid] )
end
##############################################################################
def recordreceivedata(rid,sid,accept,challenge,grouping)
##############################################################################
# Rails.logger.debug("def " + __method__.to_s + " Called by : " + __callee__.to_s)
gidx = Constants::Grouping[grouping]
# Rails.logger.debug("******** @activities[@activeindex][gidx][sid][rid]")
# Rails.logger.debug("B - " +@activities[@activeindex][gidx][sid][rid].inspect)
@activities[@activeindex][gidx][sid][rid][:accept] = accept.to_i
@activities[@activeindex][gidx][sid][rid][:challenge] = challenge.to_i
# Rails.logger.debug("A - " +@activities[@activeindex][gidx][sid][rid].inspect)
@allinteractions[sid][@activeindex].push(rid) unless @allinteractions[sid][@activeindex].include?(rid)
@allinteractions[rid][@activeindex].push(sid) unless @allinteractions[rid][@activeindex].include?(sid)
@userdata[sid.to_i].historysendadd(@activeindex,gidx, @activities[@activeindex][gidx][sid][rid])
@userdata[rid.to_i].historyrecadd(@activeindex,gidx, @activities[@activeindex][gidx][sid][rid])
Rails.logger.debug(">>> recordreceivedata - rid = " + rid.to_s + " sid = " + sid.to_s + " accept = " + accept.to_s + " challenge = " + challenge.to_s + " grouping = " + grouping.inspect)
countaction(@activeindex,gidx, sid.to_i, rid.to_i, @activities[@activeindex][gidx][sid][rid])
end
##############################################################################
def countaction(aidx, gidx, sid, rid, action)
##############################################################################
# Rails.logger.debug("def " + __method__.to_s + " Called by : " + __callee__.to_s)
if action[:flip] == 2
@totalsactivities[aidx][gidx][:flip2] += 1
# @userdata[rid].addflip2(aidx,gidx)
@userdata[sid].addflip2(aidx,gidx)
elsif action[:flip] == 4
@totalsactivities[aidx][gidx][:flip4] += 1
# @userdata[rid].addflip4(aidx,gidx)
@userdata[sid].addflip4(aidx,gidx)
end
if action[:split] == 2
@totalsactivities[aidx][gidx][:split2] += 1
@userdata[rid].addsplit2rec(aidx,gidx)
@userdata[sid].addsplit2(aidx,gidx)
elsif action[:split] == 4
@totalsactivities[aidx][gidx][:split4] += 1
# @userdata[rid].addsplit4(aidx,gidx)
@userdata[sid].addsplit4(aidx,gidx)
end
if action[:accept] == 1
@totalsactivities[aidx][gidx][:accept] += 1
@userdata[rid].addaccept(aidx,gidx)
# @userdata[sid].addaccept(aidx,gidx)
end
if action[:challenge] == 1
@totalsactivities[aidx][gidx][:challenge] += 1
@userdata[rid].addchallenge(aidx,gidx)
# @userdata[sid].addchallenge(aidx,gidx)
end
if action[:flip] == 4 && action[:split] == 2
@totalsactivities[aidx][gidx][:lies] += 1
# Rails.logger.debug("Lie rid = " + rid.to_s)
# @userdata[rid].addlie(aidx,gidx)
# Rails.logger.debug("Lie sid = " + sid.to_s)
@userdata[sid].addlie(aidx,gidx)
end
senderscore, receiverscore = getscore(action[:flip], action[:split], action[:accept])
@userdata[sid].updatesendscore(aidx, gidx, senderscore)
@userdata[rid].updaterecscore(aidx, gidx, receiverscore)
end
def updateusertotals()
for pid in 1..40
@lies[pid] = @userdata[pid].getlies(@activeindex)
@challenges[pid] = @userdata[pid].getchallenges(@activeindex)
end
# Rails.logger.debug("updateusertotals() @lies = " + @lies.inspect)
# Rails.logger.debug("updateusertotals() @challenges = " + @challenges.inspect)
for pid in 1..40
@userdata[pid].updatemytotals(@activeindex,@lies,@challenges)
end
end
##############################################################################
def getscore(flip,split,accept)
##############################################################################
receiver = 0
sender = 0
if flip == 2
if accept == 1
receiver = 1
sender = 1
else
receiver = 0
sender = 2
end
else
case split
when 2
if accept == 1
receiver = 1
sender = 3
else
receiver = 4
sender = 0
end
when 4
receiver = 2
sender = 2
end
end
return sender,receiver
end
##############################################################################
def getsaveableactivites()
##############################################################################
newline = "\n"
comma = ","
groupname = Array["Unk","Same","Diff"]
header = "Round,Gouping,SenderID,ReceiverID,Send Group, Receiver Group, Coin, Message, Challenge"
csvdata = ""
csvdata += header + newline
for aidx in 0..1
for gidx in 0..2
for sid in 1..40
@activities[aidx][gidx][sid].each_value { |activity|
nextactivity = ""
nextactivity += aidx.to_s + comma
nextactivity += groupname[gidx].to_s + comma
nextactivity += activity[:sid].to_s + comma
nextactivity += activity[:rid].to_s + comma
nextactivity += activity[:sg].to_s + comma
nextactivity += activity[:rg].to_s + comma
nextactivity += activity[:flip].to_s + comma
nextactivity += activity[:split].to_s + comma
nextactivity += activity[:challenge].to_s + newline
csvdata += nextactivity.to_s
}
end
end
end
return csvdata
end
def initinteractions
@interactions[1][0][Constants::Diff] = [21,22,23,24,25,26]
@interactions[1][0][Constants::Same] = [5,6,7,8,9,10]
@interactions[1][0][Constants::Unk] = [2,3,4,27,28,29]
@interactions[2][0][Constants::Diff] = [22,23,24,25,26,27]
@interactions[2][0][Constants::Same] = [4,5,6,7,8,9]
@interactions[2][0][Constants::Unk] = [3,10,1,28,29,30]
@interactions[3][0][Constants::Diff] = [23,24,25,26,27,28]
@interactions[3][0][Constants::Same] = [4,5,6,7,8,10]
@interactions[3][0][Constants::Unk] = [9,1,2,21,29,30]
@interactions[4][0][Constants::Diff] = [24,25,26,27,28,29]
@interactions[4][0][Constants::Same] = [5,6,7,8,2,3]
@interactions[4][0][Constants::Unk] = [9,10,1,30,21,22]
@interactions[5][0][Constants::Diff] = [25,26,27,28,29,30]
@interactions[5][0][Constants::Same] = [9,10,1,2,3,4]
@interactions[5][0][Constants::Unk] = [6,7,8,21,22,23]
@interactions[6][0][Constants::Diff] = [26,27,28,29,30,21]
@interactions[6][0][Constants::Same] = [9,10,1,2,3,4]
@interactions[6][0][Constants::Unk] = [7,8,5,22,23,24]
@interactions[7][0][Constants::Diff] = [27,28,29,30,21,22]
@interactions[7][0][Constants::Same] = [8,9,1,2,3,4]
@interactions[7][0][Constants::Unk] = [10,5,6,23,24,25]
@interactions[8][0][Constants::Diff] = [28,29,30,21,22,23]
@interactions[8][0][Constants::Same] = [10,1,2,3,4,7]
@interactions[8][0][Constants::Unk] = [9,5,6,24,25,26]
@interactions[9][0][Constants::Diff] = [29,30,21,22,23,24]
@interactions[9][0][Constants::Same] = [10,1,2,5,6,7]
@interactions[9][0][Constants::Unk] = [3,4,8,25,26,27]
@interactions[10][0][Constants::Diff] = [30,21,22,23,24,25]
@interactions[10][0][Constants::Same] = [1,3,5,6,8,9]
@interactions[10][0][Constants::Unk] = [2,4,7,26,27,28]
@interactions[11][0][Constants::Diff] = [31,32,33,34,35,36]
@interactions[11][0][Constants::Same] = [15,16,17,18,19,20]
@interactions[11][0][Constants::Unk] = [12,13,14,37,38,39]
@interactions[12][0][Constants::Diff] = [32,33,34,35,36,37]
@interactions[12][0][Constants::Same] = [14,15,16,17,18,19]
@interactions[12][0][Constants::Unk] = [13,20,11,38,39,40]
@interactions[13][0][Constants::Diff] = [33,34,35,36,37,38]
@interactions[13][0][Constants::Same] = [14,15,16,17,18,20]
@interactions[13][0][Constants::Unk] = [19,11,12,39,40,31]
@interactions[14][0][Constants::Diff] = [34,35,36,37,38,39]
@interactions[14][0][Constants::Same] = [15,16,17,18,12,13]
@interactions[14][0][Constants::Unk] = [19,20,11,40,31,32]
@interactions[15][0][Constants::Diff] = [35,36,37,38,39,40]
@interactions[15][0][Constants::Same] = [19,20,11,12,13,14]
@interactions[15][0][Constants::Unk] = [16,17,18,31,32,33]
@interactions[16][0][Constants::Diff] = [36,37,38,39,40,31]
@interactions[16][0][Constants::Same] = [19,20,11,12,13,14]
@interactions[16][0][Constants::Unk] = [17,18,15,32,33,34]
@interactions[17][0][Constants::Diff] = [37,38,39,40,31,32]
@interactions[17][0][Constants::Same] = [18,19,11,12,13,14]
@interactions[17][0][Constants::Unk] = [20,15,16,33,34,35]
@interactions[18][0][Constants::Diff] = [38,39,40,31,32,33]
@interactions[18][0][Constants::Same] = [20,11,12,13,14,17]
@interactions[18][0][Constants::Unk] = [19,15,16,34,35,36]
@interactions[19][0][Constants::Diff] = [39,40,31,32,33,34]
@interactions[19][0][Constants::Same] = [20,11,12,15,16,17]
@interactions[19][0][Constants::Unk] = [13,14,18,35,36,37]
@interactions[20][0][Constants::Diff] = [40,31,32,33,34,35]
@interactions[20][0][Constants::Same] = [11,13,15,16,18,19]
@interactions[20][0][Constants::Unk] = [12,14,17,36,37,38]
@interactions[21][0][Constants::Diff] = [1,6,7,8,9,10]
@interactions[21][0][Constants::Same] = [25,26,27,28,29,30]
@interactions[21][0][Constants::Unk] = [3,4,5,22,23,24]
@interactions[22][0][Constants::Diff] = [1,2,7,8,9,10]
@interactions[22][0][Constants::Same] = [24,25,26,27,28,29]
@interactions[22][0][Constants::Unk] = [4,5,6,23,30,21]
@interactions[23][0][Constants::Diff] = [1,2,3,8,9,10]
@interactions[23][0][Constants::Same] = [24,25,26,27,28,30]
@interactions[23][0][Constants::Unk] = [5,6,7,29,21,22]
@interactions[24][0][Constants::Diff] = [1,2,3,4,9,10]
@interactions[24][0][Constants::Same] = [25,26,27,28,22,23]
@interactions[24][0][Constants::Unk] = [6,7,8,29,30,21]
@interactions[25][0][Constants::Diff] = [1,2,3,4,5,10]
@interactions[25][0][Constants::Same] = [29,30,21,22,23,24]
@interactions[25][0][Constants::Unk] = [7,8,9,26,27,28]
@interactions[26][0][Constants::Diff] = [1,2,3,4,5,6]
@interactions[26][0][Constants::Same] = [29,30,21,22,23,24]
@interactions[26][0][Constants::Unk] = [8,9,10,27,28,25]
@interactions[27][0][Constants::Diff] = [2,3,4,5,6,7]
@interactions[27][0][Constants::Same] = [28,29,21,22,23,24]
@interactions[27][0][Constants::Unk] = [1,9,10,30,25,26]
@interactions[28][0][Constants::Diff] = [3,4,5,6,7,8]
@interactions[28][0][Constants::Same] = [30,21,22,23,24,27]
@interactions[28][0][Constants::Unk] = [1,2,10,29,25,26]
@interactions[29][0][Constants::Diff] = [4,5,6,7,8,9]
@interactions[29][0][Constants::Same] = [30,21,22,25,26,27]
@interactions[29][0][Constants::Unk] = [1,2,3,23,24,28]
@interactions[30][0][Constants::Diff] = [5,6,7,8,9,10]
@interactions[30][0][Constants::Same] = [21,23,25,26,28,29]
@interactions[30][0][Constants::Unk] = [2,3,4,22,27,24]
@interactions[31][0][Constants::Diff] = [11,16,17,18,19,20]
@interactions[31][0][Constants::Same] = [35,36,37,38,39,40]
@interactions[31][0][Constants::Unk] = [13,14,15,32,33,34]
@interactions[32][0][Constants::Diff] = [11,12,17,18,19,20]
@interactions[32][0][Constants::Same] = [34,35,36,37,38,39]
@interactions[32][0][Constants::Unk] = [14,15,16,33,40,31]
@interactions[33][0][Constants::Diff] = [11,12,13,18,19,20]
@interactions[33][0][Constants::Same] = [34,35,36,37,38,40]
@interactions[33][0][Constants::Unk] = [15,16,17,39,31,32]
@interactions[34][0][Constants::Diff] = [11,12,13,14,19,20]
@interactions[34][0][Constants::Same] = [35,36,37,38,32,33]
@interactions[34][0][Constants::Unk] = [16,17,18,39,40,31]
@interactions[35][0][Constants::Diff] = [11,12,13,14,15,20]
@interactions[35][0][Constants::Same] = [39,40,31,32,33,34]
@interactions[35][0][Constants::Unk] = [17,18,19,36,37,38]
@interactions[36][0][Constants::Diff] = [11,12,13,14,15,16]
@interactions[36][0][Constants::Same] = [39,40,31,32,33,34]
@interactions[36][0][Constants::Unk] = [18,19,20,37,38,35]
@interactions[37][0][Constants::Diff] = [12,13,14,15,16,17]
@interactions[37][0][Constants::Same] = [38,39,31,32,33,34]
@interactions[37][0][Constants::Unk] = [11,19,20,40,35,36]
@interactions[38][0][Constants::Diff] = [13,14,15,16,17,18]
@interactions[38][0][Constants::Same] = [40,31,32,33,34,37]
@interactions[38][0][Constants::Unk] = [11,12,20,39,33,34]
@interactions[39][0][Constants::Diff] = [14,15,16,17,18,19]
@interactions[39][0][Constants::Same] = [40,31,32,35,36,37]
@interactions[39][0][Constants::Unk] = [11,12,13,34,37,36]
@interactions[40][0][Constants::Diff] = [15,16,17,18,19,20]
@interactions[40][0][Constants::Same] = [31,33,35,36,38,39]
@interactions[40][0][Constants::Unk] = [12,13,14,32,35,38]
@interactions[1][1][Constants::Diff] = [31,32,33,34,35,36]
@interactions[1][1][Constants::Same] = [11,20,19,18,17,16]
@interactions[1][1][Constants::Unk] = [15,14,13,37,38,39]
@interactions[2][1][Constants::Diff] = [32,33,34,35,36,37]
@interactions[2][1][Constants::Same] = [12,11,20,19,18,17]
@interactions[2][1][Constants::Unk] = [16,15,14,38,39,40]
@interactions[3][1][Constants::Diff] = [33,34,35,36,37,38]
@interactions[3][1][Constants::Same] = [13,12,11,20,19,18]
@interactions[3][1][Constants::Unk] = [17,16,15,39,40,31]
@interactions[4][1][Constants::Diff] = [34,35,36,37,38,39]
@interactions[4][1][Constants::Same] = [14,13,12,11,20,19]
@interactions[4][1][Constants::Unk] = [18,17,16,40,31,32]
@interactions[5][1][Constants::Diff] = [35,36,37,38,39,40]
@interactions[5][1][Constants::Same] = [15,14,13,12,11,20]
@interactions[5][1][Constants::Unk] = [19,18,17,31,32,33]
@interactions[6][1][Constants::Diff] = [36,37,38,39,40,31]
@interactions[6][1][Constants::Same] = [16,15,14,13,12,11]
@interactions[6][1][Constants::Unk] = [20,19,18,32,33,34]
@interactions[7][1][Constants::Diff] = [37,38,39,40,31,32]
@interactions[7][1][Constants::Same] = [17,16,15,14,13,12]
@interactions[7][1][Constants::Unk] = [11,20,19,33,34,35]
@interactions[8][1][Constants::Diff] = [38,39,40,31,32,33]
@interactions[8][1][Constants::Same] = [18,17,16,15,14,13]
@interactions[8][1][Constants::Unk] = [12,11,20,34,35,36]
@interactions[9][1][Constants::Diff] = [39,40,31,32,33,34]
@interactions[9][1][Constants::Same] = [19,18,17,16,15,14]
@interactions[9][1][Constants::Unk] = [13,12,11,35,36,37]
@interactions[10][1][Constants::Diff] = [40,31,32,33,34,35]
@interactions[10][1][Constants::Same] = [20,19,18,17,16,15]
@interactions[10][1][Constants::Unk] = [14,13,12,36,37,38]
@interactions[11][1][Constants::Diff] = [21,22,23,24,25,26]
@interactions[11][1][Constants::Same] = [1,2,3,4,5,6]
@interactions[11][1][Constants::Unk] = [7,8,9,27,28,29]
@interactions[12][1][Constants::Diff] = [22,23,24,25,26,27]
@interactions[12][1][Constants::Same] = [2,3,4,5,6,7]
@interactions[12][1][Constants::Unk] = [8,9,10,28,29,30]
@interactions[13][1][Constants::Diff] = [23,24,25,26,27,28]
@interactions[13][1][Constants::Same] = [3,4,5,6,7,8]
@interactions[13][1][Constants::Unk] = [9,10,1,29,30,21]
@interactions[14][1][Constants::Diff] = [24,25,26,27,28,29]
@interactions[14][1][Constants::Same] = [4,5,6,7,8,9]
@interactions[14][1][Constants::Unk] = [10,1,2,30,21,22]
@interactions[15][1][Constants::Diff] = [25,26,27,28,29,30]
@interactions[15][1][Constants::Same] = [5,6,7,8,9,10]
@interactions[15][1][Constants::Unk] = [1,2,3,21,22,23]
@interactions[16][1][Constants::Diff] = [26,27,28,29,30,21]
@interactions[16][1][Constants::Same] = [6,7,8,9,10,1]
@interactions[16][1][Constants::Unk] = [2,3,4,22,23,24]
@interactions[17][1][Constants::Diff] = [27,28,29,30,21,22]
@interactions[17][1][Constants::Same] = [7,8,9,10,1,2]
@interactions[17][1][Constants::Unk] = [3,4,5,23,24,25]
@interactions[18][1][Constants::Diff] = [28,29,30,21,22,23]
@interactions[18][1][Constants::Same] = [8,9,10,1,2,3]
@interactions[18][1][Constants::Unk] = [4,5,6,24,25,26]
@interactions[19][1][Constants::Diff] = [29,30,21,22,23,24]
@interactions[19][1][Constants::Same] = [9,10,1,2,3,4]
@interactions[19][1][Constants::Unk] = [5,6,7,25,26,27]
@interactions[20][1][Constants::Diff] = [30,21,22,23,24,25]
@interactions[20][1][Constants::Same] = [10,1,2,3,4,5]
@interactions[20][1][Constants::Unk] = [6,7,8,26,27,28]
@interactions[21][1][Constants::Diff] = [11,20,19,18,17,16]
@interactions[21][1][Constants::Same] = [31,40,39,38,37,36]
@interactions[21][1][Constants::Unk] = [15,14,13,35,34,33]
@interactions[22][1][Constants::Diff] = [12,11,20,19,18,17]
@interactions[22][1][Constants::Same] = [32,31,40,39,38,37]
@interactions[22][1][Constants::Unk] = [16,15,14,36,35,34]
@interactions[23][1][Constants::Diff] = [13,12,11,20,19,18]
@interactions[23][1][Constants::Same] = [33,32,31,40,39,38]
@interactions[23][1][Constants::Unk] = [17,16,15,37,36,35]
@interactions[24][1][Constants::Diff] = [14,13,12,11,20,19]
@interactions[24][1][Constants::Same] = [34,33,32,31,40,39]
@interactions[24][1][Constants::Unk] = [18,17,16,38,37,36]
@interactions[25][1][Constants::Diff] = [15,14,13,12,11,20]
@interactions[25][1][Constants::Same] = [35,34,33,32,31,40]
@interactions[25][1][Constants::Unk] = [19,18,17,39,38,37]
@interactions[26][1][Constants::Diff] = [16,15,14,13,12,11]
@interactions[26][1][Constants::Same] = [36,35,34,33,32,31]
@interactions[26][1][Constants::Unk] = [20,19,18,40,39,38]
@interactions[27][1][Constants::Diff] = [17,16,15,14,13,12]
@interactions[27][1][Constants::Same] = [37,36,35,34,33,32]
@interactions[27][1][Constants::Unk] = [11,20,19,31,40,39]
@interactions[28][1][Constants::Diff] = [18,17,16,15,14,13]
@interactions[28][1][Constants::Same] = [38,37,36,35,34,33]
@interactions[28][1][Constants::Unk] = [12,11,20,32,31,40]
@interactions[29][1][Constants::Diff] = [19,18,17,16,15,14]
@interactions[29][1][Constants::Same] = [39,38,37,36,35,34]
@interactions[29][1][Constants::Unk] = [13,12,11,33,32,31]
@interactions[30][1][Constants::Diff] = [20,19,18,17,16,15]
@interactions[30][1][Constants::Same] = [40,39,38,37,36,35]
@interactions[30][1][Constants::Unk] = [14,13,12,34,33,32]
@interactions[31][1][Constants::Diff] = [1,10,9,8,7,6]
@interactions[31][1][Constants::Same] = [21,22,23,24,25,26]
@interactions[31][1][Constants::Unk] = [5,4,3,27,28,29]
@interactions[32][1][Constants::Diff] = [2,1,10,9,8,7]
@interactions[32][1][Constants::Same] = [22,23,24,25,26,27]
@interactions[32][1][Constants::Unk] = [6,5,4,28,29,30]
@interactions[33][1][Constants::Diff] = [3,2,1,10,9,8]
@interactions[33][1][Constants::Same] = [23,24,25,26,27,28]
@interactions[33][1][Constants::Unk] = [7,6,5,29,30,21]
@interactions[34][1][Constants::Diff] = [4,3,2,1,10,9]
@interactions[34][1][Constants::Same] = [24,25,26,27,28,29]
@interactions[34][1][Constants::Unk] = [8,7,6,30,21,22]
@interactions[35][1][Constants::Diff] = [5,4,3,2,1,10]
@interactions[35][1][Constants::Same] = [25,26,27,28,29,30]
@interactions[35][1][Constants::Unk] = [9,8,7,21,22,23]
@interactions[36][1][Constants::Diff] = [6,5,4,3,2,1]
@interactions[36][1][Constants::Same] = [26,27,28,29,30,21]
@interactions[36][1][Constants::Unk] = [10,9,8,22,23,24]
@interactions[37][1][Constants::Diff] = [7,6,5,4,3,2]
@interactions[37][1][Constants::Same] = [27,28,29,30,21,22]
@interactions[37][1][Constants::Unk] = [1,10,9,23,24,25]
@interactions[38][1][Constants::Diff] = [8,7,6,5,4,3]
@interactions[38][1][Constants::Same] = [28,29,30,21,22,23]
@interactions[38][1][Constants::Unk] = [2,1,10,24,25,26]
@interactions[39][1][Constants::Diff] = [9,8,7,6,5,4]
@interactions[39][1][Constants::Same] = [29,30,21,22,23,24]
@interactions[39][1][Constants::Unk] = [3,2,1,25,26,27]
@interactions[40][1][Constants::Diff] = [10,9,8,7,6,5]
@interactions[40][1][Constants::Same] = [30,21,22,23,24,25]
@interactions[40][1][Constants::Unk] = [4,3,2,26,27,28]
end
##############################################################################
def initinteractionsdisabled
# Populates the interaction table of which user plays against which user.
##############################################################################
for id in 1..20 do
for act in 0..5 do
diff1value = 20 + id + act
diff1value = diff1value - 20 if diff1value > 40
diff2value = 20 + id + act + 6
diff2value = diff2value - 20 if diff2value > 40
same1value = 1 + id + act
same1value = same1value - 20 if same1value > 20
same2value = 1 + id + act + 6
same2value = same2value - 20 if same2value > 20
unk1value = 1 + id + act + 12 unless act > 2
unk1value = 20 + id + act + 9 unless act < 3
unk1value = unk1value - 20 if unk1value > 20 && act < 3
unk1value = unk1value - 20 if unk1value > 40 && act > 2
unk2value = 1 + id + act + 15 unless act > 2
unk2value = 20 + id + act + 12 unless act < 3
unk2value = unk2value - 20 if unk2value > 20 && act < 3
unk2value = unk2value - 20 if unk2value > 40 && act > 2
@interactions[id][0][Constants::Diff][act] = diff1value
@interactions[id][1][Constants::Diff][act] = diff2value
@interactions[id][0][Constants::Same][act] = same1value
@interactions[id][1][Constants::Same][act] = same2value
@interactions[id][0][Constants::Unk][act] = unk1value
@interactions[id][1][Constants::Unk][act] = unk2value
g2id = id + 20
diff1value = 21 - id - act
diff1value = diff1value + 20 if diff1value < 1
diff2value = 21 - id - act - 6
diff2value = diff2value + 20 if diff2value < 1
same1value = 21 + id + act
same1value = same1value - 20 if same1value > 40
same2value = 21 + id + act + 6
same2value = same2value - 20 if same2value > 40
unk1value = 21 + id + act + 12 unless act > 2
unk1value = 21 - id - act - 9 unless act < 3
unk1value = unk1value - 20 if unk1value > 40 && act < 3
unk1value = unk1value + 20 if unk1value < 1 && act > 2
unk2value = 21 + id + act + 15 unless act > 2
unk2value = 21 - id - act - 12 unless act < 3
unk2value = unk2value - 20 if unk2value > 40 && act < 3
unk2value = unk2value + 20 if unk2value < 1 && act > 2
@interactions[g2id][0][Constants::Diff][act] = diff1value
@interactions[g2id][1][Constants::Diff][act] = diff2value
@interactions[g2id][0][Constants::Same][act] = same1value
@interactions[g2id][1][Constants::Same][act] = same2value
@interactions[g2id][0][Constants::Unk][act] = unk1value
@interactions[g2id][1][Constants::Unk][act] = unk2value
end
end
Rails.logger.debug("id,phase,type,a1,a2,a3,b1,b2,b3")
for dbi in 1..40 do
for grp in 0..1 do
for grping in 0..2 do
Rails.logger.debug(dbi.to_s + "," + grp.to_s + "," + grping.to_s + "," + @interactions[dbi][grp][grping].join(","))
end
end
end
end
end
|
class J0850
attr_reader :options, :name, :field_type, :node
def initialize
@name = "Frequency of Indicator of Pain or Possible Pain in the last 5 days (J0850)"
@field_type = DROPDOWN
@node = "J0850"
@options = []
@options << FieldOption.new("^", "NA")
@options << FieldOption.new("1", "Indicators of pain or possible pain observed 1 to 2 days")
@options << FieldOption.new("2", "Indicators of pain or possible pain observed 3 to 4 days")
@options << FieldOption.new("3", "Indicators of pain or possible pain observed daily")
end
def set_values_for_type(klass)
return "^"
end
end
|
class Api::V1::UserInterestsController < ApplicationController
before_action :authenticate_user, only: [:update, :destroy]
# Add a user's new selected interest.
def create
if !params["user"]["interests"].nil?
UserInterest.create(user_id: current_user.id, interest_id: params["user"]["interests"]["id"])
end
render json: {
interests: current_user.interests
}
end
# Remove a user's interest.
def destroy
if !params["user"]["interests"].nil?
UserInterest.find_by(user_id: current_user.id, interest_id: params["user"]["interests"]["id"]).delete
render json: {
interests: current_user.interests
}
end
end
private
def authorize
return_unauthorized unless current_user && current_user.can_modify_user?(params[:id])
end
end
|
require 'rails_helper'
feature 'Product rendering', type: :feature do
include_context 'synced products'
scenario 'Visitor is presented with 10 products along with information' do
visit '/'
expect(page).to have_selector('.product', count: 10)
expect(page).to have_selector('.product img', count: 10)
expect(page).to have_selector('.product .name', count: 10)
expect(page).to have_selector('.product .producer', count: 10)
end
context 'when product/s become out of stock' do
include_context 'synced products'
before(:all) do
VCR.use_cassette('verve-api/common-minus-one') do
store_products = ::Remote::Product.store_products(1)
product_service = ::ProductService.new(store_products)
product_service.update_stock
end
end
scenario 'Visitor is presented with one product out of stock' do
visit '/'
expect(page).to have_selector('.product.out-of-stock', count: 1)
end
end
end |
class Sistema::Usuario < ApplicationRecord
has_secure_password
before_create :generar_numero_cuenta, :asignar_saldo_regalo
has_many :transacciones, class_name: 'Finanzas::Transaccion'
has_many :depositos, class_name: 'Finanzas::Deposito'
has_many :retiros, class_name: 'Finanzas::Retiro'
has_many :transferencias, class_name: 'Finanzas::Transferencia'
validates :nombre, :email, :password, :password_confirmation, presence: true
validates :email, :numero_cuenta, uniqueness: true
validates :email, email_format: true
private
def generar_numero_cuenta
self.numero_cuenta = Digest::SHA1.hexdigest("#{self.nombre}#{self.email}")
end
def asignar_saldo_regalo
self.balance = 2000.0
end
end
# ## Schema Information
#
# Table name: `sistema_usuarios`
#
# ### Columns
#
# Name | Type | Attributes
# ---------------------- | ------------------ | ---------------------------
# **`id`** | `bigint(8)` | `not null, primary key`
# **`nombre`** | `string` |
# **`email`** | `string` |
# **`numero_cuenta`** | `string` |
# **`balance`** | `string` |
# **`password_digest`** | `string` |
# **`created_at`** | `datetime` | `not null`
# **`updated_at`** | `datetime` | `not null`
#
|
module Ricer::Plug::Settings
class DurationSetting < FloatSetting
def self.db_value(input)
lib.human_to_seconds(input)
end
def self.to_label(input)
lib.human_duration(input)
end
def self.to_hint(options)
I18n.t('ricer.plug.settings.hint.duration', min: lib.human_duration(min(options)), max: lib.human_duration(max(options)))
end
end
end
|
# frozen_string_literal: true
# == Schema Information
#
# Table name: slots
#
# id :bigint not null, primary key
# temp :string
# created_at :datetime not null
# updated_at :datetime not null
# vending_machine_id :bigint
#
# Indexes
#
# index_slots_on_vending_machine_id (vending_machine_id)
#
# Foreign Keys
#
# fk_rails_... (vending_machine_id => vending_machines.id)
#
class Slot < ApplicationRecord
has_one :product
has_many :stocks
has_many :purchases
belongs_to :vending_machine
end
|
require './hand'
require './winning_strategy'
require './prob_strategy'
require './player'
seed1 = Random.new(314)
seed2 = Random.new(15)
player1 = Player.new('Taro', WinningStrategy.new(seed1.rand(0..2)))
player2 = Player.new('Hana', ProbStrategy.new(seed2.rand(0..2)))
100.times do |i|
next_hand1 = player1.next_hand
next_hand2 = player2.next_hand
if next_hand2.weaker_than?(next_hand1)
puts "Winner: #{player1.name}"
player1.win
player2.lose
elsif next_hand2.stronger_than?(next_hand1)
puts "Winner: #{player2.name}"
player1.lose
player2.win
else
puts "Even..."
player1.even
player2.even
end
end
puts "Total result:\n#{player1.to_string}\n#{player2.to_string}"
|
class TasksController < ApplicationController
before_action :authenticate_user!
before_action :load_task, only: %i[update destroy]
before_action :load_report, only: %i[create update]
after_action :publish_task, only: [:create]
respond_to :js
def create
@task = @report.tasks.new(task_params.merge(user_id: current_user.id))
@task.tag_list = params[:tag_list].join(',') if params[:tag_list]
@task.save!
respond_with @task
end
def update
@task.update(task_params)
respond_with @task
end
def destroy
respond_with @task.destroy
end
private
def task_params
params.require(:task).permit(:body, :status, tag_list: [])
end
def publish_task
return if @task.errors.any?
ActionCable.server.broadcast(
"/reports/#{@report.id}/tasks",
task: @task,
tags: @task.tags,
report: @report,
status: @task.status
)
end
def load_report
@report = @task.try(:report) || Report.find(params[:report_id])
end
def load_task
@task = Task.find(params[:id])
end
end
|
require 'rspec'
require_relative '../../src/core/object_change'
describe ObjectChange do
context 'Test object change on custom class object' do
before do
class MyObject
attr_accessor :internal_var
def initialize
@internal_var = 1
end
end
@custom_class_object = MyObject.new
@object_change = ObjectChange.new(@custom_class_object)
end
it 'should correctly detect that an object of a custom class didnt change if nothing is performed in the object' do
@object_change.working.internal_var
expect(@object_change.has_changed?).to eq(false)
end
it 'should correctly detect that an object of a custom class has changed when changing an instance variable' do
@object_change.working.internal_var = 2
expect(@object_change.has_changed?).to eq(true)
end
end
end |
# frozen_string_literal: true
require 'spec_helper'
describe 'mongocryptd prose tests' do
require_libmongocrypt
require_enterprise
min_server_version '7.0.0-rc0'
include_context 'define shared FLE helpers'
include_context 'with local kms_providers'
let(:mongocryptd_uri) { 'mongodb://localhost:27777' }
let(:encryption_client) do
new_local_client(
SpecConfig.instance.addresses,
SpecConfig.instance.test_options.merge(
auto_encryption_options: {
kms_providers: kms_providers,
kms_tls_options: kms_tls_options,
key_vault_namespace: key_vault_namespace,
schema_map: { 'auto_encryption.users' => schema_map },
extra_options: extra_options,
},
database: 'auto_encryption'
)
)
end
before do
skip 'This test requires crypt shared library' unless SpecConfig.instance.crypt_shared_lib_path
key_vault_collection.drop
key_vault_collection.insert_one(data_key)
encryption_client['users'].drop
end
context 'when shared library is loaded' do
let(:extra_options) do
{
crypt_shared_lib_path: SpecConfig.instance.crypt_shared_lib_path,
mongocryptd_uri: mongocryptd_uri
}
end
let!(:connect_attempt) do
Class.new do
def lock
@lock ||= Mutex.new
end
def done?
lock.synchronize do
!!@done
end
end
def done!
lock.synchronize do
@done = true
end
end
end.new
end
let!(:listener) do
Thread.new do
TCPServer.new(27_777).accept
connect_attempt.done!
end
end
after do
listener.exit
end
it 'does not try to connect to mongocryptd' do
encryption_client[:users].insert_one(ssn: ssn)
expect(connect_attempt.done?).to be false
end
end
context 'when shared library is required' do
let(:extra_options) do
{
crypt_shared_lib_path: SpecConfig.instance.crypt_shared_lib_path,
crypt_shared_lib_required: true,
mongocryptd_uri: mongocryptd_uri,
mongocryptd_spawn_args: [ '--pidfilepath=bypass-spawning-mongocryptd.pid', '--port=27777' ]
}
end
let(:mongocryptd_client) { new_local_client(mongocryptd_uri) }
it 'does not spawn mongocryptd' do
expect { encryption_client[:users].insert_one(ssn: ssn) }
.not_to raise_error
expect { mongocryptd_client.database.command(hello: 1) }
.to raise_error(Mongo::Error::NoServerAvailable)
end
end
end
|
require 'spec_helper'
describe 'scopes' do
let!(:user1) { User.create! :name => 'Mr. White' do |user| user.properties(:dashboard).theme = 'white' end }
let!(:user2) { User.create! :name => 'Mr. Blue' }
it "should find objects with existing properties" do
expect(User.with_properties).to eq([user1])
end
it "should find objects with properties for key" do
expect(User.with_properties_for(:dashboard)).to eq([user1])
expect(User.with_properties_for(:foo)).to eq([])
end
it "should records without properties" do
expect(User.without_properties).to eq([user2])
end
it "should records without properties for key" do
expect(User.without_properties_for(:foo)).to eq([user1, user2])
expect(User.without_properties_for(:dashboard)).to eq([user2])
end
it "should require symbol as key" do
[ nil, "string", 42 ].each do |invalid_key|
expect { User.without_properties_for(invalid_key) }.to raise_error(ArgumentError)
expect { User.with_properties_for(invalid_key) }.to raise_error(ArgumentError)
end
end
end
|
FactoryGirl.define do
factory :article do
tag_list 'tag1, tag2'
sequence(:article_type) {|n| n}
sequence(:link) { |n| "http://vimeo.com/1228033#{n}" }
end
end
|
require 'open-uri'
require 'json'
module Location
class GoogleAPI
def initialize
@root = "https://maps.googleapis.com/maps/api/geocode/json?address="
end
def set_location(address)
@search = address
@search.sub! ' ', '+'
@request_url = @root + @search
fetch_data
end
def fetch_data
@data = open(@request_url).read
@json = JSON.parse(@data)
@location = {
formatted_address: @json["results"][0]["formatted_address"],
lat: @json["results"][0]["geometry"]["location"]["lat"],
lng: @json["results"][0]["geometry"]["location"]["lng"]
}
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.