text stringlengths 10 2.61M |
|---|
# == Schema Information
#
# Table name: profiles
#
# id :integer not null, primary key
# user_id :integer
# created_at :datetime not null
# updated_at :datetime not null
# first_name :string
# last_name :string
# date_of_birth :datetime
# gender :integer
# avatar_id :integer
#
# Indexes
#
# index_profiles_on_avatar_id (avatar_id)
# index_profiles_on_first_name (first_name)
# index_profiles_on_gender (gender)
# index_profiles_on_last_name (last_name)
# index_profiles_on_user_id (user_id) UNIQUE
#
class Profile < ApplicationRecord
include TranslateEnum
include PgSearch
belongs_to :user, optional: true
enum gender: { not_shown: 0, male: 1, female: 2 }
translate_enum :gender
validates :first_name, :last_name, presence: true, length: { minimum: 2, maximum: 30 }
validates :gender, :date_of_birth, presence: true
has_many :albums
has_many :photos, through: :albums
belongs_to :avatar, class_name: 'Photo', optional: true
has_many :friend_requests, foreign_key: 'sender_id', class_name: 'FriendRequest'
with_options foreign_key: 'sender_id', class_name: 'FriendRequest' do
has_many :outgoing_accepted_friend_requests, -> { accepted }
has_many :outgoing_unaccepted_friend_requests, -> { unaccepted }
end
with_options foreign_key: 'recipient_id', class_name: 'FriendRequest' do
has_many :incoming_accepted_friend_requests, -> { accepted }
has_many :incoming_unaccepted_friend_requests, -> { unaccepted }
has_many :incoming_pending_friend_requests, -> { pending }
has_many :incoming_declined_friend_requests, -> { declined }
end
has_many :out_friends, through: :outgoing_accepted_friend_requests, source: :recipient
has_many :in_friends, through: :incoming_accepted_friend_requests, source: :sender
def friends
in_friends.union(out_friends).order(:updated_at)
end
def accepted_friend_request_with(profile)
(
[ outgoing_accepted_friend_requests.find { |fr| fr.recipient_id == profile.id } ] <<
incoming_accepted_friend_requests.find { |fr| fr.sender_id == profile.id }
).compact.first
end
def out_unaccepted_request_with(profile)
outgoing_unaccepted_friend_requests.find{ |req| req.recipient_id == profile.id }
end
def in_unaccepted_request_with(profile)
incoming_unaccepted_friend_requests.find{ |req| req.sender_id == profile.id }
end
def incoming_requests
incoming_pending_friend_requests
.order(:updated_at)
.union(incoming_declined_friend_requests.order(:updated_at))
end
def conversation_with(profile)
conversations
.joins(:profiles)
.where(profiles: {id: profile})
.group('conversations.id')
.having('count(conversations.id) = ?', 1)
.first
end
def full_name
[first_name, last_name].join(' ')
end
scope :online, -> {
joins(:user).merge(User.where("last_seen > ?", Time.now - 10.minutes))
}
pg_search_scope :search_by_full_name, against: [:first_name, :last_name], using: { tsearch: { prefix: true } }
has_and_belongs_to_many :conversations
end
|
class CompanyResearchesController < ApplicationController
def index
@company_researches = CompanyResearch.all
render("company_researches/index.html.erb")
end
def show
@company_research = CompanyResearch.find(params[:id])
render("company_researches/show.html.erb")
end
def new
@company_research = CompanyResearch.new
render("company_researches/new.html.erb")
end
def create
@company_research = CompanyResearch.new
@company_research.article_link = params[:article_link]
@company_research.company_id = params[:company_id]
@company_research.user_id = params[:user_id]
save_status = @company_research.save
if save_status == true
redirect_to("/company_researches/#{@company_research.id}", :notice => "Company research created successfully.")
else
render("company_researches/new.html.erb")
end
end
def edit
@company_research = CompanyResearch.find(params[:id])
render("company_researches/edit.html.erb")
end
def update
@company_research = CompanyResearch.find(params[:id])
@company_research.article_link = params[:article_link]
@company_research.company_id = params[:company_id]
@company_research.user_id = params[:user_id]
save_status = @company_research.save
if save_status == true
redirect_to("/company_researches/#{@company_research.id}", :notice => "Company research updated successfully.")
else
render("company_researches/edit.html.erb")
end
end
def destroy
@company_research = CompanyResearch.find(params[:id])
@company_research.destroy
if URI(request.referer).path == "/company_researches/#{@company_research.id}"
redirect_to("/", :notice => "Company research deleted.")
else
redirect_to(:back, :notice => "Company research deleted.")
end
end
end
|
class Hotel < ActiveRecord::Base
has_many :reviews
mount_uploader :photo, ImageUploader
validates :name, presence: true, length: {maximum: 50}
validates :rating, presence: true, length: {maximum: 5}
def self.latest
Hotel.order(:updated_at).last
end
end
|
module Services::Searchers
module Errors
ERROR_CODES = {
empty_params: 2,
empty_keywords: 4,
empty_type: 6,
unknown_type: 8
}
end
end
|
class CreateWaterReleases < ActiveRecord::Migration[5.1]
def change
create_table :water_releases do |t|
t.references :dam
t.datetime :start_at
t.datetime :stop_at
t.timestamps
end
end
end
|
# Transformation Step of ETL
class ETL
def self.transform(old_format)
old_format.each_with_object({}) do |(key, value), new_format|
value.each { |e| new_format[e.downcase] = key }
end
end
end
|
# Copyright (c) 2009-2011 VMware, Inc.
require "redis"
$LOAD_PATH.unshift File.join(File.dirname(__FILE__), ".")
require "redis_error"
# Redis client library doesn't support renamed command, so we override the functions here.
class Redis
def config(config_command_name, action, *args)
synchronize do |client|
client.call [config_command_name.to_sym, action, *args] do |reply|
if reply.kind_of?(Array) && action == :get
Hash[*reply]
else
reply
end
end
end
end
def shutdown(shutdown_command_name)
synchronize do |client|
client.with_reconnect(false) do
begin
client.call [shutdown_command_name.to_sym]
rescue ConnectionError
# This means Redis has probably exited.
nil
end
end
end
end
def save(save_command_name)
synchronize do |client|
client.call [save_command_name.to_sym]
end
end
end
module VCAP
module Services
module Redis
module Util
@redis_timeout = 2 if @redis_timeout == nil
VALID_CREDENTIAL_CHARACTERS = ("A".."Z").to_a + ("a".."z").to_a + ("0".."9").to_a
def generate_credential(length=12)
Array.new(length) { VALID_CREDENTIAL_CHARACTERS[rand(VALID_CREDENTIAL_CHARACTERS.length)] }.join
end
def fmt_error(e)
"#{e}: [#{e.backtrace.join(" | ")}]"
end
def dump_redis_data(instance, dump_path, gzip_bin=nil, compressed_file_name=nil)
dir = get_config(instance.port, instance.password, "dir")
set_config(instance.port, instance.password, "dir", dump_path)
begin
Timeout::timeout(@redis_timeout) do
redis = ::Redis.new({:port => instance.port, :password => instance.password})
redis.save(@save_command_name)
end
rescue => e
raise RedisError.new(RedisError::REDIS_CONNECT_INSTANCE_FAILED)
ensure
begin
set_config(instance.port, instance.password, "dir", dir)
redis.quit if redis
rescue => e
end
end
if gzip_bin
dump_file = File.join(dump_path, "dump.rdb")
cmd = "#{gzip_bin} -c #{dump_file} > #{dump_path}/#{compressed_file_name}"
on_err = Proc.new do |cmd, code, msg|
raise "CMD '#{cmd}' exit with code: #{code}. Message: #{msg}"
end
res = CMDHandle.execute(cmd, nil, on_err)
return res
end
true
rescue => e
@logger.error("Error dump instance #{instance.name}: #{fmt_error(e)}")
nil
ensure
FileUtils.rm(File.join(dump_path, "dump.rdb")) if gzip_bin
end
def import_redis_data(instance, dump_path, base_dir, redis_server_path, gzip_bin=nil, compressed_file_name=nil)
name = instance.name
dump_file = File.join(dump_path, "dump.rdb")
temp_file = nil
if gzip_bin
# add name in temp file name to prevent file overwritten by other import jobs.
temp_file = File.join(dump_path, "#{name}.dump.rdb")
zip_file = File.join(dump_path, "#{compressed_file_name}")
cmd = "#{gzip_bin} -dc #{zip_file} > #{temp_file}"
on_err = Proc.new do |cmd, code, msg|
raise "CMD '#{cmd}' exit with code: #{code}. Message: #{msg}"
end
res = CMDHandle.execute(cmd, nil, on_err)
if res == nil
return nil
end
dump_file = temp_file
end
config_path = File.join(base_dir, instance.name, "redis.conf")
stop_redis_server(instance)
FileUtils.cp(dump_file, File.join(base_dir, instance.name, "data", "dump.rdb"))
pid = fork
if pid
@logger.debug("Service #{instance.name} started with pid #{pid}")
# In parent, detch the child.
Process.detach(pid)
return pid
else
$0 = "Starting Redis instance: #{instance.name}"
close_fds
exec("#{redis_server_path} #{config_path}")
end
true
rescue => e
@logger.error("Failed in import dumpfile to instance #{instance.name}: #{fmt_error(e)}")
nil
ensure
FileUtils.rm_rf temp_file if temp_file
end
def check_password(port, password)
Timeout::timeout(@redis_timeout) do
redis = ::Redis.new({:port => port})
redis.auth(password)
end
true
rescue => e
if e.message == "ERR invalid password"
return false
else
raise RedisError.new(RedisError::REDIS_CONNECT_INSTANCE_FAILED)
end
ensure
begin
redis.quit if redis
rescue => e
end
end
def get_info(port, password)
info = nil
Timeout::timeout(@redis_timeout) do
redis = ::Redis.new({:port => port, :password => password})
info = redis.info
end
info
rescue => e
raise RedisError.new(RedisError::REDIS_CONNECT_INSTANCE_FAILED)
ensure
begin
redis.quit if redis
rescue => e
end
end
def get_config(port, password, key)
config = nil
Timeout::timeout(@redis_timeout) do
redis = ::Redis.new({:port => port, :password => password})
config = redis.config(@config_command_name, :get, key)[key]
end
config
rescue => e
raise RedisError.new(RedisError::REDIS_CONNECT_INSTANCE_FAILED)
ensure
begin
redis.quit if redis
rescue => e
end
end
def set_config(port, password, key, value)
Timeout::timeout(@redis_timeout) do
redis = ::Redis.new({:port => port, :password => password})
redis.config(@config_command_name, :set, key, value)
end
rescue => e
raise RedisError.new(RedisError::REDIS_CONNECT_INSTANCE_FAILED)
ensure
begin
redis.quit if redis
rescue => e
end
end
def stop_redis_server(instance)
Timeout::timeout(@redis_timeout) do
redis = ::Redis.new({:port => instance.port, :password => instance.password})
begin
redis.shutdown(@shutdown_command_name)
rescue RuntimeError => e
if e.message == "ERR max number of clients reached"
# The max clients limitation could be reached, try to kill the process
instance.kill
instance.wait_killed ?
@logger.debug("Redis server pid: #{instance.pid} terminated") :
@logger.error("Timeout to terminate Redis server pid: #{instance.pid}")
else
# It could be a disabled instance
if @disable_password
redis = ::Redis.new({:port => instance.port, :password => @disable_password})
redis.shutdown(@shutdown_command_name)
end
end
end
end
rescue Timeout::Error => e
@logger.warn(e)
end
def close_fds
3.upto(get_max_open_fd) do |fd|
begin
IO.for_fd(fd, "r").close
rescue
end
end
end
def get_max_open_fd
max = 0
dir = nil
if File.directory?("/proc/self/fd/") # Linux
dir = "/proc/self/fd/"
elsif File.directory?("/dev/fd/") # Mac
dir = "/dev/fd/"
end
if dir
Dir.foreach(dir) do |entry|
begin
pid = Integer(entry)
max = pid if pid > max
rescue
end
end
else
max = 65535
end
max
end
end
end
end
end
|
module Facter::Util::WithPuppet
def with_puppet
# This is in case this fact is running without Puppet loaded
if Module.constants.include? "Puppet"
begin
yield if block_given?
rescue Facter::Util::PuppetCertificateError => detail
# To be as un-intrusive (e.g. when running 'facter') as possible, this
# doesn't even warn at the moment
# Facter.warnonce "Could not load facts for #{Puppet[:hostcert]}: #{detail}"
end
else
nil
end
end
end
|
class Stuff < ApplicationRecord
has_one_attached :image
belongs_to :user
has_many :stuff_categories
has_many :categories, through: :stuff_categories
validates :title, presence: true, length: { maximum: 20 }
validates :description, presence: true, length: {maximum: 300}
validate :image_type
after_commit :add_default_image, on: %i[create update]
validate :found_or_lost
#search with word
def self.search(search)
stuff = all
stuff = Stuff.where('title LIKE ?', "%#{search}%")
return stuff
end
#search location
def self.searchLoc(search)
stuff = all
stuff = Stuff.where('address LIKE ?', "%#{search}%")
return stuff
end
#search found
def self.found(stuff)
stuff = all
stuff = Stuff.where(find: true)
return stuff
end
#search lost
def self.lost(stuff)
stuff = all
stuff = Stuff.where(find: false)
return stuff
end
def self.cat(cat)
stuff = all
stuff = Stuff.joins(:categories).where('categories.id LIKE ?', "%#{cat}%")
return stuff
end
def self.between(start_date, end_date)
stuff = all
stuff = Stuff.where('found_date >= ? AND found_date <= ?', start_date, end_date)
return stuff
end
def stuff_image
if image.attached?
image.variant(resize: "150x150!").processed
else
"/image-not-found.png"
end
end
private
def image_type
if image.attached? == false
add_default_image
elsif
!image.content_type.in?(%('image/jpeg image/png'))
errors.add(:image, 'needs to be a JPEG or PNG')
end
end
def add_default_image
unless image.attached?
image.attach(
io: File.open(
Rails.root.join(
'app', 'assets', 'images', 'image-not-found.png'
)
),
filename: 'image-not-found.png',
content_type: 'image/png'
)
end
end
def found_or_lost
if find.blank? && lost.blank?
errors[:base] << "Must select found or lost"
end
end
end
|
class ServicesController < ApplicationController
def create
@service = service.build(params.require(:service).permit(:duration, :price, :service_name))
if @service.save
flash[:success] = "New service created."
redirect_to welcome_url
else
flash.now[:error] = "Service could not be created."
end
end
end
|
class Instructor < ApplicationRecord
has_many :courses
end |
require 'stringio'
module Zlib
# The superclass for all exceptions raised by Ruby/zlib.
class Error < StandardError; end
# constants from zlib.h as linked into Gemstone libgcilnk.so
ZLIB_VERSION = "1.2.5"
Z_NO_FLUSH = 0
# Z_PARTIAL_FLUSH = 1 # will be removed, use Z_SYNC_FLUSH instead
Z_SYNC_FLUSH = 2
Z_FULL_FLUSH = 3 # inflate() will terminate a block of compressed data
Z_FINISH = 4
Z_BLOCK = 5 # deflate() will return at end of next block boundary,
# or after the gzip header .
Z_TREES = 6
Z_OK = 0
Z_STREAM_END = 1
Z_NEED_DICT = 2
Z_ERRNO = (-1)
Z_STREAM_ERROR = (-2)
Z_DATA_ERROR = (-3)
Z_MEM_ERROR = (-4)
Z_BUF_ERROR = (-5)
Z_VERSION_ERROR = (-6)
Z_NO_COMPRESSION = 0
Z_BEST_SPEED = 1
Z_BEST_COMPRESSION = 9
Z_DEFAULT_COMPRESSION = (-1)
Z_FILTERED = 1
Z_HUFFMAN_ONLY = 2
Z_RLE = 3
Z_FIXED = 4
Z_DEFAULT_STRATEGY = 0
Z_DEFLATED = 8
# from zconf.h
MAX_WBITS = 15 # 32K LZ77 window
MAX_MEM_LEVEL = 9
DEF_MEM_LEVEL = 9
OS_UNIX = 0x03
OS_CODE = OS_UNIX
# class Zlib::ZStream was defined during bootstrap in zlib_czstream.rb
class GzipFile # {
class Error < Zlib::Error; end
#SYNC = Zlib::ZStream::UNUSED
#HEADER_FINISHED = Zlib::ZStream::UNUSED << 1
#FOOTER_FINISHED = Zlib::ZStream::UNUSED << 2
FLAG_MULTIPART = 0x2
FLAG_EXTRA = 0x4
FLAG_ORIG_NAME = 0x8
FLAG_COMMENT = 0x10
FLAG_ENCRYPT = 0x20
FLAG_UNKNOWN_MASK = 0xc0
EXTRAFLAG_FAST = 0x4
EXTRAFLAG_SLOW = 0x2
MAGIC1 = 0x1f
MAGIC2 = 0x8b
METHOD_DEFLATE = 8
def self.wrap(io, &block)
obj = self.new(io)
if block_given? then
begin
yield obj
ensure
obj.close
end
end
end
# TODO: protect against multiple calls to close, or a close after a finish
def close
io = finish()
io.close if io.respond_to? :close
io
end
def closed?
@io._equal?(nil)
end
def comment
raise Error, 'closed gzip stream' if @io.nil?
@comment.dup
end
# def finish # subclass responsibility
def finished?
self.closed?()
end
# def footer_finished? # not implemented
# def header_finished? # not implemented
def mtime
Time.at(@mtime)
end
def orig_name
raise Error, 'closed gzip stream' if @io.nil?
@orig_name.dup
end
end # }
class GzipReader < GzipFile # {
def initialize(io)
@io = io
@zstream = ZStream.open_read(io, Error) # Error resolves to GzipFile::Error
super()
arr = @zstream.read_header()
@orig_name = arr[0]
@comment = arr[1]
@mtime = arr[2]
end
def rewind
@zstream.close
@io.rewind
@zstream = ZStream.open_read(@io, Error)
arr = @zstream.read_header()
@orig_name = arr[0]
@comment = arr[1]
@mtime = arr[2]
0
end
def eof?
@zstream.at_eof
end
def pos
sio = @contents_sio
if sio._not_equal?(nil)
sio.pos
else
@zstream.total_out()
end
end
def read(length = nil)
if length.nil?
buf = ''
while ! eof?
buf << @zstream.read(16384)
end
buf
else
@zstream.read(length)
end
end
def finish
# does not call close method of the associated IO object.
@zstream.close
io = @io
@io = nil
io
end
def each_byte(&block)
sio = self.__contents_sio
sio.each_byte(&block)
self
end
def __contents_sio
sio = @contents_sio
if sio._equal?(nil)
str = String.new
while not eof?
buf = self.read(4096)
if buf._equal?(nil)
return str
end
str << buf
end
sio = PureRubyStringIO.open(str)
@contents_sio = sio
end
sio
end
def each_line(sep=$/, &block)
sio = self.__contents_sio
sio.each_line(sep, &block)
end
alias each each_line
def getc
sio = self.__contents_sio
sio.getc
end
def gets(sep_string=nil)
sio = self.__contents_sio
if sep_string._equal?(nil)
sio.__gets( $/ , 0x41) # called via bridge meth
else
sio.__gets(sep_string, 0x31)
end
end
end # }
class GzipWriter < GzipFile # {
GzfError = GzipFile::Error
##
# Creates a GzipWriter object associated with +io+. +level+ and +strategy+
# should be the same as the arguments of Zlib::Deflate.new. The
# GzipWriter object writes gzipped data to +io+. At least, +io+ must
# respond to the +write+ method that behaves same as write method in IO
# class.
def initialize(io, level = Z_DEFAULT_COMPRESSION,
strategy = Z_DEFAULT_STRATEGY)
@level = level
@strategy = strategy
@io = io
@mtime = 0
@buffer = ''
@bufsize = 0
@zstream = nil
super()
end
def comment=(v)
# Set the comment
unless @zstream._equal?(nil) then
raise GzfError, 'header is already written' # Error resolves to GzipFile::Error
end
@comment = v
end
def mtime=(time)
unless @zstream._equal?(nil) then
raise GzfError, 'header is already written' # Error resolves to GzipFile::Error
end
t = Integer(time)
@mtime = t
end
def orig_name=(v)
# Set the original name
unless @zstream._equal?(nil) then
raise GzfError, 'header is already written' # Error resolves to GzipFile::Error
end
@orig_name = v
end
def __validate_string(obj)
unless obj._equal?(nil)
unless obj._isString
raise ArgumentError, 'argument must be a String'
end
end
end
def write_header
__validate_string(@orig_name)
__validate_string(@comment)
lev = @level
if (lev < Z_DEFAULT_COMPRESSION || lev > Z_BEST_COMPRESSION)
raise ArgumentError, 'compression level out of range'
end
@zstream = ZStream.open_write(@io, Error, lev) # Error resolves to GzipFile::Error
tim = @mtime.to_i
unless tim._isFixnum
raise ArgumentError, 'mtime must be a Fixnum'
end
arr = [ @orig_name, @comment, tim]
@zstream.write_header(arr)
end
def write(data)
strm = @zstream
if strm._equal?(nil)
write_header
strm = @zstream
end
unless data._isString
data = String(data)
end
ds = data.length
bs = @bufsize
if (ds >= 1024)
if bs > 0
strm.write(@buffer, bs)
@bufsize = 0
end
strm.write(data, ds)
else
if (bs >= 1024)
strm.write(@buffer, bs)
@bufsize = 0
bs = 0
end
@buffer[bs, ds] = data
@bufsize = bs + ds
end
end
alias << write
def finish(flags=Z_SYNC_FLUSH)
strm = @zstream
if strm._equal?(nil)
write_header
strm = @zstream
end
bs = @bufsize
if bs > 0
strm.write(@buffer, bs)
@bufsize = 0
end
unless flags == Z_SYNC_FLUSH
strm.flush(flags) # writes footer
end
@io
end
def flush(flags=Z_SYNC_FLUSH)
self.finish(flags)
end
def close
self.finish(Z_FINISH)
@zstream.close
@zstream = nil
io = @io
if io
# RubyGems RestrictedStream only understands #initialize and #write
io.flush if io.respond_to?(:flush)
io.close if io.respond_to?(:close)
@io = nil
end
io
end
end # }
# Zlib:Inflate is the class for decompressing compressed data. Unlike
# Zlib::Deflate, an instance of this class is not able to duplicate
# (clone, dup) itself.
class Inflate < ZStream
# Decompress +string+.
def self.inflate(string)
inflate_stream = Zlib::Inflate.new
buf = inflate_stream.inflate(string)
inflate_stream.finish
inflate_stream.close
buf
end
def inflate(string)
__open(false, StringIO.new(string), Error, Z_DEFAULT_COMPRESSION) # Error resolves to Zlib::Error
self.flush_next_out
end
def <<(string)
io = @ioObj
if io._equal?(nil)
__open(false, StringIO.new(string), Error, Z_DEFAULT_COMPRESSION)
else
@ioObj << string
end
end
def flush_next_out
buf = ''
while ! at_eof
buf << read(2048)
end
buf
end
def finish
flush_next_out
end
def close
unless @isClosed
@isClosed = true
super()
end
end
def closed?
@isClosed
end
def finished?
at_eof
end
end
# class Deflate < ZStream
# # Compresses the given +string+. Valid values of level are
# # <tt>Zlib::NO_COMPRESSION</tt>, <tt>Zlib::BEST_SPEED</tt>,
# # <tt>Zlib::BEST_COMPRESSION</tt>, <tt>Zlib::DEFAULT_COMPRESSION</tt>, and an
# # integer from 0 to 9.
# #
# # This method is almost equivalent to the following code:
# #
# # def deflate(string, level)
# # z = Zlib::Deflate.new(level)
# # dst = z.deflate(string, Zlib::FINISH)
# # z.close
# # dst
# # end
# #
# # TODO: what's default value of +level+?
# def deflate(string, flush = Zlib::FINISH)
# end
# end
end
|
class CreateCollectibles < ActiveRecord::Migration[6.0]
def change
create_table :collectibles do |t|
t.string :category
t.string :brand
t.string :model
t.string :reference
t.float :retail_price
t.float :resell_value
t.string :description
t.references :user, null: false, foreign_key: true
t.integer :nft_number
t.timestamps
end
end
end
|
Rails.application.routes.draw do
resources :notes
resources :offers
resources :tasks
resources :projects
resources :contacts
resources :companies
root 'root#index'
end
|
require 'router'
require 'byebug'
require './lib/action_dispatch_lite/path_helper'
describe ActionDispatchLite::PathHelper do
PATHS = { edit: '/edit', new: '/new', id: '/:id' }
subject( :route ) { Route.new( Regexp.new( path ), :get, 'CakeOfTheDay', :wow ) }
describe '#method_name' do
context 'when the path pertains to a singular resource' do
it 'attempts to singularise the resources plural, when appropriate for the path type' do
{ 'cats' => 'cat', 'cities' => 'city', 'equipment' => 'equipment' }.each do |pl, si|
route = Route.new( Regexp.new( "^/#{pl}/:id$" ), :get, 'Test', :show )
expect( route.method_name )
.to eq( si )
end
end
end
PATHS.each do |sym, path_end|
next if sym == :id
context "when the path ends with '#{path_end}'" do
let( :path ) { "^/cakes#{path_end}$" }
it "returns a name in the form of #{sym}_resource" do
expect( route.method_name ).to start_with( sym.to_s )
end
end
end
context "when the path ends with '/:id'" do
let( :path ) { "^/cakes/:id$" }
it 'returns the the singularized resource name' do
expect( route.method_name ).to eq 'cake'
end
end
context 'when the path ends with the pluralised resource' do
let( :path ) { '^/cakes$' }
it 'returns the pluralised resource name' do
expect( route.method_name ).to eq 'cakes'
end
end
end
describe '#path' do
reg_strings = {
'^/account/users$' => '/account/users',
'^/users/:id$' => '/users/:id',
'^/chippy_teas/edit$' => '/chippy_teas/edit'
}
context 'when the route pattern is a regex' do
it 'converts regex paths to string url paths on init' do
reg_strings.each do |regex, path|
route = Route.new( Regexp.new( regex ), :get, 'CakeOfTheDay', :wow )
expect( route.path ).to eq( path )
end
end
end
context 'when the route pattern is a string' do
it 'does not alter the path string' do
reg_strings.values.each do |path|
route = Route.new( path, :get, 'Paths', :x )
expect( route.path ).to eq( path )
end
end
end
end
describe '#static_segments' do
let( :path ) { '^/users$' }
it 'returns the static segment of a simple route path as an array of substrings' do
expect( route.static_segments( route.path ) ).to eq( [ 'users' ] )
end
end
end |
require "rails_helper"
include AccommodationsHelper
RSpec.describe AccommodationsHelper do
describe ".search_reserved_rooms" do
it "finds all reserved rooms" do
room_booking = FactoryGirl.create :present_room_booking
result = search_reserved_rooms(Date.current, Date.current + 5)
expect(result).to eq([room_booking.accommodation])
end
it "DOES NOT find reserved rooms" do
room_booking = FactoryGirl.create :future_room_booking
result = search_reserved_rooms(Date.current + 30, Date.current + 35)
expect(result).to eq([])
end
end
describe ".search_reserved_meeting_rooms" do
it "finds all reserved meeting rooms" do
meeting_room_booking = FactoryGirl.create :present_meeting_room_booking
result = search_reserved_meeting_rooms(Date.current, DateTime.now + 1.hour)
expect(result).to eq([meeting_room_booking.accommodation])
end
it "DOES NOT find reserved meeting rooms" do
meeting_room_booking = FactoryGirl.create :present_meeting_room_booking
result = search_reserved_rooms(Date.current , DateTime.now + 10.hour)
expect(result).to eq([])
end
end
describe ".search_reserved_event_halls" do
it "finds all reserved event halls" do
event_hall_booking = FactoryGirl.create :present_event_hall_booking
result = search_reserved_event_halls(Date.current, 2)
expect(result).to eq([event_hall_booking.accommodation])
end
it "DOES NOT find reserved event halls" do
event_hall_booking = FactoryGirl.create :future_event_hall_booking
result = search_reserved_event_halls(Date.current + 3, 1)
expect(result).to eq([])
end
end
describe ".available_room?" do
it "room is available" do
room_booking = FactoryGirl.create :future_room_booking
result = available_room?(room_booking.accommodation , Date.current + 1, Date.current + 3)
expect(result).to eq(true)
end
it "room IS NOT available today" do
room_booking = FactoryGirl.create :present_room_booking
result = available_room?(room_booking.accommodation , Date.current, Date.current + 3)
expect(result).to eq(false)
end
end
describe ".available_meeting_room?" do
it "meeting room is available" do
meeting_room_booking = FactoryGirl.create :future_meeting_room_booking
result = available_meeting_room?(meeting_room_booking.accommodation , Date.current + 5, DateTime.now + 5.days + 10.hour)
expect(result).to eq(true)
end
it "meeting room IS NOT available" do
meeting_room_booking = FactoryGirl.create :present_meeting_room_booking
result = available_meeting_room?(meeting_room_booking.accommodation , Date.current, DateTime.now + 2.hour)
expect(result).to eq(false)
end
end
describe ".available_event_hall?" do
it "event hall is available" do
event_hall_booking = FactoryGirl.create :future_event_hall_booking
result = available_event_hall?(event_hall_booking.accommodation , Date.current + 5.days, 1)
expect(result).to eq(true)
end
it "event hall IS NOT available today" do
event_hall_booking = FactoryGirl.create :present_event_hall_booking
result = available_event_hall?(event_hall_booking.accommodation , Date.current, 2)
expect(result).to eq(false)
end
end
end
|
describe Repositories::Workers::CheckPullRequest do
describe '#perform' do
subject(:worker_result) { described_class.new.perform(pull_request.id) }
let(:pull_request) { create :pull_request }
let(:failure) { false }
let(:error) { nil }
before do
allow(PullRequest).to receive(:find).and_return(pull_request)
interactor_result = double(failure?: failure, error: error) # rubocop:disable RSpec/VerifiedDoubles
allow(Repositories::Interactors::CheckPullRequest).to receive(:call)
.and_return(interactor_result)
end
it 'calls interactor correctly' do
worker_result
expect(Repositories::Interactors::CheckPullRequest).to have_received(:call)
.with({ pull_request: pull_request })
end
context 'when it fails' do
let(:failure) { true }
let(:error) { 'Pull request check status failed' }
it 'raise exception' do
expect { worker_result }.to raise_error(described_class::CheckPullRequestError)
end
end
end
end
|
require 'gtk3'
require './Classes/boutonNbTentes.rb'
#====== La classe BoutonNbTentes représente les boutons sur le côté gauche de la grille de jeu pour remplir une ligne/colonne d'herbe
class BoutonNbTentesLigne < BoutonNbTentes
#=Variable d'instance
# @bouton : Le bouton
# @coordI, @coordJ : Coordonnées du bouton
attr_reader :indice
attr_accessor :bouton
attr_accessor :clic
attr_reader :chemin
#Initialise le bouton de sélection de ligne
# @param uneGrille //Grille de jeu
# @param grilleInterface //affichage de grille de jeu
# @param indice //indice ligne/colonne
# @param chemin //Le chemin d'accès du dossier contenant les différentes images
# @param unJoueur //Le joueur concerné
# @param classique //booléen mode classique ou non
# @return void //ne renvoie rien
def initialize(uneGrille, grilleInterface, indice, chemin, unJoueur, classique)
super(uneGrille, grilleInterface, indice, chemin, unJoueur, classique)
# puts "@indice interne #{@indice}"
end
#Change l'image du bouton en fonction de l'état
# @param monApp //l'application
# @param etatC //un chiffre représentant l'état d'une case
# @param chrono //le chronomètre
# @return void //ne renvoie rien
def chgEtat(monApp, etatC, chrono)
if !etatC
for i in (0..@grilleDeJeu.taille-1)
if (@grilleDeJeu.grilleJ[i][@indice].etat != 1 && @grilleDeJeu.grilleJ[i][@indice].etat != 2)
@pix = (GdkPixbuf::Pixbuf.new(:file =>"#{@chemin}/herbe.png",:width=> monApp.width/25, :height=> monApp.height/25))
@boutonGrille[i][@indice].bouton.set_image(Gtk::Image.new(:pixbuf => @pix))
focus_hadjustment=(:start)
@grilleDeJeu.grilleJ[i][@indice].etat = 3
if(@classique == true)
@grilleDeJeu.enregistrerFichier(@joueur.pseudo, chrono)
end
end
end
end
end
end
|
class HomeController < ApplicationController
before_filter :authenticate_user!
def index
@first_time = current_user.new_to_update?
current_user.update_attribute(:new_to_update, false) if @first_time
respond_to do |format|
format.html # index.html.erb
end
end
end
|
# only_even.rb
# Using `next`, modify the code below so that it only prints even numbers.
number = 0
until number == 10
number += 2
puts number
end
puts '----'
# Launch School solution:
number = 0
until number == 10
number += 1
next if number.odd?
puts number
end
|
class CellSerializer < ActiveModel::Serializer
attributes :board_index, :cell_type
end
|
json.exchanges @exchanges do |exchange|
json.extract! exchange, :id, :name, :exchange_kind
end
json.message_routes @message_routes do |message_route|
json.extract! message_route, :id, :from_exchange_id, :to_exchange_id, :routing_key
end
json.route_arguments @route_arguments do |route_argument|
json.extract! route_argument, :id, :message_route_id, :key
if !route_argument.value.nil?
json.value route_argument.value
end
end
|
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery
after_filter :set_csrf_cookie_for_ng, :set_access_control_header
def set_csrf_cookie_for_ng
cookies['XSRF-TOKEN'] = form_authenticity_token if protect_against_forgery?
end
def set_access_control_header
# Very bad. Don't release this app untill security is 100% rock solid.
# Don't forget, we are trying to release this product in Nigeria
verified_host()
end
protected
def verified_request?
super || valid_authenticity_token?(session, request.headers['X-XSRF-TOKEN'])
end
def verified_host
host_name = request.headers['ORIGIN']
secure = (host_name == 'https://localhost:9000')
unsecure = (host_name == 'http://localhost:9000')
print(secure)
print('\n')
print(unsecure)
if secure || unsecure
headers['Access-Control-Allow-Origin'] = host_name
headers['Access-Control-Allow-Method'] = '*'
end
end
end
|
class Calculator::Freight < Calculator
def self.description
"Freight"
end
def self.register
super
ShippingMethod.register_calculator(self)
end
def compute(shipment)
shipment.adjustment.nil? ? 0 : shipment.adjustment.amount
end
def available?(order,options)
order.weight_of_line_items_for_supplier(options[:supplier]) > 150
end
end
|
class NewsController < ApplicationController
include ApplicationHelper
before_filter :can_add_news, only: [:new, :create]
before_filter :can_edit_news, only: [:edit, :update]
before_filter :can_delete_news, only: [:destroy]
def index
@news = New.order('created_at DESC').page(params[:page]).per(10)
end
def new
@new = New.new
end
def create
@new = New.new(params[:new])
if @new.save
redirect_to news_index_path
else
render :new
end
end
def edit
@new = New.find(params[:id])
end
def update
new = New.find(params[:id])
if new.update_attributes(params[:new])
redirect_to news_index_path
else
render :edit
end
end
def destroy
new = New.find(params[:id])
new.destroy
redirect_to news_index_path
end
# TODO: Завернуть 3 шляпных метода в одно прекрасное
def can_add_news
redirect_to news_index_path unless can?('create_news')
end
def can_edit_news
redirect_to news_index_path unless can?('edit_news')
end
def can_delete_news
redirect_to news_index_path unless can?('delete_news')
end
end
|
require 'spec_helper'
describe ProjectsController, :type => :controller do
# This should return the minimal set of attributes required to create a valid
# Project. As you add validations to Project, be sure to
# update the return value of this method accordingly.
def valid_attributes
{ 'name' => 'MyString' }
end
# This should return the minimal set of values that should be in the session
# in order to pass any filters (e.g. authentication) defined in
# ProjectsController. Be sure to keep this updated too.
def valid_session
{}
end
describe 'GET index' do
it 'assigns active projects as @projects' do
project = Project.create! valid_attributes
archived = Project.create!(name: 'Archive', archived: true)
get :index, {}, valid_session
expect(assigns(:projects)).to eq([project])
end
end
describe 'GET archived' do
it 'assigns archived projects as @projects' do
project = Project.create! valid_attributes
archived = Project.create!(name: 'Archive', archived: true)
get :archived, {}, valid_session
expect(assigns(:projects)).to eq([archived])
end
end
describe 'GET show' do
it 'assigns the requested project as @project' do
project = Project.create! valid_attributes
get :show, {:id => project.to_param}, valid_session
expect(assigns(:project)).to eq(project)
end
end
describe 'GET new' do
it 'assigns a new project as @project' do
get :new, {}, valid_session
expect(assigns(:project)).to be_a_new(Project)
end
end
describe 'GET edit' do
it 'assigns the requested project as @project' do
project = Project.create! valid_attributes
get :edit, {:id => project.to_param}, valid_session
expect(assigns(:project)).to eq(project)
end
end
describe 'POST create' do
describe 'with valid params' do
it 'creates a new Project' do
expect {
post :create, {:project => valid_attributes}, valid_session
}.to change(Project, :count).by(1)
end
it 'assigns a newly created project as @project' do
post :create, {:project => valid_attributes}, valid_session
expect(assigns(:project)).to be_a(Project)
expect(assigns(:project)).to be_persisted
end
it 'redirects to the created project' do
post :create, {:project => valid_attributes}, valid_session
expect(response).to redirect_to(Project.last)
end
context 'when default template task exists, ' do
let(:template_task){TemplateTask.new(name: 'Task', price_per_day: 40000, default_task: false)}
let(:default_template_task){TemplateTask.new(name: 'Default Task', price_per_day: 50000, default_task: true)}
before do
template_task.save!
default_template_task.save!
end
it 'default TemplateTask is added' do
post :create, {:project => valid_attributes}, valid_session
project_tasks = ProjectTask.where(project_id: Project.last.id)
expect(project_tasks.count).to eq 1
expect(project_tasks[0].name).to eq 'Default Task'
expect(project_tasks[0].price_per_day).to eq 50000
end
end
end
describe 'with invalid params' do
it 'assigns a newly created but unsaved project as @project' do
# Trigger the behavior that occurs when invalid params are submitted
allow_any_instance_of(Project).to receive(:save).and_return(false)
post :create, {:project => { 'name' => 'invalid value' }}, valid_session
expect(assigns(:project)).to be_a_new(Project)
end
it "re-renders the 'new' template" do
# Trigger the behavior that occurs when invalid params are submitted
allow_any_instance_of(Project).to receive(:save).and_return(false)
post :create, {:project => { 'name' => 'invalid value' }}, valid_session
expect(response).to render_template('new')
end
end
end
describe 'PUT update' do
describe 'with valid params' do
it 'updates the requested project' do
project = Project.create! valid_attributes
# Assuming there are no other projects in the database, this
# specifies that the Project created on the previous line
# receives the :update_attributes message with whatever params are
# submitted in the request.
expect_any_instance_of(Project).to receive(:update_attributes).with({ 'name' => 'MyString' })
put :update, {:id => project.to_param, :project => { 'name' => 'MyString' }}, valid_session
end
it 'assigns the requested project as @project' do
project = Project.create! valid_attributes
put :update, {:id => project.to_param, :project => valid_attributes}, valid_session
expect(assigns(:project)).to eq(project)
end
it 'redirects to the project' do
project = Project.create! valid_attributes
put :update, {:id => project.to_param, :project => valid_attributes}, valid_session
expect(response).to redirect_to(project)
end
end
describe 'with invalid params' do
it 'assigns the project as @project' do
project = Project.create! valid_attributes
# Trigger the behavior that occurs when invalid params are submitted
allow_any_instance_of(Project).to receive(:save).and_return(false)
put :update, {:id => project.to_param, :project => { 'name' => 'invalid value' }}, valid_session
expect(assigns(:project)).to eq(project)
end
it "re-renders the 'edit' template" do
project = Project.create! valid_attributes
# Trigger the behavior that occurs when invalid params are submitted
allow_any_instance_of(Project).to receive(:save).and_return(false)
put :update, {:id => project.to_param, :project => { 'name' => 'invalid value' }}, valid_session
expect(response).to render_template('edit')
end
end
end
describe 'DELETE destroy' do
it 'destroys the requested project' do
project = Project.create! valid_attributes
expect {
delete :destroy, {:id => project.to_param}, valid_session
}.to change(Project, :count).by(-1)
end
it 'redirects to the projects list' do
project = Project.create! valid_attributes
delete :destroy, {:id => project.to_param}, valid_session
expect(response).to redirect_to(archived_projects_url)
end
end
describe "GET 'dup_form'" do
before do
@project = Project.new(name: 'Sample', days_per_point: 0.5)
@project.save!
end
describe 'check redirect path' do
before{ get :dup_form, { id: @project.id } }
subject{ response }
it{ is_expected.to redirect_to root_url }
end
end
describe 'Post archive' do
before do
@project = Project.create(name: 'Sample', archived: false)
end
describe 'check to updating project data' do
before{ post :archive, { id: @project.id } }
subject{ Project.find(@project.id) }
describe '#archived' do
subject { super().archived }
it { is_expected.to be_truthy }
end
end
describe 'check redirect path' do
before{ post :archive, { id: @project.id } }
subject{ response }
it{ is_expected.to redirect_to root_url }
end
end
describe 'Post active' do
before do
@project = Project.create(name: 'Sample', archived: true)
end
describe 'check to updating project data' do
before{ post :active, { id: @project.id } }
subject{ Project.find(@project.id) }
describe '#archived' do
subject { super().archived }
it { is_expected.to be_falsey }
end
end
describe 'check redirect path' do
before{ post :active, { id: @project.id } }
subject{ response }
it{ is_expected.to redirect_to archived_projects_path }
end
end
end
|
module Naf
class LoggerStylesController < Naf::ApplicationController
before_filter :set_cols_and_attributes
def index
@rows = Naf::LoggerStyle.all
render template: 'naf/datatable'
end
def show
@logger_style = Naf::LoggerStyle.find(params[:id])
end
def destroy
@logger_style = Naf::LoggerStyle.find(params[:id])
@logger_style.destroy
flash[:notice] = "Logger Style '#{@logger_style.name}' was successfully deleted."
redirect_to(action: "index")
end
def new
@logger_style = Naf::LoggerStyle.new
@logger_style.logger_style_names.build
end
def create
@logger_style = Naf::LoggerStyle.new(params[:logger_style])
if @logger_style.save
redirect_to(@logger_style,
notice: "Logger Style '#{@logger_style.name}' was successfully created.")
else
render action: "new"
end
end
def edit
@logger_style = Naf::LoggerStyle.find(params[:id])
end
def update
@logger_style = Naf::LoggerStyle.find(params[:id])
if @logger_style.update_attributes(params[:logger_style])
redirect_to(@logger_style,
notice: "Logger Style '#{@logger_style.name}' was successfully updated.")
else
render action: "edit"
end
end
private
def set_cols_and_attributes
@attributes = Naf::LoggerStyle.attribute_names.map(&:to_sym)
@cols = [:id, :name, :note, :_logger_names, :logger_levels]
end
end
end
|
class ProposalFieldedSearchQuery
attr_reader :field_pairs
def initialize(field_pairs)
@field_pairs = field_pairs
end
def present?
return false unless field_pairs
to_s.present?
end
def value_for(key)
if field_pairs && field_pairs.key?(key)
field_pairs[key]
end
end
def to_s
clauses = []
if field_pairs
field_pairs.each do |k, v|
next if v.nil?
next if v.blank?
next if v == "*"
clauses << clause_to_s(k, v)
end
end
clauses.join(" ")
end
def to_h
hash = {}
if field_pairs
field_pairs.each do |k, v|
next if v.nil?
next if v.blank?
next if v == "*"
hash[k] = v
end
end
hash
end
def humanized(client_model)
humanized = {}
to_h.each do |k, v|
if k.match(/^client_data\./)
attr = k.match(/^client_data\.(.+)/)[1]
humanized[client_model.human_attribute_name(attr)] = v
else
humanized[Proposal.human_attribute_name(k)] = v
end
end
self.class.new(humanized)
end
private
def clause_to_s(key, value)
if value.to_s.match(/^\w/)
"#{key}:(#{value})"
else
"#{key}:#{value}"
end
end
end
|
require "./Node"
class LinkedList
def initialize
@count = 0
@top = nil
end
def add(x)
if @top
tmp = @top
while tmp.next
tmp = tmp.next
end
tmp.next = Node.new(x)
else
@top = Node.new(x)
end
end
def showAll()
ary = Array.new
tmp = @top
while tmp.next
ary << tmp.data
tmp = tmp.next
end
ary << tmp.data
return ary
end
def size()
if @top
tmp = @top
i = 1
while tmp.next
i +=1
tmp = tmp.next
end
else
i = 0
end
return i
end
def empty()
return @top.nil?
end
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
instructor1 = User.create! email: "olivier@nimbl3.com",
first_name: "Olivier",
last_name: "Robert",
citizen_id: "12345678",
password: "nimbl3",
password_confirmation: "nimbl3",
department_name: "Nimbl3",
instructor_id: "87654321",
role: "instructor"
instructor2 = User.create! email: "fkfikrikarim@gmail.com",
first_name: "Fikri",
last_name: "Karim",
citizen_id: "10416005",
password: "NARUTO",
password_confirmation: "NARUTO",
department_name: "Microbiology yay",
instructor_id: "16116093",
role: "instructor"
student1 = User.create! email: "kratae@gmail.com",
first_name: "Kratae",
last_name: "Rsiam",
citizen_id: "84419957",
student_id: "68883848",
password: "nimbl3",
password_confirmation: "nimbl3",
role: "student"
student2 = User.create! email: "palmy@gmail.com",
first_name: "Palmy",
last_name: "Hand",
citizen_id: "29742039",
student_id: "85364979",
password: "nimbl3",
password_confirmation: "nimbl3",
role: "student"
student3 = User.create! email: "Shen@gmail.com",
first_name: "Shen",
last_name: "Chia-Yi",
citizen_id: "37234749",
student_id: "71902308",
password: "nimbl3",
password_confirmation: "nimbl3",
role: "student"
student4 = User.create! email: "nattasha@gmail.com",
first_name: "Nattasha",
last_name: "Nauljam",
citizen_id: "39349363",
student_id: "51006564",
password: "nimbl3",
password_confirmation: "nimbl3",
role: "student"
student5 = User.create! email: "somchai@gmail.com",
first_name: "Somchai",
last_name: "Nan",
citizen_id: "11529265",
student_id: "86392057",
password: "nimbl3",
password_confirmation: "nimbl3",
role: "student"
student6 = User.create! email: "somsak@gmail.com",
first_name: "Somsak",
last_name: "Fah",
citizen_id: "79448469",
student_id: "93886838",
password: "nimbl3",
password_confirmation: "nimbl3",
role: "student"
student7 = User.create! email: "prasert@gmail.com",
first_name: "Prasert",
last_name: "Nan",
citizen_id: "22253660",
student_id: "62433022",
password: "nimbl3",
password_confirmation: "nimbl3",
role: "student"
group1 = Group.create! name: "Thaiband 🇹🇭",
project: "Create a catchy music video",
submission: "https://www.youtube.com/watch?v=y6120QOlsfU",
score: "100"
group1.users<<(student1)
group1.users<<(student2)
group2 = Group.create! name: "ภาพยนตร์ที่ฉันรู้",
project: "Search a movie that you think shows best side of humanity",
submission: "www.imdb.com/title/tt0050083/"
group2.users<<(student3)
group2.users<<(student4)
group3 = Group.create! name: "ฉันไม่รู้ว่าการแปลถูกต้องหรือไม่"
group3.users<<(student5)
group4 = Group.create! name: "Group #4"
|
# frozen_string_literal: true
# Challenge
# The method sqrt takes in one square number.
# Fill the method sqrt_recursive that returns the square root of a given number.
# Do not use any built in methods for calculating the square-root and don't try searching through all the numbers. Instead, use a binary-style search to home in on the actual square root.
# (To make it simpler, the input will just contain square numbers.)
# Examples
# puts sqrt(25)
# # => 5
# puts sqrt(7056)
# # => 84
def sqrt(number)
sqrt_recursive(number, 0, number)
end
def sqrt_recursive(number, min_interval, max_interval)
midpoint = (min_interval + max_interval) / 2
if midpoint * midpoint == number
midpoint
elsif midpoint * midpoint > number
sqrt_recursive(number, min_interval, midpoint - 1)
else
sqrt_recursive(number, midpoint + 1, max_interval)
end
end
puts sqrt(25)
puts sqrt(7056)
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
require 'open-uri'
require 'nokogiri'
require 'faker'
puts "Erase all User data"
User.destroy_all
number_of_users = 30
num_of_stroller = 80
firstname = []
lastname = []
address = []
File.readlines('db/seed_data/firstname.txt').each do |line|
firstname << line.chomp
end
File.readlines('db/seed_data/lastname.txt').each do |line|
lastname << line.chomp
end
File.readlines('db/seed_data/address.txt').each do |line|
address << line.chomp
end
User.create!(
email: "test@test.com",
first_name: firstname.sample.capitalize,
last_name: lastname.sample.upcase,
phone: Faker::PhoneNumber.cell_phone,
address: "#{address.sample} France",
password: '123456',
password_confirmation: '123456',
bio: Faker::Quote.most_interesting_man_in_the_world,
)
number_of_users.times do
print "."
User.create!(
email: Faker::Internet.email,
first_name: firstname.sample.capitalize,
last_name: lastname.sample.upcase,
phone: Faker::PhoneNumber.cell_phone,
address: "#{address.sample} France",
password: 'secret',
password_confirmation: 'secret',
bio: Faker::Quote.most_interesting_man_in_the_world,
)
end
puts ""
puts "Erase all Item data"
Item.destroy_all
category = [ "2 places", "3 places", "3 roues", "Bagage cabine", "Canne" ]
tag =["Stylée", "Maniable", "Esthetique", "Sportive", "Citadine", "Polyvalente",
"Tout-terrain", "0-6 mois", "6+ mois", "Bagage cabine"]
#Scrape a stroller title:
url = "https://www.natalys.com/balade/poussette?srule=price-high-to-low&start=0&sz=#{num_of_stroller}"
html_file = open(url).read
html_doc = Nokogiri::HTML(html_file)
html_doc.search('.link').each do |element|
print '.'
e = element.text.strip.split(':')
Item.create!(
title: e[0],
category: category.sample,
tag: tag.sample,
description: Faker::Lorem.paragraph(sentence_count: 5),
price_in_cents: rand(500..1500),
address: "#{address.sample} France",
availability: [true, false].sample,
start_date: Faker::Date.in_date_period(year: 2019, month: rand(1..12)),
end_date: Faker::Date.in_date_period(year: 2020, month: rand(1..12)),
user: User.all.sample,
)
end
#correct bad Geolocalisation
bad_geoloc = Item.where(longitude: nil)
bad_geoloc.each do |item|
item.destroy
end
|
class CreateRequisicoes < ActiveRecord::Migration
def self.up
create_table :requisicoes do |t|
t.string :pedido, :null => false
t.datetime :data, :null => false
t.string :estado, :null => false
t.boolean :emergencial, :null => false
t.boolean :transporte, :null => false
t.references :unidade
t.references :usuario, :null => false
t.references :empresa, :null => false
t.references :departamento
t.timestamps
end
end
def self.down
drop_table :requisicoes
end
end
|
class Profile < ApplicationRecord
has_attachment :avatar, accept: [:jpg, :png, :gif]
has_many :posts, dependent: :destroy
belongs_to :user
def full_name
"#{first_name} #{last_name}"
end
end
|
# encoding: utf-8
module HerokuCloudBackup
VERSION = "0.3.0"
end
|
require_relative '../automated_init'
context "Error Data Equality" do
test "When attributes are equal" do
error_data_1 = ErrorData::Controls::ErrorData.example
error_data_2 = ErrorData::Controls::ErrorData.example
assert(error_data_1 == error_data_2)
end
end
|
class QuestionsController < ApplicationController
def new
@book = Book.find_by_id(params[:book_id])
render :new
end
def create
params[:question][:book_id] = params[:book_id]
@question = current_user.questions.new(params[:question])
if @question.save
flash[:alert] = ["Question created!"]
redirect_to book_url(@question.book)
else
flash[:error] = @question.errors.full_messages
redirect_to book_url(@question.book)
end
end
def show
@question = Question.find_by_id(params[:id])
render :show
end
def edit
@question = Question.find_by_id(params[:id])
render :edit
end
def update
@question = Question.find_by_id(params[:id])
if @question.update_attributes(params[:question])
flash[:alert] = ["Question Updated"]
redirect_to question_url(@question)
else
flash[:error] = ["ERROR: Question update failed."]
redirect_to question_url(@question)
end
end
def destroy
end
end
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'OmniauthCallbacksController', type: :request do
describe 'Oauth' do
it 'should register a new client', test: true do
expect { login }.to change(ActiveStorage::Attachment, :count).by(1)
expect(User.all.count).to eq(1)
expect(response.status).to eq 200
end
it 'should sign-in an existing client' do
FactoryBot.create(:user, banned: false, uid: 1000, provider: 'marvin', two_factor: false)
login
expect(response.status).to eq 200
end
it 'should promote owner, admin' do
ENV['P42NG_OWNER_UID'] = '42'
login(ENV['P42NG_OWNER_UID'])
expect(response.status).to eq 200
expect(User.first.admin?).to eq(true)
end
it 'should not sign-in a banned user' do
FactoryBot.create(:user, banned: true, uid: 1000, provider: 'marvin', two_factor: false)
login
expect(response.status).to eq 403
end
it 'should not sign-in a banned user with 2FA' do
FactoryBot.create(:user, banned: true, uid: 1000, provider: 'marvin', two_factor: true)
login
expect(response.status).to eq 403
end
it 'should not sign-in a user with 2FA' do
FactoryBot.create(:user, banned: false, uid: 1000, provider: 'marvin', two_factor: true, two_factor_code: '1234')
ActiveJob::Base.queue_adapter = :test
expect do
login
end.to have_enqueued_job(TwoFactorResetJob)
expect(response.status).to eq 200
end
end
def login(uid = '1000')
Rails.application.env_config['devise.mapping'] = Devise.mappings[:user] # If using Devise
Rails.application.env_config['omniauth.auth'] = OmniAuth.config.mock_auth[:marvin]
valid_marvin_login_setup(uid)
get '/auth/marvin', params: {
auth_origin_url: 'http://www.example.com/'
}
follow_all_redirects!
end
def valid_marvin_login_setup(uid)
if Rails.env.test?
OmniAuth.config.test_mode = true
OmniAuth.config.mock_auth[:marvin] = OmniAuth::AuthHash.new({
provider: 'marvin',
uid: uid,
info: {
nickname: 'herve',
email: 'test@example.com',
image: 'https://cdn.42.fr/toto/'
},
credentials: {
token: '123456',
expires_at: Time.now + 1.week
},
extra: {
raw_info: {
}
}
})
end
end
def follow_all_redirects!
follow_redirect! while response.status.to_s =~ /^3\d{2}/
end
end
|
module Api
class ServicesController < ApiController
before_action :authenticate_resource
def index
render json: ListServiceSerializer.new(services: BaseService.all).to_json
end
end
end
|
require './template_method_pattern/template.rb'
class HTMLMenu < Menu #inherits from the basic menu class, which contains the menu template
#contains output for HTML formatting of the menu
def output_start
puts '<html>'
end
def output_head
puts '<head>'
puts "<title> Menu for #{Time.now} </title>"
puts '</head>'
end
def output_body_start
puts '<body>'
end
def output_line(line)
puts "<p> #{line} </p>"
end
def output_body_end
puts '</body>'
end
def output_end
puts '</html>'
end
end |
class Review < ActiveRecord::Base
validates :rating, presence: true
validates :description, presence: true
validates :reservation_id, presence: true
validate :reservation_accepted
belongs_to :reservation
belongs_to :guest, :class_name => "User"
def reservation_accepted
if !(reservation && self.reservation.status=='accepted' && Date.today > self.reservation.checkout)
errors.add(:rating, "You can't leave a review(yet)")
end
end
end
|
# frozen_string_literal: true
require 'bolt_command_helper'
test_name "C100548: \
bolt script run should execute script on remote hosts via ssh" do
extend Acceptance::BoltCommandHelper
ssh_nodes = select_hosts(roles: ['ssh'])
skip_test('no applicable nodes to test on') if ssh_nodes.empty?
script = "C100548.sh"
step "create script on bolt controller" do
create_remote_file(bolt, script, <<-FILE)
#!/bin/sh
echo "$* from $(hostname)"
FILE
end
step "execute `bolt script run` via SSH" do
bolt_command = "bolt script run #{script} hello"
flags = { '--targets' => 'ssh_nodes' }
result = bolt_command_on(bolt, bolt_command, flags)
ssh_nodes.each do |node|
message = "Unexpected output from the command:\n#{result.cmd}"
assert_match(/hello from #{node.hostname.split('.')[0]}/, result.stdout, message)
end
end
end
|
class ParticularDiscount < ActiveRecord::Base
belongs_to :particular_payment
named_scope :for_particular_payments, lambda { |tran_id| {
:conditions => ["particular_payments.finance_transaction_id = ?", tran_id],
:joins => :particular_payment} }
end
|
require 'spec_helper'
describe SurveysController do
let(:user) { create(:user) }
let(:admin) { create(:admin) }
# create a mock model of a survey
# (will raise an error if any methods are called on it)
# this will ensure that nothing is making it past authorization
let(:survey) { mock_model(Survey, id: 1)}
context "standard users" do
before { sign_in(:user, user) }
actions = { new: :get,
create: :post,
edit: :get,
update: :put,
destroy: :delete }
actions.each do |action, method|
it "cannot access the #{action} action" do
send(method, action, id: survey.id)
response.should redirect_to(new_user_session_path)
end
end
end
describe "request for missing survey" do
context "anonymous users" do
before { get :show, id: "not-here" }
specify { response.should redirect_to(new_user_session_path) }
message = "You need to sign in or sign up before continuing."
specify { flash[:alert].should == message }
end
context "regular users" do
before { get :show, id: "not-here" }
specify { response.should redirect_to(new_user_session_path) }
message = "You need to sign in or sign up before continuing."
specify { flash[:alert].should == message }
end
context "admin users" do
before do
sign_in(:user, admin)
get :show, id: "not-here"
end
specify { response.should redirect_to(surveys_path) }
message = "The survey you were looking for could not be found."
specify { flash[:alert].should == message }
end
end
end
|
# frozen_string_literal: true
class DiscordMessageShim
extend Memoist
def initialize(event, pattern, plug)
@event = event
@pattern = pattern[0]
@opts = pattern[1]
@plug = plug
end
def inner
@event
end
def message
@event.message.content
end
def params
groups = message.match(@pattern).captures
if groups.empty?
[self, param]
else
[self, *groups]
end
end
def param
message.sub(/^\s*#{Rogare.prefix}#{@plug[:command]}/i, '')
end
def reply(message)
@event.respond message
end
def debugly(*things)
@event.respond things.map { |thing| "`#{thing.inspect}`" }.join("\n")
end
def user
Rogare.user_cache.getset(@event.message.author.id) do
User.create_from_discord(@event.message.author)
end
end
def channel
DiscordChannelShim.new @event.channel
end
memoize :user, :channel
end
class DiscordChannelShim
def initialize(chan)
@chan = chan
end
def inner
@chan
end
def send_msg(msg)
return if @chan.voice?
@chan.send msg
end
def users
case type
when :public
@chan.server.members.map { |u| User.from_discord u }
else
[]
end
end
# Practically, channels other than public aren't supported
def type
case @chan.type
when 0
:public
when 1
:private
when 2
:voice
when 3
:group
end
end
def name
@chan.name
end
def to_s
if @chan.server
@chan.server.id.to_s
else
'PM'
end + '/' + @chan.id.to_s
end
def pretty
"#{server.name.downcase.tr(' ', '~')}/#{name}"
end
def server
@chan.server
end
end
|
class Htop < DebianFormula
homepage 'http://htop.sourceforge.net/'
url 'http://downloads.sourceforge.net/project/htop/htop/0.9/htop-0.9.tar.gz'
md5 '7c5507f35f363f3f40183a2ba3c561f8'
name 'htop'
section 'utils'
version '0.9+github1'
description 'an interactive process viewer for Linux'
build_depends 'libncurses-dev'
depends 'libncurses5'
end
|
require 'yaml'
require 'base_screen.rb'
require 'log.rb'
require 'constants.rb'
include Constants
class Meditation < BaseScreen
def initialize
userdata = File.join(DATA_PATH,"userdata.yml")
@loaded_data = YAML.load_file(userdata)
end
def start!
setup
meditate
reflect
save_data
end
def setup
# Setup before the action session – sets duration, displays instruction
# and confirms the start of the session
proceed = false
until proceed do
blank 2
line
pretty_puts 'Desired Length of Meditation (minutes): '
blank
action = get_action.to_i # CHANGE TO MINUTES by * 60
blank SCREEN_GAP
if action > 0
@duration = action * DURATION_MODIFIER
proceed = true
else
invalid_input
end
end
proceed = false
bindings = @loaded_data['options']['binding']
until proceed do
blank 2
line
title_puts 'Instructions'
blank
pretty_puts '1. Type "Y" to start the meditation session.'
pretty_puts '2. Once the session begins and you notice that you have been distracted,'
pretty_puts "1. Type \"1\" to indicate that you have been distracted by #{bindings[0]}.", true
pretty_puts "2. Type \"2\" to indicate that you have been distracted by #{bindings[1]}.", true
pretty_puts "3. Type \"3\" to indicate that you have been distracted by #{bindings[2]}.", true
pretty_puts "4. Type \"4\" to indicate that you have been distracted by #{bindings[3]}.", true
pretty_puts "5. Type \"5\" to indicate that you have been distracted by #{bindings[4]}.", true
pretty_puts '6. Type "Quit" to quit the session any time. All stats will be saved.', true
pretty_puts "3. When the session ends, there will be an
optional note that can be used to
record the meditation session's details."
pretty_puts "4. Data from step 2 and 3 will be saved to be displayed in \"Stats\" section
of the app
for your viewing later."
blank
action = get_action
blank SCREEN_GAP
if action == 'y'
proceed = true
else
invalid_input
end
end
end
def meditate
# Meditation session thread that keeps looping
session = Thread.new do
# screen for meditation
simple_on = @loaded_data['options']['simple'] == 'true'
dm = @loaded_data['options']['dm']
@distractions = @loaded_data['options']['binding']
@distract_counts = [0,0,0,0,0]
top_distraction = ''
# Set start time in the beginning
start_time = Time.now
min_delta = 0
last_action = 0
top_distraction = "________"
curr_distraction = "________"
invalid_flag = false
# Until curr_time = start_time + duration, loop
until min_delta >= @duration do
# update the screen
blank SCREEN_GAP
line
blank
if simple_on
blank
else
title_puts dm
end
blank 14
if simple_on
blank 2
else
pretty_puts "Watch for #{top_distraction} today."
pretty_puts "Regained awareness from #{curr_distraction}!"
end
if invalid_flag
invalid_input
invalid_flag = false
else
blank 3
end
line
last_action = get_action.to_i
#handles user input
case last_action
when 1
@distract_counts[0]+=1
curr_distraction = @distractions[0]
when 2
@distract_counts[1]+=1
curr_distraction = @distractions[1]
when 3
@distract_counts[2]+=1
curr_distraction = @distractions[2]
when 4
@distract_counts[3]+=1
curr_distraction = @distractions[3]
when 5
@distract_counts[4]+=1
curr_distraction = @distractions[4]
else
invalid_flag = true
end
# update top distraction
d_index = 0
for i in 0...@distract_counts.length do
if @distract_counts[d_index] < @distract_counts[i]
d_index = i
end
end
top_distraction = @distractions[d_index]
# update elapsed time
min_delta = ((Time.now - start_time)/60).to_i
end
end
# Timer thread to end the meditation session
timer = Thread.new do
sleep @duration # *60
session.kill
blank SCREEN_GAP
blank 11
title_puts "Your #{@duration} minute session has finished."
title_puts "Continue walking the path to enlightenment."
blank 11
sleep 5
blank SCREEN_GAP
end
timer.join
end
def reflect
# Acquire reflection notes from the user
line
title_puts "Optional Reflection Notes"
line
blank 17
pretty_puts 'Describe in detail the most prominent distraction for this session.'
pretty_puts 'Type the enter key to skip this question.'
blank
@q1 = get_action
line
title_puts "Optional Reflection Notes"
line
blank 17
pretty_puts 'Describe your mind\'s predominant reaction upon being distracted.'
pretty_puts 'Type the enter key to skip this question.'
blank
@q2 = get_action
line
title_puts "Optional Reflection Notes"
line
blank 17
pretty_puts 'Describe any other relevant details you\'d like to note.'
pretty_puts 'Type the enter key to skip this question.'
blank
@q3 = get_action
blank SCREEN_GAP
end
def save_data
# If doesn't exist, add title / count for a source of distraction to a hash
stats_hash = @loaded_data['data']['contents']
for i in 0...@distract_counts.length do
key = @distractions[i]
if stats_hash.has_key? key
stats_hash[key] += @distract_counts[i]
else
stats_hash[key] = @distract_counts[i]
end
end
# Add @duration to min_meditated and update streak
@loaded_data['min_meditated'] += @duration
last_used_date = @loaded_data['data']['last_used']
streak_refresh = @loaded_data['data']['streak_refresh']
today = Time.local(Time.now.year, Time.now.month, Time.now.day)
if today - last_used_date < 60*60*24*2 && today >= streak_refresh
@loaded_data['streak'] += 1
@loaded_data['data']['streak_refresh'] += 60*60*24
@loaded_data['data']['last_used'] = today
end
@loaded_data['data']['last_used'] = today
# Create a Log item based on the session's details and convert the hash generated to YAML
log = Log.new(@duration, @distractions, @distract_counts, @q1, @q2, @q3)
@loaded_data['data']['session_info'] << log.to_hash
# Convert hash to YAML and write the file
File.open(File.join(DATA_PATH,"userdata.yml"), 'w') do |f|
f.puts @loaded_data.to_yaml
end
end
end |
class Supply < ActiveRecord::Base
belongs_to :game
belongs_to :card_pile, dependent: :destroy
has_many :piles, through: :card_pile
has_many :cards, through: :piles
def name
return card_pile.name
end
end
|
class RoleConstraint
def initialize(*roles)
@roles = roles
end
def matches?(request)
@roles.include?(current_user)
end
end |
class Admin::BaseController < ApplicationController
before_action :authorized?
def authorized?
if current_user.nil? || !current_user.admin?
flash[:warning] = "Sorry but you are not authorized to view that page"
log_out
redirect_to '/'
end
else
true
end
end
|
# frozen_string_literal: true
module AsyncHelpers
# Wait for block to return true of raise error
def wait(timeout = 1)
until yield
sleep 0.1
timeout -= 0.1
raise "Timeout error" unless timeout > 0
end
end
def concurrently(enum)
enum.map { |*x| Concurrent::Future.execute { yield(*x) } }.map(&:value!)
end
end
|
require 'test_helper'
class FreeBusyAggregateTest < ActiveSupport::TestCase
context 'aggregating a single RiCal Calendar with a single event' do
setup do
@calendar = RiCal.Calendar do |cal|
cal.event do |evt|
evt.summary = 'Private Stuff'
evt.description = "I really don't want people to know about this"
evt.dtstart = 2.days.from_now
evt.dtend = (2.days + 2.hours).from_now
evt.location = 'Nowhere you need to know about'
end
end
@aggregate = FreeBusyAggregate.new(@calendar).aggregate
end
should 'yield an aggregate calendar with one event' do
assert_equal 1, @aggregate.events.size
end
should 'yield an aggregate with a matching event entry' do
event = @calendar.events.first
freebusy = @aggregate.events.first
assert_equal event.start_time, freebusy.dtstart
assert_equal event.finish_time, freebusy.dtend
end
should 'not reveal the details of the original event' do
event = @calendar.events.first
assert !(@aggregate.to_s.include?(event.summary))
assert !(@aggregate.to_s.include?(event.description))
assert !(@aggregate.to_s.include?(event.location))
end
end
context 'aggregating several RiCal calendars, each with a single event' do
setup do
@parties = RiCal.Calendar do |cal|
cal.event do |evt|
evt.summary = "Vishal's Birthday Party"
evt.description = "Petting zoo FTW!"
evt.dtstart = 5.days.from_now
evt.dtend = (5.days + 5.hours).from_now
evt.location = "Vishal's House"
end
end
@dates = RiCal.Calendar do |cal|
cal.event do |evt|
evt.summary = "Dinner with Sue"
evt.description = "Reminder: Sue loves caramel"
evt.dtstart = 6.days.from_now
evt.dtend = (6.days + 3.hours).from_now
evt.location = "Three Monkey Island"
end
end
@aggregate = FreeBusyAggregate.new(@parties, @dates).aggregate
end
should 'yield a calendar with two events' do
assert_equal 2, @aggregate.events.size
end
should 'yield matching events' do
freebusy_entries = @aggregate.events
(@parties.events + @dates.events).each do |event|
assert(freebusy_entries.find do |fb|
fb.dtstart.to_datetime == event.dtstart.to_datetime &&
fb.dtend.to_datetime == event.dtend.to_datetime
end.present?, "Could not find #{event.summary} in the aggregate feed.")
end
end
should 'not reveal the details of the original events' do
aggregate = @aggregate.to_s
assert !(aggregate.include?(@parties.events.first.summary))
assert !(aggregate.include?(@parties.events.first.description))
assert !(aggregate.include?(@parties.events.first.location))
assert !(aggregate.include?(@dates.events.first.summary))
assert !(aggregate.include?(@dates.events.first.description))
assert !(aggregate.include?(@dates.events.first.location))
end
end
end
|
module Apress
module Images
# Public: джоб нарезки изображений
#
# В случае падения срабатывает retry стратегия.
# Периоды последующих попыток запуститься:
# (@backoff_strategy[номер попытки] * <случайное число от 1 до @retry_delay_multiplicand_max>) в сек.
class ProcessJob
extend Resque::Plugins::ExponentialBackoff
@backoff_strategy = [1.minute, 5.minutes, 15.minutes, 30.minutes]
@retry_delay_multiplicand_max = 2.0
def self.queue
:images
end
def self.non_online_queue
:non_online_images
end
def self.perform(image_id, class_name, opts = {})
options = opts.with_indifferent_access
model = class_name.camelize.constantize
image = model.where(id: image_id).first!
image.assign_attributes(options[:assign_attributes]) if options[:assign_attributes]
image.img.process_delayed! if image.processing?
end
ActiveSupport.run_load_hooks(:'apress/images/process_job', self)
end
end
end
|
class GameSuggester
def initialize(rating, ratings)
@rating = rating
@ratings = ratings
@rand = Random.new(Time.zone.now.beginning_of_day.to_i)
end
def suggest
return if !@rating || @ratings.empty?
closest = @ratings.select{|r| r.id != @rating.id }.sort_by {|r| (@rating.low_rank - r.low_rank).abs }
closest.first(5).sample(random: @rand)
end
end
|
require 'spec_helper'
require 'csv_writer'
describe CSVWriter do
let(:user) { create(:user) }
let(:writer) { CSVWriter.new(user.id) }
describe "#generate_csv" do
it "generates a csv for a user with readings" do
reading1 = create(:reading, user: user)
reading2 = create(:reading, :violation, user: user, humidity: 43.2452)
generated_csv = writer.generate_csv
time = "%l:%M%p"
date = "%m/%d/%Y"
expect(generated_csv).to include("TIME,DATE,TEMP INSIDE,HUMIDITY INSIDE (%),TEMP OUTSIDE,TEMP OF HOT WATER,NOTES")
expect(generated_csv).to include("#{reading1.created_at.strftime(time)},#{reading1.created_at.strftime(date)},#{reading1.temp},,#{reading1.outdoor_temp},,")
expect(generated_csv).to include("#{reading2.created_at.strftime(time)},#{reading2.created_at.strftime(date)},#{reading2.temp},43.2,#{reading2.outdoor_temp},,violation")
end
it "returns a filename" do
expect(writer.filename).to eq("#{user.last_name}.csv")
end
it "generates a csv for a user without readings" do
generated_csv = writer.generate_csv
expect(generated_csv).to include("TIME,DATE,TEMP INSIDE,HUMIDITY INSIDE (%),TEMP OUTSIDE,TEMP OF HOT WATER,NOTES")
end
end
end
|
class ArtworkShare < ApplicationRecord
validates :artwork_id, presence: true, uniqueness: { scope: :viewer_id, message: "Viewer may only be shared this artwork once" }
validates :viewer_id, presence: true
belongs_to :artwork,
foreign_key: :artwork_id,
class_name: :Artwork
belongs_to :viewer,
foreign_key: :viewer_id,
class_name: :User
end
|
class AddWorkstationIdsToReceipts < ActiveRecord::Migration
def change
add_column :receipts, :workstation_ids, :string
end
end
|
class Point
attr_reader :x, :y
def initialize(x, y)
@x, @y = x, y
end
def mongoize
[ x, y ]
end
class << self
def demongoize(object)
Point.new(object[0], object[1])
end
def evolve(object)
if object.is_a?(Point)
[ object.x, object.y ]
else
object
end
end
end
end
|
class Study < ActiveRecord::Base
acts_as_cached(:version => 1, :expires_in => 1.week)
attr_accessible :title
belongs_to :user
belongs_to :subject
has_and_belongs_to_many :entries
has_many :resources, as: :resource_host, dependent: :destroy
def entries_count
CACHE.fetch(entries_count_cache_key) { self.entries.length }
end
def entries_count_cache_key
"/study_entries_count/#{self.id}/"
end
end
|
module OpsWorks
module ShellOut
extend self
# This would be your new default timeout 3Hrs.
DEFAULT_OPTIONS = { timeout: 10 }
def shellout(command, options = {})
cmd = Mixlib::ShellOut.new(command, DEFAULT_OPTIONS.merge(options))
cmd.run_command
cmd.error!
[cmd.stderr, cmd.stdout].join("\n")
end
end
end
|
# A Ruby implementation of Joshua Bloch's
# [typesafe enum pattern](http://www.oracle.com/technetwork/java/page1-139488.html#replaceenums)
module TypeIsEnum
# Base class for typesafe enum classes.
class Enum
include Comparable
class << self
# Returns an array of the enum instances in declaration order
# @return [Array<self>] All instances of this enum, in declaration order
def to_a
as_array.dup
end
# Returns the number of enum instances
# @return [Integer] the number of instances
def size
as_array ? as_array.length : 0
end
# Iterates over the set of enum instances
# @yield [self] Each instance of this enum, in declaration order
# @return [Array<self>] All instances of this enum, in declaration order
def each(&block)
to_a.each(&block)
end
# Iterates over the set of enum instances
# @yield [self, Integer] Each instance of this enum, in declaration order,
# with its ordinal index
# @return [Array<self>] All instances of this enum, in declaration order
def each_with_index(&block)
to_a.each_with_index(&block)
end
# Iterates over the set of enum instances
# @yield [self] Each instance of this enum, in declaration order
# @return [Array] An array containing the result of applying `&block`
# to each instance of this enum, in instance declaration order
def map(&block)
to_a.map(&block)
end
# Looks up an enum instance based on its key
# @param key [Symbol] the key to look up
# @return [self, nil] the corresponding enum instance, or nil
def find_by_key(key)
by_key[key]
end
# Looks up an enum instance based on its ordinal
# @param ord [Integer] the ordinal to look up
# @return [self, nil] the corresponding enum instance, or nil
def find_by_ord(ord)
return nil if ord < 0 || ord > size
as_array[ord]
end
private
def add(key, *args, &block)
fail TypeError, "#{key} is not a symbol" unless key.is_a?(Symbol)
obj = new(*args)
obj.instance_variable_set :@key, key
obj.instance_variable_set :@ord, size
class_exec(obj) do |instance|
register(instance)
instance.instance_eval(&block) if block_given?
end
end
def by_key
@by_key ||= {}
end
def as_array
@as_array ||= []
end
def valid_key(instance)
key = instance.key
if find_by_key(key)
warn("ignoring redeclaration of #{name}::#{key} (source: #{caller[4]})")
nil
else
key
end
end
def register(instance)
key = valid_key(instance)
return unless key
const_set(key.to_s, instance)
by_key[key] = instance
as_array << instance
end
end
# The symbol key for the enum instance
# @return [Symbol] the key
attr_reader :key
# The ordinal of the enum instance, in declaration order
# @return [Integer] the ordinal
attr_reader :ord
# Compares two instances of the same enum class based on their declaration order
# @param other [self] the enum instance to compare
# @return [Integer, nil] -1 if this value precedes `other`; 0 if the two are
# the same enum instance; 1 if this value follows `other`; `nil` if `other`
# is not an instance of this enum class
def <=>(other)
ord <=> other.ord if self.class == other.class
end
# Generates a Fixnum hash value for this enum instance
# @return [Fixnum] the hash value
def hash
@hash ||= begin
result = 17
result = 31 * result + self.class.hash
result = 31 * result + ord
result.is_a?(Fixnum) ? result : result.hash
end
end
def name
key.to_s
end
def to_s
"#{self.class}::#{key} [#{ord}]"
end
end
end
|
Puppet::Type.newtype(:gce_disk) do
desc 'creates a persistent disk image'
ensurable
newparam(:name, :namevar => true) do
desc 'name of disk to create'
validate do |v|
unless v =~ /[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?/
raise(Puppet::Error, "Invalid disk name: #{v}")
end
end
end
newparam(:zone) do
desc 'zone where this disk lives'
end
newparam(:size_gb) do
desc 'size in GB for disk'
end
newparam(:description) do
desc 'description of disk'
end
newparam(:source_image) do
desc 'boot image to use when creating disk'
end
newparam(:wait_until_complete) do
desc 'wait until disk is complete'
end
newparam(:disk_type)
validate do
if self[:ensure] == :present
raise(Puppet::Error, 'Must specify a zone for the disk') unless self[:zone]
end
end
end
|
class BranchesController < ApplicationController
before_action :must_be_admin!, except:[:index, :show]
before_action :set_branch, except: [:index, :create, :new]
def index
@branches = Branch.all.page(params[:page]).per(15)
respond_to do |format|
format.html # index.html.erb
format.json { render json: @branches }
end
end
def show
respond_to do |format|
format.js
format.json { render json: @branch }
end
end
def edit
end
def new
@branch = Branch.new
@branch.build_address
end
def create
@branch = Branch.new(branch_params)
if @branch.save
redirect_to branches_path, flash: {info: 'Branch was successfully created.'}
else
render action: "new"
end
end
def update
if @branch.update_attributes(branch_params)
redirect_to branches_path, flash: {info: 'Branch was successfully updated.'}
else
render action: "edit"
end
end
def destroy
@branch.destroy
redirect_to branches_path, flash: {info: "Branch was successfully deleted."}
end
private
def set_branch
@branch = Branch.find(params[:id])
end
def branch_params
params.require(:branch).permit(:name, :description, address_attributes: [
:number, :street, :city, :province, :country, :postal_code])
end
def must_be_admin!
authenticate_user!
redirect_to root_path, alert:"You do not have the required permissions to access this content." unless current_user.admin?
end
end
|
class Madden18::DefensiveTackleScorer < BaseScorer
def score
case @style
when '43'
# In a 4-3 scheme your tackles primary job is to stuff runs up the middle
# but they are also expected to put pressure on the QB.
# On top of strong run stuffing stats, speed and strength are valued highly
# as well as good power moves to bull-rush offensive linemen.
(@card.block_shedding * 1.1) +
(@card.tackle * 1.1) +
(@card.pursuit * 1.0) +
(@card.strength * 1.1) +
(@card.speed * 1.1) +
(@card.acceleration * 1.0) +
(@card.power_moves * 1.0) +
(@card.awareness * 1.0) +
(@card.hit_power * 1.0) +
(@card.play_recognition * 1.0)
when '34'
# The nose tackle has an essential role in a 3-4 scheme and that is
# to clog up the middle of the line by requiring multiple offensive linemen
# to block him. By requiring the center and one or both of the guards
# to block him, a single player can shut down the run up the middle and
# open up gaps for your linebackers and safeties to quickly
# get into the backfield and pressure the QB or stop the running back
# behind the line. Weight is an essential attribute next to run stuffing stats,
# and your nose tackles should be as heavy as possible to ensure
# they attract double teams.
(@card.weight_in_pounds * 1.2)
(@card.strength * 1.1) +
(@card.block_shedding * 1.1) +
(@card.tackle * 1.1) +
(@card.pursuit * 1.0) +
(@card.speed * 1.0) +
(@card.acceleration * 1.0) +
(@card.power_moves * 1.0) +
(@card.awareness * 1.0) +
(@card.hit_power * 1.0) +
(@card.play_recognition * 1.0)
else
0.0
end
end
end
|
module Tramway::Admin
class RecordsController < ApplicationController
def index
@records = decorator_class.decorate model_class.active.send(params[:scope] || :all).page params[:page]
end
def show
@record = decorator_class.decorate model_class.active.find params[:id]
end
def edit
@record_form = form_class.new model_class.active.find params[:id]
end
def update
@record_form = form_class.new model_class.active.find params[:id]
if @record_form.submit params[:record]
redirect_to params[:redirect] || record_path(@record_form.model)
else
render :edit
end
end
def new
@record_form = form_class.new model_class.new
end
def create
@record_form = form_class.new model_class.new
if @record_form.submit params[:record]
redirect_to params[:redirect] || record_path(@record_form.model)
else
render :new
end
end
def destroy
record = model_class.active.find params[:id]
record.remove
redirect_to records_path
end
end
private
# FIXME replace to module
def record_path(*args, **options)
super args, options.merge(model: params[:model])
end
def edit_record_path(*args, **options)
super args, options.merge(model: params[:model])
end
def new_record_path(*args, **options)
super args, options.merge(model: params[:model])
end
def records_path(*args, **options)
super args, options.merge(model: params[:model])
end
end
|
class AddTimeToExercise < ActiveRecord::Migration[5.2]
def change
add_column :exercises, :timed_exercise, :boolean, default: false
add_column :exercises, :time_by_minutes, :integer, default: 30
end
end
|
require 'spec_helper'
describe Shoulda::Matchers::ActionController::SetSessionMatcher do
context 'a controller that sets a session variable' do
it 'accepts assigning to that variable' do
expect(controller_with_session(var: 'hi')).to set_session(:var)
end
it 'accepts assigning to that variable with specifying the key by string' do
expect(controller_with_session(var: 'hi')).to set_session('var')
end
it 'accepts assigning the correct value to that variable' do
expect(controller_with_session(var: 'hi')).to set_session(:var).to('hi')
end
it 'rejects assigning another value to that variable' do
expect(controller_with_session(var: 'hi')).not_to set_session(:var).to('other')
end
it 'rejects assigning to another variable' do
expect(controller_with_session(var: 'hi')).not_to set_session(:other)
end
it 'accepts assigning nil to another variable' do
expect(controller_with_session(var: 'hi')).to set_session(:other).to(nil)
end
it 'rejects assigning nil to that variable' do
expect(controller_with_session(var: 'hi')).not_to set_session(:var).to(nil)
end
it 'accepts assigning nil to cleared variable' do
expect(controller_with_session(var: nil)).to set_session(:var).to(nil)
end
it 'accepts assigning false to that variable' do
expect(controller_with_session(var: false)).to set_session(:var).to(false)
end
it 'rejects assigning false to other variable' do
expect(controller_with_session(var: false)).not_to set_session(:other).to(false)
end
it 'rejects assigning false to a variable with value' do
expect(controller_with_session(var: 'hi')).not_to set_session(:other).to(false)
end
it 'accepts assigning to the same value in the test context' do
context = stub(expected: 'value')
expect(controller_with_session(var: 'value')).
to set_session(:var).in_context(context).to { expected }
end
it 'rejects assigning to the another value in the test context' do
context = stub(expected: 'other')
expect(controller_with_session(var: 'unexpected')).
not_to set_session(:var).in_context(context).to { expected }
end
it 'accepts assigning nil to another variable in the test context' do
context = stub(expected: nil)
expect(controller_with_session(var: 'hi')).
to set_session(:other).in_context(context).to { expected }
end
it 'rejects assigning nil to that variable in the test context' do
context = stub(expected: nil)
expect(controller_with_session(var: 'hi')).
not_to set_session(:var).in_context(context).to { expected }
end
it 'accepts assigning nil to a cleared variable in the test context' do
context = stub(expected: nil)
expect(controller_with_session(var: nil)).
to set_session(:var).in_context(context).to { expected }
end
it 'accepts assigning false to that variable in the test context' do
context = stub(expected: false)
expect(controller_with_session(var: false)).
to set_session(:var).in_context(context).to { expected }
end
it 'accepts assigning false to other variable in the test context' do
context = stub(expected: false)
expect(controller_with_session(var: false)).
not_to set_session(:other).in_context(context).to { expected }
end
it 'accepts assigning false to other variable in the test context' do
context = stub(expected: false)
expect(controller_with_session(var: 'hi')).
not_to set_session(:var).in_context(context).to { expected }
end
def controller_with_session(session_hash)
build_fake_response do
session_hash.each do |key, value|
session[key] = value
end
end
end
end
end
|
# typed: false
# frozen_string_literal: true
# This file was generated by GoReleaser. DO NOT EDIT.
class Csv2tbl < Formula
desc "`csv2tbl` is tool to convert csv to table."
homepage "https://github.com/takaishi/csv2tbl"
version "0.0.1"
on_macos do
if Hardware::CPU.arm?
url "https://github.com/takaishi/csv2tbl/releases/download/v0.0.1/csv2tbl_0.0.1_darwin_arm64.tar.gz"
sha256 "cb67c1132a73279f5219e48f24b842ef16380489a2e2f89c673f6cfc9de4c41d"
def install
bin.install Dir['csv2tbl']
end
end
if Hardware::CPU.intel?
url "https://github.com/takaishi/csv2tbl/releases/download/v0.0.1/csv2tbl_0.0.1_darwin_amd64.tar.gz"
sha256 "cdc3ad4a572305ca9fd6bd3d9b450e40c7848ced9448167c939462d5e97993c4"
def install
bin.install Dir['csv2tbl']
end
end
end
on_linux do
if Hardware::CPU.intel?
url "https://github.com/takaishi/csv2tbl/releases/download/v0.0.1/csv2tbl_0.0.1_linux_amd64.tar.gz"
sha256 "61e3c7d276be7c2438272ef5945a757a59af5783f053b76180391f057ab07458"
def install
bin.install Dir['csv2tbl']
end
end
if Hardware::CPU.arm? && Hardware::CPU.is_64_bit?
url "https://github.com/takaishi/csv2tbl/releases/download/v0.0.1/csv2tbl_0.0.1_linux_arm64.tar.gz"
sha256 "1ee6a71607b81d2ec2477724d406ff3d1546cb187e35e49df56e9c58f315bdc3"
def install
bin.install Dir['csv2tbl']
end
end
end
test do
system "#{bin}/csv2tbl"
end
end
|
require 'rspec'
require 'recursion_problems'
describe "#sum_recur" do
#Problem 1: You have array of integers. Write a recursive solution to find
#the sum of the integers.
it "returns 0 if blank array" do
sum_recur([]) == 0
end
it "returns the sum of all numbers in array" do
sum_recur([1, 3, 5, 7, 9, 2, 4, 6, 8]).should == 45
end
it "should not modify original array" do
original = [1, 3, 5, 7, 9, 2, 4, 6, 8]
sum_recur(original)
original.should == [1, 3, 5, 7, 9, 2, 4, 6, 8]
end
it "calls itself recursively" do
# this should enforce you calling your method recursively.
should_receive(:sum_recur).at_least(:twice).and_call_original
sum_recur([1, 3, 5, 7, 9, 2, 4, 6, 8])
end
end
describe "#includes?" do
#Problem 2: You have array of integers. Write a recursive solution to
#determine whether or not the array contains a specific value.
it "returns false if target isn't found" do
includes?([1, 3, 5, 7, 9, 2, 4, 6, 8], 11).should == false
end
it "returns true if target isn't found" do
includes?([1, 3, 5, 7, 9, 2, 4, 6, 8], 9).should == true
end
it "should not modify original array" do
original = [1, 3, 5, 7, 9, 2, 4, 6, 8]
includes?(original, 9)
original.should == [1, 3, 5, 7, 9, 2, 4, 6, 8]
end
it "calls itself recursively" do
should_receive(:includes?).at_least(:twice).and_call_original
includes?([1, 3, 5, 7, 9, 2, 4, 6, 8], 9)
end
end
describe "#num_occur" do
#Problem 3: You have an unsorted array of integers. Write a recursive
#solution to count the number of occurrences of a specific value.
it "returns number of times the target occurs in the array" do
num_occur([1, 1, 2, 3, 4, 5, 5, 4, 5, 6, 7, 6, 5, 6], 5).should == 4
end
it "returns zero if target doesn't occur" do
num_occur([1, 1, 2, 3, 4, 5, 5, 4, 5, 6, 7, 6, 5, 6], 13).should == 0
end
it "should not modify original array" do
original = [1, 3, 5, 7, 9, 2, 4, 6, 8]
num_occur(original, 9)
original.should == [1, 3, 5, 7, 9, 2, 4, 6, 8]
end
it "calls itself recursively" do
should_receive(:num_occur).at_least(:twice).and_call_original
num_occur([1, 3, 5, 7, 9, 2, 4, 6, 8], 9)
end
end
describe "#add_to_twelve?" do
#Problem 4: You have array of integers. Write a recursive solution to
#determine whether or not two adjacent elements of the array add to 12.
it "returns true if two adjacent numbers add to twelve" do
add_to_twelve?([1, 1, 2, 3, 4, 5, 7, 4, 5, 6, 7, 6, 5, 6]).should == true
end
it "returns false if target doesn't occur" do
add_to_twelve?([1, 1, 2, 3, 4, 5, 5, 4, 5, 6, 7, 6, 5, 6]).should == false
end
it "should not modify original array" do
original = [1, 3, 5, 7, 9, 2, 4, 6, 8]
add_to_twelve?(original)
original.should == [1, 3, 5, 7, 9, 2, 4, 6, 8]
end
it "calls itself recursively" do
should_receive(:add_to_twelve?).at_least(:twice).and_call_original
add_to_twelve?([1, 3, 5, 7, 9, 2, 4, 6, 8])
end
end
describe "#sorted?" do
#Problem 5: You have array of integers. Write a recursive solution to
#determine if the array is sorted.
it "returns true if array has only one value" do
sorted?([1]).should == true
end
it "returns true if array is empty" do
sorted?([]).should == true
end
it "returns true if array is sorted" do
sorted?([1, 2, 3, 4, 4, 5, 6, 7]).should == true
end
it "returns false if array is not sorted" do
sorted?([1, 1, 2, 3, 4, 5, 5, 4, 5, 6, 7, 6, 5, 6]).should == false
end
it "should not modify original array" do
original = [1, 3, 5, 7, 9, 2, 4, 6, 8]
sorted?(original)
original.should == [1, 3, 5, 7, 9, 2, 4, 6, 8]
end
it "calls itself recursively" do
should_receive(:sorted?).at_least(:twice).and_call_original
sorted?([1, 3, 5, 7, 9, 2, 4, 6, 8])
end
end
describe "#reverse" do
#Problem 6: Write the code to give the value of a number after it is
#reversed. (Don't use any #reverse methods!)
it "returns same number if only one digit" do
reverse(1).should == 1
end
it "returns reversed number if more than one digit" do
reverse(12345).should == 54321
end
it "should not modify original number" do
original = 123456
reverse(original)
original.should == 123456
end
it "calls itself recursively" do
should_receive(:reverse).at_least(:twice).and_call_original
reverse(123456)
end
end
|
# frozen_string_literal: true
require 'omniauth-oauth2'
module OmniAuth
module Strategies
class MicrosoftGraph < OmniAuth::Strategies::OAuth2
BASE_AZURE_URL = 'https://login.microsoftonline.com'
option :scopes, %w[openid profile offline_access]
option :name, :microsoft_graph
option :tenant_provider, nil
args [:tenant_provider]
option :extensions, nil
def client
provider = if options.tenant_provider
options.tenant_provider.new(self)
else
options # if pass has to config, get mapped right on to options
end
options.scope = provider.scopes.join(' ')
options.client_id = provider.client_id
options.client_secret = provider.client_secret
options.tenant_id =
provider.respond_to?(:tenant_id) ? provider.tenant_id : 'common'
options.base_azure_url =
provider.respond_to?(:base_azure_url) ? provider.base_azure_url : BASE_AZURE_URL
if provider.respond_to?(:authorize_params)
options.authorize_params = provider.authorize_params
end
if provider.respond_to?(:domain_hint) && provider.domain_hint
options.authorize_params.domain_hint = provider.domain_hint
end
if defined? request && request.params['prompt']
options.authorize_params.prompt = request.params['prompt']
end
options.client_options.authorize_url = "#{options.base_azure_url}/#{options.tenant_id}/oauth2/v2.0/authorize"
options.client_options.token_url = "#{options.base_azure_url}/#{options.tenant_id}/oauth2/v2.0/token"
super
end
option :authorize_options, %i[display score auth_type scope prompt login_hint domain_hint response_mode]
uid { raw_info['id'] }
info do
{
'email' => raw_info['mail'],
'first_name' => raw_info['givenName'],
'last_name' => raw_info['surname'],
'name' => [raw_info['givenName'], raw_info['surname']].join(' '),
'nickname' => raw_info['displayName']
}
end
extra do
{
'raw_info' => raw_info,
'memberships' => memberships,
'extensions' => extensions,
'params' => access_token.params
}
end
def raw_info
@raw_info ||= access_token.get('https://graph.microsoft.com/v1.0/me').parsed
end
def memberships
@memberships ||= access_token.get('https://graph.microsoft.com/v1.0/me/transitiveMemberOf?$select=displayName&$top=999').parsed
end
def extensions
if options[:extensions]
@extensions ||= access_token.get('https://graph.microsoft.com/v1.0/me?$select=' + options[:extensions]).parsed
end
end
def callback_url
full_host + script_name + callback_path
end
end
end
end
|
json.array!(@telefone_fornecedors) do |telefone_fornecedor|
json.extract! telefone_fornecedor, :id, :ddd, :telefone, :Fornecedor_id
json.url telefone_fornecedor_url(telefone_fornecedor, format: :json)
end
|
class FriendshipsChangeColumns < ActiveRecord::Migration
def up
rename_column :friendships, :following, :user_id
rename_column :friendships, :follower, :follower_id
end
def down
rename_column :friendships, :user_id, :following
rename_column :friendships, :follower_id, :follower
end
end |
class AddPageToWebsite < ActiveRecord::Migration[5.0]
def change
add_column :pages, :is_homepage, :boolean, index: true
add_index :pages, ["is_homepage"], name: "index_pages_on_is_homepage", using: :btree
add_index :pages, ["website_id","is_homepage"], name: "index_pages_on_website_id_hp", using: :btree
end
end
|
class Citibike
include ActiveSupport::Inflector
def search(location)
gmaps_response = GoogleMaps.new.location(location)
gmaps = JSON.parse(gmaps_response)
response = if gmaps['status'] == 'OK'
lat = gmaps['results'][0]['geometry']['location']['lat']
long = gmaps['results'][0]['geometry']['location']['lng']
# Get station info
station_info = JSON.parse(get_station_info)['data']['stations']
# Get station status
station_status = JSON.parse(get_station_status)['data']['stations']
stations = (station_info + station_status).group_by { |s| s['station_id'] }.map { |k, v| v.reduce(:merge) }
# Sort stations by distance
stations.sort! { |a,b| distance([lat, long], [a['lat'], a['lon']]) <=> distance([lat, long], [b['lat'], b['lon']]) }
# Get the first one that has > 0 bikes
station = stations.find { |s| s['num_bikes_available'] > 0 }
build_response(lat, long, station)
else
{ text: 'Sorry, I don’t understand that address.', response_type: 'ephemeral' }
end
end
private
def build_response(lat, long, station)
name = station['name']
bikes = station['num_bikes_available']
docks = station['num_docks_available']
station_lat = station['lat']
station_long = station['lon']
link = "https://maps.google.com?saddr=#{lat},#{long}&daddr=#{station_lat},#{station_long}&dirflg=w"
attachments = []
attachment = { fallback: "The nearest Citibike station with bikes is #{name}: #{link}", color: '#1d5b97', pretext: "This is the nearest Citibike station with bikes:", title: name, title_link: link, image_url: GoogleMaps.new.image(station_lat, station_long) }
fields = []
fields << { title: 'Available Bikes', value: bikes, short: true }
fields << { title: 'Available Docks', value: docks, short: true }
attachment[:fields] = fields
attachments << attachment
{ response_type: 'in_channel', attachments: attachments }
end
# Haversine distance formula from http://stackoverflow.com/a/12969617
def distance(loc1, loc2)
rad_per_deg = Math::PI/180 # PI / 180
rkm = 6371 # Earth radius in kilometers
rm = rkm * 1000 # Radius in meters
dlat_rad = (loc2[0]-loc1[0]) * rad_per_deg # Delta, converted to rad
dlon_rad = (loc2[1]-loc1[1]) * rad_per_deg
lat1_rad, lon1_rad = loc1.map {|i| i * rad_per_deg }
lat2_rad, lon2_rad = loc2.map {|i| i * rad_per_deg }
a = Math.sin(dlat_rad/2)**2 + Math.cos(lat1_rad) * Math.cos(lat2_rad) * Math.sin(dlon_rad/2)**2
c = 2 * Math::atan2(Math::sqrt(a), Math::sqrt(1-a))
rm * c # Delta in meters
end
def get_station_info
Rails.cache.fetch("citibike_station_info", expires_in: 1.week) do
HTTParty.get('https://gbfs.citibikenyc.com/gbfs/en/station_information.json').body
end
end
def get_station_status
Rails.cache.fetch("citibike_station_status", expires_in: 5.minutes) do
HTTParty.get('https://gbfs.citibikenyc.com/gbfs/en/station_status.json').body
end
end
end
|
# Define a configset by ENV['RAILS_CONFIGSET'] || default, then do the following:
# - if config/settings/configsets/set_name.yml exists, then add its contents to the config settings.
# This file is intended for things that may vary machine to machine, but do not contain secrets
# - if credentials.yml.enc has a configsets[set_name] key, then add its contents to the config settings.
# This is intended for things that have secrets. Note that because of the way the config gem works
# it may be that not just the credentials need to go here - e.g. there is no apparent way to inject
# credentials into each object of an array of objects, for example.
#Probably this is useful primarily in a production environment - for dev/test environments more of the stuff
# should be settable directly (for consistency) or via the test.local/development.local files (for an individual's
# unique dev environment)
#
# The raison d'etre here is to allow us to keep Rails-y environment settings (e.g. caching, class loading behavior, etc.)
# using the tradition Rails environment while allowing us to inject information that may vary from machine to machine
# for various production environments. I.e. the -prod and -demo environments are mostly the same as far as Rails is
# concerned, but may do things like connect to different servers/buckets/etc.
#Config needs to be loaded, as do the secrets in credentials.yml.enc, before this will work.
require_relative 'config'
configset = ENV['RAILS_CONFIGSET'] || 'default'
config_file = File.join(Rails.root, 'config', 'settings', 'configsets', "#{configset}.yml")
if File.exist?(config_file)
Settings.add_source!(config_file)
end
credential_configset = (Rails.application.credentials.configsets[configset.to_sym] rescue nil)
if credential_configset
Settings.add_source!(credential_configset.to_h)
end
Settings.reload!
|
=begin
#Scubawhere API Documentation
#This is the documentation for scubawhere's RMS API. This API is only to be used by authorized parties with valid auth tokens. [Learn about scubawhere](http://www.scubawhere.com) to become an authorized consumer of our API
OpenAPI spec version: 1.0.0
Contact: bryan@scubawhere.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=end
require 'spec_helper'
require 'json'
# Unit tests for SwaggerClient::CourseApi
# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen)
# Please update as you see appropriate
describe 'CourseApi' do
before do
# run before each test
@instance = SwaggerClient::CourseApi.new
end
after do
# run after each test
end
describe 'test an instance of CourseApi' do
it 'should create an instact of CourseApi' do
expect(@instance).to be_instance_of(SwaggerClient::CourseApi)
end
end
# unit tests for create_course
# Create a new course
#
# @param name
# @param description
# @param capacity
# @param prices
# @param [Hash] opts the optional parameters
# @option opts [Integer] :certificate_id
# @option opts [Array<Integer>] :tickets
# @option opts [Array<Integer>] :trainings
# @return [InlineResponse20027]
describe 'create_course test' do
it "should work" do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
# unit tests for delete_course
# Delete a course by ID
#
# @param id
# @param [Hash] opts the optional parameters
# @return [InlineResponse2003]
describe 'delete_course test' do
it "should work" do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
# unit tests for edit_course
# Update a course by ID
#
# @param id
# @param name
# @param description
# @param capacity
# @param [Hash] opts the optional parameters
# @option opts [Integer] :certificate_id
# @option opts [Array<Integer>] :tickets
# @option opts [Array<Integer>] :trainings
# @return [InlineResponse20028]
describe 'edit_course test' do
it "should work" do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
# unit tests for get_all_courses
# Retrieve all courses including any deleted models
#
# @param [Hash] opts the optional parameters
# @return [Array<Course>]
describe 'get_all_courses test' do
it "should work" do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
# unit tests for get_all_with_trashed_courses
# Retrieve all courses including any deleted models
#
# @param [Hash] opts the optional parameters
# @return [Array<Course>]
describe 'get_all_with_trashed_courses test' do
it "should work" do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
# unit tests for get_course
# Retrieve a course by ID
#
# @param [Hash] opts the optional parameters
# @option opts [Integer] :id
# @return [InlineResponse20027]
describe 'get_course test' do
it "should work" do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
end
|
class Interface::Vlan < Interface::Base
attr_accessor :id, :vlan_raw_device
def name=(name)
@name = name.sub(/[0-9]*$/, '')
@id = name.sub(/^.*?([0-9]*)$/, '\1') if @id.blank?
end
def name
(@name ||= 'vlan') + id
end
def to_save
params = super
params[:vlan_raw_device] = vlan_raw_device unless vlan_raw_device.blank?
params
end
def to_hash
super.merge({ :name => @name, :id => @id, :type => 'VLAN'})
end
end
|
class ShopperReport < ActiveRecord::Base
has_many :shop_collections, dependent: :destroy
def convert_from_json(json)
self.shopper_name = json[:shopper_name]
self.orders_count = json[:orders_count]
self.items_count = json[:items_count]
self.total_time = json[:total_time]
unless json[:shop_collections].nil?
self.shop_collections = json[:shop_collections].collect {|x| ShopCollection.new.convert_from_json(x)}
end
self
end
end |
# frozen_string_literal: true
require_relative "test_helper"
require "tar/header"
class HeaderTest < Minitest::Test
def test_parse
header = Tar::Header.parse(header_data("020523"))
assert_equal "path/to/file", header.name
assert_equal 0o644, header.mode
assert_equal 83, header.uid
assert_equal 302, header.gid
assert_equal 1080, header.size
assert_equal Time.utc(2017, 5, 11, 20, 14, 49), header.mtime
assert_equal 0o20523, header.checksum
assert_equal "0", header.typeflag
assert_equal "path/to/link", header.link_name
assert_equal "ustar", header.magic
assert_equal "00", header.version
assert_equal "haines", header.uname
assert_equal "staff", header.gname
assert_equal 0, header.dev_major
assert_equal 0, header.dev_minor
assert_equal "prefix/to/add", header.prefix
end
def test_parse_fails_if_checksum_is_invalid
assert_raises Tar::ChecksumMismatch do
Tar::Header.parse(header_data("012345"))
end
end
private
def header_data(checksum)
"path/to/file".ljust(100, "\0") + # name
"000644 \0" + # mode
"000123 \0" + # uid
"000456 \0" + # gid
"00000002070 " + # size
"13105143071 " + # mtime
"#{checksum}\0 " + # checksum
"0" + # typeflag
"path/to/link".ljust(100, "\0") + # link_name
"ustar\0" + # magic
"00" + # version
"haines".ljust(32, "\0") + # uname
"staff".ljust(32, "\0") + # gname
"000000 \0" + # dev_major
"000000 \0" + # dev_minor
"prefix/to/add".ljust(155, "\0") + # prefix
"\0" * 12 # padding
end
end
|
class Zoo
attr_reader :enclosure
def initialize(name)
@name = name
@enclosure = []
end
def add_animal(animal)
@enclosure << animal
end
def number_of_animals
return @enclosure.length
end
end
class Animal
attr_accessor :name
attr_reader :sound, :number_of_legs
def initialize(name)
@name = name
@sound = "no sound"
@number_of_legs = 4
@lieblingsessen = "futter"
@schlafzeit = 0
end
def make
"#{@name} makes #{@sound}, eats #{@lieblingsessen} and sleeps #{@schlafzeit} hours!"
end
def to_s
return "name: #{@name} is a #{self.class} \n makes #{@sound} \n eats #{@lieblingsessen} \n sleeps #{@schlafzeit} hours!"
end
end
class Dog < Animal
def initialize(name)
super # Parent Klasse init
@sound = "woof"
@lieblingsessen = "nassfutter mit kaninchen"
@schlafzeit = "12"
end
end
class Lion < Animal
def initialize(name)
super # Parent Klasse init
@sound = "roar"
@lieblingsessen = "schnitzel"
@schlafzeit = "17"
end
end
class Zebra < Animal
def initialize(name)
super # Parent Klasse init
@sound = "igogo"
@lieblingsessen = "grass"
@schlafzeit = "9"
end
end
|
class User < Sequel::Model
plugin :validation_helpers
def validate
super
validates_presence [:email, :name, :dni, :surname, :password, :username]
validates_unique [:email, :username, :dni]
validates_format /\A.*@.*\..*\z/, :email, message: 'is not a valid email'
end
many_to_many :documents
one_to_many :notifications
end
|
module Cultivation
class UpdateTaskIndent
prepend SimpleCommand
def initialize(task_id, indent_action, current_user)
@task_id = task_id&.to_bson_id
@indent_action = indent_action
@current_user = current_user
end
def call
# TODO::ANDY: Can move into update task? so that the duration
# can be calculated correctly
if valid_params? && can_indent?
tasks = get_tasks(task_to_indent.batch)
@task_to_indent = get_task(tasks, @task_id)
children = task_to_indent.children(tasks)
if can_indent_in?
task_to_indent.indent += 1
task_to_indent.save!
children.each do |t|
t.indent += 1
t.save!
end
end
if can_indent_out?
task_to_indent.indent -= 1
task_to_indent.save!
children.each do |t|
t.indent -= 1
t.save!
end
end
Cultivation::UpdateTask.call(@current_user, task_to_indent)
task_to_indent
end
end
private
def can_indent_in?
@indent_action == 'in' && !task_to_indent.wbs.ends_with?('.1')
end
def can_indent_out?
@indent_action == 'out' && task_to_indent.indent > 1
end
def print_current_order(batch)
res = get_tasks(batch)
output = res.map do |rec|
{
name: rec.name,
wbs: rec.wbs,
indent: rec.indent,
position: rec.position,
}
end
pp output
end
def get_tasks(batch)
Cultivation::QueryTasks.call(batch).result
end
def get_task(batch_tasks, task_id)
batch_tasks.detect { |t| t.id == task_id }
end
def task_to_indent
@task_to_indent ||= Cultivation::Task.
includes(:batch).
find_by(id: @task_id)
end
def valid_params?
if @task_id.nil?
errors.add(:error, 'Missing param :task_id')
return false
end
if @indent_action.nil?
errors.add(:error, 'Missing param :indent_action')
return false
end
true
end
def can_indent?
if task_to_indent.nil?
errors.add(:error, 'Task Not Found')
return false
end
if task_to_indent.indelible.present? && task_to_indent.indelible
errors.add(:id, "Cannot indent indelible task: #{task_to_indent.name}")
return false
end
true
end
end
end
|
require 'person'
require 'test/unit'
class TestPerson < Test::Unit::TestCase
def test_simple
assert_equal(1964, Person.new("Al",43).year_born)
assert_equal(15823, Person.new("Al",43).days_alive)
end
end |
# Write a function:
# def solution(a)
# that, given an array A describing N discs as explained above, returns the number of (unordered) pairs of intersecting discs. The function should return −1 if the number of intersecting pairs exceeds 10,000,000.
def solution(a)
return 0 unless a.size > 1
disc_edges = []
a.each_with_index do |r, j|
disc_edges << [j - r, :begin]
disc_edges << [j + r, :end]
end
disc_edges.sort_by! {|point, status| [point, status]}
active_discs = 0
intersections = 0
disc_edges.each do |edge|
if edge[1] == :begin
intersections += active_discs
active_discs += 1
else
active_discs -= 1
end
end
return -1 if intersections > 10_000_000
intersections
end
|
# frozen_string_literal: true
require 'mini_magick'
module Jiji::Services
class ImagingService
include Jiji::Errors
def create_icon(stream, w = 192, h = 192)
img = MiniMagick::Image.read(stream)
img.define "size=#{w}x#{h}"
img.combine_options do |cmd|
resize_to_fit_longest_edge(cmd, img, w, h)
cmd.auto_orient
crop(cmd, img, w, h)
end
img.format 'png'
img.to_blob
end
private
def resize_to_fit_longest_edge(cmd, img, w, h)
cols, rows = img[:dimensions]
return if w == cols && h == rows
scale = calculate_scale(w, h, cols, rows)
cmd.resize "#{(cols * scale).ceil}x#{(rows * scale).ceil}"
end
def calculate_scale(w, h, cols, rows)
[w / cols.to_f, h / rows.to_f].max
end
def crop(cmd, img, w, h)
cmd.gravity 'Center'
cmd.background 'rgba(255,255,255,0.0)'
cmd.extent "#{w}x#{h}"
end
end
end
|
require 'spec_helper'
describe Bucket do
describe "::posts" do
it 'only grabs published posts' do
bucket = create :bucket
post_unpublished = create :post, status: Post::STATUS[:draft]
post_published = create :post, status: Post::STATUS[:published]
bucket.posts = [post_unpublished, post_published]
bucket.reload.posts.should eq [post_published]
end
end
end
|
class RecipeIngredient < ApplicationRecord
belongs_to :recipe
belongs_to :ingredient
# Validations
validates :ingredient_amount, presence: true, numericality: true
validates :ingredient_unit, presence: true
end
|
require 'serverspec'
include Serverspec::Helper::Exec
include Serverspec::Helper::DetectOS
RSpec.configure do |c|
c.before :all do
c.os = backend(Serverspec::Commands::Base).check_os
c.path = '/sbin:/usr/sbin'
end
end
describe file('/srv/frog/webapp/webapp/settings.py') do
it { should be_owned_by 'frog' }
it { should be_grouped_into 'frog' }
it { should be_mode 600 }
its(:content) { should match(/'ENGINE': 'django.db.backends.mysql'/) }
its(:content) { should match(/'NAME': 'frog'/) }
its(:content) { should match(/'USER': 'frog'/) }
its(:content) { should match(/'PASSWORD': 'frogadmin'/) }
its(:content) { should match(/'HOST': '.*rds.amazonaws.com'/) }
its(:content) { should match(/'PORT': [0-9]*/) }
end
|
require 'optparse'
class TestRunParser
def parse_args(args)
options = {}
parser = OptionParser.new do |opts|
opts.banner = "Usage: mobcli test run [options]. It runs tests through adb based on a JUnit XML report."
opts.on("--path [PATH]", "List the JUnit tests the have failed based on JUnit XML report") do |path|
raise OptionParser::MissingArgument.new("a [PATH] is required") if path.nil?
options[:path] = path
end
opts.on("--filter [failure|passes]", "Filter test by type of result") do |filter|
raise OptionParser::MissingArgument.new("should receive one of the options [failure|passes]") unless
%w(failure passes errors skipped).include? filter
options[:filter] = filter
end
opts.on("--applicationId [applicationId]", "Informs the applicationId of the project") do |applicationId|
raise OptionParser::MissingArgument.new("a [applicationId] is required") if applicationId.nil?
options[:applicationId] = applicationId
end
opts.on("-h", "--help", "Prints this help") do
raise ParserExit, opts
end
end
parser.parse(args)
raise OptionParser::MissingArgument.new("--path is required") if options[:path].nil?
raise OptionParser::MissingArgument.new("--applicationId is required") if options[:applicationId].nil?
options
end
end |
# frozen_string_literal: true
module GraphQL
module Pagination
# A Connection wraps a list of items and provides cursor-based pagination over it.
#
# Connections were introduced by Facebook's `Relay` front-end framework, but
# proved to be generally useful for GraphQL APIs. When in doubt, use connections
# to serve lists (like Arrays, ActiveRecord::Relations) via GraphQL.
#
# Unlike the previous connection implementation, these default to bidirectional pagination.
#
# Pagination arguments and context may be provided at initialization or assigned later (see {Schema::Field::ConnectionExtension}).
class Connection
class PaginationImplementationMissingError < GraphQL::Error
end
# @return [Object] A list object, from the application. This is the unpaginated value passed into the connection.
attr_reader :items
# @return [GraphQL::Query::Context]
attr_accessor :context
# @return [Object] the object this collection belongs to
attr_accessor :parent
# Raw access to client-provided values. (`max_page_size` not applied to first or last.)
attr_accessor :before_value, :after_value, :first_value, :last_value
# @return [String, nil] the client-provided cursor. `""` is treated as `nil`.
def before
if defined?(@before)
@before
else
@before = @before_value == "" ? nil : @before_value
end
end
# @return [String, nil] the client-provided cursor. `""` is treated as `nil`.
def after
if defined?(@after)
@after
else
@after = @after_value == "" ? nil : @after_value
end
end
# @return [Hash<Symbol => Object>] The field arguments from the field that returned this connection
attr_accessor :arguments
# @param items [Object] some unpaginated collection item, like an `Array` or `ActiveRecord::Relation`
# @param context [Query::Context]
# @param parent [Object] The object this collection belongs to
# @param first [Integer, nil] The limit parameter from the client, if it provided one
# @param after [String, nil] A cursor for pagination, if the client provided one
# @param last [Integer, nil] Limit parameter from the client, if provided
# @param before [String, nil] A cursor for pagination, if the client provided one.
# @param arguments [Hash] The arguments to the field that returned the collection wrapped by this connection
# @param max_page_size [Integer, nil] A configured value to cap the result size. Applied as `first` if neither first or last are given and no `default_page_size` is set.
# @param default_page_size [Integer, nil] A configured value to determine the result size when neither first or last are given.
def initialize(items, parent: nil, field: nil, context: nil, first: nil, after: nil, max_page_size: NOT_CONFIGURED, default_page_size: NOT_CONFIGURED, last: nil, before: nil, edge_class: nil, arguments: nil)
@items = items
@parent = parent
@context = context
@field = field
@first_value = first
@after_value = after
@last_value = last
@before_value = before
@arguments = arguments
@edge_class = edge_class || self.class::Edge
# This is only true if the object was _initialized_ with an override
# or if one is assigned later.
@has_max_page_size_override = max_page_size != NOT_CONFIGURED
@max_page_size = if max_page_size == NOT_CONFIGURED
nil
else
max_page_size
end
@has_default_page_size_override = default_page_size != NOT_CONFIGURED
@default_page_size = if default_page_size == NOT_CONFIGURED
nil
else
default_page_size
end
end
def max_page_size=(new_value)
@has_max_page_size_override = true
@max_page_size = new_value
end
def max_page_size
if @has_max_page_size_override
@max_page_size
else
context.schema.default_max_page_size
end
end
def has_max_page_size_override?
@has_max_page_size_override
end
def default_page_size=(new_value)
@has_default_page_size_override = true
@default_page_size = new_value
end
def default_page_size
if @has_default_page_size_override
@default_page_size
else
context.schema.default_page_size
end
end
def has_default_page_size_override?
@has_default_page_size_override
end
attr_writer :first
# @return [Integer, nil]
# A clamped `first` value.
# (The underlying instance variable doesn't have limits on it.)
# If neither `first` nor `last` is given, but `default_page_size` is
# present, default_page_size is used for first. If `default_page_size`
# is greater than `max_page_size``, it'll be clamped down to
# `max_page_size`. If `default_page_size` is nil, use `max_page_size`.
def first
@first ||= begin
capped = limit_pagination_argument(@first_value, max_page_size)
if capped.nil? && last.nil?
capped = limit_pagination_argument(default_page_size, max_page_size) || max_page_size
end
capped
end
end
# This is called by `Relay::RangeAdd` -- it can be overridden
# when `item` needs some modifications based on this connection's state.
#
# @param item [Object] An item newly added to `items`
# @return [Edge]
def range_add_edge(item)
edge_class.new(item, self)
end
attr_writer :last
# @return [Integer, nil] A clamped `last` value. (The underlying instance variable doesn't have limits on it)
def last
@last ||= limit_pagination_argument(@last_value, max_page_size)
end
# @return [Array<Edge>] {nodes}, but wrapped with Edge instances
def edges
@edges ||= nodes.map { |n| @edge_class.new(n, self) }
end
# @return [Class] A wrapper class for edges of this connection
attr_accessor :edge_class
# @return [GraphQL::Schema::Field] The field this connection was returned by
attr_accessor :field
# @return [Array<Object>] A slice of {items}, constrained by {@first_value}/{@after_value}/{@last_value}/{@before_value}
def nodes
raise PaginationImplementationMissingError, "Implement #{self.class}#nodes to paginate `@items`"
end
# A dynamic alias for compatibility with {Relay::BaseConnection}.
# @deprecated use {#nodes} instead
def edge_nodes
nodes
end
# The connection object itself implements `PageInfo` fields
def page_info
self
end
# @return [Boolean] True if there are more items after this page
def has_next_page
raise PaginationImplementationMissingError, "Implement #{self.class}#has_next_page to return the next-page check"
end
# @return [Boolean] True if there were items before these items
def has_previous_page
raise PaginationImplementationMissingError, "Implement #{self.class}#has_previous_page to return the previous-page check"
end
# @return [String] The cursor of the first item in {nodes}
def start_cursor
nodes.first && cursor_for(nodes.first)
end
# @return [String] The cursor of the last item in {nodes}
def end_cursor
nodes.last && cursor_for(nodes.last)
end
# Return a cursor for this item.
# @param item [Object] one of the passed in {items}, taken from {nodes}
# @return [String]
def cursor_for(item)
raise PaginationImplementationMissingError, "Implement #{self.class}#cursor_for(item) to return the cursor for #{item.inspect}"
end
private
# @param argument [nil, Integer] `first` or `last`, as provided by the client
# @param max_page_size [nil, Integer]
# @return [nil, Integer] `nil` if the input was `nil`, otherwise a value between `0` and `max_page_size`
def limit_pagination_argument(argument, max_page_size)
if argument
if argument < 0
argument = 0
elsif max_page_size && argument > max_page_size
argument = max_page_size
end
end
argument
end
def decode(cursor)
context.schema.cursor_encoder.decode(cursor, nonce: true)
end
def encode(cursor)
context.schema.cursor_encoder.encode(cursor, nonce: true)
end
# A wrapper around paginated items. It includes a {cursor} for pagination
# and could be extended with custom relationship-level data.
class Edge
attr_reader :node
def initialize(node, connection)
@connection = connection
@node = node
end
def parent
@connection.parent
end
def cursor
@cursor ||= @connection.cursor_for(@node)
end
end
end
end
end
|
class KegTemplatesGenerator < Rails::Generators::Base
source_root File.expand_path('../templates', __FILE__)
def generate_keg_templates
files = ["_form", "show", "edit", "index", "new"]
files.each do |file|
copy_file "#{file}.html.haml", "lib/templates/haml/scaffold/#{file}.html.haml"
end
end
end |
class CourseTeacherAssignmentsController < ApplicationController
def create
@course_teacher_assignment = CourseTeacherAssignment.create(course_id: params[:course_teacher_assignment][:course_id], teacher_id: params[:course_teacher_assignment][:teacher_id])
if @course_teacher_assignment.save
flash[:notice] = "#{current_user.full_name} has been added to #{@course_teacher_assignment.course.name}!"
redirect_to(:back)
else
flash[:alert] = "Error in saving!"
redirect_to(:back)
end
end
end
|
class Following < ApplicationRecord
belongs_to :client
belongs_to :artist
end
|
class CreateAnswerDetail < ActiveRecord::Migration
def change
create_table :answer_details do |t|
t.integer :topic_id
t.integer :question_id
t.integer :activity_id
t.string :answer
t.string :comment
t.timestamps
end
end
end
|
# frozen_string_literal: true
class AddWorkspaceRefsToTicketsAndFolders < ActiveRecord::Migration[5.2]
def change
add_reference :tickets, :workspace, foreign_key: true
add_reference :folders, :workspace, foreign_key: true
end
end
|
FactoryGirl.define do
factory :location do
code "dummycode"
name "dummycode"
end
end |
class Home < ActiveRecord::Base
def self.to_csv(options = {})
CSV.generate(options) do |csv|
csv << column_names
all.each do |home|
csv << home.attributes.values_at(*column_names)
end
end
end
end
|
require 'rails_helper'
RSpec.describe Position do
describe ".names" do
it "returns an array of position names" do
expect(described_class.names.size).to eq(19)
expect(described_class.names).to eq([
'Quarterback',
'Halfback',
'Wide Receiver',
'Fullback',
'Tight End',
'Right Tackle',
'Right Guard',
'Center',
'Left Guard',
'Left Tackle',
'Free Safety',
'Strong Safety',
'Cornerback',
'Right Outside Linebacker',
'Middle Linebacker',
'Left Outside Linebacker',
'Left End',
'Right End',
'Defensive Tackle'])
end
end
describe ".abbreviations" do
it "returns an array of position abbreviations" do
expect(described_class.abbreviations.size).to eq(19)
expect(described_class.abbreviations).to eq([
'qb',
'hb',
'wr',
'fb',
'te',
'rt',
'rg',
'c',
'lg',
'lt',
'fs',
'ss',
'cb',
'rolb',
'mlb',
'lolb',
'le',
're',
'dt'])
end
end
describe ".styles" do
it "returns the styles for a given position name" do
expect(described_class
.styles(position_name_or_abbreviation: 'Quarterback'))
.to eq(['dual_threat', 'pocket_passer', 'mobile'])
end
it "returns the styles for a given position abbreviation" do
expect(described_class.styles(position_name_or_abbreviation: 'qb'))
.to eq(['dual_threat', 'pocket_passer', 'mobile'])
end
end
describe ".name_from_abbreviation" do
it "returns the position abbreviation when given a name" do
expect(described_class.name_from_abbreviation(abbreviation: 'qb'))
.to eq('Quarterback')
end
end
describe ".abbreviation_from_name" do
it "returns the position abbreviation when given a name" do
expect(described_class.abbreviation_from_name(position_name: 'Quarterback'))
.to eq('qb')
end
end
describe ".general_stats" do
it "returns the general player stats" do
expect(described_class.general_stats).to eq([
:height_in_inches,
:weight_in_pounds,
:speed,
:strength,
:agility,
:acceleration,
:awareness,
:catching,
:jumping,
:stamina,
:injury
])
end
end
describe ".offensive_stats" do
it "returns the offensive player stats" do
expect(described_class.offensive_stats).to eq([
:trucking,
:elusiveness,
:ball_carrier_vision,
:stiff_arm,
:spin_move,
:juke_move,
:carrying,
:route_running,
:catch_in_traffic,
:spectacular_catch,
:release,
:throw_power,
:throw_accuracy_short,
:throw_accuracy_mid,
:throw_accuracy_deep,
:throw_on_the_run,
:play_action,
:run_block,
:pass_block,
:impact_blocking
])
end
end
describe ".defensive_stats" do
it "returns the defensive player stats" do
expect(described_class.defensive_stats).to eq([
:tackle,
:hit_power,
:power_moves,
:finesse_moves,
:block_shedding,
:pursuit,
:play_recognition,
:man_coverage,
:zone_coverage,
:press
])
end
end
describe ".special_teams_stats" do
it "returns the special teams player stats" do
expect(described_class.special_teams_stats).to eq([
:kick_power,
:kick_accuracy,
:kick_return,
])
end
end
describe ".traits" do
it "returns the player traits by position" do
expect(described_class.traits).to eq({
qb: [
:trait_quarterback_style,
:trait_throws_tight_spiral,
:trait_senses_pressure,
:trait_throws_ball_away,
:trait_forces_passes,
:trait_clutch,
:trait_penalty
],
hb: [
:trait_clutch,
:trait_covers_ball,
:trait_fights_for_extra_yards,
:trait_makes_aggressive_catches,
:trait_makes_rac_catches,
:trait_makes_possession_catches,
:trait_drops_open_passes,
:trait_makes_sideline_catches,
:trait_high_motor,
:trait_penalty
],
wr: [
:trait_clutch,
:trait_covers_ball,
:trait_fights_for_extra_yards,
:trait_makes_aggressive_catches,
:trait_makes_rac_catches,
:trait_makes_possession_catches,
:trait_drops_open_passes,
:trait_makes_sideline_catches,
:trait_high_motor,
:trait_penalty
],
fb: [
:trait_clutch,
:trait_covers_ball,
:trait_fights_for_extra_yards,
:trait_makes_aggressive_catches,
:trait_makes_rac_catches,
:trait_makes_possession_catches,
:trait_drops_open_passes,
:trait_makes_sideline_catches,
:trait_high_motor,
:trait_penalty
],
te: [
:trait_clutch,
:trait_covers_ball,
:trait_fights_for_extra_yards,
:trait_drops_open_passes,
:trait_makes_sideline_catches,
:trait_high_motor,
:trait_makes_aggressive_catches,
:trait_makes_rac_catches,
:trait_makes_possession_catches,
:trait_drops_open_passes,
:trait_penalty
],
rt: [
:trait_high_motor,
:trait_penalty
],
rg: [
:trait_high_motor,
:trait_penalty
],
c: [
:trait_high_motor,
:trait_penalty
],
lg: [
:trait_high_motor,
:trait_penalty
],
lt: [
:trait_high_motor,
:trait_penalty
],
fs: [
:trait_clutch,
:trait_high_motor,
:trait_linebacker_style,
:trait_dl_swim_move,
:trait_dl_spin_move,
:trait_dl_bull_rush_move,
:trait_big_hitter,
:trait_strips_ball,
:trait_plays_ball_in_air,
:trait_penalty
],
ss: [
:trait_clutch,
:trait_high_motor,
:trait_linebacker_style,
:trait_dl_swim_move,
:trait_dl_spin_move,
:trait_dl_bull_rush_move,
:trait_big_hitter,
:trait_strips_ball,
:trait_plays_ball_in_air,
:trait_penalty
],
cb: [
:trait_clutch,
:trait_high_motor,
:trait_dl_swim_move,
:trait_dl_spin_move,
:trait_dl_bull_rush_move,
:trait_big_hitter,
:trait_strips_ball,
:trait_plays_ball_in_air,
:trait_penalty
],
rolb: [
:trait_clutch,
:trait_high_motor,
:trait_linebacker_style,
:trait_dl_swim_move,
:trait_dl_spin_move,
:trait_dl_bull_rush_move,
:trait_big_hitter,
:trait_strips_ball,
:trait_plays_ball_in_air,
:trait_penalty
],
mlb: [
:trait_clutch,
:trait_high_motor,
:trait_linebacker_style,
:trait_dl_swim_move,
:trait_dl_spin_move,
:trait_dl_bull_rush_move,
:trait_big_hitter,
:trait_strips_ball,
:trait_plays_ball_in_air,
:trait_penalty
],
lolb: [
:trait_clutch,
:trait_high_motor,
:trait_linebacker_style,
:trait_dl_swim_move,
:trait_dl_spin_move,
:trait_dl_bull_rush_move,
:trait_big_hitter,
:trait_strips_ball,
:trait_plays_ball_in_air,
:trait_penalty
],
le: [
:trait_high_motor,
:trait_dl_swim_move,
:trait_dl_spin_move,
:trait_dl_bull_rush_move,
:trait_big_hitter,
:trait_strips_ball,
:trait_penalty
],
re: [
:trait_high_motor,
:trait_dl_swim_move,
:trait_dl_spin_move,
:trait_dl_bull_rush_move,
:trait_big_hitter,
:trait_strips_ball,
:trait_penalty
],
dt: [
:trait_high_motor,
:trait_dl_swim_move,
:trait_dl_spin_move,
:trait_dl_bull_rush_move,
:trait_big_hitter,
:trait_strips_ball,
:trait_penalty
]
})
end
end
end
|
require 'spec_helper'
describe Dickburt::Response do
before :each do
@response = Dickburt::Response.new("beer", "Text")
end
it "should give me a hash for campfire" do
@response.to_campfire_hash.must_be_kind_of Hash
@response.to_campfire_hash.keys.must_include :message
end
it "should respond to to_json with the appropriate hash" do
JSON.parse(@response.to_json).keys.must_include "message"
end
end |
# rubocop:disable Metrics/BlockLength
require 'rails_helper'
RSpec.feature 'CreateGiftProcesses', type: :feature do
before(:each) do
user = User.create(name: 'user')
Group.create(name: 'test-group', user: user, icon: '')
visit '/sign-in'
fill_in 'session_name', with: 'user'
click_button 'Sign in'
end
it 'Returns success if new gift created' do
click_on 'All Groups'
click_on 'test-group'
click_on 'Add Gift'
fill_in 'gift_name', with: 'gift-test'
fill_in 'gift_amount', with: 1
click_on 'Create Gift'
expect(page).to have_content 'Group: test-group'
end
it 'Raises error if gift amount not provided' do
click_on 'All Groups'
click_on 'test-group'
click_on 'Add Gift'
fill_in 'gift_name', with: 'gift-test'
click_on 'Create Gift'
expect(page).to have_content 'Amount can\'t be blank'
end
it 'Raises error if name too short' do
click_on 'All Groups'
click_on 'test-group'
click_on 'Add Gift'
click_on 'Create Gift'
expect(page).to have_content 'Name can\'t be blank'
end
end
# rubocop:enable Metrics/BlockLength
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.