text stringlengths 10 2.61M |
|---|
class VisitsController < ApplicationController
before_action :find_visit, only: [:update]
def update
if @visit.update_attributes(visit_params)
@visit.update_procedures @visit.research_billing_qty, 'research_billing_qty'
@visit.update_procedures @visit.insurance_billing_qty, 'insurance_billing_qty'
flash[:success] = t(:visit)[:flash_messages][:updated]
else
@visit.errors.full_messages.each do |error|
flash[:alert] = error
end
end
end
private
def visit_params
params.require(:visit).permit(:research_billing_qty, :insurance_billing_qty, :effort_billing_qty)
end
def find_visit
@visit = Visit.find(params[:id])
end
end
|
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:omniauthable, omniauth_providers: [:facebook, :vkontakte]
has_many :events, dependent: :destroy
has_many :user_choices, dependent: :destroy
class << self
def from_omniauth(auth)
where(email: auth.info.email).first_or_create do |user|
user.uid = auth.uid
user.provider = auth.provider
user.email = auth.info.email
user.name = auth.info.name
user.password ||= Devise.friendly_token[1, 20]
user.save!
end
end
def from_vk(code)
@client = VkontakteApi::Client.new
@vk = VkontakteApi.authorize(code: code)
@user = @client.users.get(uid: @vk.user_id)[0]
where(email: @vk.email).first_or_create do |user|
user.email = @vk.email
user.name = @user.first_name + " " + @user.last_name
user.uid = @vk.user_id
user.provider = "vkontakte"
user.password ||= Devise.friendly_token[1, 20]
user.save!
end
end
end
end
|
# Source: https://launchschool.com/exercises/e0500589
# Write a method that takes a string, and then returns a hash that contains 3 entries: one represents the percentage of characters in the string that are lowercase letters, one the percentage of characters that are uppercase letters, and one the percentage of characters that are neither.
# You may assume that the string will always contain at least one character.
def letter_percentages(str)
char_arr = str.chars
total_len = char_arr.size
lower_pct = char_arr.select { |char| ('a'..'z').to_a.include?(char) }.size / total_len.to_f * 100
upper_pct = char_arr.select { |char| ('A'..'Z').to_a.include?(char) }.size / total_len.to_f * 100
neither_pct = (100 - lower_pct - upper_pct)
{ lowercase: lower_pct, uppercase: upper_pct, neither: neither_pct }
end
puts letter_percentages('abCdef 123') == { lowercase: 50, uppercase: 10, neither: 40 }
puts letter_percentages('AbCd +Ef') == { lowercase: 37.5, uppercase: 37.5, neither: 25 }
puts letter_percentages('123') == { lowercase: 0, uppercase: 0, neither: 100 }
|
require 'file_upload_cache/engine.rb'
require 'active_support/core_ext/module/attribute_accessors.rb'
require 'file_upload_cache/cached_attributes.rb'
require 'uuid'
module FileUploadCache
mattr_accessor :cache
def self.file_cache
if cache
cache
elsif defined?(Rails)
Rails.cache
else
raise "Unspecified Cache Store for File Upload Cache"
end
end
end
|
class CreateHotelDatePrices < ActiveRecord::Migration
def change
create_table :hotel_date_prices do |t|
t.date :date
t.float :price
t.integer :f2r_hotel_inventory_item_id
t.timestamps
end
end
end
|
class RouteArgument < ApplicationRecord
belongs_to :message_route, inverse_of: :route_arguments, optional: true
# validates_presence_of :message_route
validates_presence_of :key, :allow_blank => false
end
|
require 'Gosu'
require_relative '../Lives.rb'
require_relative '../bullet_types.rb'
require_relative 'being.rb'
class Player < Being
def initialize()
super
@sprite = Gosu::Image.new('../sprites/spaceship2.png')
#@engine_sfx = Gosu::Song.new('sfx/player/red_bullet_sfx.mp3')
#@explosion_sfx = Gosu::Song.new('sfx/player/red_bullet_sfx.mp3')
@lives = Lives.new(5)
@weapon = Weapon.new(RED_BULLET)
@rocket_count = 0
end
def rocket_fire(x_coord,y_coord)
@rocket_count -= 1 if @rocket_count > 0
end
def decrease_lives()
@lives.decrease()
end
def increase_lives()
@lives.increase()
end
def fireWeapon()
@weapon.fire
end
def draw(x_coord,y_coord)
@sprite.draw(x_coord,y_coord)
end
end
|
# frozen_string_literal: true
require 'bolt/task/run'
module Bolt
class Plugin
class Module
class InvalidPluginData < Bolt::Plugin::PluginError
def initialize(msg, plugin)
msg = "Invalid Plugin Data for #{plugin}: #{msg}"
super(msg, 'bolt/invalid-plugin-data')
end
end
def self.load(name, modules, opts)
mod = modules[name]
if mod&.plugin?
opts[:mod] = mod
plugin = Bolt::Plugin::Module.new(opts)
plugin.setup
plugin
else
raise PluginError::Unknown, name
end
end
attr_reader :config
def initialize(mod:, context:, config:, **_opts)
@module = mod
@config = config
@context = context
end
# This method interacts with the module on disk so it's separate from initialize
def setup
@data = load_data
@hook_map = find_hooks(@data['hooks'] || {})
if @data['config']
msg = <<~MSG.chomp
Found unsupported key 'config' in bolt_plugin.json. Config for a plugin is inferred
from task parameters, with config values passed as parameters.
MSG
raise InvalidPluginData.new(msg, name)
end
# Validate againsts the intersection of all task schemas.
@config_schema = process_schema(extract_task_parameter_schema)
validate_config(@config, @config_schema)
end
def name
@module.name
end
def hooks
(@hook_map.keys + [:validate_resolve_reference]).uniq
end
def load_data
JSON.parse(File.read(@module.plugin_data_file))
rescue JSON::ParserError => e
raise InvalidPluginData.new(e.message, name)
end
def process_schema(schema)
raise InvalidPluginData.new('config specification is not an object', name) unless schema.is_a?(Hash)
schema.each do |key, val|
unless key =~ /\A[a-z][a-z0-9_]*\z/
raise InvalidPluginData.new("config specification key, '#{key}', is not allowed", name)
end
unless val.is_a?(Hash) && (val['type'] || '').is_a?(String)
raise InvalidPluginData.new("config specification #{val.to_json} is not allowed", name)
end
type_string = val['type'] || 'Any'
begin
val['pcore_type'] = Puppet::Pops::Types::TypeParser.singleton.parse(type_string)
if val['pcore_type'].is_a? Puppet::Pops::Types::PTypeReferenceType
raise InvalidPluginData.new("Could not find type '#{type_string}' for #{key}", name)
end
rescue Puppet::ParseError
raise InvalidPluginData.new("Could not parse type '#{type_string}' for #{key}", name)
end
end
schema
end
def validate_config(config, config_schema)
config.each_key do |key|
msg = "Config for #{name} plugin contains unexpected key #{key}"
raise Bolt::ValidationError, msg unless config_schema.include?(key)
end
config_schema.each do |key, spec|
val = config[key]
unless spec['pcore_type'].instance?(val)
raise Bolt::ValidationError, "#{name} plugin expects a #{spec['type']} for key #{key}, got: #{val}"
end
val.nil?
end
nil
end
def find_hooks(hook_data)
raise InvalidPluginData.new("'hooks' must be a hash", name) unless hook_data.is_a?(Hash)
hooks = {}
# Load hooks specified in the config
hook_data.each do |hook_name, hook_spec|
unless hook_spec.is_a?(Hash) && hook_spec['task'].is_a?(String)
msg = "Unexpected hook specification #{hook_spec.to_json} in #{@name} for hook #{hook_name}"
raise InvalidPluginData.new(msg, name)
end
begin
task = @context.get_validated_task(hook_spec['task'])
rescue Bolt::Error => e
msg = if e.kind == 'bolt/unknown-task'
"Plugin #{name} specified an unkown task '#{hook_spec['task']}' for a hook"
else
"Plugin #{name} could not load task '#{hook_spec['task']}': #{e.message}"
end
raise InvalidPluginData.new(msg, name)
end
hooks[hook_name.to_sym] = { 'task' => task }
end
# Check for tasks for any hooks not already defined
(Set.new(KNOWN_HOOKS.map) - hooks.keys).each do |hook_name|
task_name = "#{name}::#{hook_name}"
begin
task = @context.get_validated_task(task_name)
rescue Bolt::Error => e
raise e unless e.kind == 'bolt/unknown-task'
end
hooks[hook_name] = { 'task' => task } if task
end
Bolt::Util.symbolize_top_level_keys(hooks)
end
def validate_params(task, params)
@context.validate_params(task.name, params)
end
def process_params(task, opts)
# opts are passed directly from inventory but all of the _ options are
# handled previously. That may not always be the case so filter them
# out now.
meta, params = opts.partition { |key, _val| key.start_with?('_') }.map(&:to_h)
params = config.merge(params)
validate_params(task, params)
meta['_boltdir'] = @context.boltdir.to_s
[params, meta]
end
def extract_task_parameter_schema
# Get the intersection of expected types (using Set)
type_set = @hook_map.each_with_object({}) do |(_hook, task), acc|
next unless (schema = task['task'].metadata['parameters'])
schema.each do |param, scheme|
next unless scheme['type'].is_a?(String)
scheme['type'] = Set.new([scheme['type']])
if acc.dig(param, 'type').is_a?(Set)
scheme['type'].merge(acc[param]['type'])
end
end
acc.merge!(schema)
end
# Convert Set to string
type_set.each do |_param, schema|
next unless schema['type']
schema['type'] = if schema['type'].size > 1
"Optional[Variant[#{schema['type'].to_a.join(', ')}]]"
else
"Optional[#{schema['type'].to_a.first}]"
end
end
end
def run_task(task, opts)
opts = opts.reject { |key, _val| key.start_with?('_') }
params, metaparams = process_params(task, opts)
params = params.merge(metaparams)
# There are no executor options to pass now.
options = { catch_errors: true }
result = @context.run_local_task(task,
params,
options).first
raise Bolt::Error.new(result.error_hash['msg'], result.error_hash['kind']) unless result.ok
result.value
end
def run_hook(hook_name, opts, value = true)
hook = @hook_map[hook_name]
# This shouldn't happen if the Plugin api is used
raise PluginError::UnsupportedHook.new(name, hook_name) unless hook
result = run_task(hook['task'], opts)
if value
unless result.include?('value')
msg = "Plugin #{name} result did not include a value, got #{result}"
raise Bolt::Plugin::PluginError::ExecutionError.new(msg, name, hook_name)
end
result['value']
end
end
def validate_resolve_reference(opts)
# Merge config with params
merged = @config.merge(opts)
params = merged.reject { |k, _v| k.start_with?('_') }
sig = @hook_map[:resolve_reference]['task']
if sig
validate_params(sig, params)
end
if @hook_map.include?(:validate_resolve_reference)
run_hook(:validate_resolve_reference, opts, false)
end
end
# These are all the same but are defined explicitly for clarity
def resolve_reference(opts)
run_hook(__method__, opts)
end
def secret_encrypt(opts)
run_hook(__method__, opts)
end
def secret_decrypt(opts)
run_hook(__method__, opts)
end
def secret_createkeys(opts = {})
run_hook(__method__, opts)
end
def puppet_library(opts, target, apply_prep)
task = @hook_map[:puppet_library]['task']
params, meta_params = process_params(task, opts)
options = {}
options[:run_as] = meta_params['_run_as'] if meta_params['_run_as']
proc do
apply_prep.run_task([target], task, params, options).first
end
end
end
end
end
|
require_relative '../lib/cart.rb'
describe Cart do
before do
@cart = Cart.new
end
context "第一種情境:不打折" do
it "第一集買 1 本" do
@cart.add({ "1st": 1, "2nd": 0, "3rd": 0, "4th": 0, "5th": 0 })
expect(@cart.calculate).to eq(100)
end
it "第一集買 3 本" do
@cart.add({ "1st": 3, "2nd": 0, "3rd": 0, "4th": 0, "5th": 0 })
expect(@cart.calculate).to eq(300)
end
end
context "第二種情境:打 5% 折扣" do
it "第一集買 1 本、第二集買 1 本" do
@cart.add({ "1st": 1, "2nd": 1, "3rd": 0, "4th": 0, "5th": 0 })
expect(@cart.calculate).to eq(190)
end
it "第一集買 2 本、第二集買 2 本" do
@cart.add({ "1st": 2, "2nd": 2, "3rd": 0, "4th": 0, "5th": 0 })
expect(@cart.calculate).to eq(380)
end
it "第一集買 1 本、第二集買 2 本" do
@cart.add({ "1st": 1, "2nd": 2, "3rd": 0, "4th": 0, "5th": 0 })
expect(@cart.calculate).to eq(290)
end
it "第一集買 2 本、第二集買 3 本" do
@cart.add({ "1st": 2, "2nd": 3, "3rd": 0, "4th": 0, "5th": 0 })
expect(@cart.calculate).to eq(480)
end
end
context "第三種情境:打 10% 折扣" do
it "第一集買 1 本、第二集買 1 本、第三集買 1 本" do
@cart.add({ "1st": 1, "2nd": 1, "3rd": 1, "4th": 0, "5th": 0 })
expect(@cart.calculate).to eq(270)
end
it "第一集買 2 本、第二集買 2 本、第三集買 3 本" do
@cart.add({ "1st": 2, "2nd": 2, "3rd": 3, "4th": 0, "5th": 0 })
expect(@cart.calculate).to eq(640)
end
it "第一集買 1 本、第二集買 2 本、第三集買 1 本" do
@cart.add({ "1st": 1, "2nd": 2, "3rd": 1, "4th": 0, "5th": 0 })
expect(@cart.calculate).to eq(370)
end
it "第一集買 2 本、第二集買 3 本、第二集買 4 本" do
@cart.add({ "1st": 2, "2nd": 3, "3rd": 4, "4th": 0, "5th": 0 })
expect(@cart.calculate).to eq(830)
end
end
context "第四種情境:打 15% 折扣" do
it "第一集買 1 本、第二集買 1 本、第三集買 1 本、第三集買 1 本" do
@cart.add({ "1st": 1, "2nd": 1, "3rd": 1, "4th": 1, "5th": 0 })
expect(@cart.calculate).to eq(340)
end
it "第一集買 2 本、第二集買 2 本、第三集買 2 本、第三集買 4 本" do
@cart.add({ "1st": 2, "2nd": 2, "3rd": 2, "4th": 4, "5th": 0 })
expect(@cart.calculate).to eq(880)
end
it "第一集買 1 本、第二集買 2 本、第三集買 3 本、第三集買 4 本" do
@cart.add({ "1st": 1, "2nd": 2, "3rd": 3, "4th": 4, "5th": 0 })
expect(@cart.calculate).to eq(900)
end
it "第一集買 1 本、第二集買 0 本、第二集買 4 本、第三集買 1 本" do
@cart.add({ "1st": 1, "2nd": 0, "3rd": 4, "4th": 1, "5th": 0 })
expect(@cart.calculate).to eq(570)
end
end
context "第五種情境:打 20% 折扣" do
it "第一集買 1 本、第二集買 1 本、第三集買 1 本、第四集買 1 本、第五集買 1 本" do
@cart.add({ "1st": 1, "2nd": 1, "3rd": 1, "4th": 1, "5th": 1 })
expect(@cart.calculate).to eq(400)
end
it "第一集買 2 本、第二集買 2 本、第三集買 2 本、第四集買 4 本、第五集買 1 本" do
@cart.add({ "1st": 2, "2nd": 2, "3rd": 2, "4th": 4, "5th": 1 })
expect(@cart.calculate).to eq(940)
end
it "第一集買 1 本、第二集買 2 本、第三集買 3 本、第四集買 4 本、第五集買 1 本" do
@cart.add({ "1st": 1, "2nd": 2, "3rd": 3, "4th": 4, "5th": 1 })
expect(@cart.calculate).to eq(960)
end
it "第一集買 1 本、第二集買 0 本、第二集買 4 本、第四集買 1 本、第五集買 1 本" do
@cart.add({ "1st": 1, "2nd": 0, "3rd": 4, "4th": 1, "5th": 1 })
expect(@cart.calculate).to eq(640)
end
end
end |
class Programme < ActiveRecord::Base
validate :date_in_the_past
def date_in_the_past
errors.add(:date, "You can't choose a date in the past.") if
!date.blank? and date < Date.today
end
end
|
#Example 1
RSpec.describe "An Example Group with positive and negative Examples" do
context 'when testing Ruby\'s build-in math library' do
it 'can do normal numeric operations' do
expect(1 + 1).to eq(2)
end
it 'generates an error when expected' do
expect{1/0}.to raise_error(ZeroDivisionError)
end
end
end
#run `rspec filter_spec.rb` in terminal
#Example 2
RSpec.describe "An Example Group with positive and negative Examples" do
context 'when testing Ruby\'s build-in math library' do
it 'can do normal numeric operations', positive: true do
expect(1 + 1).to eq(2)
end
it 'generates an error when expected', negative: true do
expect{1/0}.to raise_error(ZeroDivisionError)
end
end
end
#run `rspec --tag positive filter_spec.rb` or `rspec --tag negative filter_spec.rb` in terminal
#Example 3
RSpec.describe "A spec file to demonstrate how RSpec Formatters work" do
context 'when running some tests' do
it 'the test usually calls the expect() method at least once' do
expect(1 + 1).to eq(2)
end
end
end
#rspec --format progress formatter_spec.rb
#rspec --format doc formatter_spec.rb
#Example 3
RSpec.describe "A spec file to demonstrate how RSpec Formatters work" do
context 'when running some tests' do
it 'the test usually calls the expect() method at least once' do
expect(1 + 1).to eq(1)
end
end
end
#rspec --format doc formatter_spec.rb
|
module Boris
module Structure
include Lumberjack
CATEGORIES = %w{
file_systems
hardware
hosted_shares
installed_applications
installed_patches
installed_services
local_user_groups
network_id
network_interfaces
operating_system
running_processes
}
CATEGORIES.each do |category|
attr_accessor category.to_sym
end
def file_system_template
[
:capacity_mb,
:file_system,
:mount_point,
:san_storage,
:used_space_mb
].to_nil_hash
end
def hosted_share_template
[
:name,
:path
].to_nil_hash
end
def installed_application_template
[
:date_installed,
:install_location,
:license_key,
:name,
:vendor,
:version
].to_nil_hash
end
def installed_patch_template
[
:date_installed,
:installed_by,
:patch_code
].to_nil_hash
end
def installed_service_template
[
:name,
:install_location,
:start_mode
].to_nil_hash
end
def local_user_groups_template
{
:group=>nil,
:members=>[]
}
end
def network_interface_template
[
:auto_negotiate,
:current_speed_mbps,
:duplex,
:fabric_name,
:is_uplink,
:mac_address,
:model,
:model_id,
:mtu,
:name,
:node_wwn,
:port_wwn,
:remote_mac_address,
:remote_wwn,
:status,
:type,
:vendor,
:vendor_id,
:dns_servers=>[],
:ip_addresses=>[]
].to_nil_hash
end
def running_process_template
[
:command,
:cpu_time,
:date_started
].to_nil_hash
end
def get_file_systems
debug 'preparing to fetch file systems'
@file_systems = []
end
def get_hardware
debug 'preparing to fetch hardware'
@hardware = [
:cpu_architecture,
:cpu_core_count,
:cpu_model,
:cpu_physical_count,
:cpu_speed_mhz,
:cpu_vendor,
:firmware_version,
:model,
:memory_installed_mb,
:serial,
:vendor
].to_nil_hash
end
def get_hosted_shares
debug 'preparing to fetch hosted shares'
@hosted_shares = []
end
def get_installed_applications
debug 'preparing to fetch installed applications'
@installed_applications = []
end
def get_installed_patches
debug 'preparing to fetch installed patches'
@installed_patches = []
end
def get_installed_services
debug 'preparing to fetch installed_services'
@installed_services = []
end
def get_local_user_groups
debug 'preparing to fetch users and groups'
@local_user_groups = []
end
def get_network_id
debug 'preparing to fetch network id'
@network_id = [
:domain,
:hostname
].to_nil_hash
end
def get_network_interfaces
debug 'preparing to fetch network_interfaces'
@network_interfaces = []
end
def get_operating_system
debug 'preparing to fetch operating system'
@operating_system = [
:date_installed,
:kernel,
:license_key,
:name,
:service_pack,
:version,
:features=>[],
:roles=>[]
].to_nil_hash
end
def get_running_processes
debug 'preparing to fetch running_processes'
@running_processes = []
end
alias get_installed_daemons get_installed_services
end
end
|
require 'test_helper'
class EncontrosControllerTest < ActionDispatch::IntegrationTest
setup do
@encontro = encontros(:one)
end
test "should get index" do
get encontros_url
assert_response :success
end
test "should get new" do
get new_encontro_url
assert_response :success
end
test "should create encontro" do
assert_difference('Encontro.count') do
post encontros_url, params: { encontro: { descricao: @encontro.descricao, fim_encontro: @encontro.fim_encontro, fim_inscricoes: @encontro.fim_inscricoes, inicio_encontro: @encontro.inicio_encontro, inicio_inscricoes: @encontro.inicio_inscricoes, quant_max: @encontro.quant_max, tema: @encontro.tema, titulo: @encontro.titulo, valor: @encontro.valor } }
end
assert_redirected_to encontro_url(Encontro.last)
end
test "should show encontro" do
get encontro_url(@encontro)
assert_response :success
end
test "should get edit" do
get edit_encontro_url(@encontro)
assert_response :success
end
test "should update encontro" do
patch encontro_url(@encontro), params: { encontro: { descricao: @encontro.descricao, fim_encontro: @encontro.fim_encontro, fim_inscricoes: @encontro.fim_inscricoes, inicio_encontro: @encontro.inicio_encontro, inicio_inscricoes: @encontro.inicio_inscricoes, quant_max: @encontro.quant_max, tema: @encontro.tema, titulo: @encontro.titulo, valor: @encontro.valor } }
assert_redirected_to encontro_url(@encontro)
end
test "should destroy encontro" do
assert_difference('Encontro.count', -1) do
delete encontro_url(@encontro)
end
assert_redirected_to encontros_url
end
end
|
module CDI
module V1
module ServiceConcerns
module UserParams
extend ActiveSupport::Concern
WHITELIST_ATTRIBUTES = [
:first_name,
:last_name,
:birthday,
:gender,
:email,
:about,
:profile_type,
:password,
:password_confirmation,
:profile_image,
:phone_number,
:phone_area_code,
:tof_accepted
]
ADDRESS_WHITELIST_ATTRIBUTES = [
:city_id,
:street,
:number,
:district,
:complement,
:zipcode
]
POSTMON_ENDPOINT = 'http://api.postmon.com.br/v1/cep/%s'
DEFAULT_PROVIDER = :site
included do
def user_params
@user_params ||= set_image_crop_params(filter_hash(attributes_hash, WHITELIST_ATTRIBUTES))
@user_params[:password_confirmation] ||= @options[:user] && @options[:user].fetch(:password_confirmation, true)
@user_params
end
def attributes_hash
@options[:user]
end
def set_image_crop_params(params, mounted_as = :profile_image)
return params unless updating_profile_image?
geometry = (attributes_hash && attributes_hash[:"#{mounted_as}_crop_geometry"]) || []
if geometry
x,y,w,h = nil
if geometry.is_a?(String)
x,y,w,h = array_values_from_string(geometry)
elsif geometry.is_a?(Array)
x,y,w,h = geometry
elsif geometry.is_a?(Hash)
x,y,w,h = geometry[:x], geometry[:y], geometry[:w], geometry[:h]
end
geometries = [x,y,w,h]
if geometries.any?
# remove negative values
geometries.map! {|g| g.to_i.abs }
[:crop_x, :crop_y, :crop_w, :crop_h].each_with_index do |a , i|
params.merge!(:"#{mounted_as}_#{a}" => geometries[i])
end
end
end
params
end
def classes_codes
@classes_codes ||= array_values_from_params(@options, :classes_codes, :user)
end
def non_change_trackable_attributes
[:password_confirmation]
end
def educational_institution
institution_id = attributes_hash.fetch(:educational_institution_id, nil)
@educational_institution ||= EducationalInstitution.find_by(id: institution_id)
end
def valid_educational_institution?
valid_object?(educational_institution, ::EducationalInstitution)
end
def student_signup?
profile_type == User::VALID_PROFILES_TYPES[:student]
end
def multiplier_signup?
User::VALID_MULTIPLIER_PROFILES_TYPES.values.member?(profile_type)
end
def profile_type
user_params[:profile_type].to_s
end
def updating_profile_image?
attributes_hash && attributes_hash[:profile_image].present?
end
end
end
end
end
end
|
require 'rails_helper'
RSpec.feature 'user', type: :feature do
given(:user) { build(:user) }
given(:login_user) { create(:user) }
given(:prototype) { build(:prototype, :with_sub_images) }
it 'creates new user', js: true do
visit root_path
page.save_screenshot 'sample.png'
click_on 'Get Started'
click_on 'Sign up now'
fill_in 'user_name', with: user.name
fill_in 'user_email', with: user.email
fill_in 'user_password', with: user.password
fill_in 'user_member', with: user.member
fill_in 'user_profile', with: user.profile
fill_in 'user_works', with: user.works
click_button 'SAVE'
expect(page).to have_selector '.alert-notice', text: 'Welcome! You have signed up successfully.'
end
it 'signs in ', js: true do
visit root_path
click_on 'Get Started'
fill_in 'user_email', with: login_user.email
fill_in 'user_password', with: login_user.password
click_button 'Sign in'
expect(page).to have_selector '.alert-notice', text: 'Signed in successfully.'
end
it 'creates a new prototype', js: true do
visit root_path
click_on 'Get Started'
fill_in 'user_email', with: login_user.email
fill_in 'user_password', with: login_user.password
click_button 'Sign in'
click_on 'New Proto'
fill_in 'prototype_title', with: prototype.title
fill_in 'prototype_catch_copy', with: prototype.catch_copy
fill_in 'prototype_concept', with: prototype.concept
attach_file 'prototype[thumbnails_attributes][0][image]', File.join(Rails.root, '/spec/fixtures/img/sample.png'), visible: false
1.upto(3) do |i|
attach_file "prototype[thumbnails_attributes][#{i}][image]", File.join(Rails.root, '/spec/fixtures/img/sample.png'), visible: false
end
click_on '投稿する'
expect(page).to have_selector '.alert-success', text: 'success'
end
end
|
# encoding: utf-8
module TextUtils
module Filter
# allow plugins/helpers; process source (including header) using erb
def erb( content, options={} )
puts " Running embedded Ruby (erb) code/helpers..."
content = ERB.new( content ).result( binding() )
content
end
end # module Filter
end # module TextUtils |
class Holopic < ActiveRecord::Base
#Interpolation
Paperclip.interpolates :file_name do |attachment, style|
"image_#{attachment.instance.id.to_s}"
end
# This method associates the attribute ":avatar" with a file attachment
has_attached_file :avatar, path: ":style/:file_name"
validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/
end
|
require_dependency 'hooks/change_header_color_hook'
Redmine::Plugin.register :redmine_change_header_color do
name 'Redmine Change Header Color plugin'
author 'Joe Naha'
description 'This is a plugin for changing header color by projects'
version '0.0.1'
url 'https://github.com/j5a/redmine_change_header_color'
author_url 'https://github.com/j5a'
end
|
# write a method that returns an array that contains
# every other element of an array
# that is passed in as an argument
# the values in the returned list should be those values
# that are in the 1st, 3rd, 5th, and so on elements of the argument array
# Examples:
#
# oddities([2, 3, 4, 5, 6]) == [2, 4, 6]
# oddities([1, 2, 3, 4, 5, 6]) == [1, 3, 5]
# oddities(['abc', 'def']) == ['abc']
# oddities([123]) == [123]
# oddities([]) == []
def oddities(arr)
new_arr = []
arr.each_with_index do |element, index|
new_arr << element if index.even?
end
new_arr
end
p oddities([2, 3, 4, 5, 6])
p oddities([1, 2, 3, 4, 5, 6])
p oddities(['abc', 'def'])
p oddities([123])
p oddities([]) |
# What will each of the 4 puts statements print?
require 'date'
puts Date.new
# -4712-01-01 defaults to the Julian year
puts Date.new(2016)
# 2016, month - day defaults to 01
puts Date.new(2016, 5)
# 2016-05. day default
puts Date.new(2016, 5, 13)
# no default values |
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
u1 = User.first
# e1 = Evenement.create( titre:'Sayna Yeaeh', date: '2018-04-07 00:00:00', description:'Ne ratez pas l\'occasion de votre vie', price: 300,picture: "coucou.jpg")
# c1 = Category.create( name:'education')
# o1 = Organisateur.create( title:'Sayna', about:'Help people rise out of poverty by digital work')
# section = Section.create(title: 'free', duration: '2018-03-12 00:00:00')
# s1 = Status.create(title: 'entreprise')
# u1.organisateur = o1
coms = Commentaire.create(comment: "Coucou")
coms.user = u1
coms.evenement = Evenement.last
# p Evenement.last
coms.save!
# o1.user = u1
# o1.save
# u1.section = section
# e1.category = c1
# e1.organisateur = o1
# o1.status = s1
# e1.save
# c1.save
# o1.save
# section.save
# s1.save
# e = Evenement.first
# puts "Section: "+e.section.title
# puts "Organisateur: "+e.organisateur.title
# puts "Section: "+e.category.name
# puts "User:"+u1.organisateur.title
# u2 = User.new
# puts u2
# section = Section.create(title: 'free', duration: '2018-03-12 00:00:00')
# section.save
# u2.section = section
# puts User.first.name
# p u2
|
class AddHeaderFieldsToParticipants < ActiveRecord::Migration
def change
add_column :participants, :recruitment_source, :string
add_column :participants, :external_id, :string
add_column :participants, :middle_initial, :string, limit: 1
end
end
|
module Effect
class CraftingRecipe
attr_reader :name
attr_reader :costs
attr_reader :catalysts
attr_reader :reagents
attr_reader :outputs
attr_reader :message
def initialize(parent, costs = nil, catalysts = nil, reagents = nil, outputs = nil, message = nil, name = nil)
@parent = parent
@costs = Hash.new{|hash, key| 0}
unless costs === nil
costs.each do |cost, delta|
@costs[cost.to_sym] = delta.to_i
end
end
@catalysts = Hash.new
unless catalysts === nil
catalysts.each do |catalyst, quantity|
@catalysts[catalyst.to_sym] = quantity.to_i
end
end
@reagents = Hash.new
unless reagents === nil
reagents.each do |reagent, quantity|
@reagents[reagent.to_sym] = quantity.to_i
end
end
@outputs = Hash.new
unless outputs === nil
outputs.each do |output, quantity|
@outputs[Entity::ItemType.find(output.to_i)] = quantity.to_i
end
end
@message = message
@name = name
@name = @parent.name if @name === nil
end
def craft_intent(intent)
intent.name = name
@costs.each do |cost, delta|
intent.add_cost cost, delta
end
end
def describe
stuff = ''
@costs.each do |cost, delta|
stuff = stuff + "#{delta.to_s} #{cost.to_s},"
end
@reagents.each do |agent, quantity|
stuff = stuff + " #{quantity.to_s} #{agent.to_s}#{ quantity != 1 ? 's' : '' },"
end
if @catalysts.count > 0
stuff = stuff + ' and requiring'
@catalysts.each do |cata, quantity|
stuff = stuff + " #{quantity.to_s} #{cata.to_s}#{ quantity != 1 ? 's' : '' },"
end
end
if @outputs.count > 1
stuff = stuff + ' and producing'
else
stuff = stuff + ' it produces '
end
@outputs.each do |item, quantity|
stuff = stuff + " #{quantity.to_s} #{item.to_s}#{ quantity != 1 ? 's' : '' },"
end
return "#{@name.to_s} is a crafting recipe, costing#{stuff.chomp(',')}."
end
def save_state
serialised_outputs = Hash.new
@outputs.each do |item, quantity|
serialised_outputs[item.id] = quantity
end
if @name === @parent.name
['CraftingRecipe', @costs, @catalysts, @reagents, outputs, @message]
else
['CraftingRecipe', @costs, @catalysts, @reagents, outputs, @message, @name]
end
end
end
end |
class Game < ActiveRecord::Base
before_create :set_vars
#takes a shot at the grid square specified by coord. if no coordinates are
#given, the cpu shoots at the player. returns a message and the shot location.
def shoot(*coord)
location = 0 #shot location
ships = '' #ship hitpoints
board = '' #board layout
output = '' #message to be displayed to the player
#fill the above variables with the opponents setup
if not coord.empty? #player is shooting
ships = cpu_ships.clone
board = cpu_board.clone
location = coord[0].to_i
else #cpu is shooting
ships = player_ships.clone
board = player_board.clone
location = cpu_shot
end
symbol = board[location] #symbol occupying the shooting spot
if symbol =~ /[0-4]/ #if symbol is a ship
board[location] = 'H' #mark a hit
output << ship_hit(symbol.to_i, ships)
elsif symbol == 'O' #if the symbol is an open spot
board[location] = 'M' #mark a miss
output << 'Miss.'
else
output << 'You have already gone there.'
end
#check for remaining ships
if (board =~ /\d/).nil?
output << ' Game over! Refresh to play again.'
end
#set the oponents board to its new state
if not coord.empty?
self.cpu_ships = ships
self.cpu_board = board
else
self.player_ships = ships
self.player_board = board
end
return [output, location]
end
private
#set ship hitpoints and initial board layout
def set_vars
self.cpu_ships = '23345'
self.player_ships = '23345'
self.cpu_board = generate_board
self.player_board = generate_board
end
#the cpu's shooting strategy. right now the cpu checks all spaces sequentially.
def cpu_shot
player_board.scan(/./).each_with_index do |symbol, i|
return i if symbol != 'M' and symbol != 'H'
end
end
#runs if a ship is hit
def ship_hit(number, ships)
#hash of ship numbers => names
ship_hash = {0 => 'Patrol boat', 1 => 'Submarine', 2 => 'Destroyer',
3 => 'Battleship', 4 => 'Aircraft carrier'}
#decrement ship's hitpoints
ships[number.to_i] = (ships[number.to_i].to_i - 1).to_s
#check if the hit sunk the ship
outcome = ships[number] == '0' ? ' sunk!' : ' hit!'
#return message
return ship_hash[number] + outcome
end
#automatically places ships. each ship is placed by selecting a random
#grid square and then using that square as a pivot point. All possible
#orientations are tried, and if one is found that doesn't conflict with
#another ship, the ship is placed. Otherwise, a new pivot is tried.
def generate_board
board = 'O' * 100
ship_hash = {0 => 2, 1 => 3, 2 => 3, 3 => 4, 4 => 5} #ship sybol => size
ship_hash.each do |symbol, size|
while true
#find a free pivot point
pivot = rand(100)
while board[pivot] != 'O'
pivot = rand(100)
end
#figure out possible ship orientations based on the start point
directions = [-1, 1, -10, 10] #left, right, up, down
#can it go left?
directions.delete(-1) if (pivot-size-1)/10 < pivot/10 or (pivot-size-1) < 0
#right?
directions.delete(1) if (pivot+size-1)/10 > pivot/10
#up?
directions.delete(-10) if (pivot-10*(size-1)) < 0
#down?
directions.delete(10) if (pivot+10*(size-1)) > 99
while not directions.empty? #try all possible orientations
direction = directions[rand(directions.size-1)]
ship = (0..size-1).collect{ |i| pivot+i*direction }
if conflict(ship, board)
directions.delete(direction)
else
break #no conflict, so place the ship
end
end
if directions.empty?
next #no possible orientations, so try again
else
#place the ships symbols on the board
ship.each{ |loc| board[loc] = symbol.to_s }
break
end
end
end
return board
end
#returns true if the proposed ship location conflicts with another ship
def conflict(ship, board)
if ship.empty?
return true
end
ship.each do |loc|
return true if board[loc] =~ /\d/
end
return false
end
end
|
class NoteController < ApplicationController
def index
@notes = Note.all
end
def show
@note = Note.find(params[:id])
end
def new
@note = Note.new
end
def create
@note = Note.new(note_params)
if @note.try(:save)
flash.notice = '"#{@note.name}" has been created.'
# Below: @note.id or just @note?
redirect_to note_url(@note.id)
else
flash.notice = '"#{@note.name}" could not be saved.'
render :new
end
end
def edit
@note = Note.find(params[:id])
render :edit
end
def update
@note = Note.find(params[:id])
if @note.update_attributes(note_params)
flash.notice = 'Changes to "#{@note.name}" have been saved.'
redirect_to note_url(@note)
else
flash.notice = 'Changes to "#{@note.name}" could NOT be saved.'
render :edit
end
end
def destroy
@note = Note.find(params[:id])
note = Note.find_by_id(@note.note_id)
if @note.try(:destroy)
flash.notice = '"#{@note.name}" and its albums and tracks have been deleted.'
# Below: @note.id or just @note?
redirect_to note_url(@note)
else
flash.notice = '"#{@note.name}" and its albums and tracks could NOT be deleted.'
render :edit
end
end
private
def note_params
params.require(:note).permit(:body, :user_id, :track_id)
end
end
|
class RenameLineItemsCountToQuantity < ActiveRecord::Migration
def up
rename_column :line_items, :count, :quantity
change_column :line_items, :quantity, :decimal
change_column_default :line_items, :quantity, 0
LineItem.where(quantity: nil).each do |line_item|
line_item.update_column(:quantity, 0)
end
end
def down
change_column :line_items, :quantity, :integer
rename_column :line_items, :quantity, :count
end
end |
require 'data_mapper' unless defined?DataMapper
module Yito
module Model
module Booking
class BookingCategoryHistoric
include DataMapper::Resource
storage_names[:default] = 'bookds_categories_historics'
belongs_to :category, 'Yito::Model::Booking::BookingCategory',
:child_key => [:category_code], :parent_key => [:code], :key => true
property :year, Integer, :key => true
property :stock, Integer, default: 0
end
end
end
end |
# frozen_string_literal: true
module HealthQuest
module PatientGeneratedData
module Patient
##
# A service object for querying the PGD for Patient resources.
#
# @!attribute headers
# @return [Hash]
class MapQuery
include PatientGeneratedData::FHIRClient
attr_reader :headers
##
# Builds a PatientGeneratedData::Patient::MapQuery instance from a given hash of headers.
#
# @param headers [Hash] the set of headers.
# @return [PatientGeneratedData::Patient::MapQuery] an instance of this class
#
def self.build(headers)
new(headers)
end
def initialize(headers)
@headers = headers
end
##
# Gets patient information from an id
#
# @param id [String] the logged in user's ICN.
# @return [FHIR::DSTU2::Patient::ClientReply] an instance of ClientReply
#
def get(id)
client.read(dstu2_model, id)
end
##
# Create a patient resource from the logged in user.
#
# @param user [User] the logged in user.
# @return [FHIR::DSTU2::Patient::ClientReply] an instance of ClientReply
#
def create(user)
patient = Resource.manufacture(user).prepare
client.create(patient)
end
##
# Returns the FHIR::DSTU2::Patient class object
#
# @return [FHIR::DSTU2::Patient]
#
def dstu2_model
FHIR::DSTU2::Patient
end
end
end
end
end
|
json.array!(@seats) do |seat|
json.extract! seat, :id, :user_id, :row, :seat, :section
json.url seat_url(seat, format: :json)
end
|
# -*- ruby -*-
module LAAG
VERSION = $LOADED_FEATURES
.map { |f| f.match %r{/laag-(?<version>[[:digit:]]+\.[[:digit:]]+\.[[:digit:]]+(\.pre)?)} }
.compact
.map { |gem| gem['version'] }
.uniq
.first
end
|
require 'spec_helper'
require 'hutch/worker'
describe Hutch::Worker do
let(:consumer) { double('Consumer', routing_keys: %w( a b c ),
get_queue_name: 'consumer', get_arguments: {},
get_options: {}, get_serializer: nil) }
let(:consumers) { [consumer, double('Consumer')] }
let(:broker) { Hutch::Broker.new }
let(:setup_procs) { Array.new(2) { Proc.new {} } }
subject(:worker) { Hutch::Worker.new(broker, consumers, setup_procs) }
describe ".#run" do
it "calls each setup proc" do
setup_procs.each { |prc| expect(prc).to receive(:call) }
allow(worker).to receive(:setup_queues)
allow(Hutch::Waiter).to receive(:wait_until_signaled)
allow(broker).to receive(:stop)
worker.run
end
end
describe '#setup_queues' do
it 'sets up queues for each of the consumers' do
consumers.each do |consumer|
expect(worker).to receive(:setup_queue).with(consumer)
end
worker.setup_queues
end
end
describe '#setup_queue' do
let(:queue) { double('Queue', bind: nil, subscribe: nil) }
before { allow(broker).to receive_messages(queue: queue, bind_queue: nil) }
it 'creates a queue' do
expect(broker).to receive(:queue).with(consumer.get_queue_name, consumer.get_options).and_return(queue)
worker.setup_queue(consumer)
end
it 'binds the queue to each of the routing keys' do
expect(broker).to receive(:bind_queue).with(queue, %w( a b c ))
worker.setup_queue(consumer)
end
it 'sets up a subscription' do
expect(queue).to receive(:subscribe).with(consumer_tag: %r(^hutch\-.{36}$), manual_ack: true)
worker.setup_queue(consumer)
end
context 'with a configured consumer tag prefix' do
before { Hutch::Config.set(:consumer_tag_prefix, 'appname') }
it 'sets up a subscription with the configured tag prefix' do
expect(queue).to receive(:subscribe).with(consumer_tag: %r(^appname\-.{36}$), manual_ack: true)
worker.setup_queue(consumer)
end
end
context 'with a configured consumer tag prefix that is too long' do
let(:maximum_size) { 255 - SecureRandom.uuid.size - 1 }
before { Hutch::Config.set(:consumer_tag_prefix, 'a'.*(maximum_size + 1)) }
it 'raises an error' do
expect { worker.setup_queue(consumer) }.to raise_error(/Tag must be 255 bytes long at most/)
end
end
end
describe '#handle_message' do
let(:payload) { '{}' }
let(:consumer_instance) { double('Consumer instance') }
let(:delivery_info) { double('Delivery Info', routing_key: '',
delivery_tag: 'dt') }
let(:properties) { double('Properties', message_id: nil, content_type: "application/json") }
before { allow(consumer).to receive_messages(new: consumer_instance) }
before { allow(broker).to receive(:ack) }
before { allow(broker).to receive(:nack) }
before { allow(consumer_instance).to receive(:broker=) }
before { allow(consumer_instance).to receive(:delivery_info=) }
it 'passes the message to the consumer' do
expect(consumer_instance).to receive(:process).
with(an_instance_of(Hutch::Message))
expect(consumer_instance).to receive(:message_rejected?).and_return(false)
worker.handle_message(consumer, delivery_info, properties, payload)
end
it 'acknowledges the message' do
allow(consumer_instance).to receive(:process)
expect(broker).to receive(:ack).with(delivery_info.delivery_tag)
expect(consumer_instance).to receive(:message_rejected?).and_return(false)
worker.handle_message(consumer, delivery_info, properties, payload)
end
context 'when the consumer fails and a requeue is configured' do
it 'requeues the message' do
allow(consumer_instance).to receive(:process).and_raise('failed')
requeuer = double
allow(requeuer).to receive(:handle) { |delivery_info, properties, broker, e|
broker.requeue delivery_info.delivery_tag
true
}
allow(worker).to receive(:error_acknowledgements).and_return([requeuer])
expect(broker).to_not receive(:ack)
expect(broker).to_not receive(:nack)
expect(broker).to receive(:requeue)
worker.handle_message(consumer, delivery_info, properties, payload)
end
end
context 'when the consumer raises an exception' do
before { allow(consumer_instance).to receive(:process).and_raise('a consumer error') }
it 'logs the error' do
Hutch::Config[:error_handlers].each do |backend|
expect(backend).to receive(:handle)
end
worker.handle_message(consumer, delivery_info, properties, payload)
end
it 'rejects the message' do
expect(broker).to receive(:nack).with(delivery_info.delivery_tag)
worker.handle_message(consumer, delivery_info, properties, payload)
end
end
context "when the payload is not valid json" do
let(:payload) { "Not Valid JSON" }
it 'logs the error' do
Hutch::Config[:error_handlers].each do |backend|
expect(backend).to receive(:handle)
end
worker.handle_message(consumer, delivery_info, properties, payload)
end
it 'rejects the message' do
expect(broker).to receive(:nack).with(delivery_info.delivery_tag)
worker.handle_message(consumer, delivery_info, properties, payload)
end
end
end
describe '#acknowledge_error' do
let(:delivery_info) { double('Delivery Info', routing_key: '',
delivery_tag: 'dt') }
let(:properties) { double('Properties', message_id: 'abc123') }
subject { worker.acknowledge_error delivery_info, properties, broker, StandardError.new }
it 'stops when it runs a successful acknowledgement' do
skip_ack = double handle: false
always_ack = double handle: true
never_used = double handle: true
allow(worker).
to receive(:error_acknowledgements).
and_return([skip_ack, always_ack, never_used])
expect(never_used).to_not receive(:handle)
subject
end
it 'defaults to nacking' do
skip_ack = double handle: false
allow(worker).
to receive(:error_acknowledgements).
and_return([skip_ack, skip_ack])
expect(broker).to receive(:nack)
subject
end
end
end
|
require_relative 'merchant'
require_relative 'csv_loader'
require_relative 'search'
class MerchantRepository
include CsvLoader
include Search
attr_reader :merchants
def initialize(csv_file_path, engine)
@merchants = create_merchants(csv_file_path, engine)
@engine = engine
return self
end
def create_merchants(csv_file_path, engine)
create_instances(csv_file_path, 'Merchant', engine)
end
def all
@merchants
end
def find_by_id(search_id)
find_instance_by_id(@merchants, search_id)
end
def find_by_name(search_name)
find_instance_by_name(@merchants, search_name)
end
def find_all_by_name(search_all_name)
search_all_name = search_all_name.downcase
@merchants.find_all do |merchant|
name = merchant.name.downcase
name.include?(search_all_name)
end
end
def inspect
"#<#{self.class} #{@merchants.size} rows>"
end
end
|
class CreateContainerKinds < ActiveRecord::Migration
def self.up
create_table :container_kinds do |t|
t.string :name
t.string :aka
t.boolean :can_contain_boxes
t.timestamps
end
end
def self.down
drop_table :container_kinds
end
end
|
class Planets
attr_accessor :name, :rotation_period, :orbital_period, :diameter, :climate, :gravity, :population
@@all = []
def initialize(name:, rotation_period:, orbital_period:, diameter:, climate:, gravity:, population:)
self.name = name
self.rotation_period = rotation_period
self.orbital_period = orbital_period
self.diameter = diameter
self.climate = climate
self.gravity = gravity
self.population = population
self.save
end
def save
@@all << self
end
def self.all
@@all
end
end
|
# frozen_string_literal: true
class TasksController < ApplicationController
def index
# Returns all tasks in order by id
@tasks = Task.order(id: :asc)
end
def filtered
# this is the task that have been filterd by the users input
@tasks = Task.where(tag: params[:tagsearch])
# if noting was entered, then just reload the /tasks page
if params[:tagsearch] == ''
redirect_to '/tasks'
return
end
# if nothing returned on a search, then display error message and redirect to /tasks
if Task.where(tag: params[:tagsearch]).count.zero? == true
render(
html: "<script>alert('Nothing Found');
window.location.replace(\"/tasks\")</script>".html_safe
)
end
end
def show
@task = Task.find(params[:id])
end
def new
@task = Task.new
redirect_to '/tasks' if current_user.role != 'admin' && current_user.role != 'moderator'
end
def create
#redirect_to '/tasks' if current_user.role != 'admin' && current_user.role != 'moderator'
@task = Task.new(task_params)
if @task.save
redirect_to @task
else
render :new
end
end
def edit
@task = Task.find(params[:id])
#redirect_to '/tasks' if current_user.role != 'admin' && current_user.role != 'moderator'
end
def update
@task = Task.find(params[:id])
#if current_user.role == 'admin' || current_user.role == 'moderator'
if @task.update(task_params)
redirect_to @task
else
render :edit
end
#else
#render :new
#end
end
def destroy
@task = Task.find(params[:id])
@task.destroy
redirect_to root_path
end
private
def task_params
params.require(:task).permit(:task_name, :claimed_by, :child_task_id, :due_date, :task_description, :tag)
end
end
|
class AddPackageRefToPackageItems < ActiveRecord::Migration[5.0]
def change
add_reference :package_items, :package, foreign_key: true
end
end
|
class AddMissingIndex < ActiveRecord::Migration
def change
add_index :texts, ["app", "context", "locale"]
end
end
|
class KatoRoomsController < ApplicationController
before_action :set_kato_room, only: [:show, :edit, :update, :destroy]
# GET /kato_rooms
# GET /kato_rooms.json
def index
@url =KatoAdHocExpress.setInfo( response, "EMxxK0z32ULskJgTKlgrouB6C9fDIjkXq92UPb1ICwk",3600, "1", "foo", "1", "bar")
respond_to do |format|
format.html {render action: "index"}
format.json {render json: { "JWTToken" => @url}}
end
end
# GET /kato_rooms/1
# GET /kato_rooms/1.json
def show
end
# GET /kato_rooms/new
def new
@kato_room = KatoRoom.new
end
# GET /kato_rooms/1/edit
def edit
end
# POST /kato_rooms
# POST /kato_rooms.json
def create
@kato_room = KatoRoom.new(kato_room_params)
respond_to do |format|
if @kato_room.save
format.html { redirect_to @kato_room, notice: 'Kato room was successfully created.' }
format.json { render :show, status: :created, location: @kato_room }
else
format.html { render :new }
format.json { render json: @kato_room.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /kato_rooms/1
# PATCH/PUT /kato_rooms/1.json
def update
respond_to do |format|
if @kato_room.update(kato_room_params)
format.html { redirect_to @kato_room, notice: 'Kato room was successfully updated.' }
format.json { render :show, status: :ok, location: @kato_room }
else
format.html { render :edit }
format.json { render json: @kato_room.errors, status: :unprocessable_entity }
end
end
end
# DELETE /kato_rooms/1
# DELETE /kato_rooms/1.json
def destroy
@kato_room.destroy
respond_to do |format|
format.html { redirect_to kato_rooms_url, notice: 'Kato room was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_kato_room
@kato_room = KatoRoom.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def kato_room_params
params.require(:kato_room).permit(:Get)
end
end
|
require_relative 'game'
class HumanPlayers
attr_accessor :guess
attr_reader :name, :game
def initialize(name)
@name = name
end
def guess
gets.chomp
end
def alert_invalid_guess
"Invalid play, try again. "
end
end
|
class Book < ActiveRecord::Base
before_save :generate_timestamp
validates :name, presence: true, uniqueness: true
mount_uploader :cover_image, BookImageUploader
def generate_timestamp
self.create_at = DateTime.now
end
end
|
require 'spec_helper'
module Fakebook
describe Cache::Persist do
it 'saves the item' do
item = Cache::Persist.new('me_fields_name', { :name => 'Jordan Rogers-Smith', id: 123456789 })
item.save
expect(Dir[@directory].empty?).to be false
end
it 'give subdirectory saves there' do
Fakebook.cache_subfolder = 'example'
item = Cache::Persist.new('me_fields_name', { :name => 'Jordan Rogers-Smith', id: 123456789 })
item.save
expect(Dir["#{@directory}/example/"].empty?).to be false
Fakebook.cache_subfolder = ''
end
end
end
|
module SubmissionsHelper
def potentially_truncated_errors(submission)
submission.sheet_errors.any? { |_sheet_key, errors| errors.size >= 10 }
end
def submission_completed_text(task)
[
task.description,
"management information for #{task.framework.short_name} #{task.framework.name} submitted to CCS"
].compact.join(' ').upcase_first
end
end
|
# -*- coding: utf-8 -*-
require 'spec_helper'
describe Follower do
before :all do
DB = db_connect 'test'
@model = Object.const_get('Follower')
@model.truncate
end
context 'save followers' do
before do
@source = [0,8,4,2,6]
end
it 'should save and restore dummy value' do
@model.save_followers(@source).should be_empty
last = @model.reverse.first
JSON.parse(last.followers_list).should be_eql @source
last.followers.should be_eql @source.count
end
it 'should not save same as last value' do
@model.save_followers(@source).should be_empty
end
it 'should save difference as last value' do
@model.save_followers(@source << 10).should_not be_empty
@model.count.should be_eql 2
end
it 'should return increment / decrement' do
new_source = [0,2,4,12]
diff = @model.save_followers(new_source)
diff[:dec].sort.should be_eql ((@source << 10) - new_source).sort
diff[:inc].sort.should be_eql (new_source - (@source << 10)).sort
end
end
end
|
class AuthenticationController < ApplicationController
skip_before_action :authenticate_request, only: %i[login finding_user]
# POST /auth/login
def login
if params[:email].present?
# @user = User.find_by_email(params[:email])
@user = User.find_by("email ILIKE ?", "%#{params[:email]}%")
if @user && @user.password == params[:password]
# if @user&.authenticate(params[:password])
if @user.active_status == true
token = JsonWebToken.encode(user_id: @user.id)
user = User.select(:name, :email, :user_uid, :id, :role_id).find(@user.id)
render json: { token: token, message: 'Login Success', user: user }, status: :ok
else
render json: { error: 'Need to subscription' }
end
else
render json: { error: 'Invalid credential' }, status: :unauthorized
end
else
render json: { error: 'Give the valid Email' }, status: :unauthorized
end
end
def finding_user
user_email = User.where(email: params[:email])
if user_email.present?
render json: user_email
else
render json: { error: 'Give the valid Email' }, status: :unauthorized
end
end
private
def login_params
params.permit(:email, :password)
end
end
|
class CreateEntries < ActiveRecord::Migration[6.0]
def change
create_table :entries do |t|
t.date :date
t.string :feather
t.string :stone
t.belongs_to :user
t.timestamps
end
end
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
section_list = [
["Breakfast", "Breakfast dishes"],
[ "Lunch", "Lunch dishes" ],
[ "Dinner", "Dinner dishes" ],
[ "Drink", "Drinks" ]
]
food_list = [
[ "Pho Bo", "Vietnamese famous noodle", "Breakfast", 35000],
[ "Bun Bo", "Vietnamese famous noodle", "Breakfast", 35000],
[ "Hu Tieu", "Vietnamese famous noodle", "Breakfast", 30000],
[ "Op la", "Made from eggs", "Breakfast", 15000],
[ "Banh Canh", "Vietnamese famous noodle", "Breakfast", 25000],
[ "Com Ga", "Lunch meal", "Lunch", 35000],
[ "Com Suon", "Lunch meal", "Lunch", 15000],
[ "Com Nieu", "Lunch meal", "Lunch", 25000],
[ "My Quang", "Lunch meal", "Lunch", 65000],
[ "Chao Long", "Lunch meal", "Lunch", 10000]
]
section_list.each do |name, desc|
unless Section.exists? :section_name => name
Section.create(section_name: name, description: desc)
end
end
food_list.each do |name,desc,section,price|
section1 = Section.where(section_name: section).take
FoodItem.create(name: name, description: desc, price: price, section: section1)
end
|
class CreateCategories < ActiveRecord::Migration
def change
create_table :categories do |t|
t.string :category_name1
t.string :category_name2
t.string :icon1
t.string :icon2
t.string :category_intro
# 1 : 중앙동아리 2 : 과 동아리
t.integer :category_flag
t.timestamps null: false
end
end
end
|
require_relative '../../test_helper'
class CmsFixtureBlockTest < ActiveSupport::TestCase
def test_params
text = '{% cms_fixture id:header locale:en %} Hello World{% endcms_fixture %}'
template = Liquid::Template.parse(text)
tag = template.root.nodelist.detect { |t| t.params['id'] == 'header' }
assert_equal 'en', tag.params['locale']
assert_equal 'header', tag.params['id']
end
def test_parses_params
text = '{% cms_fixture id:header locale:en %}Hello{% endcms_fixture %}'
template = Liquid::Template.parse(text)
tag = template.root.nodelist.first
expected_params = { 'id' => 'header', 'locale' => 'en' }
assert_equal expected_params, tag.params
end
def test_find_by_identifier
text = '{% cms_fixture id:header locale:en %}Hello{% endcms_fixture %}'
text += '{% cms_fixture id:header locale:fr %}Bonjour{% endcms_fixture %}'
template = Liquid::Template.parse(text)
en = template.root.nodelist.detect { |t| t.params['locale'] == 'en' && t.params['id'] == 'header' }
fr = template.root.nodelist.detect { |t| t.params['locale'] == 'fr' && t.params['id'] == 'header' }
assert_equal 'Hello', en.nodelist.first
assert_equal 'Bonjour', fr.nodelist.first
end
def test_multiline
text = '{% cms_fixture id:content locale:en %}before{% raw %}{% cms_file id:1 %}{% endraw %}after{% endcms_fixture %}'
template = Liquid::Template.parse(text)
en = template.root.nodelist.detect { |t| t.params['locale'] == 'en' && t.params['id'] == 'content' }
results = MomentumCms::Tags::CmsFixture.get_contents(en)
assert_equal 'before{% cms_file id:1 %}after', results
end
def test_fixture_invalid
text = '{% cms_breadcrumb %}'
template = Liquid::Template.parse(text)
en = template.root.nodelist.detect { |t| t.params['locale'] == 'en' && t.params['id'] == 'content' }
results = MomentumCms::Tags::CmsFixture.get_contents(en)
assert_equal '', results
end
end
|
require 'minitest_helper'
describe FuzzyScanner do
before do
@fs = FuzzyScanner.new
@fs.regex = /([0 ][1-9]|1[012])[-\/.~X](0[1-9]|[12][0-9]|3[01])[-\/.~X]([0-9][0-9]$)/
end
describe "Fuzzily find matching text!" do
describe "finds the matches" do
it "finds perfectly matched text with fuzziness 0" do
matches = @fs.fscan!("03/18/14", 0)
matches.length.must_equal 1
matches[0][0].must_equal "03/18/14"
end
it "finds 1-edit matched text with fuzziness 1" do
matches = @fs.fscan!("03/I8/14", 1)
matches.length.must_equal 1
matches[0][0].must_equal "03/I8/14"
end
end
describe "cannot find the matches" do
it "cannot find 2-edit text with fuzziness 1" do
matches = @fs.fscan!("03/18/IA", 1)
matches.must_be_empty
end
it "cannot find matches with regex not matching" do
matches = @fs.fscan!("18/18/14", 0)
matches.must_be_empty
end
end
end
end |
module MessageSchemas
@cog_message_schema = {
"type" => "object",
"required" => ["patient_id", "status", "study_id"],
"properties" => {
"patient_id" => {"type" => "string", "minLength" => 1},
"study_id" => {"type" => "string", "minLength" => 1},
"status" => {"type" => "string", "minLength" => 1,
"enum" => ["REGISTRATION",
"ON_TREATMENT_ARM",
"REQUEST_ASSIGNMENT",
"REQUEST_NO_ASSIGNMENT",
"OFF_STUDY",
"OFF_STUDY_BIOPSY_EXPIRED"
]}
}
}
@specimen_received_message_schema = {
"type" => "object",
"required" => ["specimen_received"],
"properties" => {
"specimen_received" => {
"type" => "object",
"required" => ["patient_id", "study_id", "type"],
"properties" => {
"patient_id" => {"type" => "string", "minLength" => 1},
"type" => {"type" => "string", "minLength" => 1, "enum" => ["BLOOD", "TISSUE"]}
}
}
}
}
@specimen_shipped_message_schema = {
"type" => "object",
"required" => ["specimen_shipped"],
"properties" => {
"specimen_shipped" => {
"type" => "object",
"required" => ["patient_id", "study_id", "type", "carrier", "tracking_id"],
"properties" => {
"patient_id" => {"type" => "string", "minLength" => 1},
"type" => {"type" => "string", "minLength" => 1, "enum" => ["BLOOD_DNA", "TISSUE_DNA_AND_CDNA", "SLIDE"]}
}
}
}
}
@assay_message_schema = {
"type" => "object",
"required" => ["patient_id", "study_id", "surgical_event_id", "biomarker", "reported_date", "result",
"case_number", "type"],
"properties" => {
"patient_id" => {"type" => "string", "minLength" => 1},
"surgical_event_id" => {"type" => "string", "minLength" => 1},
"biomarker" => {"type" => "string", "minLength" => 1
# "enum" => ["PTen",
# "MSH",
# "Third"]
},
"case_number" => {"type" => "string", "minLength" => 1},
"type" => {"type" => "string", "minLength" => 1, "enum" => ["RESULT"]}
}
}
@pathology_status_message_schema = {
"type" => "object",
"required" => ["patient_id", "study_id", "surgical_event_id", "status"],
"properties" => {
"patient_id" => {"type" => "string", "minLength" => 1},
"surgical_event_id" => {"type" => "string", "minLength" => 1},
"status" => {"type" => "string", "minLength" => 1,
"enum" => ["Y",
"N",
"U"]
},
"case_number" => {"type" => "string", "minLength" => 1},
"type" => {"type" => "string", "minLength" => 1, "enum" => ["PATHOLOGY_STATUS"]}
}
}
@variant_files_uploaded_schema = {
"type" => "object",
"required" => ["ion_reporter_id",
"molecular_id",
"analysis_id",
"tsv_file_name"
],
"properties" => {
"ion_reporter_id" => {"type" => "string", "minLength" => 1},
"molecular_id" => {"type" => "string", "minLength" => 1},
"analysis_id" => {"type" => "string", "minLength" => 1},
"tsv_file_name" => {"type" => "string", "minLength" => 1}
}
}
@variant_report_status_schema = {
"type" => "object",
"required" => ["patient_id", "analysis_id", "status", "comment", "comment_user"],
"properties" => {
"patient_id" => {"type" => "string", "minLength" => 1},
"analysis_id" => {"type" => "string", "minLength" => 1},
"comment" => {"type" => "string"},
"comment_user" => {"type" => "string", "minLength" => 1},
"status" => {"type" => "string", "minLength" => 1, "enum" => ["CONFIRMED",
"REJECTED"]}
}
}
@assignment_status_schema = {
"type" => "object",
"required" => ["status_type", "patient_id", "analysis_id", "status", "comment", "comment_user"],
"properties" => {
"status_type" => {"type" => "string", "minLength" => 1},
"patient_id" => {"type" => "string", "minLength" => 1},
"analysis_id" => {"type" => "string", "minLength" => 1},
"comment" => {"type" => "string", "minLength" => 1},
"comment_user" => {"type" => "string", "minLength" => 1},
"status" => {"type" => "string", "minLength" => 1, "enum" => ["CONFIRMED"]}
}
}
@treatement_arms = {
"type" => "object",
"required" => ["treatment_arms"]
}
@assignment_internal_message = {
"type" => "object",
"required" => ["patient_id", "message_type"],
"properties" => {
"patient_id" => {"type" => "string", "minLength" => 1},
"message_type" => {"type" => "string", "minLength" => 1, "enum" => ["AWAITING_PATIENT_DATA",
"AWAITING_TREATMENT_ARM_STATUS",
"NOTIFY_TREATMENT_ARM_API"]}
}
}
def self.assignment_internal_message
return @assignment_internal_message
end
def self.treatement_arms
return @treatement_arms
end
def self.variant_report_status_schema
return @variant_report_status_schema
end
def self.variant_files_uploaded_schema
return @variant_files_uploaded_schema
end
def self.pathology_status_message_schema
return @pathology_status_message_schema
end
def self.assay_message_schema
return @assay_message_schema
end
def self.specimen_shipped_message_schema
return @specimen_shipped_message_schema
end
def self.specimen_received_message_schema
return @specimen_received_message_schema
end
def self.cog_message_schema
return @cog_message_schema
end
def self.assignment_status_schema
return @assignment_status_schema
end
end |
require "rails_helper"
RSpec.describe User do
describe "Validations" do
it { should validate_uniqueness_of(:email) }
it { should validate_presence_of(:password) }
end
describe "Associations" do
it { should have_many(:links) }
end
describe "Methods" do
describe "#links_by_updated_at" do
let(:user) { create(:user) }
it "returns links sorted descending by updated at" do
link1 = create(:link, user: user)
sleep(1/10)
link2 = create(:link, user: user)
sleep(1/10)
link3 = create(:link, user: user)
link2.update(title: "UPDATE")
expect(user.links_by_updated_at.pluck(:id)).to match [link2.id, link3.id, link1.id]
end
end
end
end
|
require 'test_helper'
class EndorsementsControllerTest < ActionDispatch::IntegrationTest
setup do
@endorsement = endorsements(:one)
end
test "should get index" do
get endorsements_url
assert_response :success
end
test "should get new" do
get new_endorsement_url
assert_response :success
end
test "should create endorsement" do
assert_difference('Endorsement.count') do
post endorsements_url, params: { endorsement: { } }
end
assert_redirected_to endorsement_url(Endorsement.last)
end
test "should show endorsement" do
get endorsement_url(@endorsement)
assert_response :success
end
test "should get edit" do
get edit_endorsement_url(@endorsement)
assert_response :success
end
test "should update endorsement" do
patch endorsement_url(@endorsement), params: { endorsement: { } }
assert_redirected_to endorsement_url(@endorsement)
end
test "should destroy endorsement" do
assert_difference('Endorsement.count', -1) do
delete endorsement_url(@endorsement)
end
assert_redirected_to endorsements_url
end
end
|
class CreateOpportunities < ActiveRecord::Migration[5.2]
def change
create_table :opportunities do |t|
t.string :sfdc_id
t.string :account_id
t.string :name
t.string :stage
t.string :batch
t.string :status
t.timestamps
end
end
end
|
class Category < ActiveHash::Base
self.data = [
{id: 1, name: '---'}, {id: 2, name: '小説・文学'}, {id: 3, name: '言語'},
{id: 4, name: '自己啓発'},{id: 5, name: 'ビジネス・経済'}, {id: 6, name: '自然科学'},
{id: 7, name: 'テクノロジー'}, {id: 8, name: '歴史・地理'},{id: 9, name: '専門書'}
]
end
#class Category < ApplicationRecord
#belongs_to :book
#has_ancestry
#end |
module Queries
NodeIdentification = GraphQL::Relay::GlobalNodeIdentification.define do
# Given a UUID & the query context,
# return the corresponding application object
object_from_id ->(id, _config) do
type_name, id = NodeIdentification.from_global_id(id)
return Viewer if id == ::Viewer.id
type_name.constantize.find(id)
end
# Given an application object,
# return a GraphQL ObjectType to expose that object
type_from_object ->(object) do
GraphqlSchema.types[object.class.name]
end
end
end
GraphqlSchema.node_identification = Queries::NodeIdentification
|
# encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module MobileCenterApi
module Models
#
# Model object.
#
#
class DistributionGroupUserDeleteResponse
# @return [String] The code of the result
attr_accessor :code
# @return [Integer] The message of the result
attr_accessor :message
# @return [Integer] The status code of the result
attr_accessor :status
# @return [String] The email of the user
attr_accessor :user_email
#
# Mapper for DistributionGroupUserDeleteResponse class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
required: false,
serialized_name: 'DistributionGroupUserDeleteResponse',
type: {
name: 'Composite',
class_name: 'DistributionGroupUserDeleteResponse',
model_properties: {
code: {
required: false,
serialized_name: 'code',
type: {
name: 'String'
}
},
message: {
required: false,
serialized_name: 'message',
type: {
name: 'Number'
}
},
status: {
required: true,
serialized_name: 'status',
type: {
name: 'Number'
}
},
user_email: {
required: false,
serialized_name: 'user_email',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
|
# encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module MobileCenterApi
module Models
#
# a single frame of a stack trace
#
class StackFrame
# @return [String] address of the frame
attr_accessor :address
# @return [String] name of the class
attr_accessor :class_name
# @return [String] name of the method
attr_accessor :method
# @return [Boolean] is a class method
attr_accessor :class_method
# @return [String] name of the file
attr_accessor :file
# @return [Integer] line number
attr_accessor :line
# @return [Boolean] this line isn't from any framework
attr_accessor :app_code
# @return [String] Name of the framework
attr_accessor :framework_name
# @return [String] Raw frame string
attr_accessor :code_raw
# @return [String] Formatted frame string
attr_accessor :code_formatted
# @return [Enum] programming language of the frame. Possible values
# include: 'JavaScript', 'CSharp', 'Objective-C', 'Objective-Cpp', 'Cpp',
# 'C', 'Swift', 'Java', 'Unknown'
attr_accessor :language
# @return [Boolean] frame should be shown always
attr_accessor :relevant
# @return [String] parameters of the frames method
attr_accessor :method_params
#
# Mapper for StackFrame class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
required: false,
serialized_name: 'StackFrame',
type: {
name: 'Composite',
class_name: 'StackFrame',
model_properties: {
address: {
required: false,
serialized_name: 'address',
type: {
name: 'String'
}
},
class_name: {
required: false,
serialized_name: 'class_name',
type: {
name: 'String'
}
},
method: {
required: false,
serialized_name: 'method',
type: {
name: 'String'
}
},
class_method: {
required: false,
serialized_name: 'class_method',
type: {
name: 'Boolean'
}
},
file: {
required: false,
serialized_name: 'file',
type: {
name: 'String'
}
},
line: {
required: false,
serialized_name: 'line',
type: {
name: 'Number'
}
},
app_code: {
required: true,
serialized_name: 'app_code',
type: {
name: 'Boolean'
}
},
framework_name: {
required: false,
serialized_name: 'framework_name',
type: {
name: 'String'
}
},
code_raw: {
required: true,
serialized_name: 'code_raw',
type: {
name: 'String'
}
},
code_formatted: {
required: true,
serialized_name: 'code_formatted',
type: {
name: 'String'
}
},
language: {
required: false,
serialized_name: 'language',
type: {
name: 'String'
}
},
relevant: {
required: false,
serialized_name: 'relevant',
type: {
name: 'Boolean'
}
},
method_params: {
required: false,
serialized_name: 'method_params',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
|
class Match < ApplicationRecord
belongs_to :loser, class_name: "Player"
belongs_to :winner, class_name: "Player"
end
|
class AddQuestionCommentToReviewQuestionInstance < ActiveRecord::Migration
def self.up
add_column :review_question_instances, :question_comment, :boolean, :default => false
end
def self.down
remove_column :review_question_instances, :question_comment
end
end
|
module TestBench
module Controls
module Path
def self.example
TestFile.filename
end
def self.alternate
TestFile::Alternate.filename
end
Directory = Controls::Directory
module TestFile
def self.example(filename: nil, text: nil, directory: nil)
filename ||= self.filename
text ||= text
basename, extension, _ = filename.partition('.rb')
file = Tempfile.new([basename, extension], directory)
file.write(text)
file.close
tempfiles << file
file.path
end
def self.filename
'some_test_file.rb'
end
def self.text
'assert(true)'
end
def self.tempfiles
@tempfiles ||= []
end
module Alternate
def self.example
Path.example(filename: filename)
end
def self.filename
'other_test_file.rb'
end
end
module Pass
def self.example(directory: nil)
TestFile.example(filename: filename, directory: directory)
end
def self.filename
'some_passing_test.rb'
end
end
module Failure
def self.example(directory: nil)
TestFile.example(text: text, filename: filename, directory: directory)
end
def self.filename
'some_passing_test.rb'
end
def self.text
'refute(true)'
end
end
end
end
end
end
|
module ApplicationHelper
def paperclip_url(attachment)
#FixMe: Esto debe buscar la url actual
if Rails.env == "production"
"http://congresos.uach.mx#{attachment.url}"
elsif Rails.env == "development"
"http://localhost:3000#{attachment.url}"
end
end
def imagen?(nombre_archivo)
nombre_separado = nombre_archivo.split "."
extension = nombre_separado.last
extension == "png" or extension == "jpg" or extension == "jpg" or extension == "gif"
end
end
|
require 'spec_helper'
require File.expand_path "../../lib/injectable_rails_env", __FILE__
describe "InjectableRailsEnv" do
class Foo
include InjectableRailsEnv
end
let(:foo) { Foo.new }
# maybe not the best idea to meta progam tests but I'm lazy here :)
InjectableRailsEnv::SUPPORTED_ENVS.each do |name|
describe "#rails_env_#{name}?" do
it "is a private method" do
foo.private_methods(:false).map(&:to_s).should include("rails_env_#{name}?")
end
context "without injected rails_env" do
it "delegates to Rails.env.#{name}?" do
Rails.env.should_receive("#{name}?")
foo.send("rails_env_#{name}?")
end
end
context "with injected rails_env" do
context "in #{name} env" do
it "returns true" do
foo.rails_env = "#{name}"
foo.send("rails_env_#{name}?").should be_true
end
end
context "in none #{name} env" do
it "returns false" do
foo.rails_env = "non-#{name}"
foo.send("rails_env_#{name}?").should be_false
end
end
end
end
end
InjectableRailsEnv::SUPPORTED_ENVS.each do |name|
describe "::rails_env_#{name}?" do
before(:each) { Foo.rails_env = nil }
it "is a private method" do
Foo.private_methods(:false).map(&:to_s).should include("rails_env_#{name}?")
end
context "without injected rails_env" do
it "delegates to Rails.env.#{name}?" do
Rails.env.should_receive("#{name}?")
Foo.send("rails_env_#{name}?")
end
end
context "with injected rails_env" do
context "in #{name} env" do
it "returns true" do
Foo.rails_env = "#{name}"
Foo.send("rails_env_#{name}?").should be_true
end
end
context "in none #{name} env" do
it "returns false" do
Foo.rails_env = "non-#{name}"
Foo.send("rails_env_#{name}?").should be_false
end
end
end
end
end
end |
# For this practice problem, write a one-line program that creates the
# following output 10 times, with the subsequent line indented 1 space
# to the right:
10.times {|i| puts (" " * i) + "The Flintstones Rock!"} |
class Song
attr_accessor :name, :artist, :genre
@@all = []
def initialize (name, genre = nil)
@name = name
@genre = genre
save
end
def save
@@all << self
end
def artist_name
if self.artist != nil
self.artist.name
else
nil
end
end
def self.all
@@all
end
end
|
# Encoding: utf-8
class Pdp
include PageObject
page_url("#{BASE_URL}/the-sandringham-mid-length-heritage-trench-coat-p39004551")
h1(:title_bar, :css => '.titlebar-text')
# list_item(:description, :css => '.description')
h1(:itemName, :css => 'h1.titlebar-text')
div(:carousel, :css => '.js-carousel-track')
div(:itemNumber, :css => '.product-id')
div(:itemPrice, :css => '.js-price')
list_item(:description, :xpath => '//li[3]/p')
div(:shippingRestrictions, :css => '.shipping-restrictions.msg')
link(:descriptionTabCTA, :css => '.js-tabs-nav .tabs-nav-item:nth-child(1)')
link(:shippingTabCTA, :css => '.js-tabs-nav .tabs-nav-item:nth-child(2)')
div(:shippingInfo, :css => 'ul.shipping-returns')
list_item(:features, :css => '.description .features-set')
div(:colourPicker, :css => '.js-colour-picker')
div(:colourCTA, :css => '.js-carousel-toggler')
label(:colourName, :css => '.swatch h3 span:nth-child(1)') # To be replaced with '.colour-name' when it's reinstated
label(:moreColours, :css => '.swatch h3 span:nth-child(2)') # To be replaced with '.more-colours' when it's reinstated
div(:colourCarousel, :css => '.js-colour-picker .optioncarousel-picker')
div(:selectedColour, :css => '.js-colour-picker .optioncarousel-picker .carousel-item.selected a')
div(:size, :css => '.product-cta')
select(:size_cta, :css => '.product-cta select')
link(:add_to_bag, :css => '.js-add-to-bag a')
link(:contactUsCTA, :css => 'a[href="/customer-service/"].btn')
div(:sharingCell, :css => '.share')
div(:recommendedItems, :css => '.js-recommended-items')
image(:fullscreenImage, :css => '.js-fullscreen-content img')
button(:closeImage, :css => '.js-btn.icn-cross')
label(:bagMessage, :css => '.js-bag-message')
link(:addAnotherCTA, :css => '.js-bag-message a')
button(:viewBag, :css => '.js-view-bag')
label(:bagNotification, :css => '.js-mybby .js-notification')
link(:add_another, :css => '.add-another-message a')
link(:view_bag, :css => '.js-view-bag a')
p(:max_items, :css => '.js-bag-message p')
# link(:checkout, :css => '.js-checkout a')
def recommendedItem (i)
self.class.div(:recItem, :css => ".js-recommended-items li:nth-child(#{i}) a")
return self.recItem_element
end
def recommendedItemName (i)
self.class.label(:recName, :css => ".js-recommended-items li:nth-child(#{i}) .item-name")
return self.recName_element
end
def recommendedItemPrice (i)
self.class.label(:recPrice, :css => ".js-recommended-items li:nth-child(#{i}) .price")
return self.recPrice_element
end
def carouselImage (i)
self.class.div(:img, :css => ".js-carousel-container li:nth-child(#{i})")
return self.img_element
end
def visibleImages
carousel=$browser.find_element(:css, '.js-carousel-track')
carouselLeft=carousel.location.x
carouselRight=carousel.location.x + carousel.size.width
imgs=Array.new
i=1
#For each image in the carousel, check image position is within the bounds of the carousel
while self.carouselImage(i).exists?
#Don't even ask (calling .location.x on carousel images was scrolling to that image on iOS. Had to use javascript instead)
imagePos=$browser.execute_script("var rect = document.querySelector('.js-carousel-container li:nth-child(#{i})').getBoundingClientRect();return rect.left;")
if imagePos.between?(carouselLeft,carouselRight)
imgs.push(i)
end
i+=1
end
return imgs
end
def colourCarouselItem (i)
self.class.div(:colourImg, :css => ".js-colour-picker .optioncarousel-picker li:nth-child(#{i})")
return self.colourImg_element
end
def colourItemLink (i)
self.class.div(:colourLink, :css => ".js-colour-picker .optioncarousel-picker li:nth-child(#{i}) a")
return self.colourLink_element
end
def sizeOption (i)
self.class.div(:size, :css => ".product-cta option:nth-child(#{i})")
return self.size_element
end
def scroll(element)
$general.scroll(element,'.page.slider-item')
end
end |
class Api::V1::SessionsController < ApplicationController
def create
user = User.find_by(email: login_params[:email])
if user && user.authenticate(login_params[:password])
jwt = Auth.issue({user: user.id})
response = {
jwt: jwt,
id: user.id,
email: user.email,
name: user.name
}
render json: response, status: 201
else
render json: {errors: "Invalid username or password"}, status: 401
end
end
private
def login_params
params.require(:login).permit(:email, :password)
end
end
|
# p044inverse.rb
def inverte(x)
raise ArgumentError, 'O argumento não é numérico.' unless x.is_a? Numeric
1.0 / x
end
puts inverte(2)
puts inverte('Não é um número.')
|
ImportPage::Engine.routes.draw do
root to: 'import#show'
resource :import, controller: 'import'
end
|
module Accessible
extend ActiveSupport::Concern
protected
def get_user
current_admin ? current_admin : current_user
end
end
|
class Report < ActiveRecord::Base
belongs_to :user
has_many :subscriptions, class_name: ScheduledReport, foreign_key: :report_id
visitable # Used to track user visit associated with processed report
def client_query
@_client_query ||= ProposalFieldedSearchQuery.new(query[user.client_model_slug])
end
def text_query
query["text"]
end
def humanized_query
query["humanized"]
end
def query_string
if text_query.present? && client_query.present?
"(#{text_query}) AND (#{client_query})"
elsif client_query.present?
"#{client_query}"
else
text_query
end
end
def query
super || default_query
end
def default_query
{ "humanized" => "", "text" => "" }
end
def url
allowed_params = ["text", user.client_model_slug, "from", "size"]
params = query.slice(*allowed_params)
params[:report] = id
"#{Rails.application.routes.url_helpers.query_proposals_path}?#{params.to_query}"
end
def run
client_param_name = user.client_model_slug
fielded_query = query[user.client_model_slug]
params = ActionController::Parameters.new(text: text_query, client_param_name => fielded_query, size: :all)
ProposalListingQuery.new(user, params).query
end
def subscribed?(some_user)
subscriptions.where(user: some_user).any?
end
def subscription_for(some_user)
subscriptions.find_by(user: some_user)
end
def self.sql_for_user(user)
<<-SQL.gsub(/^ {6}/, "")
SELECT * FROM reports
WHERE user_id=#{user.id}
OR (
shared=true AND user_id IN (
SELECT id FROM users WHERE client_slug='#{user.client_slug}'
)
)
SQL
end
def self.for_user(user)
sql = sql_for_user(user)
self.find_by_sql(sql)
end
end
|
class Day11Solver < SolverBase
class Cell
attr_reader :x, :y, :power_level
def initialize(x, y, serial)
@x, @y = x + 1, y + 1
@serial = serial
init_power_level
end
def to_s
"cell(#{x}, #{y})"
end
private
def init_power_level
@rack_id = x + 10
@power_level = @rack_id * y
@power_level += @serial
@power_level *= @rack_id
@power_level = (@power_level / 100) % 10 - 5
end
end
class Grid
attr_reader :column, :row
def initialize(row, column, serial)
@row = row
@column = column
@serial = serial
@grid = Array.new(@row) { [] }
set_cells
end
def cell(x, y)
@grid[x] && @grid[x][y]
end
private
def set_cells
(0...@row).each do |row|
(0...@column).each do |column|
@grid[row][column] = Cell.new(row, column, @serial)
end
end
end
end
class GridPowerLevelScanner
attr_reader :grid, :power_levels
def initialize(grid)
@grid = grid
@power_levels = init_power_levels
end
def scan(size = nil)
size ||= grid.row
(2..size).each do |size|
puts size
even = (size % 2).zero?
(0...grid.row).each do |x|
break if (x + size) > grid.row
(0...grid.column).each do |y|
break if (y + size) > grid.column
if even
half = size / 2
power_level = [
[x, y, half],
[x + half, y, half],
[x, y + half, half],
[x + half, y + half, half]
].map { |k| power_levels.fetch(k) }.sum
power_levels[[x, y, size]] = power_level
else
other_x = x + size - 1
other_y = y + size - 1
cells_power_level = (0...size).map { |dy| grid.cell(other_x, y + dy).power_level }.sum
cells_power_level += (0...size).map { |dx| grid.cell(x + dx, other_y).power_level }.sum
cells_power_level -= power_levels.fetch([other_x, other_y, 1])
power_levels[[x, y, size]] = cells_power_level + power_levels[[x, y, size - 1]]
end
end
end
end
# puts power_levels[[231, 250, 12]]
end
private
def init_power_levels
power_levels = {}
(0...grid.row).each do |x|
(0...grid.column).each do |y|
power_levels[[x, y, 1]] = grid.cell(x, y).power_level
end
end
power_levels
end
end
end
class Day11Solver < SolverBase
def call(serial)
grid = Grid.new(300, 300, serial)
scan(grid).max_by { |e| e.first }
end
def call2(serial, size = nil)
grid = Grid.new(300, 300, serial)
scanner = GridPowerLevelScanner.new(grid)
scanner.scan(size)
scanner.power_levels.max_by do |(k, v)|
v
end.first
end
def call3(serial, size = nil)
grid = Grid.new(300, 300, serial)
scanner = GridPowerLevelScanner.new(grid)
scanner.scan(size)
scanner
end
def call4(serial, size = nil)
grid = Grid.new(300, 300, serial)
scan_all_sizes(grid)
end
private
def scan(grid)
subgrids = []
(0...grid.row).map do |x|
(0...grid.column).map do |y|
next if (x + 2) >= grid.row || (y + 2) >= grid.column
cells = [0, 1, 2].map do |i|
grid.cell(x + i, y)
end
cells += [0, 1, 2].map do |i|
grid.cell(x + i, y + 1)
end
cells += [0, 1, 2].map do |i|
grid.cell(x + i, y + 2)
end
subgrids << [cells.map(&:power_level).sum, cells.first]
end
end
subgrids
end
def scan_all_sizes(grid, want = 12)
subgrids = []
(0...grid.row).each do |x|
(0...grid.column).each do |y|
(1..want).each do |size|
next if (x + size) > grid.row || (y + size) > grid.column
cells = []
(0...size).each do |yi|
cells += (0...size).map do |xi|
grid.cell(x + xi, y + yi)
end
end
subgrids << [cells.map(&:power_level).sum, cells.first, size]
end
end
end
subgrids.max_by { |x| x.first }
end
end
|
module CamaleonCms
module CaptchaHelper
# build a captcha image
# len: Number or characters to include in captcha (default 5)
def cama_captcha_build(len = 5)
img = MiniMagick::Image.open(File.join($camaleon_engine_dir.present? ? $camaleon_engine_dir : Rails.root.to_s,
'lib', 'captcha', "captcha_#{rand(12)}.jpg").to_s)
text = cama_rand_str(len)
session[:cama_captcha] = [] unless session[:cama_captcha].present?
session[:cama_captcha] << text
img.combine_options do |c|
c.gravity 'Center'
c.fill('#FFFFFF')
c.draw "text 0,5 #{text}"
c.font File.join($camaleon_engine_dir.present? ? $camaleon_engine_dir : Rails.root.to_s, 'lib', 'captcha',
'bumpyroad.ttf')
c.pointsize '30'
end
img
end
# build a captcha tag (image with captcha)
# img_args: attributes for image_tag
# input_args: attributes for input field
def cama_captcha_tag(len = 5, img_args = { alt: '' }, input_args = {}, bootstrap_group_mode = false)
unless input_args[:placeholder].present?
input_args[:placeholder] =
I18n.t('camaleon_cms.captcha_placeholder',
default: 'Please enter the text of the image')
end
img_args['onclick'] = "this.src = \"#{cama_captcha_url(len: len)}\"+\"&t=\"+(new Date().getTime());"
img = "<img style='cursor: pointer;' src='#{cama_captcha_url(len: len,
t: Time.current.to_i)}' #{img_args.collect do |k, v|
"#{k}='#{v}'"
end.join(' ')} />"
input = "<input type='text' name='captcha' #{input_args.collect { |k, v| "#{k}='#{v}'" }.join(' ')} />"
if bootstrap_group_mode
"<div class='input-group input-group-captcha'><span class='input-group-btn' style='vertical-align: top;'>#{img}</span>#{input}</div>"
else
"<div class='input-group-captcha'>#{img}#{input}</div>"
end
end
# verify captcha value
def cama_captcha_verified?
(session[:cama_captcha] || []).include?((params[:cama_captcha] || params[:captcha]).to_s.upcase)
end
# ************************* captcha in attack helpers ***************************#
# check if the current visitor was submitted 5+ times
# key: a string to represent a url or form view
# key must be the same as the form "captcha_tags_if_under_attack(key, ...)"
def cama_captcha_under_attack?(key)
session["cama_captcha_#{key}"] ||= 0
session["cama_captcha_#{key}"].to_i > current_site.get_option('max_try_attack', 5).to_i
end
# verify captcha values if this key is under attack
# key: a string to represent a url or form view
def captcha_verify_if_under_attack(key)
res = cama_captcha_under_attack?(key) ? cama_captcha_verified? : true
session["cama_captcha_#{key}"] = 0 if cama_captcha_verified?
res
end
# increment attempts for key by 1
def cama_captcha_increment_attack(key)
session["cama_captcha_#{key}"] ||= 0
session["cama_captcha_#{key}"] = session["cama_captcha_#{key}"].to_i + 1
end
# reset the attacks counter for key
# key: a string to represent a url or form view
def cama_captcha_reset_attack(key)
session["cama_captcha_#{key}"] = 0
end
# return a number of attempts for key
# key: a string to represent a url or form view
def cama_captcha_total_attacks(key)
session["cama_captcha_#{key}"] ||= 0
end
# show captcha if under attack
# key: a string to represent a url or form view
def cama_captcha_tags_if_under_attack(key, captcha_parmas = [5, {}, { class: 'form-control required' }])
cama_captcha_tag(*captcha_parmas) if cama_captcha_under_attack?(key)
end
private
# generate random string for captcha
# len: length of characters, default 6
def cama_rand_str(len = 6)
alphabets = [('A'..'Z').to_a].flatten!
alphanumerics = [('A'..'Z').to_a, ('1'..'9').to_a].flatten!
str = alphabets[rand(alphabets.size)]
(len.to_i - 1).times do
str << alphanumerics[rand(alphanumerics.size)]
end
str
end
end
end
|
class Repository
include Mongoid::Document
field :name
embeds_many :users
validates_presence_of :name
def set_statistic(type, users_stats, period)
users_stats.each { |user, value|
user_model = users.find_or_create_by(login: user)
user_model.set_statistic(type, value, period)
}
end
def self.get_statistic(period)
stats = []
repositories = Repository.all
repositories.each{ |repository|
best = repository.find_best_user(period)
if best && best[:value] > 0
stats << { repository_name: repository.name, user: best }
end
}
stats
end
def self.find_absolute_user(period)
user_stats = { }
repositories = Repository.all
repositories.each{|repository|
repository.users.each{|user|
value = user.summary_for_period(period)
if value > 0
if user_stats[user.login]
user_stats[user.login] = user_stats[user.login] + value
else
user_stats[user.login] = value
end
end
}
}
return nil if user_stats.empty?
best = user_stats.max_by{|k,v| v}
{ login: best[0] , value: best[1] }
end
def find_best_user(period)
users_hash = { }
return nil if users.empty?
users.each{|user|
summary = user.summary_for_period(period)
users_hash[user.login] = summary
}
best = users_hash.max_by{|k,v| v}
{ login: best[0] , value: best[1] }
end
end
|
class App < Sinatra::Base
enable :logging
SHARED_SECRET = ENV['SHARED_SECRET']
post '/webhooks/order' do
hmac = request.env['HTTP_X_SHOPIFY_HMAC_SHA256']
request.body.rewind
data = request.body.read
halt 403, "You're not authorized to perform this action" unless verify_webhook(hmac, data)
json_data = JSON.parse(data)
gateway = json_data['gateway']
checkout_id = json_data['checkout_id']
if gateway == 'mercado_pago'
logger.info refund_order(checkout_id)
end
return [200, 'Webhook notification received successfully']
end
helpers do
def refund_order(checkout_id)
mp = MercadoPago.new(ENV['CLIENT_ID'], ENV['CLIENT_SECRET'])
response = mp.get("/collections/search?external_reference=#{checkout_id}")['response']
results = response['results']
return if results.empty?
payment = results.first
payment_id = payment['collection']['id'].to_s
mp.refund_payment(payment_id)
end
def verify_webhook(hmac, data)
digest = OpenSSL::Digest.new('sha256')
calculated_hmac = Base64.encode64(OpenSSL::HMAC.digest(digest, SHARED_SECRET, data)).strip
hmac == calculated_hmac
end
end
end
|
class RenameBaseQuestionsToGameQuestions < ActiveRecord::Migration
def change
rename_table :base_questions, :game_questions
remove_column :game_questions, :type
end
end
|
class ChangeDataTypesForScoresAndDistances < ActiveRecord::Migration
def up
change_column :exercises, :score, :decimal, :precision => 12, :scale => 7
change_column :bike_records, :distance, :decimal, :precision => 12, :scale => 7
change_column :run_records, :distance, :decimal, :precision => 12, :scale => 7
end
def down
change_column :exercises, :score, :integer
change_column :bike_records, :distance, :integer
change_column :run_records, :distance, :integer
end
end
|
# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
require 'gettext/rails'
class ApplicationController < ActionController::Base
include AuthenticatedSystem
include RoleRequirementSystem
# You can move this into a different controller, if you wish. This module gives you the require_role helpers, and others.
helper :all # include all helpers, all the time
# See ActionController::RequestForgeryProtection for details
# Uncomment the :secret if you're not using the cookie session store
# protect_from_forgery # :secret => 'd0e46da1171dbcc213f85ac6040dc20d'
before_filter :login_required
before_init_gettext :set_default_locale
after_filter :set_headers
init_gettext 'banco_tematico'
# Rescatar desde una excepcion en el controlador publico
def rescue_action_in_public(exception)
case(exception)
when ActiveRecord::RecordNotFound
if !request.xhr?
render :text => '<h3>No se encuentra el registro que busca</h3>', :layout => "login"
else
render :text => '<h3>No se encuentra el registro que busca</h3>', :layout => false
end
when NoMethodError
if !request.xhr?
render :text => '<h3>No se encuentra el metodo que busca</h3>', :layout => "login"
else
render :text => '<h3>No se encuentra el metodo que busca</h3>', :layout => false
end
else
if !request.xhr?
render :text => "<h3>El sitio no tiene la informacion pedida</h3>", :layout => "login"
else
render :text => "<h3>El sitio no tiene la informacion pedida</h3>", :layout => false
end
end
end
# Coloca los enlaces a las series cronologicas
def colocarenlaces(serie,url_base)
tags = Tag.find(:all)
for tag in tags
mylink = Enlace.find(:all, :conditions=>['lactual=? AND tag_id=?',url_base+serie.id.to_s,tag.id])
if mylink.length > 0
case url_base
when /tema_clave/
#serie.hecho =serie.hecho.sub(/#{tag.descripcion}/i,"<a href='#{mylink[0].lsiguiente}'>#{tag.descripcion}</a>") if !serie.hecho.nil?
serie.hecho =serie.hecho.gsub(/#{tag.descripcion}/i,"<a href='/tema_clave/show_ocurrencias/#{tag.id}'>#{tag.descripcion}</a>") if !serie.hecho.nil?
serie.contexto=serie.contexto.gsub(/#{tag.descripcion}/i,"<a href='/tema_clave/show_ocurrencias/#{tag.id}'>#{tag.descripcion}</a>") if !serie.contexto.nil?
serie.gobierno=serie.gobierno.gsub(/#{tag.descripcion}/i,"<a href='/tema_clave/show_ocurrencias/#{tag.id}'>#{tag.descripcion}</a>") if !serie.gobierno.nil?
serie.fuentes =serie.fuentes.gsub(/#{tag.descripcion}/i,"<a href='/tema_clave/show_ocurrencias/#{tag.id}'>#{tag.descripcion}</a>") if !serie.fuentes.nil?
when /biblioteca/
#serie.titulo =serie.titulo.sub(/#{tag.descripcion}/i,"<a href='#{mylink[0].lsiguiente}'>#{tag.descripcion}</a>") if !serie.titulo.nil?
serie.titulo =serie.titulo.gsub(/#{tag.descripcion}/i,"<a href='/tema_clave/show_ocurrencias/#{tag.id}'>#{tag.descripcion}</a>") if !serie.titulo.nil?
serie.autor =serie.autor.gsub(/#{tag.descripcion}/i,"<a href='/tema_clave/show_ocurrencias/#{tag.id}'>#{tag.descripcion}</a>") if !serie.autor.nil?
serie.descripcion=serie.descripcion.gsub(/#{tag.descripcion}/i,"<a href='/tema_clave/show_ocurrencias/#{tag.id}'>#{tag.descripcion}</a>") if !serie.descripcion.nil?
when /primera_manos/
#serie.titular =serie.titular.sub(/#{tag.descripcion}/i,"<a href='#{mylink[0].lsiguiente}'>#{tag.descripcion}</a>") if !serie.titular.nil?
serie.titular =serie.titular.gsub(/#{tag.descripcion}/i,"<a href='/tema_clave/show_ocurrencias/#{tag.id}'>#{tag.descripcion}</a>") if !serie.titular.nil?
serie.presentacion=serie.presentacion.gsub(/#{tag.descripcion}/i,"<a href='/tema_clave/show_ocurrencias/#{tag.id}'>#{tag.descripcion}</a>") if !serie.presentacion.nil?
serie.fuentes =serie.fuentes.gsub(/#{tag.descripcion}/i,"<a href='/tema_clave/show_ocurrencias/#{tag.id}'>#{tag.descripcion}</a>") if !serie.fuentes.nil?
end
end
end
end
def set_default_locale
#set_locale settings.lang locale = params[:lang] || cookies["lang"] || "es"
set_locale 'es_ES'
end
protected
def set_headers
headers['Expires'] = 'Thu, 27 Mar 1980 23:59:00 GMT'
headers['Cache-Control'] = 'no-cache, must-revalidate'
headers['Pragma'] = 'no-cache'
headers['p3p'] = 'CP="CAO PSA OUR"'
end
end
|
require 'sidekiq'
require 'sidekiq-status'
class OneMoneyPublishWorker
include Sidekiq::Worker
include Sidekiq::Status::Worker
def perform(one_money_id, target, options = {})
default_options = {
sign_url: Settings.app.website + '/authorize/weixin',
api_url: '/api/promotions/one_money',
qr_code: true,
prefix: Settings.promotions.one_money.enter_url,
type: :one_money,
winners_num: 50
}
options.symbolize_keys!
options = options.reverse_merge(default_options)
one_money = OneMoney[one_money_id]
dir, exec = get_scripts_type(options[:type])
Rails.logger.info options
Rails.logger.info default_options
context = {
name: target,
one_money_id: one_money.id,
qrcode: options[:qr_code],
home_img: one_money.cover_url,
list_img: one_money.head_url,
api_url: options[:api_url],
winners: options[:winners_num],
sign_url: options[:sign_url]
}
exec.gsub! /\$(\w+)/ do |m|
key = $1.to_sym
context[key]
end
Rails.logger.info dir
Rails.logger.info exec
`cd #{dir}; #{exec}`
store url: File.join(options[:prefix], target)
end
def get_scripts_type(type)
scripts =
case type
when :one_money, "one_money", ""
Settings.promotions.one_money.scripts.publish
when :daily_cheap, "daily_cheap"
Settings.promotions.daily_cheap.scripts.publish
else
scripts = Settings.promotions.one_money.scripts.publish
end
dir = scripts.dir
exec = scripts.exec.dup
[dir, exec]
end
end
|
class AddFieldsToInstance < ActiveRecord::Migration
def change
add_column :instances, :region_id, :integer
add_column :instances, :name, :string
end
end
|
class RemoveTimeToEvents < ActiveRecord::Migration[5.0]
def change
remove_column :events, :time, :string
remove_column :events, :month, :integer
remove_column :events, :day, :integer
add_column :events, :begin_time, :datetime
add_column :events, :end_time, :datetime
end
end
|
require 'rails_helper'
require_relative '../factories/cryptocurrencies.rb'
RSpec.describe Cryptocurrency, type: :model do
subject { create(:cryptocurrency) }
let(:pairs) { ['USD'] }
describe 'validations' do
describe 'name' do
it 'must be present' do
expect(subject).to be_valid
subject.name = nil
expect(subject).to_not be_valid
end
it 'must be unique' do
expect(subject).to be_valid
subject_clone = create(:cryptocurrency)
subject_clone.name = subject.name
expect(subject_clone).to_not be_valid
end
end
describe 'symbol' do
it 'must be present' do
expect(subject).to be_valid
subject.symbol = nil
expect(subject).to_not be_valid
end
it 'must be unique' do
expect(subject).to be_valid
subject_clone = create(:cryptocurrency)
subject_clone.symbol = subject.symbol
expect(subject_clone).to_not be_valid
end
end
describe 'pair' do
it 'must be present' do
expect(subject).to be_valid
subject.pair = nil
expect(subject).to_not be_valid
end
it 'must have default value when created' do
expect(subject.pair).to eq(Cryptocurrency.pairs.keys[0])
end
it 'must have an enum value' do
pairs.each_with_index do |pair, index|
expect(described_class.pairs[pair]).to eq index
end
end
end
describe 'price' do
it 'must be present' do
expect(subject).to be_valid
subject.price = nil
expect(subject).to_not be_valid
end
it 'must have only numbers' do
expect(subject).to be_valid
subject.price = 'AB001'
expect(subject).to_not be_valid
end
end
describe 'market_cap' do
it 'must be present' do
expect(subject).to be_valid
subject.market_cap = nil
expect(subject).to_not be_valid
end
it 'must have only numbers' do
expect(subject).to be_valid
subject.market_cap = 'AB001'
expect(subject).to_not be_valid
end
end
describe 'total_volume' do
it 'must be present' do
expect(subject).to be_valid
subject.total_volume = nil
expect(subject).to_not be_valid
end
it 'must have only numbers' do
expect(subject).to be_valid
subject.total_volume = 'AB001'
expect(subject).to_not be_valid
end
end
describe 'favorites_count' do
it 'must have default value when created' do
expect(subject.favorites_count).to eq(0)
end
it 'must have only numbers' do
expect(subject).to be_valid
subject.favorites_count = 'AB001'
expect(subject).to_not be_valid
end
end
end
describe 'associations' do
describe 'favorite_cryptocurrencies' do
it { expect(described_class.reflect_on_association(:favorite_cryptocurrencies).macro).to eq(:has_many) }
end
describe 'users' do
it { expect(described_class.reflect_on_association(:users).macro).to eq(:has_many) }
end
end
describe 'instance methods' do
it '#increment_favorite_count! should increment by 1 favorites_count' do
expect(subject.favorites_count).to eq(0)
subject.increment_favorites_count!
expect(subject.favorites_count).to eq(1)
end
it '#decrement_favorites_count! should decrease by 1 favorites_count' do
subject.favorites_count = 1
expect(subject.favorites_count).to eq(1)
subject.decrement_favorites_count!
expect(subject.favorites_count).to eq(0)
end
end
end
|
class Position < ActiveRecord::Base
has_and_belongs_to_many :authors
has_and_belongs_to_many :categories
has_many :bookings
def self.search(search)
if search
where(["title LIKE ?","%#{search}%"])
else
all
end
end
def first_possible_date
if self.bookings.empty?
return DateTime.now
end
fdate = self.bookings.first.end_date
self.bookings.each do |b|
if b.end_date < fdate
fdate = b.end_date
end
end
fdate
end
end
|
class User < ApplicationRecord
has_many :jokes, dependent: :destroy
has_many :gigs, dependent: :destroy
has_many :clubs, through: :gigs
validates :name, :age, :user_name, :email, :hometown, presence: true
has_secure_password
def featured_jokes
test = self.jokes.max_by {|joke| joke.like}
end
def upcoming_gigs
self.gigs.sort_by {|gig| gig.date}
end
def dogshit_joke
test = self.jokes.max_by {|joke| joke.dislike}
end
end
|
class ModifyCommentStoreId < ActiveRecord::Migration
def up
rename_column :comments, :store_id, :coupon_id
end
def down
rename_column :comments, :coupon_id, :store_id
end
end
|
class Person < ActiveRecord::Base
has_many :addresses
accepts_nested_attributes_for :addresses, allow_destroy: true
def full_name
self.name + " " + self.last_name
end
end
|
=begin
Skill Master Script
by Fomar0153
Version 1.0
----------------------
Notes
----------------------
Requires my unique classes script
Allows you to learn new skills by using your existing skills.
----------------------
Instructions
----------------------
You will need to edit module Skill_Uses, further instructions
are located there.
----------------------
Known bugs
----------------------
None
=end
module Skill_Uses
SKILLS = []
# Add/Edit lines like the one below
# SKILLS[ORIGINAL] = [NEW, USES, REPLACE] REPLACE should be true or false
SKILLS[3] = [4, 50, true]
# Reads as: When using skill 3 for it's 50th time replace it with skill 4
end
class Game_SkillMaster < Game_Actor
#--------------------------------------------------------------------------
# ● New Method setup
#--------------------------------------------------------------------------
def setup(actor_id)
super(actor_id)
@skill_uses = []
end
#--------------------------------------------------------------------------
# ● New Method add_skill_use
#--------------------------------------------------------------------------
def add_skill_use(id)
if @skill_uses[id] == nil
@skill_uses[id] = 0
end
@skill_uses[id] += 1
unless Skill_Uses::SKILLS[id] == nil
if @skill_uses[id] == Skill_Uses::SKILLS[id][1]
learn_skill(Skill_Uses::SKILLS[id][0])
forget_skill(id) if Skill_Uses::SKILLS[id][2]
SceneManager.scene.add_text(@name + " learns " + $data_skills[Skill_Uses::SKILLS[id][0]].name + ".")
end
end
end
end
class Game_Battler < Game_BattlerBase
#--------------------------------------------------------------------------
# ● Aliases item_apply
#--------------------------------------------------------------------------
alias fomar0004_item_apply item_apply
def item_apply(user, item)
if user.is_a?(Game_SkillMaster) and item.is_a?(RPG::Skill)
user.add_skill_use(item.id)
end
fomar0004_item_apply(user, item)
end
end
class Scene_Battle < Scene_Base
#--------------------------------------------------------------------------
# ● New method add_text
#--------------------------------------------------------------------------
def add_text(text)
@log_window.add_text(text)
end
end |
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe PersistentApiToken do
let(:token) { create(:persistent_api_token) }
it 'does not set an expiration date on create' do
expect(token.expires_at).to be_nil
end
it 'has the correct length token' do
expect(token.new_token.bytes.length).to eq(64)
end
describe 'current scope' do
it 'does not include non-persistent tokens', :aggregate_failures do
user = create(:user)
at = ApiToken.create(user: user)
pat = described_class.create(user: user)
pat_at = ApiToken.find(pat.id)
expect(user.api_tokens.to_a).to contain_exactly(at, pat_at)
expect(described_class.current).to contain_exactly(pat)
end
end
describe '#current?' do
it 'returns true when not expired' do
expect(token.current?).to be(true)
end
it 'returns false when expired' do
token.expires_at = 1.second.ago
expect(token.current?).to be(false)
end
end
describe '#expire!' do
it 'expires the token' do
expect { token.expire! }.to change { token.current? }.to(false)
end
end
describe '#match?' do
context 'when using the persistent model' do
it 'matches with the correct token' do
t = token.new_token
expect(described_class.find(token.id)).to be_match(t)
end
it 'does not match with an invalid token' do
expect(described_class.find(token.id)).not_to be_match('invalid')
end
end
context 'when using the base model' do
it 'matches with the correct token' do
t = token.new_token
expect(ApiToken.find(token.id)).to be_match(t)
end
it 'does not match with an invalid token' do
expect(ApiToken.find(token.id)).not_to be_match('invalid')
end
end
end
end
|
module ApplicationHelper
require 'rtesseract'
require 'java'
java_import java.lang.System
def sysout()
version = System.getProperties["java.runtime.version"]
version
end
def getTesseract()
image = RTesseract.new("niCherries.jpg")
image.to_s
end
def get_season()
time = Time.new
if(time.month >= 3) && (time.month <=5)
"Yay for spring"
elsif (time.month >= 5) && (time.month <=8)
"everyone like summer excpet in the desert"
elsif(time.month >= 8) && (time.month <=11)
"fall is ok"
else
"winter is the best in the desert"
end
end
def count_to_10
x=2
number_list = "1"
loop do
number_list = number_list + ", " + x.to_s
x += 1
break if x > 10
end
"#{number_list}"
end
end
|
# displayed: with/without
Then(/^I verify the 'Close Idea' popup is displayed "([^"]*)" the "([^"]*)" radio group$/) do |displayed, radiogroup_label|
within @viewideapage.closeidea_container do
if displayed == 'with'
within(:xpath,".//div[contains(@class,'pageTypeOptions')]") do
has_text?(radiogroup_label).should eq(true)
@viewideapage.has_successfulclose_radiobutton?.should eq(true)
@viewideapage.has_abortclose_radiobutton?.should eq(true)
end
else
has_xpath?(".//div[contains(@class,'pageTypeOptions')]").should eq(false)
end
end
end
Then(/^I verify "([^"]*)" info text is displayed on the 'Close Idea' popup$/) do |text|
within @viewideapage.closeideainfo_container do
has_text?(text).should eq(true)
end
end
And(/^I verify the idea's image is displayed on the 'Close Idea' popup$/) do
within @viewideapage.closeidea_container do
has_xpath?(".//div[@class='idea-image tiny']/img").should eq(true)
end
end
And(/^I verify the "([^"]*)" text editor is displayed on the 'Close Idea' popup$/) do |texteditor_label|
within @viewideapage.closeidea_container do
has_text?(texteditor_label).should eq(true)
@viewideapage.has_reasonideaclosure_iframe?.should eq(true)
end
end
And(/^I verify the "([^"]*)" custom field is displayed on the 'Close Idea' popup$/) do |field|
within @viewideapage.closeidea_container do
has_xpath?(".//div[@class='formElement' and contains(.,'#{field}')]/*").should eq(true)
end
end
And(/^I fill in the "([^"]*)" custom field with "([^"]*)" on the 'Close Idea' popup$/) do |fieldLabel, value|
within @viewideapage.closeidea_container do
case fieldLabel
when /Text Field/ then
find(:xpath,".//div[@class='formElement' and contains(.,'#{fieldLabel}')]/input[@type='text']").set(value)
when /Text Editor/ then
within_frame(find(:xpath, ".//div[@class='formElement' and contains(.,'#{fieldLabel}')]//iframe")) do
editor = find_by_id('tinymce')
editor.click
editor.native.clear
editor.native.send_keys(value)
end
when /Checkbox/ then
@value = value == 'on' ? true : false
find(:xpath,".//div[@class='formElement' and contains(.,'#{fieldLabel}')]/input[@type='checkbox']").set(@value)
else
fail(ArgumentError.new("'#{fieldLabel}' field is not listed!"))
end
end
end
And(/^I verify the "([^"]*)" error message is displayed on the 'View Idea' page$/) do |message|
message = message.gsub("'",34.chr)
@message_xpath = ".//div[contains(@class,'popup-notice')][contains(.,'#{message}')]"
puts @message_xpath
waitTime = Time.now + 10
loop do
@result = has_xpath?(@message_xpath)
break if Time.now > waitTime or @result
end
@result.should eq(true)
end
And(/^I click on the "([^"]*)" button on the "([^"]*)" popup$/) do |button, popup|
case popup
when 'Close Idea' then
within @viewideapage.closeidea_container do
@viewideapage.clickButton('Submit')
end
else
fail(ArgumentError.new("'#{popup}' is not listed!"))
end
end
And(/^I select "([^"]*)" on 'Was the idea implemented\?'$/) do |option|
begin
within @viewideapage.closeidea_container do
option == 'Yes' ? @viewideapage.successfulclose_radiobutton.click : @viewideapage.abortclose_radiobutton.click
end
rescue
option == 'Yes' ? @viewideapage.successfulclose_radiobutton.click : @viewideapage.abortclose_radiobutton.click
sleep 2
end
end
Then(/^I verify that "([^"]*)" received a "([^"]*)" email notification for "([^"]*)" idea with "([^"]*)" reason$/) do |user, notification, idea, reason|
sleep 10
emailacc = @users.getUser(user,'email')
emailpsw = @users.getUser(user,'emailpsw')
match = emailacc[/\+(.*?)@/m]
emailacc = emailacc.gsub(match,'@') unless match.nil? #retrieving mail w/o alias
case notification
when 'Idea Closed Unsuccessfully Notice' then
subject = "Your Idea, (#{@mainpage.getIdeaTitle(idea)}), closed unsuccessfully."
@inboxemails = @mainpage.getNumberEmailsByContent(emailacc, emailpsw, subject, reason)
when 'Idea Closed Successfully Notice' then
subject = "Your Idea, (#{@mainpage.getIdeaTitle(idea)}), closed."
@inboxemails = @mainpage.getNumberEmailsByContent(emailacc, emailpsw, subject, reason)
end
fail(ArgumentError.new("No '#{subject}' email was received!")) if @inboxemails == 0
end
Then(/^I verify the 'Close Idea' popup is not displayed$/) do
@viewideapage.has_closeidea_container?.should eq(false)
end
Then(/^I verify that "([^"]*)" received a "([^"]*)" email notification for "([^"]*)" idea with "([^"]*)" message due to "([^"]*)"'s request$/) do |user, notification, idea, message, user_action|
@mainpage.waitAmountMinutes(3)
emailacc = @users.getUser(user,'email')
emailpsw = @users.getUser(user,'emailpsw')
match = emailacc[/\+(.*?)@/m]
emailacc = emailacc.gsub(match,'@') unless match.nil? #retrieving mail w/o alias
userNameAction = "#{@users.getUser(user_action,'firstname')} #{@users.getUser(user_action,'lastname')}"
ideaTitle = @mainpage.getIdeaTitle(idea)
case notification
when 'Request to Close Idea as Successful' then
@subject = 'Request to Close Idea Successfully'
@content = "The owner of this idea #{ideaTitle}.*,.*#{userNameAction} has submitted a request to close it successfully..*#{message}*Please click here.*to process this request."
when 'Request to Close Idea as Unsuccessful' then
@subject = 'Request to close idea unsuccessfully'
@content = "The owner of this idea #{ideaTitle}.*,.*#{userNameAction} has submitted a request to close it unsuccessfully..*#{message}*To process this request, please click here.*."
when 'Comment in Moderation Has Been Approved' then
@subject = "Your post was Approved: #{idea}"
userName = "#{@users.getUser(user,'firstname')} #{@users.getUser(user,'lastname')}"
@content = "#{userName}, your category thread, #{idea}$.*was Approved.$"
when 'Comment in Moderation Has Been Rejected' then
@subject = "Your Category Thread, (#{idea}) was rejected by #{userNameAction}."
@content = "Your Category Thread #{idea}$.*has been rejected by #{userNameAction}.$"
else
fail(ArgumentError.new("'#{notification}' is not listed!"))
end
fail(ArgumentError.new("'#{@subject}' not found with the expected content!")) unless @homepage.mailHasContent(emailacc, emailpsw, @subject, @content, true)
end
When(/^I open the "([^"]*)"'s 'Request to Close Idea as (.*)' email and click on the "([^"]*)" link sent for "([^"]*)" idea$/) do |user, successful, link, idea|
emailacc = @users.getUser(user,'email')
emailpsw = @users.getUser(user,'emailpsw')
match = emailacc[/\+(.*?)@/m]
emailacc = emailacc.gsub(match,'@') unless match.nil? #retrieving mail w/o alias
sleep 7
content = @mainpage.getIdeaTitle(idea)
if successful == 'Successful' then
@subject = 'Request to Close Idea Successfully'
elsif successful == 'Unsuccessful'
@subject = 'Request to close idea unsuccessfully'
end
link == 'idea' ? link = content : link = link
@homepage.clickEmailLink(emailacc, emailpsw, @subject, content, link, true)
end
Then(/^I share the idea with "([^"]*)" user using "([^"]*)" message$/) do |user, message|
@viewideapage.clickLink 'Share'
@viewideapage.fillValue('Share Username', user)
@viewideapage.fillValue('Share Message', message)
@viewideapage.clickButton('Send')
end
And(/^I open Closed Idea popup banner on the "([^"]*)" title on View Ideas$/) do |title|
find(:xpath, ".//div[@id='viewIdeasViewPort']/ul/li[div[h3[a[text()='#{@mainpage.getIdeaTitle(title)}']]]]/div[contains(@class,'closedIdea')]/span[@class='label']").click
sleep 1
fail(ArgumentError.new("No Closed Banner Popup was displayed.")) unless has_xpath?(".//body[@id='ViewIdeas']/div[@aria-describedby='closedIdeaInfoDialog' and contains(@style,'block;')]")
end
Then(/^I verify "([^"]*)" status title, "([^"]*)"'s image and title, and "([^"]*)" closure message are displayed on the Close Idea popup$/) do |status, title, reason|
within @viewideaspage.closeideainfopopup_container do
@viewideaspage.closed_idea_popup_status_label.text.should eq(status)
has_xpath?(".//a[contains(@class,'idea-image')]/img[not(@src='')]").should eq(true)
@viewideaspage.closed_idea_popup_title_label.text.should eq(@mainpage.getIdeaTitle(title))
@viewideaspage.closed_idea_popup_closure_reason_label.text.should eq(reason)
end
end
Then(/^I verify "([^"]*)" status title, "([^"]*)"'s image and title, Text Field: "([^"]*)", Checkbox Field: "([^"]*)" and Text Editor: "([^"]*)" are displayed on the Close Idea popup$/) do |status, title, text_field, checkbox, text_editor|
within @viewideaspage.closeideainfopopup_container do
@viewideaspage.closed_idea_popup_status_label.text.should eq(status)
has_xpath?(".//a[contains(@class,'idea-image')]/img[not(@src='')]").should eq(true)
@viewideaspage.closed_idea_popup_title_label.text.should eq(@mainpage.getIdeaTitle(title))
all(:xpath, ".//div[@class='userIdeaContent']").each do |container|
field = container.find(:xpath, ".//strong").text
case field
when 'Close Idea Text Field' then
container.find(:xpath, ".//p").text.should eq(text_field)
when 'Close Idea Checkbox Field' then
container.find(:xpath, ".//p").text.should eq(checkbox)
when 'Close Idea Text Editor' then
container.find(:xpath, ".//p").text.should eq(text_editor)
end
end
end
end
Then(/^I verify that Closed Idea popup banner is closed$/) do
fail(ArgumentError.new("Closed Banner Popup was not closed.")) unless has_no_xpath?(".//body[@id='ViewIdeas']/div[@aria-describedby='closedIdeaInfoDialog' and contains(@style,'block;')]")
end
Then(/^I verify that "([^"]*)" status title and "([^"]*)" closure message are displayed on View Idea page$/) do |status, reason|
@viewideapage.closed_idea_banner_status_label.text.should eq(status)
@viewideapage.closed_idea_banner_closure_reason_label.text.should eq(reason)
end
Then(/^I verify that Closed Idea banner is collapsed on View Idea page$/) do
@viewideapage.has_closed_idea_banner_status_label?.should eq(false)
@viewideapage.has_closed_idea_banner_closure_reason_label?.should eq(false)
end
Then(/^I verify that "([^"]*)" status title, Text Field: "([^"]*)", Checkbox Field: "([^"]*)" and Text Editor: "([^"]*)" values are displayed on View Idea page$/) do |status, text_field, checkbox, text_editor|
@viewideapage.closed_idea_banner_status_label.text.should eq(status)
all(:xpath, ".//div[@class='ugc']/div[@class='userIdeaContent']").each do |container|
field = container.find(:xpath, ".//strong").text
case field
when 'Close Idea Text Field' then
container.find(:xpath, ".//p").text.should eq(text_field)
when 'Close Idea Checkbox Field' then
container.find(:xpath, ".//p").text.should eq(checkbox)
when 'Close Idea Text Editor' then
container.find(:xpath, ".//p").text.should eq(text_editor)
end
end
end
And(/^I click on the message of "([^"]*)" user with "([^"]*)" content from "([^"]*)" idea$/) do |user, message, title|
fullname = "#{@users.getUser(user,'firstname')} #{@users.getUser(user,'lastname')}"
idea_title = @mainpage.getIdeaTitle(title)
sleep 2
find(:xpath, ".//ul[@id='conversationLists']/li/div[div[@class='media-heading' and b[text()='#{fullname}']] and div[div[text()='#{message}']]]").click
sleep 2
attempts = 3
scrolldowns = 3
flag = true
while attempts > 0 and flag do
page.execute_script("$('.messagesWrapper').scrollTop(0)")
while scrolldowns > 0 and flag do
begin
all(:xpath, ".//ul[@id='privateMessageLists']/li/div[p[a[text()='#{fullname}']] and p[text()='#{message}']]//div/b/a[text()='#{idea_title}']").last.click
flag = false
rescue
sleep 2
outerHeight = page.execute_script("return $('.messagesWrapper').outerHeight();")
# scrollHeight = page.execute_script("return $('.messagesWrapper').get(0).scrollHeight;")
# scrollTop = page.execute_script("return $('.messagesWrapper').scrollTop();")
page.execute_script("$('.messagesWrapper').scrollTop(#{outerHeight + 100})")
end
scrolldowns = scrolldowns - 1
end
attempts = attempts - 1
end
end
Then(/^I verify that "([^"]*)" status title and "([^"]*)" closure message are displayed on My Inbox page$/) do |status, reason|
@myinboxpage.closed_idea_banner_status_label.text.should eq(status)
@myinboxpage.closed_idea_banner_closure_reason_label.text.should eq(reason)
end
Then(/^I verify that Closed Idea banner is collapsed on My Inbox popup$/) do
@myinboxpage.has_closed_idea_banner_status_label?.should eq(false)
@myinboxpage.has_closed_idea_banner_closure_reason_label?.should eq(false)
end
Then(/^I verify that "([^"]*)" status title, Text Field: "([^"]*)", Checkbox Field: "([^"]*)" and Text Editor: "([^"]*)" values are displayed on My Inbox$/) do |status, text_field, checkbox, text_editor|
@myinboxpage.closed_idea_banner_status_label.text.should eq(status)
all(:xpath, ".//div[@class='ugc']/div[@class='userIdeaContent']").each do |container|
field = container.find(:xpath, ".//strong").text
case field
when 'Close Idea Text Field' then
container.find(:xpath, ".//p").text.should eq(text_field)
when 'Close Idea Checkbox Field' then
container.find(:xpath, ".//p").text.should eq(checkbox)
when 'Close Idea Text Editor' then
container.find(:xpath, ".//p").text.should eq(text_editor)
end
end
end
#TODO: Implement verification on fields (url=Idea/CloseIdea?ideaid=)
And(/^I verify "([^"]*)" custom field is displayed with "([^"]*)" value on the Close Idea page$/) do |arg1, arg2|
puts 'Not implemented...'
end |
module Vote
module Condorcet
module Schulze
class Classifications
def initialize(schulze_basic)
@schulze_basic = schulze_basic
end
# compute all possible solutions
# since this can take days, there is an option to limit the number of calculated classifications
# the default is 10. if the system is calculating more then 10 possible classifications it will stop
# raising a TooManyClassifications exception
# you can set it to false to disable the limit
def classifications(limit_results = false)
@classifications = []
@limit_results = limit_results
calculate_classifications
@classifications
end
# compute the final classification with ties included
# the result is an array of arrays. each position can contain one or more elements in tie
# e.g. [[0,1], [2,3], [4], [5]]
def classification_with_ties
result = []
result << @schulze_basic.potential_winners # add potential winners on first place
result += @schulze_basic.ties.clone.sort_by { |tie| -@schulze_basic.ranking[tie[0]] } # add ties by ranking
result.uniq! # remove duplicates (potential winners are also ties)
add_excludeds(result)
end
private
def add_excludeds(result)
excludeds = (@schulze_basic.candidates - result.flatten) # all remaining elements (not in tie, not winners)
excludeds.each do |excluded|
result.each_with_index do |position, index|
# insert before another element if they have a better ranking
break result.insert(index, [excluded]) if better_ranking?(excluded, position[0])
# insert at the end if it's the last possible position
break result.insert(-1, [excluded]) if index == result.size - 1
end
end
result
end
def better_ranking?(a, b)
@schulze_basic.ranking[a] > @schulze_basic.ranking[b]
end
def rank_element(el)
rank = 0
rank -= 100 if @schulze_basic.potential_winners.include?(el)
@schulze_basic.beat_couples.each do |b|
rank -= 1 if b[0] == el
end
rank
end
def calculate_classifications
start_list = (0..@schulze_basic.ranking.length - 1).to_a
start_list.sort! { |e1, e2| rank_element(e1) <=> rank_element(e2) }
compute_classifications([], @schulze_basic.potential_winners, @schulze_basic.beat_couples, start_list)
end
def compute_classifications(classif = [], potential_winners, beated_list, start_list)
return compute_permutations(classif, start_list) if beated_list.empty?
next_list = (classif.empty? && potential_winners.any?) ? potential_winners : start_list
add_elements(beated_list, classif, next_list, start_list)
end
def add_elements(beated_list, classif, potential_winners, start_list)
potential_winners.each { |element| add_element(classif, beated_list, start_list, element) }
end
def compute_permutations(classif, start_list)
start_list.permutation.each do |array|
@classifications << classif + array
check_limits
end
end
def check_limits
fail TooManyClassificationsException if @limit_results && @classifications.size > @limit_results
end
def add_element(classif, beated_list, start_list, element)
return if beated_list.any? { |c| c[1] == element }
classification = classif.clone << element
next_start_list = clone_and_delete(start_list, element)
if next_start_list.empty?
@classifications << classification
check_limits
else
compute_classifications(classification, nil,
beated_list.clone.delete_if { |c| c[0] == element }, next_start_list)
end
end
def clone_and_delete(list, element)
list.clone.tap { |l| l.delete(element) }
end
end
end
end
end
class TooManyClassificationsException < StandardError
end
|
require 'open-uri'
module TradeEvent
class DlData
include Importable
include ::VersionableResource
attr_accessor :reject_if_ends_before
ENDPOINT = 'http://www.state.gov/rss/channels/dl.xml'
XPATHS = {
event_name: './title',
description: './description',
url: './link',
}.freeze
def initialize(resource = ENDPOINT, options = {})
@resource = resource
self.reject_if_ends_before = options.fetch(:reject_if_ends_before, Date.current)
end
def import
doc = Nokogiri::XML(loaded_resource)
trade_events = doc.xpath('//item').map do |event_info|
process_event_info(event_info)
end.compact
Dl.index(trade_events)
end
private
def process_event_info(event_info)
event_hash = extract_fields(event_info, XPATHS)
event_hash[:source] = model_class.source[:code]
event_hash[:id] = Utils.generate_id(event_hash, %i(event_name description url id))
sanitize_entry(event_hash)
end
end
end
|
class WordAnalysis
def initialize (text)
@text = text
end
attr_reader :text
# I guess this isn't needed but I WROTE IT AND I'M LEAVING IT HERE
def word_number
text.split.size
end
def word_count
text.scan(/\w+/).inject(Hash.new(0)) { |h, c| h[c] += 1; h }
end
def letter_count
text.scan(/[a-zA-Z]/).inject(Hash.new(0)) { |h, c| h[c] += 1; h }
end
def symbol_number
text.scan(/[^a-zA-Z0-9 ]/).inject(Hash.new(0)) { |h, c| h[c] += 1; h }
end
def three_most_common_words
text_hash = word_count
text_hash.sort_by { |k, v| v }.reverse.take(3).to_h
end
def three_most_common_letters
text_hash = letter_count
text_hash.sort_by { |k, v| v }.reverse.take(3).to_h
end
end
|
require "exact_cover"
require "byebug"
ALPHABET = %w[a b c d e f g h i j k l m n o p q r s t u v w x y z .].freeze
DICTIONARY = File.read("wordlist.txt").split("\n").map(&:strip).map(&:downcase)
WORDS = (ALPHABET + DICTIONARY).uniq
W = 6 # cols
H = 5 # rows
def build_zeroes_array(size, one_index)
(0..size - 1).map do |i| i == one_index ? 1 : 0 end
end
def build_ones_array(size, zero_index)
(0..size - 1).map do |i| i == zero_index ? 0 : 1 end
end
Word = Struct.new(:word, :row, :col, :horizontal)
class CrosswordGenerator
attr_reader :solutions
attr_reader :matrix
attr_reader :matrix_row_to_word
attr_reader :constraints
def initialize(constraints = [])
@constraints = constraints
@matrix = []
@matrix_row_to_word = {}
WORDS.each do |word|
puts "adding #{word}"
word_index = WORDS.index(word)
# represent the word in the row
(0..H-1).each do |row|
(0..W-1).each do |col|
if word.size + col <= W
matrix_row = add_horizontal_word(word, row, col, word_index)
@matrix_row_to_word[matrix_row] = Word.new(word, row, col, true)
@matrix << matrix_row
end
if word.size + row <= H
matrix_row = add_vertical_word(word, row, col, word_index)
@matrix_row_to_word[matrix_row] = Word.new(word, row, col, false)
@matrix << matrix_row
end
end
end
end
add_constraints
end
def solutions(time_limit: nil)
ExactCover::CoverSolver.new(@matrix.shuffle, time_limit: 3).call
end
def format(solution)
grid = format_solution(solution)
print_grid(grid)
end
private
def add_constraints
puts "Starting with #{@matrix.size} rows"
(0..H-1).each do |row|
(0..W-1).each do |col|
letter = constraints[row][col]
index = (row * W + col) * ALPHABET.size
if letter == "?" # we don't want a black cell here
matrix_row_horizontal = build_zeroes_array(ALPHABET.size, ALPHABET.index("."))
matrix_row_vertical = build_ones_array(ALPHABET.size, ALPHABET.index("."))
@matrix = @matrix.select do |matrix_row|
keep = true
keep = false if matrix_row[index...index+ALPHABET.size] == matrix_row_horizontal
keep = false if matrix_row[index...index+ALPHABET.size] == matrix_row_vertical
keep
end
else # for this cell to be the given letter
next if letter == " "
zeroes = build_zeroes_array(ALPHABET.size, -1)
matrix_row_horizontal = build_zeroes_array(ALPHABET.size, ALPHABET.index(letter))
matrix_row_vertical = build_ones_array(ALPHABET.size, ALPHABET.index(letter))
# Remove all matrix entries that don't match either one of those !
@matrix = @matrix.select do |matrix_row|
keep = false
keep ||= true if matrix_row[index...index+ALPHABET.size] == zeroes
keep ||= true if matrix_row[index...index+ALPHABET.size] == matrix_row_horizontal
keep ||= true if matrix_row[index...index+ALPHABET.size] == matrix_row_vertical
keep
end
end
end
end
# (0..H-1).each do |row|
# (0..W-1).each do |col|
# next if constraints.include? [row, col]
#
# letter = "."
# index = (row * W + col) * ALPHABET.size
#
# # remove matrix rows that have a black square in this cell
# matrix_row_horizontal = build_zeroes_array(ALPHABET.size, ALPHABET.index(letter))
# matrix_row_vertical = build_ones_array(ALPHABET.size, ALPHABET.index(letter))
#
# @matrix = @matrix.select do |matrix_row|
# keep = true
# keep = false if matrix_row[index...index+ALPHABET.size] == matrix_row_horizontal
# keep = false if matrix_row[index...index+ALPHABET.size] == matrix_row_vertical
# keep
# end
# end
# end
puts "Reste #{@matrix.size} rows"
end
def print_grid(grid)
solution_str = ""
(0..H-1).each do |row|
row_str = ""
(0..W-1).each do |col|
row_str << grid[row][col] + " "
end
solution_str << row_str + "\n"
end
solution_str
end
def format_solution(solution)
grid = Array.new(H)
(0..H-1).each do |row|
grid[row] = Array.new(W, ".")
end
solution.each do |matrix_row|
word = @matrix_row_to_word[matrix_row]
# puts "word: #{word}"
next unless word
word.word.split("").each_with_index do |letter, idx|
next if letter == "."
if word.horizontal
col_index = word.col + idx
grid[word.row][col_index] = letter
else
row_index = word.row + idx
grid[row_index][word.col] = letter
end
end
end
grid
end
def add_horizontal_word(word, row, col, word_index, real: true)
# puts "Adding #{word} to #{row}, #{col}"
matrix_row = Array.new(2 * W * H * ALPHABET.size, 0)
offset = W * H * ALPHABET.size
offset_words = 2 * W * H * ALPHABET.size
word.split("").each_with_index do |letter, idx|
break if col + idx >= W
index = (row * W + col + idx) * ALPHABET.size
# horizontal part
matrix_row[index + ALPHABET.index(letter)] = 1
# vertical part
ALPHABET.each do |alphabet_letter|
if alphabet_letter != letter
matrix_row[offset + index + ALPHABET.index(alphabet_letter)] = 1
end
end
# add_vertical_word(letter, row, col + idx, word_index, real: false) if real
end
if word != "." && col + word.size < W
# add a X at the end of the word
index = (row * W + col + word.size) * ALPHABET.size
# horizontal part
matrix_row[index + ALPHABET.index(".")] = 1
# vertical part
ALPHABET.each do |alphabet_letter|
if alphabet_letter != "."
matrix_row[offset + index + ALPHABET.index(alphabet_letter)] = 1
end
end
end
matrix_row
end
def add_vertical_word(word, row, col, word_index, real: true)
# puts "Adding #{word} to #{row}, #{col}"
matrix_row = Array.new(2 * W * H * ALPHABET.size, 0)
offset = W * H * ALPHABET.size
offset_words = 2 * W * H * ALPHABET.size
word.split("").each_with_index do |letter, idx|
break if row + idx >= H
index = ((row + idx) * W + col) * ALPHABET.size
# horizontal part
ALPHABET.each do |alphabet_letter|
if alphabet_letter != letter
matrix_row[index + ALPHABET.index(alphabet_letter)] = 1
end
end
# vertical part
matrix_row[offset + index + ALPHABET.index(letter)] = 1
# add_horizontal_word(letter, row + idx, col, word_index, real: false) if real
end
if word != "." && row + word.size < H
# add a X at the end of the word
index = ((row + word.size) * W + col) * ALPHABET.size
# vertical part
matrix_row[offset + index + ALPHABET.index(".")] = 1
# horizontal part
ALPHABET.each do |alphabet_letter|
if alphabet_letter != "."
matrix_row[index + ALPHABET.index(alphabet_letter)] = 1
end
end
end
matrix_row
end
end
#
# num_black_square = (0.99 * W * H).round
# black_squares_positions =
# num_black_square.times.map do
# [rand(H), rand(W)]
# end
#
# black_squares_positions = []
# (0..W-1).each do |j|
# (0..H-1).each do |i|
# black_squares_positions << [i, j] unless rand(100) > 10
# end
# end
#
constraints = [
" n ",
"hacker",
" w ",
" s ",
" ",
].map { |s| s.split("") }
generator = CrosswordGenerator.new(constraints)
solutions = generator.solutions
solutions.each do |solution|
grid = generator.format solution
puts grid
puts "__"
end
puts "fini"
|
class Review < ActiveRecord::Base
belongs_to :product
belongs_to :reviewer, class_name: 'User'
end
|
Rails.application.routes.draw do
root 'movies#index'
get '/directors/(:director)/all_movies', to: 'movies#director_all_movies', as: 'director_all_movies'
resources :movies
end
|
Then(/^I type "([^"]*)" in search field$/) do |arg|
find_element(id: "search_src_text").send_keys(arg)
end
Then(/^I press on search icon$/) do
find_element(id: "action_search").click
end
And(/^I press return button on soft keyboard$/) do
Appium::TouchAction.new.tap(x:0.99 , y:0.99, count: 1).perform
end
Then(/^I see "([^"]*)" as a current unit converter$/) do |arg|
find_element(name: "#{arg}")
end
Then(/^Left Unit Picker value should be "([^"]*)"$/) do |left_unit|
element = find_element(name: "#{left_unit}").text
if element != left_unit
fail("Exepted left unit piker value is #{left_unit}, actual result #{element}")
end
end
And(/^Right Unit Picker value should be "([^"]*)"$/) do |right_unit|
element = find_element(name: "#{right_unit_unit}").text
if element != right_unit
fail("Exepted left unit piker value is #{right_unit}, actual result #{element}")
end
end
Then(/^I press on add to Favorits icon$/) do
find_element(id: "action_add_favorites").click
end
Then(/^I press on Favorit conversion$/) do
find_element(name: "Favorite conversions").click
end
And(/^I veryfy "([^"]*)" added to Favorit conversions list$/) do |arg|
find_element(name: "#{arg}")
end
Then(/^Show all button should be (disabled|enabled)$/) do |state|
button_state = find_element(id: "btn_show_all").enabled?
if state == "enabled"
puts fail("enabled")if button_state != true
elsif state == "disabled"
puts fail("disabled") if button_state !=false
end
end
Then(/^I should see result "([^"]*)"$/) do |result|
value = find_element(id: "target_value").text
if value != result
fail("expected value is #{result}, actual value is #{value}")
end
end
When(/^I type "([^"]*)" on application keybord$/) do |test|
digits = test.split("")
digits.each do |num|
find_element(xpath: "//android.widget.Button[@text ='#{num}']").click
end
end
Then(/^I select "([^"]*)" from menu$/) do |value|
text(value).click
end
Then(/^I select "([^"]*)" from right unit piker$/) do |value|
find_element(id: "select_unit_spinner").click
find_in_list(value)
end
Then(/^I select droup down menu$/) do
Appium::TouchAction.new.tap(x:1014 , y:345, count: 1).perform
end
Then(/^I select "([^"]*)" from left unit piker$/) do |value|
find_element(id: "select_unit_spinner_arrow").click
find_in_list(value)
end
|
module Pm
module ARExt
module PmModelAttr
def model_attr
[["IsWeb", true],
["base", "HtmlModel"],
["modelNamespace", namespaces.join(".")],
["controltypeNamespace", "AWatir"]].build_ordered_hash
end
def automan_class_name
name
end
end
module PmElementAttr
def method_attr
the_type = if self.sub_model?
model_type
else
automan_html_type(properties.html_type)
end
[["name", name],
["type", the_type],
["selector", properties.selector],
["collection", properties.collection],
["cache", "false"]].build_ordered_hash
end
def model_attr
if self.root?
[["type", self.pm_model.automan_class_name], ["Root", "true"]].build_ordered_hash
else
#assert !self.leaf?
[["type", model_type], ["Root", "false"]].build_ordered_hash
end
end
protected
def model_type
assert self.sub_model?
self.name.classify
end
def automan_html_type(html_type)
"AWatir::#{html_type}"
end
end
module PmModelExt
include Pm::ARExt::PmModelAttr
def included(base)
base.send :include, ActionController::UrlWriter
end
def xml_render
Pm::XmlRender.new(self)
end
def xml_file_name
"#{name}.xml"
end
def xml_file_url
pm_model_url(self, :format=>"xml")
end
end
end
end |
class Purchase < ActiveRecord::Base
attr_accessible :date_purchased, :price_total, :reference, :user_id, :status
has_many :purchase_items, dependent: :destroy
has_many :ipn_logs, dependent: :destroy
belongs_to :user
def download_items
purchase_items.select { |purchase_item| purchase_item.product.format == "Download" }
end
end
# == Schema Information
#
# Table name: purchases
#
# id :integer not null, primary key
# date_purchased :datetime
# reference :string(255)
# price_total :integer
# user_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
|
## Two Classes to Interface with the Yelp API
## Yelp Base Class.
class Yelp::Base
def initialize
end
## Authenticate from YAML file stored on "/config/api.yml"
def authenticate
api_config = YAML::load(File.read(Rails.root.to_s + "/config/api.yml"))
yelp = api_config['yelp']
consumer = OAuth::Consumer.new(yelp['consumer_key'], yelp['consumer_secret'], {:site => "http://api.yelp.com"})
OAuth::AccessToken.new(consumer, yelp['token'], yelp['token_secret'])
end
end
## Business Search From Yelp
class Yelp::BusinessSearch < Yelp::Base
attr_reader :url
def initialize(business_type, location, limit=nil)
@url = "/v2/search?term=#{URI.escape(business_type)}&#{URI.escape(location)}"
@url += "&limit=#{limit}" if limit
end
## Return a Hash of Popular Places. Limit each with 'limit' parameter
def self.popular_places(location, limit)
{
:restaurants => restaurants(location, limit),
:shopping => shopping(location, limit),
:bars_and_clubs => bars_and_clubs(location, limit),
:personal_services => personal_services(location, limit)
}
end
def self.restaurants(location, limit = nil)
new('restaurants', location, limit).results
end
def self.shopping(location, limit = nil)
new('shopping', location, limit).results
end
def self.bars_and_clubs(location, limit = nil)
new('bars and clubs', location, limit).results
end
def self.personal_services(location, limit = nil)
new('personal services', location, limit).results
end
## Get A Hash of Results From An API call to Yelp
def results
begin
access_token = authenticate
response = nil
## Issue an Exception If it is taking too long.
Timeout.timeout(3) {
response = access_token.get(self.url).body
}
json_response = ActiveSupport::JSON.decode(response)
if json_response['businesses'].present?
json_response['businesses'].map do |c|
{
:id => c['id'],
:name => c['name'],
:street => c['location']['address'].join(" "),
:city => c['location']['city'],
:state => c['location']['state_code'],
:phone => c['phone'],
:rating => c['rating'],
:rating_img => c['rating_img_url'],
:url => c['url'],
:review_count => c['review_count']
}
end
else
puts response
return []
end
rescue Timeout::Error => e
puts e.message
return []
rescue => e
puts e.message
return []
end
end
end |
class AddCorrectAndIncorrectAnswersToBirds < ActiveRecord::Migration[5.1]
def change
change_table :birds do |t|
t.integer :correct_answers
t.integer :incorrect_answers
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.