text stringlengths 10 2.61M |
|---|
require 'spec_helper'
describe "LogRoutes" do
it do
{ :get => '/freenode/ruby/logs/' }.
should route_to :controller => 'logs', :action => 'index',
:network => 'freenode', :channel => 'ruby'
end
it do
{ :get => '/freenode/ruby/logs.rss' }.
should route_to :controller => 'logs', :action => 'index', :format => 'rss',
:network => 'freenode', :channel => 'ruby'
end
it do
{ :get => '/freenode/ruby/logs/random.txt' }.
should route_to :controller => 'logs', :action => 'random', :format => 'txt',
:network => 'freenode', :channel => 'ruby'
end
it do
{ :get => '/freenode/ruby/logs/search.txt' }.
should route_to :controller => 'logs', :action => 'search', :format => 'txt',
:network => 'freenode', :channel => 'ruby'
end
it do
{ :get => '/freenode/ruby/logs/previous.txt' }.
should route_to :controller => 'logs', :action => 'previous', :format => 'txt',
:network => 'freenode', :channel => 'ruby'
end
it do
{ :post => '/freenode/ruby/logs/' }.
should route_to :controller => 'logs', :action => 'create',
:network => 'freenode', :channel => 'ruby'
end
end
|
# coding: utf-8
lib = File.expand_path('lib', __dir__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'ecraft/extensions/version'
Gem::Specification.new do |spec|
spec.name = 'ecraft-extensions'
spec.version = Ecraft::Extensions::VERSION
spec.authors = ['Tre Kronor']
spec.email = ['team.trekronor@ecraft.com']
spec.summary = 'eCraft Extensions'
spec.description = 'Extension methods for various Ruby classes'
spec.homepage = 'https://github.com/ecraft/ecraft-extensions'
spec.licenses = []
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.bindir = 'exe'
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ['lib']
spec.add_runtime_dependency 'activesupport', '>= 4.0'
spec.add_runtime_dependency 'json', '>= 1.8'
spec.add_development_dependency 'bundler'
spec.add_development_dependency 'coveralls'
spec.add_development_dependency 'guard-rspec', '~> 4.7'
spec.add_development_dependency 'rake'
spec.add_development_dependency 'rspec'
spec.add_development_dependency 'rubocop', '~> 0.51'
spec.add_development_dependency 'simplecov'
spec.add_development_dependency 'yard'
end
|
# .all √
# customer √
# Restaurant √
# rating √
# content √
class Review
@@all = []
attr_writer :review
attr_reader :customer, :restaurant, :content, :rating
def initialize(customer,restaurant,content,rating)
@customer = customer
@restaurant = restaurant
@content = content
@rating = rating
self.class.all << self
end
def self.all
@@all
end
end
|
ActiveAdmin.register Type do
menu parent: "News"
# See permitted parameters documentation:
# https://github.com/activeadmin/activeadmin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters
#
# permit_params :list, :of, :attributes, :on, :model
#
# or
#
# permit_params do
# permitted = [:permitted, :attributes]
# permitted << :other if resource.something?
# permitted
# end
permit_params :name
form do |f|
f.inputs "Type" do
f.input :name
end
f.actions
end
show do |ad|
attributes_table do
row :name
end
end
controller do
# This code is evaluated within the controller class
before_action :checkuser
def checkuser
if (current_user.email == "myhanhqt96@gmail.com")
else
redirect_to root_path, :notice => "You aren't Admin!"
end
end
end
end
|
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
post 'user_token', to: 'user_token#create'
resources :users
resources :visions
resources :goals
resources :sub_goals
resources :categories
resources :tags
resources :taggings
resources :cheers
resources :request_statuses
resources :connections
resources :squads
resources :squad_members
resources :collaborations
resources :projects
resources :project_goals
resources :project_sub_goals
resources :project_members
resources :collaboration_goals
end
|
class CreateUsers < ActiveRecord::Migration[6.0]
def change
create_table :users do |t|
t.string :name , null: false
t.string :email , null: false
t.string :username , null: false
t.string :password_digest, null: false
t.boolean :active , null: false, default: true
t.timestamps null: false
end
end
end
|
# frozen_string_literal: true
require 'spec_helper'
describe Dotloop::Authenticate do
let(:app_id) { 'abc' }
let(:app_secret) { 'secret' }
let(:application) { 'blah' }
subject(:dotloop_auth) { Dotloop::Authenticate.new(app_id: app_id, app_secret: app_secret, application: application) }
describe '#initialize' do
it 'take an app id' do
expect(dotloop_auth).to be_a(Dotloop::Authenticate)
expect(dotloop_auth.app_id).to eq('abc')
end
context 'without application' do
subject(:dotloop_auth) { Dotloop::Authenticate.new(app_id: app_id, app_secret: app_secret) }
it 'default the application name to dotloop' do
expect(dotloop_auth.application).to eq('dotloop')
end
end
it 'take an application name' do
expect(dotloop_auth.application).to eq('blah')
end
it 'take an app secret' do
expect(dotloop_auth.app_secret).to eq('secret')
end
context 'without an app id' do
let(:app_id) { nil }
it 'raise the error' do
expect { dotloop_auth }.to raise_error RuntimeError
end
end
context 'without an app secret' do
let(:app_secret) { nil }
it 'raise the error' do
expect { dotloop_auth }.to raise_error RuntimeError
end
end
end
end
|
class MouseFocus < Draco::System
filter Clickable, Position
def tick(args)
return if entities.nil?
current = world.scene || world
current.filter([Clickable, Position]).each do |entity|
if args.inputs.mouse.point.inside_rect?(entity_rect(entity))
unless entity.components[:focused]
entity.components << Focused.new
world.dispatch(Focus, entity)
end
if args.inputs.mouse.button_left
unless entity.components[:active]
entity.components << Active.new
end
entity.position.y -= 4
else
entity.components.delete(entity.active) if entity.components[:active]
world.dispatch(Click, entity) if args.inputs.mouse.up
end
else
entity.components << Ready.new unless entity.components[:ready]
entity.components.delete(entity.focused) if entity.components[:focused]
entity.components.delete(entity.active) if entity.components[:active]
end
end
end
def entity_rect(e)
[e.position.x, e.position.y, e.size.width, e.size.height]
end
end
|
require 'spec_helper'
module Dustbag
describe Offer do
include_context 'load xml from fixture'
it_behaves_like 'a node'
describe '#condition' do
it { expect(subject.condition).to eq 'New' }
end
describe '#id' do
it { expect(subject.id).to eq 'DZEJaOVZkxOW3bnN9SFvLNIEVwWDB3Y0HBG5zgBQ7jwJI9gANnOgNkJYiwRiuWUAx8GXFAWOjSrH4nrN4grN4gmtpEZHnkVZy4bHkNzvMu2G18d6bykCLQ%3D%3D' }
end
describe '#price' do
it { expect(subject.price).to be_a_kind_of Money }
it { expect(subject.price.format).to eq '$179.62' }
end
describe '#amount_saved' do
it { expect(subject.amount_saved).to be_a_kind_of Money }
it { expect(subject.amount_saved.format).to eq '$0.37' }
end
describe '#availability' do
it { expect(subject.availability).to eq 'Usually ships in 24 hours' }
end
describe '#availability_attributes' do
it { expect(subject.availability_attributes).to be_a_kind_of AvailabilityAttributes }
end
describe '#eligible_for_super_saver_shipping?' do
it { expect(subject.eligible_for_super_saver_shipping?).to be_truthy }
end
describe '#eligible_for_prime?' do
it { expect(subject.eligible_for_prime?).to be_truthy }
end
end
end
|
RSpec.describe "POST /api/v1/votes", type: :request do
let!(:user) { create(:user) }
let(:credentials) { user.create_new_auth_token }
let(:headers) { { HTTP_ACCEPT: "application/json" }.merge!(credentials) }
describe "successfully" do
before do
post "/api/v1/votes",
params: {
jokeId: "db09c5d9659d44448c4da0ae5d321e55",
},
headers: headers
end
it "should respond with 200 status" do
expect(response.status).to eq 200
end
it "should respond with success message" do
expect(response_json["message"]).to eq "Thank's for your vote!"
end
it "should respond with joke_id" do
expect(response_json["joke"]).to have_key "id"
end
it "api responds with the same joke that was sent in the post request" do
expect(response_json["joke"]["id"]).to eq "db09c5d9659d44448c4da0ae5d321e55"
end
end
describe "unsuccessfully" do
before do
post "/api/v1/votes",
params: {
jokeId: "invalid_id",
},
headers: headers
end
it "should respond with 404 status" do
expect(response.status).to eq 404
end
it "should respond with error message" do
expect(response_json["error_message"]).to eq "Sorry, we are not that funny, we don't have that joke!"
end
end
end
|
ActiveAdmin.register CleanupEvent do
permit_params :name, :start_date, :end_date
index do
selectable_column
column :id do |event|
link_to event.id, admin_cleanup_event_path(event)
end
column :name
column :start_date
column :end_date
column :created_at
column :updated_at
column { |event| link_to 'Download Report', "/api/pickups_csv/#{event.id}" }
actions
end
end
|
module Raft
class RpcProvider
def request_votes(_request, _cluster)
raise 'Your RpcProvider subclass must implement #request_votes'
end
def append_entries(_request, _cluster)
raise 'Your RpcProvider subclass must implement #append_entries'
end
def append_entries_to_follower(_request, _node_id)
raise 'Your RpcProvider subclass must implement #append_entries_to_follower'
end
def command(_request, _node_id)
raise 'Your RpcProvider subclass must implement #command'
end
end
class AsyncProvider
def await
raise 'Your AsyncProvider subclass must implement #await'
end
end
end
|
class Answer < ActiveRecord::Base
belongs_to :user
belongs_to :question
has_many :comments, dependent: :destroy
validates :body, presence: true
def user_first_name
user.first_name if user
end
end
|
#!/usr/bin/env ruby
# Write code to search and return all those file names present in a given directory
# (for e.g. C:\>) where the string "Amazon" is present. All the files will be located
# at different folder levels. Also discuss your approach, time and space complexities
# for your solution.
#
# ref: http://www.careercup.com/page?pid=software-engineer-in-test-interview-questions
# I interpret this to mean "Recursively find all files and directories containing a
# particular case sensitive substring in their names."
def find_files(fdir,name,options = {})
a = []
defaults = {case_sensitive: true, ignore_hidden: true}.freeze
options = defaults.merge(options)
Dir.entries(fdir).each do |e|
next if defaults[:ignore_hidden] && e =~ /^\..*?/
f = fdir + File::SEPARATOR + e
m = options[:case_sensitive] ? (e =~ /.*?(#{name}).*?/) : (e =~ /.*?(#{name}).*?/i)
if m
a << f
end
if File.directory?(f) && !(f =~ /\.{1,2}/)
a += find_files(f,name,options)
next
end
end
a
end
fdir = ENV["HOME"]
p find_files(fdir,"mp4",case_sensitive: true)
|
class AddPrecoCompraAndLucroToProduto < ActiveRecord::Migration
def change
add_column :produtos, :preco_compra, :float
add_column :produtos, :lucro, :float
end
end
|
class BufferingLogger::RackBuffer
def initialize(app, logger, transform: nil)
@app, @logger, @transform = app, logger, transform
end
def call(env)
@logger.buffered(transform: @transform) { @app.call(env) }
end
end
|
FactoryGirl.define do
factory :user do
sequence(:name) { |i| "user#{i}" }
password "1111"
status 1
end
factory :invalid_user, class: User do
name ""
password "1111"
status 1
end
end
|
require 'rails_helper'
feature 'Managing structure images', :js do
let!(:user) { create(:user) }
let!(:audit) { create(:audit, user: user) }
let(:test_image_path) do
Rails.root.join('spec', 'fixtures', 'testupload.jpg')
end
before do
signin_as user
click_audit audit.name
end
scenario 'for an audit structure' do
click_section_tab 'Photos'
expect(page).to_not have_css('.thumb img')
upload_photo test_image_path
click_section_tab 'Photos'
expect(page).to have_css('.thumb img', count: 1)
click_delete_image!
click_section_tab 'Photos'
expect(page).to_not have_css('.thumb img')
end
scenario 'for a substructure' do
window_type = create(:audit_strc_type,
name: 'Window',
parent_structure_type: audit.audit_structure.audit_strc_type)
create(:audit_structure,
name: 'My window',
parent_structure: audit.audit_structure,
audit_strc_type: window_type)
visit current_path
click_structure_row 'My window'
click_section_tab 'Photos'
expect(page).to_not have_css('.thumb img')
upload_photo test_image_path
click_section_tab 'Photos'
expect(page).to have_css('.thumb img', count: 1)
click_delete_image!
click_section_tab 'Photos'
expect(page).to_not have_css('.thumb img')
end
scenario 'when the audit is locked' do
audit.update(locked_by: user)
visit current_path
click_section_tab 'Photos'
expect(page).to_not have_field 'Upload image'
expect(page).to_not have_css('.thumb .thumb__delete')
end
def click_delete_image!
find('.thumb img').hover
find('.thumb .thumb__delete').click
end
def upload_photo(path)
execute_script '$(".js-upload-image").css("height", "auto");'
attach_file 'Upload image', path
end
end
|
Rails.application.routes.draw do
require "sidekiq/web"
mount Sidekiq::Web => "/sidekiq"
post "inbound" => "twilio_inbound#create"
get "/", to: redirect("/admin")
scope "/admin" do
root to: "polls#index"
devise_for :users
resources :polls do
resources :poll_choices
end
resources :events
resources :blasts, except: [:destroy, :edit] do
resources :questions
post :deliver
end
resources :users
resources :citizens, only: [:index, :show]
resources :listeners, only: [:index]
resources :lists
end
end
|
# encoding: utf-8
class AssetUploader < CarrierWave::Uploader::Base
# Choose what kind of storage to use for this uploader
storage MARIO_CONFIG['files']['storage'].to_sym
def store_dir
"img"
end
def cache_dir
"#{RAILS_ROOT}/tmp/uploads"
end
end
|
class UsersController < ApplicationController
def index
redirect_to user_path(current_user)
end
def new
#displays new user form, new.html.erb
@user = User.new
end
def create
#takes info from new user form, validates user, generates user, redirects to show
#sets current_user= new created user
@user = User.new(create_params)
if @user.save
session[:user_id] = @user.id
redirect_to root_path
else
render new_user_path
end
end
def show
@user = current_user
@matters = @user.matters.order('updated_at DESC').limit(5)
end
private
def create_params
params.require(:user).permit(:email, :name, :password, :password_confirmation)
end
end
|
module TestHelpers
module JsonTestHelper
def json_response options={}
assert_response options[:expected_response] || :success
JSON.parse response.body, symbolize_names: true
end
end
end
|
class MessageRelayJob < ApplicationJob
queue_as :default
def perform(message)
convo = message.conversation
MessagesChannel.broadcast_to(convo, MessageSerializer.new(message))
end
end
|
class UtilityPolicy < ApplicationPolicy
class Scope < ApplicationPolicy::Scope
def resolve
if user.present?
scope.where(id: user.utilities + user.shared_utilities)
else
scope.none
end
end
end
end
|
##
#6.7 Solo Challange | Create a Game
#Cassi Gallagher
##
##
#Pseudocode
#Get initial word from player 1
#Create a loop that loops as long as the inital word
#Ask player 2 for a guess
#Let player 2 enter a letter
#if the letter == the first letter of guess_word
#shovel that letter into an array
#store that letter in an array
#else
#shovel " _ " into an array
## Attempted to deal with logic on if letter is guessed in the wrong order of the word but still is in the letter - got stalled on that
#While the game is less than the length of the array
#if the player 1 word and the player 2 word is correct
#win!
#else
#lose
## BEGIN GAME LOGIC
class GuessingGame
attr_reader :p1_word, :p2_guess, :p2_word, :guess_count, :p2_guesses, :letter_correct, :right_letter
def initialize
@p1_word = ''
@p2_guess = ''
@p2_word = []
@guess_count = 0
@p2_guesses = false
@letter_correct = []
end
def p1_word_guess
@p1_word = gets.chomp.split('')
end
def p2_guess
@p1_word.map do |letter|
puts "Enter a letter"
@p2_guess = gets.chomp
if @p2_guess == letter
puts "That letter is in the word" #
@p2_word << @p2_guess
@letter_correct << @p2_guess
elsif @p2_guess != letter
puts 'That letter is not in the word'
@letter_correct << " _ "
end
p @letter_correct
end
end
def win_game
if @p1_word.join == @p2_word.join
p "Congratulations - you win the game."
else
p "Well, this is awkward...LOSE"
end
end
end
## BEGIN GAME INTERFACE
puts 'Welcome to WordGuessGame - the game that is definitely not hangman, but totally our own thing'
game = GuessingGame.new
puts "Player 1 Please enter a word"
game.p1_word
puts "Player 2 please guess the word one letter at a time. You get #{game.p1_word_guess.length} guesses"
game.p2_guess
game.win_game
|
Given /^the product "([^\"]*)" exists$/ do |title|
source = Source['sears']
product = Factory :product, :title => title, :source => source
Factory :partner_product, :product => product, :partner_key => product.id, :source => source
end
Given /^the merchant "([^\"]*)" exists$/ do |merchant_title|
source = Source.find_by_short_name('sears_merchants') || Source.create(:name => 'Sears Merchants', :short_name => 'sears_merchants')
Source.clear_cache
merchant = Factory :product, :title => merchant_title, :source => source
Factory :partner_product, :product => merchant, :partner_key => merchant.id, :source => source
end
Given /^the sears merchant source exists$/ do
Source.find_or_create_by_name_and_short_name 'Sears Merchants', 'sears_merchants'
end
Given /^the app has partner review path enabled$/ do
App.stub! :partner_review_path, :return => { :enabled => true }
end
When /^I rate it "([^\"]*)"$/ do |stars|
set_hidden_field "review[stars]", :to => stars.to_i.to_s
end
Given /^the order id params are set to "([^\"]*)"$/ do |oid|
@controller.params[:oid] = oid
end
Then /^the review's order_id should be "([^\"]*)"$/ do |oid|
assert_equal oid, Review.last.order_id
end
|
# encoding: UTF-8
# Copyright 2011-2013 innoQ Deutschland GmbH
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require File.join(File.expand_path(File.dirname(__FILE__)), '../integration_test_helper')
class EditConceptsTest < ActionDispatch::IntegrationTest
setup do
@concept = Concept::SKOS::Base.new.tap do |c|
RDFAPI.devour c, 'skos:prefLabel', '"foo"@en'
c.publish
c.save
end
end
test 'create a new concept version' do
login('administrator')
visit concept_path(@concept, lang: 'de', format: 'html')
assert page.has_button?('Neue Version erstellen'), "Button 'Neue Version erstellen' is missing on concepts#show"
click_link_or_button('Neue Version erstellen')
assert_equal edit_concept_url(@concept, published: 0, lang: 'de', format: 'html'), current_url
visit concept_path(@concept, lang: 'de', format: 'html')
assert !page.has_button?('Neue Version erstellen'), "Button 'Neue Version erstellen' although there already is a new version"
assert page.has_link?('Vorschau der Version in Bearbeitung'), "Link 'Vorschau der Version in Bearbeitung' is missing"
click_link('Vorschau der Version in Bearbeitung')
assert_equal concept_url(@concept, published: 0, lang: 'de', format: 'html'), current_url
end
end
|
#simplest ruby program to read from arduino serial,
#using the SerialPort gem
#(http://rubygems.org/gems/serialport)
require "serialport"
#params for serial port
port_str = "COM3" #may be different for you
baud_rate = 57600
data_bits = 8
stop_bits = 1
parity = SerialPort::NONE
sp = SerialPort.new(port_str, baud_rate, data_bits, stop_bits, parity)
#just read forever
File.open('log.dat', 'wb') do |f|
f.sync = true
f.write("Time|T|Ambient|Boiler|Brewgroup\n")
while true do
begin
c = sp.readline
if(!c.nil?)
l = "#{Time.now.to_f}|#{c}"
puts l
if(c.match(/^T\|/))
f.write(l)
end
end
rescue
puts "no data"
end
end
end
sp.close #see note 1 |
if Rails.env.development?
mail = "#{Rails.root}/config/mail.yml"
if File.exists? mail
YAML.load_file(mail).each { |key, value| ENV[key] = value.to_s }
else
raise "config/mail.yml does not exist"
end
end
|
require "codeclimate-test-reporter"
CodeClimate::TestReporter.configure do |config|
config.path_prefix = "src" #the root of your Rails application relative to the repository root
#config.git_dir = `https://github.com/sheyooo/andela-project.git` #the relative or absolute location of your git root compared to where your tests are run
config.git_dir = `git rev-parse --show-toplevel`.strip
end
CodeClimate::TestReporter.start
require_relative "notes"
RSpec.describe Sheyi::NotesApplication do
it "raises error if no name is supplied" do
expect {Sheyi::NotesApplication.new ""}.to raise_error "No name supplied!"
end
it "raises error if invalid name is supplied" do
expect {Sheyi::NotesApplication.new "\n\n\n\t"}.to raise_error "No name supplied!"
end
it "initialize the app with name" do
expect(Sheyi::NotesApplication.new "Tester").to be_instance_of Sheyi::NotesApplication
end
it "creation note content shouldn't be empty" do
app = Sheyi::NotesApplication.new "Tester"
res = app.create("")
expect(res).to eq nil
end
it "creation note content should return note" do
app = Sheyi::NotesApplication.new "Tester"
res = app.create("Andela")
expect(res).to eq ({author: "Tester", content: "Andela"})
end
it "create function should store in instance var" do
app = Sheyi::NotesApplication.new "Tester"
app.create("new note in var")
expect(app.notes[0]).to eq ({author: "Tester", content: "new note in var"})
end
it "create function should store in instance var more than one note" do
app = Sheyi::NotesApplication.new "Tester"
app.create("new note in var")
app.create("another note in var")
expect(app.notes[0]).to eq ({author: "Tester", content: "new note in var"})
expect(app.notes[1]).to eq ({author: "Tester", content: "another note in var"})
expect(app.notes.length).to eq 2
end
it "edit function should edit appropriately" do
app = Sheyi::NotesApplication.new "Tester"
app.create("new note in var")
app.edit(0, "edited text")
expect(app.notes[0]).to eq ({author: "Tester", content: "edited text"})
end
it "the delete function should delete appropriately" do
app = Sheyi::NotesApplication.new "Tester"
app.create("a note")
app.delete(0)
expect(app.notes.length).to eq 0
end
it "create function should store name in @author var" do
app = Sheyi::NotesApplication.new "Tester"
expect(app.author).to eq "Tester"
end
it "the list function should return empty array if not populated" do
app = Sheyi::NotesApplication.new "Tester"
res = app.list
expect(res).to eq []
end
it "the get function should return nil if not found" do
app = Sheyi::NotesApplication.new "Tester"
res = app.get(0)
expect(res).to eq nil
end
it "the get function should return the string content of the note at an index" do
app = Sheyi::NotesApplication.new "Tester"
app.create("content1")
app.create("content2")
expect(app.get(0)).to eq "content1"
expect(app.get(1)).to eq "content2"
end
it "the list function should list all notes if populated" do
app = Sheyi::NotesApplication.new "Tester"
app.create("nice")
app.create("another")
res = app.list
expect(res).to eq ([{author: "Tester", content: "nice"}, {author: "Tester", content: "another"}])
end
it "the edit function should return nil if index not found" do
app = Sheyi::NotesApplication.new "Tester"
res = app.edit(0, "edit")
expect(res).to eq nil
end
it "the edit function should return nil if new content is empty" do
app = Sheyi::NotesApplication.new "Tester"
app.create("miya")
res = app.edit(0, "")
expect(res).to eq nil
end
it "the edit function should return the new content if index is available and content is not empty" do
app = Sheyi::NotesApplication.new "Tester"
app.create("to be edited")
res = app.edit(0, "new content")
expect(res).to eq "new content"
expect(app.get(0)).to eq "new content"
end
it "the delete function should always return nil" do
app = Sheyi::NotesApplication.new "Tester"
expect(app.delete(0)).to eq nil
end
it "search should return appropriately" do
app = Sheyi::NotesApplication.new "Tester"
app.create("Andela is a beautiful place")
app.create("Welcome is a beautiful place")
matches = app.search("Andela")
expect(matches).to eq [0]
end
it "search should be case insensitive" do
app = Sheyi::NotesApplication.new "Tester"
app.create("Andela is a beautiful place")
app.create("The andela fellowship")
app.create("Welcome is a beautiful place")
matches = app.search("ANDELA")
expect(matches).to eq [0, 1]
end
end |
require 'data_mapper'
class Book
include DataMapper::Resource
property :id, Serial
property :title, String
property :owner, String
property :amazon_description, String, :default => '', :length => 150
property :isbn_13, String, :default => '', :length => 150
property :cover, String, :default => '', :length => 150
property :google_books_description, String, :default => '', :length => 150
def == another_book
@title==another_book.title and @owner==another_book.owner
end
end
|
class User < ApplicationRecord
has_secure_password
has_secure_token
validates :email, presence: true,
uniqueness: { case_sensitive: false },
format: { with: VALID_EMAIL_REGEX }
validates :password, :password_confirmation,
presence: true, confirmation: true, length: { minimum: 6 }, on: :create
def generate_new_token!
regenerate_token
self
end
end
|
module Win32
class SystemPath
# BCD WMI Provider Enumerations (values)
# http://msdn.microsoft.com/en-us/library/cc441427(VS.85).aspx
SYSTEM_STORE_GUID = '{9dea862c-5cdd-4e70-acc1-f32b344d4795}'
BCD_BOOTMGR_OBJECT_DEFAULTOBJECT = '23000003' # 0x23000003
BCD_OS_LOADER_DEVICE_OSDEVICE = '21000001' # 0x21000001
BCD_OS_LOADER_STRING_SYSTEMROOT = '22000002' # 0x22000002
BCD_LIBRARYSTRING_DESCRIPTION = '12000004' # 0x12000004
def self.registryPath(fs = nil, root = nil)
File.join(system32Path(fs, root), "config")
end
def self.system32Path(fs = nil, root = nil)
return File.join(root, "system32") if root
File.join(systemRoot(fs), "system32")
end
def self.systemRoot(fs = nil, si = nil)
si = systemIdentifier(fs) if si.nil?
raise(MiqException::MiqVmMountError, "Filesystem does not contain system root identifiers.") if si.blank?
system32_dir = File.join(si[:system_root], 'system32')
raise(MiqException::MiqVmMountError, "Filesystem does not contain system root folder (#{system32_dir}).") unless fs.fileDirectory?(system32_dir)
si[:system_root]
end
def self.systemIdentifier(fs = nil, options = {})
# If we are not passed a fs handle return the %systemRoot% from the environment
if fs.nil?
raise(MiqException::MiqVmMountError, "System root not available through environment variables.") if ENV["SystemRoot"].nil?
return File.expand_path(ENV["SystemRoot"].tr('\\', '/'))
end
# Use the boot.ini file to get the starting path to the Windows folder
fn = [{:file => "/boot.ini", :type => :boot_ini}, {:file => "/boot/BCD", :type => :bcd}, {:file => '/Windows/System32/config/SYSTEM', :type => :registry_file}]
drive_letter = fs.pwd.to_s[0, 2]
if drive_letter[1, 1] == ':'
fs.chdir("#{drive_letter}/")
fn.each { |f| f[:file] = "#{drive_letter}#{f[:file]}" }
end
# Determine where the initial boot information is stored (boot.ini or BCD registry
boot_cfg = fn.detect { |b| fs.fileExists?(b[:file]) }
# If we did not find either identifier above raise an error.
return {} if boot_cfg.nil?
# Set default system root path
boot_cfg[:system_root] = "/Windows"
$log.debug "Boot info stored in: [#{boot_cfg.inspect}]" if $log
case boot_cfg[:type]
when :boot_ini
begin
if fs.kind_of?(MiqFS)
boot_cfg_text = fs.fileOpen(boot_cfg[:file]).read
$log.warn "Contents of <#{boot_cfg[:file]}>\n#{boot_cfg_text}" if $log && options[:debug] == true
boot_cfg[:system_root] = $'.split("\n")[0].split("\\")[1].chomp if boot_cfg_text =~ /default=/
end
boot_cfg[:system_root].strip!
boot_cfg[:system_root] = "/#{boot_cfg[:system_root]}"
rescue RuntimeError => err
$log.warn "Win32::SystemPath.systemRoot [#{err}]" if $log
end
when :bcd
boot_cfg.merge!(parse_bcd(fs))
boot_cfg[:system_root].tr!('\\', '/') unless boot_cfg[:system_root].nil?
when :registry_files
# TODO: Needs to change to support BCD on different partition. This is just a work-around
end
boot_cfg
end
def self.parse_bcd(fs)
result = {}
reg = RemoteRegistry.new(fs, XmlHash, '/boot')
xml = reg.loadBootHive
# Find the GUID of the default Boot element
default_guid_path = "HKEY_LOCAL_MACHINE\\BCD\\Objects\\#{SYSTEM_STORE_GUID}\\Elements\\#{BCD_BOOTMGR_OBJECT_DEFAULTOBJECT}\\Element"
default_os = MIQRexml.findRegElement(default_guid_path, xml.root)
default_os = MIQRexml.findRegElement("HKEY_LOCAL_MACHINE\\BCD\\Objects\\#{default_os.text}\\Elements", xml.root) if default_os
[BCD_OS_LOADER_DEVICE_OSDEVICE, :os_device, BCD_OS_LOADER_STRING_SYSTEMROOT, :system_root,
BCD_LIBRARYSTRING_DESCRIPTION, :os_description].each_slice(2) do |key_id, name|
device = MIQRexml.findRegElement("#{key_id}\\Element", default_os) if default_os
result[name] = device.text unless device.nil?
end
# Decode disk signature
unless result[:os_device].nil?
d = result[:os_device].split(',')
result[:disk_sig] = (d[59] + d[58] + d[57] + d[56]).to_i(16) if d.size >= 60
end
result
end
end
end
|
require 'test_helper'
class RegistrationTest < ActiveSupport::TestCase
test "should save valid registration" do
registration = Registration.new
registration.subscriber = subscribers(:subscriber_1)
assert registration.save, "Invalid registration"
end
test "should not save registration without subscriber" do
registration = Registration.new
assert_not registration.save, "Empty subscriber"
end
test "should not save more than one registration per subscriber by day" do
registration1 = registrations(:registration_1)
registration2 = Registration.new subscriber: registration1.subscriber, created_at: registration1.created_at
assert_not registration2.save, "Duplicated registration"
end
test "should save more than one registration per subscriber by different day" do
registration1 = registrations(:registration_1)
registration2 = Registration.new subscriber: registration1.subscriber
assert registration2.save, "Invalid registration"
end
# test "prize assigment" do
# third = subscribers(:test_three)
# registration = Registration.new subscriber: third
# assert registration.save, "Invalid registration"
# subs4 = subscribers(:subscriber_4)
# registration = Registration.new subscriber: subs4
# assert registration.save, "Invalid registration"
# end
end
|
require 'json'
require 'octokit'
require_relative "restaurant"
require_relative "craving"
require_relative "../../config/data_mapper"
module LunchZone
class User
include DataMapper::Resource
property :id, Serial
property :nickname, String, :unique => true
property :email, String, :unique => true
property :partnerpedia_employee, Boolean
property :token, String
property :gravatar_id, String
has n, :cravings
has n, :restaurants, :through => :cravings
def self.find_or_create_from_omniauth(params)
nickname = params['info']['nickname']
user = first(:nickname => nickname)
if user
update_employee_status(user)
else
create_from_omniauth(params)
end
end
def self.update_employee_status(user)
if is_visible_on_github_org?(user.nickname)
user.partnerpedia_employee = true
else
user.partnerpedia_employee = false
end
user.save
user
end
def self.create_from_omniauth(params)
nickname = params['info']['nickname']
token = params['credentials']['token']
email = params['info']['email']
gravatar_id = params['extra']['raw_info']['gravatar_id']
partnerpedia_employee = is_visible_on_github_org?(nickname)
create(
:email => email,
:nickname => nickname,
:partnerpedia_employee => partnerpedia_employee,
:token => token,
:gravatar_id => gravatar_id
)
end
def self.is_visible_on_github_org?(nickname)
members = Octokit.organization_members('Partnerpedia').map { |user|
user['login']
}
members.include?(nickname)
end
def new_craving(restaurant, date = Date.today)
craving = Craving.new
craving.restaurant = restaurant
craving.user = self
craving.date = date
craving.save
end
def is_partnerpedia_employee?
partnerpedia_employee
end
def gravatar_url
# generate this from the email
end
def public_attributes
publishable_attributes = attributes
publishable_attributes.delete(:partnerpedia_employee)
publishable_attributes.delete(:token)
publishable_attributes
end
def to_json
public_attributes.to_json
end
end
end
|
class Genre
attr_accessor :songs, :name
@@genres = []
def Genre.all
@@genres
end
def Genre.reset_genres
@@genres.clear
end
def Genre.count
@@genres.count
end
def initialize
@name = name
@songs = []
@artists = []
@@genres << self
end
def artists
@artists = self.songs.collect {|song| song.artist}
@artists = @artists.uniq
end
end
|
RSpec.describe Report::GroupedCommentsFetcher do
let(:report) { build(:report) }
let(:comment_relation) { double("ActiveRecord::Relation") }
let(:activities) do
[
build(:project_activity, id: SecureRandom.uuid),
build(:project_activity, id: SecureRandom.uuid),
build(:project_activity, id: SecureRandom.uuid)
]
end
let(:comments) do
[
build_list(:comment, 3, commentable: activities[0]),
build_list(:comment, 2, commentable: activities[1]),
build(:comment, commentable: build(:refund, parent_activity: activities[0]), commentable_type: "Refund"),
build(:comment, commentable: build(:adjustment, parent_activity: activities[1]), commentable_type: "Adjustment")
]
end
let(:first_activity_comments) { comments[0].append(comments[2]) }
let(:second_activity_comments) { comments[1].append(comments[3]) }
let(:grouped_comments) do
{
activities[0] => first_activity_comments,
activities[1] => second_activity_comments
}
end
subject { described_class.new(report: report, user: user) }
before do
allow(report).to receive(:comments).and_return(comment_relation)
end
context "when the user is a partner organisation user" do
let(:user) { build(:partner_organisation_user) }
it "returns comments, grouped by activity" do
expect(comment_relation).to receive(:includes).with(
owner: [:organisation],
commentable: [
:parent_activity,
parent: [
parent: [:parent]
]
]
).and_return(comments.flatten)
expect(subject.all).to eq(grouped_comments)
end
end
context "when the user is a service owner" do
let(:user) { build(:beis_user) }
it "returns comments, grouped by activity" do
expect(comment_relation).to receive(:includes).with(commentable: [:parent_activity]).and_return(comments.flatten)
expect(subject.all).to eq(grouped_comments)
end
end
end
|
class Invitation < ActiveRecord::Base
belongs_to :invitor, foreign_key: 'invitor_id', class_name: 'User'
belongs_to :invitee, foreign_key: 'invitee_id', class_name: 'User'
end
|
# == Schema Information
#
# Table name: group_members
#
# id :integer not null, primary key
# user_id :integer not null
# group_id :integer not null
# pending :boolean default(TRUE), not null
# created_at :datetime
# updated_at :datetime
# rank :integer default(0), not null
#
class GroupMember < ActiveRecord::Base
belongs_to :user
belongs_to :group
scope :pending, -> { where(pending: true) }
scope :accepted, -> { where(pending: false) }
enum rank: [:pleb, :mod, :admin]
validates :user_id, uniqueness: {scope: :group_id}
after_save do
update_group_scores!
if pending_changed? && pending == false
update_counter_cache! +1
end
end
after_destroy do
update_counter_cache! -1
end
def update_counter_cache!(diff)
# Atomically incr/decr the counter
Group.update_counters(self.group_id, confirmed_members_count: diff)
end
def update_group_scores!
if self.pending_changed? && self.pending == false
TrendingGroups.vote(self.group_id)
end
end
end
|
require_relative '../../lib/identificator_mapping'
# output only non-targets
invert_selection = ARGV.delete('--invert-selection')
# transcripts_after_splicing.txt mTOR_mapping.txt
input_file, targets_filename = ARGV.first(2)
mtor_targets, translational_genes = read_mtor_mapping(targets_filename)
File.open(input_file) do |f|
gene_infos = []
f.each_line do |line|
if line.start_with? '>'
# dump previous transcript infos
unless gene_infos.empty?
hgnc_id = gene_infos.shift
if !!mtor_targets.has_key?(hgnc_id) ^ !!invert_selection
puts gene_infos.join
end
end
# started reading new transcript infos
hgnc_id = line[1..-1].strip.split("\t").first
hgnc_id = hgnc_from_string(hgnc_id)
gene_infos = [hgnc_id]
end
gene_infos << line
end
end
|
require 'spork'
Spork.prefork do
# Loading more in this block will cause your tests to run faster. However,
# if you change any configuration or code from libraries loaded here, you'll
# need to restart spork for it take effect.
# This file is copied to spec/ when you run 'rails generate rspec:install'
# ENV["RAILS_ENV"] ||= 'test'
# require File.expand_path("../../config/environment", __FILE__)
# require 'rspec/rails'
require 'jazz'
require 'rspec/core'
require 'rspec/expectations'
RSpec.configure do |config|
config.treat_symbols_as_metadata_keys_with_true_values = true
config.run_all_when_everything_filtered = true
config.filter_run :focus
end
end
Spork.each_run do
# Dir["#{Rails.root}/app/**/*.rb"].each {|f| load f}
# Dir["#{Rails.root}/lib/**/*.rb"].each {|f| load f}
end
|
module JquerySortableTreeController
module DefineVariablesMethod
def sortable_model
@sortable_model ||= self.class.to_s.split(':').last.sub(/Controller/, '').singularize.constantize
end
def sortable_collection
@sortable_collection ||= self.class.to_s.split(':').last.sub(/Controller/,'').underscore.downcase
end
def the_define_common_variables
["@#{sortable_collection.singularize}", sortable_collection, sortable_model]
end
def id
@id ||= params[:id].to_i
end
def parent_id
@parent_id ||= params[:parent_id].to_i
end
def sort
@sort ||= params[:tree_sort] == 'reversed' ? 'reversed_nested_set' : 'nested_set'
end
def prev_id
@prev_id ||= params[:prev_id].to_i
end
def next_id
@next_id ||= params[:next_id].to_i
end
def move_to_prev
@move_to_prev ||= params[:tree_sort] == 'reversed' ? :move_to_left_of : :move_to_right_of
end
def move_to_next
@move_to_next ||= params[:tree_sort] == 'reversed' ? :move_to_right_of : :move_to_left_of
end
def move_to_parent
:move_to_child_of
end
def object_to_rebuild
self.sortable_model.find(id)
end
def move_to_nowhere?
parent_id.zero? && prev_id.zero? && next_id.zero?
end
def prev_next_parent
return 'prev' unless prev_id.zero?
return 'next' unless next_id.zero?
return 'parent' unless parent_id.zero?
end
def move_to
send("move_to_#{prev_next_parent}")
end
def node_id
send("#{prev_next_parent}_id")
end
def node
sortable_model.find(node_id)
end
end
module ExpandNode
include DefineVariablesMethod
def expand_node
@children = object_to_rebuild.children.send(sort) if id && sort
return render(plain: '', status: :no_content) if !@children || @children.count.zero?
render layout: false, template: "#{sortable_collection}/expand_node"
end
end
module Rebuild
include DefineVariablesMethod
def rebuild
return render(plain: '', status: :no_content) if move_to_nowhere?
object_to_rebuild.send(move_to, node)
render(plain: '', status: :ok)
end
end
end
|
# This file has the top level of module
# Top level module of bnicovideo gem.
module Bnicovideo
autoload :Mylist, File.join(File.dirname(__FILE__), 'bnicovideo', 'mylist.rb')
autoload :Tag, File.join(File.dirname(__FILE__), 'bnicovideo', 'tag.rb')
autoload :UserSession, File.join(File.dirname(__FILE__), 'bnicovideo', 'user_session.rb')
autoload :Video, File.join(File.dirname(__FILE__), 'bnicovideo', 'video.rb')
autoload :OsDetector, File.join(File.dirname(__FILE__), 'bnicovideo', 'os_detector.rb')
autoload :WindowsDetector, File.join(File.dirname(__FILE__), 'bnicovideo', 'windows_detector.rb')
end
|
class PostCommentsController < ApplicationController
def create
customer = Customer.find(params[:customer_id])
comment = current_member.post_comments.new(post_comment_params)
comment.customer_id = customer.id
comment.score = Language.get_data(post_comment_params[:comment])
comment.save
redirect_to customer_path(customer)
end
def destroy
PostComment.find_by(id: params[:id], customer_id: params[:customer_id]).destroy
redirect_to customer_path(params[:customer_id])
end
private
def post_comment_params
params.require(:post_comment).permit(:comment)
end
end
|
require 'rails_helper'
describe Invite::Revoke do
before do
allow_any_instance_of(One::Client).to receive(:groups).and_return(build_list(:one_group, 1))
end
let(:current_user) { build(:current_user) }
let!(:invite) do
Invite::Create.(
invite: attributes_for(:invite),
current_user: current_user
).model
end
subject(:revoke) { Invite::Revoke.run(id: invite.id, current_user: current_user) }
it 'revokes the invite' do
expect { revoke }.to change { invite.reload.status }.from(Invite::STATUS_PENDING).to(Invite::STATUS_REVOKED)
end
context 'given an already revoked invite' do
before { Invite::Revoke.run(id: invite.id, current_user: current_user) }
it 'fails' do
expect { revoke }.to raise_error ActiveRecord::RecordNotFound
end
end
end
|
class ReservationsController < ApplicationController
before_action :find_book
before_action :find_reservation, only: [:edit, :update, :destroy]
def new
@reservation = Reservation.new
end
def create
@reservation = Reservation.new(reservation_params)
@reservation.book_id = @book.id
@reservation.user_id = current_user.id
if @reservation.save
redirect_to book_path(@book)
else
render 'new'
end
end
def edit
end
def update
if @reservation.update(reservation_params)
redirect_to book_path(@book)
else
render 'edit'
end
end
def destroy
@reservation.destroy
redirect_to book_path(@book)
end
private
def reservation_params
params.require(:reservation).permit(:name, :email, :address, :contact_nmber, :date_of_reservation)
end
def find_book
@book = Book.find(params[:book_id])
end
def find_reservation
@reservation = Reservation.find(params[:id])
end
end
|
#
# The objective is to count the nucleotides (A,C,T,G) in a string.
#
# ## Simplest solution
# We could construct the pipe ahead of time, with four branches.
require 'aqueductron'
# - Start a new pipe
cn = Duct.new.
# - turn any string passed in into a sequence of chars; each char
# gets passed down individually.
expand(->(s) {s.each_char}).
# - translate each char into uppercase
through(->(c) {c.upcase}).
# - split the duct into four pipes. Each filters out only the letter it cares about, and counts them.
split( {
:A => Duct.new.keeping(->(actg) { actg == "A"}).count,
:T => Duct.new.keeping(->(actg) { actg == "T"}).count,
:C => Duct.new.keeping(->(actg) { actg == "C"}).count,
:G => Duct.new.keeping(->(actg) { actg == "A"}).count })
# Now we have a static pipe. To use it, we
# - send in one string
resultingCounts = cn.drip("ACCTAACG").
# - tell it we're done
eof
# - get the results
# => 3
resultingCounts.value(:A)
# => 3
resultingCounts.value(:C)
# => 1
resultingCounts.value(:T)
# => 3
resultingCounts.value(:G)
## More General Case
# what if we get some other letter? You're bound to see an N (for no data) in
# any real sequence string.
#
# The more interesting implementation counts
# whatever the heck it gets.
#
puts "This part is more interesting"
# - start the duct
countChars = Duct.new.
# - expand strings into characters, as before
expand(->(s) {s.each_char}).
# - dynamically divide the data according to a categorization function,
# in this case: uppercase version of the character
partition(->(a) {a.upcase},
# - for each unique category, a new duct will be created using this function.
->(a) { Duct.new.count })
# Now, we can pass in strings of whatever, and it'll count what it sees.
countChars.drip("AACTGTNNA").eof
# ---
# A => 3
# ---
# ---
# C => 1
# ---
# ---
# T => 2
# ---
# ---
# G => 1
# ---
# ---
# N => 2
# ---
|
require 'rails_helper'
describe Hotel do
it "should create a valid object" do
expect(Fabricate.build(:hotel)).to be_valid
end
it "is invalid if star_rating is not an integer" do
expect(Fabricate.build(:hotel, star_rating: "string")).not_to be_valid
end
end
|
# Участник поручительства
class SuretyMember < ActiveRecord::Base
belongs_to :surety, inverse_of: :surety_members
belongs_to :user, inverse_of: :surety_members
belongs_to :account_code, inverse_of: :surety_member
validates :surety, :email, :full_name, presence: true, unless: :user
validates :email, email_format: { message: 'имеет не верный формат' }, unless: :user
before_create :refill_from_user, if: :user
after_create :create_account_for_user, if: :user
after_create :create_account_code_for_user, unless: :user
def full_name
u = user || User.new { |user| user.first_name = first_name; user.last_name = last_name; user.middle_name = middle_name }
u.full_name
end
private
def refill_from_user
self.last_name = user.last_name
self.first_name = user.first_name
self.middle_name = user.middle_name
self.email = user.email
true
end
def create_account_for_user
conditions = { user_id: user_id, project_id: surety.project_id }
a = Account.where(conditions).first_or_create!
a.allowed? || a.allow!
end
def create_account_code_for_user
create_account_code! do |code|
code.email = email
code.project = surety.project
code.surety_member = self
end
end
end
|
class TeamPresenter
include ActionView::Helpers::UrlHelper
def initialize(context)
@context = context
end
def links
bodies.zip(urls).map do |body, url|
link_to(body, url, class: "team")
end
end
def li_classes
classes = Array.new(all_teams.length, "")
index = all_teams.index(context.team) || 0
classes[index] = %(class="selected").html_safe
classes
end
private
attr_reader :context
def all_teams
@all_teams ||= Team.all.order(:name)
end
def urls
all_teams.map do |team|
args = path_params(team)
path_helper(args)
end
end
def path_helper(args)
Rails.application.routes.url_helpers.root_path(args)
end
def path_params(team)
{
season: context.season.year_start,
team: team.abbreviation,
game_type: context.game_type,
game_order: context.game_order
}
end
def bodies
all_teams.pluck(:name)
end
end
|
Vagrant.configure(2) do |config|
# vagrant box
config.vm.box = "ubuntu/trusty64"
# ports to access the virtual machine
config.vm.network "forwarded_port", guest: 8000, host: 8111,
auto_correct: true
# shared folder setup
config.vm.synced_folder ".", "/home/vagrant/django_starter"
# SSH agent forwarding
config.ssh.forward_agent = true
end
|
class LocationImage < ActiveRecord::Base #These are the restaurant profile pictures
require 'file_size_validator'
include Rotatable
mount_uploader :image, ImageUploader
belongs_to :location
validates :image, presence: true, file_size: { maximum: 4.0.megabytes.to_i }
default_scope order('location_images.index ASC')
after_save :reprocess_image, :if => :cropping?
after_destroy :remove_images_dir #remove directory left after destroy
attr_accessible :image, :location_id, :crop_x, :crop_y, :crop_w, :crop_h, :rate, :index, :location_token
attr_accessor :ver, :crop_x, :crop_y, :crop_w, :crop_h, :rate
def remove_images_dir
#remove carrierwave uploads
FileUtils.remove_dir("#{Rails.root}/public/uploads/location_image/image/#{id}", :force => true)
end
def cropping?
!crop_x.blank? && !crop_y.blank? && !crop_w.blank? && !crop_h.blank?
end
private
def reprocess_image
self.image.recreate_versions!
end
end
|
Rails.application.routes.draw do
# get 'review/index'
# get 'review/new'
# get 'review/create'
# get 'restaurant/index'
# get 'restaurant/show'
# get 'restaurant/new'
# get 'restaurant/create'
resources :restaurants do
resources :reviews, only: [:new, :create]
end
end
|
Rails.application.routes.draw do
devise_for :users, controllers: { registrations: 'users/registrations',
sessions: 'users/sessions' }
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
resources :users, only: [:show]
get 'hello' => 'hello#index'
resources :posts do
resources :likes, only: [:create, :destroy]
resources :replies, only: [:create]
end
root 'hello#index'
end
|
require 'rails_helper'
describe Sagashi::Tokenizer do
before :each do
@tokenizer = Sagashi::Tokenizer.new
end
it 'tokenizes a string' do
@tokenizer.str = "This is a body."
expect(@tokenizer.tokenize).to eq(%w(this bodi))
end
it 'tokenizes known words properly' do
@tokenizer.str = 'U.S.A.'
expect(@tokenizer.tokenize).to eq(['usa'])
@tokenizer.str = 'anti-discriminatory'
expect(@tokenizer.tokenize).to eq(['antidiscriminatori'])
end
it 'tokenizes a Japanese string' do
@tokenizer.str = "これは、文書体です。"
expect(@tokenizer.tokenize).to eq(["これは","文書体です"])
end
it 'tokenizes a Korean string' do
@tokenizer.str = "이것은 문서 체입니다."
expect(@tokenizer.tokenize).to eq(['이것은', '문서', '체입니다'])
end
it 'tokenizes words with apostophes properly' do
@tokenizer.str = "O'Neill aren't"
expect(@tokenizer.tokenize).to eq(%w(oneil arent))
end
end
|
require 'rails_helper'
RSpec.describe Order, type: :model do
describe '#name' do
it 'will prevent creation of order if name has 0 characters' do
order = build(:order, :with_all_needed_associations)
order.name = nil
expect(order.save).to eq false
end
it 'allows creation of order if name has atleast 1 character' do
order = build(:order, :with_all_needed_associations)
order.name = "Andrew"
expect(order.save).to eq true
end
end
describe '#email' do
it 'will prevent creation of order if email has 0 characters' do
order = build(:order, :with_all_needed_associations)
order.email = nil
expect(order.save).to eq false
end
it 'will prevent creation of order if email is invalid' do
order = build(:order, :with_all_needed_associations)
order.email = "andrew@test"
expect(order.save).to eq false
end
it 'allows creation of order if email is valid' do
order = build(:order, :with_all_needed_associations)
order.email = "aplatkin@hotmail.com"
expect(order.save).to eq true
end
end
describe '#creditcardnum' do
it 'will prevent creation of order if credit card is not atleast 14 characters' do
order = build(:order, :with_all_needed_associations)
order.creditcardnum = "12312312"
expect(order.save).to eq false
end
it 'will prevent creation of order if credit card is greater than 16 characters' do
order = build(:order, :with_all_needed_associations)
order.creditcardnum = "1123123123123123123123123123123123"
expect(order.save).to eq false
end
it 'allows creation of order if credit card is 16 characters' do
order = build(:order, :with_all_needed_associations)
order.creditcardnum = "1234123412341234"
expect(order.save).to eq true
end
end
describe '#expirationdate' do
it 'will prevent creation of order if expiration date is not provided' do
order = build(:order, :with_all_needed_associations)
order.expirationdate = nil
expect(order.save).to eq false
end
it 'allows creation of order if expiration date is provided' do
order = build(:order, :with_all_needed_associations)
order.expirationdate = "12-2015"
expect(order.save).to eq true
end
end
describe '#quantity' do
it 'will prevent creation of order if quantity is not not greater than 0' do
order = build(:order, :with_all_needed_associations)
order.quantity = 0
expect(order.save).to eq false
end
it 'will prevent creation of order if quantity is not an integer' do
order = build(:order, :with_all_needed_associations)
order.quantity = 1.55
expect(order.save).to eq false
end
it 'will prevent creation of order if quantity requested is more than quantity of tickets available' do
order = build(:order, :with_all_needed_associations)
order.quantity = (order.showing.tickets_remaining + 1)
expect(order.save).to eq false
end
it 'allows creation of order if quantity is provided and tickets are available' do
order = build(:order, :with_all_needed_associations)
order.quantity = 1
expect(order.save).to eq true
end
end
describe '#created_at' do
it 'will prevent creation of order if tickets are trying to be bought and the movie date has already passed' do
order = build(:order, :with_all_needed_associations)
order.showing.showtime = 5.hours.ago
expect(order.save).to eq false
end
it 'allows creation of order if the movie showtime is upcoming' do
order = build(:order, :with_all_needed_associations)
order.showing.showtime = 5.days.from_now
expect(order.save).to eq true
end
end
end
|
class UserSerializer < ActiveModel::Serializer
attributes :myMessagesCount, :subscriptionsCount, :username, :email,
:friends, :full_name, :currentUser
has_one :channel
has_many :myMessages
has_many :messagesToMe
has_many :posts, only: [:id, :body, :slug]
has_many :subscriptions
def myMessages
User.sorted_messages_by(object)
end
def messagesToMe
User.sorted_messages_for(object)
end
def currentUser
{ id: object.id.to_s, name: object.name }
end
def subscriptionsCount
object.subscriptions.count.to_s
end
def myMessagesCount
myMessages.count.to_s
end
def friends
object.friend_ids.map do |id|
Rails.application.routes.url_helpers.user_path(id)
end
end
end |
module Ricer::Plugins::Poll
class Answer < ActiveRecord::Base
self.table_name = 'poll_answers'
belongs_to :user, :class_name => 'Ricer::Irc::User'
belongs_to :option, :class_name => Option.name
def self.upgrade_1
m = ActiveRecord::Migration.new
m.create_table table_name do |t|
t.integer :user_id, :null => false
t.integer :option_id, :null => false
t.timestamp :created_at, :null => false
end
end
end
end
|
class VotesController < ApplicationController
before_action :authenticate_user!
before_action :find_vote, :authorize_user!, :only: [:create, :destroy]
def create
review = Review.find params[:review_id]
vote = Vote.new user: current_user, review: review, is_up: params[:is_up]
if !can?(:vote, review)
redirect_to review.product, alert: "can't vote"
elsif vote.save
redirect_to review.product, notice: 'voted'
else
redirect_to review.product, alert: 'Not Voted'
end
end
def update
find_vote
if vote.is_up
vote.is_up = false
vote.update(is_up: false)
else
vote.update(is_up: true)
end
redirect_to vote.review.product
end
end
def destroy
find_vote
vote.destroy
redirect_to vote.review.product, notice: 'Vote removed'
else
redirect_to vote.review.product, alert: "can't delete vote"
end
end
private
def find_vote
@vote = Vote.find params[:id]
def authorize_user!
redirect_to @vote.review.product unless can? (:crud, @vote)
end
end
|
# frozen_string_literal: true
module Audit
class DeathsWorker < WorkerBase
def perform(user_id)
DeathProcessService.new(user_id).call
end
end
end
|
# -*- encoding: us-ascii -*-
module GC
def self.stat
@agent ||= begin
require 'rubinius/agent'
Rubinius::Agent.loopback
end
stats = {
:gc => {
:young => {
:count => @agent.get('system.gc.young.count')[1],
:total_wallclock => @agent.get('system.gc.young.total_wallclock')[1],
:last_wallclock => @agent.get('system.gc.young.last_wallclock')[1]
},
:full => {
:count => @agent.get('system.gc.full.count')[1],
:total_wallclock => @agent.get('system.gc.full.total_wallclock')[1],
:last_wallclock => @agent.get('system.gc.full.last_wallclock')[1]
}
},
:memory => {
:counter => {
:young_objects => @agent.get("system.memory.counter.young_objects")[1],
:young_bytes => @agent.get("system.memory.counter.young_bytes")[1],
:promoted_objects => @agent.get("system.memory.counter.promoted_objects")[1],
:promoted_bytes => @agent.get("system.memory.counter.promoted_bytes")[1],
:mature_objects => @agent.get("system.memory.counter.mature_objects")[1],
:mature_bytes => @agent.get("system.memory.counter.mature_bytes")[1],
},
:young => {:bytes => @agent.get("system.memory.young.bytes")[1]},
:mature => {:bytes => @agent.get("system.memory.mature.bytes")[1]},
:large => {:bytes => @agent.get("system.memory.large.bytes")[1]},
:code => {:bytes => @agent.get("system.memory.code.bytes")[1]},
:symbols => {:bytes => @agent.get("system.memory.symbols.bytes")[1]}
}
}
stats
end
end
|
class AddProductionToActor < ActiveRecord::Migration[6.1]
def change
add_column :actors, :production_id, :integer
add_column :actors, :production_type, :string
end
end
|
Pod::Spec.new do |s|
s.name = 'DVAManagers'
s.version = '1.2.0'
s.summary = 'Common DVAManagers for iOS Apps'
s.license = 'MIT'
s.authors = {"Pablo Romeu"=>"pablo.romeu@develapps.com"}
s.homepage = 'https://bitbucket.org/dvalibs/dvamanagers'
s.description = 'This pod implements managers for common tasks like:
- Using a paginated resource
- Photo picker
- Location Manager
- Facebook Manager
New 1.1.0
---------
Added cache types at paginated resource'
s.social_media_url = 'https://twitter.com/pabloromeu'
s.requires_arc = true
s.source = {}
s.platform = :ios, '9.0'
s.ios.platform = :ios, '9.0'
s.ios.preserve_paths = 'ios/DVAManagers.framework'
s.ios.public_header_files = 'ios/DVAManagers.framework/Versions/A/Headers/*.h'
s.ios.resource = 'ios/DVAManagers.framework/Versions/A/Resources/**/*'
s.ios.vendored_frameworks = 'ios/DVAManagers.framework'
end
|
class TopicsController < ApplicationController
#before_filter :signed_in_as_admin
respond_to :html, :json
def index
@topic = Topic.new
@topics = Topic.paginate(page: params[:page])
@subjects = Subject.all
end
def create
@topic = Topic.new(params[:topic])
@topics = Topic.paginate(page: params[:page])
@subjects = Subject.all
if @topic.save
flash[:success] = "Topic created!"
redirect_to topics_path
else
render 'index'
end
end
def update
@topic = Topic.find(params[:id])
@topic.update_attributes(params[:topic])
respond_with @topic
end
def destroy
Topic.find(params[:id]).destroy
flash[:success] = "Topic deleted."
redirect_to topics_path
end
def topics_by_subject
if params[:id].present?
@topics = Subject.find(params[:id]).topics
else
@topics = []
end
respond_to do |format|
format.js
end
end
end |
require 'httpclient'
require 'nokogiri'
require 'fileutils'
module OHOLFamilyTrees
class Mirror
PublicDataUrl = 'http://publicdata.onehouronelife.com'
MonumentsUrl = "http://onehouronelife.com"
attr_reader :log
attr_reader :public_data
attr_reader :cache
attr_reader :check_all
attr_reader :http
attr_accessor :monuments_url
def initialize(log, public_data = PublicDataUrl, cache = 'cache', check_all = false)
@log = log
@public_data = public_data
@cache = cache
@check_all = check_all
@http = HTTPClient.new
@monuments_url = MonumentsUrl
end
def lives
mirror('publicLifeLogData')
end
def maps
mirror('publicMapChangeData')
end
def mirror(subdir)
base_url = "#{public_data}/#{subdir}/"
base_path = "#{cache}/#{subdir}"
ensure_directory(base_path)
server_directory = fetch_file(base_url, "", "#{base_path}/index.html", Time.now)
server_list = extract_path_list(server_directory)
server_list.each do |path,date|
FileUtils.mkdir_p("#{base_path}/#{path}")
index = fetch_file(base_url, path, "#{base_path}/#{path}/index.html", date)
unchanged = 0
log_paths = extract_path_list(index)
log_paths.reverse_each do |log_path,log_date|
if unchanged < 28 or check_all then # accounts for lives + names
cache_path = "#{base_path}/#{path}#{log_path}"
if has_file?(cache_path, log_date)
unchanged += 1
else
unchanged = 0
get_file(base_url, "#{path}#{log_path}", cache_path)
end
end
end
end
end
def ensure_directory(path)
unless Dir.exist?(path)
loop do
puts "Target directory '#{path}' does not exist"
puts "c Create"
puts "a Abort"
case $stdin.gets.chomp.downcase
when 'c'
FileUtils.mkdir_p(path)
break
when 'a'
raise "output directory does not exist"
end
end
end
end
def fetch_file(base, path, cache_path, date = Time.at(0))
if has_file?(cache_path, date)
return File.open(cache_path, "r") {|f| f.read}
else
return get_file(base, path, cache_path)
end
end
def has_file?(cache_path, date = Time.at(0))
File.exist?(cache_path) && date < File.mtime(cache_path)
end
def get_file(base, path, cache_path)
log.warn path
contents = http.get_content(base + path)
File.open(cache_path, "w") do |f|
f.write(contents)
end
return contents
end
def extract_path_list(directory)
paths = []
Nokogiri::HTML(directory).css('a').each do |node|
path = node.attr(:href)
next if path == '../' or path == 'lifeLog/'
date = DateTime.parse(node.next.content.strip.chop.strip).to_time
paths << [path, date]
end
return paths
end
def extract_monument_path_list(directory)
paths = []
Nokogiri::HTML(directory).css('table table table a').each do |node|
path = node.attr(:href)
paths << path
end
return paths
end
def monuments
base_path = "#{cache}/monuments"
ensure_directory(base_path)
known = nil
if File.exists?("#{base_path}/count.txt")
known = File.read("#{base_path}/count.txt")
end
known = known && known.to_i
fetch_file(monuments_url, "/monumentStats.php", "#{base_path}/monumentStats.php", Time.now)
contents = File.read("#{base_path}/monumentStats.php")
count = nil
if contents && match = contents.match(/(\d+) monuments completed/)
count = match[1].to_i
File.write("#{base_path}/count.txt", count.to_s)
end
p "#{count} monuments now, #{known} last time"
if known.nil? || count.nil? || count > known
sync_monuments(base_path)
end
end
def sync_monuments(base_path)
base_url = "#{monuments_url}/monuments/"
monument_directory = fetch_file(base_url, "", "#{base_path}/index.html", Time.now)
monument_list = extract_monument_path_list(monument_directory)
monument_list.each do |path|
fetch_file(base_url, path, "#{base_path}/#{path}", Time.now)
end
end
end
end
|
#!/usr/bin/env ruby
require 'xmpp4r'
require 'xmpp4r/muc/helper/simplemucclient'
require 'xmpp4r/roster'
require 'yaml'
require 'sqlite3'
require 'logger'
require 'optparse'
require_relative 'commands/command_parser'
require_relative 'commands/remind'
class Bot
attr_reader :config, :users, :db, :log
def initialize(options)
@config = YAML::load_file(options[:config] || 'config.yml')
@connection_dead = false
@nick = @config['xmpp']['nick']
@botname = @config['xmpp']['botname']
@users = {}
@rooms = {}
@db = SQLite3::Database.new(@config['database']['name'])
@log = Logger.new('chatbot.log')
end
def lookup_room(room)
found = nil
@config['xmpp']['rooms'].each do |k, v|
m = /(\d+)_(.+)/.match(k)
if m
name = m[2].gsub('_', ' ')
if name.downcase == room.downcase
found = k
break
end
end
end
return found
end
def respond(text, nick, time, room=nil)
is_pm = room == nil
match = /^(?:room|channel)? (.+);(?:\s)?(.+)?/.match(text)
if match
room = lookup_room($1)
if !room
send_message(nick, "Sorry, I can't post anything to that room because I'm not subscribed to it.")
return
end
text = $2
end
begin
cmd = CommandParser.parse(text)
if cmd
cmd.set_attributes(self, time, nick, room, text, is_pm)
cmd.respond
end
rescue => e
@log.fatal(e.message)
@log.fatal(e.backtrace)
@connection_dead = true
end
end
def connect
@client = Jabber::Client.new(@config['xmpp']['username'])
@client.connect(@config['xmpp']['server'])
@client.auth(@config['xmpp']['password'])
@client.send(Jabber::Presence.new.set_type(:available))
@roster = Jabber::Roster::Helper.new(@client)
@roster.add_subscription_callback do |m|
@users[m.name] = {
'jid' => m.jid,
'mention' => m.attributes['mention_name'],
'email' => m.attributes['email']
}
end
@config['xmpp']['rooms'].each do |room|
@rooms[room] = Jabber::MUC::SimpleMUCClient.new(@client)
@rooms[room].join("#{room}@#{@config['xmpp']['conf']}/#{@config['xmpp']['nick']}",
nil, {:history => false})
@rooms[room].on_message do |time, nick, text|
t = (time || Time.new).strftime("%I:%M")
# Make sure they're talking to us.
if nick != @config['xmpp']['nick'] &&
(/^#{@botname} (.*)/.match(text) || /^(\/.*)/.match(text))
respond($1, nick, t, room)
end
end
end
@client.add_message_callback do |mesg|
begin
if mesg.body and mesg.body.length
respond(mesg.body, mesg.from, Time.new.strftime("%I:%M"))
end
rescue => e
@log.fatal(e.message)
@log.fatal(e.backtrace)
@connection_dead = true
end
end
# Load initial roster
@roster.get_roster()
@roster.wait_for_roster()
@roster.items.each do |k,v|
@users[v.attributes['name']] = {
'jid' => v.jid,
'mention' => v.attributes['mention_name'],
'email' => v.attributes['email']
}
end
self
end
def send_message(nick, message)
mess = Jabber::Message.new
mess.to = nick
mess.from = @config['xmpp']['username']
mess.body = message
mess.set_type(:chat)
@client.send(mess)
end
def send(room, text, mention=nil)
if mention
text = "@#{mention} #{text}"
end
@rooms[room].send(Jabber::Message.new(room, text))
end
def run
@log.info("Running Bot...")
Thread.start {
loop do
if @connection_dead
if @client
@client.close
end
exit
end
Remind::check_reminders(self)
sleep(1)
end
}.join
end
end
options = {}
OptionParser.new do |opts|
opts.banner = "Usage: bot --config=configfile"
opts.on("-c", "--config", "Location of your YML config file.") do |v|
options[:config] = v
end
opts.on('-d', '--debug', "Debugging. Won't fork") do |v|
options[:debug] = true
end
end
# if options[:debug]
# pid = fork {
# b = Bot.new(options)
# b.connect.run
# }
# File.open("bot.pid", "w") do |f|
# f.write(pid)
# end
# else
b = Bot.new(options)
b.connect.run
# end
|
class User < ActiveRecord::Base
has_many :histories
has_many :reviews
has_many :subscription_requests
validates_uniqueness_of :login_name
validates_presence_of :login_name, :password, :name
def self.authenticate(login_name, password)
if password.blank?
return where(["login_name=? AND (password=? OR password IS NULL)",
login_name, password]).first
else
return where(["login_name=? AND password=?",
login_name, password]).first
end
end
def self.current=(user)
@current_user = user
end
def self.current
@current_user
end
end
|
class ChangeSmoochBotDeactivateSettingLabel < ActiveRecord::Migration[4.2]
def change
tb = BotUser.smooch_user
unless tb.nil?
settings = tb.get_settings.clone || []
i = settings.find_index{ |s| s['name'] == 'smooch_disabled' }
settings[i]['label'] = 'Pause the bot'
settings[i]['description'] = 'When paused, the bot will send the "Notice of activity" message to any user interacting with the tipline. No other messages will be sent. The tipline will not be deactivated.'
tb.set_settings(settings)
tb.save!
end
end
end
|
require 'digest/sha1'
class User < ActiveRecord::Base
# レベル:ユーザ
named_scope :level_users, :conditions => ["level = 'user'"]
validates_presence_of :login_id, :message => 'が入力されていません。' # 存在検証
validates_presence_of :password, :message => 'が入力されていません。' # 存在検証
validates_uniqueness_of :login_id, :message => 'は既に登録されています。' # 一意検証
attr_accessor :password_confirmation
attr_accessor :edit_password
validates_confirmation_of :password, :message => 'が一致しません。' # 再入力検証
#----------#
# validate #
#----------#
# データ検証
def validate
errors.add_to_base( "パスワードを設定して下さい。" ) if self.hashed_password.blank?
end
#----------#
# password #
#----------#
# 読み込み用メソッド
# 'password'は仮想属性
def password
@password
end
#-------------------#
# password=( pass ) #
#-------------------#
# 書き込み用メソッド
def password=( pass )
@password = pass
# ソルト生成
create_new_salt
# ハッシュパスワード設定
self.hashed_password = User.encrypted_password( self.password, self.salt )
end
#-----------------#
# password_check? #
#-----------------#
# パスワードチェック
def password_check?( check_password )
# 暗号化パスワード生成
expected_password = User.encrypted_password( check_password, self.salt )
# 暗号化パスワードとハッシュパスワードが一致しなければ
unless expected_password == self.hashed_password
return false
else
return true
end
end
private
#-----------------#
# create_new_salt #
#-----------------#
# ソルト生成
def create_new_salt
# オブジェクトIDと乱数よりソルトを生成
self.salt = self.object_id.to_s + rand.to_s
end
#-------------------------#
# self.encrypted_password #
#-------------------------#
# 暗号化パスワード生成
def self.encrypted_password( password, salt )
string_to_hash = password + "wibble" + salt # 'wibble'を付けて推測されにくくする
Digest::SHA1.hexdigest( string_to_hash )
end
#-------------------#
# self.authenticate #
#-------------------#
# ユーザ認証メソッド(ログイン)
def self.authenticate( login_id, password )
# ユーザ検索
current_user = self.find_by_login_id( login_id )
unless current_user.blank?
# 暗号化パスワード生成
expected_password = encrypted_password( password, current_user.salt )
# 暗号化パスワードとハッシュパスワードが一致しなければ
if current_user.hashed_password != expected_password
# ユーザに[ nil ]を設定
current_user = nil
end
end
# ユーザを返す
current_user
end
end
|
class CreateMedicalCats < ActiveRecord::Migration[5.2]
def change
create_table :medical_cats do |t|
t.date :date
t.string :nature_of_emergency
t.boolean :permanent
t.integer :period_year
t.integer :period_month
t.boolean :hospitalized
t.integer :personel_detail_id
t.timestamps
end
end
end
|
# @param {String} s
# @param {String} t
# @return {Boolean}
def is_anagram(s, t)
char_hash = {}
s.each_char do |char|
if char_hash.has_key? char
char_hash[char] += 1
else
char_hash[char] = 1
end
end
t.each_char do |char|
if char_hash.has_key? char
char_hash[char] -= 1
else
char_hash[char] = 1
end
end
return char_hash.select{|k,v| v > 0 }.size > 0 ? false : true
end
|
require 'hydramata/works/base_presenter'
require 'hydramata/works/conversions/translation_key_fragment'
module Hydramata
module Works
class WorkTypePresenter < SimpleDelegator
include Conversions
def initialize(object, collaborators = {})
__setobj__(object)
@translator = collaborators.fetch(:translator) { default_translator }
@translation_scopes = collaborators.fetch(:translation_scopes) { default_translation_scopes }
end
def description(options = {})
translator.translate('description', options.reverse_merge(scopes: translation_scopes))
end
def label(options = {})
translator.translate('label', options.reverse_merge(scopes: translation_scopes, default: __getobj__.name))
end
alias_method :to_s, :label
def inspect
format('#<%s:%#0x presenting=%s>', self.class, __id__, __getobj__.inspect)
end
def instance_of?(klass)
super || __getobj__.instance_of?(klass)
end
def to_work_type
__getobj__
end
private
attr_reader :translator, :translation_scopes
private :translator, :translation_scopes
def default_translation_scopes
[
['work_types', TranslationKeyFragment(self)]
]
end
def default_translator
require 'hydramata/core'
Hydramata.configuration.translator
end
end
end
end
|
require 'open-uri'
require 'openssl'
require 'zlib'
require 'set'
require 'rss'
require 'fileutils'
module RssItemsNotifier
class Listener
attr_accessor :name
def initialize(settings)
@crc_feeds = Set.new
@rss_url = settings[:rss_url]
@rss_open_properties = settings[:rss_open_properties]
@name = settings[:name] || @rss_url
@state_file = settings[:state_file]
load
end
def obtain_new_items
new_crc_feeds = Set.new
open(@rss_url, @rss_open_properties) do |rss|
feed = RSS::Parser.parse(rss)
feed.items.each do |item|
feed_crc = Zlib::crc32(item.link).to_i
new_crc_feeds.add feed_crc
yield item unless @crc_feeds.include?(feed_crc)
end
end
@crc_feeds = new_crc_feeds unless new_crc_feeds.empty?
end
def save
if @state_file then
File.open(@state_file, 'w+') do |f|
f.puts(@crc_feeds.to_a)
end
end
end
protected
def load
if @state_file then
FileUtils.touch @state_file
File.open(@state_file, 'r+') do |f|
f.each_line do |line|
@crc_feeds.add line.to_i
end
end
end
end
end
end
|
class UserDecorator < Draper::Decorator
def full_name
"#{object.name}"
end
def time_decorate(time)
time.strftime("%A, %d %b %Y %l:%M %p")
end
end |
require_relative 'acceptance_helper'
feature 'Change rating of Quesiton', %q{
In order to rate Questions
As an authorized User
I want to be able to change Question's rating
} do
given(:user) { create(:user) }
given(:question) { create(:question) }
given(:own_question) { create(:question, user: user) }
before(:each, authorized: :true) do
question
sign_in(user)
end
scenario 'Authorized user votes for good question', authorized: :true, js: true do
click_on 'Plus'
sleep(1)
within '.rating' do
expect(page).to have_text '1'
end
end
scenario 'Authorized user votes against bad question', authorized: :true, js: true do
click_on 'Minus'
sleep(1)
within '.rating' do
expect(page).to have_text '-1'
end
end
scenario "Authorized user can't vote for own question", js: true do
sign_in(user)
own_question
expect(page).to_not have_link 'Plus'
expect(page).to_not have_link 'Minus'
end
scenario "Unauthorized user can't vote", js: true do
question
expect(page).to_not have_link 'Plus'
expect(page).to_not have_link 'Minus'
end
end |
require 'sinatra'
set :show_exceptions, false
get '/' do
'Hello world!'
end
get '/timeout' do
sleep 100
end
get '/client-error' do
status 404
'client error'
end
get '/server-error' do
status 500
'error'
end
|
# frozen_string_literal: true
module Mongo
module Benchmarking
# A utility class for encapsulating the summary information for a
# benchmark, including behaviors for reporting on the summary.
class Summary
# @return [ Array<Numeric> ] the timings of each iteration in the
# benchmark
attr_reader :timings
# @return [ Percentiles ] the percentiles object for querying the
# timing at a given percentile value.
attr_reader :percentiles
# @return [ Numeric ] the composite score for the benchmark
attr_reader :score
# Construct a new Summary object with the given timings, percentiles,
# and score.
#
# @param [ Array<Numeric> ] timings the timings of each iteration in the
# benchmark
# @param [ Percentiles ] percentiles the percentiles object for querying
# the timing at a given percentile value
# @param [ Numeric ] score the composite score for the benchmark
def initialize(timings, percentiles, score)
@timings = timings
@percentiles = percentiles
@score = score
end
# @return [ Numeric ] the median timing for the benchmark.
def median
percentiles[50]
end
# Formats and displays the results of a single benchmark run.
#
# @param [ Integer ] indent how much the report should be indented
# @param [ Array<Numeric> ] points the percentile points to report
#
# @return [ String ] a YAML-formatted summary
def summary(indent, points)
[].tap do |lines|
lines << format('%*sscore: %g', indent, '', score)
lines << format('%*smedian: %g', indent, '', median)
lines << format('%*spercentiles:', indent, '')
points.each do |pct|
lines << format('%*s%g: %g', indent + 2, '', pct, percentiles[pct])
end
end.join("\n")
end
end
end
end
|
class ChangeSubmissionUserIdToInteger < ActiveRecord::Migration[6.0]
def change
change_column :submissions, :user_id, 'integer USING CAST(user_id AS integer)'
end
end
|
class Game < ApplicationRecord
belongs_to :home_team, :class_name => 'Team'
belongs_to :visiting_team, :class_name => 'Team'
has_many :events
end
|
# frozen_string_literal: true
# rubocop:todo all
require 'lite_spec_helper'
require 'support/shared/server_selector'
describe Mongo::ServerSelector::PrimaryPreferred do
let(:name) { :primary_preferred }
include_context 'server selector'
let(:default_address) { 'test.host' }
it_behaves_like 'a server selector mode' do
let(:secondary_ok) { true }
end
it_behaves_like 'a server selector accepting tag sets'
it_behaves_like 'a server selector accepting hedge'
it_behaves_like 'a server selector with sensitive data in its options'
describe '#initialize' do
context 'when max_staleness is provided' do
let(:options) do
{ max_staleness: 95 }
end
it 'sets the max_staleness option' do
expect(selector.max_staleness).to eq(options[:max_staleness])
end
end
end
describe '#==' do
context 'when max staleness is the same' do
let(:options) do
{ max_staleness: 95 }
end
let(:other) do
described_class.new(options)
end
it 'returns true' do
expect(selector).to eq(other)
end
end
context 'when max staleness is different' do
let(:other_options) do
{ max_staleness: 100 }
end
let(:other) do
described_class.new(other_options)
end
it 'returns false' do
expect(selector).not_to eq(other)
end
end
end
describe '#to_mongos' do
context 'tag sets not provided' do
it 'returns a read preference formatted for mongos' do
expect(selector.to_mongos).to eq({ :mode => 'primaryPreferred' })
end
end
context 'tag set provided' do
let(:tag_sets) { [tag_set] }
it 'returns a read preference formatted for mongos' do
expect(selector.to_mongos).to eq(
{ :mode => 'primaryPreferred', :tags => tag_sets}
)
end
end
context 'max staleness not provided' do
let(:expected) do
{ :mode => 'primaryPreferred' }
end
it 'returns a read preference formatted for mongos' do
expect(selector.to_mongos).to eq(expected)
end
end
context 'max staleness provided' do
let(:max_staleness) do
100
end
let(:expected) do
{ :mode => 'primaryPreferred', maxStalenessSeconds: 100 }
end
it 'returns a read preference formatted for mongos' do
expect(selector.to_mongos).to eq(expected)
end
end
end
describe '#select_in_replica_set' do
context 'no candidates' do
let(:candidates) { [] }
it 'returns an empty array' do
expect(selector.send(:select_in_replica_set, candidates)).to be_empty
end
end
context 'single primary candidate' do
let(:candidates) { [primary] }
it 'returns an array with the primary' do
expect(selector.send(:select_in_replica_set, candidates)).to eq( [primary] )
end
end
context 'single secondary candidate' do
let(:candidates) { [secondary] }
it 'returns an array with the secondary' do
expect(selector.send(:select_in_replica_set, candidates)).to eq( [secondary] )
end
end
context 'primary and secondary candidates' do
let(:candidates) { [secondary, primary] }
let(:expected) { [primary] }
it 'returns an array with the primary' do
expect(selector.send(:select_in_replica_set, candidates)).to eq(expected)
end
end
context 'secondary and primary candidates' do
let(:candidates) { [secondary, primary] }
let(:expected) { [primary] }
it 'returns an array with the primary' do
expect(selector.send(:select_in_replica_set, candidates)).to eq(expected)
end
end
context 'tag sets provided' do
let(:tag_sets) { [tag_set] }
let(:matching_primary) do
make_server(:primary, :tags => server_tags, address: default_address )
end
let(:matching_secondary) do
make_server(:secondary, :tags => server_tags, address: default_address )
end
context 'single candidate' do
context 'primary' do
let(:candidates) { [primary] }
it 'returns array with primary' do
expect(selector.send(:select_in_replica_set, candidates)).to eq([primary])
end
end
context 'matching_primary' do
let(:candidates) { [matching_primary] }
it 'returns array with matching primary' do
expect(selector.send(:select_in_replica_set, candidates)).to eq([matching_primary])
end
end
context 'matching secondary' do
let(:candidates) { [matching_secondary] }
it 'returns array with matching secondary' do
expect(selector.send(:select_in_replica_set, candidates)).to eq([matching_secondary])
end
end
context 'secondary' do
let(:candidates) { [secondary] }
it 'returns an empty array' do
expect(selector.send(:select_in_replica_set, candidates)).to be_empty
end
end
end
context 'multiple candidates' do
context 'no matching secondaries' do
let(:candidates) { [primary, secondary, secondary] }
it 'returns an array with the primary' do
expect(selector.send(:select_in_replica_set, candidates)).to eq([primary])
end
end
context 'one matching primary' do
let(:candidates) { [matching_primary, secondary, secondary] }
it 'returns an array of the primary' do
expect(selector.send(:select_in_replica_set, candidates)).to eq([matching_primary])
end
end
context 'one matching secondary' do
let(:candidates) { [primary, matching_secondary, secondary] }
let(:expected) { [primary] }
it 'returns an array of the primary' do
expect(selector.send(:select_in_replica_set, candidates)).to eq(expected)
end
end
context 'two matching secondaries' do
let(:candidates) { [primary, matching_secondary, matching_secondary] }
let(:expected) { [primary] }
it 'returns an array of the primary ' do
expect(selector.send(:select_in_replica_set, candidates)).to eq(expected)
end
end
context 'one matching primary, one matching secondary' do
let(:candidates) { [primary, matching_secondary, secondary] }
let(:expected) { [primary] }
it 'returns an array of the primary' do
expect(selector.send(:select_in_replica_set, candidates)).to eq(expected)
end
end
end
end
context 'high latency servers' do
let(:far_primary) { make_server(:primary, :average_round_trip_time => 0.100, address: default_address) }
let(:far_secondary) { make_server(:secondary, :average_round_trip_time => 0.113, address: default_address) }
context 'single candidate' do
context 'far primary' do
let(:candidates) { [far_primary] }
it 'returns array with far primary' do
expect(selector.send(:select_in_replica_set, candidates)).to eq([far_primary])
end
end
context 'far secondary' do
let(:candidates) { [far_secondary] }
it 'returns array with far primary' do
expect(selector.send(:select_in_replica_set, candidates)).to eq([far_secondary])
end
end
end
context 'multiple candidates' do
context 'primary available' do
context 'local primary, local secondary' do
let(:candidates) { [primary, secondary] }
let(:expected) { [primary] }
it 'returns an array of the primary' do
expect(selector.send(:select_in_replica_set, candidates)).to eq(expected)
end
end
context 'local primary, far secondary' do
let(:candidates) { [primary, far_secondary] }
let(:expected) { [primary] }
it 'returns an array of the primary' do
expect(selector.send(:select_in_replica_set, candidates)).to eq(expected)
end
end
context 'far primary, local secondary' do
let(:candidates) { [far_primary, secondary] }
let(:expected) { [far_primary] }
it 'returns an array of the far primary' do
expect(selector.send(:select_in_replica_set, candidates)).to eq(expected)
end
end
context 'far primary, far secondary' do
let(:candidates) { [far_primary, far_secondary] }
let(:expected) { [far_primary] }
it 'returns an array of the far primary' do
expect(selector.send(:select_in_replica_set, candidates)).to eq(expected)
end
end
context 'two local servers, one far server' do
context 'local primary, local secondary, far secondary' do
let(:candidates) { [primary, secondary, far_secondary] }
let(:expected) { [primary] }
it 'returns an array of the primary' do
expect(selector.send(:select_in_replica_set, candidates)).to eq(expected)
end
end
context 'two local secondaries' do
let(:candidates) { [far_primary, secondary, secondary] }
let(:expected) { [far_primary] }
it 'returns an array with primary' do
expect(selector.send(:select_in_replica_set, candidates)).to eq(expected)
end
end
end
end
context 'primary not available' do
context 'one secondary' do
let(:candidates) { [secondary] }
let(:expected) { [secondary] }
it 'returns an array with the secondary' do
expect(selector.send(:select_in_replica_set, candidates)).to eq(expected)
end
end
context 'one local secondary, one far secondary' do
let(:candidates) { [secondary, far_secondary] }
let(:expected) { [secondary] }
it 'returns an array of the secondary' do
expect(selector.send(:select_in_replica_set, candidates)).to eq(expected)
end
end
context 'two local secondaries, one far secondary' do
let(:candidates) { [secondary, secondary, far_secondary] }
let(:expected) { [secondary, secondary] }
it 'returns an array of the secondary' do
expect(selector.send(:select_in_replica_set, candidates)).to eq(expected)
end
end
end
end
end
end
end
|
class TreatmentTime < ActiveRecord::Base
belongs_to :visitation_time
belongs_to :treatment
end
|
#==============================================================================
# *** QuestData
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# This module contains all the configuration data for the quest journal
#==============================================================================
module QuestData
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# * Setup Quest
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def self.setup_quest(quest_id)
q = { objectives: [] }
case quest_id
#\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
# BEGIN Editable Region B
#||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
# Quest Setup
#
# This is where you set up the data for every quest in the game. While
# it may seem complicated, I urge you to pay attention and, once you get
# the hang of it, I am sure it will quickly become second nature.
#
# Every single quest should be set up in the following format, but note
# that if you are not setting anything for a particular aspect, you can
# delete that line. Anyway, this is what each quest should look like, with
# the values on the left being the default values if you don't set them:
#
# when quest_id
# q[:name] = "??????"
# q[:icon_index] = 0
# q[:level] = 0
# q[:description] = ""
# q[:banner] = ""
# q[:banner_hue] = 0
# q[:objectives][0] = ""
# q[:objectives][1] = ""
# q[:objectives][2] = ""
# q[:objectives][n] = ""
# q[:prime_objectives] = [0, 1, 2, n]
# q[:custom_categories] = []
# q[:client] = ""
# q[:location] = ""
# q[:rewards] = []
# q[:common_event_id] = 0
# q[:layout] = false
#
# For each line, with the exception of objectives, it is only the value on
# the right of the equals sign that you will need to change. Now I will
# explain each line:
#
# when quest_id
# quest_id - is an integer of your choosing, and this is how you
# reference a quest in order to advance and do anything else. It
# must be unique for every quest; if you use 1 for the first quest,
# you cannot use 1 for any other quest.
#
# q[:name] = ""
# "" - This line sets the name of the quest which shows in the Quest
# List.
#
# q[:icon_index] = 0
# 0 - This line sets the icon to be used for this quest. It will show
# to the left of the quest's name in the Quest List.
#
# q[:level] = 0
# 0 - This line sets the level of the quest. If 0, no level will be
# shown. See the level options at lines 441-458 for more detail.
#
# q[:description] = ""
# "" - This line sets the description of the quest. You can use message
# codes in this string, but if you are using "" then you need to use
# \\ to identify codes and not just \. Ie. It's \\v[x], not \v[x]
#
# q[:objectives][0] = ""
# q[:objectives][1] = ""
# q[:objectives][2] = ""
# q[:objectives][n] = ""
# Objectives are slightly different. Notice that after q[:objectives] on
# each line there is an integer enclosed in square brackets:
# [n] - This is the ID of the objective, and n MUST be an integer. No
# quest can have more than one objective with the same ID. This is
# how you identify which objective you want to reveal, complete or
# fail. That said, you can make as many objectives as you want, as
# long as you give them all distinct IDs. The IDs should be in
# sequence as well, so there shouldn't be a q[:objectives][5] if
# there is no q[:objectives][4].
# "" - This is the text of the objective. You can use message codes in
# this string, but if you are using "" then you will need to use
# \\ to identify codes and not just \. Ie: It's \\v[x], not \v[x]
#
# q[:prime_objectives] = [0, 1, 2, n]
# [0, 1, 2, n] - This array determines what objectives need to be
# completed in order for the quest to be complete. In other words,
# all of the objectives with the IDs in this array need to be
# complete for the quest to be complete. If any one of them is
# failed, the quest will be failed. If you remove this line
# altogether, then all objectives are prime. If you set this to [],
# then the quest will never be automatically completed or failed and
# you need to use the manual options described at lines 208-219.
#
# q[:custom_categories] = []
# [] - This allows you to set an array of custom categories for this
# quest, whiich means this quest will show up in each of those
# categories if you add it to the CATEGORIES array at line 370.
# Note that each category you make must be identified by a unique
# :symbol, and you must set up all the category details for that
# :symbol.
#
# q[:banner] = ""
# "" - This line sets the banner to be used for a quest. It must be the
# filename of an image in the Pictures folder of Graphics.
#
# q[:banner_hue] = 0
# 0 - The hue of the banner graphic, if used
#
# q[:client] = ""
# "" - This line sets the client name for this quest. (basic data)
#
# q[:location] = ""
# "" - This line sets the location of the quest. (basic data)
#
# q[:rewards] = []
# [] - In this array, you can identify particular rewards that will
# show up. Each reward should be in its own array and can be any of
# the following:
# [:item, ID, n],
# [:weapon, ID, n],
# [:armor, ID, n],
# [:gold, n],
# [:exp, n],
# where ID is the ID of the item, weapon or armour you want
# distributed and n is the amount of the item, weapon, armor, gold,
# or experience you want distributed. Additionally, you can also set
# some text to show up in the rewards format but which wouldn't be
# automatically distributed. You would need to specify that type of
# reward text in the following format:
# [:string, icon_index, "string", "vocab"],
# where icon_index is the icon to be shown, "string" is what you
# would show up as the amount, and "vocab" is what would show up as a
# label between the icon and the amount.
#
#
# q[:common_event_id] = 0
# 0 - This allows you to call the identified common event immediately
# and automatically once the quest is completed. It is generally
# not recommended, as for most quests you should be controlling it
# enough not to need this feature.
#
# q[:layout] = false
# false - The default value for this is false, and when it is false the
# layout for the quest will be inherited from the default you set at
# 302. However, you can also give the quest its own layout - the
# format would be the same as you set for the default at line 307.
#
# Template:
#
# When making a new quest, I recommend that you copy and paste the
# following template, removing whichever lines you don't want to alter.
# Naturally, you need to remove the #~. You can do so by highlighting
# the entire thing and pressing CTRL+Q:
#~ when 2 # <= REMINDER: The Quest ID MUST be unique
#~ q[:name] = "??????"
#~ q[:icon_index] = 0
#~ q[:level] = 0
#~ q[:description] = ""
#~ # REMINDER: You can make as many objectives as you like, but each must
#~ # have a unique ID.
#~ q[:objectives][0] = ""
#~ q[:objectives][1] = ""
#~ q[:objectives][2] = ""
#~ q[:prime_objectives] = [0, 1, 2]
#~ q[:custom_categories] = []
#~ q[:banner] = ""
#~ q[:banner_hue] = 0
#~ q[:client] = ""
#~ q[:location] = ""
#~ q[:rewards] = []
#~ q[:common_event_id] = 0
when 1 # Quest 1 - SAMPLE QUEST
q[:name] = "Sieged Deadend"
q[:level] = 5
q[:icon_index] = 7
q[:description] = "Crystal Empire is fell to the King Sombra, now must report to the Princess in Canterlot."
q[:objectives][0] = "(Main)Escape from Crystal Empire"
q[:objectives][1] = "(Selective)Save Crystal Ponies"
q[:objectives][2] = "(Selective)Save the librarian"
q[:objectives][3] = "Find the mysterious device in the library"
q[:objectives][4] = "Gather the infromation in the library, find way to active the device and leave here"
q[:prime_objectives] = [1]
q[:custom_categories] = []
q[:banner] = ""
q[:banner_hue] = 0
q[:client] = "Mainline Mission"
q[:location] = "Crystal Empire"
q[:common_event_id] = 0
q[:rewards] = [
#[:item, 1, 3],
[:gold, 100],
]
q[:layout] = false
when 2
q[:name] = "Tutorial"
q[:level] = 1
q[:icon_index] = 230
q[:description] = "Learn the game mechanics and how to play."
q[:objectives][0] = "Enable the tactic mode"
q[:objectives][1] = "Enable the tactic mode, command your teammate move to the flag"
q[:objectives][2] = "Enable the tactic mode, command yout teammate to attack the enemy"
q[:prime_objectives] = [1]
q[:custom_categories] = []
q[:banner] = ""
q[:banner_hue] = 0
q[:client] = "GM"
q[:location] = "Celestia Plane"
q[:common_event_id] = 0
q[:rewards] = [
[:item, 1, 3],
]
q[:layout] = false
#||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
# END Editable Region B
#//////////////////////////////////////////////////////////////////////
end
q
end
end
|
# frozen_string_literal: true
class RenameColumns < ActiveRecord::Migration[6.0]
def up
rename_column :jerseys, :fullName, :name
end
end
|
require "json"
require "util"
require "inventory"
require "map"
require "permissive_fov"
class Player
include Util
include PermissiveFieldOfView
STATUS=[
:hp, :hp_max, :energy, :energy_max,
:str, :dex, :int, :lv, :experience, :ac, :ev, :regeneration_count,
:speed, :spent,
:x, :y, :current_level_num, :enable_minimap
]
ACCESSOR = STATUS +
[:inventory, :maps, :dungeon] +
[:fov, :fov_shade, :mode, :maps ] +
[:s, :mini_map]
attr_accessor *ACCESSOR
def load( save_data )
save_data.each{|k,v|
next if k == "inventory"
next if k == "equipment"
self.send k+"=", v
}
inventory.load save_data["inventory"]
save_data["equipment"].each{|k,v|
equipment[ k.intern ] = inventory.slot[v.to_i]
}
@maps = []
(dungeon.levels.size-1).times{|i|
v = JSON.parse File.read "#{$save_dir}/map_#{1+i}.json"
@maps[1+i] = Map.new( dungeon.levels[1+i].w, dungeon.levels[1+i].h )
v.each.with_index{|row,y|
row.each.with_index{|c,x|
@maps[1+i][x,y] = Grid.new c[0], c[1] if c
}
}
}
update_fov
update
end
def save_json(target, file_name)
save_file = open("#{$save_dir}/#{file_name}.json","w")
#JSON.dump player.to_h, save_file
save_data = JSON.pretty_generate target
save_file.write save_data
save_file.close
end
def save
puts "save"
save_json self.to_h, "#{name}"
save_json dungeon.to_h, "dungeon"
save_json current_level.to_h, "level_#{current_level_num}"
save_json self.map.to_a, "map_#{current_level_num}"
end
def to_h
h = Hash[ *(STATUS.map{|k| [ k, self.send(k) ] }.flatten) ]
h[:inventory] = inventory.to_a
h[:equipment] = Hash[ *( equipment.map{|k,v| [k, v ? inventory.slot.index(v) : nil] }.flatten(1) ) ]
h
end
def self.config
$player_config ||= JSON.parse File.read("data/player.json")
end
def config
Player.config
end
def message( m, gsub_list={} )
Crawl.logging messages["player"][m.to_s], gsub_list
end
def initialize( dungeon )
@dungeon = dungeon
@s = new_surface(32,32)
@mini_map_size = 50
@mini_map = new_surface(@mini_map_size,@mini_map_size)
@fov_shade = new_surface(SCREEN_W, SCREEN_H)
@fov = []
@inventory = Inventory.new(self)
end
def init_with_default
STATUS.each{|key|
self.send( "#{key}=", config["default_status"][key.to_s].to_i )
}
@maps = []
config["default_equipment"].each{|k,v|
if k=="accessory1" or k=="accessory2"
i = Item.new( "accessory", v )
else
i = Item.new( k, v )
end
equipment[k.to_sym] = i
@inventory.push i
}
config["default_inventory"].each{|v|
@inventory.push Item.new(v[0],v[1])
}
update
end
def map
maps[current_level_num]
end
def put_chip( place )
if equipment[ place ] and equipment[ place ].status["chip"]
Tile.blit_to( s, 0, 0, equipment[ place ].status["chip"] )
end
end
def update
s.fill_rect(0,0,s.w,s.h,[0,0,0,0])
Tile.blit_to( s, 0,0, config["chip"]["body"] )
Tile.blit_to( s, 0,0, config["chip"]["hair"] )
put_chip :boots
put_chip :armor
put_chip :helm
put_chip :accessory1
put_chip :accessory2
put_chip :weapon
put_chip :shield
end
def effective_ev
@ev + equipment.inject(0){|r,i| r+(i[1] ? i[1].ev : 0) }
end
def effective_ac
@ac + equipment.inject(0){|r,i| r+(i[1] ? i[1].ac : 0) }
end
def weight
inventory.weight
end
def weight_limit
str*3
end
def name
config["name"]
end
def equipped?(item)
equipment.any?{|k,v| v==item}
end
def pickup
unless items_here[0]
message :no_pickup_item
return false
end
unless inventory.empty_slot
message :inventory_full
return false
end
i = item_pickup( 0 )
inventory.push( i )
message :pickup, {:item_name=>i.name}
@spent -= 10
true
end
def drop(item)
return false unless item
item_drop( item )
inventory.pop item
equipment.each{|k,v|
if v == item
equipment[k] = nil
update
end
}
inventory.listing
@spent -= 10
true
end
def eat(food)
return false unless food
return false unless food.type == :ration
e = food.status["spec"]["energy"].to_i
energy_add e if e > 0
if food.status["message_at_eat"]
Crawl.logging food.status["message_at_eat"]
end
if food.status["spec"]["after"]
food.id = food.status["spec"]["after"]
else
inventory.pop food
end
inventory.listing
@spent -= 10
true
end
def quaff(potion)
return false unless potion
return false unless potion.type == :potion
@spent -= 10
message :quaff, {:potion_name=>potion.name}
if potion.status["message_at_quaff"]
Crawl.logging potion.status["message_at_quaff"]
end
e = potion.status["spec"]["energy"].to_i
hp_dice = potion.status["spec"]["hp"]
energy_add 40+e, false
if hp_dice
@hp += dice(hp_dice)
end
if potion.status["spec"]["after"]
potion.id = potion.status["spec"]["after"]
else
inventory.pop potion
end
inventory.listing
true
end
def die
message :die
end
def hit?( monster, weapon_hit )
to_hit = rand( 15 + dex/2 + weapon_hit )
monster.effective_ev <= to_hit
end
def weapon
equipment[:weapon]
end
def lv_up
@lv += 1
@hp_max += 4
@hp += 4
@hp = @hp_max if @hp > @hp_max
end
def get_experience(xp)
lv_table = [
0,10,30,70,140,270,520,1010,1980,3910,
7760, 15450, 29000, 48500, 74000, 105500, 143000, 186500, 236000, 291500,
353000, 420500, 494000, 573500, 659000, 750500, 848000
]
@experience += xp
loop do
if lv_table[ lv ] <= @experience
lv_up
message :lv_up, {:lv=>lv}
else
break
end
end
end
def attack(monster)
gsub_list = {:name=>monster.name}
if weapon
gsub_list[:weapon] = weapon.name
power = weapon.status["spec"]["power"].to_i
weapon_type = weapon.status["spec"]["type"][0]
weapon_attributes = weapon.status["spec"]["attributes"] || []
weapon_hit = weapon.status["spec"]["hit"]
else
power = 1
weapon_type = "slap"
weapon_attributes = []
weapon_hit = 0
end
if weapon_attributes.include?("use_energy")
energy_add -80
end
energy_add -3
@spent -= 10
unless hit?( monster, weapon_hit )
message :miss_by_dodge, {:name=>name, :target_name=>monster.name}
return
end
damage = rand(1+power).to_i - rand(1+monster.effective_ac).to_i
if damage <= 0
damage = 0
message :miss_by_armor, {:name=>name, :target_name=>monster.name}
else
gsub_list[:damage] = damage
monster.hp -= damage
message weapon_type, gsub_list
if monster.hp <= 0
message :kill, gsub_list
get_experience monster.xp
end
end
end
def monster_in_fov?
fov.any?{|f|
current_level.monster_at( f[0], f[1] )
}
end
def update_fov
@fov = get_fov( x, y, 8 )
@fov_shade.fill_rect( 0,0,SCREEN_W, SCREEN_H, [0,0,0,196] );
fov.each{|f|
fx = (f[0] - x)*32+CENTER_X
fy = (f[1] - y)*32+CENTER_Y
@fov_shade.fill_rect( fx,fy, 32,32, [0,0,0,0] );
map[*f] = current_level.grid[ f[0], f[1] ].clone
}
end
def mini_map
colors = {wall:gray.push(128),floor:ivory.push(128),ladder_down:magenta.push(128)}
@mini_map.fill_rect( 0,0,@mini_map.w,@mini_map.h,[0,0,0,0] )
@mini_map_size.times{|dx|
@mini_map_size.times{|dy|
px = x- @mini_map_size/2 +dx
py = y- @mini_map_size/2 +dy
next if px<0 or py<0
if px==x and py==y
@mini_map.fill_rect( dx,dy,1,1, white )
next
end
g = map[ px, py ]
next unless g
c = colors[g.type]
@mini_map.fill_rect( dx,dy,1,1, c )
}
}
@mini_map
end
def draw_map( target_surface )
ox = x - CENTER_X/32
oy = y - CENTER_Y/32
SCREEN_W/32.times{|dx|
SCREEN_H/32.times{|dy|
next if ox+dx<0 or oy+dy<0
g = map[ ox+dx, oy+dy ]
next unless g
current_level.blit target_surface, dx*32, dy*32, g
}
}
end
def entering_new_level
@current_level_num += 1
dungeon.down_to current_level_num
maps[ current_level_num ] ||= Map.new( w, h )
move_to_random_position
update_fov
end
def climb_downwards
if grid_here.type == :ladder_down
message :climb_downwards
save
entering_new_level
return true
end
message :no_ladder
return false
end
def move_to_random_position
loop do
nx = rand(w)
ny = rand(h)
if current_level.empty_grid?( nx, ny )
to nx,ny
break
end
end
end
def energy_add( e, with_message=true )
@energy += e.to_i
if e > 0
if e > 1000
message :recover_energy_greatly if with_message
else
message :recover_energy if with_message
end
end
if energy_max <= energy
@energy = energy_max
message :energy_max if with_message
end
if energy < 0
@energy = 0
message :energy_empty if with_message
@hp -= 2
end
end
def regeneration
return unless hp < hp_max
@regeneration_count -= 1
if regeneration_count <= 0
@hp += 1
@hp = hp_max if hp > hp_max
@regeneration_count = 10+rand(10)
end
end
def rest
energy_add -3
@spent -= 10
regeneration
end
def to(x,y)
@x = x
@y = y
end
def move_to(x,y)
if m = current_level.monster_at(x,y)
attack( m )
return true
end
to(x,y)
unless items_here.empty?
items_here.each{|i|
message :item_here, {:item_name=>i.name}
}
end
energy_add -3
@spent -= 10
regeneration
update_fov
end
def get_fov(x,y,r)
@fov = []
do_fov(x,y,r)
@fov
end
def equipment
inventory.equipment
end
####
def current_level
dungeon.levels[current_level_num]
end
def grid_here
current_level.grid[x,y]
end
def items_here
current_level.items(x,y)
end
def item_drop(item)
current_level.item_drop(x,y,item)
end
def item_pickup(n)
current_level.item_pickup(x,y,n)
end
def blocked?(x,y)
current_level.blocked?(x,y)
end
def light(x,y)
@fov << [x,y]
end
def w
current_level.w
end
def h
current_level.h
end
end |
require 'rails_helper'
RSpec.describe User, type: :model do
# pending "add some examples to (or delete) #{__FILE__}"
let!(:user) { create(:user) }
describe 'validations' do
it { should validate_presence_of(:username) }
it { should validate_presence_of(:password_digest) }
it { should validate_presence_of(:session_token) }
it { should validate_uniqueness_of(:username) }
it { should validate_length_of(:password) }
end
describe 'associations' do
it { should have_many(:favorites) }
it { should have_many(:favorite_benches) }
end
describe 'model_methods' do
describe '.find_by_credentials' do
context 'when given correct credentials' do
it 'should find the right user' do
# test goes here
expect(User.find_by_credentials('breakfast', 'password')).to eq(:user)
end
end
context 'when given incorrect credentials' do
it 'should return nil' do
# test goes here
expect(User.find_by_credentials('breakfast', 'passwor')).to be_nil
end
end
end
end
end
|
require 'rails_helper'
RSpec.describe User, type: :model do
describe 'belongs to relationship' do
it 'should have many restaurants' do
u = User.reflect_on_association(:restaurants)
expect(u.macro).to eq :has_many
end
it 'should have many reviews' do
u = User.reflect_on_association(:reviews)
expect(u.macro).to eq :has_many
end
end
end
|
class AddColumnAvailabilityZoneToAmazons < ActiveRecord::Migration
def change
add_column :amazons, :availability_zone, :string
end
end
|
class CreateOrders < ActiveRecord::Migration[5.1]
def change
create_table :orders do |t|
t.date :delivery_date
t.references :food_business, foreign_key: true
t.references :supplier, foreign_key: true
t.decimal :gross_total
t.decimal :gst
t.string :order_number
t.timestamps
t.index :created_at
end
end
end
|
# Copyright 2015 ClearStory Data, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Starts the given Monit service.
actions :start
# Stops the given Monit service.
actions :stop
# Restarts the given Monit service.
actions :restart
# Does not do anything.
actions :nothing
default_action :nothing
# If this is specified and the service is not registered with Monit, it will be started as a
# regular service using the standard "service" resource.
attribute :fallback_to_regular_service, kind_of: [TrueClass, FalseClass], default: false
# A host:port combination of another service. If this is specified, we wait for this the given host
# to start listening on the given TCP port before attempting to start or restart the service. This
# could be used for handling dependencies on remote services.
attribute :wait_for_host_port, String
|
class AddDefaultToList < ActiveRecord::Migration[5.0]
def change
add_column :user_lists, :default, :boolean, default: false
User.find_each do |user|
user.user_lists.order(sort_order: :asc).first&.update(default: true)
end
end
end
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'Contacts', type: :request do
include AppHelper
context 'GET API' do
describe 'return success' do
it 'get all Contacts' do
get '/api/contacts', headers: headers
expect(response).to have_http_status(200)
end
it 'get contact detail' do
get "/api/contacts/#{contact.id}", headers: headers
expect(response).to have_http_status(200)
expect(response.body).to_not be_empty
end
end
describe 'return failed' do
it 'get contact detail' do
get '/api/contacts/12', headers: headers
expect(response).to have_http_status(500)
end
end
end
context 'POST API' do
let(:valid_params) { { contact: { phone: '08565243546' } } }
let(:invalid_params) { { contact: { phone: nil } } }
describe 'return success' do
it 'post using valid params' do
params = { contact: { phone: recipient.phone } }
post '/api/contacts', params: params, headers: headers
expect(response).to have_http_status(201)
end
end
describe 'return failed' do
it 'post using invalid params' do
post '/api/contacts', params: invalid_params, headers: headers
expect(response).to have_http_status(422)
end
end
end
context 'PUT API' do
let(:valid_params) { { contact: { phone: '08565243546' } } }
describe 'return success' do
it 'contact is created by current user' do
put "/api/contacts/#{contact.id}", params: valid_params, headers: headers
expect(response).to have_http_status(200)
end
end
describe 'should return route not found' do
it 'contact is not created by current user' do
put "/api/contacts/#{contact_recipient.id}", params: valid_params, headers: headers_recipient
expect(response).to have_http_status(404)
end
end
it 'contact does not exist' do
put '/api/contacts/12', params: valid_params, headers: headers
expect(response).to have_http_status(500)
end
end
context 'DELETE API' do
describe 'return success' do
it 'contact is created by current user' do
delete "/api/contacts/#{contact.id}", headers: headers
expect(response).to have_http_status(200)
end
end
describe 'return failed or route not found' do
it 'contact is not created by current user' do
delete "/api/contacts/#{contact_recipient.id}", headers: headers
expect(response).to have_http_status(404)
end
end
end
end
|
class CreateReferences < ActiveRecord::Migration
def change
create_table :encyclical_references do |t|
t.references :content_fragment
t.references :encyclical
t.integer :start
t.integer :end
t.timestamps
end
add_index :encyclical_references, :content_fragment_id
add_index :encyclical_references, :encyclical_id
end
end
|
require 'test_helper'
class ShipmentPackerTest < Minitest::Test
def setup
@dimensions = [5.1, 15.2, 30.5]
end
def test_pack_divide_order_into_a_single_package
items = [{ grams: 1, quantity: 1, price: 1.0 }]
packages = ShipmentPacker.pack(items, @dimensions, 1, 'USD')
assert_equal 1, packages.size
package = packages.first
assert_equal 1, package.weight
end
def test_divide_order_with_multiple_lines_into_a_single_package
items = [{ grams: 1, quantity: 2, price: 1.0 }]
packages = ShipmentPacker.pack(items, @dimensions, 2, 'USD')
assert_equal 1, packages.size
package = packages.first
assert_equal 2, package.weight
end
def test_divide_order_with_single_line_into_two_packages
items = [{ grams: 1, quantity: 2, price: 1.0 }]
packages = ShipmentPacker.pack(items, @dimensions, 1, 'USD')
assert_equal 2, packages.size
packages.each do |package|
assert_equal 1, package.weight
end
end
def test_divide_order_with_single_line_into_two_packages_max_weight_as_float
max_weight = 68038.8555
items = [{ grams: 45359, quantity: 2, price: 1.0 }]
packages = ShipmentPacker.pack(items, @dimensions, max_weight, 'USD')
assert_equal 2, packages.size
packages.each do |package|
assert_equal 45359, package.weight
end
end
def test_divide_order_with_multiple_lines_into_two_packages
items = [
{ grams: 1, quantity: 1, price: 1.0 },
{ grams: 1, quantity: 1, price: 1.0 }
]
packages = ShipmentPacker.pack(items, @dimensions, 1, 'USD')
assert_equal 2, packages.size
packages.each do |package|
assert_equal 1, package.weight
end
end
def test_divide_order_into_two_packages_mixing_line_items
items = [
{ grams: 1, quantity: 1, price: 1.0 },
{ grams: 1, quantity: 1, price: 1.0 },
{ grams: 1, quantity: 1, price: 1.0 }
]
packages = ShipmentPacker.pack(items, @dimensions, 2, 'USD')
assert_equal 2, packages.size
assert_equal 2, packages[0].weight
assert_equal 1, packages[1].weight
end
def test_raise_overweight_exception_when_a_single_item_exceeds_the_maximum_weight_of_a_package
assert_raises(ShipmentPacker::OverweightItem) do
items = [{ grams: 2, quantity: 1, price: 1.0 }]
ShipmentPacker.pack(items, @dimensions, 1, 'USD')
end
end
def test_raise_over_weight_exceptions_before_over_package_limit_exceptions
assert_raises(ShipmentPacker::OverweightItem) do
items = [{ grams: 5, quantity: ShipmentPacker::EXCESS_PACKAGE_QUANTITY_THRESHOLD + 1, price: 1.0 }]
ShipmentPacker.pack(items, @dimensions, 4, 'USD')
end
end
def test_returns_an_empty_list_when_no_items_provided
assert_equal [], ShipmentPacker.pack([], @dimensions, 1, 'USD')
end
def test_add_summarized_prices_for_all_items_and_currency_to_package
items = [
{ grams: 1, quantity: 3, price: 1.0 },
{ grams: 2, quantity: 1, price: 2.0 }
]
packages = ShipmentPacker.pack(items, @dimensions, 5, 'USD')
assert_equal 1, packages.size
assert_equal 500, packages.first.value
assert_equal 'USD', packages.first.currency
end
def test_divide_items_and_prices_accordingly_when_splitting_into_two_packages
items = [
{ grams: 1, quantity: 1, price: 1.0 },
{ grams: 1, quantity: 1, price: 1.0 },
{ grams: 1, quantity: 1, price: 1.0 }
]
packages = ShipmentPacker.pack(items, @dimensions, 2, 'USD')
assert_equal 2, packages.size
assert_equal 200, packages[0].value
assert_equal 100, packages[1].value
assert_equal 'USD', packages[0].currency
assert_equal 'USD', packages[1].currency
end
def test_symbolize_item_keys
string_key_items = [{ 'grams' => 1, 'quantity' => 1, 'price' => 1.0 }]
indifferent_access_items = [{ 'grams' => 1, 'quantity' => 1, 'price' => 1.0 }.with_indifferent_access]
[string_key_items, indifferent_access_items].each do |items|
packages = ShipmentPacker.pack(items, @dimensions, 1, 'USD')
assert_equal 1, packages.size
package = packages.first
assert_equal 1, package.weight
assert_equal 100, package.value
end
end
def test_cast_quantity_and_grams_to_int
items = [{ grams: '1', quantity: '1', price: '1.0' }]
packages = ShipmentPacker.pack(items, @dimensions, 1, 'USD')
package = packages.first
assert_equal 1, package.weight
assert_equal 100, package.value
end
def test_excess_packages_raised_over_threshold_before_packing_begins
ActiveShipping::Package.expects(:new).never
items = [{ grams: 1, quantity: ShipmentPacker::EXCESS_PACKAGE_QUANTITY_THRESHOLD + 1, price: 1.0 }]
assert_raises(ShipmentPacker::ExcessPackageQuantity) do
ShipmentPacker.pack(items, @dimensions, 1, 'USD')
end
end
def test_excess_packages_not_raised_at_threshold
items = [{ grams: 1, quantity: ShipmentPacker::EXCESS_PACKAGE_QUANTITY_THRESHOLD, price: 1.0 }]
packages = ShipmentPacker.pack(items, @dimensions, 1, 'USD')
assert_predicate packages, :present?
end
def test_excess_packages_not_raised_below_threshold
items = [{ grams: 1, quantity: ShipmentPacker::EXCESS_PACKAGE_QUANTITY_THRESHOLD - 1, price: 1.0 }]
packages = ShipmentPacker.pack(items, @dimensions, 1, 'USD')
assert_predicate packages, :present?
end
def test_excess_packages_with_slightly_larger_max_weight_than_item_weight
max_weight = 750
items = [{ grams: 500, quantity: ShipmentPacker::EXCESS_PACKAGE_QUANTITY_THRESHOLD + 1, price: 1.0 }]
assert_raises(ShipmentPacker::ExcessPackageQuantity) do
ShipmentPacker.pack(items, @dimensions, max_weight, 'USD')
end
end
def test_lots_of_zero_weight_items
items = [{ grams: 0, quantity: 1_000_000, price: 1.0 }]
packages = ShipmentPacker.pack(items, @dimensions, 1, 'USD')
assert_equal 1, packages.size
assert_equal 0, packages[0].grams
assert_equal 100_000_000, packages[0].value
end
def test_dont_destroy_input_items
items = [{ grams: 1, quantity: 5, price: 1.0 }]
packages = ShipmentPacker.pack(items, @dimensions, 10, 'USD')
assert_equal 1, items.size
assert_equal 1, packages.size
end
def test_dont_modify_input_item_quantities
items = [{ grams: 1, quantity: 5, price: 1.0 }]
ShipmentPacker.pack(items, @dimensions, 10, 'USD')
assert_equal 5, items.first[:quantity]
end
def test_items_with_negative_weight
items = [{ grams: -1, quantity: 5, price: 1.0 }]
ShipmentPacker.pack(items, @dimensions, 10, 'USD')
assert_equal 5, items.first[:quantity]
end
end
|
require 'matrix' #matrix library in Ruby standard library
def spiral_order(n)
row_begin = 0
row_end = n - 1
column_begin = 0
column_end = n - 1
counter = 1
results = Matrix.build(n){|row,col| 0 } #creates a matrix n x n, with 0 as value
direction = 0
while(row_begin <= row_end && column_begin <= column_end)
if(direction == 0)
column_begin.upto(column_end) do |i|
results[row_begin,i] = counter
counter += 1
end
row_begin += 1
direction = 1
elsif(direction == 1)
row_begin.upto(row_end) do |j|
results[j,column_end] = counter
counter += 1
end
column_end -= 1
direction = 2
elsif(direction == 2)
column_end.downto(column_begin) do |k|
results[row_end,k] = counter
counter += 1
end
row_end -= 1
direction =3
elsif(direction == 3)
row_end.downto(row_begin) do |l|
results[l,column_begin] = counter
counter += 1
end
column_begin += 1
direction = 0
end
end
return results.to_a #results will be a matrix so call .to_a to return an array of arrays
end
|
class Thinking < ApplicationRecord
validates :factor, presence: true
has_many :relationships, dependent: :destroy
end
|
require 'test/helpers'
describe 'apt_control include' do
include CLIHelper
before do
setup_dirs
with_default_reprepro_config
end
it 'does nothing if there are no packages to include' do
build 'worker', '0.5.5-5'
include 'production', 'worker', '0.5.5-5'
control production: { worker: '= 0.5.5' }
run_apt_control 'include'
end
it 'will print out what it wants to do if there are packages to include in dry run mode' do
build 'api', '0.5.0'
build 'api', '0.5.1-3'
include 'production', 'api', '0.5.0'
control production: { api: '~> 0.5' }
run_apt_control 'include --noop'
assert_last_stdout_include "production api 0.5.0 => 0.5.1-3"
end
it 'will include a new package if it is includeable' do
build 'api', '0.5.0'
build 'api', '0.5.1-3'
include 'production', 'api', '0.5.0'
control production: { api: '~> 0.5' }
run_apt_control 'include'
run_apt_control 'status -m'
assert_last_stdout_include "production api (~> 0.5) .S included=0.5.1-3"
end
end
|
# Copyright © 2011-2019 MUSC Foundation for Research Development
# All rights reserved.
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided with the distribution.
# 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
# BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
# SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
require 'rails_helper'
RSpec.describe ServiceRequestsController, type: :controller do
stub_controller
let!(:before_filters) { find_before_filters }
let!(:logged_in_user) { create(:identity) }
describe '#catalog' do
it 'should call before_filter #initialize_service_request' do
expect(before_filters.include?(:initialize_service_request)).to eq(true)
end
it 'should call before_filter #authorize_identity' do
expect(before_filters.include?(:authorize_identity)).to eq(true)
end
it 'should call before_filter #find_locked_org_ids' do
expect(before_filters.include?(:find_locked_org_ids)).to eq(true)
end
context 'editing service request' do
it 'should assign @institutions' do
i1 = create(:institution, order: 1)
i2 = create(:institution, order: 2)
protocol = create(:protocol_without_validations, primary_pi: logged_in_user)
sr = create(:service_request_without_validations, protocol: protocol)
session[:srid] = sr.id
get :catalog, xhr: true
expect(assigns(:institutions).count).to eq(2)
expect(assigns(:institutions)[0]).to eq(i1)
expect(assigns(:institutions)[1]).to eq(i2)
end
end
context 'use_google_calendar is true' do
stub_config('use_google_calendar', true)
it 'should assign @events' do
get :catalog, xhr: true
expect(assigns(:events)).to be
end
end
context 'use_news_feed is true' do
stub_config('use_news_feed', true)
it 'should assign @news' do
get :catalog, xhr: true
expect(assigns(:news)).to be
end
end
context 'params[:service_id] is present' do
it 'should assign @service' do
service = create(:service)
allow_any_instance_of(Service).to receive(:provider).and_return(nil)
allow_any_instance_of(Service).to receive(:program).and_return(nil)
allow_any_instance_of(Service).to receive(:core).and_return(nil)
get :catalog, params: { service_id: service.id }, xhr: true
expect(assigns(:service)).to eq(service)
end
context 'service is inactive' do
it 'should redirect' do
service = create(:service, is_available: false)
allow_any_instance_of(Service).to receive(:provider).and_return(nil)
allow_any_instance_of(Service).to receive(:program).and_return(nil)
allow_any_instance_of(Service).to receive(:core).and_return(nil)
get :catalog, params: { service_id: service.id }, xhr: true
expect(controller).to redirect_to(catalog_service_request_path)
end
end
end
it 'should render template' do
protocol = create(:protocol_without_validations, primary_pi: logged_in_user)
sr = create(:service_request_without_validations, protocol: protocol)
session[:srid] = sr.id
get :catalog, xhr: true
expect(controller).to render_template(:catalog)
end
it 'should respond ok' do
protocol = create(:protocol_without_validations, primary_pi: logged_in_user)
sr = create(:service_request_without_validations, protocol: protocol)
session[:srid] = sr.id
get :catalog, xhr: true
expect(controller).to respond_with(:ok)
end
end
end
|
class ImportFacilitiesJob < ApplicationJob
queue_as :default
self.queue_adapter = :sidekiq
def perform(facilities)
import_facilities = []
facilities.each do |facility|
organization = Organization.find_by(name: facility[:organization_name])
facility_group = FacilityGroup.find_by(name: facility[:facility_group_name],
organization_id: organization.id)
import_facility = Facility.new(facility.merge!(facility_group_id: facility_group.id))
import_facilities << import_facility
end
Facility.import!(import_facilities, validate: true)
end
end
|
module AASM
module SupportingClasses
class StateTransition
attr_reader :from, :to, :opts
def initialize(opts)
@from, @to, @guard, @on_transition = opts[:from], opts[:to], opts[:guard], opts[:on_transition]
@opts = opts
end
def perform(obj)
case @guard
when Symbol, String
obj.send(@guard)
when Proc
@guard.call(obj)
else
true
end
end
def execute(obj, *args)
case @on_transition
when Symbol, String
obj.send(@on_transition, *args)
when Proc
@on_transition.call(obj, *args)
end
end
def ==(obj)
@from == obj.from && @to == obj.to
end
end
end
end
|
When /^I visit the forum page with no tag$/ do
step "I go to the forum page"
end
When /^I visit the forum page with tag "([^\"]*)"$/ do |tag|
visit "/#{tag}/forum"
end
Then /^I should see the tags of the topic$/ do
response.body.should have_text /#{@topic.tags.map(&:name).join('\s+')}/
end
#TODO: check if this step is still valid
Then /^I should see the tags$/ do
topic = Topic.last
topic.tags.should_not be_empty
step %{I should see "#{topic.tags.map(&:names).join(' ')}"}
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.