text stringlengths 10 2.61M |
|---|
# User model class
class User < ApplicationRecord
has_secure_password
def subscriber?
role == 'subscriber'
end
def admin?
role == 'admin'
end
end
|
class ScoreCalc
VALUE_LOSE = -5_000_000
LIMIT_EXP = 100
LIMIT_STATUS = 28
def self.load_pack(param_values_pack)
@@values = param_values_pack
end
def self.summary_value(company)
value = company_value(company) + heros_value(company)
value
end
def self.company_value(company)
value = 0
value = VALUE_LOSE if company.honor < company.antipathy
value += company.honor * @@values["honor"]
value += company.research * @@values["research"]
value -= company.antipathy * @@values["antipathy"]
value -= company.outlay * @@values["outlay"]
value -= 100_0 unless company.b_reducting_final_mission
num_buildings = 0
company.list_buildings.each_with_index do |building, num_room|
if building.nil?
break
else
list_need_nexted = %w(medic armo training_room convesation_class library tech_labo shelter)
list_obsoleting = %w(medic armo training_room convesation_class library)
unless list_need_nexted.include?(building.name) && num_room != 1 && num_room != 3
unless list_obsoleting.include?(building.name) && company.heros.first.level != 4
value += @@values[building.name]
end
end
end
end
value
end
def self.heros_value(company)
value = 0
company.heros.each do |hero|
value += hero_value(hero)
end
value
end
def self.hero_value(hero)
value = 0
value += hero_params_value(hero)
value += hero.num_actions * 100
value += hero.stamina * 100
(hero.list_weapons || []).each do |weapon|
value += weapon.int_effect * @@values["weapon"]
end
value
end
def self.hero_params_value(hero)
value = 0
proc_add_status_value = proc do |status, value_status, limit|
if status < limit
value += status * value_status
else
value += status * limit
end
end
proc_add_status_value.call(hero.exp, @@values["exp"], LIMIT_EXP)
proc_add_status_value.call(hero.physical, @@values["physical"], LIMIT_STATUS)
proc_add_status_value.call(hero.agility, @@values["agility"], LIMIT_STATUS)
proc_add_status_value.call(hero.sociability, @@values["sociability"], LIMIT_STATUS)
proc_add_status_value.call(hero.skill, @@values["skill"], LIMIT_STATUS)
value
end
def self.score(name)
@@values[name]
return @@values[name]
end
end
|
include_recipe "chimpstation_base::workspace_directory"
node.git_projects.each do |repo_name, repo_address|
execute "clone #{repo_name}" do
command "git clone #{repo_address} #{repo_name}"
user WS_USER
cwd "#{WS_HOME}/#{node['workspace_directory']}/"
not_if { ::File.exists?("#{WS_HOME}/#{node['workspace_directory']}/#{repo_name}") }
end
execute "track origin master" do
command "git branch --set-upstream master origin/master"
cwd "#{WS_HOME}/#{node['workspace_directory']}/#{repo_name}"
user WS_USER
end
execute "git submodule init for #{repo_name}" do
command "git submodule init"
cwd "#{WS_HOME}/#{node['workspace_directory']}/#{repo_name}"
user WS_USER
end
execute "git submodule update for #{repo_name}" do
command "git submodule update"
cwd "#{WS_HOME}/#{node['workspace_directory']}/#{repo_name}"
user WS_USER
end
end
|
# frozen_string_literal: true
require "spec_helper"
describe LiteCable::Config do
let(:config) { LiteCable.config }
it "sets defailts", :aggregate_failures do
expect(config.coder).to eq LiteCable::Coders::JSON
expect(config.identifier_coder).to eq LiteCable::Coders::Raw
end
end
|
require 'aws/broker/publishing'
module Aws
class Broker
class Railtie < Rails::Railtie
initializer 'aws-broker.extend_active_record' do
ActiveSupport.on_load(:active_record) do
ActiveRecord::Base.send(:extend, Aws::Broker::Publishing)
end
end
end
end
end
|
# frozen_string_literal: true
require 'sidekiq'
module AppealsApi
class NoticeOfDisagreementUploadStatusUpdater
include Sidekiq::Worker
sidekiq_options 'retry': true, unique_until: :success
def perform(ids)
NoticeOfDisagreement.where(id: ids).find_in_batches(batch_size: 100) do |batch|
NoticeOfDisagreement.refresh_statuses_using_central_mail! batch
end
end
end
end
|
class NetworkManager
INPUT_NO = 2 #入力層のセル数
HIDDEN_NO = 2 #中間層のセル数
def initialize()
@wh = [] #中間層の重み
@vh =[] #中間層のしきい値
@wo = [] #出力槽の重み
@vo =0.0 #出力層のしきい値
end
attr_accessor :wh, :wo, :vh, :vo
def init()
init_wh()
init_wo()
init_vh()
init_vo()
end
def init_wh()
array = Array.new(HIDDEN_NO){|i| Array.new(HIDDEN_NO,0)}
HIDDEN_NO.times{|i|
(INPUT_NO + 1).times{|j|
array[i][j] = Random.rand
}
}
@wh = array
end
def init_wo()
array = Array.new(HIDDEN_NO,0)
HIDDEN_NO.times{|i|
array[i] = Random.rand
}
@wo = array
end
def init_vh()
array = []
(HIDDEN_NO).times{|i|
array[i] = Random.rand
}
@vh = array
end
def init_vo()
@vo = Random.rand
end
def print()
puts "wh-------"
@wh.each{|whi|
whi.each{|whij|
puts "#{whij}"
}
}
puts "wo-------"
@wo.each{|woi|
puts "#{woi}"
}
end
end |
require "spec_helper"
RSpec.describe Game do
it "should have a players hand" do
Game.new.player_hand.cards.length.should eq(2)
end
it "should have a dealers hand" do
Game.new.dealer_hand.cards.length.should eq(2)
end
it "should have a status" do
Game.new.status.should_not be_nil
end
it "should hit when I tell it to" do
game = Game.new
game.hit
game.player_hand.cards.length.should eq(3)
end
it "should play the dealer hand when I stand" do
game = Game.new
game.stand
game.status[:winner].should_not be_nil
end
describe "#determine_winner" do
it "should have dealer win when player busts" do
game = Game.new.determine_winner(22, 15)
expect(game).to eq(:dealer)
end
it "should player win if dealer busts" do
Game.new.determine_winner(18, 22).should eq(:player)
end
it "should have player win if player > dealer" do
Game.new.determine_winner(18, 16).should eq(:player)
end
it "should have push if tie" do
Game.new.determine_winner(16, 16).should eq(:push)
end
end
end
|
class AppointmentMailer < ApplicationMailer
default from: 'hospital@kachirocks.com'
before_action :retrieve_admins, only: %i[
new_appointment confirm_appointment change_of_doctor
]
def new_appointment
@appointment = params[:appointment]
@patient = @appointment.patient.name
@specialization = @appointment.specialization.name
mail(to: @doctors, subject: 'A patient just made a new appointment')
end
def confirm_appointment
@appointment = params[:appointment]
@patient = @appointment.patient
@doctor = @appointment.doctor
mail(to: [@patient.email, @doctor.email],
subject: 'Your appointment has just been confirmed')
end
def decline_appointment
@appointment = params[:appointment]
@patient = @appointment.patient.name
@doctor = @appointment.doctor.name
mail(to: @patient, subject: 'Your appointment has been declined')
end
def change_of_doctor
@patient = params[:patient]
mail(to: @patient.email, bcc: @doctors, subject: 'Change of doctor')
end
def retrieve_admins
@doctors = Doctor.where(admin: true).pluck(:email)
end
end
|
# Single Element In a Sorted Array
#
# Given a sorted array consisting of only integers where every element
# appears twice except for one element which appears once. Find this
# single element that appears only once. Do it in O(log n) time and O(1)
# space!
#
# things you should be thinking of:
# - O(log n) should immediately make you think of Binary Search.
# - What condition are we checking for?
# - How do we know which direction to go next?
# example: [ 1, 1, 2, 2, 3, 3, 4, 5, 5, 6, 6, 7, 7 ]
#
# solution:
def single_in_sorted(arr)
lo = 0
hi = (arr.length - 1)
while lo < hi
mid = ((hi - lo) / 2 )+ lo
return arr[mid] if arr[mid] != arr[mid-1] && arr[mid] != arr[mid + 1 ]
if (arr[mid] == arr[mid-1] && mid.odd?) || (arr[mid] == arr[mid+1] && mid.even?)
low = mid + 1
else
hi = mid -1
end
end
arr[lo]
end
#Time complexity = O(log n)
p single_in_sorted([1,1,2,2,3,3,4,5,5,6,6,7,7])
|
# Write a program that:
#
# Asks your user to enter any word and have it spelled out letter by letter.
p "Enter a word for me to spell:"
word = gets.chomp
word = word.split("")
word.each do |the_character|
p the_character.upcase
end
|
class User < ApplicationRecord
has_many :bookings
has_many :rooms, through: :bookings
scope :booking_info, -> (id) { where(id: id).pluck("bookings.checkin_date","bookings.no_of_guests","rooms.room_type","rooms.no") }
end
|
require 'rails_helper'
RSpec.describe CustomersController, type: :controller do
# Get customer list
shared_examples_for "get customer list" do |record_count, params, expected_size|
it "return customer list" do
create_list(:customer, record_count)
get :index, params: params
expect(response.status).to eq(200)
expect(json_data.size).to eq(expected_size)
end
end
describe "GET /v1/customers" do
it_should_behave_like "get customer list", 0, {}, 0
it_should_behave_like "get customer list", 1, {}, 1
it_should_behave_like "get customer list", 10, {}, 10
it_should_behave_like "get customer list", 100, {}, 30
it_should_behave_like "get customer list", 100, {page: 1}, 30
it_should_behave_like "get customer list", 100, {page: 4}, 10
end
# Get customer details
describe "GET /v1/customers/:id" do
context "success" do
let(:customer) { create(:customer) }
it "return customer details" do
get :show, params: {id: customer.id}
expect(response).to have_http_status(200)
expect(json_data).to include("id" => customer.id)
end
end
context "fail" do
it "return 404 not found" do
get :show, params: {id: 999}
expect(response).to have_http_status(404)
end
end
end
# Create customer
describe "POST /v1/customers" do
context "success" do
let(:params_name) { {name: "World"} }
let(:params_pref) do
{
preferences: {
"dog": {
breed: ["poodle"],
}
}
}
end
let(:params_age) do
{
preference_age_min: 1,
preference_age_max: 3,
}
end
let(:params) { params_name.merge(params_pref).merge(params_age) }
it "creates a new Customer" do
expect {
post :create, params: params
}.to change(Customer, :count).by(1)
end
it "renders a JSON response with the new customer" do
post :create, params: params
expect(response).to have_http_status(:created)
expect(response.content_type).to eq('application/json')
["id", "name", "preferences", "preference_age_min", "preference_age_max"].each do |field|
expect(json_data).to have_key(field)
end
expect(json_data["preferences"]).to have_key("dog")
end
it "create customer with no preferences" do
post :create, params: params_name
expect(response).to have_http_status(:created)
expect(response.content_type).to eq('application/json')
["id", "name", "preferences"].each do |field|
expect(json_data).to have_key(field)
end
expect(json_data["preferences"]).to be_nil
end
end
context "fail" do
it "renders a JSON response with errors for the new customer" do
post :create
expect(response).to have_http_status(:unprocessable_entity)
expect(response.content_type).to eq('application/json')
end
end
end
# match pets
describe "GET /v1/customers/:id/matches" do
it "returns no pets" do
customer = create(:customer)
get :matching, params: {id: customer.id}
expect(response).to have_http_status(200)
expect(json_data.size).to eq(0)
end
it "returns a pet" do
pet = create(:pet)
customer = create(:customer)
get :matching, params: {id: customer.id}
expect(response).to have_http_status(200)
expect(json_data.size).to eq(1)
end
it "returns all matching pets" do
pet = create_list(:pet, 5)
customer = create(:customer)
get :matching, params: {id: customer.id}
expect(response).to have_http_status(200)
expect(json_data.size).to eq(5)
end
end
# Adopt pet
describe "POST /v1/customers/:id/adoptions" do
context "success" do
let(:pet) { create(:pet) }
let(:customer) { create(:customer) }
it "response status code 201" do
expect {
post :adopt, params: {id: customer.id, pet_id: pet.id}
}.to change(Adoption, :count).by(1)
expect(response).to have_http_status(201)
expect(pet.reload.adopted_by).to eq(customer.id)
end
end
context "fail" do
let(:adopted_pet) { create(:adopted_pet) }
let(:unavailable_pet) { create(:unavailable_pet) }
let(:customer) { create(:customer) }
it "response 400 for adopted pet" do
post :adopt, params: {id: customer.id, pet_id: adopted_pet.id}
expect(response).to have_http_status(400)
end
it "response 400 for unavailable pet" do
post :adopt, params: {id: customer.id, pet_id: unavailable_pet.id}
expect(response).to have_http_status(400)
end
end
end
end
|
require 'boolean_amenity_constraint'
class BooleanAmenitiesController < ApplicationController
include PropertiesHelper
include SessionsHelper
before_action :signed_in_user
def new
@amenity = BooleanAmenity.new
end
def create
params = amenity_params
@same_amenity = BooleanAmenity.find_by(params)
@amenity = BooleanAmenity.new(amenity_params)
if @same_amenity
@amenity = @same_amenity
update_amenity_and_redirect_to_property_location
else
if @amenity.save
update_amenity_and_redirect_to_property_location
else
render new_boolean_amenity_path
end
end
end
private
def amenity_params
params.require(:boolean_amenities).permit(:dining_table, :fridge,
:sofa, :gas_pipe, :stove, :gym, :swimming_pool,
:lift, :washing_machine, :microwave, :servent_room)
end
def update_amenity_and_redirect_to_property_location
current_property.update(PropertyConstraint.row_boolean_amenity_id => @amenity.id)
redirect_to new_integer_amenity_path
end
end
|
class Api::ThresholdsController < ApplicationController
before_action :set_threshold, only: [:show, :update, :destroy]
# GET /thresholds
def index
@thresholds = Threshold.all
render json: @thresholds
end
# GET /thresholds/1
def show
render json: @threshold
end
# POST /thresholds
def create
@threshold = Threshold.new(threshold_params)
if @threshold.save
render json: @threshold, status: :created
else
render json: @threshold.errors, status: :unprocessable_entity
end
end
# PATCH/PUT /thresholds/1
def update
if @threshold.update(threshold_params)
render json: @threshold
else
render json: @threshold.errors, status: :unprocessable_entity
end
end
# DELETE /thresholds/1
def destroy
@threshold.destroy
end
private
# Use callbacks to share common setup or constraints between actions.
def set_threshold
@threshold = Threshold.find(params[:id])
end
# Only allow a list of trusted parameters through.
def threshold_params
params.require(:threshold).permit(:name, :min, :max)
end
end
|
# encoding: utf-8
#
# © Copyright 2013 Hewlett-Packard Development Company, L.P.
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
require 'hpcloud/connection.rb'
require 'mime/types'
require 'ruby-progressbar'
module HP
module Cloud
class Resource
attr_accessor :path
attr_reader :fname, :ftype, :container
attr_reader :public_url, :readers, :writers, :public
attr_reader :destination, :cstatus
attr_reader :restart
@@limit = nil
def initialize(storage, fname)
@cstatus = CliStatus.new
@storage = storage
@fname = fname
@ftype = ResourceFactory.detect_type(@fname)
@disable_pbar = false
@mime_type = nil
@restart = false
@readacl = []
@writeacl = []
parse()
end
def is_valid?
return @cstatus.is_success?
end
def set_error(from)
return unless is_valid?
@cstatus.set(from.cstatus)
end
def not_implemented(value)
@cstatus = CliStatus.new("Not implemented: #{value}")
return false
end
def isLocal()
return ResourceFactory::is_local?(@ftype)
end
def isRemote()
return ResourceFactory::is_remote?(@ftype)
end
def is_object_store?
return @ftype == :object_store
end
def is_container?
return @ftype == :container
end
def is_shared?
return @ftype == :shared_resource || @ftype == :shared_directory
end
def isDirectory()
return @ftype == :directory ||
@ftype == :container_directory ||
@ftype == :shared_directory ||
@ftype == :container ||
@ftype == :object_store
end
def isFile()
return @ftype == :file
end
def isObject()
return @ftype == :object || @ftype == :shared_resource
end
def parse
@container = nil
@path = nil
if @fname.empty?
return
end
if @fname[0,1] == ':'
@container, *rest = @fname.split('/')
@container = @container[1..-1] if @container[0,1] == ':'
@path = rest.empty? ? '' : rest.join('/')
unless @container.length < 257
raise Exception.new("Valid container names must be less than 256 characters long")
end
else
rest = @fname.split('/')
@path = rest.empty? ? '' : rest.join('/')
end
end
def to_hash
hash = {}
instance_variables.each {|var| hash[var.to_s.delete("@")] = instance_variable_get(var) }
hash
end
def set_mime_type(value)
@mime_type = value.tr("'", "") unless value.nil?
end
def get_mime_type()
return @mime_type unless @mime_type.nil?
filename = ::File.basename(@fname)
unless (mime_types = ::MIME::Types.of(filename)).empty?
return mime_types.first.content_type
end
return 'application/octet-stream'
end
def valid_source()
return true
end
def isMulti()
return true if isDirectory()
found = false
foreach { |x|
if (found == true)
return true
end
found = true
}
return false
end
def valid_destination(source)
return true
end
def set_destination(from)
return true
end
def head()
@cstatus = CliStatus.new("Not supported on local object '#{@fname}'.", :not_supported)
return false
end
def container_head()
@cstatus = CliStatus.new("Not supported on local object '#{@fname}'.", :not_supported)
return false
end
def open(output=false, siz=0)
return not_implemented("open")
end
def read()
not_implemented("read")
return nil
end
def write(data)
return not_implemented("write")
end
def close()
return not_implemented("close")
end
def copy_file(from)
return not_implemented("copy_file")
end
def copy(from)
if copy_all(from)
return true
end
set_error(from)
return false
end
def copy_all(from)
if ! from.valid_source()
@cstatus = from.cstatus
return false
end
if ! valid_destination(from) then return false end
copiedfile = false
original = File.dirname(from.path)
from.foreach { |file|
if (original != '.')
filename = file.path.sub(original, '').sub(/^\//, '')
else
filename = file.path
end
return false unless set_destination(filename)
unless copy_file(file)
from.set_error(file)
return false
end
copiedfile = true
}
if (copiedfile == false)
@cstatus = CliStatus.new("No files found matching source '#{from.path}'", :not_found)
return false
end
return true
end
def foreach(&block)
return
end
def get_destination()
return @destination.to_s
end
def remove(force, at=nil, after=nil)
@cstatus = CliStatus.new("Removal of local objects is not supported: #{@fname}", :incorrect_usage)
return false
end
def tempurl(period = 172800)
@cstatus = CliStatus.new("Temporary URLs of local objects is not supported: #{@fname}", :incorrect_usage)
return nil
end
def grant(acl)
@cstatus = CliStatus.new("ACLs of local objects are not supported: #{@fname}", :incorrect_usage)
return false
end
def revoke(acl)
@cstatus = CliStatus.new("ACLs of local objects are not supported: #{@fname}", :incorrect_usage)
return false
end
def set_restart(value)
@restart = value
end
end
end
end
|
class BrandsController < ApplicationController
skip_before_action :authenticate_user!, only: :scores
def index
if params[:query].present?
@brands = Brand.search_by_name(params[:query]).order('name ASC')
elsif params[:category]
if params[:category] == 'All'
@brands = Brand.all.order('name ASC')
else
@brands = Brand.joins(:categories).where(categories: { name: params[:category] }).order('name ASC')
end
else
@brands = Brand.all.order('name ASC')
end
@brands.each do |brand|
if brand.quality_score.nil?
brand.overall_score = (brand.environmental_score.to_f + brand.social_score.to_f) / 2
else
brand.overall_score = (brand.environmental_score.to_f + brand.social_score.to_f + brand.quality_score.to_f) / 3
end
end
@request = Request.new
@categories = Category.all
respond_to do |format|
format.html {}
format.json {
render json: @brands.map { |brand| brand.to_hash }
}
end
end
def show
@brand = Brand.find(params[:id])
@toggle = current_user.favorites.select { |favorite| favorite.brand_id == @brand.id }
@review = Review.new
sum = 0
@brand.reviews.each { |review| sum += review.score }
@consumer_score = sum / @brand.reviews.size.to_f
if @brand.quality_score.nil?
@brand.overall_score = (@brand.environmental_score.to_f + @brand.social_score.to_f) / 2
else
@brand.overall_score = (@brand.environmental_score.to_f + @brand.social_score.to_f + @brand.quality_score.to_f) / 3
end
sorted = Brand.where('id != ?', @brand.id).where("overall_score >= 3")
@random = sorted.sample(6)
NewsController.create(@brand)
end
def scores
array_params = params[:url].split(",").map {|word| word.capitalize}
@brand = Brand.find_by('name IN (?)', array_params)
respond_to do |format|
format.html {}
format.json {
render json: @brand
}
end
end
end
|
DIRECTIONS = { 'E' => 0, 'S' => 1, 'W' => 2, 'N' => 3 }.freeze
waypoint = Hash.new(0)
waypoint['E'] = 10
waypoint['N'] = 1
route = Hash.new(0)
def process(entry, route, directions, waypoint)
case entry[:cmd]
when 'F'
move_forward(entry[:val], route, waypoint)
when 'R'
rotate_waypoint(entry[:val], waypoint, directions)
when 'L'
rotate_waypoint(-1 * entry[:val], waypoint, directions)
when *directions.keys
waypoint[entry[:cmd]] += entry[:val]
end
end
def move_forward(val, route, waypoint)
waypoint.keys.each { |d| route[d] += waypoint[d].to_i * val }
end
def rotate_waypoint(deg, waypoint, directions)
rotated = Hash.new(0)
waypoint.keys.each do |d|
rotated[directions.keys[(directions[d] + (deg / 90)) % 4]] = waypoint[d]
end
waypoint.clear
rotated.keys.each { |k| waypoint[k] = rotated[k] }
end
input = File.read('input.txt')
.split(/\n/)
.map { |x| { cmd: x[0], val: x[1..-1].to_i } }
input.each { |cmd| process(cmd, route, DIRECTIONS, waypoint) }
puts route['S'] - route['N'] + route['E'] - route['W']
|
# encoding: utf-8
$: << 'RspecTests'
$: << 'RspecTests/Generated/array'
require 'rspec'
require 'generated/body_array'
require 'helper'
module ArrayModule
include ArrayModule::Models
describe ArrayModule::Array do
before(:all) do
@base_url = ENV['StubServerURI']
dummyToken = 'dummy12321343423'
@credentials = MsRest::TokenCredentials.new(dummyToken)
client = AutoRestSwaggerBATArrayService.new(@credentials, @base_url)
@array_client = Array.new(client)
@arr_bool = [true, false, false, true]
@arr_string = ["foo1", "foo2", "foo3"]
@arr_int = [1, -1, 3, 300]
@arr_float = [0, -0.01, -1.2e20]
@arr_date = [Date.new(2000, 12, 01, 0), Date.new(1980, 1, 2, 0),Date.new(1492, 10, 12, 0)]
@arr_date_nil = [Date.new(2012, 1, 1, 0), nil, Date.new(1776, 7, 4, 0)]
@arr_dateTime = [DateTime.new(2000, 12, 01, 0, 0, 1), DateTime.new(1980, 1, 2, 0, 11, 35),DateTime.new(1492, 10, 12, 10, 15, 1)]
@arr_dateTime_rfc1123 = [DateTime.new(2000, 12, 01, 0, 0, 1, 'Z'), DateTime.new(1980, 1, 2, 0, 11, 35, 'Z'), DateTime.new(1492, 10, 12, 10, 15, 1, 'Z')]
@arr_dateTime_nil = [DateTime.new(2000, 12, 01, 0, 0, 1), nil]
@product1 = Product.new
@product2 = Product.new
@product3 = Product.new
@product1.string = "2"
@product1.integer = 1
@product2.string = "4"
@product2.integer = 3
@product3.string = "6"
@product3.integer = 5
@arr_complex = [@product1, @product2, @product3]
@arr_complex_empty = [@product1, Product.new, @product3]
@arr_complex_nil = [@product1, nil, @product3]
@arr_byte = [[0x0FF, 0x0FF, 0x0FF, 0x0FA],[0x01, 0x02, 0x03],[0x025, 0x029, 0x043]]
@arr_byte_nil = [[0x0AB, 0x0AC, 0x0AD], nil]
@arr_array= [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
@arr_dict = [{'1'=> 'one', '2' => 'two', '3' => 'three'}, {'4'=> 'four', '5' => 'five', '6' => 'six'}, {'7'=> 'seven', '8' => 'eight', '9' => 'nine'}]
end
it 'should create test service' do
# expect(1).to eq(2)
expect { AutoRestSwaggerBATArrayService.new(@credentials, @base_url) }.not_to raise_error
end
it 'should get null' do
result = @array_client.get_null_async().value!
expect(result.response.status).to eq(200)
expect(result.body).to be_nil
end
it 'should get empty' do
result = @array_client.get_empty_async().value!
expect(result.response.status).to eq(200)
expect(result.body).to eq([])
end
it 'should put empty' do
result = @array_client.put_empty_async([]).value!
expect(result.response.status).to eq(200)
end
# Boolean tests
it 'should get boolean tfft' do
result = @array_client.get_boolean_tfft_async().value!
expect(result.response.status).to eq(200)
expect(result.body).to eq(@arr_bool)
end
it 'should put boolean tfft' do
result = @array_client.put_boolean_tfft_async(@arr_bool).value!
expect(result.response.status).to eq(200)
end
it 'should get boolean invalid null' do
result = @array_client.get_boolean_invalid_null_async().value!
expect(result.response.status).to eq(200)
expect(result.body).to eq([true, nil, false])
end
it 'should get boolean invalid string' do
result = @array_client.get_boolean_invalid_string_async().value!
expect(result.response.status).to eq(200)
expect(result.body).to eq([true, "boolean", false])
end
# Integer tests
it 'should get integer valid' do
result = @array_client.get_integer_valid_async().value!
expect(result.response.status).to eq(200)
expect(result.body).to eq(@arr_int)
end
it 'should put integer valid' do
result = @array_client.put_integer_valid_async(@arr_int).value!
expect(result.response.status).to eq(200)
end
it 'should get int invalid null' do
result = @array_client.get_int_invalid_null_async().value!
expect(result.response.status).to eq(200)
expect(result.body).to eq([1, nil, 0])
end
it 'should get int invalid string' do
expect { result = @array_client.get_int_invalid_string_async().value! }.to raise_error(MsRest::DeserializationError)
end
# Long integer tests. Ruby automtically converts int to long int, so there is no
# special data type.
it 'should get long valid' do
result = @array_client.get_long_valid_async().value!
expect(result.response.status).to eq(200)
expect(result.body).to eq(@arr_int)
end
it 'should put long valid' do
result = @array_client.put_long_valid_async(@arr_int).value!
expect(result.response.status).to eq(200)
end
it 'should get long invalid null' do
result = @array_client.get_long_invalid_null_async().value!
expect(result.response.status).to eq(200)
expect(result.body).to eq([ 1, nil, 0 ])
end
it 'should get long invalid string' do
expect { result = @array_client.get_long_invalid_string_async().value! }.to raise_error(MsRest::DeserializationError)
end
# Float tests
it 'should get float valid' do
result = @array_client.get_float_valid_async().value!
expect(result.response.status).to eq(200)
expect(result.body).to eq(@arr_float)
end
it 'should put float valid' do
result = @array_client.put_float_valid_async(@arr_float).value!
expect(result.response.status).to eq(200)
end
it 'should get float invalid null' do
result = @array_client.get_float_invalid_null_async().value!
expect(result.response.status).to eq(200)
expect(result.body).to eq([ 0.0, nil, -1.2e20 ])
end
it 'should get float invalid string' do
expect { result = @array_client.get_float_invalid_string_async().value! }.to raise_error(MsRest::DeserializationError)
end
# Double tests
it 'should get double valid' do
result = @array_client.get_double_valid_async().value!
expect(result.response.status).to eq(200)
expect(result.body).to eq(@arr_float)
end
it 'should put double valid' do
result = @array_client.put_double_valid_async(@arr_float).value!
expect(result.response.status).to eq(200)
end
it 'should get double invalid null' do
result = @array_client.get_double_invalid_null_async().value!
expect(result.response.status).to eq(200)
expect(result.body).to eq([ 0.0, nil, -1.2e20 ])
end
it 'should get double invalid string' do
expect { result = @array_client.get_double_invalid_string_async().value! }.to raise_error(MsRest::DeserializationError)
end
# String tests
it 'should get string valid' do
result = @array_client.get_string_valid_async().value!
expect(result.response.status).to eq(200)
expect(result.body).to eq(@arr_string)
end
it 'should put string valid' do
result = @array_client.put_string_valid_async(@arr_string).value!
expect(result.response.status).to eq(200)
end
it 'should get string invalid null' do
result = @array_client.get_string_with_null_async().value!
expect(result.response.status).to eq(200)
expect(result.body).to eq([ "foo", nil, "foo2"])
end
it 'should get string invalid' do
result = @array_client.get_string_with_invalid_async().value!
expect(result.response.status).to eq(200)
expect(result.body).to eq(["foo", 123, "foo2"])
end
# Date tests
it 'should get date valid' do
result = @array_client.get_date_valid_async().value!
expect(result.response.status).to eq(200)
expect(result.body).to eq(@arr_date)
end
it 'should put date valid' do
result = @array_client.put_date_valid_async(@arr_date).value!
expect(result.response.status).to eq(200)
end
it 'should get date invalid null' do
result = @array_client.get_date_invalid_null_async().value!
expect(result.response.status).to eq(200)
expect(result.body).to eq(@arr_date_nil)
end
it 'should get date invalid chars' do
expect { @array_client.get_date_invalid_chars_async().value! }.to raise_exception(MsRest::DeserializationError)
end
# DateTime tests
it 'should get dateTime valid' do
result = @array_client.get_date_time_valid_async().value!
expect(result.response.status).to eq(200)
expect(result.body).to eq(@arr_dateTime)
end
it 'should put dateTime valid' do
result = @array_client.put_date_time_valid_async(@arr_dateTime).value!
expect(result.response.status).to eq(200)
end
it 'should get dateTime invalid null' do
result = @array_client.get_date_time_invalid_null_async().value!
expect(result.response.status).to eq(200)
expect(result.body).to eq(@arr_dateTime_nil)
end
it 'should get dateTime invalid string' do
expect { @array_client.get_date_time_invalid_chars_async().value! }.to raise_exception(MsRest::DeserializationError)
end
# DateTimeRfc1123 tests
it 'should get dateTimeRfc1123 valid' do
result = @array_client.get_date_time_rfc1123valid_async().value!
expect(result.response.status).to eq(200)
expect(result.body).to eq(@arr_dateTime_rfc1123)
end
it 'should put dateTimeRfc1123 valid' do
pending("Ruby DateTime -> RFC1123 serialization thinks DateTime.new(1492, 10, 12, 10, 15, 1, 'Z') is a Friday, but NodeJS/C# think it's a Wed")
result = @array_client.put_date_time_rfc1123valid_async(@arr_dateTime_rfc1123).value!
expect(result.response.status).to eq(200)
end
# Byte tests
it 'should get byte valid' do
result = @array_client.get_byte_valid_async().value!
expect(result.response.status).to eq(200)
expect(result.body).to eq(@arr_byte)
end
it 'should put byte valid' do
result = @array_client.put_byte_valid_async(@arr_byte).value!
expect(result.response.status).to eq(200)
end
it 'should get byte invalid null' do
result = @array_client.get_byte_invalid_null_async().value!
expect(result.response.status).to eq(200)
expect(result.body).to eq(@arr_byte_nil)
end
#Complex tests
it 'should get complex null' do
result = @array_client.get_complex_null_async().value!
expect(result.response.status).to eq(200)
expect(result.body).to be_nil
end
it 'should get empty null' do
result = @array_client.get_complex_null_async().value!
expect(result.response.status).to eq(200)
expect(result.body).to be_nil
end
it 'should get сomplex item null' do
result = @array_client.get_complex_item_null_async().value!
expect(result.response.status).to eq(200)
expect(result.body.count).to eq(@arr_complex_nil.count)
@arr_complex_nil.each_with_index do |item, index|
expect(result.body[index]).to be_equal_objects(item)
end
end
it 'should get complex array empty' do
result = @array_client.get_complex_empty_async().value!
expect(result.response.status).to eq(200)
expect(result.body.count).to eq(0)
end
it 'should get complex item empty' do
result = @array_client.get_complex_item_empty_async().value!
expect(result.response.status).to eq(200)
expect(result.body.count).to eq(@arr_complex_empty.count)
@arr_complex_empty.each_with_index do |item, index|
expect(result.body[index]).to be_equal_objects(item)
end
end
it 'should get complex valid' do
result = @array_client.get_complex_valid_async().value!
expect(result.response.status).to eq(200)
expect(result.body.count).to eq(@arr_complex.count)
@arr_complex.each_with_index do |item, index|
expect(result.body[index]).to be_equal_objects(item)
end
end
it 'should put complex valid' do
result = @array_client.put_complex_valid_async(@arr_complex).value!
expect(result.response.status).to eq(200)
end
# Array tests
it 'should get array null' do
result = @array_client.get_array_null_async().value!
expect(result.response.status).to eq(200)
expect(result.body).to be_nil
end
it 'should handle invalid value for arrays' do
expect { @array_client.get_invalid_async().value! }.to raise_error(MsRest::DeserializationError)
end
it 'should get array empty' do
result = @array_client.get_array_empty_async().value!
expect(result.response.status).to eq(200)
expect(result.body).to eq([])
end
it 'should get array item null' do
result = @array_client.get_array_item_null_async().value!
expect(result.response.status).to eq(200)
expect(result.body).to eq([["1", "2", "3"], nil, ["7", "8", "9"]])
end
it 'should get array item empty' do
result = @array_client.get_array_item_empty_async().value!
expect(result.response.status).to eq(200)
expect(result.body).to eq([["1", "2", "3"], [], ["7", "8", "9"]])
end
it 'should get array valid' do
result = @array_client.get_array_valid_async().value!
expect(result.response.status).to eq(200)
expect(result.body).to eq(@arr_array)
end
it 'should put array valid' do
result = @array_client.put_array_valid_async(@arr_array).value!
expect(result.response.status).to eq(200)
end
# Dictionary tests
it 'should get dictionary null' do
result = @array_client.get_dictionary_null_async().value!
expect(result.response.status).to eq(200)
expect(result.body).to be_nil
end
it 'should get dictionary empty' do
result = @array_client.get_dictionary_empty_async().value!
expect(result.response.status).to eq(200)
expect(result.body).to eq([])
end
it 'should get dictionary item null' do
result = @array_client.get_dictionary_item_null_async().value!
expect(result.response.status).to eq(200)
expect(result.body).to eq([{'1'=> 'one', '2' => 'two', '3' => 'three'}, nil, {'7'=> 'seven', '8' => 'eight', '9' => 'nine'}])
end
it 'should get dictionary item empty' do
result = @array_client.get_dictionary_item_empty_async().value!
expect(result.response.status).to eq(200)
expect(result.body).to eq([{'1'=> 'one', '2' => 'two', '3' => 'three'}, {}, {'7'=> 'seven', '8' => 'eight', '9' => 'nine'}])
end
it 'should get dictionary valid' do
result = @array_client.get_dictionary_valid_async().value!
expect(result.response.status).to eq(200)
expect(result.body).to eq(@arr_dict)
end
it 'should put dictionary valid' do
result = @array_client.put_dictionary_valid_async(@arr_dict).value!
expect(result.response.status).to eq(200)
end
it 'should get uuid arrays' do
result = @array_client.get_uuid_valid_async().value!
expect(result.response.status).to eq(200)
expect(result.body.count).to eq(3)
expect(result.body[0]).to eq('6dcc7237-45fe-45c4-8a6b-3a8a3f625652')
expect(result.body[1]).to eq('d1399005-30f7-40d6-8da6-dd7c89ad34db')
expect(result.body[2]).to eq('f42f6aa1-a5bc-4ddf-907e-5f915de43205')
end
it 'should put uuid arrays' do
array_body = ['6dcc7237-45fe-45c4-8a6b-3a8a3f625652', 'd1399005-30f7-40d6-8da6-dd7c89ad34db', 'f42f6aa1-a5bc-4ddf-907e-5f915de43205']
result = @array_client.put_uuid_valid_async(array_body).value!
expect(result.response.status).to eq(200)
end
end
end
|
class ReservationsController < ApplicationController
def index
@reservations = Reservation.all
end
def show
@reservation = Reservation.find(params[:id])
end
def new
@reservation = Reservation.new
end
def update
@reservation = Reservation.find(params[:id])
if @reservation.update(cleaned_res_params) #if we successfully save, show us the res on a show.html.erb view
redirect_to @reservation
else
render 'edit'
end
end
def edit
@reservation = Reservation.find(params[:id])
end
def create
@reservation = Reservation.new(cleaned_res_params)
if @reservation.save
redirect_to @reservation #could also render 'index' to go back to calendar view
else
render 'new'
end
end
def destroy
@reservation = Reservation.find(params[:id])
@reservation.destroy
redirect_to reservations_path #same as render 'index'
end
private
def cleaned_res_params
params.require(:reservation).permit(:name,:phone,:start,:duration,:court,:rackets,:goggles,:ball,:guest1,:guest2,:guest3)
#as convert what needs to be an integer to an integer
end
end
|
class Quote < ApplicationRecord
belongs_to :mood
has_many :user_moods
end
|
class AddMetaToCategories < ActiveRecord::Migration[5.0]
def change
add_column :categories, :description, :text
add_column :categories, :carriers, :text, array: true, default: []
end
end
|
class HomeController < ApplicationController
before_action :authenticate_user!, only: [:index]
before_action :set_q, only: [:index, :search]
before_action :set_scraping, only: [:index, :search]
before_action :set_posts, only: [:index, :search]
def index
@graph = Post.group(:time).order(time: 'ASC').average(:congestion_level)
end
def about
end
def set_q
@q = Post.ransack(params[:q])
end
def search
@results = @q.result
@search = Post.where(direction:params[:q][:direction]).where(station_id:params[:q][:station_id]).where(day_of_week:params[:q][:day_of_week])
@graph = @search.group(:time).order(time: 'ASC').average(:congestion_level)
respond_to do |format|
format.html { render :index }
format.js
end
end
private
def post_params
params.require(:post).permit(:comment, :congestion_level, :date, :day_of_week, :time, :direction, :train_type, :station_id)
end
def set_scraping
require 'nokogiri'
require 'open-uri'
url = 'https://transit.yahoo.co.jp/traininfo/detail/86/0/'
doc = Nokogiri::HTML(open(url),nil,"utf-8")
nodes = doc.xpath('//*[@id="mdServiceStatus"]/dl/dt/text()')
@traffic = nodes.each { |node| pp node }
end
def set_posts
@posts = Post.all.includes(:user, :station).order(date: 'DESC', time: 'DESC').limit(30)
@icon = ["混雑1.jpg", "混雑2.jpg", "混雑3.jpg", "混雑4.jpg", "混雑5.jpg"]
end
end
|
# encoding: utf-8
require "logstash/filters/base"
require "logstash/namespace"
# This filter lets you convert an event field ( that must be 12 strings character ) in to an Ean13 string with a checksum
# This can be usefull if you need to output barcodes or some other sort of codes from a event field.
#
class LogStash::Filters::Ean < LogStash::Filters::Base
config_name "ean"
# The key you'll eanize ( under the EAN 13 standard )
config :key, :validate => :string, :default => "message"
public
def register
@to_ean = ""
end
public
def filter(event)
return unless filter?(event)
@logger.debug("Running ean filter", :event => event)
@logger.debug("Adding key to string", :current_key => @key)
@to_ean = event[@key]
@logger.debug("Final string built", :to_ean => @to_ean)
digested_string = eanize(@to_ean)
@logger.debug("Digested string", :digested_string => digested_string)
event[@key] = digested_string
end
public
def eanize(twelve)
twelve = twelve.to_s
return "" unless twelve.length == 12 && twelve.match(/\d{11}/)
arr = (0..11).to_a.collect do |i|
if (i+1).even?
twelve[i,1].to_i * 3
else
twelve[i,1].to_i
end
end
sum = arr.inject { |sum, n| sum + n }
remainder = sum % 10
if remainder == 0
check = 0
else
check = 10 - remainder
end
twelve + check.to_s
end
end # class LogStash::Filters::Ean
|
require 'test_helper'
class SelfieChainTest < Minitest::Test
def test_that_it_has_a_version_number
refute_nil ::SelfieChain::VERSION
end
def setup
@h = {a: {b: {}}}
end
def test_with_block
assert_equal @h[:a][:b][:c].to_i.selfie(-1) {|x| x > 0}, -1
@h[:a][:b] = {c: "14"}
assert_equal @h[:a][:b][:c].to_i.selfie(-1) {|x| x > 0}, 14
end
def test_share_selfie
@h[:a][:b] = {c: "14"}
assert_equal @h.selfie[:a][:b][:c]["d"].to_i.share_selfie, nil
@h[:a][:b][:c] = {"d" => "14"}
assert_equal @h.selfie[:a][:b][:c]["d"].to_i.share_selfie, 14
end
def test_share_selfie_with_block
@h[:a][:b] = {c: "14"}
assert_equal @h.selfie[:a][:b][:c]["d"].to_i.share_selfie(0) {|x| true}, nil
assert_equal @h.selfie[:a][:b][:c]["d"].to_i.share_selfie(0) {|x| true} || 15, 15
@h[:a][:b][:c] = {"d" => "14"}
assert_equal @h.selfie[:a][:b][:c]["d"].to_i.share_selfie(0) {|x| false}, 0
assert_equal @h.selfie[:a][:b][:c]["d"].to_i.share_selfie(0) {|x| true}, 14
assert_equal @h.selfie[:a][:b][:c]["d"].to_i.share_selfie {|x| true}, 14
assert_equal @h.selfie[:a][:b][:c]["d"].to_i.share_selfie {|x| false}, nil
end
def test_share_selfie_selfie
@h[:a][:b] = {c: "14"}
assert_equal @h.selfie[:a][:b][:c]["d"].to_i.share_selfie.selfie(0) {|x| !x.nil?}, 0
assert_equal @h.selfie[:a][:b][:c]["d"].to_i.share_selfie(0) {|x| !x.nil?}, nil
assert_equal @h.selfie[:a][:b][:c]["d"].to_i.share_selfie.selfie(0) {|x| x.nil?}, nil
end
end
|
require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper')
describe Admin::CommentsController do
fixtures :users
before(:each) do
login_as :quentin
stub!(:reset_session)
@blog = mock_model(Blog)
@post = mock_model(Post)
@user = mock_model(User)
@comment = mock_model(Comment, :destroy => true)
@comments = mock("Array of Comments", :to_xml => "XML")
Blog.stub!(:find).and_return(@blog)
Post.stub!(:find).and_return(@post)
Comment.stub!(:find).and_return(@comment)
Comment.stub!(:new).and_return(@comment)
end
describe "handling GET /admin/blogs/1/comments" do
def do_get
get :index, :blog_id => "1"
end
it "should be successful, render template and assign comments for view" do
@blog.should_receive(:comments).and_return(@comments)
@comments.should_receive(:paginate).with({ :include => { :post => :blog },
:per_page => 10, :page => nil }).and_return([@comment])
do_get
response.should be_success
response.should render_template('index')
assigns[:blog].should == @blog
assigns[:comments].should == [@comment]
end
end
describe "handling GET /admin/blogs/1/comments.xml" do
def do_get
@request.env["HTTP_ACCEPT"] = "application/xml"
get :index, :blog_id => "1"
end
it "should be successful and render comments as xml" do
@blog.should_receive(:comments).and_return(@comments)
@comments.should_receive(:recent).and_return(@comments)
@comments.should_receive(:to_xml).and_return("XML")
do_get
response.should be_success
end
end
describe "handling GET /admin/users/1/comments" do
before(:each) do
User.stub!(:find).and_return(@user)
end
def do_get
get :index, :user_id => "1"
end
it "should be successful, render template and assign comments and user for view" do
@user.should_receive(:comments).and_return(@comments)
@comments.should_receive(:paginate).with({ :include => { :post => :blog },
:per_page => 10, :page => nil }).and_return([@comment])
do_get
response.should be_success
response.should render_template('index')
assigns[:user].should == @user
assigns[:comments].should == [@comment]
end
end
describe "handling GET /admin/blogs/1/posts/1/comments" do
def do_get
get :index, :blog_id => "1", :post_id => "1"
end
it "should be successful, render template and assign comments for view" do
@blog.should_receive(:posts).and_return(@post)
@post.should_receive(:find).and_return(@post)
@post.should_receive(:comments).and_return(@comments)
@comments.should_receive(:paginate).with({ :include => { :post => :blog },
:per_page => 10, :page => nil }).and_return([@comment])
do_get
response.should be_success
response.should render_template('index')
assigns[:blog].should == @blog
assigns[:post].should == @post
assigns[:comments].should == [@comment]
end
end
describe "handling GET /admin/blogs/1/users/1/comments" do
before(:each) do
User.stub!(:find).and_return(@user)
end
def do_get
get :index, :blog_id => "1", :user_id => "1"
end
it "should be successful, render template and assign comments for view" do
@blog.should_receive(:comments).and_return(@comments)
@comments.should_receive(:by_user).with(@user).and_return(@comments)
@comments.should_receive(:paginate).with({ :include => { :post => :blog },
:per_page => 10, :page => nil }).and_return([@comment])
do_get
response.should be_success
response.should render_template('index')
assigns[:blog].should == @blog
assigns[:user].should == @user
assigns[:comments].should == [@comment]
end
end
describe "handling GET /admin/blogs/1/posts/1/comment/1" do
def do_get
get :show, :id => "1", :blog_id => "1", :post_id => "1"
end
it "should be successful, render show template find the comment and assign for the view" do
Comment.should_receive(:find).with("1", { :include => [:post, :user] }).and_return(@comment)
do_get
response.should be_success
response.should render_template('show')
assigns[:comment].should equal(@comment)
end
end
describe "handling GET /admin/blogs/1/posts/1/comment/1.xml" do
def do_get
@request.env["HTTP_ACCEPT"] = "application/xml"
get :show, :id => "1", :blog_id => "1", :post_id => "1"
end
it "should be successful, render as XML and find the comment and assign for the view" do
Comment.should_receive(:find).with("1", { :include => [:post, :user] }).and_return(@comment)
@comment.should_receive(:to_xml).and_return("XML")
do_get
response.should be_success
response.body.should == "XML"
end
end
describe "handling GET /admin/blogs/1/posts/1/comments/new" do
def do_get
get :new, :blog_id => "1", :post_id => "1"
end
it "should be successful, render new template, create new comment and assign for view" do
Comment.should_receive(:new).and_return(@comment)
@comment.should_not_receive(:save)
do_get
response.should be_success
response.should render_template('new')
assigns[:comment].should equal(@comment)
end
end
describe "handling GET /admin/blogs/1/posts/1/comments/1/edit" do
def do_get
get :edit, :id => "1", :blog_id => "1", :post_id => "1"
end
it "should be successful, render edit template, find commment and assign for view" do
Comment.should_receive(:find).and_return(@comment)
do_get
response.should be_success
response.should render_template('edit')
assigns[:comment].should equal(@comment)
end
end
describe "handling POST /admin/blogs/1/posts/1/comments" do
describe "with setting author (user) and into comments collection (sucessful create)" do
def do_post
@post.should_receive(:blog).and_return(@blog)
@post.should_receive(:comments).and_return(@comment)
@comment.should_receive(:build).and_return(@comment)
@comment.should_receive(:user=).with(users(:aaron)).and_return(true)
@post.should_receive(:save).and_return(true)
post :create, :comment => {}, :blog_id => "1", :post_id => "1"
end
it "should create a new comment with the correct author set" do
login_as :aaron
do_post
end
it "should redirect to the new comment" do
login_as :aaron
do_post
response.should redirect_to(admin_blog_post_comment_url(@blog, @post, @comment))
end
end
describe "with failed create" do
def do_post
@post.should_receive(:comments).and_return(@comment)
@comment.should_receive(:build).and_return(@comment)
@comment.should_receive(:user=).with(users(:aaron)).and_return(true)
@post.should_receive(:save).and_return(false)
post :create, :comment => {}, :blog_id => "1", :post_id => "1"
end
it "should re-render 'new'" do
login_as :aaron
do_post
response.should render_template('new')
end
end
end
describe "handling PUT /admin/blogs/1/posts/1/comments/1" do
describe "with successful update" do
def do_put
@comment.should_receive(:update_attributes).and_return(true)
@comment.should_receive(:post).twice.and_return(@post)
@post.should_receive(:blog).and_return(@blog)
put :update, :id => "1", :post_id => "1", :comment => { }, :blog_id => "1"
end
it "should update the found comment and redirect to the comment" do
do_put
response.should redirect_to(admin_blog_post_comment_url(@blog, @post, @comment))
end
end
describe "with failed update" do
def do_put
@comment.should_receive(:update_attributes).and_return(false)
put :update, :id => "1", :blog_id => "1", :post_id => "1"
end
it "should re-render 'edit'" do
do_put
response.should render_template('edit')
end
end
end
describe "handling DELETE /admin/posts/1/comments/1" do
def do_delete
@comment.should_receive(:post).twice.and_return(@post)
@post.should_receive(:blog).and_return(@blog)
delete :destroy, :id => "1", :blog_id => "1", :post_id => "1"
end
it "should call destroy on the found comment and redirect to the comments list" do
@comment.should_receive(:destroy)
do_delete
response.should redirect_to(admin_blog_post_comments_url(@blog, @post))
end
end
describe "handling exceptions" do
before(:each) do
controller.use_rails_error_handling!
end
it "should render 404 for RecordNotFound on GET /admin/blogs/1/posts/1/comments/15155199 " do
Comment.stub!(:find).and_raise(ActiveRecord::RecordNotFound)
get :show, :id => "15155199", :blog_id => "1", :post_id => "1"
response.should render_template("#{RAILS_ROOT}/public/404.html")
end
end
end |
class Subject < ActiveRecord::Base
# attr_accessible :title, :body
has_many :pages
validates_presence_of :name
validates_length_of :name, :maximum => 255
end
|
class AddPathToWorkingArticle < ActiveRecord::Migration[5.2]
def change
add_column :working_articles, :publication_name, :string
add_column :working_articles, :path, :string
add_column :working_articles, :date, :date
add_column :working_articles, :page_number, :integer
add_column :working_articles, :page_heading_margin_in_lines, :integer
add_column :working_articles, :grid_width, :float
add_column :working_articles, :grid_height, :float
add_column :working_articles, :gutter, :float
end
end
|
require "rails_helper"
RSpec.describe "Setting up a pool", js: true do
let(:pool) { create(:pool) }
let!(:contestants) { create_list(:contestant, 3, pool: pool) }
let!(:other_contestant) { create(:contestant) }
let!(:entries) { create_list(:entry, 3, pool: pool) }
let!(:other_entry) { create(:entry) }
before { visit "/pools/#{pool.id}/setup" }
it "display links to pool standings, setup, and scoring" do
pool_id = pool.id
within(".pool-admin-links") do
expect(page).to have_link("Standings", href: "/pools/#{pool_id}")
expect(page).to have_link("Setup", href: "/pools/#{pool_id}/setup")
expect(page).to have_link("Score", href: "/pools/#{pool_id}/score")
end
end
describe "contestants" do
it "displays a list of the contestants" do
within(".contestants-list") do
expect(all(".contestant").count).to eq contestants.count
expect(all("a.remove").count).to eq contestants.count
contestants.each do |contestant|
expect(page).to have_text contestant.first_name
end
end
end
describe "adding a contestant" do
let(:args) { attributes_for(:contestant) }
context "successfully" do
it "appends the contestant to the list and clears the form" do
within(".create-contestant") do
fill_in "first_name", with: args[:first_name]
fill_in "last_name", with: args[:last_name]
fill_in "residence", with: args[:residence]
fill_in "description", with: args[:description]
click_button "Create Contestant"
end
within(".contestants-list") do
expect(page).to have_text args[:first_name]
end
within(".create-contestant") do
expect(find("input#first_name").value).to eq ""
end
end
end
context "unsuccessfully" do
xit "displays an error message"
end
end
describe "removing a contestant" do
let(:entry) { entries.last }
let(:contestant) { contestants.last }
let!(:pick) { create(:pick, entry: entry, contestant: contestant) }
let!(:contestant_score) { create(:contestant_score, contestant: contestant, score: create(:score, points: 5)) }
it "removes the contestant from the pool and updates entry scores appropriately" do
visit "/pools/#{pool.id}/setup"
entry_points = find(".entry", text: /#{entry.name}/i).find(".points")
expect(entry_points.text).to eq "5"
expect(page).to have_text contestant.first_name
remove_contestant_link = find(".contestant", text: /#{contestant.first_name}/i).find("a.remove")
expect do
remove_contestant_link.click
sleep 1
end.to change(pool.reload.contestants, :count).by(-1)
expect(page).to_not have_text contestant.first_name
expect(page).to have_text contestants.first.first_name
expect(entry_points.text).to eq "0"
end
xit "uses a confirm box to ensure the action"
end
end
describe "entries" do
it "displays a list of the entries" do
within(".entries-list") do
expect(all(".entry").count).to eq entries.count
expect(all("a.admin-link", text: /remove/i).count).to eq entries.count
entries.each do |entry|
expect(page).to have_text entry.name
expect(page).to have_text entry.points
expect(page).to have_link(text: "Make Picks", href: "/entries/#{entry.id}/picks")
end
end
entry = entries.first
link = find(:css, "a.admin-link[href='/entries/#{entry.id}/picks']")
link.click
expect(page).to have_text(/#{entry.name} - #{entry.points} points/i)
end
describe "adding an entry" do
let(:entry_name) { "The Champ" }
context "successfully" do
it "appends the entry to the list and clears the form" do
within(".create-entry") do
fill_in "entry_name", with: entry_name
click_button "Create Entry"
end
within(".entries-list") do
expect(page).to have_text entry_name
end
within(".create-entry") do
expect(find("input#entry_name").value).to eq ""
end
end
end
context "unsuccessfully" do
xit "displays an error message"
end
end
describe "removing an entry" do
let(:entry) { entries.first }
it "removes the entry from the pool" do
expect(page).to have_text entry.name
entry_row = find("a[href='/entries/#{entry.id}/picks']").first(:xpath, ".//..")
expect do
entry_row.find("a.remove").click
sleep 1
end.to change(pool.reload.entries, :count).by(-1)
expect(page).to_not have_text entry.name
expect(page).to have_text entries.last.name
end
xit "uses a confirm box to ensure the action"
end
end
end
|
class Shops::Admin::ExpressTemplatesController < Shops::Admin::BaseController
before_action :set_express_template, only: [:show, :edit, :update, :destroy]
# GET /express_templates
# GET /express_templates.json
def index
@express_templates = current_shop.express_templates
.page(params[:page])
.per(params[:per])
# render json: @express_templates
end
def new
@express_template = current_shop.express_templates
.build(free_shipping: false, template: {
default: { first_quantity: 1 }
})
end
# GET /express_templates/1
# GET /express_templates/1.json
def show
# render json: @express_template
end
def edit
end
# POST /express_templates
# POST /express_templates.json
def create
@express_template = current_shop.express_templates.build(express_template_params)
respond_to do |format|
if @express_template.save
format.html do
flash[:notice] = "成功创建运费模板\"#{@express_template.name}\"!"
redirect_to shop_admin_express_templates_path(current_shop.name)
end
format.json { render json: @express_template, status: :created }
else
format.html { render "edit" }
format.json { render json: @express_template.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /express_templates/1
# PATCH/PUT /express_templates/1.json
def update
@express_template = current_shop.express_templates.find(params[:id])
respond_to do |format|
if @express_template.update(express_template_params)
format.html do
flash[:notice] = "成功保存运费模板\"#{@express_template.name}\"!"
redirect_to shop_admin_express_templates_path(current_shop.name)
# redirect_to shop_admin_express_template_path(current_shop.name, @express_template) }
end
format.json { head :no_content }
else
format.html { render "edit" }
format.json { render json: @express_template.errors, status: :unprocessable_entity }
end
end
end
# DELETE /express_templates/1
# DELETE /express_templates/1.json
def destroy
@express_template.destroy
respond_to do |format|
format.html { redirect_to shop_admin_express_templates_path(current_shop.name) }
format.json { head :no_content }
end
end
def next_nodes
list = ChinaCity.list(params[:code])
render json: list
end
def set_default
current_shop.update(default_express_template_id: params[:template_id])
end
def cancel_default
current_shop.update(default_express_template_id: nil)
end
private
def set_express_template
@express_template = current_shop.express_templates.find(params[:id])
end
def express_template_params
params.require(:express_template)
.permit(:shop_id, :name, :free_shipping)
.tap do |white_list|
template = params[:express_template][:template]
if template.present?
white_list[:template] = {}
template.each do |code, setting|
if "default" == code || (ChinaCity.get(code) rescue false)
white_list[:template][code] = template[code]
end
end
end
end
end
end
|
require 'test_helper'
class TaskTest < ActiveSupport::TestCase
def setup
@user = users(:first)
@list = lists(:one)
@task = @list.tasks.build(content: "Task content", user_id: @user.id)
end
test "should be valid" do
assert @task.valid?
end
test "user id should be present" do
@task.user_id = nil
assert_not @task.valid?
end
test "list id should be present" do
@task.list_id = nil
assert_not @task.valid?
end
test "content should be present" do
@task.content = nil
assert_not @task.valid?
end
test "content should be at most 140 characters" do
@task.content = "a" * 141
assert_not @task.valid?
end
end
|
class Reverse < Command
def self.help
return "Reverse the given message."
end
def self.run(nick, channel, msg)
return msg.reverse
end
end
|
require 'spec_helper'
describe Webex::Meeting::Action do
custom_attributes = { meeting_key: 'fweofuw9873ri' }
context '[PARAMS]delete' do
api_type = 'DM'
it '#api /m.php with custom set' do
params = Webex::Meeting::Action.new(custom_attributes).delete
expect(params['AT']).to eq api_type
expect(params['ST']).to eq 'FAIL'
expect(params['RS']).to eq 'AccessDenied'
end
end
context '[ERROR]delete' do
it '#api /m.php with option_missing' do
expect { Webex::Meeting::Action.new.delete }.to raise_error(Webex::MissingOption)
end
end
context '[PARAMS]host' do
api_type = 'HM'
it '#api /m.php with custom set' do
params = Webex::Meeting::Action.new(custom_attributes).host
expect(params['AT']).to eq api_type
expect(params['ST']).to eq 'FAIL'
expect(params['RS']).to eq 'AccessDenied'
end
end
context '[ERROR]host' do
it '#api /m.php with option_missing' do
expect { Webex::Meeting::Action.new.host }.to raise_error(Webex::MissingOption)
end
end
context '[PARAMS]join' do
api_type = 'JM'
it '#api /m.php with custom set' do
params = Webex::Meeting::Action.new(custom_attributes).join
expect(params['AT']).to eq api_type
expect(params['ST']).to eq 'FAIL'
expect(params['RS']).to eq 'InvalidDataFormat'
end
end
context '[ERROR]join' do
it '#api /m.php with option_missing' do
expect { Webex::Meeting::Action.new.join }.to raise_error(Webex::MissingOption)
end
end
context '[PARAMS]list_meetings' do
api_type = 'LM'
it '#api /m.php with custom set' do
params = Webex::Meeting::Action.new(custom_attributes).list_meetings
expect(params['AT']).to eq api_type
expect(params['ST']).to eq 'FAIL'
expect(params['RS']).to eq 'AccessDenied'
end
end
context '[PARAMS]list_open_meetings' do
it '#api /m.php with custom set' do
params = Webex::Meeting::Action.new(custom_attributes).list_open_meetings
expect(params['ST']).to eq 'FAIL'
expect(params['RS']).to eq 'AccessDenied'
end
end
end
|
require 'rubygems'
require 'rake'
begin
require 'jeweler'
Jeweler::Tasks.new do |gem|
gem.name = "kindeditor"
gem.summary = %Q{Rails KindEditor plugin}
gem.description = %Q{Rails KindEditor integration plugin with paperclip support for rails3 Rc,it supports active_record and mongoid!}
gem.email = "doinsist@gmail.com"
gem.homepage = "http://github.com/doabit/kindeditor"
gem.authors = ["doabit"]
gem.add_development_dependency "paperclip", ">= 2.3.3"
# gem is a Gem::Specification... see http://www.rubygems.org/read/chapter/20 for additional settings
end
Jeweler::GemcutterTasks.new
rescue LoadError
puts "Jeweler (or a dependency) not available. Install it with: gem install jeweler"
end
|
# frozen_string_literal: true
module Types
class LocationType < Types::BaseObject
field :id, ID, null: false
field :name, String, null: true
field :description, String, null: true
field :latitude, Float, null: true
field :longitude, Float, null: true
# Fetches the url of a stored image
def image_url
return object.image.service_url if object.image.attached?
nil
end
end
end |
# frozen_string_literal: true
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
# get 'tasks' => 'tasks#index', as: :tasks
# get 'tasks/new' => 'tasks#new', as: :tasks_new
# get 'tasks/:id' => 'tasks#show', as: :task
# post 'tasks' => 'tasks#create'
# get 'tasks/:id/edit' => 'tasks#edit', as: :task_edit
# patch 'tasks/:id' => 'tasks#update'
# delete 'tasks/:id' => 'tasks#destroy'
resources :tasks
get 'task/:id/complete' => 'tasks#complete', as: :task_complete
get 'task/:id/uncomplete' => 'tasks#uncomplete', as: :task_uncomplete
end
|
class AddUrlToBands < ActiveRecord::Migration
def change
add_column :bands, :url, :string
Band.initialize_urls
end
end
|
require "pp"
module TicTacToe
class Board
PositionOccupiedError = Class.new(StandardError)
OutOfBoundsError = Class.new(StandardError)
def initialize
@data = [[nil,nil,nil],[nil,nil,nil],[nil,nil,nil]]
end
def [](row,col)
@data[row][col]
end
def []=(row,col,value)
raise OutOfBoundsError if [2,row,col].max > 2
raise PositionOccupiedError if @data[row][col]
@data[row][col] = value
end
def rows
@data
end
def columns
@data.transpose
end
def diagonals
[[self[0,0], self[1,1], self[2,2]],
[self[0,2], self[1,1], self[2,0]]]
end
def lines
rows + columns + diagonals
end
def to_s
rows.map { |row| row.map { |e| e || "*" }.join(" | ") }.join("\n")
end
end
class Game
def initialize
@board = TicTacToe::Board.new
@symbols = ["X","O"].cycle
new_turn
end
attr_reader :board, :current_symbol
def move(row,col)
@board[row,col] = @current_symbol
end
def new_turn
@current_symbol = @symbols.next
end
def finished?
@board.lines.any? { |line| line.all? { |e| e == @current_symbol } }
end
end
module UI
extend self
def play
game = TicTacToe::Game.new
loop do
puts game.board
print ">> "
move = gets.chomp.split(",").map { |e| e.to_i }
begin
game.move(*move)
rescue TicTacToe::Board::OutOfBoundsError
puts "Out of bounds, try another position"
next
rescue TicTacToe::Board::PositionOccupiedError
puts "There is already a mark in that position"
next
end
if game.finished?
puts "#{game.current_symbol} wins"
exit
end
game.new_turn
end
end
end
end
TicTacToe::UI.play
|
# frozen_string_literal: true
module Rabbitek
class CLI
##
# OS signal handlers
class SignalHandlers
SIGNALS = {
INT: :shutdown,
TERM: :shutdown
}.freeze
def self.setup(io_w)
SIGNALS.each do |signal, hook|
Signal.trap(signal) { io_w.write("#{hook}\n") }
end
end
def self.shutdown
raise Interrupt
end
end
end
end
|
class Topic < ActiveRecord::Base
attr_accessible :title, :questions_attributes
has_many :questions
accepts_nested_attributes_for :questions
end
|
require 'spec_helper'
describe RecyclingCenter do
context 'before_validation' do
it 'calls encode_location before validation' do
rc = FactoryGirl.build(:recycling_center, lat: nil, lng: nil)
rc.should_receive(:encode_location)
rc.save
end
it 'reencodes lat and lng if address is changed' do
rc = FactoryGirl.create(:recycling_center)
lat, lng = rc.lat, rc.lng
rc.address = 'Glostrup genbrugsplads, 2600 Glostrup'
rc.save
rc.lat.should_not eq(lat)
rc.lng.should_not eq(lng)
end
end
end
# == Schema Information
#
# Table name: recycling_centers
#
# id :integer not null, primary key
# name :string(255)
# address :string(255)
# lat :float
# lng :float
# category :string(255)
# factions :text
# created_at :datetime
# updated_at :datetime
#
|
class ComplaintBuildingAsset < ActiveRecord::Base
belongs_to :user
validates_inclusion_of :repair_action, :in => [true, false]
validates_inclusion_of :spare_part_action, :in => [true, false]
validates :building_asset_type_id, :type_id, :item_id, :location, :serial_no, :reason, :presence => true
has_many :building_asset_types
end
|
class SearchController < ApplicationController
before_filter :login_required
before_filter :search_count
def search_count
@query = params[:query]
@media_resources_count = MediaResource.search_count(@query,
:conditions => {:creator_id => current_user.id, :is_removed => 0})
@media_shares_count = MediaShare.search_count(@query,
:conditions => {:receiver_id => current_user.id})
@public_resources_count = PublicResource.search_count(@query,
:conditions => {:creator_id => current_user.id})
@tag_media_resources_count = MediaResource.tagged_with(@query).of_creator(current_user).count
@tag_public_media_resources_count = MediaResource.tagged_with(@query).public_share.count
@tag_share_media_resources_count = current_user.received_shared_media_resources.tagged_with(@query).count
@courses_count = Course.search_count @query
@students_count = Student.search_count @query
@teachers_count = Teacher.search_count @query
@all_count = @media_resources_count + @media_shares_count + @public_resources_count +
@tag_media_resources_count + @tag_public_media_resources_count + @tag_share_media_resources_count +
@courses_count + @students_count + @teachers_count
end
def index
@media_resources = MediaResource.search(@query,
:conditions => {:creator_id => current_user.id, :is_removed => 0},
:per_page => 3, :page => 1)
@media_shares = MediaShare.search(@query,
:conditions => {:receiver_id => current_user.id},
:per_page => 3, :page => 1)
@public_resources = PublicResource.search(@query,
:conditions => {:creator_id => current_user.id},
:per_page => 3, :page => 1)
@tag_media_resources = MediaResource.tagged_with(@query).of_creator(current_user).paginate(:per_page => 3, :page => 1)
@tag_public_media_resources = MediaResource.tagged_with(@query).public_share.paginate(:per_page => 3, :page => 1)
@tag_share_media_resources = current_user.received_shared_media_resources.tagged_with(@query).paginate(:per_page => 3, :page => 1)
@courses = Course.search @query, :per_page => 3, :page => 1
@students = Student.search @query, :per_page => 3, :page => 1
@teachers = Teacher.search @query, :per_page => 3, :page => 1
end
def show
query = params[:query]
case params[:kind]
when 'media_resource'
search_media_resource
when 'media_share'
search_media_share
when 'public_resource'
search_public_resource
when 'tag'
search_tag
when 'course'
search_course
when 'student'
search_student
when 'teacher'
search_teacher
else
render_status_page 404, "页面不存在"
end
end
def search_media_resource
@media_resources = MediaResource.search(@query,
:conditions => {:creator_id => current_user.id, :is_removed => 0},
:per_page => params[:per_page]||30, :page => params[:page]||1)
render :template => "/search/search_media_resource"
end
def search_media_share
@media_shares = MediaShare.search(@query,
:conditions => {:receiver_id => current_user.id},
:per_page => params[:per_page]||30, :page => params[:page]||1)
render :template => "/search/search_media_share"
end
def search_public_resource
@public_resources = PublicResource.search(@query,
:conditions => {:creator_id => current_user.id},
:per_page => params[:per_page]||30, :page => params[:page]||1)
render :template => "/search/search_public_resource"
end
def search_tag
@tag_media_resources = MediaResource.tagged_with(@query).of_creator(current_user).paginate(:per_page => params[:per_page]||30, :page => params[:page]||1)
@tag_share_media_resources = current_user.received_shared_media_resources.tagged_with(@query).paginate(:per_page => params[:per_page]||30, :page => params[:page]||1)
@tag_public_media_resources = MediaResource.tagged_with(@query).public_share.paginate(:per_page => params[:per_page]||30, :page => params[:page]||1)
render :template => "/search/search_tag"
end
def search_course
@courses = Course.search @query, :per_page => params[:per_page]||30, :page => params[:page]||1
render :template => "/search/search_course"
end
def search_student
@students = Student.search @query, :per_page => params[:per_page]||30, :page => params[:page]||1
render :template => "/search/search_student"
end
def search_teacher
@teachers = Teacher.search @query, :per_page => params[:per_page]||30, :page => params[:page]||1
render :template => "/search/search_teacher"
end
end |
module Generamba
VERSION = '1.5.0'
RELEASE_DATE = '29.04.2019'
RELEASE_LINK = "https://github.com/rambler-digital-solutions/Generamba/releases/tag/#{VERSION}"
end
|
# frozen_string_literal: true
require 'rails_helper'
describe User, type: :model do
let(:user) { create :user }
describe 'validations' do
subject { create :user }
it { is_expected.to validate_presence_of(:uid) }
it { is_expected.to validate_presence_of(:email) }
it { is_expected.to validate_presence_of(:first_name) }
it { is_expected.to validate_uniqueness_of(:uid) }
end
describe '.alphabetically' do
let(:first_user) { create :user, last_name: 'aaaaaa' }
let(:last_user) { create :user, last_name: 'zzzzzz' }
before { first_user && last_user }
it 'orders users by last name' do
expect(described_class.alphabetically.first).to eq(first_user)
expect(described_class.alphabetically.last).to eq(last_user)
end
it 'can sort them in reverse' do
expect(described_class.alphabetically(:desc).first).to eq(last_user)
expect(described_class.alphabetically(:desc).last).to eq(first_user)
end
end
describe '#name' do
it 'returns the full name' do
expect(user.name).to eq("#{user.first_name} #{user.last_name}")
end
end
end
|
require 'singleton'
module Ki
class KiConfig
include Singleton
attr_reader :config, :environment
def read(environment)
@environment = environment
@config = YAML.load_file(config_file_path)[environment]
@config['cors'] ||= true
end
def config_file_path
'config.yml'
end
def cors?
@config['cors']
end
def middleware
used_middleware = %w(ApiHandler CoffeeCompiler SassCompiler HamlCompiler
PublicFileServer)
used_middleware = @config['middleware'] if @config['middleware'].present?
# convert middleware to ruby object
used_middleware.map do |middleware|
Object.const_get('Ki').const_get('Middleware').const_get(middleware)
end
end
def database
@config['database']
end
end
end
|
class Api::V1::TimelogsController < ApplicationController
before_action :authenticate_user!
before_action :set_timelog, only: [:show, :edit, :update]
def index
if params[:page] && params[:per]
@timelogs = Logtime.page(params[:page]).per(params[:per])
else
@timelogs = Logtime.limit(20)
end
render json: @timelogs
end
def show
render json: @timelog
end
def create
@timesheet_check = Logtime.where("task_master_id =#{params[:task_master_id]} and task_date = '#{params[:date].to_date}' and user_id = #{params[:user_id]}")
puts"-----#{params[:task_master_id]}----#{params[:date].to_date}---#{params[:user_id]}--"
if @timesheet_check != nil and @timesheet_check.size != 0
@timelog = @timesheet_check[0]
else
@timelog = Logtime.new(timelog_params)
end
if @timelog.save
@timelog.task_date = params[:date]
@timelog.taskboard_id = params[:id]
if params[:task_time] and params[:task_time]!=nil
@timelog.task_time = params[:task_time]
else
if @timelog.end_time!=nil and @timelog.start_time!=nil
@timelog.task_time = ((@timelog.end_time - @timelog.start_time) / 1.hour)
end
end
@timelog.user_id = params[:user_id]
@timelog.status = "pending"
@timelog.save
if params[:assign] != nil and params[:assign].to_i == 1 and params[:assigned_user_id].present?
#convert_param_to_array(params[:assigned_user_id])
@assigned_user_id = params[:assigned_user_id]
p=0
@assigned_user_id.each do |user|
@find_user = Assign.where("taskboard_id = #{params[:id]} and assigned_user_id = #{user}")
puts "---del-2222222---#{@find_user.size}-----finduser---#{user}----#{params[:id]}-------id---@find_user[0].id-"
if @find_user != nil and @find_user.size != 0
else
@assign = Assign.new
@assign.taskboard_id = params[:id]
@assign.assigned_user_id = user
@assign.assigneer_id = params[:user_id]
@assign.track_id = params[:user_id]
@assign.is_delete = 0
@assign.save!
end
end
end
puts "---del-----#{@del}-----finduser---#{ params[:unassigned_user_id]}-----#{ params[:unassigned_user_id].class}--id---@find_user[0].id-"
if params[:assign] != nil and params[:assign].to_i == 1 and params[:unassigned_user_id].present?
#convert_param_to_array(params[:unassigned_user_id])
@unassigned_user_id = params[:unassigned_user_id]
p=0
@unassigned_user_id.each do |user|
@find_unassinged_user = Assign.where("taskboard_id = #{params[:id]} and assigned_user_id = #{user}")
puts "---del-11111----#{@find_unassinged_user.size}-----finduser---#{user}----#{params[:id]}-------id---@find_unassinged_user[0].id-"
if @find_unassinged_user != nil and @find_unassinged_user.size != 0
@del = Assign.find_by_id(@find_unassinged_user[0].id)
@del.is_delete = 1
@del.save!
#@del.destroy if @del != nil
else
end
end
end
log_values = []
log_values << {
'taskboard_id' => @timelog.taskboard_id,
'task_time' => @timelog.task_time
}
log_values={
'valid' => true,
'time_log' => log_values,
'msg' => "created successfully"
}
render json: log_values
else
render json: { valid: false, error: @timelog.errors }, status: 404
end
end
def update
if @timelog.update(timelog_params)
render json: { valid: true, msg:"timelog updated successfully."}
else
render json: { valid: false, error: @timelog.errors }, status: 404
end
end
def destroy
end
private
# Use callbacks to share common setup or constraints between actions.
def set_timelog
@timelog = Logtime.find_by_id(params[:id])
if @timelog
else
render json: { valid: false}, status: 404
end
end
# Never trust parameters from the scary internet, only allow the white list through.
def timelog_params
#params.require(:branch).permit(:name, :active, :user_id)
raw_parameters = { :date => "#{params[:date]}", :start_time => "#{params[:start_time]}", :end_time => "#{params[:end_time]}", :taskboard_id => "#{params[:taskboard_id]}", :task_master_id => "#{params[:task_master_id]}", :project_master_id => "#{params[:project_master_id]}" , :sprint_planning_id => "#{params[:sprint_planning_id]}" }
parameters = ActionController::Parameters.new(raw_parameters)
parameters.permit(:date, :start_time, :end_time, :taskboard_id, :task_master_id, :project_master_id, :sprint_planning_id)
end
end
|
class AddIndexToMemberships < ActiveRecord::Migration
def change
add_index :memberships, [:user_id, :meetup_id, :owner], unique: true
end
end
|
begin
require 'terminal-table'
rescue LoadError
puts "You must `gem install terminal-table` in order to use the rake tasks in #{__FILE__}"
end
namespace :rack_attack_admin do
def clear
puts "\e[H\e[2J"
end
desc "Watch the internal state of Rack::Attack. Similar to /admin/rack_attack but auto-refreshes, and shows previous value if there was a change. (Mostly useful in dev where there aren't many keys and they don't change very often.)"
task :watch do
interval = ENV['interval']&.to_i || 1
curr_h = {}
prev_h = {}
prev_h_s_ago = 0
curr_banned = []
prev_banned = []
prev_banned_s_ago = 0
loop do
clear
if curr_banned != Rack::Attack::Fail2Ban.banned_ip_keys
prev_banned = curr_banned
prev_banned_s_ago = 0
curr_banned = Rack::Attack::Fail2Ban.banned_ip_keys
end
if curr_h != Rack::Attack.counters_h
prev_h = curr_h
prev_h_s_ago = 0
curr_h = Rack::Attack.counters_h
end
puts Terminal::Table.new(
headings: ['Banned IP', "Previous (#{prev_h_s_ago} s ago)"],
rows: [].tap { |rows|
while (
row = [
curr_banned.shift,
prev_banned.shift
]
row.any?
) do
row = row.map {|key| key && Rack::Attack.humanize_key(key) }
rows << row
end
}
)
keys = (
curr_h.keys |
prev_h.keys
)
rows = keys.map do |key|
[
"%-80s" % Rack::Attack.humanize_key(key),
curr_h[key],
prev_h[key],
]
end
puts Terminal::Table.new(
headings: ['Key', 'Current Count', "Previous (#{prev_h_s_ago} s ago)"],
rows: rows
)
sleep interval
prev_h_s_ago += interval
prev_banned_s_ago += interval
end
end
end
|
FactoryBot.define do
factory :hotel do
name { Faker::Name.name }
address { Faker::Address.full_address }
phone { Faker::PhoneNumber.phone_number }
latlng { "#{Faker::Address.latitude}, #{Faker::Address.longitude}" }
price { Faker::Commerce.price }
end
end
|
# frozen_string_literal: true
class InProgressFormCleaner
include Sidekiq::Worker
def perform
Sentry::TagRainbows.tag
forms = InProgressForm.where("updated_at < '#{InProgressForm::EXPIRES_AFTER.ago}'")
logger.info("Deleting #{forms.count} old saved forms")
forms.delete_all
end
end
|
module Bibliovore
# Circulation information for copies of titles in individual library
# locations
class Copy
# @return [Bibliovore::LibraryLocation] The location of the copies
attr_reader :location
attr_reader :status
def initialize(data)
@data = data
@location = LibraryLocation.new(@data['location'])
@status = Status.new(@data['status'])
end
# @return [String] The collection to which the copies belong
def collection
@data['collection']
end
# @return [String] The call number
def call_number
@data['call_number']
end
# @return [String] Circulation status of the copies
def library_status
@data['library_status']
end
end
end
|
class Challenge1
def self.balanced?(string)
pairs = { ')' => '(', '}' => '{', ']' => '['}
opening_char = ['(', '[', '{']
closing_char = [')', ']', '}']
stack = []
string.each_char do |item| #iterate to each character of array
if opening_char.include?(item) #if it is an opening character, put in the stack
stack.push(item)
else closing_char.include?(item) #check if next character is a closing char
if stack.empty?
return false
elsif closing_char != stack.last
return false
else closing_char == stack.last # if it is a match, pop the last character from the stack
stack.pop(item)
end
end
end
if stack.empty?
true
else
false
end
end
end
|
class Admin::CategoriesController < Admin::ApplicationController
before_filter :cat_id, :only => [:show, :edit, :update, :destroy]
def index
@categories = Category.all
end
def show
@post = @category.posts
end
def new
@category = Category.new(params[:category])
end
def create
@category = Category.new(params[:category])
respond_to do |format|
if @category.save
flash[:success] = "Category Created!"
format.html { redirect_to admin_categories_path }
else
flash[:error] = "Error saving category!"
format.html { render :action => "new"}
end
end
end
def edit
end
def update
respond_to do |format|
if @category.update_attributes(params[:category])
flash[:success] = "Category updated!"
format.html { redirect_to admin_categories_path }
else
flash[:error] = "Error updating category"
end
end
end
def destroy
@category.destroy
respond_to do |format|
format.html { redirect_to admin_categories_path }
end
end
def cat_id
@category = Category.find(params[:id])
end
end |
class CreateAttachments < ActiveRecord::Migration[5.0]
def change
create_table :attachments do |t|
t.string :file_url
t.references :quotation_comment
t.timestamps
end
QuotationComment.where.not(s3_attachment_url: nil).find_each do |comment|
Attachment.create!(quotation_comment: comment, file_url: comment.s3_attachment_url)
end
end
end
|
class TransportTransactionDiscount < ActiveRecord::Base
belongs_to :finance_transaction
belongs_to :transport_fee_discount
after_update :build_report_sync_job, :if => lambda { |x| x.is_active_changed? and !x.is_active }
def deactivate
finance_transaction.present? ? self.update_attribute('is_active', false) : self.destroy
end
def perform
fetch_discount_and_reverse_sync
end
def build_report_sync_job
## Queue:: master_particular_reports
## change queue name only for testing purpose
queue_name = 'master_particular_reports'
# queue_name = 'master_particular_reports_test'
Delayed::Job.enqueue(self, {:queue => queue_name}) if valid_for_sync
end
def valid_for_sync
return false if is_active
ft = self.finance_transaction
trs = ft.transaction_report_sync
transport_fee = ft.try(:finance)
return (ft.present? and transport_fee.try(:receiver_type) == 'Student')
end
def fetch_discount_and_reverse_sync
# should process only not an active record
return unless valid_for_sync
ft = self.finance_transaction
transport_fee = ft.try(:finance)
# ft = transport_transaction_discount.try(:finance_transaction)
trs = ft.try(:transaction_report_sync)
unless trs.present?
mfp = MasterFeeParticular.find_by_particular_type 'TransportFee'
search_data = {}
search_data['date'] = "#{ft.transaction_date}"
search_data['student_id'] = "#{ft.payee_id}"
search_data['school_id'] = "#{ft.school_id}"
search_data['batch_id'] = "#{transport_fee.groupable_id}"
search_data['mode_of_payment'] = "#{ft.payment_mode}"
search_data['fee_account_id'] = "#{ft.fee_account.try(:id)}"
search_data['master_fee_particular_id'] = "#{mfp.id}"
digest = calculate_crc(search_data)
mpr = MasterParticularReport.find_by_digest digest
if mpr.present?
mpr.discount_amount -= discount_amount
mpr.discount_amount = 0 if mpr.discount_amount < 0
# destroy self when reverse sync is done
TransactionReportSync.transaction do
begin
self.destroy if mpr.save
rescue Exception => e
puts e.inspect
raise ActiveRecord::Rollback
end
end
end
end
end
def calculate_crc data
str = ""
TransactionReportSync::DIGEST_COLUMNS.each do |k|
str += data[k]
end
TransactionReportSync.string_to_crc str
end
end
|
module DowlOptParse
class Formatter
def initialize(schema)
@schema = schema
end
def call
formatted_options.join("\n")
end
def formatted_options
@schema.map do |_, config|
flags = [config[:long], config[:short]].compact
flags_line = "#{flags.join(', ')} #{config[:argument]}".strip
doc_line = (config[:doc] || "").each_line.map{ |line| " #{line.strip}" }
[flags_line, doc_line].join("\n").strip
end
end
end
end
|
class ReportsMailer < ApplicationMailer
def report_view(report)
@report = report
status = (report.state == "accepted") ? "Aceptado" : "Rechazado"
mail(to: report.alumno.email, subject: "Reporte #{status}" )
end
end
|
require 'robot'
RSpec.describe Robot do
let(:robot) { Robot.new.place(1, 1, 'wEst')}
describe '#place' do
context 'with valid attributes' do
it 'places robot' do
expect(robot.x).to be 1
expect(robot.y).to be 1
expect(robot.direction[:title]).to eq 'west'
end
end
context 'with invalid attributes' do
it 'raises wrong location error' do
robot = Robot.new
expect{ robot.place(1, 5, 'west') }.to raise_error(Robot::WrongLocation)
expect{ robot.place(5, 1, 'west') }.to raise_error(Robot::WrongLocation)
expect{ robot.place(1, 1, 'yolo') }.to raise_error(Robot::WrongLocation)
end
end
end
describe '#move' do
it 'moves on direction' do
robot.place(3, 0, 'east').move
expect(robot.x).to eq 4
end
it 'raises prevet from falling error' do
robot.place(4, 0, 'east')
expect{ robot.move }.to raise_error(Robot::PrevetFromFalling)
end
end
describe '#left' do
it 'turns left' do
robot.left
expect(robot.direction[:title]).to eq 'south'
robot.left
expect(robot.direction[:title]).to eq 'east' # for edge case
end
it 'raises out of table error' do
robot = Robot.new
expect{ robot.report }.to raise_error(Robot::OutOfTable)
end
end
describe '#right' do
it 'turns right' do
robot.place(1, 1, 'north')
robot.right
expect(robot.direction[:title]).to eq 'east'
robot.right
expect(robot.direction[:title]).to eq 'south' # also edge case
end
it 'raises out of table error' do
robot = Robot.new
expect{ robot.report }.to raise_error(Robot::OutOfTable)
end
end
describe '#report' do
it 'returns coordinates' do
expect(robot.report).to eq '1, 1, west'
end
it 'raises out of table error' do
robot = Robot.new
expect{ robot.report }.to raise_error(Robot::OutOfTable)
end
end
end
|
require "spec_helper"
RSpec.describe "Day 2: Inventory Management System" do
let(:runner) { Runner.new("2018/02") }
describe "Part One" do
let(:solution) { runner.execute!(input, part: 1) }
let(:input) do
<<~TXT
abcdef
bababc
abbcde
abcccd
aabcdd
abcdee
ababab
TXT
end
it "calculates a checksum" do
expect(solution).to eq 12
end
end
describe "Part Two" do
let(:solution) { runner.execute!(input, part: 2) }
let(:input) do
<<~TXT
abcde
fghij
klmno
pqrst
fguij
axcye
wvxyz
TXT
end
it "finds the common letters for the Box IDs" do
expect(solution).to eq "fgij"
end
end
end
|
class Event < ActiveRecord::Base
validates_presence_of :name
validates_numericality_of :budget, :greater_than => 0.0
has_many :expenses
has_many :vendors, :through => :expenses
def total_expenses
expenses.sum(:amount) || BigDecimal("0.0")
end
def budget_exceeded?
total_expenses > budget
end
def balance
budget - total_expenses
end
end
|
$pot = 0
def greeting
puts "SLOTS".center(80)
puts "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY".center(80)
puts "\n\n"
# PRODUCED BY FRED MIRABELLE AND BOB HARPER ON JAN 29, 1973
# IT SIMULATES THE SLOT MACHINE.
puts "You are in the H&M Casino, in front of one of our"
puts "one-arm bandits. You can bet from $1 to $100."
puts "To pull the arm, punch the return key after making your bet."
puts "\nBet zero to end the game."
end
def overLimit
puts "House Limit is $100"
end
def underMinimum
puts "Minimum Bet is $1"
end
# bells don't work on my machine. YMMV
# I'm displaying dashes between the reels
def tenBells
10.times do
# beep if you can
print "-"
end
end
def fiveBells
"-----"
end
def goodbye
puts "\n\n\n"
# end the game
exit
end
def payUp
puts "PAY UP! PLEASE LEAVE YOUR MONEY ON THE TERMINAL."
end
def brokeEven
puts "HEY, YOU BROKE EVEN."
end
def collectWinnings
puts "COLLECT YOUR WINNINGS FROM THE H&M CASHIER."
end
def win winType, bet
case winType
when "jackpot"
winMessage = "***JACKPOT***"
winnings = 101
when "topDollar"
winMessage = "**TOP DOLLAR**"
winnings = 11
when "doubleBar"
winMessage = "*DOUBLE BAR!!*"
winnings = 6
when "double"
winMessage = "DOUBLE!!"
winnings = 3
end
puts "\nYou won: " + winMessage
$pot += (winnings * bet)
end
greeting
#$pot = 0
while true
reelArray = ["BAR","BELL","ORANGE","LEMON","PLUM","CHERRY"]
print "\nYOUR BET? "
# get input, remove leading and trailing whitespace, cast to integer
bet = gets.strip.to_i
if bet == 0 then
goodbye
elsif bet > 100 then
overLimit # error if more than $100
elsif bet < 1 then
underMinimum # have to bet at least a dollar
else
# valid bet, continue
tenBells # ding
# assign a random value from the array to each of the three reels
reel1 = reelArray[rand(5)]
reel2 = reelArray[rand(5)]
reel3 = reelArray[rand(5)]
# print the slot machine reels
puts "\n\n" + reel1 + fiveBells + reel2 + fiveBells + reel3
# see if we have a match in the first two reels
if reel1 == reel2 then
if reel2 == reel3 then
if reel3 == "BAR" then
# all three reels are "BAR"
win "jackpot", bet
else
# all three reels match but aren't "BAR"
win "topDollar", bet
end
elsif reel2 == "BAR" then
# reels 1 and 2 are both "BAR"
win "doubleBar", bet
else
# reels 1 and 2 match but aren't "BAR"
win "double", bet
end
# otherwise see if there's a match in the remaining reels
elsif reel1 == reel3 or reel2 == reel3 then
if reel3 == "BAR" then
# two reels match, both "BAR"
win "doubleBar", bet
else
# two reels match, but not "BAR"
win "double", bet
end
else
# bad news - no matches
puts "\nYou lost"
# decrement your standings by the bet amount
$pot -= bet
end
puts "Your standings are: " + $pot.to_s
print "\nAgain? " # YES to continue
# get input, remove leading and trailing whitespace, make uppercase
again = gets.strip.upcase
if again != "Y" && again != "YES" then
# that's enough... evaluate the pot and quit
if $pot < 0 then
payUp
elsif $pot == 0 then
brokeEven
else # yay!
collectWinnings
end
goodbye
end
end
end
|
class GmailAPI
class AuthError < RuntimeError; end
def self.test
acc = { login: "", passwd: "" }
api = self.new(acc)
api.login
api.get_ads_for("the email id")
end
class CookieJar < Faraday::Middleware
def initialize(app)
super
@cookies = {}
end
def pprint_meta(env, type)
return if true
case type
when :request; color = :green; header = env[:request_headers]
when :response; color = :red; header = env[:response_headers]
end
puts
puts "request".send(color)
puts "url ".send(color) + env[:url].to_s
puts "verb ".send(color) + env[:method].to_s
puts env[:body].to_s if type == :request && env[:method] == :post
puts "headers ".send(color) + header.to_s
end
def call(env)
set_meta(env)
set_cookies(env)
pprint_meta(env, :request)
parse_cookies(env)
end
def cookies_for_host(env)
@cookies ||= {}
end
def set_meta(env)
env[:request_headers]['user-agent'] = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.132 Safari/537.36'
end
def set_cookies(env)
env[:request_headers]["cookie"] = cookies_for_host(env).map { |k,v| "#{k}=#{v}"}.join("; ")
end
def parse_cookies(env)
response = @app.call(env)
response.on_complete do |e|
pprint_meta(env, :response)
raw_array = (e[:response_headers]['set-cookie'] || "").split(",")
array = []
skip = false
raw_array.each do |item|
unless skip
array << item
end
if (item =~ /(Mon|Tue|Wed|Thu|Fri|Sat|Sun)$/)
skip = true
else
skip = false
end
end
cookies = array.select { |x| x =~ /=/ }.map { |x| x.split(';').first.strip.split('=', 2) }
cookies_for_host(e).merge!(Hash[cookies])
end
response
end
Faraday.register_middleware :request, :cookie_jar => lambda { self }
end
attr_accessor :conn
def initialize(account)
@conn = Faraday.new do |faraday|
faraday.request :url_encoded
faraday.response :follow_redirects, :limit => 20
faraday.request :cookie_jar
faraday.adapter :net_http_persistent
end
account = account.attributes unless account.class.name == "Hash"
@acc = Hash[account.map { |k,v| [k.to_s, v] }]
end
def login
response = @conn.get "https://accounts.google.com/ServiceLogin"
raise "oops" if response.status != 200
n = Nokogiri::HTML(response.body)
galx = n.css('form input[name="GALX"]').attr('value').to_s
response = @conn.post "https://accounts.google.com/ServiceLoginAuth", {
"GALX" => galx,
"Email" => @acc['login'],
"Passwd" => @acc['passwd'],
"PersistentCookie" => "yes",
"signIn" => "Sign in",
}
raise AuthError if response.body =~ /incorrect/
return self
end
def hashify(data)
Hash[data.map { |v| [v[0], v[1..-1]] }]
end
def get_ads_for(mid)
r = @conn.get("https://mail.google.com/mail/?view=ad&th=#{mid}&search=inbox")
ads = ExecJS.eval "eval(#{r.body[6..-1].force_encoding('UTF-8')})"
ads = hashify(ads.first)
items = []
items.add ads['fb'][0][2] rescue nil
items.add ads['abc'][0][0] rescue nil
items.concat [*ads['ads'][0]] rescue nil
items.compact.map { |v| { :full_id => v[7],
:campaign_id => v[7].split('_')[0],
:name => v[0..2].join(" "),
:click => v[3],
:url => v[4]} }
rescue => e
puts "[GmailAPI] get_ads error"
raise e
end
end
|
require_relative 'steaminventory/game.rb'
require_relative 'steaminventory/tradingcard.rb'
class Steaminventory
VERSION = "1.0.0"
def initialize(profile_id)
@game = Game.new(profile_id)
@card = TradingCard.new(profile_id)
end
def get_game_hash
return @game.return_hash
end
def get_card_hash
return @card.return_hash
end
def get_games
return @game.return_games
end
def get_cards
return @card.get_cards
end
def get_game_info(game_name)
return @game.get_game_info(game_name)
end
def get_card_info(card_name)
return @card.get_card_info(card_name)
end
end
|
require_relative '../../../../spec_helper'
describe 'govuk_harden::sysctl::conf', :type => :define do
let(:title) { 'zebra' }
let(:pre_condition) { 'File <| tag == "govuk_harden::sysctl::conf" |>' }
context 'source param' do
let(:params) {{ :source => 'puppet:///llama' }}
it { is_expected.to contain_file('/etc/sysctl.d/70-zebra.conf').with(
:source => 'puppet:///llama',
:content => nil,
)}
end
context 'content param' do
let(:params) {{ :content => 'llama' }}
it { is_expected.to contain_file('/etc/sysctl.d/70-zebra.conf').with(
:source => nil,
:content => 'llama',
)}
end
context 'prefix => 10' do
let(:params) {{ :prefix => '10', :content => 'llama' }}
it { is_expected.to contain_file('/etc/sysctl.d/10-zebra.conf') }
end
end
|
# 问题:
# 一只青蛙一次可以跳上1级台阶,也可以跳上2级台阶。求该青蛙跳上一个n级台阶总共有多少种跳法。
#
# 一、构造状态转移方程:
#
# 题目中没有给粟子,我们可以自己举点例子。
#
# 例如:跳上一个6级台阶,有多少种跳法;由于青蛙一次可以跳两阶,也可以跳一阶,所以我们可以分成两个情况:
# 1、青蛙最后一次跳了两阶,问题变成了“跳上一个4级台阶台阶,有多少种跳法”
# 2、青蛙最后一次跳了一阶,问题变成了“跳上一个5级台阶台阶,有多少种跳法”
# 由上可得:
# f(6) = f(5) + f(4);
# f(5) = f(4) + f(3);
#
# 由此类推:f(n)=f(n-1)+f(n-2)
#
#
# *推论:有多少种跳法,就算几种求和,如果是每次可以跳1,2,3级,那么对应公式就是:
# f(n)=f(n-1)+f(n-2)+f(n-3)
def frog_jump stairs_number
return 0 if stairs_number <= 0
return 1 if stairs_number.eql? 1
return 2 if stairs_number.eql? 2
jump_ways = []
jump_ways[1] = 1
jump_ways[2] = 2
(3..stairs_number).each do | stair_index |
jump_ways[stair_index] = jump_ways[stair_index-1] + jump_ways[stair_index-2]
end
return jump_ways[stairs_number]
end
while true do
p '请给定台阶数(Q/q退出): '
input = gets.strip
break if('q' == input.to_s || 'Q' == input.to_s)
puts "\e[32m#{input}\e[0m 级台阶,青蛙每次跳1、2级,共有 \e[32m#{frog_jump(input.to_i)}\e[0m 跳法"
puts '--------------------------------------------------------------------'
end
|
class CreateJobs < ActiveRecord::Migration
def change
create_table :jobs do |t|
t.string :title
t.integer :angellist_job_id
t.string :job_type
t.string :location
t.string :role
t.integer :salary_min
t.integer :salary_max
t.string :currency_code
t.decimal :equity_min
t.decimal :equity_max
t.decimal :equity_cliff
t.decimal :equity_vest
t.boolean :remote_ok, default: false
t.string :tags, array: true, default: []
t.references :company, index: true
t.timestamps null: false
end
add_foreign_key :jobs, :companies
end
end
|
# The variable below will be randomly assigned as true or false. Write a method named time_of_day that, given a boolean as an argument, prints "It's daytime!" if the boolean is true and "It's nighttime!" if it's false. Pass daylight into the method as the argument to determine whether it's day or night.
daylight = [true, false].sample
def time_of_day(daylight)
puts daylight ? "It's daylight!" : "It's nighttime!"
end
time_of_day(daylight)
|
# == Schema Information
#
# Table name: dictionaries
#
# id :integer not null, primary key
# name :string(255)
# tag :string(255)
# ancestry :string(255)
# created_at :datetime not null
# updated_at :datetime not null
# names_depth_cache :string(255)
# organization_id :integer
# dictionary_id :integer
#
require 'spec_helper'
describe Dictionary do
context 'new Dictionary' do
it 'should be have cache_ancestry on save' do
parent = FactoryGirl.create :dictionary, name: 'Parent'
child = FactoryGirl.build :dictionary, parent: parent
child.save
child.names_depth_cache.should match(parent.name)
end
end
end
|
module Accounts
class Withdraw
def self.call(account, value)
account.withdraw_balance(value)
Transaction.new(
sender_id: account.id,
receiver_id: account.id,
t_type: 'Withdrawal',
value: value
)
end
end
end
|
FactoryBot.define do
factory :experience do
place { Faker::Company.name }
title { Faker::Job.title }
description { Faker::Lorem.paragraph }
start_date { Faker::Date.between 10.years.ago, Time.zone.today }
end_date { Faker::Date.between start_date, Time.zone.today }
applicant
end
end
|
require "spec_helper"
describe ShowRundown do
describe "associations" do
it { should belong_to(:episode).class_name("ShowEpisode") }
it { should belong_to(:segment).class_name("ShowSegment") }
end
describe "check_position" do
it "only runs if position is blank" do
rundown = create :show_rundown, position: 20
rundown.position.should eq 20
end
it "sets a segment order if none is specified" do
rundown = build :show_rundown
rundown.position.should be_blank
rundown.save
rundown.position.should_not be_blank
end
it "sets the segment order to 1 if it is the first segment" do
rundown = create :show_rundown
rundown.position.should eq 1
end
it "increases the last position by 1 if other segments exist" do
episode = create :show_episode
rundown = create :show_rundown, episode: episode, position: 5
rundown2 = create :show_rundown, episode: episode
rundown2.position.should eq 6
end
end
end
|
module Issues
class AssignIssueFollowers
prepend SimpleCommand
attr_reader :current_user,
:args,
:id,
:followers
def initialize(current_user, args)
@id = args[:id]
@users = args[:users]
end
def call
return nil unless (valid_user? && valid_data?)
issue = Issues::Issue.find(@id)
issue.followers = @users.uniq
issue.save!
issue
end
def valid_user?
true
end
def valid_data?
true
end
end
end
|
class WelcomeController < ApplicationController
NAMES = ["engineer world-class web-readiness", "unleash impactful platforms", "generate visionary synergies",
"mesh cross-media interfaces", "morph value-added communities", "integrate scalable vortals",
"optimize open-source systems", "incubate back-end content"]
def index
@projects = NAMES.map.with_index do |name, index|
start_time = ((NAMES.length / 2) - index).weeks.ago
length_of_project_in_days = rand(7 * 4) + 1
end_time = start_time + length_of_project_in_days.days
puts "%s => %s : %s" % [start_time, end_time, name]
Project.new(name: name,
start_time: start_time,
end_time: end_time)
end
end
end
|
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'urbanairship/version'
require 'rake'
Gem::Specification.new do |spec|
spec.name = "urbanairship_v3"
spec.version = Urbanairship::VERSION
spec.authors = ["Kenneth Lim"]
spec.email = ["kennethlimjf@gmail.com"]
spec.summary = %q{Ruby binding for Urbanairship}
spec.description = %q{Ruby binding for Urbanairship}
spec.homepage = ""
spec.license = "MIT"
spec.files = FileList['README.md', 'LICENSE.txt', 'Rakefile', 'lib/**/*.rb'].to_a
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.7"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rspec", "~> 2.99"
spec.add_development_dependency "pry", "~> 0.10"
end
|
require 'nokogiri'
require 'date'
module RiksbankCurrency
class Fetcher
# @param [Date] date
# @param [String] base currency
def initialize(date, base)
@date = date
@base = base.to_s
end
# Convert XML response to Hash and recalculate it by @base currency
# Example:
# {
# "EUR": 9.021,
# "USD": 7.65
# }
# @return [Hash]
def to_hash
rates = fetcher.to_hash
rates['SEK'] = 1.0
recombine_by_base(rates)
end
# Define correct rate fetcher
# @return [TodayFetcher,DateFetcher]
def fetcher
@fetcher ||=
if @date == Date.today
TodayFetcher.new
else
DateFetcher.new(@date)
end
end
# @return [Date]
def rate_date
fetcher.rate_date
end
protected
def recombine_by_base(rates)
if @base != 'SEK'
new_rates = {}
rates.each do |currency, value|
new_rates[currency] = rates[@base] / value
end
rates = new_rates
end
rates[@base] = 1.0
rates
end
end
end
|
xml.instruct!
xml.scenarios({:type => "array"}) do
for scenario in @scenarios
xml.scenario do
xml.id({:type => "integer"}, scenario.id)
xml.studentDebugAccess({:type => "boolean"}, scenario.student_debug_access)
xml.name({:type => "string"}, scenario.name)
xml.shortDescription({:type => "string"}, scenario.short_description)
xml.description({:type => "string"}, scenario.description)
end
end
end |
RSpec.describe Dabooks::Transaction do
subject do
Dabooks::Transaction.new(
date: Date.new(2018, 1, 2),
description: 'boo',
entries: entries
)
end
let(:entries) do
[
Dabooks::Entry.new(
account: Dabooks::Account["cash"],
amount: Dabooks::Amount[11],
),
Dabooks::Entry.new(
account: Dabooks::Account["bank"],
amount: Dabooks::Amount[-11],
)
]
end
it "is a value type" do
expect(subject).to have_attributes(
date: Date.new(2018, 1, 2),
description: 'boo',
entries: entries,
)
end
it "balances entries" do
expect(subject.balance).to be_zero
expect(subject).to be_balanced
end
it "is fixed if all entries are fixed" do
expect(subject).to be_fixed
end
context "with an unfixed entry" do
let(:entries) do
[
Dabooks::Entry.new(
account: Dabooks::Account["cash"],
amount: Dabooks::Amount[11],
),
Dabooks::Entry.new(
account: Dabooks::Account["bank"],
amount: Dabooks::Amount.unfixed,
)
]
end
it "is not fixed" do
is_expected.not_to be_fixed
end
it "can calcluate the fixed balance" do
is_expected.to have_attributes(fixed_balance: Dabooks::Amount[11])
end
it "can normalize unfixed entries" do
is_expected.to have_attributes(normalized_entries: [
entries.first,
entries.last.with(amount: Dabooks::Amount[-11]),
])
end
end
end
|
require 'rails_helper'
RSpec.describe User, type: :model do
describe 'attributes' do
it { expect(User.new).to respond_to(:name) }
it { expect(User.new).to respond_to(:email) }
it { expect(User.new).to respond_to(:country ) }
end
end
|
VAGRANTFILE_API_VERSION = "2"
build_path = "#{File.dirname(__FILE__)}"
project_root = build_path + '/../../../../'
require 'yaml'
require build_path + '/../src/vagrant.rb'
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
if File.exists?(project_root + 'devbox.yml') then
DevBox.configure(config, YAML::load(File.read(project_root + 'devbox.yml')))
else
puts "Unable to locate a devbox.yml file, use `devbox init` to create one."
end
end
|
class Comment < ActiveRecord::Base
belongs_to :reason
validates :message, presence: true
end
|
# Require monkey patches to standard libraries.
Dir.glob("lib/extensions/**/*.rb") do |file|
require_dependency File.expand_path(file)
end
|
class GDG::Aracaju::Barcode < GDG::Barcode
def name
"Barcode Aracaju #{date}"
end
end |
class AddCommuneToDiagnostiqueurs < ActiveRecord::Migration
def change
add_column :diagnostiqueurs, :commune, :string
end
end
|
class User < ActiveRecord::Base
validates :username, presence: true, uniqueness: true
validates :password, length: {minimum: 6}
has_many :locations
has_secure_password
end
|
class CreateCourseChangeRecords < ActiveRecord::Migration
def change
create_table :course_change_records do |t|
t.integer :course_id
t.integer :teacher_user_id
t.string :location
t.string :time_expression
t.string :semester_value
t.datetime :start_date
t.datetime :end_date
t.timestamps
end
end
end
|
require 'graph'
require 'path'
describe Path do
let(:graph) { Graph.new }
let(:node_1) { 'A' }
let(:node_2) { 'B' }
let(:node_3) { 'C' }
let(:edge_1_weight) { 1 }
before do
graph.add_node(node_1)
graph.add_node(node_2)
graph.add_edge(node_1, node_2, edge_1_weight)
end
describe '#distance' do
context 'when the path exists' do
subject { graph.build_path("#{node_1}#{node_2}") }
it 'should calculate the distance of the path' do
expect(subject.distance).to eq(edge_1_weight)
end
end
context 'when the path does not exist' do
subject { graph.build_path("#{node_1}#{node_3}") }
let(:no_path_warning) { 'NO SUCH ROUTE' }
it 'should return "NO SUCH ROUTE"' do
expect(subject.distance).to eq(no_path_warning)
end
end
end
end
|
module PUBG
class Player
class Season
class Data
class Attributes
class GameModeStats
require "pubg/player/season/data/stats"
def initialize(args)
@args = args
end
def solo
Stats.new(@args["solo"])
end
def duo
Stats.new(@args["duo"])
end
def squad
Stats.new(@args["squad"])
end
def solo_fpp
Stats.new(@args["solo-fpp"])
end
def duo_fpp
Stats.new(@args["duo-fpp"])
end
def squad_fpp
Stats.new(@args["squad-fpp"])
end
end
end
end
end
end
end |
require 'test_helper'
class WrappedErrorTest < Minitest::Spec
let(:cause) { StandardError.new("the message") }
let(:wrapped) do
SimpleJsonapi::Errors::WrappedError.new(
cause,
id: "the id",
status: "the status",
code: "the code",
title: "the title",
detail: "the detail",
source_pointer: "the source pointer",
source_parameter: "the source parameter",
about_link: "the about link",
)
end
describe SimpleJsonapi::Errors::WrappedError do
describe "cause" do
it "defaults to nil" do
assert_nil SimpleJsonapi::Errors::WrappedError.new.cause
end
it "is stored" do
assert_equal cause, wrapped.cause
end
end
describe "other properties" do
it "are stored" do
assert_equal "the id", wrapped.id
assert_equal "the status", wrapped.status
assert_equal "the code", wrapped.code
assert_equal "the title", wrapped.title
assert_equal "the detail", wrapped.detail
assert_equal "the source pointer", wrapped.source_pointer
assert_equal "the source parameter", wrapped.source_parameter
assert_equal "the about link", wrapped.about_link
end
end
end
end
|
class ProLang < ApplicationRecord
belongs_to :production
belongs_to :language
validates :production_id, presence:true
validates :language_id, presence:true
end
|
require 'spec_helper'
describe "polymorphic associations" do
#
# has_moderated_association
# has_many polymorphic
#
context "has_many polymorphic association:" do
before do
dynamic_models.task {
has_many :renamed_subtasks, :class_name => "Subtask", :as => :parentable
has_moderated_association :renamed_subtasks
}.subtask {
belongs_to :parentable, :polymorphic => true
}
end
it "creates and associates subtask (create)" do
task = Task.create! :title => "Task 1"
Moderation.count.should eq(0)
task.renamed_subtasks.create! :title => "Subtask 1"
task = Task.first
task.renamed_subtasks.count.should eq(0)
Moderation.count.should eq(1)
Moderation.last.accept
Moderation.count.should eq(0)
subtask = Task.first.renamed_subtasks.first
subtask.title.should eq("Subtask 1")
subtask.parentable.should eq(Task.first)
end
end
#
# has_moderated_association
# has_one polymorphic
#
context "has_one polymorphic association:" do
before do
dynamic_models.task {
has_one :renamed_subtask, :class_name => "Subtask", :as => :parentable
has_moderated_association :renamed_subtask
}.subtask {
belongs_to :parentable, :polymorphic => true
}
end
it "creates and associates subtask (create)" do
task = Task.create! :title => "Task 1"
Moderation.count.should eq(0)
task.renamed_subtask = Subtask.new :title => "Subtask 1"
task.save
task = Task.first
task.renamed_subtask.should be_nil
Moderation.count.should eq(1)
Moderation.last.accept
Moderation.count.should eq(0)
subtask = Task.first.renamed_subtask
subtask.title.should eq("Subtask 1")
subtask.parentable.should eq(Task.first)
end
end
end |
require 'rubygems'
require 'bundler/setup'
if ENV['COVERALL']
require 'coveralls'
Coveralls.wear!
end
TEST_ENCODINGS = Encoding.name_list.each_with_object(['UTF-8']) do |encoding, result|
test_string = '<script>'.encode(Encoding::UTF_8)
string = begin
test_string.encode(encoding)
rescue
nil
end
result << encoding if !string.nil? && string != test_string
end
def stub_stdout_constant # rubocop:disable Metrics/MethodLength
begin_block = <<-BLOCK
original_verbosity = $VERBOSE
$VERBOSE = nil
origin_stdout = STDOUT
STDOUT = StringIO.new
BLOCK
TOPLEVEL_BINDING.eval begin_block
yield
return_str = STDOUT.string
ensure_block = <<-BLOCK
STDOUT = origin_stdout
$VERBOSE = original_verbosity
BLOCK
TOPLEVEL_BINDING.eval ensure_block
return_str
end
def stub_time_now
Time.stub :now, Time.utc(1988, 9, 1, 0, 0, 0) do
yield
end
end
require 'minitest/autorun'
$LOAD_PATH.unshift 'lib'
require_relative './fixtures'
|
# Keep asking user for input and add their input to an array until they type "exit".
# After that print out the number of input they've entered. For example print:
# You've entered 10 inputs
array = []
input = ""
until input == "exit"
print "Hit me (or 'exit' to give up): "
input = gets.chomp.strip
array << input unless input.empty? || input.nil? || input == "exit"
end
puts "You've entered #{array.count} inputs."
|
# Copyright (c) 2009-2011 VMware, Inc.
$:.unshift(File.dirname(__FILE__))
require 'spec_helper'
require 'mysql_service/node'
require 'mysql_service/mysql_error'
require 'mysql2'
require 'yajl'
require 'fileutils'
module VCAP
module Services
module Mysql
class Node
attr_reader :pool, :logger, :capacity, :provision_served, :binding_served
end
end
end
end
module VCAP
module Services
module Mysql
class MysqlError
attr_reader :error_code
end
end
end
end
describe "Mysql server node" do
include VCAP::Services::Mysql
before :all do
@opts = getNodeTestConfig
@opts.freeze
# Setup code must be wrapped in EM.run
EM.run do
@node = VCAP::Services::Mysql::Node.new(@opts)
EM.add_timer(1) { EM.stop }
end
@tmpfiles = []
end
before :each do
@default_plan = "free"
@default_opts = "default"
@test_dbs = {}# for cleanup
# Create one db be default
@db = @node.provision(@default_plan)
@db.should_not == nil
@db["name"].should be
@db["host"].should be
@db["host"].should == @db["hostname"]
@db["port"].should be
@db["user"].should == @db["username"]
@db["password"].should be
@test_dbs[@db] = []
end
it "should connect to mysql database" do
EM.run do
expect {@node.pool.with_connection{|connection| connection.query("SELECT 1")}}.should_not raise_error
EM.stop
end
end
it "should report inconsistency between mysql and local db" do
EM.run do
name, user = @db["name"], @db["user"]
@node.pool.with_connection do |conn|
conn.query("delete from db where db='#{name}' and user='#{user}'")
end
result = @node.check_db_consistency
result.include?([name, user]).should == true
EM.stop
end
end
it "should provison a database with correct credential" do
EM.run do
@db.should be_instance_of Hash
conn = connect_to_mysql(@db)
expect {conn.query("SELECT 1")}.should_not raise_error
EM.stop
end
end
it "should calculate both table and index as database size" do
EM.run do
conn = connect_to_mysql(@db)
# should calculate table size
conn.query("CREATE TABLE test(id INT)")
conn.query("INSERT INTO test VALUE(10)")
conn.query("INSERT INTO test VALUE(20)")
table_size = @node.dbs_size(conn)[@db["name"]]
table_size.should > 0
# should also calculate index size
conn.query("CREATE INDEX id_index on test(id)")
all_size = @node.dbs_size(conn)[@db["name"]]
all_size.should > table_size
EM.stop
end
end
it "should enforce database size quota" do
EM.run do
opts = @opts.dup
# reduce storage quota to 20KB, default mysql allocates pages of 16kb, so inserting anything will allocate at least 16k
opts[:max_db_size] = 20.0/1024
node = VCAP::Services::Mysql::Node.new(opts)
EM.add_timer(1) do
binding = node.bind(@db["name"], @default_opts)
@test_dbs[@db] << binding
conn = connect_to_mysql(binding)
conn.query("create table test(data text)")
c = [('a'..'z'),('A'..'Z')].map{|i| Array(i)}.flatten
content = (0..21000).map{ c[rand(c.size)] }.join # enough data to exceed quota for sure
conn.query("insert into test value('#{content}')")
EM.add_timer(3) do
expect {conn.query('SELECT 1')}.should raise_error
conn.close
conn = connect_to_mysql(binding)
# write privilege should be rovoked.
expect{ conn.query("insert into test value('test')")}.should raise_error(Mysql2::Error)
conn = connect_to_mysql(@db)
expect{ conn.query("insert into test value('test')")}.should raise_error(Mysql2::Error)
# new binding's write privilege should also be revoked.
new_binding = node.bind(@db['name'], @default_opts)
@test_dbs[@db] << new_binding
new_conn = connect_to_mysql(new_binding)
expect { new_conn.query("insert into test value('new_test')")}.should raise_error(Mysql2::Error)
EM.add_timer(3) do
expect {conn.query('SELECT 1')}.should raise_error
conn.close
conn = connect_to_mysql(binding)
conn.query("delete from test")
# write privilege should restore
EM.add_timer(5) do # we need at least 5s for information_schema tables to update with new data_length
conn = connect_to_mysql(binding)
expect{ conn.query("insert into test value('test')")}.should_not raise_error
conn.query("insert into test value('#{content}')")
EM.add_timer(3) do
expect { conn.query('SELECT 1') }.should raise_error
conn.close
conn = connect_to_mysql(binding)
expect{ conn.query("insert into test value('test')") }.should raise_error(Mysql2::Error)
conn.query("drop table test")
EM.add_timer(2) do
conn = connect_to_mysql(binding)
expect { conn.query("create table test(data text)") }.should_not raise_error
expect { conn.query("insert into test value('test')") }.should_not raise_error
EM.stop
end
end
end
end
end
end
end
end
it "should able to handle orphan instances when enforce storage quota." do
begin
# forge an orphan instance, which is not exist in mysql
klass = VCAP::Services::Mysql::Node::ProvisionedService
DataMapper.setup(:default, @opts[:local_db])
DataMapper::auto_upgrade!
service = klass.new
service.name = 'test-'+ UUIDTools::UUID.random_create.to_s
service.user = "test"
service.password = "test"
service.plan = 1
if not service.save
raise "Failed to forge orphan instance: #{service.errors.inspect}"
end
EM.run do
expect { @node.enforce_storage_quota }.should_not raise_error
EM.stop
end
ensure
service.destroy
end
end
it "should return correct instances & binding list" do
EM.run do
before_ins_list = @node.all_instances_list
plan = "free"
tmp_db = @node.provision(plan)
@test_dbs[tmp_db] = []
after_ins_list = @node.all_instances_list
before_ins_list << tmp_db["name"]
(before_ins_list.sort == after_ins_list.sort).should be_true
before_bind_list = @node.all_bindings_list
tmp_credential = @node.bind(tmp_db["name"], @default_opts)
@test_dbs[tmp_db] << tmp_credential
after_bind_list = @node.all_bindings_list
before_bind_list << tmp_credential
a,b = [after_bind_list,before_bind_list].map do |list|
list.map{|item| item["username"]}.sort
end
(a == b).should be_true
EM.stop
end
end
it "should not create db or send response if receive a malformed request" do
EM.run do
@node.pool.with_connection do |connection|
db_num = connection.query("show databases;").count
mal_plan = "not-a-plan"
db = nil
expect {
db = @node.provision(mal_plan)
}.should raise_error(VCAP::Services::Mysql::MysqlError, /Invalid plan .*/)
db.should == nil
db_num.should == connection.query("show databases;").count
end
EM.stop
end
end
it "should support over provisioning" do
EM.run do
opts = @opts.dup
opts[:capacity] = 10
opts[:max_db_size] = 20
node = VCAP::Services::Mysql::Node.new(opts)
EM.add_timer(1) do
expect {
db = node.provision(@default_plan)
@test_dbs[db] = []
}.should_not raise_error
EM.stop
end
end
end
it "should not allow old credential to connect if service is unprovisioned" do
EM.run do
conn = connect_to_mysql(@db)
expect {conn.query("SELECT 1")}.should_not raise_error
msg = Yajl::Encoder.encode(@db)
@node.unprovision(@db["name"], [])
expect {connect_to_mysql(@db)}.should raise_error
error = nil
EM.stop
end
end
it "should return proper error if unprovision a not existing instance" do
EM.run do
expect {
@node.unprovision("not-existing", [])
}.should raise_error(VCAP::Services::Mysql::MysqlError, /Mysql configuration .* not found/)
# nil input handle
@node.unprovision(nil, []).should == nil
EM.stop
end
end
it "should not be possible to access one database using null or wrong credential" do
EM.run do
plan = "free"
db2 = @node.provision(plan)
@test_dbs[db2] = []
fake_creds = []
3.times {fake_creds << @db.clone}
# try to login other's db
fake_creds[0]["name"] = db2["name"]
# try to login using null credential
fake_creds[1]["password"] = nil
# try to login using root account
fake_creds[2]["user"] = "root"
fake_creds.each do |creds|
expect{connect_to_mysql(creds)}.should raise_error
end
EM.stop
end
end
it "should kill long transaction" do
if @opts[:max_long_tx] > 0 and (@node.check_innodb_plugin)
EM.run do
opts = @opts.dup
# reduce max_long_tx to accelerate test
opts[:max_long_tx] = 1
node = VCAP::Services::Mysql::Node.new(opts)
EM.add_timer(1) do
conn = connect_to_mysql(@db)
# prepare a transaction and not commit
conn.query("create table a(id int) engine=innodb")
conn.query("insert into a value(10)")
conn.query("begin")
conn.query("select * from a for update")
old_killed = node.varz_details[:long_transactions_killed]
EM.add_timer(opts[:max_long_tx] * 5) {
expect {conn.query("select * from a for update")}.should raise_error(Mysql2::Error)
conn.close
node.varz_details[:long_transactions_killed].should > old_killed
node.instance_variable_set(:@kill_long_tx, false)
conn = connect_to_mysql(@db)
# prepare a transaction and not commit
conn.query("begin")
conn.query("select * from a for update")
old_counter = node.varz_details[:long_transactions_count]
EM.add_timer(opts[:max_long_tx] * 5) {
expect {conn.query("select * from a for update")}.should_not raise_error(Mysql2::Error)
node.varz_details[:long_transactions_count].should > old_counter
old_counter = node.varz_details[:long_transactions_count]
EM.add_timer(opts[:max_long_tx] * 5) {
#counter should not double-count the same long transaction
node.varz_details[:long_transactions_count].should == old_counter
conn.close
EM.stop
}
}
}
end
end
else
pending "long transaction killer is disabled."
end
end
it "should kill long queries" do
pending "Disable for non-Percona server since the test behavior varies on regular Mysql server." unless @node.is_percona_server?
EM.run do
db = @node.provision(@default_plan)
@test_dbs[db] = []
opts = @opts.dup
opts[:max_long_query] = 1
conn = connect_to_mysql(db)
node = VCAP::Services::Mysql::Node.new(opts)
EM.add_timer(1) do
conn.query('create table test(id INT) engine innodb')
conn.query('insert into test value(10)')
conn.query('begin')
# lock table test
conn.query('select * from test where id = 10 for update')
old_counter = node.varz_details[:long_queries_killed]
conn2 = connect_to_mysql(db)
err = nil
t = Thread.new do
begin
# conn2 is blocked by conn, we use lock to simulate long queries
conn2.query("select * from test for update")
rescue => e
err = e
ensure
conn2.close
end
end
EM.add_timer(opts[:max_long_query] * 5){
err.should_not == nil
err.message.should =~ /interrupted/
# counter should also be updated
node.varz_details[:long_queries_killed].should > old_counter
EM.stop
}
end
end
end
it "should create a new credential when binding" do
EM.run do
binding = @node.bind(@db["name"], @default_opts)
binding["name"].should == @db["name"]
binding["host"].should be
binding["host"].should == binding["hostname"]
binding["port"].should be
binding["user"].should == binding["username"]
binding["password"].should be
@test_dbs[@db] << binding
conn = connect_to_mysql(binding)
expect {conn.query("Select 1")}.should_not raise_error
EM.stop
end
end
it "should supply different credentials when binding evoked with the same input" do
EM.run do
binding = @node.bind(@db["name"], @default_opts)
binding2 = @node.bind(@db["name"], @default_opts)
@test_dbs[@db] << binding
@test_dbs[@db] << binding2
binding.should_not == binding2
EM.stop
end
end
it "should delete credential after unbinding" do
EM.run do
binding = @node.bind(@db["name"], @default_opts)
@test_dbs[@db] << binding
conn = nil
expect {conn = connect_to_mysql(binding)}.should_not raise_error
res = @node.unbind(binding)
res.should be true
expect {connect_to_mysql(binding)}.should raise_error
# old session should be killed
expect {conn.query("SELECT 1")}.should raise_error(Mysql2::Error)
EM.stop
end
end
it "should not delete user in credential when unbind 'ancient' instances" do
EM.run do
# Crafting an ancient binding credential which is the same as provision credential
ancient_binding = @db.dup
expect { connect_to_mysql(ancient_binding) }.should_not raise_error
@node.unbind(ancient_binding)
# ancient_binding is still valid after unbind
expect { connect_to_mysql(ancient_binding) }.should_not raise_error
EM.stop
end
end
it "should delete all bindings if service is unprovisioned" do
EM.run do
@default_opts = "default"
bindings = []
3.times { bindings << @node.bind(@db["name"], @default_opts)}
@test_dbs[@db] = bindings
conn = nil
@node.unprovision(@db["name"], bindings)
bindings.each { |binding| expect {connect_to_mysql(binding)}.should raise_error }
EM.stop
end
end
it "should able to restore database from backup file" do
EM.run do
db = @node.provision(@default_plan)
@test_dbs[db] = []
conn = connect_to_mysql(db)
conn.query("create table test(id INT)")
conn.query("create procedure defaultfunc(out defaultcount int) begin select count(*) into defaultcount from test; end")
binding = @node.bind(db['name'], @default_opts)
new_binding = @node.bind(db['name'], @default_opts)
@test_dbs[db] << binding
@test_dbs[db] << new_binding
# create stored procedure
bind_conn = connect_to_mysql(binding)
new_bind_conn = connect_to_mysql(new_binding)
bind_conn.query("create procedure myfunc(out mycount int) begin select count(*) into mycount from test ; end")
bind_conn.query("create procedure myfunc2(out mycount int) SQL SECURITY invoker begin select count(*) into mycount from test;end")
new_bind_conn.query("create procedure myfunc3(out mycount int) begin select count(*) into mycount from test; end")
new_bind_conn.close if new_bind_conn
@node.unbind(new_binding)
conn.query("call defaultfunc(@testcount)")
conn.query("select @testcount")
conn.query("call myfunc(@testcount)")
conn.query("select @testcount")
conn.query("call myfunc2(@testcount)")
conn.query("select @testcount")
conn.query("call myfunc3(@testcount)")
conn.query("select @testcount")
bind_conn.query("call defaultfunc(@testcount)")
bind_conn.query("select @testcount")
bind_conn.query("call myfunc(@testcount)")
bind_conn.query("select @testcount")
bind_conn.query("call myfunc2(@testcount)")
bind_conn.query("select @testcount")
bind_conn.query("call myfunc3(@testcount)")
bind_conn.query("select @testcount")
# backup current db
host, port, user, password = %w(host port user pass).map{|key| @opts[:mysql][key]}
tmp_file = "/tmp/#{db['name']}.sql.gz"
@tmpfiles << tmp_file
result = `mysqldump -h #{host} -P #{port} --user='#{user}' --password='#{password}' -R #{db['name']} | gzip > #{tmp_file}`
bind_conn.query("drop procedure myfunc")
conn.query("drop table test")
res = bind_conn.query("show procedure status")
res.count().should == 3
res = conn.query("show tables")
res.count.should == 0
# create a new table which should be deleted after restore
conn.query("create table test2(id int)")
bind_conn.close if bind_conn
conn.close if conn
@node.unbind(binding)
@node.restore(db["name"], "/tmp/").should == true
conn = connect_to_mysql(db)
res = conn.query("show tables")
res.count().should == 1
res.first["Tables_in_#{db['name']}"].should == "test"
res = conn.query("show procedure status")
res.count().should == 4
expect do
conn.query("call defaultfunc(@testcount)")
conn.query("select @testcount")
end.should_not raise_error
expect do
conn.query("call myfunc(@testcount)")
conn.query("select @testcount")
end.should_not raise_error # secuirty type should be invoker or a error will be raised.
expect do
conn.query("call myfunc2(@testcount)")
conn.query("select @testcount")
end.should_not raise_error
expect do
conn.query("call myfunc3(@testcount)")
conn.query("select @testcount")
end.should_not raise_error
EM.stop
end
end
it "should be able to disable an instance" do
EM.run do
bind_cred = @node.bind(@db["name"], @default_opts)
conn = connect_to_mysql(bind_cred)
@test_dbs[@db] << bind_cred
@node.disable_instance(@db, [bind_cred])
# kill existing session
expect { conn.query('SELECT 1')}.should raise_error
expect { conn2.query('SELECT 1')}.should raise_error
# delete user
expect { connect_to_mysql(bind_cred)}.should raise_error
EM.stop
end
end
it "should able to dump instance content to file" do
EM.run do
conn = connect_to_mysql(@db)
conn.query('create table MyTestTable(id int)')
@node.dump_instance(@db, nil, '/tmp').should == true
File.open(File.join("/tmp", "#{@db['name']}.sql")) do |f|
line = f.each_line.find {|line| line =~ /MyTestTable/}
line.should_not be nil
end
@tmpfiles << File.join("/tmp", "#{@db['name']}.sql")
EM.stop
end
end
it "should recreate database and user when import instance" do
EM.run do
db = @node.provision(@default_plan)
@test_dbs[db] = []
@node.dump_instance(db, nil , '/tmp')
@node.unprovision(db['name'], [])
@node.import_instance(db, {}, '/tmp', @default_plan).should == true
conn = connect_to_mysql(db)
expect { conn.query('SELECT 1')}.should_not raise_error
@tmpfiles << File.join("/tmp", "#{db['name']}.sql")
EM.stop
end
end
it "should recreate bindings when enable instance" do
EM.run do
db = @node.provision(@default_plan)
@test_dbs[db] = []
binding = @node.bind(db['name'], @default_opts)
@test_dbs[db] << binding
conn = connect_to_mysql(binding)
@node.disable_instance(db, [binding])
expect {conn = connect_to_mysql(binding)}.should raise_error
value = {
"fake_service_id" => {
"credentials" => binding,
"binding_options" => @default_opts,
}
}
@node.enable_instance(db, value).should be_true
expect {conn = connect_to_mysql(binding)}.should_not raise_error
EM.stop
end
end
it "should recreate bindings when update instance handles" do
EM.run do
db = @node.provision(@default_plan)
@test_dbs[db] = []
binding = @node.bind(db['name'], @default_opts)
@test_dbs[db] << binding
conn = connect_to_mysql(binding)
@node.disable_instance(db, [binding])
expect {conn = connect_to_mysql(binding)}.should raise_error
value = {
"fake_service_id" => {
"credentials" => binding,
"binding_options" => @default_opts,
}
}
result = @node.update_instance(db, value)
result.should be_instance_of Array
expect {conn = connect_to_mysql(binding)}.should_not raise_error
EM.stop
end
end
it "should retain instance data after node restart" do
EM.run do
node = VCAP::Services::Mysql::Node.new(@opts)
EM.add_timer(1) do
db = node.provision(@default_plan)
@test_dbs[db] = []
conn = connect_to_mysql(db)
conn.query('create table test(id int)')
# simulate we restart the node
node.shutdown
node = VCAP::Services::Mysql::Node.new(@opts)
EM.add_timer(1) do
conn2 = connect_to_mysql(db)
result = conn2.query('show tables')
result.count.should == 1
EM.stop
end
end
end
end
it "should able to generate varz." do
EM.run do
node = VCAP::Services::Mysql::Node.new(@opts)
EM.add_timer(1) do
varz = node.varz_details
varz.should be_instance_of Hash
varz[:queries_since_startup].should >0
varz[:queries_per_second].should >= 0
varz[:database_status].should be_instance_of Array
varz[:max_capacity].should > 0
varz[:available_capacity].should >= 0
varz[:long_queries_killed].should >= 0
varz[:long_transactions_killed].should >= 0
varz[:provision_served].should >= 0
varz[:binding_served].should >= 0
EM.stop
end
end
end
it "should handle Mysql error in varz" do
pending "This test is not capatiable with mysql2 conenction pool."
EM.run do
node = VCAP::Services::Mysql::Node.new(@opts)
EM.add_timer(1) do
# drop mysql connection
node.pool.close
varz = nil
expect {varz = node.varz_details}.should_not raise_error
varz.should == {}
EM.stop
end
end
end
it "should provide provision/binding served info in varz" do
EM.run do
v1 = @node.varz_details
db = @node.provision(@default_plan)
binding = @node.bind(db["name"], [])
@test_dbs[db] = [binding]
v2 = @node.varz_details
(v2[:provision_served] - v1[:provision_served]).should == 1
(v2[:binding_served] - v1[:binding_served]).should == 1
EM.stop
end
end
it "should report instance disk size in varz" do
EM.run do
v = @node.varz_details
instance = v[:database_status].find {|d| d[:name] == @db["name"]}
instance.should_not be_nil
instance[:size].should >= 0
EM.stop
end
end
it "should report node instance status in varz" do
pending "This test is not capatiable with mysql2 conenction pool."
EM.run do
varz = @node.varz_details
varz[:instances].each do |name, status|
status.shoud == "ok"
end
node = VCAP::Services::Mysql::Node.new(@opts)
EM.add_timer(1) do
node.pool.close
varz = node.varz_details
varz[:instances].each do |name, status|
status.should == "ok"
end
EM.stop
end
end
end
it "should report instance status in varz" do
EM.run do
varz = @node.varz_details()
instance = @db['name']
varz[:instances].each do |name, value|
if name == instance.to_sym
value.should == "ok"
end
end
@node.pool.with_connection do |connection|
connection.query("Drop database #{instance}")
sleep 1
varz = @node.varz_details()
varz[:instances].each do |name, value|
if name == instance.to_sym
value.should == "fail"
end
end
# restore db so cleanup code doesn't complain.
connection.query("create database #{instance}")
end
EM.stop
end
end
it "should be thread safe" do
EM.run do
provision_served = @node.provision_served
binding_served = @node.binding_served
# Set concurrent threads to pool size. Prevent pool is empty error.
NUM = @node.pool.size
threads = []
NUM.times do
threads << Thread.new do
db = @node.provision(@default_plan)
binding = @node.bind(db["name"], @default_opts)
@node.unprovision(db["name"], [binding])
end
end
threads.each {|t| t.join}
provision_served.should == @node.provision_served - NUM
binding_served.should == @node.binding_served - NUM
EM.stop
end
end
it "should enforce max connection limitation per user account" do
EM.run do
opts = @opts.dup
opts[:max_user_conns] = 1 # easy for testing
node = VCAP::Services::Mysql::Node.new(opts)
EM.add_timer(1) do
db = node.provision(@default_plan)
binding = node.bind(db["name"], @default_opts)
@test_dbs[db] = [binding]
expect { conn = connect_to_mysql(db) }.should_not raise_error
expect { conn = connect_to_mysql(binding) }.should_not raise_error
EM.stop
end
end
end
it "should add timeout option to all management mysql connection" do
EM.run do
opts = @opts.dup
origin_timeout = Mysql2::Client.default_timeout
timeout = 1
opts[:connection_wait_timeout] = timeout
node = VCAP::Services::Mysql::Node.new(opts)
EM.add_timer(2) do
begin
# server side timeout
node.pool.with_connection do |conn|
# simulate connection idle
sleep (timeout * 5)
expect{ conn.query("select 1") }.should raise_error(Mysql2::Error, /MySQL server has gone away/)
end
# client side timeout
node.pool.with_connection do |conn|
# override server side timeout
conn.query("set @@wait_timeout=10")
expect{ conn.query("select sleep(5)") }.should raise_error(Timeout::Error)
end
ensure
# restore original timeout
Mysql2::Client.default_timeout = origin_timeout
EM.stop
end
end
end
end
it "should works well if timeout is disabled for management mysql connection" do
EM.run do
opts = @opts.dup
origin_timeout = Mysql2::Client.default_timeout
opts.delete :connection_wait_timeout
node = VCAP::Services::Mysql::Node.new(opts)
EM.add_timer(2) do
begin
# server side timeout
node.pool.with_connection do |conn|
sleep (5)
expect{ conn.query("select 1") }.should_not raise_error
end
# client side timeout
node.pool.with_connection do |conn|
expect{ conn.query("select sleep(5)") }.should_not raise_error
end
ensure
# restore original timeout
Mysql2::Client.default_timeout = origin_timeout
EM.stop
end
end
end
end
after :each do
@test_dbs.keys.each do |db|
begin
name = db["name"]
@node.unprovision(name, @test_dbs[db])
@node.logger.info("Clean up temp database: #{name}")
rescue => e
@node.logger.info("Error during cleanup #{e}")
end
end if @test_dbs
end
after :all do
@tmpfiles.each do |tmpfile|
FileUtils.rm_r tmpfile
end
end
end
|
require File.dirname(__FILE__) + '/../spec_helper'
describe ComentariosController do
describe "route generation" do
it "should map { :controller => 'comentarios', :action => 'index' } to /comentarios" do
route_for(:controller => "comentarios", :action => "index").should == "/comentarios"
end
it "should map { :controller => 'comentarios', :action => 'new' } to /comentarios/new" do
route_for(:controller => "comentarios", :action => "new").should == "/comentarios/new"
end
it "should map { :controller => 'comentarios', :action => 'show', :id => 1 } to /comentarios/1" do
route_for(:controller => "comentarios", :action => "show", :id => 1).should == "/comentarios/1"
end
it "should map { :controller => 'comentarios', :action => 'edit', :id => 1 } to /comentarios/1/edit" do
route_for(:controller => "comentarios", :action => "edit", :id => 1).should == "/comentarios/1/edit"
end
it "should map { :controller => 'comentarios', :action => 'update', :id => 1} to /comentarios/1" do
route_for(:controller => "comentarios", :action => "update", :id => 1).should == "/comentarios/1"
end
it "should map { :controller => 'comentarios', :action => 'destroy', :id => 1} to /comentarios/1" do
route_for(:controller => "comentarios", :action => "destroy", :id => 1).should == "/comentarios/1"
end
end
describe "route recognition" do
it "should generate params { :controller => 'comentarios', action => 'index' } from GET /comentarios" do
params_from(:get, "/comentarios").should == {:controller => "comentarios", :action => "index"}
end
it "should generate params { :controller => 'comentarios', action => 'new' } from GET /comentarios/new" do
params_from(:get, "/comentarios/new").should == {:controller => "comentarios", :action => "new"}
end
it "should generate params { :controller => 'comentarios', action => 'create' } from POST /comentarios" do
params_from(:post, "/comentarios").should == {:controller => "comentarios", :action => "create"}
end
it "should generate params { :controller => 'comentarios', action => 'show', id => '1' } from GET /comentarios/1" do
params_from(:get, "/comentarios/1").should == {:controller => "comentarios", :action => "show", :id => "1"}
end
it "should generate params { :controller => 'comentarios', action => 'edit', id => '1' } from GET /comentarios/1;edit" do
params_from(:get, "/comentarios/1/edit").should == {:controller => "comentarios", :action => "edit", :id => "1"}
end
it "should generate params { :controller => 'comentarios', action => 'update', id => '1' } from PUT /comentarios/1" do
params_from(:put, "/comentarios/1").should == {:controller => "comentarios", :action => "update", :id => "1"}
end
it "should generate params { :controller => 'comentarios', action => 'destroy', id => '1' } from DELETE /comentarios/1" do
params_from(:delete, "/comentarios/1").should == {:controller => "comentarios", :action => "destroy", :id => "1"}
end
end
end |
describe package('ansible') do
it { should be_installed }
end |
class ChangeGoalSoundNameFromStringToEnum < ActiveRecord::Migration
def change
remove_column :goals, :sound_name
add_column :goals, :sound_name, :integer, default: 0
end
end
|
class UploadedFilesController < ApplicationController
def file_upload
# FIX IE
if request.headers["HTTP_ACCEPT"].split(",").map(&:strip).include?("application/json")
content_type = "application/json"
else
content_type = "text/plain"
end
uploaded_file = UploadedFile.new(file: params[:files][0])
if uploaded_file.save
render json: {
files: [
{
"name" => uploaded_file.read_attribute(:file_file_name),
"size" => uploaded_file.read_attribute(:file_file_size),
"url" => uploaded_file.file.url,
"id" => uploaded_file.id
}
]
}, content_type: content_type
else
render json: {
error: {
"message" => "An error prevents the uploaded file to be saved"
}
}, content_type: content_type
end
end
end
|
# frozen_string_literal: true
require "hanami"
module Hanamimastery
# Handles HTTP requests.
class App < Hanami::App
config.actions.content_security_policy[:script_src] = "https://unpkg.com"
config.shared_app_component_keys += ["mailers.contact_mailer"]
end
end
|
require File.expand_path("../test_helper", __FILE__)
class HelloWorldTest < ProxyTest::TestCase
def test_it_says_hello_world
# Returns the real objects from the transaction
res, req = expect :get, "/hello" do |response, request|
# Modify the request inline
request["X-Someotherheader"] = "thing"
# Modify the response inline
response.body = "body goes here"
response["X-Someheader"] = "value"
end
# Assertions about response go here
#
assert_equal res.body, "body goes here"
assert_equal res["X-SOMEHEADER"], "value"
assert_equal req.env["REQUEST_METHOD"], "GET"
assert_equal req.env["X-SOMEOTHERHEADER"], "thing"
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.