text stringlengths 10 2.61M |
|---|
class Api::CardsController < Api::BaseController
before_action :authenticate_user
def index
@cards = current_user.cards
respond_with(@cards)
end
def create
card_params = {
first_name: params['card_fields']['firstName'],
last_name: params['card_fields']['lastName'],
email: params['card_fields']['emailAddress'],
phone_number: params['card_fields']['phoneNumber'],
headline: params['card_fields']['headline'],
image: params['card_fields']['pictureUrl'],
user_id: params['user_id'].to_i,
specific_location: params['card_fields']['location']['name'],
country: params['card_fields']['location']['country']['code'],
company: params['card_fields']['positions']['values'][0]['company']['name'],
title: params['card_fields']['positions']['values'][0]['title'],
skills: params['card_fields']['positions']['values'][0]['summary']
}
card = Card.new(card_params)
if card.save!
render nothing: true, status: 200
else
render nothing: true, status: 500
end
end
end
|
require 'spec_helper'
describe ::LogfmtMarshalling::Marshaller do
it 'serializes an empty hash' do
actual = marshal({})
expect(actual).to eq('')
end
it 'serializes an empty string' do
actual = marshal 'key' => ''
expect(actual).to eq('key=""')
end
it 'serializes a whitespace string' do
actual = marshal 'key' => ' '
expect(actual).to eq('key=" "')
end
it 'drops the TrueClass instance value' do
actual = marshal 'key' => true
expect(actual).to eq('key')
end
it "serializes the FalseClass instance value" do
actual = marshal 'key' => false
expect(actual).to eq('key=false')
end
it 'serializes a quoted true as a string' do
actual = marshal 'key' => 'true'
expect(actual).to eq('key="true"')
end
it 'serializes a quoted false as a string' do
actual = marshal 'key' => 'false'
expect(actual).to eq('key="false"')
end
it 'serializes a single key-value pair' do
actual = marshal 'key' => 'value'
expect(actual).to eq('key=value')
end
it 'serializes multiple key-value pairs' do
actual = marshal 'key1' => true, 'key2' => true
expect(actual).to eq('key1 key2')
end
it 'preserves order of serialized pairs' do
actual = marshal 'key1' => 'value1', 'key2' => 'value2'
expect(actual).to eq('key1=value1 key2=value2')
end
it 'serializes mixed single/non-single pairs' do
actual = marshal 'key1' => 'value1', 'key2' => true
expect(actual).to eq('key1=value1 key2')
end
it 'preserves order of mixed single/non-single pairs' do
actual = marshal 'key1' => true, 'key2' => 'value2'
expect(actual).to eq('key1 key2=value2')
end
it 'quotes values with whitespaces' do
actual = marshal 'key' => 'a value'
expect(actual).to eq('key="a value"')
end
it 'serializes escaped quote value ' do
actual = marshal 'key' => 'quoted \" value', 'r' => 'esc\\t'
expect(actual).to eq('key="quoted \" value" r="esc\t"')
end
it 'serializes mixed pairs' do
actual = marshal 'key1' => 'quoted \" value', 'key2' => true, 'key3' => 'value3'
expect(actual).to eq('key1="quoted \" value" key2 key3=value3')
end
it 'serializes mixed characters pairs' do
actual = marshal 'foo' => 'bar',
'a' => 14,
'baz' => 'hello kitty',
'ƒ' => '2h3s',
'cool%story' => 'bro',
'f' => true,
'%^asdf' => true
expect(actual).to eq('foo=bar a=14 baz="hello kitty" ƒ=2h3s cool%story=bro f %^asdf')
end
it 'serializes Ruby Symbol objects as Strings' do
actual = marshal key: :value
expect(actual).to eq('key=value')
end
it 'serializes a positive integer' do
actual = marshal 'key' => 234
expect(actual).to eq('key=234')
end
it 'serializes a negative integer' do
actual = marshal 'key' => -3428
expect(actual).to eq('key=-3428')
end
it 'serializes a bignum' do
bignum = 9999999999999999999
expect(bignum).to be_a(Bignum)
actual = marshal 'key' => bignum
expect(actual).to eq('key=9999999999999999999')
end
it 'serializes a positive float' do
actual = marshal 'key' => 3.14
expect(actual).to eq('key=3.14')
end
it 'serializes a negative float' do
actual = marshal 'key' => -0.9934
expect(actual).to eq('key=-0.9934')
end
it 'serializes an exponential float' do
actual = marshal 'key' => 2.342342342342344e+18
expect(actual).to eq('key=2.342342342342344e+18')
end
%w(
0
1
-1
123.4
-3.14
1.0e6
1.2e-3
4E20
4e+20
).each do |quoted_float|
it %{serializes a quoted number ("#{quoted_float}") as a string} do
actual = marshal 'key' => quoted_float
expect(actual).to eq(%{key="#{quoted_float}"})
end
end
def marshal(data)
described_class.new.marshal data
end
end
|
module Sentry
module Rails
module ActiveJobExtensions
def perform_now
if !Sentry.initialized? || already_supported_by_sentry_integration?
super
else
SentryReporter.record(self) do
super
end
end
end
def already_supported_by_sentry_integration?
Sentry.configuration.rails.skippable_job_adapters.include?(self.class.queue_adapter.class.to_s)
end
class SentryReporter
OP_NAME = "queue.active_job".freeze
class << self
def record(job, &block)
Sentry.with_scope do |scope|
begin
scope.set_transaction_name(job.class.name, source: :task)
transaction =
if job.is_a?(::Sentry::SendEventJob)
nil
else
Sentry.start_transaction(name: scope.transaction_name, source: scope.transaction_source, op: OP_NAME)
end
scope.set_span(transaction) if transaction
yield.tap do
finish_sentry_transaction(transaction, 200)
end
rescue Exception => e # rubocop:disable Lint/RescueException
finish_sentry_transaction(transaction, 500)
Sentry::Rails.capture_exception(
e,
extra: sentry_context(job),
tags: {
job_id: job.job_id,
provider_job_id: job.provider_job_id
}
)
raise
end
end
end
def finish_sentry_transaction(transaction, status)
return unless transaction
transaction.set_http_status(status)
transaction.finish
end
def sentry_context(job)
{
active_job: job.class.name,
arguments: sentry_serialize_arguments(job.arguments),
scheduled_at: job.scheduled_at,
job_id: job.job_id,
provider_job_id: job.provider_job_id,
locale: job.locale
}
end
def sentry_serialize_arguments(argument)
case argument
when Hash
argument.transform_values { |v| sentry_serialize_arguments(v) }
when Array, Enumerable
argument.map { |v| sentry_serialize_arguments(v) }
when ->(v) { v.respond_to?(:to_global_id) }
argument.to_global_id.to_s rescue argument
else
argument
end
end
end
end
end
end
end
|
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
add_flash_types :success, :danger, :info, :warning, :primary, :secondary
protected
def find_doctor?
current_user.doctor?
end
def find_patient?
current_user.patient?
end
def correct_user
unless find_patient?
flash[:notice] = 'Страница не доступна'
redirect_to home_path
end
end
def correct_expert
unless find_doctor?
flash[:notice] = 'Страница не доступна'
redirect_to home_path
end
end
def find_owner
unless current_user.expert == Expert.find(params[:expert_id])
flash[:notice] = 'Страница не доступна'
redirect_to home_path
end
end
end
|
users = [
{ name: "satou", age: 22 },
{ name: "yamada", age: 12 },
{ name: "takahashi", age: 32 },
{ name: "nakamura", age: 41 }
]
# 以下に回答を記載
users.each do |user|
puts "私の名前は#{user[:name]}です。年齢は#{user[:age]}歳です"
end
data1 = { name: "saitou", hobby: "soccer", age: 33, role: "admin" }
data2 = { name: "yamada", hobby: "baseball", role: "normal" }
if data1.key?(:age)
puts "OK"
else
puts "NG"
end
if data2.key?(:age)
puts "OK"
else
puts "NG"
end
puts data1.key?(:age) ? "OK" : "NG"
puts data2.key?(:age) ? "OK" : "NG"
class ClassName
def test
puts "インスタンスできてるよ"
end
end
def aaa
new_test = ClassName.new
new_test.test
end
class Car
def initialize(carname)
@name = carname
end
def dispName
print(@name, "¥n")
end
end
car1 = Car.new("crown")
car1.dispName
car2 = Car.new("civic")
car2.dispName
class UserQ17
# 以下に回答を記載
def initialize(profile)
@profile = profile
end
def info
puts "名前;#{@profile[:name]}"
puts "年齢:#{@profile[:age]}"
puts "性別:#{@profile[:gender]}"
end
end
def q17
# ここは変更しないで下さい(ユーザー情報は変更していただいてOKです)
user1 = UserQ17.new(name: "神里", age: 32, gender: "男")
user2 = UserQ17.new(name: "あじー", age: 32, gender: "男")
user1.info
puts "-------------"
user2.info
end
class UserQ18
# 以下に回答を記載
def initialize(profile)
@profile = profile
end
def introduce
if 20 < @profile[:age]
"こんにちは,#{@profile[:name]}と申します。宜しくお願いいたします。"
else
"はいさいまいど〜,#{@profile[:name]}です!!!"
end
end
def q18
# ここは変更しないで下さい
user1 = UserQ18.new(name: "あじー", age: 32)
user2 = UserQ18.new(name: "ゆたぼん", age: 10)
puts user1.introduce
puts user2.introduce
end
end |
class InfosController < ApplicationController
def upload
return unless info_params[:file].present?
@info = Info.new(name: info_params[:file].original_filename)
@info.file.attach(info_params[:file])
if @info.save
path = @info.file_path
filename = @info.name
ImportProductsWorker.perform_async(path, filename)
redirect_to root_path, notice: 'All Data have been uploaded!'
else
flash[:success] = "File was rejected!"
redirect_to :back
end
end
private
def info_params
params.permit(:file)
end
end |
class Contents::Banner < Content
self.association_type = :has_many
has_file :image, styles: { medium: "300x300>", thumb: "100x100>", large: '600x600>' },
default_url: "/images/:style/missing.png"
register do |subclass|
subclass.attribute :title, String
subclass.attribute :visible, Axiom::Types::Boolean, default: true
end
end
|
# coding: utf-8
#!/usr/bin/env ruby
# Задание:
# 1. Реализовать Ruby скрипт, который будет преобразовывать входящую
# строку следующим образом: строка - латинские буквы, каждая буква
# замещается другой линейным сдвигом по алфавиту. Размер сдвига - один из
# входящих параметров. Например: ace, 1 -> bdf.
# Задание расширено следующим функционалом:
# 1. Если буква была строчной, то строчной она и остается. С заглавной так же.
# 2. Нельзя сдвигать: специальные символы и числа. Т.е они остаются в исходном виде.
# 3. Программа разделяется на 2 этапа: ввод строки для преобразования и величины сдвига. Каждый из этих этапов зациклен (пока пользователь не введет корректные данные).
# 4. Величина сдвига может быть как положительной, так и отрицательной.
# 5. Предусмотрена возможность кругового сдвига (z, 1 -> a)
# Контроль входных данных:
# 1. Нельзя вводить пустые строки
# 2. В качестве величины сдвига нельзя выбрать вещественное число, букву, спец. символ или пустую строку.
# Проверка на существование аргументов, которые, по условиям задачи, не должны влиять на работу программы
if ARGV.count != 0
print "Введенные Вами аргументы:"
ARGV.each do|a|
print " #{a},"
end
puts " не используются в данной программе"
end
# Бесконечный цикл, который может прервать только корректный ввод данных
loop do
puts "Введите строку для сдвига: "
# Переменная @text объявлена как переменная экземпляра
@text = STDIN.gets.chomp
# Если введенный текст не является пустой строкой, то выходим из цикла
unless @text.empty?
break
# В противном случае выводим сообщение об ошибке
else
puts "Введена пустая строка"
end
end
# Бесконечный цикл, который может прервать только корректный ввод данных
loop do
puts "Величина сдвига: "
# Возможная ошибка, которая появится при парсинге целочисленного значения будет будет перехвачена с помощью rescue.
space = Integer(STDIN.gets) rescue nil
# В случае успешного парсинга
unless space.nil?
print "Ответ: "
# Вычисление величины сдвига, которая бы не превышала длины алфавита
space = space >= 0 ? space % 26 : -(-space % 26)
# Побитово осуществляем анализ входной строки
@text.each_byte do |i|
# Если текущий симол является буквой, то осуществляем сдвиг. В противном случае оставляем всё как есть.
# Функция Fixnum#chr преобразует любое число в ASCII
unless (/[A-Za-z]/.match i.chr).nil?
# Если после сдвига буква не остается буквой
unless (i.chr.upcase.ord+space).between?('A'.ord, 'Z'.ord)
# Случай, когда осуществляется сдвиг в прямом направлении
if space >= 0
print ((i.chr == i.chr.upcase ? 'A'.ord : 'a'.ord) - ('Z'.ord - i.chr.upcase.ord - space + 1)).chr
# Случай, когда осуществляется сдвиг в обратном направлении
else
print ((i.chr == i.chr.upcase ? 'Z'.ord : 'z'.ord) + (i.chr.upcase.ord - 'A'.ord + space + 1)).chr
end
# Если после сдвига буква остается буквой
else
print (i+space).chr
end
else
print i.chr
end
end
break
end
end
|
class AuthorController < ApplicationController
def show
@id = params[:id]
@user = User.find(@id)
@city = @user.city
end
end
|
class CashRegister
attr_accessor :total, :items, :discount, :last_transaction
def initialize(discount = 0)
@total = 0
@discount = discount
@items = []
@last_transaction = []
end
def add_item(title, price, quantity=1)
self.total += (price*quantity)
self.items.fill(title, self.items.size, quantity)
self.last_transaction << self.total
end
def apply_discount
if self.discount != 0
self.total -= self.total*self.discount/100
"After the discount, the total comes to $#{self.total}."
else
"There is no discount to apply."
end
end
def void_last_transaction
self.total -= self.last_transaction.pop
end
end
|
require_relative 'lib_helper'
class Robot
MAX_WEIGHT = 250
MAX_HEALTH = 100
DEFAULT_ATTACK = 5
ROBOT_RANGE = 1
MAX_SHIELD_POINTS = 50
attr_reader :position
attr_reader :health
attr_reader :items
attr_reader :shield_points
attr_accessor :equipped_weapon
@@robots = []
def initialize
@position = [0, 0]
@items = []
@items_weight = 0
@health = MAX_HEALTH
@shield_points = MAX_SHIELD_POINTS
@@robots << self
end
def move_left
@position[0] -= 1
end
def move_right
@position[0] += 1
end
def move_up
@position[1] += 1
end
def move_down
@position[1] -= 1
end
def pick_up(item)
item.feed(self) if item.instance_of?(BoxOfBolts) && health <= 80
unless reached_capacity?(item)
self.equipped_weapon = item if item.kind_of? Weapon
@items.push(item)
end
end
def items_weight
items.reduce(0) { |sum, item| sum + item.weight}
end
def recharge_shield(shield_boost)
@shield_points += shield_boost
@shield_points = MAX_SHIELD_POINTS if shield_points > MAX_SHIELD_POINTS
end
def wound(damage)
if shield_points > 0
@shield_points -= damage
else
@health -= damage
end
if shield_points < 0
@health += shield_points
@shield_points = 0
end
@health = 0 if health <= 0
end
def heal(health_boost)
heal!
@health += health_boost
@health = MAX_HEALTH if health > MAX_HEALTH
end
def heal!
raise RobotAlreadyDeadError, "Dead robots cannot heal." if health == 0
end
def attack(enemy)
attack!(enemy)
if enemy_in_range?(enemy)
if equipped_weapon
equipped_weapon.hit(enemy)
else
enemy.wound(DEFAULT_ATTACK)
end
if equipped_weapon.instance_of?(Grenade)
unequip_weapon
end
end
end
def attack!(enemy)
raise UnattackableEnemy, "Robot can attack other robots only, no other target can be attacked by a robot." unless enemy.instance_of?(Robot)
end
def self.robot_tracker
@@robots
end
def self.in_position(x, y)
@@robots.select { |robot| robot.position == [x, y] }
end
private
def reached_capacity?(item)
items_weight + item.weight > MAX_WEIGHT
end
def enemy_in_range?(enemy)
if equipped_weapon
x_coordinates_range = (position[0]-equipped_weapon.range..position[0]+equipped_weapon.range)
y_coordinates_range = (position[1]-equipped_weapon.range..position[1]+equipped_weapon.range)
else
x_coordinates_range = (position[0]-1..position[0]+1)
y_coordinates_range = (position[1]-1..position[1]+1)
end
if x_coordinates_range.include?(enemy.position[0]) && y_coordinates_range.include?(enemy.position[1])
true
else
false
end
end
def unequip_weapon
@items.delete_at(@items.index(equipped_weapon))
self.equipped_weapon = nil
end
end |
require_relative '../parser.rb'
require 'spec_helper.rb'
describe Parser do
before :all do
@parser = Parser.new
end
describe '.do_program' do
it 'should understand a whole program' do
output = capture_stdout do
@parser.do_program %(
REM *** THIRD PROGRAM - FIBONACCI 20 ***
REM
A = 1
B = 1
PRINT "1, 1, ";
666 FOR X = 1 TO 20
C = B
B = B + A
A = C
PRINT B;", ";
IF X % 10 = 0 THEN PRINT
NEXT
END
)
end
expect(output).to eq "1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, \n" \
"233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, \n"
end
end
describe 'GOTO' do
it 'should be obeyed' do
output = capture_stdout do
@parser.do_program %(
10 PRINT "LINE 10"
20 GOTO 40
25 END
30 PRINT "LINE 30"
40 PRINT "LINE 40"
50 GOTO 25
60 PRINT "LINE 60"
)
end
expect(output).to eq "LINE 10\nLINE 40\n"
end
end
describe 'READ' do
it 'should work' do
output = capture_stdout do
@parser.do_program %(
FOR I = 1 TO 10
READ J
PRINT J;", ";
476 NEXT
PRINT
DATA 10, 20, 30, 35, 40
DATA 50, 55, 60, 70, 80
PRINT "PAST DATA"
)
end
expect(output).to eq \
"10, 20, 30, 35, 40, 50, 55, 60, 70, 80, \nPAST DATA\n"
end
end
describe 'RESTORE' do
it 'should work' do
output = capture_stdout do
@parser.do_program %(
FOR I = 1 TO 5
READ J
PRINT J;", ";
NEXT
123 PRINT
RESTORE
FOR I = 1 TO 5
READ J
PRINT J;", ";
NEXT
PRINT
DATA 10, 20, 30, 35, 40
PRINT "PAST DATA"
)
end
expect(output).to eq \
"10, 20, 30, 35, 40, \n10, 20, 30, 35, 40, \nPAST DATA\n"
end
end
describe 'GOSUB' do
it 'should work as GOTO' do
output = capture_stdout do
@parser.do_program %(
10 PRINT "LINE 10"
20 GOSUB 40
30 PRINT "LINE 30"
40 PRINT "LINE 40"
)
end
expect(output).to eq "LINE 10\nLINE 40\n"
end
end
describe 'RETURN' do
it 'should work to return from GOSUB' do
output = capture_stdout do
@parser.do_program %(
10 PRINT "LINE 10"
20 GOSUB 40
30 PRINT "LINE 30"
35 END
40 PRINT "LINE 40"
50 RETURN
)
end
expect(output).to eq "LINE 10\nLINE 40\nLINE 30\n"
end
end
end
|
namespace :db do
desc 'Fill database with sample data'
task populate: :environment do
puts 'Iniciando tarefa.'
medir_tempo('Popular usuarios predefinidos') { popular_usuarios_predefinidos }
medir_tempo('Popular outros usuarios') { popular_outros_usuarios }
medir_tempo('Popular microposts') { popular_microposts }
medir_tempo('Popular relationships') { popular_relationships }
puts 'Tarefa finalizada com sucesso.'
end
end
def popular_usuarios_predefinidos
puts '-- Criando user Paulo Celio Junior.'
User.create!(name: 'Paulo Célio Júnior',
email: 'pauloceliojr@gmail.com',
password: '123456',
password_confirmation: '123456',
admin: true)
puts '-- User Paulo Celio Junior criado.'
puts '-- Criando user Example User.'
User.create!(name: 'Example User',
email: 'example@railstutorial.org',
password: '123456',
password_confirmation: '123456',
admin: true)
puts '-- User Example User criado.'
end
def popular_outros_usuarios
puts '-- Criando outros usuarios.'
99.times do |n|
name = Faker::Name.name
email = "example-#{n+1}@railstutorial.org"
password = '123456'
User.create!(name: name,
email: email,
password: password,
password_confirmation: password)
end
puts '-- Outros usuarios criados.'
end
def popular_microposts
puts '-- Criando microposts.'
users = User.limit(7)
50.times do
content = Faker::Lorem.sentence(5)
users.each { |user| user.microposts.create!(content: content) }
end
puts '-- Microposts.'
end
def popular_relationships
puts '-- Criando relationships.'
users = User.all
user = users.first
followed_users = users[2..50]
followers = users[3..50]
followed_users.each { |followed| user.follow!(followed)}
followers.each { |follower| follower.follow!(user) }
puts '-- Relationships criados.'
end
def medir_tempo(nome_etapa="Nao identificada")
puts "- Etapa '#{nome_etapa}' iniciada."
inicio = Time.now
yield
puts "- Etapa '#{nome_etapa}' completada em #{Time.now - inicio} segundos."
end |
$: << 'cf_spec'
require 'cf_spec_helper'
describe 'CF PHP Buildpack' do
let(:browser) { Machete::Browser.new(@app) }
before(:context) do
@app = Machete.deploy_app(
'composer_with_multiple_versions',
{env: {'COMPOSER_GITHUB_OAUTH_TOKEN' => ENV['COMPOSER_GITHUB_OAUTH_TOKEN']}}
)
end
after(:context) do
Machete::CF::DeleteApp.new.execute(@app)
end
it 'expects an app to be running' do
expect(@app).to be_running
end
it 'installs the version of PHP defined in `composer.json`' do
expect(@app).to have_logged 'Installing PHP'
expect(@app).to have_logged 'PHP 5.5'
end
it 'does not install the PHP version defined in `options.json`' do
expect(@app).to_not have_logged 'PHP 5.6'
end
it 'displays a useful warning message that `composer.json` is being used over `options.json`' do
expect(@app).to have_logged 'WARNING: A version of PHP has been specified in both `composer.json` and `./bp-config/options.json`.'
expect(@app).to have_logged 'WARNING: The version defined in `composer.json` will be used.'
end
end
|
# frozen_string_literal: true
class Parent < SitePrism::Section
element :slow_section_element, 'a.slow'
element :removing_section_element, '.removing-element'
section :child_section, Child, '.child-div'
end
|
@lists.each do |list|
json.set! list.id do
json.extract! list, :id, :title
json.cardIds list.cards.order('ord').ids
end
end
|
class PatientsController < ApplicationController
def index
patients = Patient.all
render json: patients, include: [:appointments]
end
def show
patient = Patient.find_by(id: params[:id])
render json: patient, include: [:appointments]
end
def create
patient = Patient.new(user_params)
if patient.save
render json: patient
else
render json: {error: "We are finding difficulty saving the Patient, please check your information."}, status: 420
end
end
private
def user_params
params.require(:patient).permit!
end
end
|
class CreateResponses < ActiveRecord::Migration
def change
create_table :responses
end
end
|
module ActionView::Helpers::DateHelper
def distance_of_time_in_words(from_time, to_time = 0, include_seconds = false)
from_time = from_time.to_time if from_time.respond_to?(:to_time)
to_time = to_time.to_time if to_time.respond_to?(:to_time)
distance_in_minutes = (((to_time - from_time).abs)/60).round
distance_in_seconds = ((to_time - from_time).abs).round
case distance_in_minutes
when 0..1
return (distance_in_minutes==0) ? _('less than a minute') : _('%d minute', 1) unless include_seconds
case distance_in_seconds
when 0..5 then _('less than %d seconds', 5)
when 6..10 then _('less than %d seconds', 10)
when 11..20 then _('less than %d seconds', 20)
when 21..40 then _('half a minute')
when 41..59 then _('less than a minute')
else _('%d minute',1)
end
when 2..45 then _("%d minute", distance_in_minutes)
when 46..90 then _('about %d hour', 1)
when 90..1440 then _("about %d hour", (distance_in_minutes.to_f / 60.0).round)
when 1441..2880 then _('%d day', 1)
when 2880..43199 then _('%d days', (distance_in_minutes / 1440).round)
when 43200..86399 then _('about 1 month')
when 86400..525599 then _('%d month', (distance_in_minutes / 43200).round)
when 525600..1051199 then _('about 1 year')
else _("over %d years", (distance_in_minutes / 525600).round)
end
end
end
|
module CrossedWires
Point = Struct.new(:x, :y) do
def <=>(other)
x_comparison = x <=> other.x
return x_comparison unless x_comparison.zero?
y <=> other.y
end
def distance(other)
(x - other.x).abs + (y - other.y).abs
end
end
end
|
class CitizensController < ApplicationController
def index
@citizens = Citizen.all
end
def show
@citizen = Citizen.find(params[:id])
end
end
|
#
# Copyright 2009 Huygens Instituut for the History of the Netherlands, Den Haag, The Netherlands.
#
# This file is part of New Women Writers.
#
# New Women Writers is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# New Women Writers is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with New Women Writers. If not, see <http://www.gnu.org/licenses/>.
#
begin
require 'base64'
rescue LoadError
end
module ActiveSupport
if defined? ::Base64
Base64 = ::Base64
else
# Base64 provides utility methods for encoding and de-coding binary data
# using a base 64 representation. A base 64 representation of binary data
# consists entirely of printable US-ASCII characters. The Base64 module
# is included in Ruby 1.8, but has been removed in Ruby 1.9.
module Base64
# Encodes a string to its base 64 representation. Each 60 characters of
# output is separated by a newline character.
#
# ActiveSupport::Base64.encode64("Original unencoded string")
# # => "T3JpZ2luYWwgdW5lbmNvZGVkIHN0cmluZw==\n"
def self.encode64(data)
[data].pack("m")
end
# Decodes a base 64 encoded string to its original representation.
#
# ActiveSupport::Base64.decode64("T3JpZ2luYWwgdW5lbmNvZGVkIHN0cmluZw==")
# # => "Original unencoded string"
def self.decode64(data)
data.unpack("m").first
end
end
end
end
|
class Address < ApplicationRecord
belongs_to :addressable, polymorphic: true
# When an address is initially created, it may not have a kommun or region assigned,
# for example when an admin creates a company but doesn't have all of the info for the main address.
belongs_to :region, optional: true
belongs_to :kommun, optional: true
validates_presence_of :addressable
validates_presence_of :country
scope :has_region, -> { where('region_id IS NOT NULL') }
scope :lacking_region, -> { where('region_id IS NULL') }
geocoded_by :entire_address
after_validation :geocode_best_possible,
:if => lambda { |obj| obj.changed? }
# geocode all of the addresses that need it
#
# sleep_between = number of seconds to sleep between each geocode call so
# that we don't go over the # requests per second of the service (ex Google)
# num_per_batch = the number to fetch from the db per batch
#
def self.geocode_all_needed(sleep_between: 0.5, num_per_batch: 50)
need_geocoding = self.not_geocoded # this method comes from Geocoder
Geocoder.configure(timeout: 20) # geocoding service timeout (secs).
# need this long to ensure we don't timeout
need_geocoding.find_each(batch_size: num_per_batch) do |addr|
addr.geocode_best_possible
addr.save
sleep(sleep_between.to_f)
end
end
def address_array
# This should only be called for address associated with a company
# Returns an array of address field values (strings) that starts with
# with address_visibility level set for the associated company.
visibility_level = addressable.address_visibility
address_pattern = %w(street_address post_code city kommun)
pattern_length = address_pattern.length
start_index = address_pattern.find_index do |field|
field == visibility_level
end
return [] unless start_index
if kommun
ary = [street_address, post_code, city, kommun.name,
sverige_if_nil][start_index..pattern_length]
else
ary = [street_address, post_code, city,
sverige_if_nil][start_index..(pattern_length-1)]
end
ary.delete_if { |f| f.blank? }
end
def entire_address
address_array.compact.join(', ')
end
# Geocode the address, starting with all of the data.
# If we don't get a geocoded result, then keep trying,
# using less and less 'specific' address information
# until we can get a latitude, longitude returned from geocoding.
# This will handle addresses that aren't correct (ex: generated with FFaker or possibly entered wrong)
# and so will guarantee that at least *some* map can be displayed. (Important for a company!)
def geocode_best_possible
return unless addressable_type == 'Company'
specificity_order = address_array
most_specific = 0
least_specific = specificity_order.size - 1
geo_result = nil
until most_specific > least_specific || geo_result.present?
geocode_address = specificity_order[most_specific..least_specific].compact.join(', ')
geo_result = Geocoder.coordinates(geocode_address)
most_specific += 1
end
unless geo_result.nil?
self.latitude = geo_result.first
self.longitude = geo_result.last
end
end
private
def sverige_if_nil
country = 'Sverige' if country.nil?
country
end
end
|
describe EnginesController do
it "should list all available engines" do
visit root_path
page.should have_link 'EACUSR'
page.should have_link 'EACTHEME'
end
end |
class ChangeStagingFlagDataTypeToLocmsrts < ActiveRecord::Migration[5.1]
def change
change_column :locmsrts, :staging_flag, :string
end
end
|
# Read about factories at http://github.com/thoughtbot/factory_girl
FactoryGirl.define do
factory :employee do
company {|c| c.association(:company) }
user {|c| c.association(:user) }
title "MyString"
status "MyString"
end
end |
module Pod
module X
module PodsDSL
def pod(name = nil, *requirements)
unless name
raise StandardError, 'A development requires a name.'
end
pod = Hash::new(nil)
pod[:name] = name
pod[:share] = true
options = requirements.last
if options && options.is_a?(Hash)
pod = pod.merge(options.dup)
end
@pods[name] = pod
end
end
module SourcesDSL
def source(domain, *requirements)
@current_domain = domain
options = requirements.last
if options && options.is_a?(Hash) && options[:group]
@current_group = options[:group]
end
yield if block_given?
ensure
@current_domain = nil
@current_group = nil
end
def pod(name = nil, *requirements)
unless name
raise StandardError, 'A development requires a name.'
end
return if @current_domain.nil?
source = Hash::new(nil)
source[:domain] = @current_domain
source[:git] = name + '.git'
source[:name] = name
if @current_group
source[:group] = @current_group
else
source[:group] = name
end
options = requirements.last
if options && options.is_a?(Hash)
source = source.merge(options.dup)
end
@sources[name] = source
end
end
module BuilderDSL
def build url
contents = File.exist?(url) ? File.open(url, 'r:utf-8', &:read) : nil
# Work around for Rubinius incomplete encoding in 1.9 mode
if !contents.nil? && contents.respond_to?(:encoding) && contents.encoding.name != 'UTF-8'
contents.encode!('UTF-8')
end
if !contents.nil? && contents.tr!('“”‘’‛', %(""'''))
# Changes have been made
CoreUI.warn "Smart quotes were detected and ignored in your #{File.basename(url)}. " \
'To avoid issues in the future, you should not use ' \
'TextEdit for editing it. If you are not using TextEdit, ' \
'you should turn off smart quotes in your editor of choice.'
end
unless contents.nil?
begin
eval(contents, nil, url.to_s)
rescue Exception => e
message = "Invalid `#{File.basename(url)}` file: #{e.message}"
raise DSLError.new(message, url, e, contents)
end
end
end
end
end
end
|
require 'spec_helper'
describe User do
context 'validations' do
it "requires a valid first name" do
user = FactoryGirl.build(:user, first_name: nil)
expect(user).to_not be_valid
expect(user.errors[:first_name]).to include "can't be blank"
end
it "requires a valid username" do
user = FactoryGirl.build(:user, user_name: nil)
expect(user).to_not be_valid
expect(user.errors[:user_name]).to include "can't be blank"
end
end
end
|
require 'openssl'
class SearsRegistration < ActiveRecord::Base
belongs_to :user
validates_uniqueness_of :auth_email
after_update :send_temporary_password
def authenticate(password)
(valid_temporary_password? && password == temporary_password) ||
crypted_password == Util.encrypt(password, salt)
end
def to_new_user(cobrand = Cobrand["mysears"])
user = User.new
[:first_name, :last_name, :country, :address_line_1, :address_line_2,
:city, :state, :zip_code, :salt, :crypted_password, :first_name,
:temporary_password, :temporary_password_expiration, :email_opt_in
].each { |field| user.send "#{field}=", self.send(field) }
user.email = auth_email
user.cobrand = cobrand
user
end
def self.find_by_auth_email_and_nil_user_id(email)
SearsRegistration.first :conditions => ['auth_email = ? AND user_id IS NULL', email]
end
def self.find_all_by_auth_email_and_nil_user_id(email)
SearsRegistration.find :all, :conditions => ['auth_email = ? AND user_id IS NULL', email]
end
def self.import(file_name)
for_each_line_in(file_name) do |line|
SearsRegistration.create_from_tsv! line
end
end
def self.update_email_opt_ins(file_name)
for_each_line_in(file_name) do |line|
sr = SearsRegistration.find_by_auth_email line.downcase
sr.update_attribute(:email_opt_in, true) if sr
end
end
def generate_temporary_password
@send_temporary_password = true
unless self.temporary_password_expiration && self.temporary_password_expiration > Time.now
# generate a new one
self.temporary_password = Util.token_string(7, true)
self.temporary_password_expiration = 3.days.from_now
end
end
def valid_temporary_password?
self.temporary_password && self.temporary_password_expiration && self.temporary_password_expiration > Time.now
end
private
def send_temporary_password
if @send_temporary_password && self.temporary_password
ETTriggeredSendAdd.send_temporary_password self
end
end
IMPORT_FILE_FIELD_ORDER = [
:machine_id, :first_name, :last_name, :auth_email, :country, :address_line_1,
:address_line_2, :city, :state, :zip_code, :birth_year, :household_size,
:privacy_version, :crypted_password
]
def self.create_from_tsv!(line)
fields = line.split "\t"
opts = {}
fields.each_index { |i| opts[IMPORT_FILE_FIELD_ORDER[i]] = fields[i] }
opts[:auth_email] = opts[:auth_email].downcase
opts[:salt], opts[:crypted_password] = SearsRegistration.reencrypt_password opts[:crypted_password]
SearsRegistration.create! opts
end
def self.reencrypt_password(orig_encrypted)
plain_text = SearsRegistration.decrypt_orig_password orig_encrypted
salt = Util.token_string User::SALT_MAX_LENGTH
new_encrypted = Util.encrypt plain_text, salt
[salt, new_encrypted]
end
KEY = [8, 89, 72, 113, 211, 224, 16, 247, 6, 107, 225, 83, 78, 163, 55, 123, 186, 58, 209, 37, 151, 151, 12, 0].pack("c*")
IV = [146, 179, 119, 242, 208, 207, 14, 119].pack("c*")
def self.decrypt_orig_password(orig_encrypted)
Util.decrypt_des_de3_cbc KEY, IV, Base64.decode64(orig_encrypted)
end
def self.for_each_line_in(file_name)
logger.info "Importing from '#{file_name}'"
line_cnt = succ_count = err_cnt = 0
File.open(file_name) do |f|
f.each_line do |l|
begin
line_cnt += 1
yield l.chomp
succ_count += 1
rescue => e
logger.error "Import error occurred:\n#{e}\n#{l}"
err_cnt += 1
end
end
end
logger.info "Import summary for '#{file_name}' -- lines seen: #{line_cnt} successes: #{succ_count} errors: #{err_cnt}"
end
end
|
require 'wsdl_mapper/naming/type_name'
require 'wsdl_mapper/naming/inflector'
module WsdlMapper
module Naming
# This is the base class of all namers, which implements common functionality.
#
# A namer is responsible for generating ruby class / module / attribute / constant
# names from schema information.
#
# For the most part, derivations such as {DefaultNamer} just implement
# common ruby conventions. The interface, though, also allows for complete
# customization.
class NamerBase
include Inflector
KEYWORDS = %w[
alias
and
begin
break
case
catch
class
def
do
elsif
else
fail
ensure
for
end
if
in
module
next
not
or
raise
redo
rescue
retry
return
then
throw
super
unless
undef
until
when
while
yield
true
false
nil
self
]
attr_reader :module_path
def initialize(module_path: [])
@module_path = module_path
end
protected
def make_parents(path)
return if path.empty?
mod, path = path.last, path[0...-1]
type_name = TypeName.new mod, path, get_file_name(mod), get_file_path(path)
type_name.parent = make_parents path
type_name
end
def get_constant_name(name)
get_key_name(name).upcase
end
def get_key_name(name)
underscore sanitize name
end
def get_accessor_name(name)
get_key_name name
end
def get_var_name(name)
"@#{get_accessor_name(name)}"
end
def get_file_name(name)
underscore(name) + '.rb'
end
def get_file_path(path)
path.map do |m|
underscore m
end
end
def sanitize(name)
if valid_symbol? name
name
else
"x_#{name}"
end
end
def valid_symbol?(name)
name =~ /^[a-zA-Z]/ && !KEYWORDS.include?(name.to_s)
end
end
end
end
|
require "spec_helper"
describe ConsultationTypesController do
describe "routing" do
it "routes to #index" do
get("/consultation_types").should route_to("consultation_types#index")
end
it "routes to #new" do
get("/consultation_types/new").should route_to("consultation_types#new")
end
it "routes to #show" do
get("/consultation_types/1").should route_to("consultation_types#show", :id => "1")
end
it "routes to #edit" do
get("/consultation_types/1/edit").should route_to("consultation_types#edit", :id => "1")
end
it "routes to #create" do
post("/consultation_types").should route_to("consultation_types#create")
end
it "routes to #update" do
put("/consultation_types/1").should route_to("consultation_types#update", :id => "1")
end
it "routes to #destroy" do
delete("/consultation_types/1").should route_to("consultation_types#destroy", :id => "1")
end
end
end
|
class AddtoPitch < ActiveRecord::Migration
def change
add_column :pitches, :team_members, :string
add_column :pitches, :other_info, :text
add_column :pitches, :launch_date, :text
add_column :pitches, :category, :text
end
end
|
class ItemsController < ApplicationController
before_filter :find_item, only: [:show, :edit, :update, :destroy]
before_filter :check_if_admin, only: [:edit, :update, :new, :destroy, :create]
def index
@items = Item.all
end
# /items/1 GET
def show
unless @item
render text: "Page not found" , status: 404
end
end
# /items/new GET
def new
@item = Item.new
end
# /items/1/edit GET
def edit
end
# /items POST
def create
@item = Item.create(params[:item])
if @item.errors.empty?
redirect_to item_path(@item)
else
render 'new'
end
end
# /items/1 PUT
def update
@item.update_attributes(params[:item])
if @item.errors.empty?
redirect_to item_path(@item)
else
render 'edit'
end
end
# /items/1/ DELETE
def destroy
@item.destroy
redirect_to action: "index"
end
def upvote
end
private
def find_item
@item = Item.find(params[:id])
end
def check_if_admin
render text: "Acces denied", status: 403 unless params[:admin]
end
end
|
# 1 Even or Odd?
# Write a loop that prints numbers 1-5 and whether the number is even or odd. Use the code below to get started.
count = 1
loop do
if count.odd?
puts "#{count} is odd!"
else
puts "#{count} is even!"
end
count += 1
break if count > 5
end
# 2 Catch the Number
# Modify the following code so that the loop stops if number is between 0 and 10.
loop do
number = rand(100)
puts number
break if number.between?(0,10)
end
# 3 Conditional Loop
# Using an if/else statement, run a loop that prints "The loop was processed!" one time if process_the_loop equals true.
# Print "The loop wasn't processed!" if process_the_loop equals false.
# Mine doesn't run a loop - hence it isn't correct!
process_the_loop = [true, false].sample
if process_the_loop == true
puts "The loop was processed!"
else
puts "The loop wasn't processed!"
end
###################
if process_the_loop
loop do
puts "The loop was processed!"
break
end
else
puts "The loop wasn't processed"
end
# code school solution
process_the_loop = [true, false].sample
if process_the_loop
loop do
puts "The loop was processed!"
break
end
else
puts "The loop wasn't processed!"
end
# 4 Get the Sum
# The code below asks the user "What does 2 + 2 equal?" and uses #gets to retrieve the user's answer.
# Modify the code so "That's correct!" is printed and the loop stops when the user's answer equals 4.
# Print "Wrong answer. Try again!" if the user's answer doesn't equal 4.
loop do
puts 'What does 2 + 2 equal?'
answer = gets.chomp.to_i
if answer == 4
puts "That's correct!"
break
else
puts "Wrong answer. Try again!"
end
end
# launch school answer
loop do
puts 'What does 2 + 2 equal?'
answer = gets.chomp.to_i
if answer == 4
puts "That's correct!"
break
end
puts 'Wrong answer. Try again!'
end
# 5 Insert Numbers
# Modify the code below so that the user's input gets added to the numbers array.
# Stop the loop when the array contains 5 numbers.
numbers = []
loop do
puts 'Enter any number:'
input = gets.chomp.to_i
numbers << input
break if numbers.length == 5
end
puts numbers
# launch school solution
numbers = []
loop do
puts 'Enter any number:'
input = gets.chomp.to_i
numbers.push(input)
break if numbers.size == 5
end
puts numbers
# 6 Empty the Array
# Given the array below, use loop to remove and print each name. Stop the loop once names
# doesn't contain any more elements.
names = ['Sally', 'Joe', 'Lisa', 'Henry']
loop do
puts names.pop
break if names.length == 0
end
# code school solution
names = ['Sally', 'Joe', 'Lisa', 'Henry']
loop do
puts names.shift
break if names.empty?
end
# 7 Stop Counting
# The method below counts from 0 to 4. Modify the block so that it prints the current number and stops
# iterating when the current number equals 2.
5.times do |index|
puts index
break if index == 2
end
# 8 Only Even
# Using next, modify the code below so that it only prints even numbers.
number = 0
until number == 10
number += 1
next if number % 2 == 1
puts number
end
# launch school solution
number = 0
until number == 10
number += 1
next if number.odd?
puts number
end
# 9 First to Five
# The following code increments number_a and number_b by either 0 or 1. loop is used so that the variables
# can be incremented more than once, however, break stops the loop after the first iteration. Use next to
# modify the code so that the loop iterates until either number_a or number_b equals 5. Print "5 was reached!"
# before breaking out of the loop.
number_a = 0
number_b = 0
loop do
number_a += rand(2)
number_b += rand(2)
next unless number_a == 5 || number_b == 5
puts "number 5 was reached!"
puts "the final values for number_a was #{number_a} & the final value for number_b was #{number_b}"
break
end
# 10 Greeting
# Given the code below, use a while loop to print "Hello!" twice.
def greeting
puts 'Hello!'
end
number_of_greetings = 2
while number_of_greetings > 0
greeting
number_of_greetings -= 1
end
# launch school solution!
def greeting
puts 'Hello!'
end
number_of_greetings = 2
while number_of_greetings > 0
greeting
number_of_greetings -= 1
end
|
require 'rails_helper'
RSpec.describe Order, type: :model do
describe 'Validations' do
it { is_expected.to validate_presence_of :offer }
it { is_expected.to validate_presence_of :quantity }
it { is_expected.to validate_presence_of :purchase }
it { is_expected.to validate_presence_of :offer_value }
xit { is_expected.to validate_numericality_of(:quantity).is_greater_than(0).is_less_than(4).only_integer }
end
describe 'Relations' do
it { is_expected.to belong_to :offer }
it { is_expected.to belong_to :purchase }
end
end
|
# encoding: UTF-8
# Question#is_mandatory is now false by default. The default_mandatory option allows you to set
# is_mandatory for all questions in a survey.
survey "IBC Protocol", :default_mandatory => false do
section "Protocol Type" do
# When :pick isn't specified, the default is :none (no checkbox or radio button)
q_principle_investigator "Principle Investigator"
a_1 :string
q_project_title "Project Title"
a_1 :string
q_application_type "Application Type: (select all that apply)", :pick => :any
a_1 "Recombinant or Synthetic Nucleic Acids (bacterial host-plasmid vector systems; recombinant or synthetic viruses in tissue culture; recombinant or synthetic nucleic acids in plants or animals; recombinant or synthetic influenzae viruses; >10 liter culture)"
a_2 "Biological Materials Registration (human, animal, and/or plant pathogens; plants; animals,)"
a_3 "Biological Toxin"
a_4 "Transgenic Animal Registration, only"
end
section "New Submission Information" do
repeater "List Co-Investigators" do
q "Co-Investigator"
a "First Name", :string
a "Last Name", :string
a "Title", :string
a "Department", :string
a "Phone", :integer, :input_mask => '(999)999-9999', :input_mask_placeholder => '#'
a "Fax", :integer, :input_mask => '(999)999-9999', :input_mask_placeholder => '#'
a "Email", :string
end
repeater "List All Research Locations" do
q "Research Location"
a "Building", :string
a "Rm#", :string
end
q "Required Biosaftey Level", :pick => :one, :display_type => :dropdown
["BSL1", "BSL2", "BSL3"].each{ |level| a level}
q_funding_agencies "Funding Agencies:"
a_1 :text
repeater "Personnel Conducting Experiments" do
label "Identify personnel conducting the experiments (including students and temporary
staff). Specify project responsibilities and applicable training/experience including
duration. Each individual must read and understand the nature of the experiment(s) and the
pertinent governing guidelines (including relevant portions of the USA Patriot Act) if
<a href='http://www.selectagents.gov/resources/List_of_Select_Agents_and_Toxins_2012-12-4-English.pdf'>
Select Agents </a>are going to be worked with."
q_1 "Person"
a "First Name", :string
a "Last Name", :string
a "Responsibilities", :text
a "Training and Experience (include CITI training)", :text
end
q_2 "Have you and each of your listed personnel completed the CITI training <a href='http://www.citiprogram.org/''>(http://www.citiprogram.org?)</a>", :pick => :one, :display_type => :dropdown
["Yes","No"].each{ |level| a level}
q_3 "Will human subjects and/or human clinical specimens be used in this research? Yes or no. If yes, please explain."
a_1"text"
q_4 "Will you transport or ship biological agents/infectious substances/diagnostic specimens?" , :pick=>:one
a_1 "Yes"
a_2 "No"
q_5 "Will you use <a href='http://www.selectagents.gov/resources/List_of_Select_Agents_and_Toxins_2012-12-4-English.pdf'>Select Agents?" , :pick=> :one
a_1 "Yes"
a_2 "No"
q_6 "Will you use agents subject to export controls?" ,:pick=> :one
a_1 "Yes"
a_2 "No"
q_7 "Are permits (import, transport, release to the environment required to work with this material? If yes, please submit a copy of all permits with this registration." , :pick=> :one
a_1 "Yes"
a_2 "No"
q_8 "Does any aspect of your work have 'dual-use potential,' as defined as research that can be reasonably anticipated to provide knowledge, products, or technologies that could be directly misapplied by others to pose a threat to public health and safety, agricultural crops and plants, animals, or the environment?" ,:pick=> :one
a_1 "Yes"
a_2 "No"
q_9 "If yes, provide a detailed explanation."
a_1"text"
end
section "Biological Materials Registration" do
#dependency :rule=> "D"
#condition_D :q_application_type, "==", :a_2
label "Please check all that apply. If you also use recombinant or synthetic nucleic acids and/or biological toxins in conjunction with the biological materials below, please complete the survey sections for these items by checking on the appropriate check boxes at the beginning of the survey."
q_classifications "Classifications", :pick => :any
a_1 "Human, Animal, and/or Plant Pathogens"
a_2 "Plants"
a_3 "Animals"
a_4 "Human or Primate Cell Lines"
#group "Pathogen Registration" do
label "Please complete the following section for each human, animal and plant pathogen used in this project."
repeater "Text Pathogen" do
q_10 "Pathogen ID"
a "Genus and species (and strain if known)", :string
a "Type of Agent: bacterium, virus, fungus, cell line, prion", :string
a "Biosafety Level: 1,2,3,4", :string
a "Source of Agent", :string
a "Pathogenic to", :string
a "Clinical Symptoms or Name of Disease", :text
a "Effective Treatments (e.g. antibiotics, immunization)", :text
a "How will you inactivate the agent upon completion of work?", :text
end
repeater " Identify all locations where the microorganisms will be stored, and/or weighed. " do
q_11 " Add Location"
a "Building", :string
a "Rm#", :string
a "Facility", :string
a "Type", :string
a "Qty (storage location)", :string
end
repeater " Identify all locations where experiments will be conducted" do
q_12 " Add Experimental Location"
a "Building", :string
a "Rm#", :string
a "Facility", :string
a "Type", :string
a "Qty (storage location)", :string
end
q_13 "Means of transportation (if storage and experiment locations are not the same):"
a :text
#end#end group
#group "Plant Use" do
label "Plant Use"
q_14 "Will plants be infected with or exposed to a pathogen? If no, skip the remaining questions in this section.", :pick=> :one
a_1 "Yes"
a_2 "No"
repeater "Infected Plants" do
q_15 "Plant Text"
a_1 "Name of Plant", :string
a_2 "Is this plant a noxious weed, invasive plant, or exotic plant?", :string
q_15a "Where will infected plants be kept? Check all that apply.", :pick=> :any
a_4 "Laboratory"
a_5 "Growth Chamber"
a_6 "Greenhouse"
a_7 "Field Release"
a_8 "Describe procedures for containment of infected plants.", :text
a_9 "How will infected plant materials be disposed of upon completion of experiments?", :text
end
# end
#
# group "Animal Use" do
label "Animal Use"
q_16 "Will animals be infected with or exposed to a pathogen? If no, skip the remaining questions in this section.", :pick=> :one
a_1 "Yes"
a_2 "No"
q_17 "Please text the animals you will be using:"
a_1 :text
q_18 "Route of infection? Check all that apply", :pick=> :any
a_1 "Intravenous"
a_2 "Intranasal"
a_3 "Intrperitoneal"
a_4 "Subcutaneous"
a_5 "Intramuscular"
a_6 "Intracerebroventricular"
a_7 "Other"
repeater "Animal Housing" do
q_19 "Where will animals be housed?"
a_1 "Building", :text
a_2 "Room", :string
end
repeater "Animal Experiment Location" do
q_20 "Where will you perform procedures using animals?"
a_1 "Building", :text
a_2 "Room", :string
end
# end
end #end section
section "Recombinant and Synthetic Nucleic Acid Molecules" do
group "Recombinant and Synthetic Nucleic Acid Molecules" do
dependency :rule => "D"
condition_D :q_application_type, "==", :a_1
label "Fill out this section if your project involves the use of Recombinant and/or Synthetic Nucleic Acid Molecules. More information: <a href='http://oba.od.nih.gov/oba/faqs/Synthetic_FAQs-Sept-2012.pdf'>Frequently Asked Questions NIH
Guidelines for Research Involving Recombinant or Synthetic Nucleic Acid Molecules</a>"
label"Check YES or NO to each question to determine which sections of the NIH Guidelines pertain to your project. You will be asked to describe your project in question __. Please address each item checked YES in that description.</a>"
q_21 "1. Does your project include deliberate transfer of a drug resistance trait to microorganisms that are NOT known to acquire the trait naturally? (Section III-A)? If yes, also answer, also answer question 1.a.", :pick=> :one
a_1 "Yes"
a_2 "No"
q_22 "1.a Could such a transfer compromise the use of the drug to control disease agents in humans, veterinary medicine, or agriculture?", :pick=> :one
a_1 "Yes"
a_2 "No"
q_23 "2. Does your project include cloning toxin molecules with an LD50 of less than 100 nanograms per kilogram body weight ? (Section III-B) If YES, please make sure to also complete the Biological Toxin section by selecting the checkbox for Biological Toxins at the beginning of the form.", :pick => :one
a_1"Yes"
a_2"No"
q_24 "3. Does your project include experiments using Risk Group 2, Risk Group 3, Risk Group 4, or Select Agents as host-vector systems? (Section III-D-1) If YES, please make sure to also complete the Biological Materials Registration section by selecting the checkbox for Biological Materials Registration at the beginning of the form.", :pick=> :one
a_1 "Yes"
a_2 "No"
q_25 "4. Does your project include experiments in which nucleic acids from Risk Group 2, Risk Group 3, Risk Group 4, or Restricted Agents is cloned into nonpathogenic prokaryotic or lower eukaryotic host-vector systems? (Section III-D-2)?", :pick=> :one
a_1 "Yes"
a_2 "No"
q_26 "5. Does your project include experiments involving the use of infectious DNA or RNA viruses or defective DNA or RNA viruses in the presence of helper virus in tissue culture systems? (Section III-D-3)", :pick=> :one
a_1 "Yes"
a_2 "No"
#a yes answer should prompt to viral vector group
q_27 "6. Does your project include experiments involving genetically engineered plants? (Section III-D-5, III-E-2)", :pick=> :one
a_1 "Yes"
a_2 "No"
# a Yes answer should prompt to rDNA Plant group
q_28 "7. Does your project include experiments involving more than 10 liters of culture? (Section III-D-6)", :pick=> :one
a_1 "Yes"
a_2 "No"
q_29 "8. Does your project include experiments involving the formation of recombinant DNA molecules containing two-thirds or less of the genome of any eukaryotic virus? (Section III-E-1)", :pick=> :one
a_1 "Yes"
a_2 "No"
q_30 "9. Does your project include experiments involving viable rDNA-modified microorganisms tested on animals? (Section III-D-4, III-E-3). ?" , :pick=> :one
a_1 "Yes"
a_2 "No"
# a yes answer should prompt to the rDNA in animals group"
q_31"10. Does your project include experiments involving whole animals in which the animal’s genome has been altered by introduction of DNA into the germ line (i.e. transgenic animals)? (Section III-D-4, III-E-3) If yes, then please register your transgenic animals by checking the TRANSGENIC ANIMAL REGISTRATION check box at the beginning of the form.", :pick=> :one
a_1 "Yes"
a_2 "No"
q_32 "11. Does your project include experiments involving the deliberate transfer of recombinant or synthetic nucleic acids into one or more human research participants (Section III-C)?", :pick=> :one
a_1 "Yes"
a_2 "No"
label "Please answer the following general questions about your project with regards to recombinant or synthetic nucleic acid use ."
q_33 "Will proteins or regulatory RNAs be expressed?", :pick=> :one
a_1 "Yes"
a_2 "No"
q_34 "Is the source of nucleic acid to be cloned associated with alterations of normal mammalian cell cycle or cell growth (i.e. a potentially oncogenic or tumorigenic gene?)"
a_1 :text
end #end group
end #end section
section "Biological Toxin" do
# dependency :rule => "B"
# condition_B :q_application_type, "==", :a_3
label "Complete this section if you are working with a biological toxin or select agent listed on the National Select Agent Registry,
a microorganism which synthesizes a toxic molecule lethal for vertebrates below, or the biosynthesis of toxic molecules."
q_35 "1) Identify the toxin(s) and their source, unfractionated mixture, purified conjugate, or microbial culture, capable of producing toxin that will be used in experiment "
a :text
q_36 "2) Is the toxin on the <a href'http://www.selectagents.gov/resources/List_of_Select_Agents_and_Toxins_2012-12-4-English.pdf'>Select Agent List?</a>", :pick => :one
a_1 "Yes"
a_2 "No"
label "Indicate the amount (if any) currently on-site: "
a :text
q_37 "3) Is the toxin being purchased from a commercial source? ", :pick => :one
a_1 "Yes"
a_2 "No"
q_38 "4) Are there plans to express the toxin in a recombinant expression system??", :pick => :one
a_1 "Yes"
a_2 "No"
label "If the toxin is on the Select Agent list, these are restricted experiments that require approval by HHS prior to initiation. Proceeding without prior approval is violation of section 13 </br>
of the Select Agent regulations (see section 73.13, <a href='http://www.selectagents.gov/Regulations.html'>http://www.selectagents.gov/Regulations.html</a>).</br>
Cloning of toxins with an LD50 of less than 100 nanograms per kilogram body weight cannot be done without approval by both the NIH/OBA and the MSU IBC. (see Sections </br>
III-B and III-B-1 of the NIH Guidelines for Recombinant and Nucleic Acid Research, <a href'http://oba.od.nih.gov/oba/rac/Guidelines/NIH_Guidelines.htm'>
http://oba.od.nih.gov/oba/rac/Guidelines/NIH_Guidelines.htm</a>)</br>
Toxins with an LD50 of <100 ng/kg body weight include select agent toxins, botulinum toxins tetanus toxin, diphtheria toxin, and Shigella dysenteriae neurotoxin."
q_39 "5) Describe the types of experiments that will be performed. "
a_1 :text
q_40 "6) Indicate the anticipated amounts that will be needed. "
a_1 :text
q_41 "7) What is the LD50 of the toxin? Cite the source of information. "
a_1 :text
q_42 "8) Will the toxin be transferred to another investigator at any time, either on-site or at another institution?", :pick => :one
a_1 "Yes"
a_2 "No"
label "See the required documentation for due diligence: <a href='http://www.selectagents.gov/Toxin_Due_Diligence_Provision.html'>
http://www.selectagents.gov/Toxin_Due_Diligence_Provision.html.</a> Documentation must be provided to the IBC and approved prior to transfer."
repeater "9) Identify all locations where the microorganism will be stored, and/or weighed and where experiments will be conducted" do
dependency :rule => "B"
condition_B :q_application_type, "==", :a_3
q_43 " Add Location"
a_1 "Building", :string
a_2 "Rm#", :string
a_3 "Facility", :string
a_4 "Type", :string
a_5 "Qty (storage location)", :string
end
# group "Biological Toxin" do
# dependency :rule => "B"
# condition_B :q_application_type, "==", :a_3
label "Means of transportation (if storage and experiment locations are not the same):"
a_1 :text
q_44 "10) Does the experiment involve the administration of toxin to animals?", :pick => :one
a_3 "Yes"
a_2 "No"
q_45 "11) Identify the method of disposal/deactivation of contaminated materials and remaining agent: "
a_1 :text
q_46 "12) Describe your written protocol covering the secure storage, safe handling and emergency procedures in case of an accident (exposure to staff or spill) for this toxin. "
a_1 :text
q_47 "13) Is there an antidote available for persons exposed to the toxin?", :pick => :one
a_1 "Yes"
a_2 "No"
q_48 "14) Have all personnel involved with this project received documented initial training and yearly updates regarding the procedures for handling the toxin?", :pick => :one
a_1 "Yes"
a_2 "No"
# end
end #end section
section "PI Statement of Understanding" do
# dependency :rule => "H or M or D"
# condition_H :q_application_type, "==", :a_3
# condition_M :q_application_type, "==", :a_2
# condition_D :q_application_type, "==", :a_1
q_49 "As Principal Investigator, I understand there are federal regulations applicable to work with Select Agent toxins. ", :pick => :any?
a_1 "I have reviewed the regulations and the proposed experiments are either exempt, or if not, I have obtained the necessary approvals."
q_50 "Description of use of Biological Materials</ br>
This section is required for all applications.</ br>
In the following space, please describe your project clearly and simply with respect to recombinant DNA, microorganism, and biological toxin usage."
a :text
q_51 "Appendix D: Laboratory Specific SOPs</ br>
Paste into this section all protocol specific SOPs for working with BSL2 organisms."
a :text
label "BY SUBMITTING THIS FORM YOU ACKNOWLEDGE THAT YOU HAVE READ AND AGREE TO THE FOLLOWING STATEMENTS</ br>
Pursuant to applicable State and Federal laws and regulations and Montana State University policies and procedures:</ br>
To the best of my knowledge, I affirm that all information contained herein is accurate and complete.</ br>
I agree to comply with federal, state, and university requirements pertaining to handling, shipment, transfer, and disposal of biological materials, to include annual lab inspections.</ br>
I agree to accept responsibility for the training of all personnel involved in this research and that all personnel have been trained.</ br>
I understand that IBC approval of this protocol constitutes approval to work with the specified agents (recombinant DNA, microorganisms, <a href='http://www.selectagents.gov/resources/List_of_Select_Agents_and_Toxins_2012-12-4-English.pdf'>
select agents</a> , biological toxins) using the specified biosafety procedures/practices and laboratory facilities described herein.</ br>
I affirm that all personnel working on the project covered by this protocol have read and are in compliance with the federal law defined in the USA Patriot Act (see <a href='https://apps.montana.edu/msupam/appendF'>
Appendix F</a>), if applicable.</ br>
I understand that all changes in agents, procedures/practices, and facilities must be reported in writing to the IBC in the prescribed format, and that IBC approval shall be obtained prior to implementation of these changes.</ br>
I understand that unauthorized use of recombinant DNA, microorganisms, <a href='http://www.selectagents.gov/resources/List_of_Select_Agents_and_Toxins_2012-12-4-English.pdf'>
select agents</a> , biological toxins or deviation from an approved IBC protocol may result in suspension of research privileges and/or disciplinary action.</ br>
I understand that any persons added to the project after initial approval requires IBC approval and a modification will be submitted and each new person will complete and submit the Patriot Act Compliance Questionnaire (<a href='https://apps.montana.edu/msupam/appendF'>
Appendix F</a>) if Select Agents are involved."
#end
end #end section
#
# good
section "RECOMBINANT DNA (rDNA)" do
q_class2 "Mark the appropriate section(s) that describes this project. If experiment does not fall into any of these categories, contact Biosafety Office for assistance (check all that apply):", :pick => :any
a_1 "III A....must receive approval from IBC and NIH Director before initiation of experiments."
a_2 "III B….must receive approval from NIH/OBA and IBC before initiation of experiments."
a_3 "III C.....must receive approval from IBC, IRB, and RAC review before research participant enrollment."
a_4 "III D....must receive approval from IBC before initiation of experiments."
a_5 "rDNA Involving Whole Animal"
a_6 "rDNA Involving Whole Plants:"
a_7 " III E….must notify IBC simultaneously upon initiation of research."
a_8 "III F......exempt from IBC Review. To request an official exemption letter email lindstrom@montana.edu"
label "Section III-A-1-a: The deliberate transfer of a drug resistance trait to microorganisms that are not known to acquire
the trait naturally if such acquisition could compromise the use of the drug to control disease agents in humans,
veterinary medicine, or agriculture. (Note that antibiotic resistance markers used for selecting and propagating plasmids in E. coli are not included.)"
dependency :rule=>"Z"
condition_Z :q_class2, "==", :a_1
label "Section III-B-1: Experiments involving the cloning of toxin molecules with LD50 of <100ng per kg body weight (e.g.,
microbial toxins such as botulinum toxin, tetanus toxin)."
dependency :rule=>"Z1"
condition_Z1 :q_class2, "==", :a_2
label "Section III-C-1: Experiments involving the deliberate transfer of rDNA, or DNA or RNA derived from rDNA, into one or more human research participants."
dependency :rule=>"Z2"
condition_Z2 :q_class2, "==", :a_3
label "< NOTE: Attach response to Points to Consider: Appendix M of the NIH Guidelines and submit any
supplemental documents such as investigator brochure, clinical study, correspondence with NIH, etc. "
label "For rDNA experiments falling under Sections III-D-5-a through III-D-5-d, physical containment requirements may be reduced to the next lower level by appropriate biological containment practices,
such as conducting experiments on a virus with an obligate insect vector in the absence of that vector or using a genetically attenuated strain."
dependency :rule=>"Z3"
condition_Z3 :q_class2, "==", :a_6
group "III-D" do
dependency :rule=>"Z4"
condition_Z4 :q_class2, "==", :a_4
q_class22 "III-D-1-a", :pick => :any
a_1 "Introduction of rDNA into Risk Group 2 (RG-2) agents."
q_class23 "III-D-1-b", :pick => :any
a_1 "Introduction of rDNA into Risk Group 3 (RG-3) agents."
q_class24 "III-D-2-a", :pick => :any
a_1 "Experiments in which DNA from RG- 2, RG- 3 agents, or RG-4 agents is transferred into nonpathogenic prokaryotes or lower eukaryotes."
q_class25 "III-D-3-a", :pick => :any
a_1 "Use of infectious or defective RG-2 viruses in the presence of helper virus."
q_class26 "III-D-3-b", :pick => :any
a_1 "Use of infectious or defective RG-3 viruses in the presence of helper virus may be conducted at BL3 containment."
q_class27 "III-D-3-d", :pick => :any
a_1 "Use of infectious or defective restricted poxviruses in the presence of helper virus shall be determined on a case-by-case
basis following NIH/OBA review. A USDA permit is required for work with plant or animal pathogens."
q_class28 "III-D-3-e", :pick => :any
a_1 "Use of infectious or defective viruses in the presence of helper virus not covered in Sections III-D-3-a through III-D-3-d."
end
#good
#
group "rDNA" do
dependency :rule=>"Z6"
condition_Z6 :q_class2, "==", :a_5
q_class2v9 "III-D-4-a", :pick => :any
a_1 "rDNA, or DNA or RNA molecules derived therefrom, from any source except for greater than two-thirds of eukaryotic viral genome may be transferred to any non-human vertebrate or any invertebrate organism and propagated under conditions of physical containment comparable to BSL1 or BSL1-N and appropriate to the organism under study. Animals that contain sequences from viral vectors, which do not lead to transmissible infection either directly or indirectly as a result of complementation or recombination in animals, may be propagated under conditions of physical containment comparable to BSL1 or BSL1-N and appropriate to the organism under study. Experiments involving the introduction of other sequences from eukaryotic viral genomes into
animals are covered under Section III-D-4-b. Investigator must demonstrate that the fraction of the viral genome being utilized does not lead to productive infection."
q_cwlass30 "III-D-4-b", :pick => :any
a_1 "Experiments involving rDNA, or DNA or RNA derived therefrom, involving whole animals, including transgenic animals, and not covered by
Sections III-D-1 or III-D-4-a, may be conducted at the appropriate containment determined by the IBC."
q_clas2s3c1"III-D-4-c-1", :pick => :any
a_1 "Experiments involving the generation of transgenic rodents that require BSL1 containment."
q_class3c"III-D-4-c-2", :pick => :any
a_1 "Purchase or transfer of transgenic rodents is exempt from the 'NIH Guidelines', but register with the IBC (Form 4)."
end
group "rDNA" do
dependency :rule=>"Z7"
condition_Z7 :q_class2, "==", :a_6
q_class29 "III-D-5-a", :pick => :any
a_1 "BSL3-P (Plants) or BSL2-P + biological containment is recommended for experiments of most exotic infectious agents with recognized potential
for serious detrimental impact on managed or natural ecosystems when rDNA techniques are associated with whole plants."
q_class30 "III-D-5-b", :pick => :any
a_1 "BSL3-P or BSL2-P + biological containment is recommended for experiments involving plants containing cloned genomes of readily transmissible exotic infectious agents with recognized potential for serious detrimental effects on managed or natural ecosystems in
which there exists the possibility of reconstituting the complete and functional genome of the infectious agent by genomic complementation in planta."
q_class3c1" III-D-5-c", :pick => :any
a_1 "BSL4-P containment is recommended for experiments with a small number of readily transmissible exotic infectious agents, such as the soybean rust fungus (Phakospora pachyrhizi) and maize streak or other viruses in the presence of
their specific arthropod vectors that have the potential of being serious pathogens of major U.S. crops."
q_class3c2 "III-D-5-d ", :pick => :any
a_1 "BSL3-P containment is recommended for experiments involving sequences encoding potent vertebrate toxins introduced into plants or associated organisms (also refer to Section III-B-1)."
q_class3c3 "III-D-5-e", :pick => :any
a_1 "BSL3-P or BSL2-P + biological containment is recommended for experiments with microbial pathogens of insects or small animals associated with plants if the
rDNA-modified organism has a recognized potential for serious detrimental impact on managed or natural ecosystems."
q_class3c4 "III-D-6", :pick => :any
a_1 "Experiments involving more than 10 liters of culture. The appropriate containment will be decided by the IBC."
end
#good
group " III E" do
dependency :rule=>"Z8"
condition_Z8 :q_class2, "==", :a_7
q_class29tr "III-E-1", :pick => :any
a_1 "Experiments involving the formation of rDNA molecules containing no more than 2/3 of the genome of any eukaryotic virus
(All viruses from a single Family being considered identical.) may be propagated and maintained in cells in tissue culture using BSL1."
q_class3043 "III-E-2-a ", :pick => :any
a_1 "BSL1-P is recommended for all experiments with rDNA-containing plants and plant-associated microorganisms not covered in Section III-E-2-b or other sections of the NIH Guidelines. Examples of such experiments are those involving rDNA-modified plants that are not noxious weeds or that cannot interbreed with noxious weeds in the immediate geographic area, and experiments involving whole plants and rDNA-modified non-exotic microorganisms that have no recognized potential for rapid and widespread dissemination or for
serious detrimental impact on managed or natural ecosystems (e.g., Rhizobium spp. and Agrobacterium spp.). Use FORM 3 Registration of rDNA modified Whole Plants."
q_class3c10"III-E-2-b", :pick => :any
a_1 "BSL2-P or BSL1-P + biological containment is recommended for the following experiments:"
q_class3c11"III-E-2-b-(1)", :pick => :any
a_1 "Plants modified by rDNA that are noxious weeds or can interbreed with noxious weeds in the immediate geographic area."
q_class3c12 "III-E-2-b-(2)", :pick => :any
a_1 "Plants in which the introduced DNA represents the complete genome of a non-exotic infectious agent."
q_clas1s3c13 "III-E-2-b-(3)", :pick => :any
a_1 "Plants associated with rDNA-modified non-exotic microorganisms that have a recognized potential for serious detrimental impact on managed or natural ecosystems."
q_class3c14 "III-E-2-b-(4)", :pick => :any
a_1 "Plants associated with rDNA-modified exotic microorganisms that have no recognized potential for serious detrimental impact on managed or natural ecosystems."
q_class3c15 "III-E-2-b-(5)", :pick => :any
a_1 "Experiments with rDNA-modified arthropods or small animals associated with plants, or with arthropods or small animals with rDNA-modified microorganisms associated with them if the
rDNA-modified microorganisms have no recognized potential for serious detrimental impact on managed or natural ecosystems."
q_class3c1e "II-E-3", :pick => :any
a_1 "Experiments involving the generation of rodents in which the animal’s genome has been altered by stable introduction of rDNA, or DNA derived therefrom, into
the germ0line (transgenic rodents). Use FORM 4 Registration of Transgenic Animals."
end
group "rDNA" do
dependency :rule=>"Z"
condition_Z :q_class2, "==", :a_8
q_class291 "III-F-1", :pick => :any
a_1 "rDNA molecules that are not in organisms or viruses."
q_class302 "III-F-2", :pick => :any
a_1 "rDNA molecules that consist entirely of DNA segments from a single nonchromosomal or viral DNA source, though one or more of the segments may be a synthetic equivalent."
q_class3c13"III-F-3", :pick => :any
a_1 "rDNA molecules that consist entirely of DNA from a prokaryotic host including its indigenous plasmids or viruses when propagated only in that
host (or a closely related strain of the same species), or when transferred to another host by well established physiological means."
q_class3c24 "III-F-4", :pick => :any
a_1 "rDNA molecules that consist entirely of DNA from a eukaryotic host including its chloroplasts, mitochondria, or plasmids (but excluding viruses) when propagated only in that host (or closely related strain of the same species)."
q_class3c35 "III-F-5", :pick => :any
a_1 "rDNA molecules that consist entirely of DNA segments from different species that exchange DNA by known physiological processes, though one or more of the segments may be a synthetic equivalent."
q_class3c46 "III-F-6", :pick => :any
a_1 "rDNA experiments that do not present a significant risk to health or the environment as determined by the NIH Director, RAC and following appropriate notice and opportunity for public comment. "
end#edn group
end #end section
end
|
class ProvidersController < ApplicationController
before_action :set_provider, only: [:show, :edit, :update, :destroy]
# GET /providers
# GET /providers.json
def index
@providers = Provider.all
end
# GET /providers/1
# GET /providers/1.json
def show
end
# GET /providers/new
def new
@organisation=Organisation.new
@provider = Provider.new
@provider.organisation=@organisation
if params[:person]
@person=Person.find(params[:person])
end
end
# GET /providers/1/edit
def edit
end
# POST /providers
# POST /providers.json
def create
@provider = Provider.new(provider_params)
if @provider.organisation_id==0
@organisation = Organisation.new(organisation_params)
@organisation.save
@provider.organisation_id=@organisation.id
end
respond_to do |format|
if @provider.save
@redirect=@provider
if params[:person]
@person=Person.find(params[:person])
@person.providers << @provider
@redirect=@person
end
format.html { redirect_to @redirect, notice: 'Provider was successfully created.' }
format.json { render :show, status: :created, location: @provider }
else
format.html { render :new }
format.json { render json: @provider.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /providers/1
# PATCH/PUT /providers/1.json
def update
if params[:provider][:organisation_id]=='0'
@organisation = Organisation.new(organisation_params)
@organisation.save
params[:provider][:organisation_id]=@organisation.id
else
@organisation = Organisation.find(params[:provider][:organisation_id])
@organisation.update(organisation_params)
end
respond_to do |format|
if @provider.update(provider_params)
format.html { redirect_to @provider, notice: 'Provider was successfully updated.' }
format.json { render :show, status: :ok, location: @provider }
else
format.html { render :edit }
format.json { render json: @provider.errors, status: :unprocessable_entity }
end
end
end
# DELETE /providers/1
# DELETE /providers/1.json
def destroy
@provider.destroy
respond_to do |format|
format.html { redirect_to providers_url, notice: 'Provider was successfully destroyed.' }
format.json { head :no_content }
end
end
def newlocation
@provider = Provider.find(params[:id])
@organisation = Organisation.new
@provider.organisation=@organisation
end
private
# Use callbacks to share common setup or constraints between actions.
def set_provider
@provider = Provider.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def provider_params
params.require(:provider).permit(:title,:family_name, :given_names, :organisation_id, :user_id, :craft_id)
end
def organisation_params
params.require(:organisation).permit(:name,:address_line, :address_line_2, :town, :state, :postcode, :phone)
end
end
|
require 'curb'
require 'mongo'
require 'active_support'
class RottenMovieRetriever
ROTTEN_API = "rrmbqvpbr9ujrf4yu855aczv"
TMDB_API = "c4123ba475b7087ce195800a8e61e29e"
def initialize
@db = Mongo::Connection.new.db("lovelyromcoms_development")
@movie_collection = @db['movies']
end
def call_url_and_retrieve_json(url)
#puts url
curl = Curl::Easy.http_get(url)
curl.perform
json_hash = ActiveSupport::JSON.decode(curl.body_str)
json_hash
end
def request_and_get_hash(search_term)
url = "http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey=#{ROTTEN_API}&page_limit=1&page=1&q=#{search_term}"
call_url_and_retrieve_json(url)
end
def request_full_details(movie_id)
url = "http://api.rottentomatoes.com/api/public/v1.0/movies/#{movie_id}.json?apikey=#{ROTTEN_API}"
json = call_url_and_retrieve_json(url)
if json['genres'].include?("Romance") or json['genres'].include?("Comedy")
return json
else
return nil
end
end
def store_movie(movie)
if movie
puts "SAVED!!"
@movie_collection.insert movie
File.open("#{File.dirname(__FILE__)}/movies/#{movie["rotten_id"]}", "w") do |f|
f.puts movie.to_s
end
end
end
def retrieve_actor_image(actor_name)
actor_name_underscore = actor_name.gsub(" ", "_")
actor_name_underscore.gsub!("-", "")
url = "http://www.rottentomatoes.com/celebrity/#{actor_name_underscore}/pictures/"
curl = Curl::Easy.http_get(url)
curl.perform
celebrity_page_html = curl.body_str
line = celebrity_page_html.scan(/<img.*alt="#{actor_name}".*>/)[0]
if line
index1 = line.index("src")+5
index2 = line.index("jpg")+3-index1
return line.slice(index1, index2)
else
return 'http://www.team-renegade-racing.co.uk/wp-content/gallery/team-photos/placeholder.jpg'
end
end
def extract_imdb_id(movie)
begin
movie['alternate_ids']['imdb']
rescue
return "XXX"
end
end
def movie_is_comedy_romance(movie)
#first check if it is already comedy AND romance
return true if movie['genres'].include?("Romance") and movie['genres'].include?("Comedy")
#if not, we consult on IMDB to see if it is comedy and romance
imdb_id = extract_imdb_id(movie)
url = "http://www.imdb.com/title/tt#{imdb_id}/"
curl = Curl::Easy.http_get(url)
curl.perform
page_html = curl.body_str
page_html.include?("/genre/Comedy") and page_html.include?("/genre/Romance")
end
def update_movie_synopsis(movie)
if movie["synopsis"].empty?
url="http://api.themoviedb.org/2.1/Movie.imdbLookup/en/json/#{TMDB_API}/tt#{extract_imdb_id(movie)}"
curl = Curl::Easy.http_get(url)
curl.perform
json_hash = ActiveSupport::JSON.decode(curl.body_str)
movie["synopsis"] = json_hash[0]["overview"]
end
end
def update_trailer_url(movie)
if movie["links"]["clips"] and !movie["links"]["clips"].empty?
url=movie["links"]["clips"]+"?apikey=rrmbqvpbr9ujrf4yu855aczv"
curl = Curl::Easy.http_get(url)
curl.perform
json_hash = ActiveSupport::JSON.decode(curl.body_str)
movie["trailer"] = {"image" => json_hash["clips"][0]["thumbnail"], "url" => json_hash["clips"][0]["links"]["alternate"]}
end
end
def remove_nil_properties(movie)
movie.reject! { |k, v| v.nil? }
end
def retrieve_and_store_movies(search_term)
json_hash = request_and_get_hash(search_term)
total = json_hash["total"].to_i
if total>0
movie = request_full_details(json_hash['movies'][0]['id'])
movie["rotten_id"] = movie["id"]
movie["id"]=nil
remove_nil_properties(movie)
movie["indicators"]== {}
if movie and movie_is_comedy_romance(movie)
update_movie_synopsis(movie)
update_trailer_url(movie)
actor1_name = movie['abridged_cast'][0]['name']
actor2_name = movie['abridged_cast'][1]['name']
actor1_image = retrieve_actor_image actor1_name
actor2_image = retrieve_actor_image actor2_name
movie['abridged_cast'][0]['image']=actor1_image
movie['abridged_cast'][1]['image']=actor2_image
store_movie movie
movie
end
end
end
end
retriever=RottenMovieRetriever.new
def execute_full_retrieval
File.open("mapreduce/results.txt") do |file|
line_number = 0
start_in_line = 2993
file.each_line do |line|
line_number += 1
next if line_number<start_in_line
movie_name = line.split("\t")[0]
next if movie_name.include?("(VG)")
movie_name.gsub!('"', "")
movie_name=movie_name.slice(0..(movie_name.index("(")-1))
movie_name.strip!
movie_name.gsub!(" ", "+")
puts movie_name
begin
retriever.retrieve_and_store_movies movie_name
sleep(0.2)
rescue
puts 'error but continuing. Error '+ $!.to_s
end
end
end
end
#execute_full_retrieval |
##
# This is the parent class TileGroup of the TileRack and Word Classes
# It embodies group of tiles
class TileGroup
## attr accessor to return the tiles
#
def tiles
return @arrayOfTiles
end
##
# Array used to store tiles
def initialize
@arrayOfTiles = Array.new
end
##
# append method adds a tile as symbol to the group
def append(tile)
@arrayOfTiles.push(tile)
end
##
# remvoes a single tile from the TileGroup
# checks if the array contains the tile
def remove(tile)
if(@arrayOfTiles.find_index(tile) != nil)
@arrayOfTiles.delete_at(@arrayOfTiles.find_index(tile))
end
end
##
# returns a string representation of the tile group array
def hand
return @arrayOfTiles.join
end
end
|
# frozen_string_literal: true
module ActiveInteractor
# The deprecation manager used to warn about methods being deprecated in the next major release.
#
# @since unreleased
# @see https://api.rubyonrails.org/classes/ActiveSupport/Deprecation.html ActiveSupport::Deprecation
#
# @return [ActiveSupport::Deprecation] an instance of `ActiveSupport::Deprecation`
NextMajorDeprecator = ActiveSupport::Deprecation.new('2.0', 'ActiveInteractor')
# The logger instance to use for logging
#
# @since 0.1.0
#
# @return [Class] the {Config#logger #config#logger} instance
def self.logger
config.logger
end
end
|
require_relative '../lib/headcount_analyst'
require_relative '../lib/district_repository'
require_relative 'test_helper'
class HeadcountAnalystTest < Minitest::Test
def test_headcount_is_existing
ha = HeadcountAnalyst.new
assert ha
end
def test_initialize_headcount_with_district
dr = DistrictRepository.new
ha = HeadcountAnalyst.new(dr)
assert ha
end
def test_kindergarten_participation_rate_variation
dr = DistrictRepository.new
dr.load_data({
:enrollment => {
:kindergarten => "./data/Kindergartners in full-day program.csv"
}
})
ha = HeadcountAnalyst.new(dr)
assert_equal 0.766, ha.kindergarten_participation_rate_variation('ACADEMY 20', :against => 'COLORADO')
assert_equal 0.447, ha.kindergarten_participation_rate_variation('ACADEMY 20', :against => 'YUMA SCHOOL DISTRICT 1')
end
def test_kindergarten_participation_rate_variation_trend
dr = DistrictRepository.new
dr.load_data({
:enrollment => {
:kindergarten => "./data/Kindergartners in full-day program.csv"
}
})
ha = HeadcountAnalyst.new(dr)
assert_equal ({2007=>0.992, 2006=>1.05, 2005=>0.96, 2004=>1.257,
2008=>0.717, 2009=>0.652, 2010=>0.681, 2011=>0.727,
2012=>0.688, 2013=>0.694, 2014=>0.661}),
ha.kindergarten_participation_rate_variation_trend('ACADEMY 20',
:against => 'COLORADO')
end
def test_kindergarten_vs_high_school
dr = DistrictRepository.new
dr.load_data({
:enrollment => {
:kindergarten => "./data/Kindergartners in full-day program.csv",
:high_school_graduation => "./data/High school graduation rates.csv"
}
})
ha = HeadcountAnalyst.new(dr)
assert_equal 0.641, ha.kindergarten_participation_against_high_school_graduation('ACADEMY 20')
end
def test_kindergarten_vs_high_school_prediction
dr = DistrictRepository.new
dr.load_data({
:enrollment => {
:kindergarten => "./data/Kindergartners in full-day program.csv",
:high_school_graduation => "./data/High school graduation rates.csv"
}
})
ha = HeadcountAnalyst.new(dr)
assert ha.kindergarten_participation_correlates_with_high_school_graduation(for: 'ACADEMY 20')
end
def test_looping_through_each_district
dr = DistrictRepository.new
dr.load_data({
:enrollment => {
:kindergarten => "./data/Kindergartners in full-day program.csv",
:high_school_graduation => "./data/High school graduation rates.csv"
}
})
ha = HeadcountAnalyst.new(dr)
refute ha.compare_all_participation
end
def test_find_if_correlates_statewide_returns_boolean
dr = DistrictRepository.new
dr.load_data({
:enrollment => {
:kindergarten => "./data/Kindergartners in full-day program.csv",
:high_school_graduation => "./data/High school graduation rates.csv"
}
})
ha = HeadcountAnalyst.new(dr)
assert_instance_of FalseClass, ha.kindergarten_participation_correlates_with_high_school_graduation(:for => 'STATEWIDE')
end
def test_find_if_correlates_selected_states_returns_boolean
dr = DistrictRepository.new
dr.load_data({
:enrollment => {
:kindergarten => "./data/Kindergartners in full-day program.csv",
:high_school_graduation => "./data/High school graduation rates.csv"
}
})
ha = HeadcountAnalyst.new(dr)
assert_instance_of TrueClass, ha.kindergarten_participation_correlates_with_high_school_graduation(:across => ['ACADEMY 20', 'BRIGHTON 27J', 'BRIGGSDALE RE-10', 'BUENA VISTA R-31'])
end
def test_high_poverty_and_high_school_graduation
dr = DistrictRepository.new
dr.load_data({
:enrollment => {
:kindergarten => "./data/Kindergartners in full-day program.csv",
:high_school_graduation => "./data/High school graduation rates.csv"},
:economic_profile => {
:median_household_income => "./data/Median household income.csv",
:children_in_poverty => "./data/School-aged children in poverty.csv",
:free_or_reduced_price_lunch => "./data/Students qualifying for free or reduced price lunch.csv"
}
})
e1 = {:name=>"DELTA COUNTY 50(J)", :free_and_reduced_price_lunch_rate=>4593, :children_in_poverty_rate=>0.1767305882352941, :high_school_graduation_rate=>0.8325039999999999}
e2 = {:name=>"FOUNTAIN 8", :free_and_reduced_price_lunch_rate=>5170, :children_in_poverty_rate=>0.16549176470588234, :high_school_graduation_rate=>0.8320219999999999}
ha = HeadcountAnalyst.new(dr)
rs = ha.high_poverty_and_high_school_graduation
assert_instance_of ResultSet, rs
assert_equal 2 , rs.matching_districts.count
assert_equal e1, rs.matching_districts.first.econ_data
assert_equal e2, rs.matching_districts.last.econ_data
end
def test_access_data_from_matching_districts
dr = DistrictRepository.new
dr.load_data({
:enrollment => {
:kindergarten => "./data/Kindergartners in full-day program.csv",
:high_school_graduation => "./data/High school graduation rates.csv"},
:economic_profile => {
:median_household_income => "./data/Median household income.csv",
:children_in_poverty => "./data/School-aged children in poverty.csv",
:free_or_reduced_price_lunch => "./data/Students qualifying for free or reduced price lunch.csv"
}
})
ha = HeadcountAnalyst.new(dr)
rs = ha.high_poverty_and_high_school_graduation
assert_equal "DELTA COUNTY 50(J)", rs.matching_districts.first.name
assert_equal 4593, rs.matching_districts.first.free_and_reduced_price_lunch_rate
assert_equal 0.1767305882352941, rs.matching_districts.first.children_in_poverty_rate
assert_equal 0.8325039999999999, rs.matching_districts.first.high_school_graduation_rate
assert_instance_of ResultEntry, rs.statewide_average
assert_equal 3151, rs.statewide_average.free_and_reduced_price_lunch_rate
assert_equal 0.16491292810457553, rs.statewide_average.children_in_poverty_rate
assert_equal 0.751708, rs.statewide_average.high_school_graduation_rate
end
def test_high_income_disparity
dr = DistrictRepository.new
dr.load_data({
:enrollment => {
:kindergarten => "./data/Kindergartners in full-day program.csv",
:high_school_graduation => "./data/High school graduation rates.csv"},
:economic_profile => {
:median_household_income => "./data/Median household income.csv",
:children_in_poverty => "./data/School-aged children in poverty.csv",
:free_or_reduced_price_lunch => "./data/Students qualifying for free or reduced price lunch.csv"
}
})
ha = HeadcountAnalyst.new(dr)
rs = ha.high_income_disparity
assert_instance_of ResultSet, rs
end
def test_high_income_disparity_can_access_matching_district_data
dr = DistrictRepository.new
dr.load_data({
:enrollment => {
:kindergarten => "./data/Kindergartners in full-day program.csv",
:high_school_graduation => "./data/High school graduation rates.csv"},
:economic_profile => {
:median_household_income => "./data/Median household income.csv",
:children_in_poverty => "./data/School-aged children in poverty.csv",
:free_or_reduced_price_lunch => "./data/Students qualifying for free or reduced price lunch.csv"
}
})
e1 = {:name=>"HINSDALE COUNTY RE 1", :median_household_income=>63265, :children_in_poverty_rate=>0.20504235294117648}
e2 = {:name=>"KIT CARSON R-1", :median_household_income=>60633, :children_in_poverty_rate=>0.18687882352941176}
ha = HeadcountAnalyst.new(dr)
rs = ha.high_income_disparity
assert_equal 2, rs.matching_districts.count
assert_equal e1, rs.matching_districts.first.econ_data
assert_equal e2, rs.matching_districts.last.econ_data
assert_equal "HINSDALE COUNTY RE 1", rs.matching_districts.first.name
assert_equal 63265, rs.matching_districts.first.median_household_income
assert_equal 0.20504235294117648, rs.matching_districts.first.children_in_poverty_rate
assert_instance_of ResultEntry, rs.statewide_average
assert_equal 57408, rs.statewide_average.median_household_income
assert_equal 0.16491292810457553, rs.statewide_average.children_in_poverty_rate
end
def test_kindergarten_participation_against_household_income
dr = DistrictRepository.new
dr.load_data({
:enrollment => {
:kindergarten => "./data/Kindergartners in full-day program.csv",
:high_school_graduation => "./data/High school graduation rates.csv"},
:economic_profile => {
:median_household_income => "./data/Median household income.csv",
:children_in_poverty => "./data/School-aged children in poverty.csv",
:free_or_reduced_price_lunch => "./data/Students qualifying for free or reduced price lunch.csv"
}
})
ha = HeadcountAnalyst.new(dr)
assert_equal 0.502, ha.kindergarten_participation_against_household_income("ACADEMY 20")
end
def test_kindergarten_participation_correlates_with_household_income
dr = DistrictRepository.new
dr.load_data({
:enrollment => {
:kindergarten => "./data/Kindergartners in full-day program.csv",
:high_school_graduation => "./data/High school graduation rates.csv"},
:economic_profile => {
:median_household_income => "./data/Median household income.csv",
:children_in_poverty => "./data/School-aged children in poverty.csv",
:free_or_reduced_price_lunch => "./data/Students qualifying for free or reduced price lunch.csv"
}
})
ha = HeadcountAnalyst.new(dr)
assert ha.kindergarten_participation_correlates_with_household_income(for: 'ACADEMY 20')
end
def test_kindergarten_participation_correlates_with_household_income_for_colorado
dr = DistrictRepository.new
dr.load_data({
:enrollment => {
:kindergarten => "./data/Kindergartners in full-day program.csv",
:high_school_graduation => "./data/High school graduation rates.csv"},
:economic_profile => {
:median_household_income => "./data/Median household income.csv",
:children_in_poverty => "./data/School-aged children in poverty.csv",
:free_or_reduced_price_lunch => "./data/Students qualifying for free or reduced price lunch.csv"
}
})
ha = HeadcountAnalyst.new(dr)
assert ha.kindergarten_participation_correlates_with_household_income(for: 'COLORADO')
end
def test_kindergarten_participation_correlates_with_household_income_statewide
dr = DistrictRepository.new
dr.load_data({
:enrollment => {
:kindergarten => "./data/Kindergartners in full-day program.csv",
:high_school_graduation => "./data/High school graduation rates.csv"},
:economic_profile => {
:median_household_income => "./data/Median household income.csv",
:children_in_poverty => "./data/School-aged children in poverty.csv",
:free_or_reduced_price_lunch => "./data/Students qualifying for free or reduced price lunch.csv"
}
})
ha = HeadcountAnalyst.new(dr)
refute ha.kindergarten_participation_correlates_with_household_income(for: 'STATEWIDE')
end
def test_kindergarten_participation_correlates_with_household_income
dr = DistrictRepository.new
dr.load_data({
:enrollment => {
:kindergarten => "./data/Kindergartners in full-day program.csv",
:high_school_graduation => "./data/High school graduation rates.csv"},
:economic_profile => {
:median_household_income => "./data/Median household income.csv",
:children_in_poverty => "./data/School-aged children in poverty.csv",
:free_or_reduced_price_lunch => "./data/Students qualifying for free or reduced price lunch.csv"
}
})
ha = HeadcountAnalyst.new(dr)
refute ha.kindergarten_participation_correlates_with_household_income(:across => ['ACADEMY 20', 'YUMA SCHOOL DISTRICT 1', 'WILEY RE-13 JT', 'SPRINGFIELD RE-4'])
end
end
|
# # encoding: UTF-8
#
# require 'spec_helper'
#
# describe Assignment do
# it { should validate_uniqueness_of :assgt_id }
#
# context "Fabricator" do
# subject { Fabricate(:assignment) }
# specify { subject.content.should_not be_nil }
# end
#
# context "converting" do
# describe 'Assignment.import_from_hash' do
# before :each do
# @teacher = Fabricate(:teacher, login: 'abramsj')
# @hash = {content: "This is some content", teacher_id: 'abramsj'}
# end
#
# it "returns an assignment" do
# expect(Assignment.import_from_hash(@hash)).to be_kind_of Assignment
# end
#
# it "has an author" do
# asst = Assignment.import_from_hash(@hash)
# expect(asst.owner).to eq @teacher
# end
# it "creates a new assignment if the assgt_id is new" do
# expect {
# Assignment.import_from_hash @hash
# }.to change(Assignment, :count).by(1)
# end
# it "updates an assignment if the assgt_id is old" do
# Assignment.import_from_hash @hash
# expect {
# Assignment.import_from_hash @hash
# }.to change(Assignment, :count).by(0)
# end
#
# end
# end
# end
#
# describe Course do
# describe '::import_from_hash' do
# it "imports from a hash" do
# hash = {
# number: 321,
# full_name: "Geometry Honors",
# short_name: "",
# schedule_name: "GeomH",
# semesters: 12,
# credits: 5.0,
# description: "This is the description",
# information: "This is the info",
# policies: "These is the policies",
# resources: "This is the resources",
# news: "This is the news",
# has_assignments:true
# }
# course = Course.import_from_hash hash
# expect(course).to be_kind_of Course
# expect(course.number).to eq 321
# expect(course.full_name).to eq "Geometry Honors"
# expect(course.short_name).to eq ''
# expect(course.schedule_name).to eq "GeomH"
# expect(course.duration).to eq Course::FULL_YEAR
# expect(course.credits).to eq 5.0
# # expect(course.branches.count).to > 0
# expect(course.description.content).to eq "This is the description"
# end
# end
# end
#
# describe SectionAssignment do
# describe 'SectionAssignment.import_from_hash' do
# before :each do
# @hash = {
# :teacher_id=>"davidsonl",
# :year=>"2013",
# :course_num=>"321",
# :block=>"D",
# :due_date=>"2012-09-06",
# :name=>"1",
# :use_assgt=>"Y",
# :assgt_id =>"614639",
# :ada=>"2012-08-19 18:34:40",
# :aa=>"2012-08-19 18:37:16"
# }
# course = Fabricate :course, number: @hash[:course_num]
# Fabricate :assignment, assgt_id: @hash[:assgt_id]
# teacher = Fabricate :teacher, login: @hash[:teacher_id]
# @section = Fabricate :section, year: @hash[:year].to_i, block: @hash[:block], course: course, teacher: teacher
#
# end
#
# it "should create a SectionAssignment if it's new" do
# sa = SectionAssignment.import_from_hash(Hash[@hash])
# expect(sa).to be_kind_of SectionAssignment
# end
#
# it "should update a SectionAssignment if it's old" do
# SectionAssignment.import_from_hash(Hash[@hash])
# @hash[:due_date] = "2012-09-07"
# expect {
# SectionAssignment.import_from_hash(Hash[@hash])
# }.to change(@section.section_assignments.to_a, :count).by(0)
# @hash[:due_date] = "2012-09-08"
# sa = SectionAssignment.import_from_hash(Hash[@hash])
# expect(sa).to be_kind_of SectionAssignment
# expect(sa.due_date).to eq Date.new(2012, 9, 8)
# end
# end
# end
#
# describe Teacher do
# context 'importing' do
# describe '::convert_record' do
# before :each do
# @hash = {
# :default_room=>203, :first_name=>"Joshua", :generic_msg=>"generic message",
# :home_page=>"http://www.westonmath.org/teachers/abramsj/math4/quotes.html",
# :honorific=>"Mr.", :last_name=>"Abrams", :old_current=>1,
# :photo_url=>"http://www.westonmath.org/teachers/abramsj/math4/picture.jpg",
# :phrase=>"this is a password", :login=>"abramsj", :upcoming_msg=>"Upcoming message"}
# @teacher = Teacher.import_from_hash(@hash)
# expect(@teacher).to_not be_nil
# end
#
# it "creates an email address from the teacher_id" do
# expect(@teacher.email).to eq "abramsj@mail.weston.org"
# end
# it "creates a password from the phrase" do
# expect(@teacher.password).to eq "tiap"
# end
# it "sets current from old_current" do
# expect(@teacher.current).to be_true
# end
#
# end
# end
# end
#
# describe Section do
# describe '::import_from_hash' do
# it "creates a section from a hash representing an old record" do
# Fabricate :course, number: 332
# Fabricate :teacher, login: 'davidsonl'
# hash = {:dept_id=>1, :course_num=>332, :number=>4, :semesters=>12, :block=>"G", :year=>2011,
# :which_occurrences=>"all", :room=>200, :teacher_id=>"davidsonl"}
# section = Section.import_from_hash(hash)
# expect(section).to be_kind_of Section
# pending "Unfinished test"
# end
# end
# end
|
class AddDefaultToLikeHits < ActiveRecord::Migration[5.2]
def change
change_column :likes, :hits, :integer, default: 0
end
end
|
require 'rqrcode'
require 'devise/version'
class Devise::TwoFactorAuthenticationController < DeviseController
prepend_before_action :authenticate_scope!
before_action :prepare_and_validate, :handle_two_factor_authentication
before_action :set_qr, only: [:new, :create]
def show
unless resource.otp_enabled
return redirect_to({ action: :new }, notice: I18n.t('devise.two_factor_authentication.totp_not_enabled'))
end
end
def new
if resource.otp_enabled
return redirect_to({ action: :edit }, notice: I18n.t('devise.two_factor_authentication.totp_already_enabled'))
end
end
def edit
end
def create
return render :new if params[:code].nil? || params[:totp_secret].nil?
if resource.confirm_otp(params[:totp_secret], params[:code]) && resource.save
after_two_factor_success_for(resource)
else
set_flash_message :notice, :confirm_failed, now: true
render :new
end
end
def update
return render :edit if params[:code].nil?
if resource.authenticate_otp(params[:code]) && resource.disable_otp
redirect_to after_two_factor_success_path_for(resource), notice: I18n.t('devise.two_factor_authentication.remove_success')
else
set_flash_message :notice, :remove_failed, now: true
render :edit
end
end
def verify
return render :show if params[:code].nil?
if resource.authenticate_otp(params[:code])
after_two_factor_success_for(resource)
else
after_two_factor_fail_for(resource)
end
end
def resend_code
resource.send_new_otp
respond_to do |format|
format.html { redirect_to send("#{resource_name}_two_factor_authentication_path"), notice: I18n.t('devise.two_factor_authentication.code_has_been_sent') }
format.json { head :no_content, status: :ok }
end
end
private
def set_qr
@totp_secret = resource.generate_totp_secret
provisioning_uri = resource.provisioning_uri(nil, otp_secret_key: @totp_secret)
@qr = RQRCode::QRCode.new(provisioning_uri).as_png(size: 250).to_data_url
end
def after_two_factor_success_for(resource)
set_remember_two_factor_cookie(resource)
warden.session(resource_name)[TwoFactorAuthentication::NEED_AUTHENTICATION] = false
# For compatability with devise versions below v4.2.0
# https://github.com/plataformatec/devise/commit/2044fffa25d781fcbaf090e7728b48b65c854ccb
if Devise::VERSION.to_f >= 4.2
bypass_sign_in(resource, scope: resource_name)
else
sign_in(resource_name, resource, bypass: true)
end
set_flash_message :notice, :success
resource.update_attribute(:second_factor_attempts_count, 0)
redirect_to after_two_factor_success_path_for(resource)
end
def set_remember_two_factor_cookie(resource)
expires_seconds = resource.class.remember_otp_session_for_seconds
if expires_seconds && expires_seconds > 0
cookies.signed[TwoFactorAuthentication::REMEMBER_TFA_COOKIE_NAME] = {
value: "#{resource.class}-#{resource.public_send(Devise.second_factor_resource_id)}",
expires: expires_seconds.from_now
}
end
end
def after_two_factor_success_path_for(resource)
stored_location_for(resource_name) || :root
end
def after_two_factor_fail_for(resource)
resource.second_factor_attempts_count += 1
resource.save
set_flash_message :alert, :attempt_failed, now: true
if resource.max_login_attempts?
sign_out(resource)
render :max_login_attempts_reached
else
render :show
end
end
def authenticate_scope!
self.resource = send("current_#{resource_name}")
end
def prepare_and_validate
redirect_to :root and return if resource.nil?
@limit = resource.max_login_attempts
if resource.max_login_attempts?
sign_out(resource)
render :max_login_attempts_reached and return
end
end
end
|
# Die Class 1: Numeric
# I worked on this challenge by myself.
# I spent 3 hours on this challenge.
# 0. Pseudocode
# Input: an integer
# Output: an integer
# Steps:
=begin
1. Start with the class Die. Intialize method by setting the argument sides to the instance variable sides
2. If the argument is less than 1, raise the Argument Error
3. The number can be any random number plus 1 because it has to at least have one side.
=end
# 1. Initial Solution
class Die
def initialize(sides)
@sides = sides
if sides < 1
raise ArgumentError.new ("Numbers greater than 1 required")
end
end
def sides
return @sides
end
def roll
return rand (@sides) + 1
end
end
#p games = Die.new(11)
#p games.roll
# 3. Refactored Solution
# 4. Reflection
=begin
What is an ArgumentError and why would you use one?
- This is an error message that indicates there's something wrong with argument, for example if you try to pass the wrong number of arguments. You would set it up to secure valid arguments for the method in your class.
What new Ruby methods did you implement? What challenges and successes did you have in implementing them?
- I have never used the rand method but found it easily during research. Its perfect application to this challenge gave me to trouble trying to implement it.
What is a Ruby class?
- A Ruby class is a blueprint for creating objects. These objects will inherit traits from the classes that they come from.
Why would you use a Ruby class?
- Ruby classes are necessary ways of organizing all the objects and methods you write so they do not overlap. For example, you should use a class when you want the same method to run on a lot of different objects - this allows you to skip writing if/else statements.
What is the difference between a local variable and an instance variable?
- A local variable can only be used within the method it was defined while the instance variable belongs to an object in which it was created so can be used for multiple methods within that object for that class. It would help to also know that a class variable is one that can be used for a given class (the superclass) and all its subclasses.
Where can an instance variable be used?
- Use an instance variable when you want a variable to for a specific instance of a class.
=end |
class ScrapedDataController < ApplicationController
def index
search = params[:term].present? ? params[:term] : nil
@scraped_data = if search
ScrapedData.search(search, where: where_cond, page: params[:page], per_page: 50)
else
ScrapedData.search("*", where: where_cond, page: params[:page], per_page: 50)
end
end
def autocomplete
render json: ScrapedData.search(params[:query], {
fields: ["url", "domain", "title^5", "keywords", "description",
"author", "twitter_title", "twitter_description", "og_site_name",
"og_title", "og_description"],
match: :word_start,
limit: 10,
load: false,
misspellings: { edit_distance: 10 }
}).map(&:domain)
end
private
def where_cond
my_hash = Hash.new
ScrapedData.columns.each do |column|
if column.type == :boolean
if params[column.name.to_sym].present? && params[column.name.to_sym] == "1"
my_hash[column.name.to_sym] = true
end
end
end
my_hash
end
end
|
require 'spec_helper'
RSpec.describe "#check_transaction" do
let(:reference_no) { CONFIG[:agent_code] + SecureRandom.hex(7) }
it "checks a transaction", vcr: {record: :once} do
client_opts = CONFIG.slice(*%i[host username password eks_path prv_path])
client = EZAPIClient.new(client_opts)
create_transaction_response = client.create_transaction(
reference_no: reference_no,
trans_date: Date.today,
sender_lastname: "Boghossian",
sender_firstname: "Peter",
sender_address1: "Portland",
recipient_lastname: "Harris",
recipient_firstname: "Sam",
recipient_address1: "LA",
recipient_phone: "+63919929199",
trans_type: "CBA",
bank_code: "BDO",
account_no: "100661036243",
landed_currency: "PHP",
landed_amount: 2005.0,
)
response = client.check_transaction(reference_no: reference_no)
expect(["PAID", "IN PROCESS", "PENDING"]).to include(response.code)
expect(response).to be_success
end
end
|
require 'securerandom'
RSpec.shared_context :integration_test_context do
subject(:client) do
ThreeScale::API.new(endpoint: @endpoint, provider_key: @provider_key, verify_ssl: @verify_ssl)
end
before :context do
@endpoint = ENV.fetch('ENDPOINT')
@provider_key = ENV.fetch('PROVIDER_KEY')
@verify_ssl = !(ENV.fetch('VERIFY_SSL', 'true').to_s =~ /(true|t|yes|y|1)$/i).nil?
@apiclient = ThreeScale::API.new(endpoint: @endpoint, provider_key: @provider_key,
verify_ssl: @verify_ssl)
@service_test = @apiclient.create_service('name' => "#{SecureRandom.hex(16)}")
raise @service_test['errors'].to_yaml unless @service_test['errors'].nil?
account_name = SecureRandom.hex(14)
@account_test = @apiclient.signup(name: account_name, username: account_name)
raise @account_test['errors'].to_yaml unless @account_test['errors'].nil?
@application_plan_test = @apiclient.create_application_plan(@service_test['id'], 'name' => "#{SecureRandom.hex(16)}")
raise @application_plan_test['errors'].to_yaml unless @application_plan_test['errors'].nil?
app_id = SecureRandom.hex(14)
@application_test = @apiclient.create_application(@account_test['id'],
plan_id: @application_plan_test['id'],
user_key: app_id)
raise @application_test['errors'].to_yaml unless @application_test['errors'].nil?
@metric_test = @apiclient.create_metric(@service_test['id'],
'friendly_name' => SecureRandom.uuid, 'unit' => 'foo')
raise @metric_test['errors'].to_yaml unless @metric_test['errors'].nil?
@mapping_rule_test = @apiclient.create_mapping_rule(@service_test['id'],
http_method: 'PUT',
pattern: '/',
metric_id: @metric_test['id'],
delta: 2)
raise @mapping_rule_test['errors'].to_yaml unless @mapping_rule_test['errors'].nil?
metrics = @apiclient.list_metrics(@service_test['id'])
raise metrics['errors'].to_yaml if metrics.respond_to?(:has_key?) && metrics['errors'].nil?
@hits_metric_test = metrics.find do |metric|
metric['system_name'] == 'hits'
end
@method_test = @apiclient.create_method(@service_test['id'], @hits_metric_test['id'],
'friendly_name' => SecureRandom.uuid, 'unit' => 'bar')
raise @method_test['errors'].to_yaml unless @method_test['errors'].nil?
end
after :context do
@apiclient.delete_service(@service_test['id']) if !@service_test.nil? && !@service_test['id'].nil?
@apiclient.delete_account(@account_test['id']) if !@account_test.nil? && !@account_test['id'].nil?
end
end
|
class CreateTfgs < ActiveRecord::Migration
def change
create_table :tfgs do |t|
t.string :tema
t.integer :num_orden
t.date :fecha_comienzo
t.timestamps
end
end
end
|
class Tweet
include Mongoid::Document
include Mongoid::Timestamp
field :created_at, type: DateTime
field :text, type: String
end
|
class Product < ActiveRecord::Base
has_many :product_photos
extend FriendlyId
friendly_id :product_slug, use: :slugged
def product_slug
existing_product = Product.where('name = ?', self.name)
if existing_product.present?
"#{name} #{existing_product.count}"
else
"#{name}"
end
end
end
|
require "rails_helper"
RSpec.describe OutgoingMessage, type: :model do
context "validations" do
it { should validate_presence_of(:body) }
end
describe "#to" do
it "gets the contacts phone number" do
contact = build_stubbed(:contact)
conversation = build_stubbed(:conversation, contact: contact)
message = build_stubbed(:outgoing_message, conversation: conversation)
phone_number = message.to
expect(phone_number).to eq(contact.phone_number)
end
end
describe "#from" do
it "gets the users phone number" do
user = build_stubbed(:user_with_number)
conversation = build_stubbed(:conversation, user: user)
message = build_stubbed(:outgoing_message, conversation: conversation)
phone_number = message.from
expect(phone_number).to eq(user.phone_number)
end
end
describe "#update_status" do
it "sets the message status to delivered" do
message = build(:outgoing_message, status: :sent)
message.update_status(double(delivered?: true, failed?: false))
expect(message.status).to eq("delivered")
end
it "sets the message status to failed" do
message = build(:outgoing_message, status: :sent)
message.update_status(double(delivered?: false, failed?: true))
expect(message.status).to eq("failed")
end
it "broadcasts that a message status has changed" do
message = build(:outgoing_message, status: :sent)
expect { message.update_status(double(delivered?: true, failed?: false)) }
.to have_enqueued_job(BroadcastMessageStatusChangedJob)
end
end
end
|
require "sinatra"
require "sinatra/reloader" if development?
require "sinatra/content_for"
require "tilt/erubis"
configure do
enable :sessions
set :session_secret, 'secret'
end
helpers do
def list_complete?(list)
list[:todos].size > 0 && list[:todos].all? { |todo| todo[:completed] }
end
def count_completed(list)
list[:todos].count { |todo| todo[:completed] }
end
def sort_lists_by_completed(lists)
lists.sort_by { |list| list_complete?(list) ? 1 : 0 }
end
def sort_todos_by_completed(todos)
todos.sort_by { |todo| todo[:completed] ? 1 : 0 }
end
def find_original_index(original_array, name)
original_array.index { |element| element[:name] == name }
end
# def sort_lists(lists, &block)
# incomplete_lists = {}
# complete_lists = {}
# lists.each_with_index do |list, index|
# if list_complete?(list)
# complete_lists[list] = index
# else
# incomplete_lists[list] = index
# end
# end
# # incomplete_lists.each( { |id, list| yield list, id})
# # complete_lists.each { |id, list| yield list, id}
# incomplete_lists.each(&block)
# complete_lists.each(&block)
# end
# def sort_lists(lists, &block)
# complete_lists, incomplete_lists = list.partition { |list| list_complete?(list) }
# incomplete_lists.each { |list| yield list, lists.index(list) }
# complete_lists.each { |list| yield list, lists.index(list) }
# end
# def sort_todos(todos, &block)
# incomplete_todos = {}
# complete_todos = {}
# todos.each_with_index do |todo, index|
# if todo[:completed]
# complete_todos[todo] = index
# else
# incomplete_todos[todo] = index
# end
# end
# # incomplete_todos.each( { |id, todo| yield todo, id})
# # complete_todos.each { |id, todo| yield todo, id}
# incomplete_todos.each(&block)
# complete_todos.each(&block)
# end
end
before do
session[:lists] ||= []
end
get "/" do
redirect "/lists"
end
# View list of lists
get "/lists" do
@lists = session[:lists]
erb :lists, layout: :layout
end
# Render the new list form
get "/lists/new" do
erb :new_list, layout: :layout
end
def error_for_list_name(name)
if !(1..100).cover? name.size
"List name must be between 1 and 100 characters."
elsif session[:lists].any? { |list| list[:name] == name }
"List name must be unique."
end
end
def error_for_new_list_name(name)
if !(1..100).cover? name.size
"List name must be between 1 and 100 characters."
end
end
# Create a new list
post "/lists" do
list_name = params[:list_name].strip
error = error_for_list_name(list_name)
if error
session[:error] = error
erb :new_list, layout: :layout
else
session[:lists] << {name: list_name, todos: [] }
session[:success] = "The list has been created"
redirect "/lists"
end
end
post "/lists/:number/destroy" do
number = params[:number].to_i
session[:lists].delete_at(number)
session[:success] = "The list has been deleted"
redirect "/lists"
end
post "/lists/:number/todos" do
@number = params[:number].to_i
@list = session[:lists][@number]
text = params[:todo].strip
error = error_for_new_list_name(text)
if error
session[:error] = error
erb :todos, layout: :layout
else
@list[:todos] << {name: text, completed: false}
session[:success] = "The todo has been added"
redirect "/lists/#{@number}"
end
end
post "/lists/:number/todos/:todo_id/destroy" do
@number = params[:number].to_i
@list = session[:lists][@number]
todo_id = params[:todo_id].to_i
@list[:todos].delete_at(todo_id)
session[:success] = "The todo has been deleted"
redirect "/lists/#{@number}"
end
post "/lists/:number/todos/:todo_id" do
@number = params[:number].to_i
@list = session[:lists][@number]
todo_id = params[:todo_id].to_i
is_completed = params[:completed] == "true"
@list[:todos][todo_id][:completed] = is_completed
session[:success] = "The todo has been updated"
redirect "/lists/#{@number}"
end
# post "/lists/:number/todos/:todo_id" do
# @number = params[:number].to_i
# @list = session[:lists][@number]
# todo_id = params[:todo_id].to_i
# completed = !@list[:todos][todo_id][:completed]
# name = @list[:todos][todo_id][:name]
# @list[:todos].delete_at(todo_id)
# if completed
# @list[:todos] << {name: name, completed: completed}
# else
# @list[:todos].unshift({name: name, completed: completed})
# end
# redirect "/lists/#{@number}"
# end
post "/lists/:number/complete_all" do
@number = params[:number]
@list = session[:lists][@number.to_i]
@list[:todos].each do |todo|
todo[:completed] = true
end
session[:success] = "All todos have been completed"
redirect "/lists/#{@number}"
end
get "/lists/:number/edit" do
@number = params[:number]
@list = session[:lists][@number.to_i]
erb :edit_list, layout: :layout
end
get "/lists/:number" do
@number = params[:number].to_i
@list = session[:lists][@number]
erb :todos, layout: :layout
end
post "/lists/:number" do
list_name = params[:list_name].strip
@number = params[:number].to_i
@list = session[:lists][@number]
error = error_for_list_name(list_name)
if error
session[:error] = error
erb :edit_list, layout: :layout
else
@list[:name] = list_name
session[:success] = "The list has been renamed"
redirect "/lists/#{@number}"
end
end
|
require 'spec_helper'
describe "Tic Tac Toe, in arrays" do
let(:___) { nil }
let(:data) {
[
['X', 'O', 'O'],
['X', 'X', 'O'],
['O', 'X', 'O']
]
}
describe "counting usage per row" do
it "returns how many times X was played in each row" do
xs_per_row = data.map do |array|
array.count("X")
end
expect(xs_per_row).to be == [1, 2, 1]
end
it "returns how many times O was played in each row" do
os_per_row = data.map do |array|
array.count("O")
end
expect(os_per_row).to be == [2, 1, 2]
end
end
describe "getting coordinates of usage" do
it "returns an array of [row, column] array coordinates for each usage of X" do
row=0
empty_x_ary=[]
x_coordinates = empty_x_ary
data.map do |array|
column=0
array.each do |value|
if value=="X"
coordinate=[row,column]
empty_x_ary.push(coordinate)
end
column+=1
end
row+=1
end
expect(x_coordinates).to be == [[0, 0], [1, 0], [1, 1], [2, 1]]
end
it "returns an array of [row, column] array coordinates for each usage of O" do
row=0
empty_o_ary=[]
x_coordinates = empty_o_ary
data.map do |array|
column=0
array.each do |value|
if value=="O"
coordinate=[row,column]
empty_o_ary.push(coordinate)
end
column+=1
end
row+=1
end
expect(x_coordinates).to be == [[0, 1], [0, 2], [1, 2], [2, 0], [2, 2]]
end
end
describe "testing who won" do
it "determines whether X or O won" do
def tic_tac_winner (data)
x_count=0
o_count=0
data.each do |array|
array.each do |value|
if value=="X"
x_count+=1
o_count=0
elsif value=="O"
o_count+=1
x_count=0
end
if x_count==3
return "X"
break
end
if o_count==3
return "O"
break
end
end
end
data.transpose.each do |array|
array.each do |value|
if value=="X"
x_count+=1
o_count=0
elsif value=="O"
o_count+=1
x_count=0
end
if x_count==3
return "X"
break
end
if o_count==3
return "O"
break
end
end
end
end
winner =tic_tac_winner(data)
expect(winner).to be == 'O'
end
end
end
|
Vagrant.configure("2") do |config|
config.vm.box = "generic/debian10"
config.vm.provider "virtualbox" do |vb|
vb.memory = "2048"
vb.cpus = "1"
end
config.vm.provision "ansible" do |ansible|
ansible.become = true
ansible.verbose = "v"
ansible.playbook = "webserver.yml"
ansible.extra_vars = {
chronograph_jar: "./chronograph.jar",
chronograph_config: "./config.edn"
}
end
config.vm.provision "ansible" do |ansible|
ansible.playbook = "test.yml"
end
end
|
require 'rails_helper'
RSpec.describe Citizen, type: :model do
it { should have_one(:address) }
it { should accept_nested_attributes_for(:address) }
it { should validate_presence_of(:full_name) }
it { should allow_value('414.444.908-42').for(:cpf) }
it { should_not allow_value('41444490842').for(:cpf) }
it { should_not allow_value('414.444.908-43').for(:cpf) }
it { should_not allow_value('444').for(:cpf) }
it { should_not allow_value('12345678900').for(:cpf) }
it { should allow_value('55 (11) 12345678').for(:phone) }
it { should allow_value('55 (11) 123456789').for(:phone) }
it { should_not allow_value('55 (11) 1234567890').for(:phone) }
it { should_not allow_value('12345678').for(:phone) }
it { should_not allow_value('123456879').for(:phone) }
it { should allow_value('10/10/1990').for(:birthdate) }
it { should_not allow_value('10-10-1990').for(:birthdate) }
it { should_not allow_value('1990/10/10').for(:birthdate) }
it { should_not allow_value('10/10/2015').for(:birthdate) }
it { should_not allow_value('10/10/1890').for(:birthdate) }
it { should allow_value('fabiomaggilunardelli@gmail.com').for(:email) }
it { should allow_value('fabio@uol.com.br').for(:email) }
it { should_not allow_value('fabio@').for(:email) }
it { should_not allow_value('fabio@gmail').for(:email) }
it { should_not allow_value('fabio').for(:email) }
it { should_not allow_value('fabio@uol').for(:email) }
it { should validate_presence_of(:photo) }
describe '#after_save' do
it 'triggers a callback to notify citizen' do
citizen = build(:citizen)
expect(citizen).to receive(:notify_citizen)
citizen.save
end
end
describe "#notify_citizen" do
it "equeue email" do
ActiveJob::Base.queue_adapter = :test
citizen = create(:citizen)
expect {
citizen.send(:notify_citizen)
}.to have_enqueued_job(ActionMailer::DeliveryJob)
end
it "enqueue sms" do
Rails.stub(env: ActiveSupport::StringInquirer.new("production"))
ActiveJob::Base.queue_adapter = :test
citizen = create(:citizen)
expect {
citizen.send(:notify_citizen)
}.to have_enqueued_job(SendSmsJob)
end
end
describe '.search_data' do
it 'return correct merged attributes' do
citizen = create(:citizen)
expect(citizen.search_data).to eq(citizen.attributes.merge( public_place_from_relation: citizen.public_place_from_relation))
end
end
end |
class Profile < ApplicationRecord
belongs_to :user, optional: true
validates :first_name, presence: true
validates :last_name, presence: true
validates :first_name_kana, presence: true
validates :last_name_kana, presence: true
validates :phone_number, presence: true
validates :zip_code, presence: true
validates :prefecture, presence: true
validates :city, presence: true
validates :address, presence: true
end
|
class MagazineOenologist < ApplicationRecord
belongs_to :magazine
belongs_to :oenologist
end
|
class Links::Game::NhlFaceoffSummary < Links::Base
include Links::Helpers
def site_name
"NHL.com"
end
def description
"Faceoff Summary"
end
def url
"http://www.nhl.com/scores/htmlreports/" \
"#{season}/FC#{game_number_without_year}.HTM"
end
def group
0
end
def position
5
end
end
|
feature "Viewing bookmarks" do
feature "Visiting the homepage" do
scenario "It shows the bookmark button" do
visit '/'
expect(page).to have_content "Bookmark Manager"
end
end
feature "Bookmarks" do
scenario "It shows the the list of bookmarks" do
visit '/bookmarks'
Bookmark.create(url: 'http://www.google.com', title: 'Google')
Bookmark.create(url: 'http://www.youtube.com', title: 'Youtube')
Bookmark.create(url: 'http://www.apple.com', title: 'Apple')
visit '/bookmarks'
expect(page).to have_link('Google', href: "http://www.google.com")
expect(page).to have_link('Youtube', href: "http://www.youtube.com")
expect(page).to have_link('Apple', href: "http://www.apple.com")
end
end
end
|
class AddLatitudeToPostLocation < ActiveRecord::Migration[5.2]
def change
add_column :post_locations, :latitude, :float
end
end
|
# frozen_string_literal: true
require 'spec_helper'
describe Diplomat::Kv do
let(:faraday) { fake }
let(:req) { fake }
context 'keys' do
let(:key) { 'key' }
let(:key_url) { "/v1/kv/#{key}" }
let(:key_params) { 'toast' }
let(:modify_index) { 99 }
let(:valid_acl_token) { 'f45cbd0b-5022-47ab-8640-4eaa7c1f40f1' }
describe '#get' do
context 'Datacenter filter' do
it 'GET' do
kv = Diplomat::Kv.new
stub_request(:get, 'http://localhost:8500/v1/kv/foo?dc=bar')
.to_return(OpenStruct.new(status: 200, body: JSON.generate([])))
kv.get('foo', dc: 'bar')
end
end
context 'ACLs NOT enabled, recurse option ON' do
let(:json) do
JSON.generate(
[
{
'Key' => key + 'dewfr',
'Value' => Base64.encode64(key_params),
'Flags' => 0
},
{
'Key' => key,
'Value' => Base64.encode64(key_params),
'Flags' => 0
},
{
'Key' => key + 'iamnil',
'Value' => nil,
'Flags' => 0
}
]
)
end
it 'GET' do
faraday.stub(:get).and_return(OpenStruct.new(status: 200, body: json))
kv = Diplomat::Kv.new(faraday)
expect(kv.get(key, recurse: true)).to eql(
[
{ key: key + 'dewfr', value: 'toast' },
{ key: key, value: 'toast' }
]
)
end
it 'GET with nil values' do
faraday.stub(:get).and_return(OpenStruct.new(status: 200, body: json))
kv = Diplomat::Kv.new(faraday)
expect(kv.get(key, recurse: true, nil_values: true)).to eql(
[
{ key: key + 'dewfr', value: 'toast' },
{ key: key, value: 'toast' },
{ key: key + 'iamnil', value: nil }
]
)
end
end
context 'ACLs NOT enabled, recurse option ON, blocking' do
let(:json) do
JSON.generate(
[
{
'Key' => key + 'dewfr',
'Value' => Base64.encode64(key_params),
'Flags' => 0
},
{
'Key' => key,
'Value' => Base64.encode64(key_params),
'Flags' => 0
},
{
'Key' => key + 'iamnil',
'Value' => nil,
'Flags' => 0
}
]
)
end
let(:headers) { JSON.generate('x-consul-index' => '12345') }
it 'GET' do
faraday.stub(:get).and_return(OpenStruct.new(headers: headers, status: 200, body: json))
kv = Diplomat::Kv.new(faraday)
allow(kv).to receive_message_chain(:raw, :headers).and_return('x-consul-index' => '12345')
expect(kv.get(key, { recurse: true }, :wait, :wait)).to eql(
[
{ key: key + 'dewfr', value: 'toast' },
{ key: key, value: 'toast' }
]
)
end
it 'GET with nil values' do
faraday.stub(:get).and_return(OpenStruct.new(headers: headers, status: 200, body: json))
kv = Diplomat::Kv.new(faraday)
allow(kv).to receive_message_chain(:raw, :headers).and_return('x-consul-index' => '12345')
expect(kv.get(key, { recurse: true, nil_values: true }, :wait, :wait)).to eql(
[
{ key: key + 'dewfr', value: 'toast' },
{ key: key, value: 'toast' },
{ key: key + 'iamnil', value: nil }
]
)
end
end
context 'ACLs NOT enabled, recurse option ON, convert_to_hash option ON' do
let(:json) do
JSON.generate(
[
{
'Key' => key + '/dewfr',
'Value' => Base64.encode64(key_params),
'Flags' => 0
},
{
'Key' => key,
'Value' => Base64.encode64(key_params),
'Flags' => 0
},
{
'Key' => key + '/iamnil',
'Value' => nil,
'Flags' => 0
},
{
'Key' => 'foo',
'Value' => Base64.encode64('bar'),
'Flags' => 0
}
]
)
end
it 'GET' do
faraday.stub(:get).and_return(OpenStruct.new(status: 200, body: json))
kv = Diplomat::Kv.new(faraday)
answer = {}
answer[key] = {}
answer[key]['dewfr'] = 'toast'
answer['foo'] = 'bar'
expect(kv.get(key, recurse: true, convert_to_hash: true)).to eql(answer)
end
it 'GET with nil values' do
faraday.stub(:get).and_return(OpenStruct.new(status: 200, body: json))
kv = Diplomat::Kv.new(faraday)
answer = {}
answer[key] = {}
answer[key]['dewfr'] = 'toast'
answer[key]['iamnil'] = nil
answer['foo'] = 'bar'
expect(kv.get(key, recurse: true, convert_to_hash: true, nil_values: true)).to eql(answer)
end
context 'single key value' do
let(:json) do
JSON.generate(
[
{
'Key' => key + '/dewfr',
'Value' => Base64.encode64(key_params),
'Flags' => 0
}
]
)
end
it 'GET' do
faraday.stub(:get).and_return(OpenStruct.new(status: 200, body: json))
kv = Diplomat::Kv.new(faraday)
answer = {}
answer[key] = {}
answer[key]['dewfr'] = 'toast'
expect(kv.get(key, recurse: true, convert_to_hash: true)).to eql(answer)
end
end
end
context 'ACLs NOT enabled, keys option ON' do
let(:json) { JSON.generate([key, key + 'ring', key + 'tar']) }
it 'GET' do
faraday.stub(:get).and_return(OpenStruct.new(status: 200, body: json))
kv = Diplomat::Kv.new(faraday)
expect(kv.get(key, keys: true)).to eql([key, key + 'ring', key + 'tar'])
end
end
context 'ACLs NOT enabled, decode_values option ON' do
let(:json) do
JSON.generate(
[
{
'Key' => key + 'dewfr',
'Value' => Base64.encode64(key_params),
'Flags' => 0
},
{
'Key' => key,
'Value' => Base64.encode64(key_params),
'Flags' => 0
},
{
'Key' => key + 'iamnil',
'Value' => nil,
'Flags' => 0
}
]
)
end
it 'GET' do
faraday.stub(:get).and_return(OpenStruct.new(status: 200, body: json))
kv = Diplomat::Kv.new(faraday)
expect(kv.get(key, decode_values: true)).to include('Key' => key, 'Value' => key_params, 'Flags' => 0)
end
end
context 'ACLs NOT enabled, recurse option ON with transformation' do
let(:number) { 1 }
let(:string) { 'x' }
let(:hash) { '{ "x": 1 }' }
let(:json) do
JSON.generate(
[
{
'Key' => key + 'number',
'Value' => Base64.encode64(number.to_s),
'Flags' => 0
},
{
'Key' => key + 'string',
'Value' => Base64.encode64("\"#{string}\""),
'Flags' => 0
},
{
'Key' => key + 'hash',
'Value' => Base64.encode64(hash),
'Flags' => 0
}
]
)
end
it 'GET' do
faraday.stub(:get).and_return(OpenStruct.new(status: 200, body: json))
kv = Diplomat::Kv.new(faraday)
expect(kv.get(key, recurse: true, transformation: proc { |x| JSON.parse("[#{x}]")[0] })).to eql(
[
{ key: key + 'number', value: number },
{ key: key + 'string', value: string },
{ key: key + 'hash', value: { 'x' => 1 } }
]
)
end
end
context 'ACLs NOT enabled' do
let(:json) do
JSON.generate(
[
{
'Key' => key,
'Value' => Base64.encode64(key_params),
'Flags' => 0
}
]
)
end
it 'GET' do
faraday.stub(:get).and_return(OpenStruct.new(status: 200, body: json))
kv = Diplomat::Kv.new(faraday)
expect(kv.get(key)).to eq('toast')
end
it 'GET with consistency param' do
options = { consistency: 'consistent' }
faraday.stub(:get).and_return(OpenStruct.new(status: 200, body: json))
kv = Diplomat::Kv.new(faraday)
expect(kv.get('key', options)).to eq('toast')
end
end
context 'ACLs enabled, without valid_acl_token' do
let(:json) do
JSON.generate(
[
{
'Key' => key,
'Value' => Base64.encode64('Faraday::ResourceNotFound: the server responded with status 404'),
'Flags' => 0
}
]
)
end
it 'GET with ACLs enabled, no valid_acl_token' do
faraday.stub(:get).and_return(OpenStruct.new(status: 200, body: json))
kv = Diplomat::Kv.new(faraday)
expect(kv.get(key)).to eq('Faraday::ResourceNotFound: the server responded with status 404')
end
it 'GET with consistency param, without valid_acl_token' do
options = { consistency: 'consistent' }
faraday.stub(:get).and_return(OpenStruct.new(status: 200, body: json))
kv = Diplomat::Kv.new(faraday)
expect(kv.get('key', options)).to eq('Faraday::ResourceNotFound: the server responded with status 404')
end
end
context 'ACLs enabled, with valid_acl_token' do
let(:json) do
JSON.generate(
[
{
'Key' => key,
'Value' => Base64.encode64(key_params),
'Flags' => 0
}
]
)
end
it 'GET with ACLs enabled, valid_acl_token' do
faraday.stub(:get).and_return(OpenStruct.new(status: 200, body: json))
Diplomat.configuration.acl_token = valid_acl_token
kv = Diplomat::Kv.new(faraday)
expect(kv.get(key)).to eq('toast')
end
it 'GET with consistency param, with valid_acl_token' do
options = { consistency: 'consistent' }
faraday.stub(:get).and_return(OpenStruct.new(status: 200, body: json))
Diplomat.configuration.acl_token = valid_acl_token
kv = Diplomat::Kv.new(faraday)
expect(kv.get('key', options)).to eq('toast')
end
end
end
describe '#get_all' do
context 'normal context' do
it 'GET_ALL' do
kv = Diplomat::Kv.new
stub_request(:get, 'http://localhost:8500/v1/kv/foo?recurse=true')
.to_return(OpenStruct.new(status: 200, body: JSON.generate([])))
kv.get_all('foo')
end
end
context 'datacenter filter' do
it 'GET_ALL for a specific datacenter' do
kv = Diplomat::Kv.new
stub_request(:get, 'http://localhost:8500/v1/kv/foo?dc=bar&recurse=true')
.to_return(OpenStruct.new(status: 200, body: JSON.generate([])))
kv.get_all('foo', dc: 'bar')
end
end
context 'get_all returns no results' do
let(:json) do
JSON.generate([])
end
it 'GET_ALL and returns an empty Array' do
faraday.stub(:get).and_return(OpenStruct.new(status: 200, body: json))
kv = Diplomat::Kv.new(faraday)
expect(kv.get_all(key)).to eql([])
end
end
context 'recursive get returns only a single result' do
let(:json) do
JSON.generate(
[
{
'Key' => key + 'foo',
'Value' => Base64.encode64(key_params),
'Flags' => 0
}
]
)
end
it 'GET_ALL and returns a single item list' do
faraday.stub(:get).and_return(OpenStruct.new(status: 200, body: json))
kv = Diplomat::Kv.new(faraday)
expect(kv.get_all(key)).to eql(
[
{ key: key + 'foo', value: 'toast' }
]
)
end
it 'GET_ALL and returns a hash' do
faraday.stub(:get).and_return(OpenStruct.new(status: 200, body: json))
kv = Diplomat::Kv.new(faraday)
expect(kv.get_all(key, convert_to_hash: true)).to eql(
key + 'foo' => 'toast'
)
end
end
context 'recursive get returns multiple nested results' do
let(:json) do
JSON.generate(
[
{
'Key' => key + 'foo',
'Value' => Base64.encode64(key_params),
'Flags' => 0
},
{
'Key' => key + 'i/am/nested',
'Value' => Base64.encode64(key_params),
'Flags' => 0
},
{
'Key' => key + 'i/am/also/nested',
'Value' => Base64.encode64(key_params),
'Flags' => 0
}
]
)
end
it 'GET_ALL and returns a list' do
faraday.stub(:get).and_return(OpenStruct.new(status: 200, body: json))
kv = Diplomat::Kv.new(faraday)
expect(kv.get_all(key)).to eql(
[
{ key: key + 'foo', value: 'toast' },
{ key: key + 'i/am/nested', value: 'toast' },
{ key: key + 'i/am/also/nested', value: 'toast' }
]
)
end
it 'GET_ALL and returns a hash' do
faraday.stub(:get).and_return(OpenStruct.new(status: 200, body: json))
kv = Diplomat::Kv.new(faraday)
expect(kv.get_all(key, convert_to_hash: true)).to eql(
'keyfoo' => 'toast',
'keyi' => {
'am' => {
'also' => {
'nested' => 'toast'
},
'nested' => 'toast'
}
}
)
end
end
end
describe '#put' do
context 'ACLs NOT enabled' do
it 'PUT' do
faraday.stub(:put).and_return(OpenStruct.new(status: 200, body: "true\n"))
kv = Diplomat::Kv.new(faraday)
expect(kv.put(key, key_params)).to eq(true)
expect(kv.value).to eq(key_params)
end
it 'PUT with CAS param' do
options = { cas: modify_index }
faraday.stub(:put).and_return(OpenStruct.new(status: 200, body: "true\n"))
kv = Diplomat::Kv.new(faraday)
expect(kv.put(key, key_params, options)).to eq(true)
expect(kv.value).to eq(key_params)
end
end
context 'ACLs enabled, without valid_acl_token' do
it 'PUT with ACLs enabled, no valid_acl_token' do
faraday.stub(:put).and_return(OpenStruct.new(status: 200, body: "false\n"))
kv = Diplomat::Kv.new(faraday)
expect(kv.put(key, key_params)).to eq(false)
end
it 'PUT with CAS param, without valid_acl_token' do
options = { cas: modify_index }
faraday.stub(:put).and_return(OpenStruct.new(status: 200, body: "false\n"))
kv = Diplomat::Kv.new(faraday)
expect(kv.put(key, key_params, options)).to eq(false)
end
end
context 'ACLs enabled, with valid_acl_token' do
it 'PUT with ACLs enabled, valid_acl_token' do
faraday.stub(:put).and_return(OpenStruct.new(status: 200, body: "true\n"))
Diplomat.configuration.acl_token = valid_acl_token
kv = Diplomat::Kv.new(faraday)
expect(kv.put(key, key_params)).to eq(true)
expect(kv.value).to eq(key_params)
end
it 'PUT with CAS param' do
options = { cas: modify_index }
faraday.stub(:put).and_return(OpenStruct.new(status: 200, body: "true\n"))
Diplomat.configuration.acl_token = valid_acl_token
kv = Diplomat::Kv.new(faraday)
expect(kv.put(key, key_params, options)).to eq(true)
expect(kv.value).to eq(key_params)
end
end
end
describe '#delete' do
context 'ACLs NOT enabled' do
it 'DELETE' do
faraday.stub(:delete).and_return(OpenStruct.new(status: 200))
kv = Diplomat::Kv.new(faraday)
expect(kv.delete(key).status).to eq(200)
end
end
context 'ACLs NOT enabled, recurse option ON' do
it 'DELETE' do
stub_request(:delete, 'http://localhost:8500/v1/kv/key?recurse=true')
.to_return(OpenStruct.new(status: 200))
kv = Diplomat::Kv.new
expect(kv.delete(key, recurse: true).status).to eq(200)
end
end
context 'ACLs enabled, without valid_acl_token' do
it 'DELETE' do
faraday.stub(:delete).and_return(OpenStruct.new(status: 403))
kv = Diplomat::Kv.new(faraday)
expect(kv.delete(key).status).to eq(403)
end
end
context 'ACLs enabled, with valid_acl_token' do
it 'DELETE' do
faraday.stub(:delete).and_return(OpenStruct.new(status: 200))
Diplomat.configuration.acl_token = valid_acl_token
kv = Diplomat::Kv.new(faraday)
expect(kv.delete(key).status).to eq(200)
end
end
end
describe '#txn' do
before :each do
Diplomat.configuration.acl_token = nil
end
let(:invalid_transaction_format) do
{
'KV' => {
'Verb' => 'get',
'Key' => 'hello/world'
}
}
end
let(:invalid_transaction_verb) do
[
{
'KV' => {
'Verb' => 'invalid_verb'
}
}
]
end
let(:invalid_top_level_key) do
[
{
'kv' => {
'Verb' => 'get',
'Key' => 'hello/world'
}
}
]
end
let(:invalid_requirements) do
[
{
'KV' => {
'Verb' => 'set',
'Key' => 'hello/world'
}
}
]
end
let(:valid_transaction) do
[
{
'KV' => {
'Verb' => 'set',
'Key' => 'test_key',
'Value' => 'test_value'
}
},
{
'KV' => {
'Verb' => 'get',
'Key' => 'hello/world'
}
}
]
end
let(:valid_return) do
{
'Results' => [
{
'KV' => {
'LockIndex' => 0,
'Key' => 'test_key',
'Flags' => 0,
'Value' => nil,
'CreateIndex' => 2_278_133,
'ModifyIndex' => 2_278_133
}
},
{
'KV' => {
'LockIndex' => 0,
'Key' => 'hello/world',
'Flags' => 0,
'Value' => 'SGVsbG8sIHdvcmxkIQ==',
'CreateIndex' => 7_639_434,
'ModifyIndex' => 7_641_028
}
}
],
'Errors' => [
{
'OpIndex' => 6_345_234,
'What' => 'Bad stuff happened'
}
]
}.to_json
end
let(:kv) do
proc do |input, options|
faraday.stub(:put).and_return(OpenStruct.new(body: valid_return, status: 200))
kv = Diplomat::Kv.new(faraday)
kv.txn(input, options)
end
end
let(:rollback_return) do
{
# Results is intentionally missing; this can happen in a rolled back transaction
'Errors' => [
{
'OpIndex' => 1,
'What' => 'failed index check for key "hello/world", current modify index 2 != 1'
}
]
}
end
let(:rollback_kv) do
proc do |input, options|
faraday.stub(:put).and_return(OpenStruct.new(body: rollback_return.to_json, status: 409))
kv = Diplomat::Kv.new(faraday)
kv.txn(input, options)
end
end
context 'transaction format verification' do
it 'verifies transaction format' do
expect { kv.call(invalid_transaction_format, nil) }.to raise_error(Diplomat::InvalidTransaction)
end
it 'verifies transaction verbs' do
expect { kv.call(invalid_transaction_verb, nil) }.to raise_error(Diplomat::InvalidTransaction)
end
it 'verifies top level transaction key' do
expect { kv.call(invalid_top_level_key, nil) }.to raise_error(Diplomat::InvalidTransaction)
end
it 'verifies required transaction parameters' do
expect { kv.call(invalid_requirements, nil) }.to raise_error(Diplomat::InvalidTransaction)
end
end
it 'returns a Hash' do
expect(kv.call(valid_transaction, {})).to be_a_kind_of(OpenStruct)
end
it 'returns arrays as the values' do
return_values = kv.call(valid_transaction, {})
return_values.each_pair do |_, values|
expect(values).to be_a_kind_of(Array)
end
end
it 'returns arrays of Hash objects' do
return_values = kv.call(valid_transaction, {})
return_values.each_pair do |_, values|
values.each do |value|
expect(value).to be_a_kind_of(Hash)
end
end
end
it 'returns with the :dc option' do
dc = 'some-dc'
options = { dc: dc }
expect(faraday).to receive(:put).and_yield(req).and_return(OpenStruct.new(body: valid_return, status: 200))
expect(req).to receive(:url).with("/v1/txn?dc=#{dc}")
kv.call(valid_transaction, options)
end
%w[consistent stale].each do |consistency|
it "returns with the :consistency #{consistency} option" do
options = { consistency: consistency }
expect(faraday).to receive(:put).and_yield(req).and_return(OpenStruct.new(body: valid_return, status: 200))
expect(req).to receive(:url).with("/v1/txn?#{consistency}")
kv.call(valid_transaction, options)
end
end
it 'only responds to \'consistent\' or \'stale\' consistencies' do
options = { consistency: 'bad-value' }
expect(faraday).to receive(:put).and_yield(req).and_return(OpenStruct.new(body: valid_return, status: 200))
expect(req).to receive(:url).with('/v1/txn')
kv.call(valid_transaction, options)
end
it 'returns undecoded options' do
options = { decode_values: false }
expected_return = kv.call(valid_transaction, options)['Results']
expect(expected_return.pop['KV']['Value']).to eq('SGVsbG8sIHdvcmxkIQ==')
end
it 'handles a rollback with missing results section' do
expect(rollback_kv.call(valid_transaction, {}).Errors).to eq(rollback_return['Errors'])
end
end
it 'namespaces' do
faraday.stub(:put).and_return(OpenStruct.new(status: 200, body: "true\n"))
kv = Diplomat::Kv.new(faraday)
expect(kv.put("toast/#{key}", key_params)).to eq(true)
expect(kv.value).to eq(key_params)
end
end
end
|
class DocumentaryControl::SecuritiesController < ApplicationController
before_filter :authenticate_user!, :only => [:index, :new, :create, :edit, :update ]
protect_from_forgery with: :null_session, :only => [:destroy, :delete]
def index
@sec = Security.where("cost_center_id = ?", get_company_cost_center('cost_center').to_s)
render layout: false
end
def show
@sec = Security.where("cost_center_id = ?", get_company_cost_center('cost_center').to_s)
render layout: false
end
def new
@cost_center = get_company_cost_center('cost_center')
@sec = Security.new
render layout: false
end
def create
flash[:error] = nil
sec = Security.new(sec_parameters)
sec.cost_center_id = get_company_cost_center('cost_center')
if sec.save
flash[:notice] = "Se ha creado correctamente."
redirect_to :action => :index
else
sec.errors.messages.each do |attribute, error|
puts flash[:error].to_s + error.to_s + " "
end
@sec = sec
render :new, layout: false
end
end
def edit
@sec = Security.find(params[:id])
@cost_center = get_company_cost_center('cost_center')
@action = 'edit'
render layout: false
end
def update
sec = Security.find(params[:id])
sec.cost_center_id = get_company_cost_center('cost_center')
if sec.update_attributes(sec_parameters)
flash[:notice] = "Se ha actualizado correctamente los datos."
redirect_to :action => :index, company_id: params[:company_id]
else
sec.errors.messages.each do |attribute, error|
flash[:error] = attribute " " + flash[:error].to_s + error.to_s + " "
end
# Load new()
@sec = sec
render :edit, layout: false
end
end
def destroy
sec = Security.destroy(params[:id])
flash[:notice] = "Se ha eliminado correctamente."
render :json => sec
end
private
def sec_parameters
params.require(:security).permit(:name, :description, :document)
end
end |
class Stmt
class Visitor
def visit_expression_statement(stmt);end
def visit_print_statement(stmt);end
def visit_var_statement(stmt);end
def visit_block_statement(stmt);end
def visit_if_statement(stmt);end
def visit_while_statement(stmt);end
def visit_break_statement(stmt);end
def visit_class_statement(stmt);end
def visit_function_statement(stmt);end
def visit_return_statement(stmt);end
end
@@names = {
'Expression' => [:expression],
'Print' => [:expression],
'Var' => [:name, :initializer],
'Block' => [:statements],
'If' => [:condition, :then_branch, :else_branch],
'While' => [:condition, :body],
'Break' => [:break],
'Function' => [:name, :function],
'Return' => [:keyword, :value]
}
Block = Struct.new(*@@names['Block']) do
def accept(visitor)
visitor.visit_block_statement(self)
end
end
Break = Struct.new(*@@names['Break']) do
def accept(visitor)
visitor.visit_break_statement(self)
end
end
Expression = Struct.new(*@@names['Expression']) do
def accept(visitor)
visitor.visit_expression_statement(self)
end
end
Function = Struct.new(*@@names['Function']) do
def accept(visitor)
visitor.visit_function_statement(self)
end
end
If = Struct.new(*@@names['If']) do
def accept(visitor)
visitor.visit_if_statement(self)
end
end
Print = Struct.new(*@@names['Print']) do
def accept(visitor)
visitor.visit_print_statement(self)
end
end
Return = Struct.new(*@@names['Return']) do
def accept(visitor)
visitor.visit_return_statement(self)
end
end
Var = Struct.new(*@@names['Var']) do
def accept(visitor)
visitor.visit_var_statement(self)
end
end
While = Struct.new(*@@names['While']) do
def accept(visitor)
visitor.visit_while_statement(self)
end
end
end |
class CineplexShowtimes::CLI
def call
get_showtime_list
showtime_list
menu
end
# initializes scraper and returns the showtimes array
def get_showtime_list
@showtimes = CineplexShowtimes::Showtimes.showtimes
end
# displays showtime array to CLI
def showtime_list
puts " "
@showtimes.each.with_index(1) {|showtime, index| puts "#{index}. #{showtime.movie[0]}"}
end
# displays menu in CLI
def menu
input = ""
while input != "exit"
puts "\nEnter the number of the movie you would like to know more about, type 'list' to display the list of showtimes again or type 'exit'\n "
input = gets.strip.downcase
if input.to_i > 0
showtime = @showtimes[input.to_i - 1]
puts " "
puts <<~DOC
#{showtime.movie[0]} | #{showtime.runtime}
Rated: "#{showtime.rating}" for #{showtime.rating_description}
Showtimes: #{showtime.time.sort.join(", ")}
Synopsis:
#{showtime.synopsis}
DOC
elsif input == "list"
showtime_list
elsif input == "exit"
goodbye
else
puts "\nUnrecognized command, please enter 'list' or 'exit'\n "
end
end
end
# farewell message when closing the program
def goodbye
puts "\n Thank you for using the Cineplex Showtimes gem, have yourself a great day!\n "
end
end
|
class Rectangle
attr_accessor :length, :width, :area, :x, :y, :diagonal
def initialize(length, width, x = nil, y = nil)
@length = length
@width = width
@area = length * width
@x = x
@y = y
@square_root = length * length + width * width
@diagonal = Math.sqrt(@square_root)
if @x.nil? || @y.nil?
@x = 0
@y = 0
end
end
def move_right
@x += 1
end
def move_up
@y += 1
end
def move_left
@x -= 1
end
def move_down
@y -= 1
end
end
# class Rectangle
# attr_reader :length, :width, :area
# def initialize(length, width)
# @length = length
# @width = width
# @area = length * width
#
# end
# end
#
#
# first_rectangle = Rectangle.new(3, 5)
# second_rectangle = Rectangle.new(4, 6)
# puts first_rectangle.area
# puts second_rectangle.area
|
require 'spec_helper'
describe MembershipObserver do
before (:each) do
@group = Factory(:group)
@group.save!
@user = Factory(:user)
@user.save!
end
it "should put an item in the user feed when a new membership is created (user joins a hub)" do
@group.add_user(@user)
feed_item_count = @group.feed.feed_items.where( :referenced_model_id => @group.id,
:user_id => @user.id, :feed_type => :user_joined_hub
).count
feed_item_count.should == 1
end
it "should put an item in the user feed when a new hub is built" do
@group.add_creator(@user)
feed_item_count = @group.feed.feed_items.where( :referenced_model_id => @group.id,
:user_id => @user.id, :feed_type => :user_built_hub
).count
feed_item_count.should == 1
end
it "should put an item in the user feed when a user leaves a hub" do
@group.add_user(@user)
@group.remove_user(@user)
feed_item_count = @group.feed.feed_items.where( :referenced_model_id => @group.id,
:user_id => @user.id, :feed_type => :user_left_hub
).count
feed_item_count.should == 1
end
it "should put an item in the feed for fellow group members when a user joins / leaves a hub" do
user2 = Factory(:user, :email => Factory.next(:email))
user2.save!
@group.add_creator(@user)
@group.add_user(user2)
feed_item_count = @user.feed.feed_items.where( :referenced_model_id => @group.id,
:user_id => user2.id, :feed_type => :user_joined_hub
).count
feed_item_count.should == 1
end
it "should put an item in the group feed for when a member is banned" do
user2 = Factory(:user, :email => Factory.next(:email))
user2.save!
@group.add_user( @user )
@group.remove_user(@user, :via_ban_by => user2 )
feed_item_count = @group.feed.feed_items.where( :referenced_model_id => @group,
:user_id => @user, :feed_type => :user_banned_from_hub
).count
feed_item_count.should == 1
end
end
|
class DropStravaActivityIdFromCommutingStopReports < ActiveRecord::Migration
def change
remove_column :commuting_stop_reports, :strava_activity_id
end
end
|
require 'spec_helper'
describe Game do
it {should have_many(:decks)}
it {should have_many(:cards)}
it {should belong_to(:user)}
let(:game) {FactoryGirl.create(:game)}
let(:seed) {Seeders::Cards.seed}
it 'should create a new deck on creation' do
previous_count = Deck.count
FactoryGirl.create(:game)
expect(Deck.count).to eql(previous_count + Game::NUMBER_OF_DECKS)
end
it 'should deal cards' do
seed
game.deal
expect(game.player_cards.count).to eql(2)
expect(game.dealer_cards.count).to eql(1)
end
it 'should have initial state of started' do
expect(game.state).to eql('started')
end
context 'aces' do
before(:each) do
seed
aces = Card.all.keep_if {|x| x.value == 'A'}.map{|x| x.id}
nines = Card.all.keep_if {|x| x.value == '9'}.map{|x| x.id}
game.player_cards = [aces[0], nines[0]]
end
it 'will change the value of the ace if your going to bust' do
expect(game.player_score).to eql(20)
game.dealt
game.hit
expect(game.state).to_not eql('finished')
end
end
context 'get winner' do
it 'the dealer wins if the player busts' do
game.stub(:player_score) {22}
game.get_winner
expect(game.winner).to eql('dealer')
end
it 'the player wins if the dealer busts' do
game.stub(:dealer_score) {22}
game.get_winner
expect(game.winner).to eql('player')
end
it 'the player wins if they have a higher score than the dealer' do
game.stub(:player_score) {21}
game.stub(:dealer_score) {17}
game.get_winner
expect(game.winner).to eql('player')
end
it 'the dealer wins if they have a higher score than the player' do
game.stub(:player_score) {17}
game.stub(:dealer_score) {21}
game.get_winner
expect(game.winner).to eql('dealer')
end
it 'should be a tie if they both have the same score' do
game.stub(:player_score) {21}
game.stub(:dealer_score) {21}
game.get_winner
expect(game.winner).to eql('tie')
end
end
context 'scores' do
before(:each) do
seed
kings = Card.all.keep_if {|x| x.value == 'K'}.map{|x| x.id}
game.player_cards = kings[0..1]
game.dealer_cards = kings[2..-1]
end
it 'should calculate the players score' do
expect(game.player_score).to eql(20)
end
it 'should calculate the dealers score' do
expect(game.dealer_score).to eql(20)
end
end
context 'hitting' do
it 'should get a card if not bust' do
seed
game.dealt
game.hit
expect(game.player_cards.count).to eql(1)
end
it 'should finish the game if you go bust' do
seed
game.dealt
game.stub(:player_score) {22}
game.hit
expect(game.state).to eql('finished')
end
end
end
|
require 'spec_helper'
describe CompanyMailer do
let(:sales_lead) { FactoryGirl.create(:sales_lead) }
let(:mail) { CompanyMailer.company_registration_request(sales_lead) }
describe 'Company Registration Request' do
before do
CompanyMailer.company_registration_request(sales_lead).deliver
end
it 'should send an email' do
ActionMailer::Base.deliveries.count.should == 1
end
it 'assigns sales_lead' do
expect(mail.body.encoded).to match(sales_lead.email)
end
end
end
|
Rails.application.routes.draw do
#admin routes
devise_for :admin_users, ActiveAdmin::Devise.config
ActiveAdmin.routes(self)
#application routes
root 'homepage#index'
resources :shops, :only => [:show], :path => :shop
resources :restaurants, :only => [:show], :path => :eat
resources :experiences, :only => [:show], :path => :experience
resources :events, :only => [:show], :path => :play
resources :pdfs, :only => [:show]
get 'directory_pdf', to: 'files#directory_pdf'
get 'sales_pdf', to: 'files#sales_pdf'
get 'index', to: 'homepage#index'
#robot
get 'robots.txt', to: 'files#robots'
#redirects
get 'events', to: 'redirect#to', :id => 'play'
get 'directions', to: 'redirect#to', :id => 'visit'
get 'communityassembled', to: 'static#community'
get 'giveaway', to: 'static#giveaway'
# get 'newsletter', to: 'section#show', :id => 'newsletter'
get 'play', to: 'section#show', :id => 'play'
get 'visit', to: 'section#show', :id => 'visit'
get 'shop', to: 'section#show', :id => 'shop'
get 'eat', to: 'section#show', :id => 'eat'
get 'experience', to: 'section#show', :id => 'experience'
get 'live', to: 'section#show', :id => 'live'
get 'work', to: 'section#show', :id => 'work'
get 'discover', to: 'section#show', :id => 'discover'
get 'communityassembly',to: 'section#show', :id => 'communityassembly'
get 'visit/preferred_partners', to: 'preferred_partners#index'
get 'work/careers', to: 'careers#index'
get 'discover/newsletter-signup', to: 'static#newsletter'
end
|
require 'eb_ruby_client/support/resource'
require 'eb_ruby_client/resource/address'
module EbRubyClient
module Resource
class Venue
include EbRubyClient::Support::Resource
attr_accessor :name, :id, :resource_uri, :latitude, :longitude
contains_one :address
def initialize(data)
set_attributes(data)
set_members(data)
end
def to_data
data = {"venue.name" => name}
address.to_data.inject(data) do |acc, next_pair|
k, v = next_pair
acc["venue.address.#{k}"] = v
acc
end
end
end
end
end
|
# frozen_string_literal: true
class CreateOrders < ActiveRecord::Migration[6.0]
def change
create_table :orders, id: :uuid do |t|
t.integer :price, null: false
t.string :comment
t.integer :status, default: 0, null: false
t.date :delivery_date, null: false
t.string :address, null: false
t.integer :months, default: 1, null: false
t.timestamps
end
end
end
|
require 'miw/view'
module MiW
class ScrollBar < View
autoload :DefaultModel, 'miw/scroll_bar/default_model'
autoload :ExtentBoundsModel, 'miw/scroll_bar/extent_bounds_model'
VALID_ORIENTATION = [:vertical, :horizontal]
RepeatInfo = Struct.new(:dir, :threshold)
def initialize(id, orientation: :vertical, thickness: 16,
model: DefaultModel.new, size: nil, **opts)
unless VALID_ORIENTATION.include? orientation
raise ArgumentError, "invalid orientation specified"
end
super id, **opts
@knob = Rectangle.new(0, 0, 0, 0)
@orientation = orientation
@thickness = thickness
@mouse_in = false
self.model = model
if size
resize_to size
else
if @orientation == :vertical
resize_to @thickness, self.size.height
else
resize_to self.size.width, @thickness
end
end
end
attr_reader :orientaion, :thickness, :model
def model=(m)
@model.delete_observer self if @model
@model = m
@model.add_observer self
update
end
def vertical?
@orientation == :vertical
end
def update
update_knob
invalidate
end
def frame_resized(w, h)
update
end
def draw(rect)
# fill frame
cs = MiW.colors
cairo.move_to 0, 0
cairo.rectangle 0, 0, width, height
if @mouse_in || dragging?
c = cs[:control_inner_background_highlight]
else
c = cs[:control_inner_background]
end
cairo.set_source_color c
cairo.fill_preserve
# stroke frame
c = cs[:control_inner_border]
cairo.set_source_color c
cairo.stroke
# knob
cairo.rectangle @knob.x, @knob.y, @knob.width, @knob.height
cs = MiW.colors
if @mouse_in || dragging?
c = cs[:control_background_highlight]
else
c = cs[:control_background]
end
cairo.set_source_color c
cairo.fill
end
def mouse_down(mx, my, button, status, count)
if button == 1
if vertical?
return unless height > 0
top = @knob.top
bottom = @knob.bottom
mv = my
else
return unless width > 0
top = @knob.left
bottom = @knob.right
mv = mx
end
if mv >= top && mv < bottom
start_dragging mx, my
else
start_repeat_page_scroll(top, mv)
end
end
end
def mouse_moved(mx, my, transit, data)
if vertical?
return unless height > 0
else
return unless width > 0
end
prev = @mouse_in
case transit
when :entered
@mouse_in = true
when :exited
@mouse_in = false
end
invalidate if prev != @mouse_in
if dragging?
px = vertical? ? my : mx
px_delta = px - @drag_start_px
val_delta = px_to_val px_delta
@model.value = align_val @drag_start_val + val_delta
end
end
def mouse_up(mx, my, button, *a)
if button == 1
if dragging?
end_dragging
elsif repeat_page_scroll?
end_repeat_page_scroll
end
invalidate
end
end
def scroll_page(dir)
case dir
when :backward
@model.value = [@model.min, @model.value - @model.proportion].max
when :forward
@model.value = [@model.max - @model.proportion, @model.value + @model.proportion].min
else
return
end
invalidate
end
private
def val_to_px(value)
px_size = vertical? ? height : width
va_size = @model.max - @model.min
if va_size > 0
value * px_size / va_size
else
px_size
end
end
def px_to_val(px)
px_size = vertical? ? height : width
if px_size > 0
px * (@model.max - @model.min) / px_size
else
@model.max
end
end
def update_knob
if vertical?
w = width * 0.6
h = val_to_px @model.proportion
kx = width * 0.2
ky = val_to_px @model.value
else
w = val_to_px @model.proportion
h = height * 0.6
kx = val_to_px @model.value
ky = height * 0.2
end
@knob.offset_to kx, ky
@knob.resize_to w, h
@knob.intersect bounds
end
def start_dragging(mx, my)
grab_input
@drag_start_px = vertical? ? my : mx
@drag_start_val = @model.value
end
def end_dragging
ungrab_input
@drag_start_px = nil
end
def dragging?
@drag_start_px != nil
end
def start_repeat_page_scroll(px, mouse_px)
grab_input
dir = mouse_px < px ? :backward : :forward
threshold = px_to_val mouse_px
@repeat_info = RepeatInfo.new dir, threshold
scroll_page dir
EM.add_timer(0.2, method(:repeat_scroll_page))
end
def end_repeat_page_scroll
ungrab_input
@repeat_info = nil
end
def repeat_page_scroll?
@repeat_info != nil
end
def align_val(val)
if val + @model.proportion > @model.max
val = @model.max - @model.proportion
end
if val < @model.min
val = @model.min
end
if @model.step && @model.step > 1
# todo
m = val % @model.step
val -= m
val += step if m > step / 2
end
val
end
def repeat_scroll_page
if @repeat_info
if (@repeat_info.dir == :forward && @model.value + @model.proportion < @repeat_info.threshold) ||
(@repeat_info.dir == :backward && @model.value > @repeat_info.threshold)
scroll_page @repeat_info.dir
EM.add_timer 0.05, method(:repeat_scroll_page)
end
end
end
end
end
|
class Article < ActiveRecord::Base
acts_as_taggable
versioned #:dependent => :tracking
has_and_belongs_to_many :mailings
attr_accessible :content, :title
validates :content, uniqueness: true, presence: true
validates :title, uniqueness: true, presence: true
# Generate Json format for select2
def to_select2
{ id: self.id, text: self.title.html_safe }
end
end
|
class AddColumnTradeToPersonelDetail < ActiveRecord::Migration[5.2]
def change
add_column :personel_details, :trade, :string
end
end
|
namespace :blacklight do
begin
require 'rspec/core'
require 'rspec/core/rake_task'
desc "Run Blacklight rspec, with test solr"
task :all_tests => :hudson
desc "Run Blacklight rspec, with test solr"
task :hudson do
Rails.env = 'test' unless ENV['RAILS_ENV']
error = Jettywrapper.wrap(Jettywrapper.load_config) do
Rake::Task["blacklight:spec"].invoke
end
raise "test failures: #{error}" if error
end
namespace :all_tests do
task :rcov do
desc "Run Blacklight rspec tests with rcov"
rm "blacklight-coverage.data" if File.exist?("blacklight-coverage.data")
Rails.env = 'test' unless ENV['RAILS_ENV']
error = Jettywrapper.wrap(Jettywrapper.load_config) do
Rake::Task["blacklight:spec:rcov"].invoke
end
raise "test failures: #{error}" if error
end
end
rescue LoadError
desc "Not available! (rspec not avail)"
task :all_tests do
abort 'Not available. Rspec needs to be installed to run blacklight:all_tests'
end
end
end
|
# -*- ruby -*-
require 'rubygems'
require 'hoe'
require './lib/mailtrap.rb'
require './lib/mailshovel.rb'
Hoe.new('mailtrap', Mailtrap::VERSION ) do |p|
p.rubyforge_name = 'simplyruby'
p.author = 'Matt Mower'
p.email = 'self@mattmower.com'
p.summary = 'Mailtrap is a mock SMTP server for use in Rails development'
p.description = p.paragraphs_of('README.txt', 2..5).join("\n\n")
p.url = p.paragraphs_of('README.txt', 0).first.split(/\n/)[1..-1]
p.changes = p.paragraphs_of('History.txt', 0..1).join("\n\n")
p.remote_rdoc_dir = 'mailtrap'
p.extra_deps << ['daemons','>= 1.0.8']
p.extra_deps << ['trollop','>= 1.7']
p.extra_deps << ['tmail','>= 1.2.2']
end
namespace :spec do
desc "Run the specs under spec"
Spec::Rake::SpecTask.new('all') do |t|
t.spec_opts = ['--options', "spec/spec.opts"]
t.spec_files = FileList['spec/**/*_spec.rb']
end
desc "Run the specs under spec in specdoc format"
Spec::Rake::SpecTask.new('doc') do |t|
t.spec_opts = ['--format', "specdoc"]
t.spec_files = FileList['spec/**/*_spec.rb']
end
desc "Run the specs in HTML format"
Spec::Rake::SpecTask.new('html') do |t|
t.spec_opts = ['--format', "html"]
t.spec_files = FileList['spec/**/*_spec.rb']
end
end
desc "Run the default spec task"
task :spec => :"spec:all"
# vim: syntax=Ruby
|
class Code
POSSIBLE_PEGS = {
"R" => :red,
"G" => :green,
"B" => :blue,
"Y" => :yellow
}
attr_reader :pegs
def self.valid_pegs?(chars)
chars.all? { |color| POSSIBLE_PEGS.has_key?(color.upcase) }
end
def self.random(length)
random_pegs = []
length.times { random_pegs << POSSIBLE_PEGS.keys.sample }
Code.new(random_pegs)
end
def self.from_string(string)
Code.new(string.split(""))
end
def initialize(chars)
if !Code.valid_pegs?(chars)
raise "contains invalid peg(s)"
else
@pegs = chars.map(&:upcase)
end
end
def [](index)
@pegs[index]
end
def length
@pegs.length
end
def num_exact_matches(guess_inst)
exact_matches = 0
(0...guess_inst.length).each do |i|
exact_matches += 1 if guess_inst[i] == self[i]
end
exact_matches
end
def num_near_matches(guess_inst)
near_matches = 0
(0...guess_inst.length).each do |i|
near_matches += 1 if self.pegs.include?(guess_inst[i]) && self[i] != guess_inst[i]
end
near_matches
end
def ==(guess_inst)
guess_inst == self.pegs
end
end
|
require 'spec_helper'
describe 'Connect Four' do
describe 'Token' do
it 'initializes to white' do
expect(Game::Token.new.color).to eq('white')
end
describe '#to_c' do
before :each do
@token = Game::Token.new
end
it 'returns a white token' do
expect(@token.to_c).to eq("\u26aa")
end
it 'returns red token' do
@token.color = 'red'
expect(@token.to_c).to eq("\u26d4")
end
it 'returns black token' do
@token.color = 'black'
expect(@token.to_c).to eq("\u26ab")
end
end
end
describe 'Board' do
before :each do
@board = Game::Board.new
end
# tests the initialize and construct methods
it 'initializes an array' do
expect(@board.plastic).to be_an_instance_of(Array)
end
it 'fills the array with arrays' do
confirm = @board.plastic.all? { |x| x.class == Array }
expect(confirm).to be(true)
end
it 'fills the arrays inside the array with Tokens' do
confirm = @board.plastic.all? do |x|
x.all? { |o| o.color == 'white' }
end
expect(confirm).to be(true)
end
end
describe 'Game' do
before :each do
@game = Game.new
end
it 'initializes a board' do
expect(Game.new.board).to be_an_instance_of(Game::Board)
end
describe '#drop_token' do
before :each do
@game = Game.new
end
it 'sets a token to red' do
@game.drop_token('red', 1)
expect(@game.board.plastic[0][0].color).to eq('red')
end
it 'sets a token to black' do
@game.drop_token('black', 1)
expect(@game.board.plastic[0][0].color).to eq('black')
end
it 'returns indices of dropped token' do
@game.drop_token('black', 4)
expect(@game.drop_token('red', 4)).to eq([1,3]) # double check this.
end
it 'sets a token to column 1' do
@game.drop_token('red', 1)
expect(@game.board.plastic[0][0].color).to eq('red')
end
it 'sets a token to column 2' do
@game.drop_token('red', 2)
expect(@game.board.plastic[0][1].color).to eq('red')
end
it 'sets a token to column 3' do
@game.drop_token('red', 3)
expect(@game.board.plastic[0][2].color).to eq('red')
end
it 'sets a token to column 4' do
@game.drop_token('red', 4)
expect(@game.board.plastic[0][3].color).to eq('red')
end
it 'sets a token to column 5' do
@game.drop_token('red', 5)
expect(@game.board.plastic[0][4].color).to eq('red')
end
it 'sets a token to column 6' do
@game.drop_token('red', 6)
expect(@game.board.plastic[0][5].color).to eq('red')
end
it 'sets a token to column 7' do
@game.drop_token('red', 7)
expect(@game.board.plastic[0][6].color).to eq('red')
end
end
it 'validates a good response' do
test = @game.valid?(1)
expect(test).to be(true)
end
it 'validates a bad response - too many tokens' do
6.times { @game.drop_token('red', 1) }
test = @game.valid?(1)
expect(test).to be(false)
end
it 'validates a bad response - column DNE' do
test = @game.valid?(10)
expect(test).to be(false)
end
describe '#winner?(drop_site)' do
describe '#win_helper' do
it 'returns true' do
array = []
2.times do |i|
array << 'red'
end
4.times do |i|
array << 'black'
end
expect(Game.new.win_helper(array, 'black')).to be(true)
end
it 'returns false' do
array = []
3.times do |i|
array << 'red'
end
3.times do |i|
array << 'black'
end
expect(Game.new.win_helper(array, 'black')).to be(false)
end
end
before :each do
@game = Game.new
end
it 'returns false if no adjacent tokens' do
@game.drop_token('red', 1)
@game.drop_token('black',1)
@game.drop_token('black',2)
@game.drop_token('black',2)
expect(@game.winner?([0,0])).to be(false)
end
it 'returns false if no adjacent tokens' do
@game.drop_token('red', 7)
@game.drop_token('black',7)
@game.drop_token('black',6)
@game.drop_token('black',6)
expect(@game.winner?([0,6])).to be(false)
end
it 'returns true if token connects four - ACROSS' do
4.times { |i| @game.drop_token('red', i) }
expect(@game.winner?([1,0])).to be(true)
end
it 'returns true if token connects four - DOWN' do
4.times { @game.drop_token('black', 3) }
expect(@game.winner?([2,3])).to be(true)
end
end
end
end
|
class Users::RegistrationsController < Devise::RegistrationsController
before_action :configure_permitted_parameters
def show
@user = User.find(params[:id])
end
protected
# my custom fields are :name, :last_name
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up) do |u|
u.permit(:name, :last_name,
:email, :password, :password_confirmation)
end
devise_parameter_sanitizer.permit(:account_update) do |u|
u.permit(:name, :last_name,
:email, :password, :password_confirmation, :current_password)
end
end
def after_update_path_for(resource)
user_path(resource)
end
end
|
# input: two arrays (with list of numbers)
# output: new array containing product of every pair of numbers that can be formed between the elements of both arrays, result should be sorted by increasing value
# result array size should be size of argument arrays multiplied
# end result should be sorted in ascending order
# data structure: array
# algo:
# set variable for result as an empty array
# iterate through the first array argument and push subset arrays of each pair combination of elements from both argument arrays into results array (can iterate through another array in real time whilst iterating through the another one)
# calculate the product of each nested array pair in the results array and then flatten
# use sort method to sort in ascending order
def multiply_all_pairs(array1, array2)
pairs_nested_array = []
array1.each do |num1|
array2.each do |num2|
pairs_nested_array << [num1, num2]
end
end
pairs_nested_array.map! do |num1, num2|
num1 * num2
end
pairs_nested_array.sort { |num1, num2| num1 <=> num2}
end
# or
def multiply_all_pairs(array_1, array_2)
products = []
array_1.each do |item_1|
array_2.each do |item_2|
products << item_1 * item_2
end
end
products.sort
end
# or
def multiply_all_pairs(array_1, array_2)
array_1.product(array_2).map { |num1, num2| num1 * num2 }.sort
end |
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
# Artists
Artist.destroy_all
eminem = Artist.create(name: "Eminem", bio: "American rapper, record producer and actor Eminem was born Marshall Bruce Mathers III on October 17, 1972, in St. Joseph, Missouri. He never knew his father, Marshall Mathers Jr., who abandoned the family when Eminem was still an infant and rebuffed all of his son's many attempts to contact him during his childhood.")
sade = Artist.create(name: "Sade", bio: "Helen Folasade Adu, CBE, known professionally as Sade Adu or simply Sade, is a British Nigerian singer, songwriter, and actress.")
skepta = Artist.create(name: "Skepta", bio: "Joseph Junior Adenuga, better known by his stage name Skepta, is an English rapper, songwriter, record producer and music video director from Tottenham, North London")
marvin_gaye = Artist.create(name: "Marvin Gaye", bio: "Marvin Pentz Gaye was an American singer, songwriter and record producer. Gaye helped to shape the sound of Motown in the 1960s, first as an in-house session player and later as a solo artist")
#Genres
Genre.destroy_all
soul = Genre.create(name: "Soul")
grime = Genre.create(name: "Grime")
rap = Genre.create(name: "Rap")
#Songs
Song.destroy_all
Song.create(name: "My Name Is", artist: eminem, genre: rap)
Song.create(name: "Lucky You", artist: eminem, genre: rap)
Song.create(name: "What's Going On?", artist: marvin_gaye, genre: soul)
Song.create(name: "Got To Give It Up", artist: marvin_gaye, genre: soul)
Song.create(name: "Pure Water", artist: skepta, genre: grime)
Song.create(name: "That's Not Me", artist: skepta, genre: grime)
# Song.create(name: "My name is", artist_id: 1, genre_id: 3)
# Song.create(name: "My name is", artist_id: eminem.id, genre_id: rap.id )
|
class Admin::ExternalFeedsController < AdminController
def index
@external_feeds = ExternalFeed.all
end
end |
# The ResponseDomainCode is based on the CodeDomain model from DDI3.X and serves as creates a
# response domain for a {CodeList}
#
# Using the min_responses and max_responses properties cardinality can be recorded.
#
# Please visit http://www.ddialliance.org/Specification/DDI-Lifecycle/3.2/XMLSchema/FieldLevelDocumentation/schemas/datacollection_xsd/elements/CodeDomain.html
#
# === Properties
# * Min Responses
# * Max Responses
class ResponseDomainCode < ApplicationRecord
# This model has all the standard {ResponseDomain} features from DDI3.X
include ResponseDomain
# All ResponseDomainCodes must belong to a {CodeList}
belongs_to :code_list
# Before creating a ResponseDomainCode in the database ensure the instrument has been set
before_create :set_instrument
# RDCs do not have their own label, so it is delagated to the {CodeList} it belongs to
delegate :label, to: :code_list
validates :min_responses, :max_responses, presence: true, numericality: { only_integer: true, allow_blank: true }
# Returns basic information on the response domain's codes
#
# @return [Array] List of codes as hashes
def codes
self.code_list.codes.includes(:code_list).map do |x|
{
label: x.category.label,
value: x.value,
order: x.order
}
end
end
private # private methods
# Sets instrument_id from the {CodeList} that this ResponseDomainCode belongs to
def set_instrument
self.instrument_id = code_list.instrument_id
end
end
|
class MarketCoinSerializer < ActiveModel::Serializer
attributes :id, :symbol, :code, :name, :coin_name, :full_name, :logo_url,
:market_cap, :price, :day_open, :day_high, :day_low, :all_time_high,
:rank, :price_variation, :day_high_variation, :day_low_variation
def price_variation
(object.price / object.day_open - 1).to_f
end
def day_high_variation
(object.day_high / object.day_open - 1).to_f
end
def day_low_variation
(object.day_low / object.day_open - 1).to_f
end
end
|
require "test_helper"
class FluentGemTest < ActiveSupport::TestCase
data("no arguments" => [],
"1 argument" => ["plugin-foo"],
"2 arguments" => ["plugin-foo", "--no-document"])
test "install" do |args|
if args.empty?
mock(FluentGem).run("install")
FluentGem.install
else
mock(FluentGem).run("install", *args)
FluentGem.install(*args)
end
end
data("no arguments" => [],
"1 argument" => ["plugin-foo"],
"2 arguments" => ["plugin-foo", "--no-document"])
test "uninstall" do |args|
if args.empty?
mock(FluentGem).run("uninstall")
FluentGem.uninstall
else
mock(FluentGem).run("uninstall", *args)
FluentGem.uninstall(*args)
end
end
data("no list" => "",
"some lines" => <<-GEM_LIST.strip_heredoc)
dummy (3.3.3)
fluent-plugin-foo (0.1.2)
more_dummy (0.0.1)
GEM_LIST
test "list" do |gem_list|
stub(FluentGem).gem { "gem" }
stub(FluentGem).__double_definition_create__.call(:`, "gem list 2>&1") { gem_list }
assert_equal(gem_list.lines.to_a, FluentGem.list)
end
sub_test_case("run") do
test "success" do
stub(FluentGem).gem { "gem" }
args = ["install", "foobar"]
stub(FluentGem).system("gem", *args) { true }
assert_true(FluentGem.run(*args))
end
test "failure" do
stub(FluentGem).gem { "gem" }
args = ["install", "foobar"]
stub(FluentGem).system("gem", *args) { false }
assert_raise(FluentGem::GemError) do
FluentGem.run(*args)
end
end
end
sub_test_case "gem" do
test "any instance not setup yet" do
assert_equal("fluent-gem", FluentGem.gem)
end
test "fluentd setup" do
stub(Fluentd).instance { Fluentd.new(id: nil, variant: "fluentd_gem", log_file: "dummy.log", pid_file: "dummy.pid", config_file: "dummy.conf") }
assert_equal("fluent-gem", FluentGem.gem)
end
test "td-agent 3 setup" do
stub(Fluentd).instance { Fluentd.new(id: nil, variant: "td_agent", log_file: "dummy.log", pid_file: "dummy.pid", config_file: "dummy.conf") }
assert_equal(FluentGem.detect_td_agent_gem, FluentGem.gem)
end
end
end
|
require 'test/test_helper'
class StateTest < ActiveSupport::TestCase
should_belong_to :country
should_have_many :cities
should_have_many :locations
def setup
@us = Factory(:us)
end
context "state" do
context "illinos" do
setup do
@il = State.create(:name => "Illinois", :code => "IL", :country => @us)
end
should_change("State.count", :by => 1) { State.count }
should "have to_s method return Illinois" do
assert_equal "Illinois", @il.to_s
end
should "have to_param method return il" do
assert_equal "il", @il.to_param
end
end
end
end
|
require('rspec')
require('teams')
require('members')
describe(Team) do
before() do
Team.clear()
end
describe('#teamname') do
it('returns the name of the team') do
test_team = Team.new({:teamname => 'testname', :description => 'testdescription'})
expect(test_team.teamname()).to(eq('testname'))
end
end
describe('#description') do
it('returns the description of the team') do
test_team = Team.new({:teamname => 'testname', :description => 'testdescription'})
expect(test_team.description()).to(eq('testdescription'))
end
end
describe('.all') do
it('@@teams empty at first') do
expect(Team.all()).to(eq([]))
end
end
describe('#saveteam') do
it('saves the team to @@team') do
test_team = Team.new({:teamname => 'testname', :description => 'testdescription'})
test_team.saveteam()
expect(Team.all()).to(eq([test_team]))
end
end
describe('.clear') do
it('clears @@team') do
test_team = Team.new({:teamname => 'testname', :description => 'testdescription'})
test_team.saveteam()
Team.clear()
expect(Team.all()).to(eq([]))
end
end
describe('.findteam') do
it('finds the team based on its unique id') do
test_team = Team.new({:teamname => 'testname', :description => 'testdescription'})
test_team.saveteam()
expect(Team.findteam(test_team.id)).to(eq(test_team))
end
end
describe('#addmember') do
it('adds a member to a specific team') do
test_member = Member.new({:membername => 'kevin', :membertype => 'engineer'})
test_member.savemember()
test_team = Team.new(:teamname => 'testname', :description => 'testdescription')
test_team.saveteam()
test_team.addmember(test_member)
expect(test_team.members).to(eq([test_member]))
end
end
#
# describe('.deletemember') do
# it('deletes a member from a specific team') do
# test_member = Member.new({:membername => 'kevin', :membertype => 'engineer'})
# test_member.savemember()
# test_member2 = Member.new({:membername => 'ian', :membertype => 'engineer'})
# test_member.savemember()
# test_team = Team.new(:teamname => 'testname', :description => 'testdescription')
# test_team.saveteam()
# test_team.addmember(test_member)
# test_team.addmember(test_member2)
# test_team.deletemember(test_member.memberid)
# end
# end
end
|
GeoNames.configure do |config|
config.username = Rails.application.credentials.geonames_api[:username]
end
|
require "mengpaneel/call_proxy"
require "mengpaneel/replayer"
require "mengpaneel/flusher"
module Mengpaneel
class Manager
MODES = %w(before_setup setup tracking).map(&:to_sym).freeze
attr_reader :controller
attr_reader :mode
attr_accessor :flushing_strategy
def initialize(controller = nil, &block)
@controller = controller
@mode = :tracking
wrap(&block) if block
end
def wrap(&block)
replay_delayed_calls
if block.arity == 1
yield(self)
else
yield
end
ensure
flush_calls
end
def call_proxy
call_proxies[@mode]
end
alias_method :mixpanel, :call_proxy
def clear_calls(mode = @mode)
call_proxies.delete(mode)
end
def all_calls
Hash[call_proxies.map { |mode, call_proxy| [mode, call_proxy.all_calls] }]
end
def with_mode(mode, &block)
original_mode = @mode
@mode = mode
begin
if block.arity == 1
yield(mixpanel)
else
yield
end
ensure
@mode = original_mode
end
end
def before_setup(&block)
with_mode(:before_setup, &block)
end
def setup(&block)
clear_calls(:setup)
with_mode(:setup, &block)
end
def tracking(&block)
with_mode(:tracking, &block)
end
def setup?
call_proxies[:setup].all_calls.length > 0
end
def replay_delayed_calls
Replayer.new(self).run
end
def flush_calls
Flusher.new(self).run
end
private
def call_proxies
@call_proxies ||= Hash.new { |proxies, mode| proxies[mode] = CallProxy.new }
end
end
end |
class DestinationsController < ApplicationController
before_action :get_dest, only: [:show,:edit,:update]
def index
@destinations = Destination.all
end
def show
@last_five_posts = @destination.posts.order(created_at: :desc).limit(5)
@initial = 0
@destination.bloggers.each do |blogger| (
@initial += blogger.age
)
end
@avg_age = @initial / @destination.bloggers.count
# redirect_to @destination
end
private
def get_dest
@destination = Destination.find(params[:id])
end
end |
# == Schema Information
#
# Table name: new_project_requests
#
# id :bigint not null, primary key
# status :integer
# created_at :datetime not null
# updated_at :datetime not null
# project_id :bigint not null
# user_id :bigint not null
#
# Indexes
#
# index_new_project_requests_on_project_id (project_id)
# index_new_project_requests_on_user_id (user_id)
#
# Foreign Keys
#
# fk_rails_... (project_id => projects.id)
# fk_rails_... (user_id => users.id)
#
class NewProjectRequest < ApplicationRecord
belongs_to :users
belongs_to :projects
enum status: %w(pending counteroffer accepted declined)
SPECIALTY = ["Business Development", "Account Management", "Sales", "Web-Development", "Recruitment"]
PAY = ["Per Hour", "Project Based", "Monthly", "Commission Based" ]
EMPTYPE = ["Full Time", "Part Time", "Contractor"]
end
|
require 'rails_helper'
require 'capybara/rspec'
RSpec.describe Comment, type: :model do
context 'Comment associations tests' do
it { should belong_to(:user) }
it { should belong_to(:post) }
end
end
|
FactoryGirl.define do
factory :dummy_module_target,
:class => Dummy::Module::Target,
:traits => [
:metasploit_model_base,
:metasploit_model_module_target
] do
ignore do
# have to use module_type from metasploit_model_module_target trait to ensure module_instance will support
# module targets.
module_class { FactoryGirl.create(:dummy_module_class, module_type: module_type) }
end
module_instance {
# module_instance MUST be built because it will fail validation without targets
FactoryGirl.build(
:dummy_module_instance,
module_class: module_class,
# disable module_instance factory's after(:build) from building module_targets since this factory is already
# building it and if they both build module_targets, then the validations will detect a mismatch.
targets_length: 0
)
}
after(:build) { |dummy_module_target, evaluator|
[:architecture, :platform].each do |infix|
attribute = "target_#{infix.to_s.pluralize}"
factory = "dummy_module_target_#{infix}"
length = evaluator.send("#{attribute}_length")
# factories add selves to associations on dummy_module_target
FactoryGirl.build_list(
factory,
length,
module_target: dummy_module_target
)
end
module_instance = dummy_module_target.module_instance
unless module_instance.targets.include? dummy_module_target
module_instance.targets << dummy_module_target
end
}
end
end |
class SaleDetail < ActiveRecord::Base
belongs_to :sale
belongs_to :product
validates :quantity, :price, :total, :product_id, presence: true
end
|
require 'jiffy'
# rubocop:disable Metrics/BlockLength
def valid_tf?
`terraform init`
`terraform validate`
return true
rescue StandardError
false
end
describe Commands::Base do
describe '#initialize' do
context 'with basic node and global configurations' do
before do
test_conf = %(
name: jiffy-test
flavor: generic
pass_hash: $1$GlI5CHXg$VtEtQUo/CJto0Q5MbIXaB1
memory: 1024
vcpu: 1
)
@base = Commands::Base.new(test_conf, false, false, false)
File.write('test.tf', @base.tf_conf)
end
it 'parses YAML correctly' do
expect(@base.conf).to match(
'flavor' => 'generic',
'memory' => 1024,
'vcpu' => 1,
'name' => 'jiffy-test',
'pass_hash' => '$1$GlI5CHXg$VtEtQUo/CJto0Q5MbIXaB1'
)
end
it 'generates a valid terraform config' do
expect(valid_tf?).to be true
end
end
context 'with a base image' do
before do
test_conf = %(
name: jiffy-test
flavor: generic
pass_hash: $1$GlI5CHXg$VtEtQUo/CJto0Q5MbIXaB1
memory: 1024
vcpu: 1
image:
location: /test_dir/test.qcow2
user: root
password: debbase
id: debian9-base
)
@base = Commands::Base.new(test_conf, false, false, false)
File.write('test.tf', @base.tf_conf)
end
it 'parses YAML correctly' do
expect(@base.conf).to match(
'flavor' => 'generic',
'memory' => 1024,
'vcpu' => 1,
'name' => 'jiffy-test',
'pass_hash' => '$1$GlI5CHXg$VtEtQUo/CJto0Q5MbIXaB1',
'image' => {
'location' => '/test_dir/test.qcow2',
'user' => 'root',
'password' => 'debbase',
'id' => 'debian9-base'
}
)
end
it 'generates a valid terraform config' do
expect(valid_tf?).to be true
end
end
context 'with a nat network' do
before do
test_conf = %(
name: jiffy-test
flavor: generic
pass_hash: $1$GlI5CHXg$VtEtQUo/CJto0Q5MbIXaB1
memory: 1024
vcpu: 1
network:
mode: nat
addresses: 192.168.0.0/24
id: default
)
@base = Commands::Base.new(test_conf, false, false, false)
File.write('test.tf', @base.tf_conf)
end
it 'parses YAML correctly' do
expect(@base.conf).to match(
'flavor' => 'generic',
'memory' => 1024,
'vcpu' => 1,
'name' => 'jiffy-test',
'pass_hash' => '$1$GlI5CHXg$VtEtQUo/CJto0Q5MbIXaB1',
'network' => {
'mode' => 'nat',
'addresses' => '192.168.0.0/24',
'id' => 'default'
}
)
end
it 'generates a valid terraform config' do
expect(valid_tf?).to be true
end
end
end
end
# rubocop:enable Metrics/BlockLength
|
$:.push File.expand_path("lib", __dir__)
# Maintain your gem's version:
require "secure_api/version"
Gem::Specification.new do |spec|
spec.name = "secure_api"
spec.version = SecureApi::VERSION
spec.authors = ["david metta"]
spec.email = ["davideliemetta@gmail.com"]
spec.summary = "API Auth framework for Rails"
spec.description = "Tiny JWT-based Authenticaton framework for RoR API's"
spec.homepage = "https://github.com/davidmetta/secure_api"
spec.license = "MIT"
spec.required_ruby_version = Gem::Requirement.new(">= 2.3.0")
spec.metadata["allowed_push_host"] = "https://rubygems.org"
spec.metadata["homepage_uri"] = spec.homepage
spec.metadata["source_code_uri"] = "https://github.com/davidmetta/secure_api.git"
# spec.metadata["changelog_uri"] = ""
# spec.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.md"]
# spec.files = Dir.chdir(File.expand_path('..', __FILE__)) { `git ls-files -z`.split("\x0") }
# spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.start_with?('test/') }
spec.test_files = `git ls-files -z`.split("\x0").select { |f| f.start_with?('test/') }
spec.bindir = "bin"
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_dependency 'jwt', '~> 2.2.2'
spec.add_dependency "rails", "~> 6.0.3", ">= 6.0.3.4"
spec.add_development_dependency "pg", '~> 1.2.3'
end
|
require "pry"
def game_hash
{
home: {
team_name: "Brooklyn Nets",
colors: ["Black", "White"],
players: {
"Alan Anderson" => {
number: 0,
shoe: 16,
points: 22,
rebounds: 12,
assists: 12,
steals: 3,
blocks: 1,
slam_dunks: 1
},
"Reggie Evans" => {
number: 30,
shoe: 14,
points: 12,
rebounds: 12,
assists: 12,
steals: 12,
blocks: 12,
slam_dunks: 7
},
"Brook Lopez" => {
number: 11,
shoe: 17,
points: 17,
rebounds: 19,
assists: 10,
steals: 3,
blocks: 1,
slam_dunks: 15
},
"Mason Plumlee" => {
number: 1,
shoe: 19,
points: 26,
rebounds: 12,
assists: 6,
steals: 3,
blocks: 8,
slam_dunks: 5
},
"Jason Terry" => {
number: 31,
shoe: 15,
points: 19,
rebounds: 2,
assists: 2,
steals: 4,
blocks: 11,
slam_dunks: 1
}
}
},
away: {
team_name: "Charlotte Hornets",
colors: ["Turquoise", "Purple"],
players: {
"Jeff Adrien" => {
number: 4,
shoe: 18,
points: 10,
rebounds: 1,
assists: 1,
steals: 2,
blocks: 7,
slam_dunks: 2
},
"Bismak Biyombo" => {
number: 0,
shoe: 16,
points: 12,
rebounds: 4,
assists: 7,
steals: 7,
blocks: 15,
slam_dunks: 10
},
"DeSagna Diop" => {
number: 2,
shoe: 14,
points: 24,
rebounds: 12,
assists: 12,
steals: 4,
blocks: 5,
slam_dunks: 5
},
"Ben Gordon" => {
number: 8,
shoe: 15,
points: 33,
rebounds: 3,
assists: 2,
steals: 1,
blocks: 1,
slam_dunks: 0
},
"Brendan Haywood" => {
number: 33,
shoe: 15,
points: 6,
rebounds: 12,
assists: 12,
steals: 22,
blocks: 5,
slam_dunks: 12
}
}
}
}
end
def num_points_scored(players_name)
game_hash.each do |location, team_data|
team_data[:players].each do |name, stats|
if name == players_name
stats.each do |item, value|
if item == :points
return value
end
end
end
end
end
end
def shoe_size(players_name)
game_hash.each do |location, team_data|
team_data[:players].each do |name, stats|
if name == players_name
stats.each do |item, value|
if item == :shoe
return value
end
end
end
end
end
end
def team_colors(name)
game_hash.each do |location, team_data|
if team_data[:team_name] == name
return team_data[:colors]
end
end
end
def team_names
names = []
game_hash.each do |location, team_data|
names << team_data[:team_name]
end
names
end
def player_numbers(name)
numbers = []
game_hash.each do |location, team_data|
if team_data[:team_name] == name
team_data[:players].each do |name, stats|
numbers << stats[:number]
end
end
end
numbers
end
def player_stats(name)
game_hash.each do |location, team_data|
team_data[:players].each do |player_name, stats|
if player_name == name
return stats
end
end
end
end
def big_shoe_rebounds
shoe_size = nil
rebounds = nil
game_hash.each do |location, team_data|
team_data[:players].each do |player_name, stats|
if shoe_size == nil || shoe_size < stats[:shoe]
shoe_size = stats[:shoe]
rebounds = stats[:rebounds]
end
end
end
rebounds
end
def most_points_scored
player = nil
points = 0
game_hash.each do |location, team_data|
team_data[:players].each do |player_name, stats|
if points < stats[:points]
points = stats[:points]
player = player_name
end
end
end
player
end
def winning_team
team = nil
home_points = 0
away_points = 0
game_hash[:home][:players].each do |name, stats|
home_points += stats[:points]
end
game_hash[:away][:players].each do |name, stats|
away_points += stats[:points]
end
if home_points > away_points
game_hash[:home][:team_name]
else
game_hash[:away][:team_name]
end
end
def player_with_longest_name
name = nil
game_hash.each do |location, team_data|
team_data[:players].each do |player_name, stats|
if name == nil || player_name.length > name.length
name = player_name
end
end
end
name
end
def long_name_steals_a_ton?
num_of_steals = nil
game_hash.each do |location, team_data|
team_data[:players].each do |player_name, stats|
if player_name == player_with_longest_name
num_of_steals = stats[:steals]
end
end
end
game_hash.each do |location, team_data|
team_data[:players].each do |player_name, stats|
if stats[:steals] > num_of_steals
return false
end
end
end
true
end
|
module Frank
class Profile < ActiveRecord::Base
# include Encryption
has_many :entries
has_many :comments
has_many :moods
has_many :love_banks
belongs_to :family
has_many :links, :class_name => 'Frank::Link'
has_and_belongs_to_many :profiles, :class_name => 'Frank::Profile', :join_table => 'frank_links', :foreign_key => 'frank_profile_id', :association_foreign_key => 'to_profile_id'
# has_and_belongs_to_many :source_profiles, :class_name => 'Frank::Profile', :join_table => 'Frank::Links', :foreign_key => 'to_profile_id',
# :association_foreign_key => 'profile_id'
has_many :source_links, :class_name => 'Frank::Link', :foreign_key => 'to_profile_id'
### Validations
# validates :firstname, presence: true
# validates :lastname, presence: true
validates :email, presence: true, uniqueness: { case_sensitive: false }
# Query for entries that the partner has made
# Any entries that have not been included yet in the daily, will be.
# otherwise send the entries since the last entry ID
def partners_entries
last_report_id = 0
last_report_id = last_daily_report_id unless last_daily_report_id.nil?
Entry.where('linked_profile_id =? and received = ? and private = ? and id > ?', id, 't', 'f', last_report_id)
end
### Encryption
# attr_encrypted :email, key: encryption_key, :encode => true
# attr_encrypted :phone, key: encryption_key, :encode => true
### stores the email to uppercase so that searches for the encrypted value are case insensitive
# def email=(value)
# write_attribute(:encrypted_email, value.downcase)
# end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.