text stringlengths 10 2.61M |
|---|
class User < ApplicationRecord
validates :username, {presence: true, uniqueness: true}
has_many :capsules
has_many :articles, through: :capsules
end
|
class Prize < ActiveRecord::Base
#############################
### ATTRIBUTES
#############################
attr_accessible :status_prize_id, :build_menu_id, :category_id,
:name, :redeem_value, :level, :role, :is_delete
attr_accessor :array_prize, :level_delete, :status_name,
:location_id, :location_logo, :location_cuisine,
:location_name, :location_lat, :location_long, :byte_prize_type
#############################
### ASSOCIATIONS
#############################
belongs_to :build_menu
belongs_to :category
belongs_to :status_prize
has_many :share_prizes, dependent: :destroy
has_many :prize_redeems, dependent: :destroy
has_many :user_prizes, dependent: :destroy
has_one :item, through: :build_menu
#############################
### VALIDATIONS
#############################
validates :status_prize_id, presence: true, numericality: { only_integer: true } # Required
validates :build_menu_id, allow_nil: true, numericality: { only_integer: true }
validates :category_id, allow_nil: true, numericality: { only_integer: true }
validates :level, presence: true, numericality: { only_integer: true } # Required
validates :redeem_value, presence: true, numericality: {greater_than: 0} # Required
#############################
### INSTANCE METHODS
#############################
def current_prizes(location_id, points, user_id)
current_prizes = Prize.get_unlocked_prizes_by_location(location_id, points, user_id)
current_prizes.delete_if do |i|
i.type != "owner" || !i.date_time_redeem.nil?
end
prizes = Prize.reject_prizes_in_order(current_prizes, location_id, user_id)
# only show prizes were linked to item or category
received_prizes = Prize.get_received_prizes(location_id, user_id)
received_prizes = received_prizes.reject{|p| p.build_menu == nil && p.category == nil}
if prizes.empty? || prizes.nil?
received_prizes = Prize.reject_prizes_in_order(received_prizes, location_id, user_id)
return received_prizes
end
first_prize = prizes.first
is_linked_to_item = false
if !first_prize.category.nil? || !first_prize.build_menu.nil?
is_linked_to_item = true
end
results = []
if is_linked_to_item
results << first_prize
end
results = results | received_prizes
results = Prize.reject_prizes_in_order(results, location_id, user_id)
# Remove redeemed prizes
results = results.reject{|p| p.date_time_redeem != nil}
return results
end
def prize_status_name
return User.get_current_status(location_id, user_id)
end
#############################
### CLASS METHODS
#############################
def self.get_redeemed_prizes_from_friend_or_restaurant(location_id, user_id)
sql = "SELECT
stp.id as status_prize_id,
pr.share_prize_id as share_prize_id,
pr.from_redeem as type,
p.id as prize_id,
p.name,
p.level AS level_number,
p.redeem_value,
pr.from_user AS from_user,
u.email as email,
DATE_FORMAT(CONVERT_TZ(pr.created_at, '+00:00', pr.timezone),
'%m/%d/%Y %H:%i:%S') as date_time_redeem,
DATE_FORMAT(NOW(), '%m/%d/%Y %H:%i:%S') as date_time_current,
DATE_FORMAT(CONVERT_TZ(NOW(), @@session .time_zone, '+00:00'),
'%m/%d/%Y %H:%i:%S') as date_currents,
DATE_FORMAT(pr.created_at, '%m/%d/%Y %H:%i:%S') as date_redeem,
p.build_menu_id,
p.category_id
FROM
prizes p
JOIN
status_prizes stp ON stp.id = p.status_prize_id
JOIN
prize_redeems pr ON p.id = pr.prize_id
LEFT JOIN
users u ON u.id = pr.from_user
WHERE
p.is_delete = 0 and stp.location_id = #{location_id} and pr.user_id = #{user_id}"
return Prize.find_by_sql(sql).uniq
end
def self.get_redeemed_prizes(location_id, user_id)
redeem_sql = "SELECT
p.id, p.level, sp.id as status_prize_id
FROM
prizes p
JOIN
prize_redeems pr ON p.id = pr.prize_id
JOIN
status_prizes sp ON sp.id = p.status_prize_id
JOIN
locations l ON l.id = sp.location_id
WHERE
pr.user_id = ? AND pr.share_prize_id = 0 AND pr.from_user = 0 AND l.id = ? AND p.is_delete = 0 AND p.status_prize_id IS NOT NULL
ORDER BY p.status_prize_id"
redeem_sql_completed = ActiveRecord::Base.send(:sanitize_sql_array, [redeem_sql, user_id, location_id])
redeemed_prizes = Prize.find_by_sql(redeem_sql_completed)
return redeemed_prizes.uniq
end
def self.get_shared_prizes(location_id, user_id)
share_sql = "SELECT
p.id, p.level, sp.id as status_prize_id
FROM
prizes p
JOIN
share_prizes shp ON p.id = shp.prize_id
JOIN
status_prizes sp ON sp.id = p.status_prize_id
JOIN
locations l ON l.id = sp.location_id
WHERE
shp.from_user = ? AND shp.share_id = 0 AND l.id = ? AND p.is_delete = 0 AND p.status_prize_id IS NOT NULL
ORDER BY p.status_prize_id"
shared_sql_completed = ActiveRecord::Base.send(:sanitize_sql_array, [share_sql, user_id, location_id])
shared_prizes = Prize.find_by_sql(shared_sql_completed)
return shared_prizes
end
def self.get_ordered_prizes(location_id, user_id)
order_sql = "SELECT
p.id, p.level, sp.id as status_prize_id
FROM
order_items oi
JOIN
orders o ON o.id = oi.order_id AND o.is_paid = 1
JOIN
prizes p ON p.id = oi.prize_id AND p.is_delete = 0
JOIN
status_prizes sp ON p.status_prize_id = sp.id
WHERE
o.user_id = ? AND sp.location_id = ? AND oi.share_prize_id = 0
AND p.is_delete = 0 AND p.status_prize_id IS NOT NULL
ORDER BY p.status_prize_id"
order_sql_completed = ActiveRecord::Base.send(:sanitize_sql_array, [order_sql, user_id, location_id])
ordered_prizes = Prize.find_by_sql(order_sql_completed)
return ordered_prizes
end
def self.get_unlocked_prizes(location_id, points, prize_ids, status_prize_id)
unlocked_prizes = []
total_redemption = 0
status_prize_id = status_prize_id
if status_prize_id.nil?
status_prize_id = StatusPrize.where('location_id = ?', location_id).order('id').first.id
end
sql = "SELECT
stp.id as status_prize_id,
0 as share_prize_id,
p.role as type,
p.id as prize_id,
p.name,
p.level as level_number,
p.redeem_value,
0 as from_user,
null as email,
DATE_FORMAT(NOW(), '%m/%d/%Y %H:%i:%S') as date_time_current,
DATE_FORMAT(CONVERT_TZ(NOW(), @@session .time_zone, '+00:00'), '%m/%d/%Y %H:%i:%S') as date_currents,
null as date_redeem,
null as date_time_redeem,
p.build_menu_id,
p.category_id
FROM
prizes p
JOIN
status_prizes stp ON p.status_prize_id = stp.id
WHERE
stp.location_id = ? AND p.is_delete = 0 AND stp.id = ?"
# In case diner hasn't redeemed, shared or paid any prize, then prize_ids is equal nil
# Else, prize_ids is an array
if prize_ids.nil?
sql = sql + " ORDER BY p.level ASC"
completed_sql = ActiveRecord::Base.send(:sanitize_sql_array, [sql, location_id, status_prize_id])
else
sql = sql + " " + "AND p.id in (?)" + " ORDER BY p.level ASC"
completed_sql = ActiveRecord::Base.send(:sanitize_sql_array, [sql, location_id, status_prize_id, prize_ids])
end
prizes = Prize.find_by_sql(completed_sql)
return prizes
end
def self.get_used_prizes(location_id, user_id, used_prize_ids)
sql = "SELECT
stp.id as status_prize_id,
pr.share_prize_id as share_prize_id,
pr.from_redeem as type,
p.id as prize_id,
p.name,
p.level AS level_number,
p.redeem_value,
pr.from_user AS from_user,
u.email as email,
DATE_FORMAT(CONVERT_TZ(pr.created_at, '+00:00', pr.timezone),
'%m/%d/%Y %H:%i:%S') as date_time_redeem,
DATE_FORMAT(NOW(), '%m/%d/%Y %H:%i:%S') as date_time_current,
DATE_FORMAT(CONVERT_TZ(NOW(), @@session .time_zone, '+00:00'),
'%m/%d/%Y %H:%i:%S') as date_currents,
DATE_FORMAT(pr.created_at, '%m/%d/%Y %H:%i:%S') as date_redeem,
p.build_menu_id,
p.category_id
FROM
prizes p
JOIN
status_prizes stp ON stp.id = p.status_prize_id
JOIN
prize_redeems pr ON p.id = pr.prize_id
LEFT JOIN
users u ON u.id = pr.from_user
WHERE
p.is_delete = 0 and stp.location_id = ? and pr.user_id = ? and p.id in (?)"
completed_sql = ActiveRecord::Base.send(:sanitize_sql_array, [sql, location_id, user_id, used_prize_ids])
prizes = Prize.find_by_sql(completed_sql)
return prizes
end
def self.get_received_prizes(location_id, user_id)
# find prizes what diners received from their friends or restaurant owner
received_sql = "SELECT
stp.id as status_prize_id,
sp.id as share_prize_id,
sp.from_share as type,
p.id as prize_id,
p.name,
p.level AS level_number,
p.redeem_value,
sp.from_user AS from_user,
u.email as email,
null as date_time_redeem,
DATE_FORMAT(NOW(), '%m/%d/%Y %H:%i:%S') as date_time_current,
DATE_FORMAT(CONVERT_TZ(NOW(), @@session .time_zone, '+00:00'), '%m/%d/%Y %H:%i:%S') as date_currents,
null as date_redeem,
p.build_menu_id,
p.category_id
FROM
prizes p
JOIN
status_prizes stp ON stp.id = p.status_prize_id
JOIN
share_prizes sp ON p.id = sp.prize_id
JOIN
users u ON u.id = sp.from_user
WHERE
p.is_delete = 0 AND stp.location_id = ? AND sp.to_user = ? AND is_redeem = 0 AND (sp.is_refunded = 0 OR sp.is_refunded = 1)"
completed_received_sql = ActiveRecord::Base.send(:sanitize_sql_array, [received_sql, location_id, user_id])
received_prizes = Prize.find_by_sql(completed_received_sql)
return received_prizes
end
def self.hide_redeemed_prizes_after_three_hours(prizes)
list_prizes = []
prizes.each do |prize|
if prize[:date_redeem].nil?
list_prizes << prize
else
date_current = Time.strptime(prize[:date_currents], '%m/%d/%Y %H:%M:%S').to_s
date_redeem = Time.strptime(prize[:date_redeem], '%m/%d/%Y %H:%M:%S').to_s
date_time = (Time.parse(date_current) - Time.parse(date_redeem))/3600
if date_time <= 3
list_prizes << prize
else
# If there is a SharePrize with the given Prize id, mark it as limited
share_prize = SharePrize.find_by_prize_id(prize.id)
share_prize.update_attributes(is_limited: 1) unless share_prize.blank?
end
end
end
return list_prizes
end
def self.get_unlocked_prizes_by_location(location_id, points, user_id)
results = []
total_redemption = 0
restauratn_prizes = Prize.joins(:status_prize).where('status_prizes.location_id = ?', location_id).select("prizes.id")
unless restauratn_prizes.empty?
redeemed_prizes = get_redeemed_prizes(location_id, user_id)
shared_prizes = get_shared_prizes(location_id, user_id)
ordered_prizes = get_ordered_prizes(location_id, user_id)
used_prizes = redeemed_prizes | shared_prizes | ordered_prizes
max_used_prize = used_prizes.sort_by{|p| [p.status_prize_id, p.level]}.last
# In case diners haven't yet ordered/shared/redeemed any prize, base on total point of them to determine current prizes
if max_used_prize.nil? || used_prizes.empty?
# get unlocked prizes base on total point of diner
prizes = get_unlocked_prizes(location_id, points, nil, nil)
unlocked_prizes = []
prizes.each do |i|
total_redemption = total_redemption + i.redeem_value
if total_redemption <= points
unlocked_prizes << i
end
end
results = unlocked_prizes
else # diners have used prizes by sharing or ordering or redeeming
redeemed_prize_ids = []
shared_prize_ids = []
ordered_prize_ids = []
redeemed_prizes.each do |redeemed_prize|
redeemed_prize_ids << redeemed_prize.id
end
shared_prizes.each do |shared_prize|
shared_prize_ids << shared_prize.id
end
ordered_prizes.each do |ordered_prize|
ordered_prize_ids << ordered_prize.id
end
used_prize_ids = redeemed_prize_ids | shared_prize_ids | ordered_prize_ids
prizes_by_status = Prize.where('status_prize_id = ?', max_used_prize.status_prize_id).select('id')
# reject prizes were used to get unlocked prizes
prizes_by_status = prizes_by_status.reject{|p| used_prize_ids.include?(p.id)}
unlocked_prizes = get_unlocked_prizes(location_id, points, prizes_by_status, max_used_prize.status_prize_id)
all_redeemed_prizes = get_used_prizes(location_id, user_id, redeemed_prize_ids)
prizes = unlocked_prizes | all_redeemed_prizes
is_redeemed_all_prizes = true
prizes.each do |i|
if i.date_time_redeem != "null" && i.date_time_redeem.nil?
is_redeemed_all_prizes = false
break
end
end
# if diner redeemed all prizes at current status, go to next status and get all prizes will be unlocked
if is_redeemed_all_prizes == true
new_unlocked_prizes = []
if (max_used_prize.status_prize_id + 1) <= StatusPrize.where('location_id = ?', location_id).maximum('id')
new_prizes = get_unlocked_prizes(location_id, points, nil, max_used_prize.status_prize_id + 1)
new_prizes.each do |i|
total_redemption = total_redemption + i.redeem_value
if total_redemption <= points
new_unlocked_prizes << i
end
end
end
results = prizes | new_unlocked_prizes
else
list_prizes_unlocked = []
prizes.each do |i|
total_redemption = total_redemption + i.redeem_value
if total_redemption <= points
list_prizes_unlocked << i
end
end
results = list_prizes_unlocked
end
end
end
return results
end
def self.save_user_prize(location, user, prize)
user_prizes_from_location = UserPrize.where(user_id: user.id, prize_id: prize.id, location_id: location.id)
if user_prizes_from_location.empty?
UserMailer.send_mail_unlock_prize(location.name, user.email, prize.name).deliver
UserPrize.create({
:location_id => location.id,
:is_sent_notification => 1,
:prize_id => prize.id,
:user_id => user.id,
})
message = "Congratulations you've unlocked #{prize.name} prize. Please go to MyPrize to Redeem your prize! Can't wait to see you at #{location.name}."
noti = Notifications.new
noti.from_user = location.owner_id
noti.to_user = user.email
noti.message = message
noti.msg_type = "single"
noti.location_id = location.id
noti.alert_type = PRIZE_ALERT_TYPE
noti.alert_logo = POINT_LOGO
noti.msg_subject= PRIZE_ALERT_TYPE
noti.points = prize.redeem_value
noti.save!
end
end
# 2015-04-23 Dan@Cabforward.com: A grep analysis indicates this method is no longer in use
# def self.check_unlock_prize
# sql = "SELECT location.*
# FROM locations AS location
# JOIN status_prizes sp ON location.id = sp.location_id
# JOIN prizes p ON p.status_prize_id = sp.id
# WHERE location.active = 1"
# locations = Location.find_by_sql(sql)
# locations = locations.uniq{|x| x.id}
# users = User.where('is_register = ? and role = ?', 0, USER_ROLE)
# users.each do |u|
# locations.each do |l|
# # get total points of user at a restaurant
# sql = "
# SELECT
# l.id,
# IFNULL(SUM(CASE WHEN u.is_give = 1 THEN u.points ELSE u.points * (- 1) END), 0) AS total
# FROM locations AS l
# JOIN user_points AS u ON l.id = u.location_id
# WHERE
# u.user_id = ?
# AND u.location_id = ?"
# completed_sql = ActiveRecord::Base.send(:sanitize_sql_array, [sql, u.id, l.id])
# user_point = Location.find_by_sql(completed_sql).first.total
# user_prizes = UserPrize.where(user_id: u.id, location_id: l.id)
# location_status = l.status_prizes.order(:id)
# unless location_status.empty?
# # if user hasn't had any prize
# if user_prizes.empty?
# first_status = location_status.first
# first_status_prizes = first_status.prizes.where('status_prize_id is not null and is_delete = 0')
# unlock_prizes = []
# total_redeem_value = 0
# first_status_prizes.each do |i|
# total_redeem_value = total_redeem_value + i.redeem_value
# if total_redeem_value <= user_point
# unlock_prizes << i
# end
# end
# unlock_prizes.each do |i|
# save_user_prize(l, u, i)
# end
# else
# last_status_prize = user_prizes.last.status_prize
# current_user_prizes_ids = UserPrize.where(user_id: u.id, location_id: l.id, prize_id: prize.id).pluck(:prize_id)
# # compare with user point and list out prize they can unlock
# current_status_prizes = last_status_prize.prizes.where('id not in (?) and is_delete = 0 and status_prize_id is not null', current_user_prizes_ids)
# # Build a list of items that the User can redeem
# total_redeem_value = 0
# unlockable_prize_ids = []
# current_status_prizes.each do |i|
# total_redeem_value = total_redeem_value + i.redeem_value
# if total_redeem_value <= user_point
# unlockable_prize_ids << i
# end
# end
# unlockable_prize_ids.each do |i|
# save_user_prize(l, u, i)
# end
# end
# else
# next
# end
# end
# end
# end
def self.reject_prizes_in_order(current_prizes, location_id, user_id)
prizes = current_prizes
prize_order_sql = "SELECT prize_id, share_prize_id FROM order_items oi
JOIN orders o on o.id = oi.order_id
JOIN locations l on l.id = o.location_id
WHERE o.location_id = #{location_id} AND oi.prize_id IS NOT NULL
AND oi.share_prize_id IS NOT NULL AND oi.is_prize_item = 1
AND o.user_id = #{user_id}"
prizes_in_order = OrderItem.find_by_sql(prize_order_sql)
prizes_in_order.each do |po|
prizes.delete_if do |j|
j.share_prize_id == po.share_prize_id && j.prize_id == po.prize_id
end
end
return prizes
end
# BEGIN WEB SERVER functions----------------------------------------------------------
def self.delete_orders_belong_to_prize(location_id, prize_ids)
orders = Order.where('location_id = ? and is_paid != 1 and is_cancel != 1', location_id)
orders.each do |o|
o.order_items.where('prize_id in (?)', prize_ids).destroy_all
end
end
# END WEB SERVER functions------------------------------------------------------------
end
|
class RenameColumnByHands < ActiveRecord::Migration
def self.up
rename_column :vendors, :business_name, :business_name1
end
end
|
begin
puts "OK!"
0 / 0
puts "No OK!"
rescue Exception => e
puts "Something wrong: #{e.message}"
puts e.backtrace
end
|
class MerchantPolicy
attr_reader :current_merchant, :order
def initialize(current_merchant, order)
@current_merchant = current_merchant
@order = order
end
def index?
@current_merchant.admin? || current_merchant.owner_of?(order)
end
def show?
@current_merchant.admin? || @current_merchant ==@order
end
def update?
@current_merchant.admin?
end
def destroy?
return false if @current_merchant ==@order
@current_merchant.admin?
end
end |
# frozen-string-literal: true
require_relative 'threaded'
# The slowest and most advanced connection pool, dealing with both multi-threaded
# access and configurations with multiple shards/servers.
#
# In addition, this pool subclass also handles scheduling in-use connections
# to be removed from the pool when they are returned to it.
class Sequel::ShardedThreadedConnectionPool < Sequel::ThreadedConnectionPool
# The following additional options are respected:
# :servers :: A hash of servers to use. Keys should be symbols. If not
# present, will use a single :default server.
# :servers_hash :: The base hash to use for the servers. By default,
# Sequel uses Hash.new(:default). You can use a hash with a default proc
# that raises an error if you want to catch all cases where a nonexistent
# server is used.
def initialize(db, opts = OPTS)
super
@available_connections = {}
@connections_to_remove = []
@connections_to_disconnect = []
@servers = opts.fetch(:servers_hash, Hash.new(:default))
remove_instance_variable(:@waiter)
remove_instance_variable(:@allocated)
@allocated = {}
@waiters = {}
add_servers([:default])
add_servers(opts[:servers].keys) if opts[:servers]
end
# Adds new servers to the connection pool. Allows for dynamic expansion of the potential replicas/shards
# at runtime. +servers+ argument should be an array of symbols.
def add_servers(servers)
sync do
servers.each do |server|
unless @servers.has_key?(server)
@servers[server] = server
@available_connections[server] = []
allocated = {}
allocated.compare_by_identity
@allocated[server] = allocated
@waiters[server] = ConditionVariable.new
end
end
end
end
# A hash of connections currently being used for the given server, key is the
# Thread, value is the connection. Nonexistent servers will return nil. Treat
# this as read only, do not modify the resulting object.
# The calling code should already have the mutex before calling this.
def allocated(server=:default)
@allocated[server]
end
# Yield all of the available connections, and the ones currently allocated to
# this thread. This will not yield connections currently allocated to other
# threads, as it is not safe to operate on them. This holds the mutex while
# it is yielding all of the connections, which means that until
# the method's block returns, the pool is locked.
def all_connections
t = Sequel.current
sync do
@allocated.values.each do |threads|
threads.each do |thread, conn|
yield conn if t == thread
end
end
@available_connections.values.each{|v| v.each{|c| yield c}}
end
end
# An array of connections opened but not currently used, for the given
# server. Nonexistent servers will return nil. Treat this as read only, do
# not modify the resulting object.
# The calling code should already have the mutex before calling this.
def available_connections(server=:default)
@available_connections[server]
end
# The total number of connections opened for the given server.
# Nonexistent servers will return the created count of the default server.
# The calling code should NOT have the mutex before calling this.
def size(server=:default)
@mutex.synchronize{_size(server)}
end
# Removes all connections currently available on all servers, optionally
# yielding each connection to the given block. This method has the effect of
# disconnecting from the database, assuming that no connections are currently
# being used. If connections are being used, they are scheduled to be
# disconnected as soon as they are returned to the pool.
#
# Once a connection is requested using #hold, the connection pool
# creates new connections to the database. Options:
# :server :: Should be a symbol specifing the server to disconnect from,
# or an array of symbols to specify multiple servers.
def disconnect(opts=OPTS)
(opts[:server] ? Array(opts[:server]) : sync{@servers.keys}).each do |s|
disconnect_connections(sync{disconnect_server_connections(s)})
end
end
def freeze
@servers.freeze
super
end
# Chooses the first available connection to the given server, or if none are
# available, creates a new connection. Passes the connection to the supplied
# block:
#
# pool.hold(:server1) {|conn| conn.execute('DROP TABLE posts')}
#
# Pool#hold is re-entrant, meaning it can be called recursively in
# the same thread without blocking.
#
# If no connection is immediately available and the pool is already using the maximum
# number of connections, Pool#hold will block until a connection
# is available or the timeout expires. If the timeout expires before a
# connection can be acquired, a Sequel::PoolTimeout is raised.
def hold(server=:default)
server = pick_server(server)
t = Sequel.current
if conn = owned_connection(t, server)
return yield(conn)
end
begin
conn = acquire(t, server)
yield conn
rescue Sequel::DatabaseDisconnectError, *@error_classes => e
sync{@connections_to_remove << conn} if conn && disconnect_error?(e)
raise
ensure
sync{release(t, conn, server)} if conn
while dconn = sync{@connections_to_disconnect.shift}
disconnect_connection(dconn)
end
end
end
# Remove servers from the connection pool. Similar to disconnecting from all given servers,
# except that after it is used, future requests for the server will use the
# :default server instead.
def remove_servers(servers)
conns = []
raise(Sequel::Error, "cannot remove default server") if servers.include?(:default)
sync do
servers.each do |server|
if @servers.include?(server)
conns.concat(disconnect_server_connections(server))
@waiters.delete(server)
@available_connections.delete(server)
@allocated.delete(server)
@servers.delete(server)
end
end
end
nil
ensure
disconnect_connections(conns)
end
# Return an array of symbols for servers in the connection pool.
def servers
sync{@servers.keys}
end
def pool_type
:sharded_threaded
end
private
# The total number of connections opened for the given server.
# The calling code should already have the mutex before calling this.
def _size(server)
server = @servers[server]
@allocated[server].length + @available_connections[server].length
end
# Assigns a connection to the supplied thread, if one
# is available. The calling code should NOT already have the mutex when
# calling this.
#
# This should return a connection if one is available within the timeout,
# or nil if a connection could not be acquired within the timeout.
def acquire(thread, server)
if conn = assign_connection(thread, server)
return conn
end
timeout = @timeout
timer = Sequel.start_timer
sync do
@waiters[server].wait(@mutex, timeout)
if conn = next_available(server)
return(allocated(server)[thread] = conn)
end
end
until conn = assign_connection(thread, server)
elapsed = Sequel.elapsed_seconds_since(timer)
# :nocov:
raise_pool_timeout(elapsed, server) if elapsed > timeout
# It's difficult to get to this point, it can only happen if there is a race condition
# where a connection cannot be acquired even after the thread is signalled by the condition variable
sync do
@waiters[server].wait(@mutex, timeout - elapsed)
if conn = next_available(server)
return(allocated(server)[thread] = conn)
end
end
# :nocov:
end
conn
end
# Assign a connection to the thread, or return nil if one cannot be assigned.
# The caller should NOT have the mutex before calling this.
def assign_connection(thread, server)
alloc = nil
do_make_new = false
sync do
alloc = allocated(server)
if conn = next_available(server)
alloc[thread] = conn
return conn
end
if (n = _size(server)) >= (max = @max_size)
alloc.to_a.each do |t,c|
unless t.alive?
remove(t, c, server)
end
end
n = nil
end
if (n || _size(server)) < max
do_make_new = alloc[thread] = true
end
end
# Connect to the database outside of the connection pool mutex,
# as that can take a long time and the connection pool mutex
# shouldn't be locked while the connection takes place.
if do_make_new
begin
conn = make_new(server)
sync{alloc[thread] = conn}
ensure
unless conn
sync{alloc.delete(thread)}
end
end
end
conn
end
# Return a connection to the pool of available connections for the server,
# returns the connection. The calling code should already have the mutex
# before calling this.
def checkin_connection(server, conn)
available_connections(server) << conn
@waiters[server].signal
conn
end
# Clear the array of available connections for the server, returning an array
# of previous available connections that should be disconnected (or nil if none should be).
# Mark any allocated connections to be removed when they are checked back in. The calling
# code should already have the mutex before calling this.
def disconnect_server_connections(server)
remove_conns = allocated(server)
dis_conns = available_connections(server)
raise Sequel::Error, "invalid server: #{server}" unless remove_conns && dis_conns
@connections_to_remove.concat(remove_conns.values)
conns = dis_conns.dup
dis_conns.clear
@waiters[server].signal
conns
end
# Disconnect all available connections immediately, and schedule currently allocated connections for disconnection
# as soon as they are returned to the pool. The calling code should NOT
# have the mutex before calling this.
def disconnect_connections(conns)
conns.each{|conn| disconnect_connection(conn)}
end
# Return the next available connection in the pool for the given server, or nil
# if there is not currently an available connection for the server.
# The calling code should already have the mutex before calling this.
def next_available(server)
case @connection_handling
when :stack
available_connections(server).pop
else
available_connections(server).shift
end
end
# Returns the connection owned by the supplied thread for the given server,
# if any. The calling code should NOT already have the mutex before calling this.
def owned_connection(thread, server)
sync{@allocated[server][thread]}
end
# If the server given is in the hash, return it, otherwise, return the default server.
def pick_server(server)
sync{@servers[server]}
end
# Create the maximum number of connections immediately. The calling code should
# NOT have the mutex before calling this.
def preconnect(concurrent = false)
conn_servers = sync{@servers.keys}.map!{|s| Array.new(max_size - _size(s), s)}.flatten!
if concurrent
conn_servers.map!{|s| Thread.new{[s, make_new(s)]}}.map!(&:value)
else
conn_servers.map!{|s| [s, make_new(s)]}
end
sync{conn_servers.each{|s, conn| checkin_connection(s, conn)}}
end
# Raise a PoolTimeout error showing the current timeout, the elapsed time, the server
# the connection attempt was made to, and the database's name (if any).
def raise_pool_timeout(elapsed, server)
name = db.opts[:name]
raise ::Sequel::PoolTimeout, "timeout: #{@timeout}, elapsed: #{elapsed}, server: #{server}#{", database name: #{name}" if name}"
end
# Releases the connection assigned to the supplied thread and server. If the
# server or connection given is scheduled for disconnection, remove the
# connection instead of releasing it back to the pool.
# The calling code should already have the mutex before calling this.
def release(thread, conn, server)
if @connections_to_remove.include?(conn)
remove(thread, conn, server)
else
conn = allocated(server).delete(thread)
if @connection_handling == :disconnect
@connections_to_disconnect << conn
else
checkin_connection(server, conn)
end
end
if waiter = @waiters[server]
waiter.signal
end
end
# Removes the currently allocated connection from the connection pool. The
# calling code should already have the mutex before calling this.
def remove(thread, conn, server)
@connections_to_remove.delete(conn)
allocated(server).delete(thread) if @servers.include?(server)
@connections_to_disconnect << conn
end
end
|
require_relative '../lib/trees/tree'
require_relative '../lib/trees/apple_tree'
require_relative '../lib/trees/orange_tree'
require_relative '../lib/trees/pear_tree'
require_relative '../lib/fruits/fruit'
require_relative '../lib/fruits/orange'
require_relative '../lib/fruits/apple'
require_relative '../lib/fruits/pear'
describe "OrangeTree" do
before :each do
@orange_tree = OrangeTree.new
end
it "creates an orange tree" do
expect(@orange_tree).to be_an_instance_of(OrangeTree)
end
it "has height" do
expect(@orange_tree.height).not_to be(nil)
end
it "has age" do
expect(@orange_tree.age).not_to be(nil)
end
it "grows height 10 cm every year" do
orange_tree = OrangeTree.new
orange_tree.age!
expect(orange_tree.height).to eq(10)
end
it "displays no orange error when there aren't oranges" do
orange = @orange_tree.pick_fruit!
expect(orange).to eq("ERROR: No Fruit Available")
end
it "can decide if is able to bear fruit" do
orange_tree = OrangeTree.new
expect(orange_tree.can_bear_fruit?).to be_falsey
16.times{ orange_tree.age! }
expect(orange_tree.can_bear_fruit?).to be_truthy
end
it "gets one year older each time it calls age!" do
orange_tree = OrangeTree.new
16.times{ orange_tree.age! }
expect(orange_tree.age).to eq(16)
end
it "only grows the height until 15 years" do
orange_tree = OrangeTree.new
19.times{ orange_tree.age! }
expect(orange_tree.height).to eq(150)
end
it "dies after 20 years" do
orange_tree = OrangeTree.new
30.times{ orange_tree.age! }
expect(orange_tree.dead?).to be_truthy
end
end
describe "Orange" do
it "has a diameter of 1" do
orange = Orange.new
expect(orange.diameter).to eq(1)
end
end
describe "AppleTree" do
before :each do
@apple_tree = AppleTree.new
end
it "creates an apple tree" do
expect(@apple_tree).to be_an_instance_of(AppleTree)
end
it "has height" do
expect(@apple_tree.height).not_to be(nil)
end
it "has age" do
expect(@apple_tree.age).not_to be(nil)
end
it "grows height 3 cm every year" do
apple_tree = AppleTree.new
apple_tree.age!
expect(apple_tree.height).to eq(3)
end
it "adds 1 year each time age! is called" do
apple_tree = AppleTree.new
apple_tree.age!
expect(apple_tree.age).to eq(1)
end
end
describe "Apple" do
it "has a diameter of 1" do
apple = Apple.new
expect(apple.diameter).to eq(1)
end
end
describe "pearTree" do
before :each do
@pear_tree = PearTree.new
end
it "creates an pear tree" do
expect(@pear_tree).to be_an_instance_of(PearTree)
end
it "has height" do
expect(@pear_tree.height).not_to be(nil)
end
it "has age" do
expect(@pear_tree.age).not_to be(nil)
end
it "grows height 5 cm every year" do
pear_tree = PearTree.new
pear_tree.age!
expect(pear_tree.height).to eq(5)
end
it "adds 1 year each time age! is called" do
pear_tree = PearTree.new
pear_tree.age!
expect(pear_tree.age).to eq(1)
end
end
describe "Pear" do
it "has a diameter of 1" do
pear = Pear.new
expect(pear.diameter).to eq(1)
end
end |
# frozen_string_literal: true
require 'stannum/constraints/boolean'
require 'support/examples/constraint_examples'
RSpec.describe Stannum::Constraints::Boolean do
include Spec::Support::Examples::ConstraintExamples
subject(:constraint) do
described_class.new(**constructor_options)
end
let(:constructor_options) { {} }
let(:expected_options) { {} }
describe '::NEGATED_TYPE' do
include_examples 'should define frozen constant',
:NEGATED_TYPE,
'stannum.constraints.is_boolean'
end
describe '::TYPE' do
include_examples 'should define frozen constant',
:TYPE,
'stannum.constraints.is_not_boolean'
end
describe '.new' do
it 'should define the constructor' do
expect(described_class)
.to be_constructible
.with(0).arguments
.and_any_keywords
end
end
include_examples 'should implement the Constraint interface'
include_examples 'should implement the Constraint methods'
describe '#match' do
let(:match_method) { :match }
let(:expected_errors) { { type: constraint.type } }
let(:expected_messages) do
expected_errors.merge(message: 'is not true or false')
end
describe 'with nil' do
let(:actual) { nil }
include_examples 'should not match the constraint'
end
describe 'with an object' do
let(:actual) { Object.new }
include_examples 'should not match the constraint'
end
describe 'with true' do
let(:actual) { true }
include_examples 'should match the constraint'
end
describe 'with false' do
let(:actual) { false }
include_examples 'should match the constraint'
end
end
describe '#negated_match' do
let(:match_method) { :negated_match }
let(:expected_errors) { { type: constraint.negated_type } }
let(:expected_messages) do
expected_errors.merge(message: 'is true or false')
end
describe 'with nil' do
let(:actual) { nil }
include_examples 'should match the constraint'
end
describe 'with an object' do
let(:actual) { Object.new }
include_examples 'should match the constraint'
end
describe 'with true' do
let(:actual) { true }
include_examples 'should not match the constraint'
end
describe 'with false' do
let(:actual) { false }
include_examples 'should not match the constraint'
end
end
end
|
class CreateVacancies < ActiveRecord::Migration[5.1]
def change
create_table :vacancies do |t|
t.string :title
t.text :description
t.datetime :start_date
t.integer :salary_min
t.integer :salary_max
t.string :location
t.integer :bounty
t.integer :available_position
t.boolean :active
t.timestamps
end
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 with: :exception
def puts! args, label=""
puts "+++ +++ #{label}"
puts args.inspect
end
def create_categories_list c
if c.nil?
@categories_list = []
else
@categories_list = [ c ]
while c.category
@categories_list.unshift c.category
c = c.category
end
end
end
end
|
# encoding: utf-8
class CompaniesController < ApplicationController
before_filter :authenticate_user!, except: [:index, :show]
before_filter :admin_user, only: [:new, :create, :edit, :update, :destroy]
def index
@companies = Company.all
end
def show
@company = Company.find(params[:id])
@feed_entries = @company.feed_entries.page(params[:page]).per_page(12).where('published_at < ?', DateTime.now)
respond_to do |format|
format.html
format.json { render json: @feed_entries }
format.js
end
end
def new
@company = Company.new
end
def edit
@company = Company.find(params[:id])
end
def create
@company = current_user.companies.build(params[:company])
if @company.save
flash[:success] = "Вами успешно была добавлена компания!"
redirect_to @company
else
render action: 'new'
end
end
def update
@company = Company.find(params[:id])
if @company.update_attributes(params[:company])
flash[:success] = "Компания успешно обновлена!"
redirect_to @company
else
render action: 'edit'
end
end
def destroy
@company = Company.find(params[:id])
@company.destroy
respond_to do |format|
format.html { redirect_to companies_url }
format.json { head :no_content }
end
end
private
def admin_user
redirect_to(root_path) unless current_user.admin?
end
end
|
class AddSourceToSongs < ActiveRecord::Migration
def change
add_column :songs, :source, :string, :default => 'direct'
add_column :songs, :soundcloud_id, :integer
end
end
|
module RailsAdmin
module Config
module Actions
class Dashboard < RailsAdmin::Config::Actions::Base
RailsAdmin::Config::Actions.register(self)
require "ibm_watson/authenticators"
require "ibm_watson/text_to_speech_v1"
require "http"
include IBMWatson
register_instance_option :root? do
true
end
register_instance_option :breadcrumb_parent do
nil
end
register_instance_option :controller do
proc do
#if current_user.admin == true
authenticator = Authenticators::IamAuthenticator.new(
apikey: ENV['WATSON']
)
text_to_speech = IBMWatson::TextToSpeechV1.new(
authenticator: authenticator
)
text_to_speech.service_url = ENV['WATSON_URL']
employee = Employee.find_by(user_id: current_user.id)
File.open("app/assets/audios/audio.mp3", "wb") do |audio_file|
response = text_to_speech.synthesize(
text: "Hello #{employee.firstName} #{employee.lastName}. There are currently #{Elevator.count} elevators deployed in the #{Building.count} buildings of your #{Customer.count} customers.Currently, #{Elevator.where(status: 1).count} elevators are not in Running Status and are being serviced, You currently have #{Quote.where(status: true).count} quotes awaiting processing, You currently have #{Lead.count} leads in your contact requests, #{Battery.count} Batteries are deployed across #{Address.pluck(:city).uniq.count} cities
",
accept: "audio/mp3",
voice: "en-US_AllisonVoice"
).result
audio_file.write(response)
end
people = rand(1..60)
c = rand(1..7)
json = JSON.parse(HTTP.get("https://swapi.dev/api/people/#{people}/").body)
phrase = ""
if json["detail"].nil?
json = JSON.parse(HTTP.get("https://swapi.dev/api/people/#{rand(1..2)}/").body)
end
case c
when 1
phrase = "#{json['name']} weighing #{json['mass']} kilograms"
when 2
if !json['films'].nil? && json['films'].count > 0
phrase = "#{json['name']} play in #{json['films'].count} films"
else
phrase = "#{json['name']} never play in a film"
end
when 3
phrase = "#{json['name']} birth in #{json['birth_year']}"
when 4
phrase = "the eyes of #{json['name']} is #{json['eye_color']}"
when 5
phrase = "the gender of #{json['name']} is #{json['gender']}"
when 6
phrase = "the skin color of #{json['name']} is #{json['skin_color']}"
when 7
phrase = "the hair color of #{json['name']} is #{json['hair_color']}"
end
File.open("app/assets/audios/star_wars.mp3", "wb") do |audio_file|
response = text_to_speech.synthesize(
text: phrase,
accept: "audio/mp3",
voice: "en-US_AllisonVoice"
).result
audio_file.write(response)
end
#end
#After you're done processing everything, render the new dashboard
render @action.template_name, status: 200
end
end
register_instance_option :route_fragment do
''
end
register_instance_option :link_icon do
'icon-home'
end
register_instance_option :statistics? do
true
end
end
end
end
end |
module ListMore
class SignUp < UseCase
attr_reader :params
def run params
@params = params
unless verify_fields
return failure "Please check all fields"
end
user = ListMore.users_repo.find_by_username params['username']
if user
return failure "User already exists"
end
user = ListMore::Entities::User.new(params)
user.update_password params['password']
ListMore.users_repo.save user
response = ListMore::CreateSession.run user
success :token => response.token, :user => user
end
def credentials
end
def verify_fields
return false if !(params['username'] && params['password'] && params['password_conf'])
return false if params['password'] != params['password_conf']
true
end
end
end
|
class Pic < ActiveRecord::Base
belongs_to :pin
belongs_to :user
has_attached_file :image, :styles => {:large => "640x480>", :medium => "200x200>", :thumb => "100x100>" }
end
|
class CreateDevelopmentalLevels < ActiveRecord::Migration
def change
create_table :developmental_levels do |t|
t.integer :student_id
t.date :observed_on
t.string :recorder
t.integer :duration
# Facilitated By Adult, in developmental_levels/developmental_level_options
# no selcection = 0
# not present = 1
# fleeting = 2
# constricted = 3
# stable = 4
t.integer :facilitated_by_adult, default: 0
t.integer :initiated_by_child, default: 0
t.integer :sensory_motor, default: 0
t.integer :pleasure, default: 0
t.integer :displeasure, default: 0
t.integer :with_object, default: 0
t.integer :sensory_motor_play, default: 0
t.integer :representational_play,default: 0
t.integer :with_adult_support, default: 0
t.integer :independently, default: 0
t.integer :cross_context_1, default: 0
t.integer :cross_context_2, default: 0
t.integer :cross_context_3, default: 0
t.integer :cross_context_4, default: 0
t.timestamps
end
end
end
|
class CreateTasks < ActiveRecord::Migration[5.0]
def up
create_table :tasks do |t|
t.string :name
t.references :card
t.boolean :done
t.timestamps
end
end
def down
drop_table :tasks
end
end
|
class Api::V1::CompositionsController < ApplicationController
def index
compositions = Composition.all
render json: CompositionSerializer.new(compositions)
end
def create
composition = Composition.new({
characters: composition_params[:characters],
colors: composition_params[:colors],
font_family: composition_params[:font_family],
created_at: composition_params[:date]
})
#find or create artist method
artist = Artist.find_or_create_by(name: composition_params[:artist_name] )
composition.artist = artist
composition.artist_id = artist.id
# byebug
if composition.save
render json: CompositionSerializer.new(composition), status: :accepted
else
render json: {errors: composition.errors.full_messages}, status: :unprocessible_entity
end
end
def show
composition = Composition.find_by(id: params[:id] )
render json: CompositionSerializer.new(composition)
end
private
def composition_params
params.require(:composition).permit(:characters, :colors, :placements, :font_family, :artist_name, :created_at)
end
end
|
class LikesController < ApplicationController
# POST /likes
# POST /likes.json
def create
@attendance = Attendance.find(params[:attendance_id])
@like = Like.new(:attendance_id => @attendance.id, :user_id => current_user.id, :conference_id => @attendance.conference.id)
logger.info(@like.attendance_id.to_s + " " + @like.user_id.to_s)
respond_to do |format|
format.html {
@like.save
redirect_to conference_attendee_path(@attendance.conference_id, params[:attendance_id])
}
format.json {
if (@like.save)
render json: @like, status: :created, location: @like
else
render json: @like.errors, status: :unprocessable_entity
end
}
end
end
# DELETE /likes/1
# DELETE /likes/1.json
def destroy
@like = Like.find(params[:id])
@attendance = Attendance.find(@like.attendance_id)
@like.destroy
respond_to do |format|
format.html { redirect_to conference_attendee_path(@attendance.conference_id, @attendance.id) }
format.json { head :no_content }
end
end
end
|
class Session < ActiveRecord::Base
belongs_to :experiment
belongs_to :lab, inverse_of: :sessions
has_many :registrations, :dependent => :delete_all
has_many :users, through: :registrations
before_validation :set_duration_if_nil
after_update :check_for_suspend
before_save :reset_reminder
validate :validate_time_range
validates :required_subjects, numericality: { only_integer: true, greater_than: 0 }
validates_presence_of :lab
def check_for_suspend
if self.finished
self.registrations.where(shown_up: false).each do |r|
r.user.check_and_suspend!
end
end
end
def reset_reminder
if remind_at_changed?
self.reminded = false
end
true
end
def set_duration_if_nil
self.duration ||= Time.at(end_time - start_time).utc
end
def validate_time_range
if start_time.advance(hours: duration.hour, minutes: duration.min) > end_time
errors.add(:end_time, "cannot be lesser than start time with duration")
end
if registration_deadline > start_time
errors.add(:registration_deadline, "cannot be later than start time")
end
if remind_at_changed? and remind_at_change[1] < Time.now
errors.add(:remind_at, "cannot be earlier then now")
end
t = Session
.where.not(id: self.id)
.where('start_time <= ? and ? <= end_time and lab_id = ?', self.end_time, self.start_time, self.lab_id)
t.each do |f|
errors.add(:selected_time, "is overlapping with the session of #{f.experiment.name} (from #{f.start_time_display} to #{f.end_time_display})")
end
end
def registered_subjects
self.registrations.count
end
def to_s
"#{start_time.strftime("%d %B %Y")} at #{start_time.strftime("%l:%M%P")} - #{end_time.strftime("%l:%M%P")} in #{self.lab.name} Lab"
end
def start_time_display
start_time.strftime("%d %B %Y at %l:%M%P")
end
def end_time_display
end_time.strftime("%d %B %Y at %l:%M%P")
end
end |
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure("2") do |config|
# All Vagrant configuration is done here. See: vagrantup.com.
# Build against CentOS 6.4 minimal, without any config management utilities.
config.vm.box = "centos64"
config.vm.box_url = "http://puppet-vagrant-boxes.puppetlabs.com/centos-64-x64-vbox4210-nocm.box"
# Enable host-only access to the machine using a specific IP.
config.vm.network :private_network, ip: "192.168.33.10"
# Alternatively, you can use NAT/bridged networking by using :public_network
# config.vm.network :public_network
# You can share additional folders to the guest VM; the first argument is the
# path to the folder on the host, the second is the path on the guest on which
# to mount the folder.
# config.vm.synced_folder "../data", "/vagrant_data"
# Uncomment the line below to use NFS for the default synced folder on non-
# Windows platforms. This should speed up filesystem access considerably.
# config.vm.synced_folder ".", "/vagrant", :nfs => !RUBY_PLATFORM.downcase.include?("w32")
# Configuration for the VirtualBox provider.
config.vm.provider :virtualbox do |v|
v.customize ["modifyvm", :id, "--name", "jenkins-sandbox"]
v.customize ["modifyvm", :id, "--natdnshostresolver1", "on"]
v.customize ["modifyvm", :id, "--memory", 512]
v.customize ["modifyvm", :id, "--cpus", 2]
v.customize ["modifyvm", :id, "--ioapic", "on"]
# Uncomment this line to boot into the GUI to show console output.
#v.gui = true
end
# Set the name of the VM. See: http://stackoverflow.com/a/17864388/100134
config.vm.define :jenkins do |jenkins_config|
end
# Run setup.sh shell script to install required packages.
config.vm.provision :shell, :path => "scripts/setup.sh"
end
|
module GapIntelligence
# @see https://api.gapintelligence.com/api/doc/v1/promotions.html
module Promotions
# Requests a list of promotions
#
# @param params [Hash] parameters of the http request
# @param options [Hash] the options to make the request with
# @yield [req] The Faraday request
# @return [RecordSet<Promotion>] the requested merchants
# @see https://api.gapintelligence.com/api/doc/v1/promotions/index.html
def promotions(params = {}, options = {}, &block)
default_option(options, :record_class, Promotion)
perform_request(:get, 'promotions', options.merge(params: params), &block)
end
end
end
|
require_relative '../../spec_helper'
RSpec.describe OpenAPIParser::Schemas::RequestBody do
let(:root) { OpenAPIParser.parse(petstore_schema, {}) }
describe 'correct init' do
subject { operation.request_body }
let(:paths) { root.paths }
let(:path_item) { paths.path['/pets'] }
let(:operation) { path_item.post }
it do
expect(subject).not_to be nil
expect(subject.object_reference).to eq '#/paths/~1pets/post/requestBody'
expect(subject.description).to eq 'Pet to add to the store'
expect(subject.required).to eq true
expect(subject.content.class).to eq Hash
expect(subject.root.object_id).to be root.object_id
end
end
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
evedata ||= Faraday.new(:url => "http://evedata.herokuapp.com") do |conn|
conn.request :json
conn.response :json, :content_type => /\bjson$/
conn.adapter Faraday.default_adapter
end
puts "Caching: all solar systems: /solar_systems?limit=5500"
Rails.cache.fetch("solar_systems.all", compress: true) { evedata.get("/solar_systems?limit=5500").body }
puts "Caching: blueprint groups: /categories/9/groups?limit=200"
all_groups = Rails.cache.fetch("category.9.groups") { evedata.get("/categories/9/groups?limit=200").body }
puts "Caching: all blueprint group members: /blueprints?group_id=XXXX&limit=200"
puts "WARNING: This will take a while :{\n"
all_groups.each do |group|
blueprints = Rails.cache.fetch("group.#{group['id']}.members") { evedata.get("/blueprints?group_id=#{group['id']}&limit=200").body }
end
puts "Caching: all items: /items?limit=1000000"
puts "and you thought the last one took a while..."
Item.all
puts "Whew... all done!!"
|
json.board do
json.extract! @board, :id, :title
json.userIds @board.users.ids
end
json.lists do
@board.lists.each do |list|
json.set! list.id do
json.extract! list, :id, :title
json.cardIds list.cards.order('ord').ids
end
end
end
json.cards do
@board.lists.each do |list|
list.cards.each do |card|
json.set! card.id do
json.extract! card, :id, :title, :list_id
end
end
end
end |
###
### Provides a hash of "cheat_prefix+hostname" => count
### Useful for functions a user may not do too often
###
module Ricer::Plug::Extender::HasCheatingDetection
OPTIONS ||= {
max_attempts: 1
}
def has_cheating_detection(options={})
class_eval do |klass|
# Options
merge_options(options, OPTIONS)
public
# Sanity
options[:max_attempts] = options[:max_attempts].to_i
unless options[:max_attempts].between?(1, 10)
throw "#{klass.name} has_cheating_detection max_attempts has to be between 1 and 10 but is: #{options[:max_attempts]}"
end
klass.instance_variable_set(:@max_cheat_attempts, options[:max_attempts])
# Register klass variables for reload cleanup
klass.register_class_variable(:@cheat_cache)
klass.register_class_variable(:@max_cheat_attempts)
klass.instance_variable_define(:@cheat_cache, {})
# Call this for checking
def cheat_detection!(slot)
raise Ricer::ExecutionException.new(cheat_detection_message) if cheat_detected?(slot)
end
def cheat_detected?(slot)
cheat_attempts(slot) >= cheat_max_attempts
end
def cheat_detection_message
I18n.t('ricer.plug.extender.has_cheating_detection.cheating_detected', :max_attempts => cheat_max_attempts)
end
def cheat_attempts(slot)
cheat_cache[slot][cheat_key]||0 rescue 0
end
# Call this for inserting
def cheat_attempt(slot)
key = cheat_key
cache = cheat_cache
cache[slot] ||= {}
cache[slot][key] ||= 0
cache[slot][key] += 1
end
# Clearing
def cheat_clear(slot)
cheat_cache.delete(slot) rescue nil
end
# Purge
def cheat_clear_all()
self.class.instance_variable_set(:@cheat_cache, {})
end
private
# Get the IP hostmask cloak part to detect renaming techniques
def cheat_key
current_message.prefix.substr_from('!').substr_from('@') rescue 'HAX0R'
end
def cheat_cache
self.class.instance_variable_get(:@cheat_cache)
end
def cheat_max_attempts
self.class.instance_variable_get(:@max_cheat_attempts)
end
end
end
end
|
# frozen_string_literal: true
require 'omniauth-oauth2'
require 'jwt'
module OmniAuth
module Strategies
class Hydra1 < OmniAuth::Strategies::OAuth2
option :client_options, {
site: 'https://auth-v1.raspberrypi.org',
authorize_url:'https://auth-v1.raspberrypi.org/oauth2/auth',
token_url: 'https://auth-v1.raspberrypi.org/oauth2/token'
}
def authorize_params
super.tap do |params|
%w[scope client_options login_options].each do |v|
params[v.to_sym] = request.params[v] if request.params[v]
end
end
end
def callback_url
full_host + callback_path
end
uid { raw_info['sub'].to_s }
info do
{
'email' => email,
'username' => username,
'name' => fullname,
'nickname' => nickname,
'image' => image,
}
end
extra do
{
'raw_info' => raw_info
}
end
def raw_info
@raw_info ||= (JWT.decode access_token.params['id_token'], nil, false)[0]
end
def email
raw_info['email']
end
# <13 accounts have username instead of email
def username
raw_info['username']
end
def nickname
raw_info['nickname']
end
# use fullname to avoid clash with 'name'
def fullname
raw_info['name']
end
def image
# deserialise openid claim into auth schema
raw_info['picture']
end
end
end
end
OmniAuth.config.add_camelization 'hydra1', 'Hydra1'
|
class VideoGameResource < ApplicationResource
attributes :title
has_one :user
before_create { _model.user = current_user }
before_create { authorize(_model, :create?) }
before_update { authorize(_model, :update?) }
before_remove { authorize(_model, :destroy?) }
def self.creatable_fields(context)
super - [:user]
end
def self.updatable_fields(context)
super - [:user]
end
def self.records(options = {})
user = current_user(options)
Pundit.policy_scope!(user, VideoGame)
end
end
|
class Post < ActiveRecord::Base
belongs_to :category
scope :rails, -> { where(category_id: 1) }
extend FriendlyId
friendly_id :title, :use => [:slugged, :finders]
mount_uploader :image, ImageUploader
end
|
class AddDataToOwners < ActiveRecord::Migration
def change
add_reference :owners, :profile, index: true, foreign_key: true
add_column :owners, :mon, :boolean, null: false, default: false
add_column :owners, :tue, :boolean, null: false, default: false
add_column :owners, :wed, :boolean, null: false, default: false
add_column :owners, :thu, :boolean, null: false, default: false
add_column :owners, :fri, :boolean, null: false, default: false
add_column :owners, :sat, :boolean, null: false, default: false
add_column :owners, :sun, :boolean, null: false, default: false
add_column :owners, :start, :time
add_column :owners, :end, :time
add_column :owners, :time_per_client, :time
end
end |
# -*- mode: ruby -*-
# vi: set ft=ruby :
# All Vagrant configuration is done below. The "2" in Vagrant.configure
# configures the configuration version (we support older styles for
# backwards compatibility). Please don't change it unless you know what
# you're doing.
Vagrant.configure(2) do |config|
config.vm.box = "ubuntu/trusty64"
config.vm.network "forwarded_port", guest: 80, host: 8080
config.vm.define "pvw" do |node|
end
# Provider-specific configuration so you can fine-tune various
# backing providers for Vagrant. These expose provider-specific options.
# Example for VirtualBox:
# Dynamically allocate memory and cpus,
# see https://stefanwrobel.com/how-to-make-vagrant-performance-not-suck
config.vm.provider "virtualbox" do |v|
host = RbConfig::CONFIG['host_os']
# Give VM 1/4 system memory & access to 1/2 of the cpu cores on the host
if host =~ /darwin/
cpus = `sysctl -n hw.ncpu`.to_i
cpus = [cpus / 2, 1].max
# sysctl returns Bytes and we need to convert to MB
mem = `sysctl -n hw.memsize`.to_i / 1024 / 1024 / 4
elsif host =~ /linux/
cpus = `nproc`.to_i
cpus = [cpus / 2, 1].max
# meminfo shows KB and we need to convert to MB
mem = `grep 'MemTotal' /proc/meminfo | sed -e 's/MemTotal://' -e 's/ kB//'`.to_i / 1024 / 4
else # Guess!
cpus = 2
mem = 4096
end
v.customize ["modifyvm", :id, "--memory", mem]
v.customize ["modifyvm", :id, "--cpus", cpus]
v.customize ["modifyvm", :id, "--nictype1", "virtio"]
v.customize ["modifyvm", :id, "--natdnshostresolver1", "on"]
v.customize ["modifyvm", :id, "--natdnsproxy1", "on"]
end
config.vm.provision "ansible" do |ansible|
ansible.compatibility_mode = '2.0'
ansible.groups = {
"all" => ["pvw"]
}
ansible.verbose = "vvvv"
ansible.extra_vars = {
default_user: "vagrant",
virtualbox: true,
port: 8080
}
ansible.playbook = "ansible-deprecated/site.yml"
end
end
|
require 'open-uri'
module Usda
class Downloader
TEMP_DIR = 'usda_temp'
ZIP_FILE_URL = "http://www.ars.usda.gov/SP2UserFiles/Place/12354500/Data/SR24/dnload/sr24.zip"
def run
download
unzip
end
private
def download
puts "Downloading #{ZIP_FILE_URL}..."
@zip_file = open(ZIP_FILE_URL)
rescue OpenURI::HTTPError
puts "USDA data files have moved. Apparently the government doesn't believe in permalinks..."
end
def unzip
return if @zip_file.nil?
puts "Unzipping #{File.basename ZIP_FILE_URL}..."
# todo - windows support?
`unzip #{@zip_file.path} -d #{TEMP_DIR}`
# return an array of all absolute filepaths unzipped
relative_files = Dir.glob(File.join(TEMP_DIR, "*.txt")).map
absolute_files = relative_files.map{ |file| File.join Dir.getwd, file }
rescue Errno::ENOENT
puts "Error unzipping the data files. Do you have the command-line utility 'unzip' installed?"
end
end
end
|
class OpenSourceStats
class User
attr_accessor :login
def initialize(login)
@login = login
end
# Returns an array of in-scope Events from the user's public activity feed
def events
@events ||= begin
if self.class == OpenSourceStats::User
events = client.user_public_events login, :per_page => 100
else
events = client.organization_public_events name, :per_page => 100
end
events.concat client.get client.last_response.rels[:next].href while next_page?
events = events.map { |e| Event.new(e) }
events.select { |e| e.in_scope? }
end
end
private
# Helper method to access the shared Octokit instance
def client
OpenSourceStats.client
end
# Helper method to improve readability.
# Asks is there another page to the results?
# Looks at both pagination and if we've gone past our allowed timeframe
def next_page?
client.last_response.rels[:next] &&
client.rate_limit.remaining > 0 &&
client.last_response.data.last[:created_at] >= OpenSourceStats.start_time
end
end
end
|
# frozen_string_literal: true
class Course < ApplicationRecord
include Auditable
include Delegable
include SplitMethods
include TimeZonable
extend FriendlyId
zonable_attribute :next_start_time
strip_attributes collapse_spaces: true
friendly_id :name, use: [:slugged, :history]
belongs_to :organization
has_many :events, dependent: :restrict_with_error
has_many :splits, dependent: :destroy
has_one_attached :gpx
delegate :stewards, to: :organization
accepts_nested_attributes_for :splits, reject_if: lambda { |s| s[:distance_from_start].blank? && s[:distance_in_preferred_units].blank? }
scope :used_for_organization, -> (organization) { organization.courses }
scope :standard_includes, -> { includes(:splits) }
validates_presence_of :name
validates_uniqueness_of :name, case_sensitive: false
validates :gpx,
content_type: %w[application/gpx+xml text/xml application/xml application/octet-stream],
size: {less_than: 500.kilobytes}
def to_s
slug
end
def earliest_event_date
events.earliest&.start_time
end
def most_recent_event_date
events.most_recent&.start_time
end
def visible_events
events.visible
end
def home_time_zone
events.latest&.home_time_zone
end
def distance
@distance ||= finish_split.distance_from_start if finish_split.present?
end
def track_points
return [] unless gpx.attached?
return @track_points if defined?(@track_points)
file = gpx.download
gpx_file = GPX::GPXFile.new(gpx_data: file)
points = gpx_file.tracks.flat_map(&:points)
@track_points = points.map { |track_point| {lat: track_point.lat, lon: track_point.lon} }
end
def vert_gain
@vert_gain ||= finish_split.vert_gain_from_start if finish_split.present?
end
def vert_loss
@vert_loss ||= finish_split.vert_loss_from_start if finish_split.present?
end
def simple?
splits_count < 3
end
end
|
class Pubsub::BaseController < ActionController::API
before_action :validate_bearer_token!
private
def validate_bearer_token!
begin
token = Authenticator.access_token(request.headers["Authorization"])
unless Authenticator.validate_token(token)
head :unauthorized
end
rescue Authenticator::Error => err
head :bad_request
end
end
end
|
require 'skyrocket/version'
module Skyrocket
autoload :Asset, "skyrocket/asset"
autoload :AssetDependency, "skyrocket/asset_dependency"
autoload :AssetLocator, "skyrocket/asset_locator"
autoload :AssetFactory, "skyrocket/asset_factory"
autoload :AssetManager, "skyrocket/asset_manager"
autoload :AssetWriter, "skyrocket/asset_writer"
autoload :CoffeescriptProcessor, "skyrocket/coffeescript_processor"
autoload :DependencySearcher, "skyrocket/dependency_searcher"
autoload :DirectiveProcessor, "skyrocket/directive_processor"
autoload :DirectiveReader, "skyrocket/directive_reader"
autoload :EmptyProcessor, "skyrocket/empty_processor"
autoload :ErbProcessor, "skyrocket/erb_processor"
autoload :JavascriptProcessor, "skyrocket/javascript_processor"
autoload :LessProcessor, "skyrocket/less_processor"
autoload :Processor, "skyrocket/processor"
autoload :ProcessorFactory, "skyrocket/processor_factory"
autoload :AssetNotFoundError, "skyrocket/errors"
autoload :CircularReferenceError, "skyrocket/errors"
autoload :NoValidProcessorError, "skyrocket/errors"
autoload :PathNotInAssetsError, "skyrocket/errors"
end
|
class Djoque < ApplicationRecord
belongs_to :djoker
has_many :likes
end
|
require 'tempfile'
module RubyMelee
class FakeWardenClient
def self.launch_container
return 'fake-container-handle'
end
def self.run(container, content)
# create temp file
file = Tempfile.new('melee.rb')
file.write content
file.close
# run it
output = `ruby #{file.path} 2>&1`
# kill the temp file
file.unlink
[output, container]
end
def self.destroy(container)
false
end
end
end |
require 'rake'
require 'pathname'
module Lightspeed
# Like Rake::FileCreationTask (which is used primarily for creating
# directories), but used for creating symbolic links. This task will
# always be needed until a symlink exists at the path specified by
# +name+.
#
class SymlinkCreationTask < Rake::FileTask
# Needed until a symlink exists at the path specified by +name+.
def needed?
! File.symlink?(name)
end
# Use the linked file's timestamp if it exists, otherwise this
# timestamp is earlier than any other timestamp.
def timesteamp
if File.exist?(name) && File.symlink?(name)
File.mtime(File.realdirpath(name.to_s))
else
Rake::EARLY
end
end
end
end
|
class CreateMemberships < ActiveRecord::Migration
def change
create_table :memberships do |t|
t.integer :donor_id, null: false
t.integer :amount_in_cents, null: false
t.integer :year, null: false
t.foreign_key :donors, dependent: :destroy
t.timestamps null: false
end
end
end
|
require "test_helper"
require "fluent/plugin/parser_apache"
require "fluent/plugin/parser_nginx"
module RegexpPreview
class SingleLineTest < ActiveSupport::TestCase
data("regexp" => ["regexp", Fluent::Plugin::RegexpParser, { "expression" => "(?<catefory>\[.+\])", "time_format" => "%Y/%m/%d" }],
"ltsv" => ["ltsv", Fluent::Plugin::LabeledTSVParser, {}],
"json" => ["json", Fluent::Plugin::JSONParser, {}],
"csv" => ["csv", Fluent::Plugin::CSVParser, { "keys" => "column1,column2" }],
"tsv" => ["tsv", Fluent::Plugin::TSVParser, { "keys" => "column1,column2" }],
"syslog" => ["syslog", Fluent::Plugin::SyslogParser, {}],
"apache" => ["apache", Fluent::Plugin::ApacheParser, {}],
"nginx" => ["nginx", Fluent::Plugin::NginxParser, {}])
test "create parser plugin instance from selected plugin name" do |(name, klass, config)|
preview = RegexpPreview::SingleLine.new("log_file.log", name, config)
assert_instance_of(klass, preview.plugin)
end
sub_test_case "#matches" do
test "regexp" do
config = {
"expression" => "(?<regexp>bar)", # bar from error0.log
"time_format" => "time_format",
}
preview = RegexpPreview::SingleLine.new(fixture_path("error0.log"), "regexp", config)
matches = [
{
whole: "bar",
matches: [
{ key: "regexp", matched: "bar", pos: [0, 3] }
]
}
]
assert_equal(config, preview.matches[:pluginConfig])
assert_equal(matches,preview.matches[:matches])
end
test "csv" do
config = { "keys" => "column1,column2" }
preview = RegexpPreview::SingleLine.new(fixture_path("error0.log"), "csv", config)
assert do
preview.matches[:matches].empty?
end
end
test "syslog" do
config = {
"time_format" => "%Y-%m-%d %H:%M:%S %z",
"keep_time_key" => true
}
preview = RegexpPreview::SingleLine.new(fixture_path("error4.log"), "syslog", config)
matches = [
{
whole: "2014-05-27 10:54:37 +0900 [info]: listening fluent socket on 0.0.0.0:24224",
matches: [
{ key: "time", matched: "2014-05-27 10:54:37 +0900", pos: [0, 25] },
{ key: "host", matched: "[info]:", pos: [26, 33] },
{ key: "ident", matched: "listening", pos: [34, 43] },
{ key: "message", matched: "24224", pos: [69, 74] }
]
}
]
assert_equal(matches, preview.matches[:matches])
end
test "syslog when keep_time_key is false" do
config = {
"time_format" => "%Y-%m-%d %H:%M:%S %z",
"keep_time_key" => false
}
preview = RegexpPreview::SingleLine.new(fixture_path("error4.log"), "syslog", config)
matches = [
{
whole: "2014-05-27 10:54:37 +0900 [info]: listening fluent socket on 0.0.0.0:24224",
matches: [
{ key: "host", matched: "[info]:", pos: [26, 33] },
{ key: "ident", matched: "listening", pos: [34, 43] },
{ key: "message", matched: "24224", pos: [69, 74] }
]
}
]
assert_equal(matches, preview.matches[:matches])
end
end
end
end
|
# frozen_string_literal: true
require_relative '../lib/relax.rb'
describe Relax::ColorSpace::Rgba do
let(:my_color) { Relax::ColorSpace::Rgba.new(1, 1, 1, 0.8) }
context 'Correct instantiating' do
it 'Instantiate a Relax::ColorSpace::Rgba object by default method' do
expect(my_color).to be_a Relax::ColorSpace::Rgba
end
it 'Instantiate a Relax::ColorSpace::Rgba object with alpha=1.0' \
'if alpha channel is not specified' do
my_color_no_alpha = Relax::ColorSpace::Rgba.new(1, 1, 1)
expect(my_color_no_alpha).to be_a Relax::ColorSpace::Rgba
expect(my_color_no_alpha.a).to equal 1.0
end
end
end
describe Relax::ColorSpace::Rgba do
# let(:my_color) {Relax::ColorSpace::Rgba.new(1, 1, 1, 0.8)}
context 'Instance initialization errors' do
it 'Raises ArgumentError when instantiating' \
'an object with a wrong argument' do
expect { Relax::ColorSpace::Rgba.new(10) }.to raise_error ArgumentError
end
it 'Raises ArgumentError when instantiating' \
'an object with a wrong argument' do
expect { Relax::ColorSpace::Rgba.new('a', 10, 10, 1) }
.to raise_error ArgumentError
end
it 'Raises ChannelsOutOfRange when instantiating' \
'an object with a wrong argument' do
expect { Relax::ColorSpace::Rgba.new(256, 0, 0, 0) }
.to raise_error Relax::Errors::Rgba::ChannelsOutOfRange
expect { Relax::ColorSpace::Rgba.new(-1, 0, 0, 0) }
.to raise_error Relax::Errors::Rgba::ChannelsOutOfRange
expect { Relax::ColorSpace::Rgba.new(1, 0, 0, 1.1) }
.to raise_error Relax::Errors::Rgba::ChannelsOutOfRange
end
end
end
describe Relax::ColorSpace::Rgba do
let(:my_color) { Relax::ColorSpace::Rgba.new(1, 1, 1, 0.8) }
context 'Conversion to HEX' do
it 'Returns a hex colorspace coded string' do
expect(my_color.to_hex).to be_a String
end
it 'Returns a String which can be used to ' \
'instantiate a ColorSpace::Hex object' do
colorspace_hex = Relax::ColorSpace::Hex.new(my_color.to_hex)
expect(colorspace_hex).to be_a Relax::ColorSpace::Hex
end
it 'Returns the hex colorspace string when called .to_hex' do
expect(my_color.to_hex).to be_a String
expect(my_color.to_hex).to eq '010101'
end
end
end
describe Relax::ColorSpace::Rgba do
let(:my_color) { Relax::ColorSpace::Rgba.new(1, 1, 1, 0.8) }
context 'Conversion to HSL' do
it 'It returns an Array with correct conversion' do
rgb_color = Relax::ColorSpace::Rgba.new(250, 28, 129, 0.3)
expect(rgb_color.to_hsla).to eq [333, 96, 55, 0.3]
end
it 'It returns an Hash with correct conversion' do
rgb_color = Relax::ColorSpace::Rgba.new(250, 28, 129, 0.55)
expect(rgb_color.to_hsla_hash)
.to eq({ hue: 333, saturation: 96, lightness: 55, alpha: 0.55 })
end
it 'Returns a Hash which can be used' \
'to instantiate a ColorSpace::Hsl object' do
hsla_hash = my_color.to_hsla_hash
hsl_colorspace = Relax::ColorSpace::Hsla.new(hsla_hash[:hue],
hsla_hash[:saturation],
hsla_hash[:lightness],
hsla_hash[:alpha])
expect(hsl_colorspace).to be_a Relax::ColorSpace::Hsla
end
end
end
describe Relax::ColorSpace::Rgba do
let(:my_color) { Relax::ColorSpace::Rgba.new(1, 1, 1, 0.8) }
context 'Other methods' do
it 'Can be converted to Relax::Color' \
'by calling to_relax_color' do
expect(my_color.to_relax_color).to be_a Relax::Color
end
it 'Returns an array when called .to_a' do
expect(my_color.to_a).to eq [1, 1, 1, 0.8]
end
it 'Returns an hash when called .to_h' do
expect(my_color.to_h)
.to eq({ red: 1, green: 1, blue: 1, alpha: 0.8 })
end
it 'Returns the hex colorspace string' \
'starting with # when called .to_html_hex' do
html_hex = my_color.to_html_hex
expect(html_hex).to be_a String
expect(html_hex[1..-1]).to eq '010101'
expect(html_hex[0]).to eq '#'
end
end
end
describe Relax::ColorSpace::Rgba do
let(:my_color) { Relax::ColorSpace::Rgba.new(1, 1, 1, 0.8) }
context 'Transparency, opacity, light?, dark?' do
it 'Respond to .transparent? returning true or false' do
expect(my_color.transparent?).to be true
expect(my_color.transparent?).to be true
end
it 'Returns true or false when a color is dark' do
dark_color = Relax::ColorSpace::Rgba.new(115, 151, 101)
expect(dark_color.dark?).to be true
expect(dark_color.light?).to be false
end
it 'Returns true or false when a color is light' do
light_color = Relax::ColorSpace::Rgba.new(122, 155, 105)
expect(light_color.dark?).to be false
expect(light_color.light?).to be true
end
end
end
describe Relax::ColorSpace::Rgba do
let(:my_color) { Relax::ColorSpace::Rgba.new(1, 1, 1, 0.8) }
context 'Opacity' do
it 'Sets alpha to 1.0 calling .opaque!, returning true if done' do
my_transparent_color = Relax::ColorSpace::Rgba.new(1, 1, 1, 0.8)
expect(my_transparent_color.opaque!).to be true
expect(my_transparent_color.a).to eq 1.0
end
it 'Sets alpha to 1 calling .opaque!, returns false when already opaque' do
my_opaque_color = Relax::ColorSpace::Rgba.new(1, 1, 1)
expect(my_opaque_color.opaque!).to be false
expect(my_opaque_color.a).to eq 1.0
end
it 'Returns a new Object with alpha channel set to 1.0' \
'calling .opaque if the object is transparent' do
my_transparent_color = Relax::ColorSpace::Rgba.new(1, 1, 1, 0.8)
my_opaque_color = Relax::ColorSpace::Rgba.new(1, 1, 1)
expect(my_opaque_color).not_to equal my_transparent_color
expect(my_opaque_color.a).to eq 1.0
end
it 'Returns the same Object calling .opaque if it is already opaque' do
my_opaque_color = Relax::ColorSpace::Rgba.new(1, 1, 1)
expect(my_opaque_color.opaque).to equal my_opaque_color
expect(my_opaque_color.a).to eq 1.0
end
end
end
|
require 'rails_helper'
RSpec.describe ContactsController, :type => :controller do
login_user
describe "GET new" do
it "returns http success" do
get :new
expect(response).to have_http_status(:success)
end
it "renders the new template" do
get :new
expect(response).to render_template(:new)
end
end
describe "GET index" do
it "returns http success" do
get :index, :page =>1, :search => " "
expect(response).to have_http_status(:success)
end
it "populates an array of contacts" do
user = FactoryGirl.create(:user)
sign_in user
contact = FactoryGirl.create(:contact)
user.contacts << contact
get :index , :page =>1
expect(assigns(:contacts)).to eq(user.contacts)
end
end
describe "POST create" do
context "with valid attributes" do
subject{
user = FactoryGirl.create(:user)
sign_in user
post :create, contact: FactoryGirl.attributes_for(:contact)
}
it "saves the new contact in the database" do
expect{subject}.to change(Contact,:count).by(1)
end
it "renders flash[:success] message" do
subject
expect(flash[:success]).to match (/Contato salvo com sucesso!/)
end
it "renders the create template" do
subject
expect(response).to render_template(:create)
end
end
context "with invalid attributes" do
subject {post :create, contact: FactoryGirl.attributes_for(:contact, name:"")}
it "doesn't save contact in the database" do
expect{subject}.to change(Contact,:count).by(0)
end
it "renders flash[:warning] message" do
subject
expect(flash[:warning]).to match(/O contato não pode ser salvo!/)
end
it "renders the error template" do
subject
expect(response).to render_template("contacts/error.html.erb")
end
end
end
describe "PUT update" do
context "with valid attributes" do
subject(:user) { FactoryGirl.create(:user_with_contacts) }
let(:contact) {user.contacts.first }
it "locates the requested contact" do
sign_in user
put :update, id: contact, contact: FactoryGirl.attributes_for(:contact)
expect(assigns(:contact)).to eq(contact)
end
it "change contact attributes" do
sign_in user
put :update, id: contact, contact: FactoryGirl.attributes_for(:contact, name: "outro")
contact.reload
expect(contact.name).to match /outro/
end
it "redirects to the updated contact" do
sign_in user
put :update, id: contact, contact: FactoryGirl.attributes_for(:contact)
expect(response).to redirect_to contacts_url
end
end
context "with invalid attributes" do
subject(:user) { FactoryGirl.create(:user_with_contacts) }
let!(:contact_no_change){user.contacts.first }
let(:contact) {user.contacts.first }
it "does not change contact" do
sign_in user
put :update, id: contact, contact: FactoryGirl.attributes_for(:contact, name: nil)
contact.reload
expect(contact.name).to eq(contact_no_change.name)
end
it "re-renders the edit action" do
sign_in user
put :update, id: contact, contact: FactoryGirl.attributes_for(:contact, name: nil)
expect(response).to render_template(:edit)
end
end
end
describe "DELETE destroy" do
subject(:user) { FactoryGirl.create(:user_with_contacts) }
let(:contact) {user.contacts.first}
it "deletes a contact" do
sign_in user
expect{
delete :destroy, id: contact}.to change(Contact, :count).by(-1)
end
it "successfully delete" do
sign_in user
delete :destroy, id: contact
(expect(response.status).to eq(200))
end
end
end
|
require 'test_helper'
class AnalysisRequestsControllerTest < ActionDispatch::IntegrationTest
setup do
@analysis_request = analysis_requests(:one)
end
test "should get index" do
get analysis_requests_url
assert_response :success
end
test "should get new" do
get new_analysis_request_url
assert_response :success
end
test "should create analysis_request" do
assert_difference('AnalysisRequest.count') do
post analysis_requests_url, params: { analysis_request: { patient_id: @analysis_request.patient_id, status: @analysis_request.status, structure_id: @analysis_request.structure_id } }
end
assert_redirected_to analysis_request_url(AnalysisRequest.last)
end
test "should show analysis_request" do
get analysis_request_url(@analysis_request)
assert_response :success
end
test "should get edit" do
get edit_analysis_request_url(@analysis_request)
assert_response :success
end
test "should update analysis_request" do
patch analysis_request_url(@analysis_request), params: { analysis_request: { patient_id: @analysis_request.patient_id, status: @analysis_request.status, structure_id: @analysis_request.structure_id } }
assert_redirected_to analysis_request_url(@analysis_request)
end
test "should destroy analysis_request" do
assert_difference('AnalysisRequest.count', -1) do
delete analysis_request_url(@analysis_request)
end
assert_redirected_to analysis_requests_url
end
end
|
desc "Update pot/po files."
task :updatepo do
require 'gettext/utils'
puts "Generating pot files for lib"
GetText.update_pofiles("restore", Dir.glob("{lib}/**/*.{rb,rhtml}"), "restore 4.0")
Dir.chdir('frontend') do
puts "Generating pot files for frontend"
GetText.update_pofiles("restore-frontend", Dir.glob("{app,lib,bin}/**/*.{rb,rhtml}"), "restore 4.0")
end
Dir.glob("modules/*").each do |m|
name = File.basename(m)
puts "Generating pot files for #{name}"
Dir.chdir(m) do
GetText.update_pofiles("restore-module-#{name}", Dir.glob("**/*.{rb,rhtml}"), "restore #{m} module 4.0")
end
end
end
desc "Create mo-files"
task :makemo do
require 'gettext/utils'
puts "Making mo files for lib"
GetText.create_mofiles(true, "po", "locale")
Dir.chdir('frontend') do
puts "Making mo files for frontend"
GetText.create_mofiles(true, "po", "locale")
end
Dir.glob("modules/*").each do |m|
name = File.basename(m)
puts "Making mo files for #{name}"
Dir.chdir(m) do
GetText.create_mofiles(true, "po", "locale")
end
end
end
|
class Ride < ApplicationRecord
belongs_to :user
has_many :requests
belongs_to :driver, :class_name => "User", optional: true
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)
#These will be loaded every time the database is loaded
#This is essentially the default locations (not to change)
#Location database not meant to be edited by user
Location.create!([
{ "name": "Farnham Road", "latitude": "51.2350098","longitude": "-0.5805567","capacity":"917"},
{ "name": "York Road", "latitude": "51.2391383", "longitude": "-0.57207","capacity":"605"},
{ "name": "Leapale Road", "latitude": "51.2373222", "longitude": "-0.5755223","capacity":"384"}
])
|
class Calc::MeasureSelectionsController < SecuredController
before_action :set_audit_report
def create
measure = Measure.find(params[:measure_selection][:measure_id])
selection = MeasureSelectionCreator.new(
measure: measure,
audit_report: @audit_report).create
calculator = AuditReportCalculator.new(audit_report: @audit_report)
measure_summary = calculator.summary_for_measure_selection(selection)
measure_selection_json =
MeasureSelectionSerializer.new(
measure_selection: selection,
measure_summary: measure_summary).as_json
render json: {
measure_selection: measure_selection_json,
audit_report_summary: AuditReportSummarySerializer.new(
audit_report: @audit_report,
audit_report_calculator: calculator
).as_json
}
end
def destroy
selection = @audit_report.measure_selections.find(params[:id])
selection.destroy
render json: {
audit_report_summary: AuditReportSummarySerializer.new(
audit_report: @audit_report
).as_json
}
end
def new
available_measure_names = Kilomeasure.registry.names
@measures = Measure.where(api_name: available_measure_names).order(:name)
render layout: false
end
def update
selection = @audit_report.measure_selections.find(params[:id])
selection.update!(measure_selection_params)
calculator = AuditReportCalculator.new(audit_report: @audit_report)
measure_summary = calculator.summary_for_measure_selection(selection)
measure_selection_json =
MeasureSelectionSerializer.new(
measure_selection: selection,
measure_summary: measure_summary).as_json
render json: {
audit_report_summary: AuditReportSummarySerializer.new(
audit_report_calculator: calculator,
audit_report: @audit_report
).as_json,
measure_selection: measure_selection_json
}
end
private
def measure_selection_params
params.require(:measure_selection)
.permit(:calculate_order_position,
:description,
:recommendation,
:enabled,
:wegoaudit_photo_id)
end
def set_audit_report
@audit_report = AuditReport.find(params[:audit_report_id])
end
end
|
FactoryBot.define do
factory :organization do
id { SecureRandom.uuid }
name { Faker::Company.name }
description { Faker::Company.catch_phrase }
end
end
|
class ItemSerializer
include FastJsonapi::ObjectSerializer
attributes :id, :name, :description, :unit_price, :merchant_id
attribute :unit_price do |object|
(object.unit_price.to_f.to_r / 100).to_f.to_s
end
end
|
require 'rails_helper'
require 'spec_helper'
describe EventsController do
let(:user) { User.create(name: "numichuu", password: "test", password_confirmation: "test", phone_number: "123-123-1234", email:"numichuu@gmail.com")}
let(:new_event) { Event.create(title: "BeerFest", status: "Active", creator_id: user.id) }
describe "#index" do
it "renders the index template" do
expect(get :index).to render_template (:index)
end
end
describe "#new" do
it "renders the new event template" do
expect(get :new).to render_template (:new)
end
it "renders form with new event" do
get :new
expect(assigns(:event)).to be_a_new Event
end
end
describe "#create" do
let!(:create_post) { post :create, :event => {title: "DBC BP", status: "Active", creator_id: user.id} }
it "adds a new event to the database" do
expect(Event.where(title: "DBC BP")).to exist
end
it "redirects events index page" do
expect(create_post).to redirect_to events_path
end
end
describe "#show" do
it "renders show template" do
expect(get :show, id: new_event.id).to render_template(:show)
end
end
describe "edit" do
it "assigns the chosen event" do
get :edit, id: new_event.id
expect(assigns(:event)).to eq new_event
end
end
describe "update" do
it "updates the event's attributes" do
new_title = "BP EXTRAVAGANZA"
patch :update, id: new_event.id, event: {title: new_title}
new_event.reload
expect(new_event.title).to eq new_title
end
end
describe "destroy" do
before do
new_event
end
let(:delete_event) {delete :destroy, id: new_event.id}
it "removes particular event from database" do
expect{
delete :destroy, id: new_event.id
}.to change(Event,:count).by(-1)
end
it "redirects to the events page" do
expect(delete_event).to redirect_to events_path
end
end
end |
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
mount_uploader :user_image, ImageUploader
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
extend ActiveHash::Associations::ActiveRecordExtensions
belongs_to_active_hash :prefecture
has_many :entrys, dependent: :destroy
has_many :likes, dependent: :destroy
has_many :comments, dependent: :destroy
validates :name, presence: true, length: {maximum:10}
validates :email, presence: true, uniqueness: true, format: { with: /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i }
# validates :password, presence: true, length: {minimum: 7, maximum: 128}, confirmation: true
validates :prefecture_id,:muscle,:muscle_training, presence: true
end
|
# Copyright (c) 2019 Danil Pismenny <danil@brandymint.ru>
# frozen_string_literal: true
require 'openssl'
require_relative 'base_client'
# Usage example:
#
# puts PeatioAPI::Client.new(endpoint: ENTPOINT).get_public('/api/v2/peatio/public/markets/tickers')
# puts client.get '/api/v2/peatio/orders', market: 'ethbtc'
module Valera
# rubocop:disable Metrics/ClassLength
class PeatioClient < BaseClient
# Map valera sides to clients sides
SIDES_MAP = { bid: 'buy', ask: 'sell' }.freeze
attr_reader :prefix
def initialize(name:,
access_key: ENV['PEATIO_API_ACCESS_KEY'],
secret_key: ENV['PEATIO_API_SECRET_KEY'],
endpoint: ENV['PEATIO_ENDPOINT'],
prefix: '/api/v2/peatio')
@access_key = access_key || raise('No access_key')
@secret_key = secret_key || raise('No secret_key')
@endpoint = endpoint || raise('No endpoint')
@prefix = prefix || raise('No prefix')
@name = name
super()
end
def account_balances(currency = nil)
if currency.present?
get("/account/balances/#{currency}")
else
get('/account/balances').each_with_object(ActiveSupport::HashWithIndifferentAccess.new) do |r, a|
a[r['currency'].upcase] = { available: r['balance'], locked: r['locked'] }
end
end
end
def markets
get('/public/markets')
end
# @params:
# market
# ord_type = [market, limit] default is limit
# price = require if ord_type == limit
# side = [sell, buy] (OrderAsk, OrderBid)
# volume
# time_in_force is not used
#
# rubocop:disable Lint/UnusedMethodArgument
# rubocop:disable Metrics/ParameterLists
def create_order(market:, price:, side:, volume:, ord_type: :limit, time_in_force: nil)
order = {
market: market.peatio_symbol,
side: SIDES_MAP.fetch(side),
ord_type: ord_type,
price: price,
volume: volume
}
build_persisted_order(
post('/market/orders', order),
skip_unknown_market: false
)
rescue Valera::BaseClient::Failure => e
report_exception e, true, order: order unless e.is_a? InsufficientBalance
raise e
end
# rubocop:enable Metrics/ParameterLists
# rubocop:enable Lint/UnusedMethodArgument
def open_orders
orders(state: :wait)
end
# optional :market,
# optional :base_unit,
# optional :quote_unit,
# optional :state,
# optional :limit,
# optional :page,
# optional :order_by,
# optional :ord_type,
# optional :type,
# optional :time_from,
# optional :time_to,
def orders(params = {})
get('/market/orders', params)
.map { |data| build_persisted_order data }
.compact
end
# @return [
# "id", "price", "amount", "total", "fee_currency", "fee", "fee_amount",
# "market", "market_type", "created_at", "taker_type", "side", "order_id", "market_symbol"
# ]
def my_trades(_markets)
trades.map do |trade|
trade['market_symbol'] = trade['market']
trade['market'] = Market.find_by(peatio_symbol: trade['market'])
trade
end
end
def trades(params = {})
get('/market/trades', params).map do |trade|
trade.merge('side' => SIDES_MAP.invert.fetch(trade['side']))
end
end
def cancel_order(order_id)
post "/market/orders/#{order_id}/cancel"
end
# @param optional Hash with keys: market, side
def cancel_orders(params = {})
post '/market/orders/cancel', params
end
def order_book(market, params = {})
get "/public/markets/#{market}/order-book", params
end
def market_depth(market)
get "/public/markets/#{market}/depth"
end
def post(path, params = {})
parse_response connection.post prefix + path, params.to_json
end
def get(path, params = {})
parse_response connection.get prefix + path, params
end
private
attr_reader :access_key, :secret_key
def connection
nonce = (Time.now.to_f * 1000).to_i.to_s
Faraday.new url: endpoint do |c|
c.adapter Faraday.default_adapter
# c.adapter :async_http
c.headers = {
'Content-Type' => 'application/json',
'Accept' => 'application/json',
'X-Auth-Apikey' => access_key,
'X-Auth-Nonce' => nonce,
'X-Auth-Signature' => OpenSSL::HMAC.hexdigest('SHA256', secret_key, nonce + access_key)
}
c.response :logger if ENV.true? 'FARADAY_LOGGER'
if ENV.true? 'CURL_LOGGER'
c.use Faraday::Response::Logger
c.request :curl, logger, :warn
end
end
end
def parse_response(response)
if response['content-type'] != 'application/json'
raise WrongResponse,
"Wrong content type (#{response['content-type']}) for #{name} with body #{response.body.truncate(100)}"
end
data = response.body.empty? ? nil : JSON.parse(response.body)
return data if response.success?
if response.status.to_i == 422 && data['errors'].include?('market.account.insufficient_balance')
raise InsufficientBalance
end
if response.status.to_i == 422 && data['errors'].include?('order.invalid_volume_or_price"')
raise InvaildVolumeOrPrice
end
raise Failure,
"Failed response status (#{response.status}) with body '#{response.body}' for #{name}"
# attach headers, like 'per', 'per-page'
end
# "id"=>1085518,
# "uuid"=>"eefb9c4e-ca2a-464c-b22d-520176c30637",
# "side"=>"sell",
# "ord_type"=>"limit",
# "price"=>"50377.1418",
# "avg_price"=>"0.0",
# "state"=>"pending",
# "market"=>"btcusdt",
# "market_type"=>"spot",
# "created_at"=>"2021-05-13T08:15:30Z",
# "updated_at"=>"2021-05-13T08:15:30Z",
# "origin_volume"=>"0.0001",
# "remaining_volume"=>"0.0001",
# "executed_volume"=>"0.0",
# "maker_fee"=>"0.0",
# "taker_fee"=>"0.0",
# "trades_count"=>0
def build_persisted_order(raw, skip_unknown_market: true)
data = raw
.symbolize_keys
.slice(*PersistedOrder.attribute_set.map(&:name))
data[:side] = SIDES_MAP.invert.fetch data.fetch(:side)
market = Market.find_by(peatio_symbol: raw.fetch('market'))
if market.present?
data[:market_id] = market.id
PersistedOrder.new(data.merge(raw: raw)).freeze
elsif skip_unknown_market
logger.warn "Unknown market #{raw.fetch('market')}. Ignore order #{data}"
nil
else
raise Error, "Unknown market #{raw.fetch('market')}"
end
end
def logger
Logger.new($stdout)
end
end
# rubocop:enable Metrics/ClassLength
end
|
module API
module V1
class BilibilisAPI < Grape::API
helpers API::SharedParams
resource :bilibilis, desc: "弹幕接口" do
desc "获取某个视频流的最新的一部分弹幕消息"
params do
requires :sid, type: String, desc: "视频ID"
optional :size, type: Integer, desc: "获取记录的条数,默认为30条"
end
get :latest do
total = params[:size] || 30
@bibis = Bilibili.where(stream_id: params[:sid]).order('id desc').limit(total.to_i)
render_json(@bibis, API::V1::Entities::Bilibili)
end # end get
desc "分页获取某个视频流的弹幕消息"
params do
requires :sid, type: String, desc: "视频ID"
use :pagination
end
get do
@bibis = Bilibili.where(stream_id: params[:sid]).order('id desc')
@bibis = @bibis.paginate(page: params[:page], per_page: page_size) if params[:page]
render_json(@bibis, API::V1::Entities::Bilibili)
end # end get
desc "保存弹幕消息"
params do
requires :content, type: String, desc: "弹幕内容,255个字符长度"
requires :stream_id, type: String, desc: "视频流ID"
optional :token, type: String, desc: "用户认证Token"
optional :location, type: String, desc: "弹幕作者的位置信息,保留参数,留着以后用"
end
post do
@bili = Bilibili.new(content: params[:content], stream_id: params[:stream_id], location: params[:location])
if params[:token].present?
u = User.find_by(private_token: params[:token])
@bili.author_id = u.id if u.present?
end
if @bili.save
video = Video.find_by(stream_id: params[:stream_id])
if video.present?
# 添加统计数据
video.msg_count += 1
video.save
else
lv = LiveVideo.find_by(stream_id: params[:stream_id])
if lv.present?
# 添加统计数据
lv.msg_count += 1
lv.save
end
end
render_json(@bili, API::V1::Entities::Bilibili)
else
render_error(5001, @bili.errors.full_messages.join(','))
end
end # end post
end # end resource
end
end
end |
class CommentsController < ApplicationController
before_action :authenticate_user!, except: :top_10_commenters
def create
@comment = movie.comments.build(comment_params)
if @comment.save
redirect_to movie_path(movie), notice: "Comment was successfully created."
else
puts @comment.errors.inspect
redirect_to movie_path(movie), flash: { errors: @comment.errors.full_messages }
end
end
def destroy
comment = movie.comments.find(params[:id])
if comment.user == current_user
comment.destroy
flash[:notice] = "Comment was successfully destroyed."
else
flash[:error] = "You cannot remove not your comments."
end
redirect_to movie_path(movie)
end
def top_10_commenters
@users = User
.select("users.*, count(*) as comments_count")
.group(:id)
.joins(:comments)
.where(comments: { created_at: 1.week.ago..Time.current })
.order("comments_count DESC")
.limit(10)
end
private
def movie
@movie ||= Movie.find(params[:movie_id])
end
def comment_params
params.require(:comment).permit(:content).merge(user: current_user, movie: movie)
end
end
|
module Cinch
module Helpers
# Helper method for turning a String into a {Target} object.
#
# @param [String] target a target name
# @return [Target] a {Target} object
# @example
# on :message, /^message (.+)$/ do |m, target|
# Target(target).send "hi!"
# end
def Target(target)
return target if target.is_a?(Target)
Target.new(target, bot)
end
# Helper method for turning a String into a {Channel} object.
#
# @param [String] channel a channel name
# @return [Channel] a {Channel} object
# @example
# on :message, /^please join (#.+)$/ do |m, target|
# Channel(target).join
# end
def Channel(channel)
return channel if channel.is_a?(Channel)
bot.channel_manager.find_ensured(channel)
end
# Helper method for turning a String into an {User} object.
#
# @param [String] user a user's nickname
# @return [User] an {User} object
# @example
# on :message, /^tell me everything about (.+)$/ do |m, target|
# user = User(target)
# m.reply "%s is named %s and connects from %s" % [user.nick, user.name, user.host]
# end
def User(user)
return user if user.is_a?(User)
bot.user_manager.find_ensured(user)
end
# @example Used as a class method in a plugin
# timer 5, method: :some_method
# def some_method
# Channel("#cinch-bots").send(Time.now.to_s)
# end
#
# @example Used as an instance method in a plugin
# match "start timer"
# def execute(m)
# timer(5) { puts "timer fired" }
# end
#
# @example Used as an instance method in a traditional `on` handler
# on :message, "start timer" do
# timer(5) { puts "timer fired" }
# end
#
# @param [Number] interval Interval in seconds
# @param [Proc] block A proc to execute
# @option options [Symbol] :method (:timer) Method to call (only if no proc is provided)
# @option options [Boolean] :threaded (true) Call method in a thread?
# @return [Timer]
# @since 1.2.0
def timer(interval, options = {}, &block)
options = {:method => :timer, :threaded => true, :interval => interval}.merge(options)
block ||= self.method(options[:method])
timer = Cinch::Timer.new(bot, options, &block)
timer.start
timer
end
# Use this method to automatically log exceptions to the loggers.
#
# @example
# def my_method
# rescue_exception do
# something_that_might_raise()
# end
# end
#
# @return [void]
# @since 1.2.0
def rescue_exception
begin
yield
rescue => e
bot.loggers.exception(e)
end
end
def Format(*args)
Formatting.format(*args)
end
alias_method :Color, :Format
end
end
|
# ../data.img#1771563:1
require_relative '../../lib/parser/comment'
require_relative '../../templates/types/function'
# Warning! This Tests have some sideeffects. All registered Tokens will create Classes, that are not
# removed on unregister
describe Token::Handler, ".register" do
before :each do
Token::Handler.unregister :test_handler
@object = CodeObject::Function.new
end
after :all do
Token::Handler.unregister :test_handler
end
context "using a default handler" do
before do
Token::Handler.register :test_handler
token = Parser::Tokenline.new :test_handler, "This is some content"
@object.process_token(token)
end
describe "the processed token" do
subject { @object.token(:test_handler).first }
it "should have got the correct content" do
subject.content.should == "This is some content"
end
end
end
context "using a typed handler" do
before do
Token::Handler.register :test_handler, :handler => :typed
token = Parser::Tokenline.new :test_handler, "[MyType] This is some content"
@object.process_token(token)
end
describe "the processed token" do
subject { @object.token(:test_handler).first }
it "should have got correct type and content" do
subject.types.should == ["MyType"]
subject.content.should == "This is some content"
end
end
end
context "using a typed_with_name handler" do
before do
Token::Handler.register :test_handler, :handler => :typed_with_name
token = Parser::Tokenline.new :test_handler, "[Foo, Bar, Baz] MyName This is some content"
@object.process_token(token)
end
describe "the processed token" do
subject { @object.token(:test_handler).first }
it "should have got correct typedname and content" do
subject.types.should == ["Foo", "Bar", "Baz"]
subject.name.should == "MyName"
subject.content.should == "This is some content"
end
end
end
context "processing a token without handler" do
token = Parser::Tokenline.new :some_not_known_handler, "[Foo, Bar, Baz] MyName This is some content"
it "should raise an error" do
should_raise Token::NoTokenHandler do
@object.process_token(token)
end
end
end
context "multiple tokens of the same type" do
before do
Token::Handler.register :test_handler
@object.process_token Parser::Tokenline.new :test_handler, "This is some content"
@object.process_token Parser::Tokenline.new :test_handler, "And another one"
@object.process_token Parser::Tokenline.new :test_handler, "Third content"
end
subject { @object.token(:test_handler) }
it "should be processed to an array" do
subject.length.should == 3
subject[0].content.should == "This is some content"
subject[1].content.should == "And another one"
subject[2].content.should == "Third content"
end
end
context "using a user-defined block as token-handler" do
before do
Token::Handler.register(:test) do |tokenklass, content|
define_singleton_method :test_token do
tokenklass
end
define_singleton_method :test_content do
content
end
end
@object.process_token Parser::Tokenline.new :test, "This is some content"
end
it "should be added to the list of handlers" do
Token::Handler.handlers.include?(:test).should == true
end
it "should be evaled in CodeObject context" do
@object.test_token.should == Token::Token::TestToken
@object.test_content.should == "This is some content"
end
end
end
|
require 'pry'
class IntCode
attr_accessor :instructions
OPCODE_ADD = 1
OPCODE_MULT = 2
OPCODE_INPUT = 3
OPCODE_OUTPUT = 4
OPCODE_JUMP_IF_TRUE = 5
OPCODE_JUMP_IF_FALSE = 6
OPCODE_LESS_THAN = 7
OPCODE_EQUALS = 8
OPCODE_ADJ_REL_BASE = 9
OPCODE_END = 99
FULL_OPCODE_INSTRUCTION_LEN = 5
MAX_PARAMS = 3
PARAM_MODE_POSITION = 0
PARAM_MODE_IMMEDIATE = 1
PARAM_MODE_RELATIVE = 2
EXTRA_MEM = 2048
class StdinInputReader
def read
puts "input: "
$stdin.gets.chomp.to_i
end
end
class StdoutOutputWriter
def write(value)
puts value
end
end
def initialize(file)
@instructions =
File.read(file).split(",").map(&:to_i) +
Array.new(EXTRA_MEM, 0)
@input_reader = StdinInputReader.new
@output_writer = StdoutOutputWriter.new
end
def set_input_reader(reader)
@input_reader = reader
end
def set_output_writer(writer)
@output_writer = writer
end
def kill
@alive = false
end
def execute
@alive = true
relative_base = 0
current_instruction = 0
while @alive do
op_code = parse_opcode(@instructions[current_instruction])
modes = parse_modes(@instructions[current_instruction])
#puts "op = #{op_code} #{current_instruction}"
case op_code
when OPCODE_END
return
when OPCODE_ADD
current_instruction = add(current_instruction, relative_base, modes)
when OPCODE_MULT
current_instruction = mult(current_instruction, relative_base, modes)
when OPCODE_INPUT
current_instruction = input(current_instruction, relative_base, modes)
when OPCODE_OUTPUT
current_instruction = output(current_instruction, relative_base, modes)
when OPCODE_JUMP_IF_TRUE
current_instruction = jump_if_true(current_instruction, relative_base, modes)
when OPCODE_JUMP_IF_FALSE
current_instruction = jump_if_false(current_instruction, relative_base, modes)
when OPCODE_LESS_THAN
current_instruction = less_than(current_instruction, relative_base, modes)
when OPCODE_EQUALS
current_instruction = equals(current_instruction, relative_base, modes)
when OPCODE_ADJ_REL_BASE
current_instruction, relative_base = adjust_relative_base(current_instruction, relative_base, modes)
end
end
end
def parse_opcode(instruction)
opcode = instruction.to_s
opcode = opcode[opcode.length - 2, 2]
opcode.to_i
end
def parse_modes(instruction)
instruction_str = instruction.to_s
default_modes = Array.new(MAX_PARAMS).fill(PARAM_MODE_POSITION).join('')
missing = FULL_OPCODE_INSTRUCTION_LEN - instruction_str.length
full_instruction = default_modes[0, missing] + instruction_str
full_instruction[0, MAX_PARAMS]
.split('')
.map{ |c| c.to_i }
.reverse
end
def value(mode, relative_base, param)
if mode == PARAM_MODE_IMMEDIATE
param
elsif mode == PARAM_MODE_RELATIVE
@instructions[param + relative_base]
else
@instructions[param]
end
end
def addr(mode, relative_base, param)
if mode == PARAM_MODE_RELATIVE
param + relative_base
else
param
end
end
def add(current_instruction, relative_base, modes)
params = @instructions[current_instruction + 1, 3]
values = params.zip(modes).map{ |param, mode| value(mode, relative_base, param) }
output_addr = addr(modes[2], relative_base, params[2])
@instructions[output_addr] = values[0] + values[1]
current_instruction + 4
end
def mult(current_instruction, relative_base, modes)
params = @instructions[current_instruction + 1, 3]
values = params.zip(modes).map{ |param, mode| value(mode, relative_base, param) }
output_addr = addr(modes[2], relative_base, params[2])
@instructions[output_addr] = values[0] * values[1]
current_instruction + 4
end
def input(current_instruction, relative_base, modes)
param = @instructions[current_instruction + 1]
output_addr = addr(modes[0], relative_base, param)
value = @input_reader.read
@instructions[output_addr] = value
current_instruction + 2
end
def output(current_instruction, relative_base, modes)
#binding.pry
param = @instructions[current_instruction + 1]
value = value(modes[0], relative_base, param)
@output_writer.write(value)
current_instruction + 2
end
def jump_if_true(current_instruction, relative_base, modes)
test_value, jump_value = @instructions[current_instruction + 1, 2]
.zip(modes)
.map { |param, mode| value(mode, relative_base, param) }
if test_value != 0
jump_value
else
current_instruction + 3
end
end
def jump_if_false(current_instruction, relative_base, modes)
test_value, jump_value = @instructions[current_instruction + 1, 2]
.zip(modes)
.map { |param, mode| value(mode, relative_base, param) }
if test_value == 0
jump_value
else
current_instruction + 3
end
end
def less_than(current_instruction, relative_base, modes)
params = @instructions[current_instruction + 1, 3]
p1, p2 = params
.zip(modes)
.map { |param, mode| value(mode, relative_base, param) }
output_addr = addr(modes[2], relative_base, params[2])
@instructions[output_addr] = (p1 < p2) ? 1 : 0
current_instruction + 4
end
def equals(current_instruction, relative_base, modes)
params = @instructions[current_instruction + 1, 3]
p1, p2 = params
.zip(modes)
.map { |param, mode| value(mode, relative_base, param) }
output_addr = addr(modes[2], relative_base, params[2])
@instructions[output_addr] = (p1 == p2) ? 1 : 0
current_instruction + 4
end
def adjust_relative_base(current_instruction, relative_base, modes)
param = @instructions[current_instruction + 1]
mode = modes[0]
adj = value(mode, relative_base, param)
relative_base += adj
current_instruction += 2
[ current_instruction, relative_base ]
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 rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
#AdminUser.create!(email: 'admin@example.com', password: 'password', password_confirmation: 'password')
growth_hacking = Purchase.create(title: "Growth Hacking",
subtitle: "Crash Course",
author: "Mattan Griffeld",
price: "4.99",
sku: "GROHACK1",
description: %{<p>A growth hacker is a rare combination: someone with the right marketing and technical skills who can come up with clever marketing hacks and also track their results.</p>
<p>In this talk, Mattan Griffel introduces you to the concept of Growth Hacking and shares his favorite tips for getting started as a growth hacker.</p>
<p><strong>What You'll Learn</strong></p>
<ul class="no-indent">
<li>What is a growth hacker?</li>
<li>The 5 stages of the user lifecycle</li>
<li>How to apply the Lean Marketing Framework</li>
<li>Resources and tools you'll need to know</li>
</ul>}
)
|
class Penyakit
include Mongoid::Document
field :nama, type: String
field :deskripsi, type: String
field :solusi, type: String
has_and_belongs_to_many :gejalas
has_one :klien
end
|
class RyshDate
def initialize date
@date = date
end
def self.day_name number
case (number % 7)+1
when 1; "Sunsday"
when 2; "Moonsday"
when 3; "Landsday"
when 4; "Midweek"
when 5; "Queensday"
when 6; "Kingsday"
when 7; "Starsday"
end
end
end |
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# email :string(255) default(""), not null
# name :string(255)
# encrypted_password :string(255) default(""), not null
# reset_password_token :string(255)
# reset_password_sent_at :datetime
# remember_created_at :datetime
# sign_in_count :integer default(0)
# current_sign_in_at :datetime
# last_sign_in_at :datetime
# current_sign_in_ip :string(255)
# last_sign_in_ip :string(255)
# created_at :datetime not null
# updated_at :datetime not null
# recommendations_up_to_date :boolean
# avatar_file_name :string(255)
# avatar_content_type :string(255)
# avatar_file_size :integer
# avatar_updated_at :datetime
# facebook_id :string(255)
# bio :string(140) default(""), not null
# sfw_filter :boolean default(TRUE)
# star_rating :boolean default(FALSE)
# mal_username :string(255)
# life_spent_on_anime :integer default(0), not null
# about :string(500) default(""), not null
# confirmation_token :string(255)
# confirmed_at :datetime
# confirmation_sent_at :datetime
# unconfirmed_email :string(255)
# cover_image_file_name :string(255)
# cover_image_content_type :string(255)
# cover_image_file_size :integer
# cover_image_updated_at :datetime
# title_language_preference :string(255) default("canonical")
# followers_count_hack :integer default(0)
# following_count :integer default(0)
# ninja_banned :boolean default(FALSE)
# last_library_update :datetime
# last_recommendations_update :datetime
# authentication_token :string(255)
# avatar_processing :boolean
# subscribed_to_newsletter :boolean default(TRUE)
# waifu :string(255)
# location :string(255)
# website :string(255)
# waifu_or_husbando :string(255)
# waifu_slug :string(255) default("#")
# waifu_char_id :string(255) default("0000")
# to_follow :boolean default(FALSE)
# dropbox_token :string(255)
# dropbox_secret :string(255)
# last_backup :datetime
# approved_edit_count :integer default(0)
# rejected_edit_count :integer default(0)
# pro_expires_at :datetime
# stripe_token :string(255)
# pro_membership_plan_id :integer
# stripe_customer_id :string(255)
# about_formatted :text
# import_status :integer
# import_from :string(255)
# import_error :string(255)
#
class User < ActiveRecord::Base
# Friendly ID.
def to_param
name
end
def self.find(id)
user = nil
if id.is_a? String
user = User.find_by_username(id)
end
user || super
end
def self.find_by_username(username)
where('LOWER(name) = ?', username.to_s.downcase).first
end
def self.match(query)
where('LOWER(name) = ?', query.to_s.downcase)
end
def self.search(query)
# Gnarly hack to provide a search rank
# TODO: switch properly to pg_search (this is harder for User because of
# maintaining the email search, unless we remove that)
select(
sanitize_sql_array([
'users.*, GREATEST(
similarity(users.name, :query),
CASE WHEN users.email = :query THEN 1.0 ELSE 0.0 END
) AS pg_search_rank',
query: query.downcase])
).where('LOWER(name) LIKE :query OR LOWER(email) LIKE :query', query: "#{query.downcase}%")
end
class << self
alias_method :instant_search, :search
alias_method :full_search, :instant_search
end
has_many :favorites
def has_favorite?(item)
self.favorites.exists?(item_id: item, item_type: item.class.to_s)
end
def has_favorite2?(item)
@favorites ||= favorites.pluck(:item_id, :item_type)
!! @favorites.member?([item.id, item.class.to_s])
end
# Following stuff.
has_many :follower_relations, dependent: :destroy, foreign_key: :followed_id, class_name: 'Follow'
has_many :followers, -> { order('follows.created_at DESC') }, through: :follower_relations, source: :follower, class_name: 'User'
has_many :follower_items, -> { select('"follows"."follower_id", "follows"."followed_id"') }, foreign_key: :followed_id, class_name: 'Follow'
has_many :following_relations, dependent: :destroy, foreign_key: :follower_id, class_name: 'Follow'
has_many :following, -> { order('follows.created_at DESC') }, through: :following_relations, source: :followed, class_name: 'User'
# Groups stuff.
has_many :group_relations, dependent: :destroy, foreign_key: :user_id, class_name: 'GroupMember'
has_many :groups, through: :group_relations
has_many :stories
has_many :substories
has_many :notifications
has_many :votes
has_one :recommendation
has_many :not_interested
has_many :not_interested_anime, through: :not_interested, source: :media, source_type: "Anime"
has_and_belongs_to_many :favorite_genres, -> { uniq }, class_name: "Genre", join_table: "favorite_genres_users"
belongs_to :waifu_character, foreign_key: :waifu_char_id, class_name: 'Casting', primary_key: :character_id
# Include devise modules. Others available are:
# :lockable, :timeoutable, :trackable, :rememberable.
devise :database_authenticatable, :registerable, :recoverable,
:validatable, :omniauthable, :confirmable, :async,
allow_unconfirmed_access_for: nil
has_attached_file :avatar,
styles: {
thumb: '190x190#',
thumb_small: {geometry: '100x100#', animated: false, format: :jpg},
small: {geometry: '50x50#', animated: false, format: :jpg}
},
convert_options: {
thumb_small: '-quality 0',
small: '-quality 0'
},
default_url: "https://hummingbird.me/default_avatar.jpg",
processors: [:thumbnail, :paperclip_optimizer]
validates_attachment :avatar, content_type: {
content_type: ["image/jpg", "image/jpeg", "image/png", "image/gif"]
}
process_in_background :avatar, processing_image_url: '/assets/processing-avatar.jpg'
has_attached_file :cover_image,
styles: {thumb: {geometry: "2880x800#", animated: false, format: :jpg}},
convert_options: {thumb: '-interlace Plane -quality 0'},
default_url: "https://hummingbird.me/default_cover.png"
validates_attachment :cover_image, content_type: {
content_type: ["image/jpg", "image/jpeg", "image/png", "image/gif"]
}
has_many :library_entries, dependent: :destroy
has_many :manga_library_entries, dependent: :destroy
has_many :reviews
has_many :quotes
# Validations
validates :name,
:presence => true,
:uniqueness => {:case_sensitive => false},
:length => {minimum: 3, maximum: 20},
:format => {:with => /\A[_A-Za-z0-9]+\z/,
:message => "can only contain letters, numbers, and underscores."}
INVALID_USERNAMES = %w(
admin administrator connect dashboard developer developers edit favorites
feature featured features feed follow followers following hummingbird index
javascript json sysadmin sysadministrator system unfollow user users wiki you
)
validate :valid_username
def valid_username
return unless name
if INVALID_USERNAMES.include? name.downcase
errors.add(:name, "is reserved")
end
if name[0,1] =~ /[^A-Za-z0-9]/
errors.add(:name, "must begin with a letter or number")
end
if name =~ /^[0-9]*$/
errors.add(:name, "cannot be entirely numbers")
end
end
validates :facebook_id, allow_blank: true, uniqueness: true
validates :title_language_preference, inclusion: {in: %w[canonical english romanized]}
enum import_status: {queued: 1, running: 2, complete: 3, error: 4}
def to_s
name
end
# Avatar
def avatar_url
# Gravatar
# gravatar_id = Digest::MD5.hexdigest(email.downcase)
# "http://gravatar.com/avatar/#{gravatar_id}.png?s=100"
avatar.url(:thumb)
end
# Public: Is this user an administrator?
#
# For now, this will just check email addresses. In production, this should
# check the user's ID as well.
def admin?
["c@vikhyat.net", # Vik
"josh@hummingbird.me", # Josh
"hummingbird.ryn@gmail.com", # Ryatt
"dev.colinl@gmail.com", # Psy
"lazypanda39@gmail.com", # Cai
"svengehring@cybrox.eu", # Cybrox
"peter.lejeck@gmail.com", # Nuck
"hello@vevix.net", # Vevix
"jimm4a1@hotmail.com", #Jim
"jojovonjo@yahoo.com", #JoJo
"synthtech@outlook.com" #Synthtech
].include? email
end
# Does the user have active PRO membership?
def pro?
pro_expires_at && pro_expires_at > Time.now
end
def pro_membership_plan
return nil if pro_membership_plan_id.nil?
ProMembershipPlan.find(pro_membership_plan_id)
end
def has_dropbox?
!!(dropbox_token && dropbox_secret)
end
def has_facebook?
!facebook_id.blank?
end
# Public: Find a user corresponding to a Facebook account.
#
# If there is an account associated with the Facebook ID, return it.
#
# If there is no such account but `signed_in_resource` is not nil (meaning that
# there is a user signed in), connect the user's account to this Facebook
# account.
#
# If there is no user logged in, check to see if there is a user with the same
# email address. If there is, connect that account to Facebook and return it.
#
# Otherwise, just create a new user and connect it to this Facebook account.
#
# Returns a user account corresponding to the given auth parameters.
def self.find_for_facebook_oauth(auth, signed_in_resource=nil)
# Try to find a user already associated with the Facebook ID.
user = User.where(facebook_id: auth.uid).first
return user if user
# If the user is logged in, connect their account to Facebook.
if not signed_in_resource.nil?
signed_in_resource.connect_to_facebook(auth.uid)
return signed_in_resource
end
# If there is a user with the same email, connect their account to this
# Facebook account.
user = User.find_by_email(auth.info.email)
if user
user.connect_to_facebook(auth.uid)
return user
end
# Just create a new account. >_>
name = auth.extra.raw_info.name.parameterize.gsub('-', '_')
name = name.gsub(/[^_A-Za-z0-9]/, '')
if User.where("LOWER(name) = ?", name.downcase).count > 0
if name.length > 20
name = name[0...15]
end
name = name[0...10] + rand(9999).to_s
end
name = name[0...20] if name.length > 20
user = User.new(
name: name,
facebook_id: auth.uid,
email: auth.info.email,
avatar: open("https://graph.facebook.com/#{auth.uid}/picture?width=200&height=200"),
password: Devise.friendly_token[0, 20]
)
user.save
user.confirm!
return user
end
# Set this user's facebook_id to the passed in `uid`.
#
# Returns nothing.
def connect_to_facebook(uid)
if not self.avatar.exists?
self.avatar = open("http://graph.facebook.com/#{uid}/picture?width=200&height=200")
end
self.facebook_id = uid
self.save
end
def update_ip!(new_ip)
if self.current_sign_in_ip != new_ip
self.attributes = {
current_sign_in_ip: new_ip,
last_sign_in_ip: self.current_sign_in_ip
}
# Avoid validating because some users apparently don't pass validation
self.save(validate: false)
end
end
# Return the top 5 genres the user has completed, along with
# the number of anime watched that contain each of those genres.
def top_genres
freqs = nil
LibraryEntry.unscoped do
freqs = library_entries.where(status: "Completed")
.where(private: false)
.joins(:genres)
.group('genres.id')
.select('COUNT(*) as count, genres.id as genre_id')
.order('count DESC')
.limit(5).each_with_object({}) do |x, obj|
obj[x.genre_id] = x.count.to_f
end
end
result = []
Genre.where(id: freqs.keys).each do |genre|
result.push({genre: genre, num: freqs[genre.id]})
end
result.sort_by {|x| -x[:num] }
end
# How many minutes the user has spent watching anime.
def recompute_life_spent_on_anime!
time_spent = nil
LibraryEntry.unscoped do
time_spent = self.library_entries.joins(:anime).select('
COALESCE(anime.episode_length, 0) * (
COALESCE(episodes_watched, 0)
+ COALESCE(anime.episode_count, 0) * COALESCE(rewatch_count, 0)
) AS mins
').map {|x| x.mins }.sum
end
self.update_attributes life_spent_on_anime: time_spent
end
def update_life_spent_on_anime(delta)
if life_spent_on_anime == 0
self.recompute_life_spent_on_anime!
else
self.update_column :life_spent_on_anime, self.life_spent_on_anime + delta
end
end
def followers_count
followers_count_hack
end
before_save do
if self.facebook_id and self.facebook_id.strip == ""
self.facebook_id = nil
end
# Make sure the user has an authentication token.
if self.authentication_token.blank?
token = nil
loop do
token = Devise.friendly_token
break unless User.where(authentication_token: token).first
end
self.authentication_token = token
end
if about_changed?
self.about_formatted = MessageFormatter.format_message about
end
if waifu_char_id != '0000' and changed_attributes['waifu_char_id']
self.waifu_slug = waifu_character ? waifu_character.castable.slug : '#'
end
end
def sync_to_forum!
UserSyncWorker.perform_async(self.id) if Rails.env.production?
end
after_save do
name_changed = self.name_changed?
auth_token_changed = self.authentication_token_changed?
avatar_changed = (not self.avatar_processing) && (self.avatar_processing_changed? || self.avatar_updated_at_changed?)
if name_changed || avatar_changed || auth_token_changed
self.sync_to_forum!
end
end
def voted_for?(target)
@votes ||= {}
@votes[target.class.to_s] ||= votes.where(:target_type => target.class.to_s).pluck(:target_id)
@votes[target.class.to_s].member? target.id
end
# Return encrypted email.
def encrypted_email
Digest::MD5.hexdigest(ENV['FORUM_SYNC_SECRET'] + self.email)
end
def avatar_template
self.avatar.url(:thumb).gsub(/users\/avatars\/(\d+\/\d+\/\d+)\/\w+/, "users/avatars/\\1/{size}")
end
attr_reader :is_followed
def set_is_followed!(v)
@is_followed = v
end
end
|
require 'colorize'
class Word
attr_accessor :guessed_letters, :blanks, :wrong_guesses, :letters, :name
def initialize(word)
@name = word
@letters = word.chars
@blanks = []
@guessed_letters = []
@guess = ""
@wrong_guesses = 0
create_blank_array
end
def create_blank_array
@letters.length.times do
@blanks << "_"
end
end
def print_blanks
@blanks.each do | value |
print value
end
end
def check_guess(guess)
if @guessed_letters.include?(guess)
puts "\nYou've already guessed this letter.".colorize(:yellow)
else
@guessed_letters << guess
end
if !@letters.include?(guess)
if guess.empty?
puts "No letter inputted. Try again."
else
@wrong_guesses += 1
puts "\nYou guessed wrong! Try again.".colorize(:red)
end
else
puts "\nCorrect!!!".colorize(:green)
end
end
def fill_blanks(guess)
@letters.each.with_index do |letter, index|
if letter == guess
@blanks[index] = guess
end
end
end
def print_guesses
print "\nGuessed letters: "
@guessed_letters.each do | value |
print value.upcase
print " "
end
end
end
class Image
def initialize
@image0 = [
" __/ \\--\\".colorize(:red),
" U |_|__|".colorize(:light_red),
" ||".colorize(:yellow),
" ||".colorize(:green),
", , , , , , , , ,|".colorize(:blue),
"||__||__||__||__||__||__||__||__||".colorize(:magenta),
"|.--..--..--..--..--..--..--..--.|".colorize(:red),
"||__||__||__||__||__||__||__||__||".colorize(:light_red),
"|.--..--..--..--..--..--..--..--.|".colorize(:yellow),
"|| || || || || || || || ||".colorize(:green)
]
@image1 = [
" __/ \\--\\".colorize(:red),
" U |_|__|".colorize(:light_red),
" ||".colorize(:yellow),
" ||".colorize(:green),
" , , , , , , , ,|".colorize(:blue),
" ||__||__||__||__||__||__||__||".colorize(:magenta),
" ..--..--..--..--..--..--..--.|".colorize(:red),
" ||__||__||__||__||__||__||__||".colorize(:light_red),
" ..--..--..--..--..--..--..--.|".colorize(:yellow),
"|| || || || || || || || ||".colorize(:green)
]
@image2 = [
" __/ \\--\\".colorize(:red),
" U |_|__|".colorize(:light_red),
" ||".colorize(:yellow),
" ||".colorize(:green),
" , , , , , , ,|".colorize(:blue),
" ||__||__||__||__||__||__||".colorize(:magenta),
" ..--..--..--..--..--..--.|".colorize(:red),
" ||__||__||__||__||__||__||".colorize(:light_red),
" ..--..--..--..--..--..--.|".colorize(:yellow),
"|| || || || || || || || ||".colorize(:green)
]
@image3 = [
" __/ \\--\\".colorize(:red),
" U |_|__|".colorize(:light_red),
" ||".colorize(:yellow),
" ||".colorize(:green),
" , , , , , ,|".colorize(:blue),
" ||__||__||__||__||__||".colorize(:magenta),
" ..--..--..--..--..--.|".colorize(:red),
" ||__||__||__||__||__||".colorize(:light_red),
" ..--..--..--..--..--.|".colorize(:yellow),
"|| || || || || || || || ||".colorize(:green)
]
@image4 = [
" __/ \\--\\".colorize(:red),
" U |_|__|".colorize(:light_red),
" ||".colorize(:yellow),
" ||".colorize(:green),
" , , , , ,|".colorize(:blue),
" ||__||__||__||__||".colorize(:magenta),
" ..--..--..--..--.|".colorize(:red),
" ||__||__||__||__||".colorize(:light_red),
" ..--..--..--..--.|".colorize(:yellow),
"|| || || || || || || || ||".colorize(:green)
]
@image5 = [
" __/ \\--\\".colorize(:red),
" U |_|__|".colorize(:light_red),
" ||".colorize(:yellow),
" ||".colorize(:green),
" , , , ,|".colorize(:blue),
" ||__||__||__||".colorize(:magenta),
" ..--..--..--.|".colorize(:red),
" ||__||__||__||".colorize(:light_red),
" ..--..--..--.|".colorize(:yellow),
"|| || || || || || || || ||".colorize(:green)
]
@image6 = [
" __/ \\--\\".colorize(:red),
" U |_|__|".colorize(:light_red),
" ||".colorize(:yellow),
" ||".colorize(:green),
" , , , ,|".colorize(:blue),
" ||__||__||__||".colorize(:magenta),
" ..--..--..--.|".colorize(:red),
" ||__||__||__||".colorize(:light_red),
" ..--..--..--.|".colorize(:yellow),
"|| || || || || || || || ||".colorize(:green)
]
@image7 = [
" __/ \\--\\".colorize(:red),
" U |_|__|".colorize(:light_red),
" ||".colorize(:yellow),
" ||".colorize(:green),
" , , ,|".colorize(:blue),
" ||__||__||".colorize(:magenta),
" ..--..--.|".colorize(:red),
" ||__||__||".colorize(:light_red),
" ..--..--.|".colorize(:yellow),
"|| || || || || || || || ||".colorize(:green)
]
@image8 = [
" __/ \\--\\".colorize(:red),
" U |_|__|".colorize(:light_red),
" ||".colorize(:yellow),
" ||".colorize(:green),
" , ,|".colorize(:blue),
" ||__||".colorize(:magenta),
" ..--.|".colorize(:red),
" ||__||".colorize(:light_red),
" ..--.|".colorize(:yellow),
"|| || || || || || || || ||".colorize(:green)
]
@gameover = [
" ||".colorize(:red),
" ||".colorize(:light_red),
" |".colorize(:yellow),
" ||".colorize(:blue),
" .|".colorize(:magenta),
" __/ \\--\\ .|".colorize(:red),
" U |_|__| .|".colorize(:light_red),
"|| || || || || || || || ||".colorize(:yellow)
]
@images = [@image0, @image1, @image2, @image3, @image4, @image5, @image6, @image7, @image8, @gameover]
end
def print_image(wrong_guesses)
@images[wrong_guesses]
end
end
class Game
attr_reader :start_game, :game_play
def initialize(word, image)
@word = word
@image = image
end
def start_game
print "Word to Guess: "
@word.print_blanks
puts "\nYou have #{9 - @word.wrong_guesses} guesses!"
puts
puts @image.print_image(0)
end
def game_play
loop_again = true
until loop_again == false
puts "\n\nGuess a letter!"
print "> "
guess = gets.chomp.downcase
@word.check_guess(guess)
@word.print_guesses
puts
print "Word To Guess: "
@word.fill_blanks(guess)
@word.print_blanks
puts "\nYou have #{9 - @word.wrong_guesses} guesses left!"
puts @image.print_image(@word.wrong_guesses)
if @word.wrong_guesses == 9 || (@word.letters == @word.blanks && @word.wrong_guesses < 9)
if @word.letters == @word.blanks && @word.wrong_guesses < 9
puts "You won!"
else
puts "You lost!"
puts "Your word was #{@word.name.upcase}!"
end
loop_again = false
end
end
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 with: :exception
skip_before_action :verify_authenticity_token
def after_sign_in_path_for(resource)
#Update this when we are going to integrate the roles specific pages
if resource.roles_mask?
# If member logged in
member_path
else
# If admin logged in
admin_path
end
end
rescue_from CanCan::AccessDenied do |exception|
flash[:error] = exception.message
redirect_to root_url
end
end
|
# manejo de excepciones en ruby
def convert_number(s)
begin
Integer(s)
rescue ArgumentError
nil
end
end |
require 'rails_helper'
describe 'Channel Parser' do
describe '.parse' do
context 'with valid parameters' do
it 'creates a new channel if one does not exist' do
team = create(:team)
ChannelParser.parse(create_pull_request_params, team)
expect(Channel.all.size).to eq(1)
end
it 'finds the channel if one does exist' do
team = create(:team)
channel = create(:channel, team: team)
ChannelParser.parse(create_pull_request_params, team)
expect(Channel.all.size).to eq(1)
end
end
context 'with invalid parameters' do
it 'returns nil if the object cannnot be parsed' do
team = create(:team)
channel = create(:channel, team: team)
invalid_params = create_pull_request_params
invalid_params.delete(:channel_id)
nil_channel = ChannelParser.parse(invalid_params, team)
expect(nil_channel).to eq(nil)
end
end
end
end
|
module Zaypay
require 'yaml'
# PriceSetting instances allows you to communicate to the Zaypay platform.
#
# It is basically a Ruby wrapper for the Zaypay-API, which provides you a bunch of payment-related methods, as well as some utility methods.
class PriceSetting
include HTTParty
attr_reader :price_setting_id, :api_key
attr_accessor :locale, :payment_method_id
base_uri 'https://secure.zaypay.com'
headers :Accept => 'application/xml'
# Creates instances of Zaypay::PriceSetting.
#
# To instantiate, one must provide a PriceSetting-id and its API-Key.
# You can obtain these information once you have created a PriceSetting on the Zaypay platform (http://www.zaypay.com).
#
# You can also call the "one-arg" or the "no-args" version of the initializer,
# but to do that, you must first create config/zaypay.yml in your Rails app, see the {file:/README.rdoc README} file.
#
# @param [Integer] price_setting_id your PriceSetting's id
# @param [String] api_key your PriceSetting's api-key
def initialize(price_setting_id=nil, api_key=nil)
@price_setting_id, @api_key = price_setting_id, api_key
select_settings
end
def locale=(arg)
case arg
when Hash
if arg.has_key?(:language) && arg.has_key?(:country)
@locale = Zaypay::Util.stringify_locale_hash(arg)
else
raise Zaypay::Error.new(:locale_not_set, "The hash you provided was invalid. Please make sure it contains the keys :language and :country")
end
when String
@locale = arg
end
end
# Returns the default locale as a string for a given ip_address, with the first part representing the language, the second part the country
#
# This method comes in handy when you want to preselect the language and country when your customer creates a payment on your website.
#
# = Example:
# # We take an ip-address from Great Britain for example:
# ip = "212.58.226.75"
# @price_setting.locale_string_for_ip(ip)
# => 'en-GB'
#
# Also see {#locale_for_ip}
# @param [String] ip an ip-address (e.g. from your site's visitors)
# @return [String] a string that represents the default locale for the given IP, in a language-country format.
def locale_string_for_ip(ip)
get "/#{ip}/pay/#{price_setting_id}/locale_for_ip" do |data|
parts = data[:locale].split('-')
Zaypay::Util.stringify_locale_hash({:country => parts[1], :language => parts[0]})
end
end
# Returns the default locale as a hash for a given ip_address.
#
# It is similar to {#locale_string_for_ip}, except that this method returns the locale as a hash
# This method comes in handy when you want to preselect only the langauge or the country for your customer
#
# = Example:
# # We take an ip-address from Great Britain for example:
# ip = "212.58.226.75"
# @price_setting.locale_string_for_ip(ip)
# => { :country => 'GB', :language => 'en' }
#
# @param [String] ip an ip-address (e.g. from your site's visitors)
# @return [Hash] a hash with :country and :language as keys
def locale_for_ip(ip)
get "/#{ip}/pay/#{price_setting_id}/locale_for_ip" do |data|
parts = data[:locale].split('-')
{:country => parts[1], :language => parts[0]}
end
end
# Returns a country as a Hash, if the country of the given IP has been configured for your Price Setting.
#
# If the country of the given IP has been configured for this Price Setting, it returns a hash with *:country* and *:locale* subhashes, else it returns *nil*.
#
# @param [String] ip an ip-address (e.g. from your site's visitors)
# @return [Hash] a hash containing *:country* and *:locale* subhashes
def country_has_been_configured_for_ip(ip, options={})
# options can take a :amount key
locale = locale_for_ip(ip)
country = list_countries(options).select{ |c| c.has_value? locale[:country] }.first
{:country => country, :locale => locale} if country
end
# Returns a hash containing the countries and languages that are available to your Price Setting.
#
# @param [Hash] options an options-hash that can take an *:amount* option, in case you want to use dynamic amounts
# @return [Hash] a hash containing subhashes of countries and languages
def list_locales(options={})
get "/#{options[:amount]}/pay/#{price_setting_id}/list_locales" do |data|
{:countries => Zaypay::Util.arrayify_if_not_an_array(data[:countries][:country]),
:languages => data[:languages][:language]}
end
end
# Returns an array of countries that are available to your Price Setting.
#
# @param [Hash] options an options-hash that can take an *:amount* option, in case you want to use dynamic pricing
# @return [Array] an array of countries, each represented by a hash with *:code* and *:name*
def list_countries(options={})
get "/#{options[:amount]}/pay/#{price_setting_id}/list_locales" do |data|
Zaypay::Util.arrayify_if_not_an_array(data[:countries][:country])
end
end
# Returns an array of languages that are available to your Price Setting.
#
# @param [Hash] options an options-hash that can take an *:amount* option, in case you want to use dynamic pricing
# @return [Array] an array of languages, each represented by a hash with *:code*, *:english_name*, *:native_name*
def list_languages(options={})
get "/#{options[:amount]}/pay/#{price_setting_id}/list_locales" do |data|
data[:languages][:language]
end
end
# Returns an array of payment methods that are available to your Price Setting with a given locale
#
# @param [Hash] options an options-hash that can take an *:amount* option, in case you want to use dynamic amounts
# @return [Array] an array of payment methods, each represented by a hash.
# @raise [Zaypay::Error] in case you call this method before setting a locale
def list_payment_methods(options={})
raise Zaypay::Error.new(:locale_not_set, "locale was not set for your price setting") if @locale.nil?
get "/#{options[:amount]}/#{@locale}/pay/#{price_setting_id}/payments/new" do |data|
Zaypay::Util.arrayify_if_not_an_array(data[:payment_methods][:payment_method])
end
end
# Creates a payment on the Zaypay platform.
#
# You can provide an options-hash, which will add additional data to your payment. The following keys have special functionalities:
#
# :amount # Enables dynamic pricing. It must be an integer representing the price in cents.
# :payalogue_id # Adds the URL of the payalogue specified to your payment as :payalogue_url.
#
# Any other keys will be added to a key named :your_variables, which can be used for your future reference. Please check the {file:/README.rdoc README} for the structure of the payment returned.
#
# = Example:
# @price_setting.create_payment(:payalogue_id => payalogue_id, :amount => optional_amount, :my_variable_1 => "value_1", :my_variable_2 => "value_2")
#
# @param [Hash] options an options-hash that can take an *:amount*, *:payalogue_id* as options, and any other keys can be used as your custom variables for your own reference
# @return [Hash] a hash containing data of the payment you just created
# @raise [Zaypay::Error] in case you call this method before setting a *locale* or a *payment_method_id*
def create_payment(options={})
raise Zaypay::Error.new(:locale_not_set, "locale was not set for your price setting") if @locale.nil?
raise Zaypay::Error.new(:payment_method_id_not_set, "payment_method_id was not set for your price setting") if @payment_method_id.nil?
query = {:payment_method_id => payment_method_id}
query.merge!(options)
amount = query.delete(:amount)
post "/#{amount}/#{@locale}/pay/#{price_setting_id}/payments", query do |data|
payment_hash data
end
end
# Returns the specified payment as a hash.
#
# @param [Integer] payment_id your payment's id
# @return [Hash] a hash containing data of the specified payment
def show_payment(payment_id)
get "///pay/#{price_setting_id}/payments/#{payment_id}" do |data|
payment_hash data
end
end
# Submits a verification code to the Zaypay platform.
#
# In some countries, the end-user must submit a verification code in order to complete a payment. Please refer to the {file:/README.rdoc README} for more details
#
# @param [Integer] payment_id the id of the payment that needs to be finalized
# @param [Integer] verification_code a code that the end-user receives through an sms and that he must submit to complete this payment
# @return [Hash] a hash containing data of the specified payment
def verification_code(payment_id, verification_code)
post "///pay/#{price_setting_id}/payments/#{payment_id}/verification_code", :verification_code => verification_code do |data|
payment_hash data
end
end
# Posts a request to the Zaypay platform to mark that you have delivered the 'goodies' to your customer.
#
# Please refer to {file:/README.rdoc README} for more details.
#
# @param [Integer] payment_id the payment's id
# @return [Hash] a hash containing data of the specified payment
def mark_payload_provided(payment_id)
post "///pay/#{price_setting_id}/payments/#{payment_id}/mark_payload_provided" do |data|
payment_hash data
end
end
protected
def select_settings
unless @price_setting_id and @api_key
begin
config = YAML.load_file("#{Rails.root}/config/zaypay.yml")
rescue => e
puts 'Please either specify price_setting id and its API-key as first 2 arguments to #new, or create a config-file (checkout the plugin README)'
raise e
end
config_error = Zaypay::Error.new(:config_error, "You did not provide a price_setting id or/and an API-key. You can either pass it to the constructor or create a config file (check out README)")
raise config_error unless config
@price_setting_id = config['default'] unless @price_setting_id
@api_key = config[@price_setting_id]
if @api_key.nil? || @price_setting_id.nil?
raise config_error
end
end
end
def method_missing(method, url, extra_query_string={})
super unless [:get, :post, :put, :delete].include?(method)
response = self.class.send(method, ('https://secure.zaypay.com' + url), {:query => default_query.merge!(extra_query_string),
:headers => {'Accept' => 'application/xml' } })
Zaypay::Util.uber_symbolize(response)
check response
block_given? ? yield(response[:response]) : response[:response]
end
def check(response)
raise Zaypay::Error.new(:http_error, "HTTP-request to zaypay yielded status #{response.code}..\n\nzaypay said:\n#{response.body}") unless response.code == 200
raise Zaypay::Error.new(:http_error, "HTTP-request to yielded an error:\n#{response[:response][:error]}") if response[:response].delete(:status)=='error'
end
def default_query
{:key => api_key}
end
def payment_hash(data)
{:payment => data.delete(:payment),
:instructions => data}.delete_if{|k,v| v.nil?}
end
end
end |
cask 'ultimate-control' do
version '1.2'
sha256 '8f26885d60c2afc502d97039c115f6bfcd22cee34ec9741017bc4d73bc3e5498'
url "http://www.negusoft.com/downloads/ultimate_control_v#{version}_mac.dmg"
name 'Ultimate Control'
homepage 'http://www.negusoft.com/index.php/ultimate-control'
license :mpl
tags :vendor => 'NEGU Soft'
app 'Ultimate Control.app'
end
|
class Api::RentalsController < ApplicationController
def index
@rentals = Rental
.where(lessee: current_user)
.includes(:lessor, :listing, :review)
.order(:start_date)
end
def create
if (Date.parse(params[:rental][:start_date]) rescue nil).nil?
return render json: ["Must enter both dates"], status: 422
end
listing = Listing.find(params[:rental][:id])
@rental = Rental.new(rental_params)
@rental.lessee_id = current_user.id
@rental.listing = listing
if @rental.save
render "api/rentals/show"
else
render json: @rental.errors.full_messages, status: 422
end
end
private
def rental_params
params.require(:rental).permit(:start_date, :end_date)
end
end
|
class CreateSendMessages < ActiveRecord::Migration
def change
create_table :send_messages, options: 'ENGINE=InnoDB, CHARSET=utf8' do |t|
# 点对点的系统消息表
t.text :message # 系统消息
t.integer :m_type, :default => '0' # 是管理员发送还是用户发送(0管理员发送,1用户发送)
t.integer :sender_id # 发送者id
t.integer :receiver_id # 接收者id
t.timestamp :send_time # 发送时间
t.timestamp :receive_time, :default => '0000-00-00 00:00:00' # 接收时间
t.integer :status, :default => '0' # 是否成功接收(0失败,1成功)
t.timestamps
end
add_index :send_messages, :sender_id
add_index :send_messages, :receiver_id
end
end
|
class Account < ActiveRecord::Base
belongs_to :account_type
belongs_to :member
end
|
class Contact < ApplicationRecord
has_many :conshejointables
has_many :sheets, through: :conshejointables
has_many :descriptions
def name
self.first_name + " " + self.last_name
end
def order_number(sheet)
Conshejointable.where(:sheet_id=> sheet.id, :contact_id => self.id).first.order_number
end
def descs_in_order
self.descriptions.order(:name)
end
def has_picture?
# filename = Rails.root.join("public", self.picture_filename).to_s
# File.exist?(filename)
!self.image.blank?
end
def picture_filename
"pictures/picture" + self.id.to_s + ".jpg"
end
def get_description(sheet)
if self.descriptions.count > 0
description_lookups = Conshejointable.where(:contact_id => self.id, :sheet_id => sheet.id)
if description_lookups.count != 0
description_id = description_lookups.first.description_id
return Description.find(description_id).text if !description_id.blank?
end
return self.descriptions.first.text
end
""
end
def set_selector(description_id)
descs_in_order = self.descs_in_order
if !descs_in_order.blank?
descs_in_order.first.id if description_id == 0
ApplicationController.helpers.select_tag :select, ApplicationController.helpers.options_for_select(descs_in_order.map{ |description| [description.name, description.id]}, description_id).html_safe, {:class => "standard", :onchange => "document.getElementById(\'select_button\').click();".html_safe }
end
end
def test
"hello" if true
"goodbye"
end
end
# <%= form_tag contact_desc_path(@contact), remote: true, :id => 'desc_form' do %>
#
# <%= select_tag :select, options_for_select( @contact.descriptions.order(:name).all.map{|description| [description.name, description.id]}, "") , {:onchange => 'desc_form.submit()'} %>
#
# <%= text_area_tag :desc, "", {class: "standard", style: "width:97%; height: 200px"} %>
# <%= submit_tag "Update" %>
# <% end %>
#ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):
# <%= form_tag contact_desc_path(@contact), remote: true, :id => 'desc_form' do %>
#
# <%= select_tag :select, options_for_select( @contact.descriptions.order(:name).all.map{|description| [description.name, description.id]}, "") , {:onchange => '("select_button").click();'.html_safe } %>
#
# <div style="display: none">
# <%= submit_tag "Select", :id => "select_button", :style =>"width: 120px" %>
# </div>
#
# <%= text_area_tag :desc, "", {class: "standard", style: "width:97%; height: 200px"} %>
# <%= submit_tag "Update" %>
# <% end %>
|
require_relative 'mongo'
class CalendarItem
include Mongoid::Document
field :outlook_id, type: String
field :google_id, type: String
field :location, type: String
field :organizer_name, type: String
field :subject, type: String
field :my_response, type: String
field :start, type: DateTime
field :end, type: DateTime
field :recurrence, type: Hash
field :exception, type: String
validates_inclusion_of :my_response, in: [ 'Accept', 'Tentative', 'Organizer', 'Decline', 'NoResponseReceived', 'Unknown' ]
validates_presence_of :outlook_id
validates_presence_of :google_id, :unless => :exception
validates_uniqueness_of :outlook_id
validates_uniqueness_of :google_id, :allow_nil => true
def self.synch_and_save(item, verbose=false)
cal_item = self.where(:outlook_id => item.id).first || self.new
cal_item.attributes = {:start => item.start, :end => item.end, :subject => item.subject,
:outlook_id => item.id, :location => item.location, :organizer_name => item.organizer.name,
:my_response => item.my_response_type}
cal_item.set_recurrence(item)
if cal_item.new_record? || cal_item.changed?
begin
cal_item.google_id = yield cal_item
rescue => e
trace = e.backtrace.join("\n\t")
message = "Error during processing: #{$!}"
if verbose
puts message
puts "Backtrace:\n\t#{trace}"
end
cal_item.exception = message
end
cal_item.save!
end
cal_item
end
def set_recurrence(item)
if item.recurrence
byday = cadence = until_date = nil
item.recurrence.each do |config|
if config[:weekly_recurrence]
config[:weekly_recurrence][:elems].each do |elem|
if elem[:interval]
cadence = elem[:interval][:text]
end
if elem[:days_of_week]
byday = elem[:days_of_week][:text][0..1].downcase
end
end
end
if config[:end_date_recurrence]
config[:end_date_recurrence][:elems].each do |elem|
if elem[:end_date]
until_date = Date.parse(elem[:end_date][:text])
end
end
end
end
self.recurrence = {freq: 'weekly', byday: byday, interval: cadence}
self.recurrence.merge!(until: until_date) if until_date
end
end
end |
class ChatroomsController < ApplicationController
before_action :authenticate_user!
def index
@chatrooms = current_user.chatrooms.uniq.reverse
end
def new
@chatroom = room_exist?
if @chatroom
redirect_to @chatroom
else
create_chatroom
end
end
def create
create_chatroom
end
def show
@chatroom = Chatroom.includes(:messages).find_by(slug: params[:slug])
@message = Message.new
end
private
def room_exist?
Chatroom.find_by_topic current_user.id.to_s + "_to_" + params[:id].to_s
end
def chatroom_params
{topic: current_user.id.to_s + "_to_" + params[:id].to_s }
end
def create_chatroom
@chatroom = Chatroom.new chatroom_params
if @chatroom.save
@message1 = Message.new user_id: current_user.id, content: " has joined the room.", chatroom_id: @chatroom.id
@message2 = Message.new user_id: params[:id], content: " has joined the room.", chatroom_id: @chatroom.id
@chatroom.messages << [@message1, @message2]
@chatroom.save
respond_to do |format|
format.html { redirect_to @chatroom }
format.js
end
else
respond_to do |format|
flash[:notice] = {error: ["a chatroom with this topic already exists"]}
format.html { redirect_to users_path }
format.js { render template: 'chatrooms/chatroom_error.js.erb'}
end
end
end
end
|
class Public::CartProductsController < ApplicationController
before_action :authenticate_customer!
def index
@cart_products = current_customer.cart_products
@total_price = 0
@cart_products.each do |cp|
# @total_price = @total_price + (cp.quantity * cp.product.price)
@total_price += cp.quantity * cp.product.tax_included_price.to_i
end
end
def create
@cart_product = CartProduct.new(cart_product_params)
@cart_product.customer_id = current_customer.id
@cart_products = current_customer.cart_products.all
@cart_products.each do |cart_product|
if cart_product.product_id == @cart_product.product_id
new_quantity = cart_product.quantity + @cart_product.quantity
cart_product.update_attribute(:quantity, new_quantity)
@cart_product.delete
end
end
@cart_product.save
redirect_to cart_products_path
end
def update
cart_product = CartProduct.find(params[:id])
cart_product.update(quantity_params)
redirect_to cart_products_path
end
def destroy
@cart_product = CartProduct.find(params[:id])
@cart_product.destroy
redirect_to cart_products_path
end
def destroy_all
@cart_products = CartProduct.all
@cart_products.destroy_all
redirect_to products_path
end
private
def quantity_params
params.require(:cart_product).permit(:quantity)
end
def cart_product_params
params.require(:cart_product).permit(:product_id, :costomer_id,:quantity)
end
end
|
class UserWorker
include Sidekiq::Worker
def perform(user_name)
puts "-"*50
puts "name: #{user_name}"
puts "-"*50
end
end
|
require "thor"
require "json"
require "httpclient"
class Updater < Thor
REPO = "artpolikarpov/fotorama"
include Thor::Actions
desc "fetch source files", "fetch source files from GitHub"
def fetch
tag = fetch_tags.last
self.destination_root = "vendor/assets"
remote = "http://fotorama.s3.amazonaws.com/#{tag}"
get "#{remote}/fotorama.css", "stylesheets/fotorama.css"
get "#{remote}/fotorama.js", "javascripts/fotorama.js"
%w(fotorama.png fotorama@2x.png).each do |img|
get "#{remote}/#{img}", "images/#{img}"
end
self.destination_root = ""
create_file "lib/fotoramajs/version.rb" do
"module Fotoramajs\n VERSION = \"#{tag}\"\nend"
end
end
desc "convert css to scss file", "convert css to scss file"
def convert
self.destination_root = "vendor/assets"
inside destination_root do
conveted = "stylesheets/fotorama.css.scss"
run("mv stylesheets/fotorama.css #{conveted}")
gsub_file conveted, '(fotorama.png)', "('fotorama.png')"
gsub_file conveted, '(fotorama@2x.png)', "('fotorama@2x.png')"
gsub_file conveted, 'url(', 'image-url('
end
end
private
def fetch_tags
http = HTTPClient.new
body = http.get("https://api.github.com/repos/#{REPO}/tags").body
response = JSON.parse(body)
response.map { |tag| Gem::Version.new(tag['name']) }.sort
end
end
|
class Admin::PlayersController < ApplicationController
before_action :authorize
before_action :set_player, only: [:edit, :update, :destroy]
# GET /players
# GET /players.json
def index
@players = Player.all
end
# GET /players/1
# GET /players/1.json
def show
respond_to do |format|
format.html { @player = Player.find(params[:id]) }
format.json { render json: Player.find(params[:id]).as_json(:include => [:items, :spells]) }
end
end
# GET /players/new
def new
@player = Player.new
end
# GET /players/1/edit
def edit
end
# POST /pla get 'players/current' => 'players#show_current'yers
# POST /players.json
def create
@player = Player.new(player_params)
@player.user = current_user
respond_to do |format|
if @player.save
format.html { redirect_to @player, notice: 'Player was successfully created.' }
format.json { render :show, status: :created, location: @player }
else
format.html { render :new }
format.json { render json: @player.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /players/1
# PATCH/PUT /players/1.json
def update
respond_to do |format|
if @player.update(player_params)
format.html { redirect_to @player, notice: 'Player was successfully updated.' }
format.json { render :show, status: :ok, location: @player }
else
format.html { render :edit }
format.json { render json: @player.errors, status: :unprocessable_entity }
end
end
end
# DELETE /players/1
# DELETE /players/1.json
def destroy
@player.destroy
respond_to do |format|
format.html { redirect_to players_url, notice: 'Player was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_player
@player = Player.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def player_params
params[:player].permit(:name)
end
def authorize
if !current_user.admin_role?
render :file => "public/401.html", :status => :unauthorized
end
end
end
|
class Student < ActiveRecord::Base
# implement your Student model here
validates :email,
format: {
with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/
}
belongs_to :teacher
after_save :add_field, if: :teacher
def add_field
Teacher.last_student_added_at = Time.now
end
def name
first_name + ' ' + last_name
end
def age
now = Date.today
now.year - birthday.year - ((now.month > birthday.month || (now.month == birthday.month && now.day >= birthday.day)) ? 0 : 1)
end
end
|
class Vaso
attr_accessor :cantidad_de_azucar
attr_accessor :tiene_cafe
attr_accessor :tiene_te
attr_accessor :tiene_leche
def initialize
self.cantidad_de_azucar = 0
end
def tiene_cafe?
self.tiene_cafe
end
def tiene_te?
self.tiene_te
end
def tiene_leche?
self.tiene_leche
end
def tiene_azucar?
self.cantidad_de_azucar > 0
end
end
|
require 'ruby_rhymes'
require 'string_to_arpa'
class Poetry_Utils
def does_rhyme(line1, line2)
#get the phrases' rhyme keys
keys1 = line1.to_phrase.rhyme_keys
keys2 = line2.to_phrase.rhyme_keys
#check intersections between rhyme key arrays of the two end words
if (keys1 & keys2).empty?
return false
else
return true
end
end
def check_syllables(line)
return line.to_phrase.syllables
end
def check_iambic_feet(line)
words = line.split(/\W+/)
stress=0
soft=0
for word in words
if word.to_arpa.tr("^0-9", '').include? '1' #or word.to_arpa.tr("^0-9", '').include? '2'
stress+=1
puts word.to_arpa
end
end
if stress==5
return true
else
puts stress
for word in words
if word.to_arpa.tr("^0-9", '').include? '1' #or word.to_arpa.tr("^0-9", '').include? '2'
puts word.to_arpa
end
end
end
end
end
if __FILE__ == $0
u = Poetry_Utils.new
puts u.does_rhyme("When I do count the clock that tells the time", "which alters when it alteration finds")
puts u.check_iambic_feet("Within his bending sickle's compass come")
end
|
require 'rails_helper'
RSpec.describe 'Pricing Api' do
let!(:panel_provider1) { create(:panel_provider) }
let!(:panel_provider2) { create(:panel_provider) }
let!(:panel_provider3) { create(:panel_provider) }
let(:panel_provider) { panel_provider1 }
let!(:user) { create(:user, panel_provider_id: panel_provider.id) }
let!(:country) { create(:country, panel_provider_id: panel_provider.id) }
let(:country_code) { country.code }
let!(:target_group) { create(:target_group, panel_provider_id: panel_provider.id) }
let (:target_group_id) { target_group.id }
let(:headers) { valid_headers_private_api }
let(:location_group1) { create(:location_group, country_id: country.id) }
let(:location_group2) { create(:location_group, country_id: country.id) }
let(:locations) do
locations = create_list(:location, 40)
locations.each do |loc|
location_group1.locations << loc
end
locations
end
let(:locations_param) do
result = []
locations[0..20].each do |loc|
result << { id: loc.id, panel_size: Faker::Number.between(1, 140) }
end
result
end
let(:params) do
params = {
'target_group_id' => target_group_id,
'locations' => locations_param
}.to_json
params
end
describe 'POST country/:country_code/price ' do
before do
post "/country/#{country_code}/price", params: params, headers: headers
end
context 'when valid user' do
context 'when valid params' do
it 'returns status 200' do
expect(response).to have_http_status(200)
end
it 'returns price' do
expect(json['price']).not_to be_nil
end
end
context 'when invalid params' do
context 'invalid country code' do
let(:country_code) { 'conanbarbarian' }
it 'returns status code 422' do
expect(response).to have_http_status(422)
end
it 'returns not found country' do
expect(response.body).to match(/Validation failed/)
end
end
context 'invalid target_group' do
let(:target_group_id) {1300}
it 'returns status code 404' do
expect(response).to have_http_status(422)
end
it 'returns not found target group' do
expect(response.body).to match(/Validation failed/)
end
end
context 'location does not belong to country' do
let(:locations_param) do
result = []
locations[0..20].each do |loc|
result << { id: loc.id, panel_size: Faker::Number.between(1, 140) }
end
result[10][:id] = 1500
result
end
it 'returns status code 422' do
expect(response).to have_http_status(422)
end
it 'returns invalid request message' do
expect(response.body).to match(/Validation failed/)
end
end
end
context 'when param is missing' do
let(:params) { { 'locations' => locations_param }.to_json }
it 'returns status code 400' do
expect(response).to have_http_status(422)
end
it 'returns invalid request message' do
expect(response.body).to match(/Validation failed/)
end
end
context 'user has no right to use private api' do
let(:user) { create(:user) }
it 'returns status code 403' do
expect(response).to have_http_status(403)
end
it 'returns forbidden message' do
expect(response.body).to match(/Forbidden/)
end
end
end
end
end |
require 'rails_helper'
feature 'vendor onboards for site' do
scenario 'by registering' do
visit root_path
click_link "Sign up"
expect(page).to have_text('Begin accepting payments')
fill_in_registration_fields
expect(page).to have_content('Welcome! You have signed up successfully.')
end
scenario 'by connecting with Stripe' do
visit root_path
click_link "Sign up"
expect(page).to have_text('Begin accepting payments')
fill_in_registration_fields
expect(page).to have_content('Welcome! You have signed up successfully.')
click_link 'CONNECT TO STRIPE'
expect(page).to have_content 'Congrats on connecting your Stripe account!'
vendor = Vendor.last
expect(vendor.stripe_uid).not_to eq nil
expect(page).to have_link('CREATE A PAYMENT LINK', href: new_invoice_path)
end
def fill_in_registration_fields
fill_in 'vendor[email]', with: Faker::Internet.email
fill_in 'vendor[password]', with: Devise.friendly_token.first(8)
click_button 'TRY IT NOW'
end
end
|
class Fabric < ActiveRecord::Base
has_many :wedding_dresses, :inverse_of => :fabric
validates :fabric_type, :presence => true
validates :fabric_type, length: { maximum: 45 }
end
|
require 'rails_helper'
describe LocationDate do
# Constants
describe "Constant" do
it "Should have be this DAYSLIST constant in LocationDate" do
LocationDate.should have_constant("DAYSLIST")
end
it "Should have proper imoprt file extension" do
LocationDate::DAYSLIST.should eq([["Monday", "monday"], ["Tuesday", "tuesday"], ["Wednesday", "wednesday"], ["Thursday", "thursday"], ["Friday", "friday"], ["Saturday", "saturday"], ["Sunday", "sunday"], ["Mon - Fri", "mon_fri"], ["Sat - Sun", "sat_sun"]])
end
end
# allow mass assignment of
describe "allow mass assignment of" do
it { should allow_mass_assignment_of(:time_from) }
it { should allow_mass_assignment_of(:time_to) }
it { should allow_mass_assignment_of(:day) }
it { should allow_mass_assignment_of(:location_id) }
end
# Associations
describe "Associations" do
it { should belong_to(:location) }
end
#method
describe "Method" do
before :each do
@location_date_with_day_one = create(:location_date_with_day_one)
@location_date_without_day = create(:location_date_without_day)
end
context ".delete_blank_record" do
it "day should be Monday" do
@location_date_with_day_one.day.should eq("Monday")
end
it "day should not be blank" do
location_date_count = LocationDate.count
@location_date_without_day
LocationDate.count.should eq(location_date_count)
end
end
end
end
|
require 'wsdl_mapper/runtime/request'
module WsdlMapper
module Runtime
module Middlewares
class SimpleRequestFactory
# Serializes the `message`, sets the service URL and adds SOAPAction and Content-Type headers. For serialization
# it relies on {WsdlMapper::Runtime::Operation#input_s8r} to return the proper input serializer for this operation.
# @param [WsdlMapper::Runtime::Operation] operation
# @param [WsdlMapper::Runtime::Message] message
# @return [Array<WsdlMapper::Runtime::Operation, WsdlMapper::Runtime::Request>]
def call(operation, message)
request = WsdlMapper::Runtime::Request.new message
serialize_envelope request, operation, message
set_url request, operation, message
add_http_headers request, operation, message
[operation, request]
end
protected
def add_http_headers(request, _operation, message)
request.add_http_header 'SOAPAction', message.action
request.add_http_header 'Content-Type', 'text/xml'
end
def set_url(request, _operation, message)
request.url = URI(message.address)
end
def serialize_envelope(request, operation, message)
request.xml = operation.input_s8r.to_xml(message.envelope)
end
end
end
end
end
|
Rails.application.routes.draw do
get 'homes/about'
get 'homes/top'
root 'homes#top'
devise_for :users, :controllers => {
:sessions => "users/sessions",
:passwords => "users/passwords",
:registrations => "users/registrations"
}
devise_for :admins, :controllers => {
:sessions => "admins/sessions"
}
resources :users, only: [:create,:show,:edit, :update, :destroy] do
resources :comments,only: [:create, :destroy]
resource :favorites,only: [:create, :destroy]
end
post 'bikes' => 'bikes#create'
get 'bikes' => 'bikes#index'
get 'bikes/:id' => 'bikes#show', as: 'bike'
get 'bikes/:id/edit' => 'bikes#edit', as: 'edit_bike'
patch 'bikes/:id' => 'bikes#update', as: 'update_bike'
delete 'bikes/:id' => 'bikes#destroy', as: 'destroy_bike'
resources :comments
post '/favorite/:bike_id' => 'favorites#favorite', as: 'favorite'
delete '/favorite/:bike_id' => 'favorites#unfavorite', as: 'unfavorite'
resources :follows, only: [:create, :destroy]
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
|
class Comment < ActiveRecord::Base
belongs_to :post
belongs_to :user
has_many :likes, as: :likable_object
has_many :liking_users, through: :likes, source: :user
attr_accessible :details
def liked_by_user?(user)
return user.liked_comments.include?(self)
end
end |
module Phaseout
class SEOFields
attr_reader :key, :human_name
attr_accessor :values, :default
alias :fields :values
def initialize(key, human_name, values = Hash.new, &block)
@key, @human_name, @values = I18n.transliterate(key).gsub(/\s+/, '_').underscore, human_name, values
yield(self) if block_given?
end
def to_html(controller)
values = evaluated_values(controller).map do |helper, argument|
begin
controller.view_context.send helper, *argument
rescue
argument
end
end
values << controller.view_context.og_auto_default
values << controller.view_context.twitter_auto_default
values.compact.join.html_safe
end
def action_key
@action_key ||= @key.match('seo_key:').post_match.match(':').pre_match
end
def action
@action ||= ::Phaseout::SEOAction.new action_key
end
def id
I18n.transliterate(@key.match(/\#.+\:/).post_match.gsub(/\!+/, '').gsub(/\s+/, '_')).underscore
end
def to_json
{
id: id,
key: @key.match('seo_key:').post_match,
fields: @values,
name: @human_name,
action_id: action_key.gsub('#', '_').underscore,
action_key: action_key
}.to_json
end
def dump
Marshal.dump self
end
def save
Phaseout.redis.set key, self.dump
end
def delete
Phaseout::SEOAction.find(action_key).remove key
Phaseout.redis.del key
end
def evaluated_values(controller)
@_values ||= if @default
@default.evaluated_values(controller).merge @values
else
Hash[
@values.map do |helper, argument|
if argument.is_a? Proc
[ helper, controller.instance_eval(&argument) ]
else
[ helper, argument ]
end
end
]
end
end
def [](index)
values[index.to_sym]
end
def []=(index, value)
values[index.to_sym] = value
end
def inspect
"#<Phaseout::SEO #{action_key} #{@human_name}>"
end
alias :to_s :inspect
def method_missing(method, *args, &block)
if block_given?
@values[method.to_sym] = block
else
@values[method.to_sym] = args unless args.empty?
end
end
def marshal_dump
[ @key, @human_name, @values ]
end
def marshal_load(dump_array)
@key, @human_name, @values = dump_array
end
def self.find(key)
dump = Phaseout.redis.get "seo_key:#{key}"
dump ? Marshal.load(dump) : nil
end
def self.all(action_key, &block)
unless block_given?
values = []
self.all(action_key){ |field| values << field }
return values
end
class_index_key = "action:#{action_key}"
Phaseout.redis.sscan_each(class_index_key) do |value|
yield self.find value.match('seo_key:').post_match
end
end
end
end
|
# frozen_string_literal: true
require 'rubocop/rake_task'
require 'rake/testtask'
require 'rake/packagetask'
require 'rubygems/package_task'
desc 'Run linter and tests'
task default: %i(rubocop test)
RuboCop::RakeTask.new
Rake::TestTask.new do |t|
t.test_files = FileList['test/spec*.rb']
# t.verbose = true
end
spec_path = File.expand_path('../rack_encrypted_cookie.gemspec', __FILE__)
spec = Gem::Specification.load(spec_path)
package_task = Gem::PackageTask.new(spec)
package_task.define
desc 'Release to rubygems.org'
task release: :package do
sh 'git', 'tag', "v#{spec.version}"
sh 'git', 'push', '--tags'
sh 'gem', 'push', File.join(package_task.package_dir, spec.file_name)
end
|
# encoding: utf-8
require "logstash/outputs/base"
require "logstash/namespace"
require "stud/buffer"
class LogStash::Outputs::AzureLogAnalytics < LogStash::Outputs::Base
include Stud::Buffer
config_name "azure_loganalytics"
# Your Operations Management Suite workspace ID
config :customer_id, :validate => :string, :required => true
# The primary or the secondary Connected Sources client authentication key
config :shared_key, :validate => :string, :required => true
# The name of the event type that is being submitted to Log Analytics.
# This must only contain alpha numeric and _, and not exceed 100 chars.
# sprintf syntax like %{my_log_type} is supported.
config :log_type, :validate => :string, :required => true
# The service endpoint (Default: ods.opinsights.azure.com)
config :endpoint, :validate => :string, :default => 'ods.opinsights.azure.com'
# The name of the time generated field.
# Be carefule that the value of field should strictly follow the ISO 8601 format (YYYY-MM-DDThh:mm:ssZ)
config :time_generated_field, :validate => :string, :default => ''
# The list of key names in in-coming record that you want to submit to Log Analytics
config :key_names, :validate => :array, :default => []
# The list of data types for each column as which you want to store in Log Analytics (`string`, `boolean`, or `double`)
# - The key names in `key_types` param must be included in `key_names` param. The column data whose key isn't included in `key_names` is treated as `string` data type.
# - Multiple key value entries are separated by `spaces` rather than commas
# See also https://www.elastic.co/guide/en/logstash/current/configuration-file-structure.html#hash
# - If you want to store a column as datetime or guid data format, set `string` for the column ( the value of the column should be `YYYY-MM-DDThh:mm:ssZ format` if it's `datetime`, and `GUID format` if it's `guid`).
# - In case that `key_types` param are not specified, all columns that you want to submit ( you choose with `key_names` param ) are stored as `string` data type in Log Analytics.
# Example:
# key_names => ['key1','key2','key3','key4',...]
# key_types => {'key1'=>'string' 'key2'=>'string' 'key3'=>'boolean' 'key4'=>'double' ...}
config :key_types, :validate => :hash, :default => {}
# Max number of items to buffer before flushing. Default 50.
config :flush_items, :validate => :number, :default => 50
# Max number of seconds to wait between flushes. Default 5
config :flush_interval_time, :validate => :number, :default => 5
public
def register
require 'azure/loganalytics/datacollectorapi/client'
#if not @log_type.match(/^[[:alpha:]]+$/)
# raise ArgumentError, 'log_type must be only alpha characters'
#end
@key_types.each { |k, v|
t = v.downcase
if ( !t.eql?('string') && !t.eql?('double') && !t.eql?('boolean') )
raise ArgumentError, "Key type(#{v}) for key(#{k}) must be either string, boolean, or double"
end
}
## Start
@client=Azure::Loganalytics::Datacollectorapi::Client::new(@customer_id,@shared_key,@endpoint)
buffer_initialize(
:max_items => @flush_items,
:max_interval => @flush_interval_time,
:logger => @logger
)
end # def register
public
def receive(event)
@log_type = event.sprintf(@log_type)
# Simply save an event for later delivery
buffer_receive(event)
end # def receive
# called from Stud::Buffer#buffer_flush when there are events to flush
public
def flush (events, close=false)
documents = [] #this is the array of hashes to add Azure Log Analytics
events.each do |event|
document = {}
event_hash = event.to_hash()
if @key_names.length > 0
# Get the intersection of key_names and keys of event_hash
keys_intersection = @key_names & event_hash.keys
keys_intersection.each do |key|
if @key_types.include?(key)
document[key] = convert_value(@key_types[key], event_hash[key])
else
document[key] = event_hash[key]
end
end
else
document = event_hash
end
# Skip if document doesn't contain any items
next if (document.keys).length < 1
documents.push(document)
end
# Skip in case there are no candidate documents to deliver
if documents.length < 1
@logger.debug("No documents in batch for log type #{@log_type}. Skipping")
return
end
begin
@logger.debug("Posting log batch (log count: #{documents.length}) as log type #{@log_type} to DataCollector API. First log: " + (documents[0].to_json).to_s)
res = @client.post_data(@log_type, documents, @time_generated_field)
if Azure::Loganalytics::Datacollectorapi::Client.is_success(res)
@logger.debug("Successfully posted logs as log type #{@log_type} with result code #{res.code} to DataCollector API")
else
@logger.error("DataCollector API request failure: error code: #{res.code}, data=>" + (documents.to_json).to_s)
end
rescue Exception => ex
@logger.error("Exception occured in posting to DataCollector API: '#{ex}', data=>" + (documents.to_json).to_s)
end
end # def flush
private
def convert_value(type, val)
t = type.downcase
case t
when "boolean"
v = val.downcase
return (v.to_s == 'true' ) ? true : false
when "double"
return Integer(val) rescue Float(val) rescue val
else
return val
end
end
end # class LogStash::Outputs::AzureLogAnalytics
|
class Story
include Mongoid::Document
field :updated_date, type: Time
field :last_id, type: Integer
embeds_many :texts
def self.fetch_from_twitter
client = AbroadTwitter.getClient
if !client
return
end
texts = []
options = {
:count => 200,
:trim_user => true,
:exclude_replies => true,
:include_entities => true
}
currentStory = Story.new(:texts => [])
prevText = nil
if !Story.all.empty?
currentStory = Story.all.desc(:updated_date).first
options[:since_id] = currentStory.last_id
prevText = currentStory.texts.last
end
while(true)
tweets = client.user_timeline("abroadguille", options)
tweets.each do |tweet|
texts << Text.parse(tweet)
end
if tweets.length == 0
break
else
options[:max_id] = tweets.last.id - 1
end
end
if texts.empty?
return
end
texts = texts.reverse()
texts.each do |text|
if prevText && far_appart(prevText,text)
currentStory.finish()
currentStory = Story.new(:texts => [text])
else
currentStory.texts << text
end
prevText = text
end
if currentStory.texts.length > 0
currentStory.finish()
end
end
def finish
#self.texts = self.texts.reverse
self.updated_date = self.texts.last.date
self.last_id = self.texts.last.tweet_id
self.save
end
def self.far_appart(text1,text2)
time1 = text1.date
time2 = text2.date
if (time1 - time2).abs > 16 * 60
return true
else
return false
end
end
end
|
require 'net/http'
require 'json'
module Kademy
class Request
attr_accessor :uri, :http, :response, :request
def initialize(options = {})
end
def get(path = "", options={})
@uri = build_uri(path)
@http = Net::HTTP.new(@uri.host, @uri.port)
@http.use_ssl = (@uri.scheme == 'https')
@request = Net::HTTP::Get.new(@uri)
@request['Content-Type'] = "application/json"
@response = http.request(@request)
self
end
def parse_response
JSON.parse(@response.body)
end
def trim_slashes(path = "")
path.gsub(/(^\/|\/)$/, "")
end
def build_uri( path = "" )
path = trim_slashes(path)
klass = Kademy.protocol.eql?("https") ? URI::HTTPS : URI::HTTP
klass.build(
scheme: Kademy.protocol,
host: "#{Kademy.locale_subdomain}.#{Kademy.hostname}",
path: "/api/#{Kademy.api_version}/#{path}"
)
end
end
end
|
require 'digest'
module WebShield
class ThrottleShield < Shield
# Options:
# period: required
# limit: required
# method: optional
# path_sensitive: optional, defualt false
allow_option_keys :period, :limit, :method, :path_sensitive, :dictatorial
def filter(request)
req_path = request.path
return unless path_matcher.match(req_path)
return :block if options[:limit] <= 0
return if options[:method] && options[:method].to_s.upcase != request.request_method
user = config.user_parser.call(request)
incr_opts = if (period = options[:period]) > 0
{expire_at: (Time.now.to_i / period + 1).to_i * period}
else
{}
end
if @config.store.incr(get_store_key(request, user), incr_opts) <= options[:limit]
write_log(:debug, "Pass '#{user}' #{request.request_method} #{req_path}")
:pass
else
write_log(:info, "Block '#{user}' #{request.request_method} #{req_path}")
:block
end
end
private
def get_store_key(request, user)
route = if options[:path_sensitive]
[request.request_method, request.path]
else
(options[:method] ? [options[:method].to_s.upcase, shield_path] : [shield_path])
end
generate_store_key("#{user.to_s}:#{Digest::MD5.hexdigest(route.join('-'))}")
end
end
end
|
module Filter8
class Request
attr_accessor :content
def initialize(content, options = {})
if content.is_a? Hash
@content = content[:content]
options = content.reject!{ |k| k == :content }
else
@content = content
end
raise Exception.new("No value for 'content' given") if(@content.nil?||@content.empty?)
options.each do |filter_name, filter_options|
validate_filter_options(filter_name, filter_options)
instance_variable_value = nil
if filter_options.is_a? Hash
instance_variable_value = { enabled: true }
instance_variable_value = instance_variable_value.merge(filter_options)
else
instance_variable_value = filter_options
end
instance_variable_set("@#{filter_name}", instance_variable_value)
self.class.send(:attr_accessor, filter_name)
end
end
def request_params
request_params = "content=#{CGI.escape(self.content)}"
Filter8::AVAILABLE_FILTERS.each do |filter_name|
if self.respond_to?(filter_name) && !self.send(filter_name).nil?
request_params = request_params + "&" + filter_options_to_params(filter_name)
end
end
request_params
end
private
def filter_options_to_params(filter_name)
params = []
filter_options = self.send(filter_name)
if filter_options.is_a? Hash
filter_options.each do |filter_option, filter_option_value|
if filter_option_value.respond_to? :each
filter_option_value.each do |value|
params << "#{filter_name}.#{filter_option}=#{value}"
end
else
params << "#{filter_name}.#{filter_option}=#{filter_option_value}"
end
end
else
params << "#{filter_name}=#{filter_options}"
end
return params.join("&")
end
def validate_filter_options(filter_name, filter_options)
raise Exception.new("'#{filter_name}' is not a valid filter8-filter") unless Filter8::AVAILABLE_FILTERS.include?(filter_name)
if filter_options.respond_to? :each
filter_options.each do |filter_option, filter_option_value|
raise Exception.new("'#{filter_option}' is not a valid option for filter '#{filter_name}'") unless Filter8::FILTER_PARAMS[filter_name].include?(filter_option)
end
end
end
end
end |
=begin
Using the following code, add the appropriate accessor methods.
Keep in mind that the last_name getter shouldn't be visible outside the class,
while the first_name getter should be visible outside the class.
class Person
def first_equals_last?
first_name == last_name
end
end
person1 = Person.new
person1.first_name = 'Dave'
person1.last_name = 'Smith'
puts person1.first_equals_last?
Expected output:
false
=end
class Person
attr_writer :first_name, :last_name
attr_reader :first_name
def first_equals_last?
first_name == last_name
end
def first_name
@first_name
end
private
def last_name
@last_name
end
end
person1 = Person.new
person1.first_name = 'Dave'
person1.last_name = 'Smith'
puts person1.first_equals_last? |
# @param {Integer} n, a positive integer
# @return {Integer}
def hamming_weight(n)
count = 0
n.to_s(2).each_char do |char|
count += 1 if char == '1'
end
return count
end
|
class ClassesController < ClassesControllerBase
before_action :find_clazz, except: [:new, :create]
before_action :owns_clazz, except: [:new, :create, :show]
def show
@is_owner = owner?
@clazz = @clazz.decorate
NavbarConfig.instance.back_link = request.referer || profile_path(@clazz.instructor_profile.profile_path)
end
def new
@clazz = Clazz.new
end
def create
@clazz = current_user.instructor_profile.classes.create create_params
if @clazz.valid?
redirect_to confirm_class_path(@clazz)
else
@clazz = @clazz.decorate
render :new
end
end
def edit
@clazz = @clazz.decorate
end
def update
if @clazz.update_attributes create_params
redirect_to confirm_class_path(@clazz)
else
@clazz = @clazz.decorate
render :edit
end
end
def confirm
@clazz = @clazz.decorate
NavbarConfig.instance.back_link = edit_class_path @clazz
end
def confirmed
if @clazz.update_attributes confirmed: true
flash[:success] = "Class created"
redirect_to profile_path(current_user.instructor_profile.profile_path)
else
@clazz = @clazz.decorate
render :edit
end
end
private
def find_clazz
@clazz = clazz_scope.find_by id: params[:id]
if @clazz.nil?
flash[:danger] = "Unable to find class"
redirect_to root_path
end
end
def owner?
user_signed_in? && current_user.id == @clazz.instructor_profile.user_id
end
def owns_clazz
unless owner?
flash[:danger] = "Unauthorized access"
redirect_to root_path
end
end
def clazz_scope
if action_name == "show"
Clazz.confirmed
else
Clazz.unconfirmed
end
end
def create_params
params.require(:clazz).permit(Clazz::PERMITTED_PARAMS)
end
end
|
FactoryGirl.define do
sequence(:handle) { |n| "handle#{n}" }
sequence(:email) { |n| "email#{n}@example.com" }
factory :user do
handle { generate :handle }
email { generate :email }
password 'password'
password_confirmation 'password'
end
end
|
namespace :seed do
desc "Makes all genderless users male and all orientationless users gay, then creates valid matches"
task fill_in_user_data: :environment do
User.all.each do |u|
u.gender = true if u.gender.nil?
u.orientation = 'gay' if u.orientation.nil?
u.save
end
Match.create_valid_matches
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.