text stringlengths 10 2.61M |
|---|
class Numbers
def initialize(first_number, second_number)
@first_number = first_number.to_i
@second_number = second_number.to_i
end
def sum
@first_number + @second_number
end
def subtraction
@first_number - @second_number
end
def multiplication
@first_number * @second_number
end
def division
@first_number / @second_number
end
end
if ARGV.length != 3
puts 'We need exactly 3 arguments!'
exit
end
namber_one, namber_two, arithmetic_fun = ARGV
arithmetic = Numbers.new(namber_one, namber_two)
if arithmetic.respond_to?(arithmetic_fun)
p arithmetic.public_send(arithmetic_fun)
else
p 'Error in the third argument! Available arguments is: sum, subtraction, multiplication, division.'
end
|
require 'net/http'
require 'pp'
class LookupService
def lookup_locations(postcode, radius=1.2)
postcode_data = get_lat_long_for(postcode)
get_bus_stops_within_range(postcode_data[:lat].to_f, postcode_data[:lng].to_f, radius)
end
def get_lat_long_for(postcode)
http = get_http()
path = "/postcode/#{sanitise_input(postcode)}.json"
request = Net::HTTP::Get.new path
request_body = http.request(request).body
postcode_data = JSON.parse(request_body, {:symbolize_names => true})
postcode_data[:geo]
end
def get_bus_stops_within_range(lat, lon, radius_in_km)
half_radius = radius_in_km.to_f * 0.009 / 2
BusStop
.where('stop_lat >= ? AND stop_lat <= ?', lat - half_radius, lat + half_radius)
.where('stop_lon >= ? AND stop_lon <= ?', lon - half_radius, lon + half_radius)
end
def get_http
http = Net::HTTP.new 'uk-postcodes.com', 80
http.read_timeout = 10
http
end
def sanitise_input(postcode)
postcode.gsub(/\s+/, '').upcase
end
end
|
get '/' do
@name = User.find(session[:user_id]).username unless session[:user_id].nil?
@array = ShortenedUrl.where(user_id: session[:user_id]) unless session[:user_id].nil?
erb :index
end
post '/' do
if session[:user_id].nil?
@current = ShortenedUrl.create(url: params[:long_url])
else
user = User.find(session[:user_id])
@current = user.shortened_urls.create(url: params[:long_url])
end
@short_url = ShortenedUrl.encode(@current.id)
erb :new
end
delete '/:id' do
begin
ShortenedUrl.destroy(params[:id])
redirect '/'
rescue ActiveRecord::RecordNotFound
redirect '/'
end
end
get '/login' do
erb :login
end
post '/signup' do
begin
current_user = User.signup(params[:new_username], params[:new_password])
session[:user_id] = current_user.id
redirect '/'
rescue ExistingUsername
@sign_up_message = "'#{params[:new_username]}' is already in use. Try a different username."
erb :login
rescue InvalidUsername
@sign_up_message = "Usernames must have between 2 and 30 characters."
erb :login
rescue InvalidNewPassword
@sign_up_message = "Create a password for your account."
erb :login
end
end
post '/login' do
begin
current_user = User.login(params[:username], params[:password])
session[:user_id] = current_user.id
redirect '/'
rescue NonexistentUsername
@log_in_message = "'#{params[:username]}' isn't in our records."
erb :login
rescue NonmatchingPassword
@log_in_message = "That password doesn't match the username '#{params[:username]}'."
erb :login
end
end
get '/logout' do
session[:user_id] = nil
redirect '/'
end
get '/:shortened' do
entry = ShortenedUrl.get_from_hex(params[:shortened])
redirect entry.url
end
|
require 'plivo'
class Friend < ApplicationRecord
include Plivo
has_many :friendships
has_many :users, through: :friendships
def self.send_bulk_message(body: nil)
unless body
self.all.each {|f| f.send_message}
else
self.all.each {|f| f.send_message(body)}
end
end
def send_message(body: nil)
begin
if self.subscribed
message = Message.all.sample
marketing_message = "Spread the love"
unless body
message_body = "Hey #{self.first_name.titleize},\n #{message.body} \n\n This is an automated message from omanii.com\n\n you were added by #{user_list}\n\n#{marketing_message}"
create_plivo_message(message_body)
else
message_body = "Hey #{self.first_name.titleize},\n\n#{body} \n\nautomated message from\nomanii.com\n\n#{marketing_message}"
create_plivo_message(message_body)
end
end
rescue
puts "\n\n\nBroken Number! #{self.number}\n\n\n"
end
end
def create_plivo_message(message_body)
client = RestClient.new(ENV['PLIVO_AUTH_ID'], ENV['PLIVO_AUTH_TOKEN'])
message_created = client.messages.create(
'+14352520588',
[self.number],
message_body
)
end
def self.create_masters_friends(friend_list)
User.find_by(email: 'dilloncortez@gmail.com').friends.create(friend_list)
end
def send_custom_message
end
def self.check_user_list_method_on_prod
self.all.map do |f|
{"#{f.id}": f.user_list}
end
end
def user_list
users_count = users.count
if users_count > 2
who_from = "#{users.last.first_name.titleize} #{users.last.last_name.titleize}, #{users.last(2).first.first_name.titleize} #{users.last(2).first.last_name.titleize} and #{users_count - 2} more"
elsif users_count == 2
who_from = "#{users.last.first_name.titleize} #{users.last.last_name.titleize} and #{users.last(2).first.first_name.titleize} #{users.last(2).first.last_name.titleize}"
else
who_from = "#{users.last.first_name.titleize} #{users.last.last_name.titleize}"
end
who_from
end
private
end
|
class SlackbotsController < ApplicationController
skip_before_action :verify_authenticity_token
CATEGORY = Struct.new(:name, :path)
CATEGORIES = [
CATEGORY.new("Tシャツ", "tops/tshirt-cutsew/"),
CATEGORY.new("カットソー", "tops/tshirt-cutsew/"),
CATEGORY.new("シャツ", "tops/shirt-blouse/"),
CATEGORY.new("ポロシャツ", "tops/polo-shirt/"),
CATEGORY.new("ニット", "tops/knit-sweater/"),
CATEGORY.new("パーカー", "tops/parka/"),
CATEGORY.new("スウェット", "tops/sweat/"),
CATEGORY.new("カーディガン", "tops/cardigan/"),
CATEGORY.new("アンサンブル", "tops/ensemble/"),
CATEGORY.new("ジャージ", "tops/jersey/"),
CATEGORY.new("タンクトップ", "tops/tank-tops/")
].freeze
def test
WearScraping.fetch_wear_page("https://wear.jp/men-category/tops/knit-sweater/")
end
def event
@body = JSON.parse(request.body.read)
if @body['type'] == 'url_verification'
return render json: @body['challenge']
end
number_of_retry = request.headers['HTTP_X_SLACK_RETRY_NUM']
# リトライなら何も処理しない
return head 200 if request.headers['HTTP_X_SLACK_RETRY_NUM'].present?
slack_message = @body['event']['text'].delete('<@US68T0M1Q>').gsub(/[\r\n]/,"")
category = CATEGORIES.find{ |category| category.name == slack_message }
if @body['event']['type'] == 'message' && @body['event']['text'].include?('<@US68T0M1Q>')
case @body['type']
when 'event_callback'
WearScraping.fetch_wear_page("https://wear.jp/men-category/#{category.path}")
end
end
end
end
|
module Hypixel
class Rank
# Returns the highest rank provided in the array.
# Supports both lists of symbols and strings.
#
# Params:
# +ranks+::List of ranks to sort.
# +symbols+::Whether or not the list provided is raw strings or symbols.
def self.top(ranks, symbols)
from_string(ranks.max_by do |rank|
unless symbols
rank = from_string(rank)
end
to_ordinal rank
end)
end
# Returns the symbol for the matching Rank.
#
# Params:
# +id+::The database name returned by the API.
def self.from_string(string)
case string
when 'ADMIN', 'MODERATOR', 'HELPER', 'YOUTUBER'
return string.capitalize.to_sym
when 'JR_HELPER'
return :JrHelper
when 'VIP', 'MVP'
return string.to_sym
when 'VIP_PLUS'
return :VIPPlus
when 'MVP_PLUS'
return :MVPPlus
end
end
private
# Defines the rank listing and sets up their ordinals.
# Only ever called internally.
def self.setup
unless defined? @ranks
@ranks = {}
[:VIP, :VIPPlus, :MVP, :MVPPlus, :JrHelper, :Youtuber, :Helper, :Moderator, :Admin].each do |key|
@ranks[key] = @ranks.size
end
end
end
# Returns the matching symbol for the ordinal.
#
# Params:
# +ordinal+::The ordinal of the rank.
def self.from_ordinal(ordinal)
setup
return nil unless @ranks.has_value? ordinal
@ranks.key ordinal
end
# Returns the matching ordinal for the symbol.
#
# Params:
# +rank+::The rank's symbol.
def self.to_ordinal(rank)
setup
return -1 unless @ranks.has_key? rank
@ranks[rank]
end
end
end
|
require_relative 'input'
module Mastermind
class Player
include Input
attr_writer :h_num
attr_reader :input
def initialize
@h_num = 0
@msg = Message.new
@code = ["r","g","b","y","c","m"]
end
def is_valid?(incode)
arr = []
for i in incode
arr << i if @code.include?(i)
end
arr
true if arr == incode
end
def player_entry(col, computer_code)
input = user_input
case
when input == "q"
puts "#{@msg.quit_msg}"
exit
when input == "h"
if @h_num < col + 1
@h_num += 1
hint(col, computer_code)
else
puts "#{@msg.hint_exceeded_msg}"
invalid(col, computer_code)
end
when input.length > 4 + col
puts "#{@msg.too_long}"
invalid(col, computer_code)
when input.length < 4 + col
puts "#{@msg.too_short}"
invalid(col, computer_code)
when is_valid?(input.split(//))
input = input.split(//)
else
puts "#{@msg.invalid_entry_msg}"
invalid(col,computer_code)
end
end
def invalid(col,computer_code)
player_entry(col,computer_code)
end
def hint(col, computer_code)
h = rand(1..4)
puts "#{@msg.hint_msg(h, computer_code)}"
h = rand(1..4)
player_entry(col,computer_code)
end
end
end
|
require 'rails_helper'
describe Address do
describe '#create' do
it "address_firstname,address_lastname,address_kana_firstname,address_kana_lastname, zipcode, prefectures, municipalities, address" do
address = build(:address)
expect(address).to be_valid
end
it "is invalid without a address_firstname" do
address = build(:address, address_firstname: nil)
address.valid?
expect(address.errors[:address_firstname]).to include("を入力してください")
end
it "is invalid without a address_lastname" do
address = build(:address, address_lastname: nil)
address.valid?
expect(address.errors[:address_lastname]).to include("を入力してください")
end
it "is invalid without a address_kana_firstname" do
address = build(:address, address_kana_firstname: nil)
address.valid?
expect(address.errors[:address_kana_firstname]).to include("を入力してください")
end
it "is invalid without a address_kana_firstname" do
address = build(:address, address_kana_lastname: nil)
address.valid?
expect(address.errors[:address_kana_lastname]).to include("を入力してください")
end
it "is invalid without a zipcode" do
address = build(:address, zipcode: nil)
address.valid?
expect(address.errors[:zipcode]).to include("を入力してください")
end
it "is invalid without a prefectures" do
address = build(:address, prefecture: nil)
address.valid?
expect(address.errors[:prefecture]).to include("を入力してください")
end
it "is invalid without a municipalities" do
address = build(:address, municipalities: nil)
address.valid?
expect(address.errors[:municipalities]).to include("を入力してください")
end
it "is invalid without a zipcode" do
address = build(:address, address: nil)
address.valid?
expect(address.errors[:address]).to include("を入力してください")
end
end
end |
class AddStatusToTenant < ActiveRecord::Migration[6.1]
def change
add_column :tenants, :status, :string
end
end
|
#here we describe class Product
class Product
def initialize(price, amount)
@price = price
@amount = amount
end
def price
@price
end
def update(params)#each child should define its own method
end
def info#the same
end
def show #this method will return a string to print it later on
"#{info} - #{@price} rub. [available #{@amount}]"
end
def self.showcase(products)# this method will print out on the screen each product and its
#poptions in a list
puts "What do you want to buy?\n\n"
products.each_with_index {|product, index|
puts "#{index}: #{product.show}"}
puts "x. Leave the store\n\n"
end
def buy
if @amount>0
puts '* * *'
puts "You've bought: #{info}"
@amount -= 1
price
else
puts "Sorry, there isn't any available"
0
end
end
#Static method of the class, reads xml-document and creates a new object with params of each
#encountered product
def self.read_from_xml(file_path)
#here we assure that xml exists
unless File.exist?(file_path)
abort "File #{file_path} doesn't exist"
end
file = File.new(file_path, 'r:UTF-8')#open file to read
doc = REXML::Document.new(file)#create new REXML::Document
file.close#close file
#create new empty array and variavles to use later
result = []
product = nil
#read every tag product nested in the tag products and iterate it
#But as in a tag <product> there is only one product it will do the loop only once
doc.elements.each('products/product') {|product_node|
#write the value of attributes 'price' and 'amount' in the variables
price = product_node.attributes['price'].to_i
amount = product_node.attributes['amount'].to_i
#iterate each product to create a sample of the needed class
product_node.each_element('book') {|book_node|
product = Book.new(price, amount)
#and updates the sample of the 'Book' whith params
product.update(
title: book_node.attributes['title'],
author: book_node.attributes['author']
)
}
#do the same but for sample of the 'Movie'
product_node.each_element('movie') { |movie_node|
product = Movie.new(price, amount)
product.update(
title: movie_node.attributes['title'],
director: movie_node.attributes['director'],
year: movie_node.attributes['year']
)
}
#And once more for 'Disk'
product_node.each_element('disk') { |disk_node|
product = Disk.new(price, amount)
product.update(
album: disk_node.attributes['album'],
artist: disk_node.attributes['artist'],
genre: disk_node.attributes['genre']
)
}
#and add the sampl to the array
result.push(product)
}
return result
end
end
|
require "fluent/test/log"
require "serverengine"
module DummyLogger
class << self
def logger
dl_opts = {log_level: ServerEngine::DaemonLogger::INFO}
logdev = Fluent::Test::DummyLogDevice.new
logger = ServerEngine::DaemonLogger.new(logdev, dl_opts)
Fluent::Log.new(logger)
end
end
end
|
require 'forwardable'
module PrawnCharts
# PrawnCharts::Graph is the primary class you will use to generate your graphs. A Graph does not
# define a graph type nor does it directly hold any data. Instead, a Graph object can be thought
# of as a canvas on which other graphs are draw. (The actual graphs themselves are subclasses of PrawnCharts::Layers::Base)
# Despite the technical distinction, we will refer to PrawnCharts::Graph objects as 'graphs' and PrawnCharts::Layers as
# 'layers' or 'graph types.'
#
#
# ==== Creating a Graph
#
# You can begin building a graph by instantiating a Graph object and optionally passing a hash
# of properties.
#
# graph = PrawnCharts::Graph.new
#
# OR
#
# graph = PrawnCharts::Graph.new(:title => "Monthly Profits", :theme => PrawnCharts::Themes::RubyBlog.new)
#
# Once you have a Graph object, you can set any Graph-level properties (title, theme, etc), or begin adding
# graph layers. You can add a graph layer to a graph by using the Graph#add or Graph#<< methods. The two
# methods are identical and used to accommodate syntax preferences.
#
# graph.add(:line, 'John', [100, -20, 30, 60])
# graph.add(:line, 'Sara', [120, 50, -80, 20])
#
# OR
#
# graph << PrawnCharts::Layers::Line.new(:title => 'John', :points => [100, -20, 30, 60])
# graph << PrawnCharts::Layers::Line.new(:title => 'Sara', :points => [120, 50, -80, 20])
#
# Now that we've created our graph and added a layer to it, we're ready to render!
#
# graph.render # Renders a 600x400 PDF graph
#
# OR
#
# graph.render(:width => 1200)
#
# And that's your basic PrawnCharts graph! Please check the documentation for the various methods and
# classes you'll be using, as there are a bunch of options not demonstrated here.
#
# A couple final things worth noting:
# * You can call Graph#render as often as you wish with different rendering options. In
# fact, you can modify the graph any way you wish between renders.
#
#
# * There are no restrictions to the combination of graph layers you can add. It is perfectly
# valid to do something like:
# graph.add(:line, [100, 200, 300])
# graph.add(:bar, [200, 150, 150])
#
# Of course, while you may be able to combine some things such as pie charts and line graphs, that
# doesn't necessarily mean they will make any logical sense together. We leave those decisions up to you. :)
class Graph
extend Forwardable
include PrawnCharts::Helpers::LayerContainer
include PrawnCharts::Helpers::Rounding
# Delegating these getters to the internal state object.
def_delegators :internal_state, :title,:x_legend,:y_legend, :theme, :default_type,
:point_markers,:point_markers_rotation,:point_markers_ticks, :value_formatter,
:key_formatter
def_delegators :internal_state, :title=, :theme=,:x_legend=,:y_legend=, :default_type=,
:point_markers=,:point_markers_rotation=,:point_markers_ticks=, :value_formatter=,
:key_formatter=
attr_reader :layout # Writer defined below
# Returns a new Graph. You can optionally pass in a default graph type and an options hash.
#
# Graph.new # New graph
# Graph.new(:line) # New graph with default graph type of Line
# Graph.new({...}) # New graph with options.
#
# Options:
#
# title:: Graph's title
# x_legend :: Title for X Axis
# y_legend :: Title for Y Axis
# theme:: A theme object to use when rendering graph
# layers:: An array of Layers for this graph to use
# default_type:: A symbol indicating the default type of Layer for this graph
# value_formatter:: Sets a formatter used to modify marker values prior to rendering
# point_markers:: Sets the x-axis marker values
# point_markers_rotation:: Sets the angle of rotation for x-axis marker values
# point_markers_ticks:: Sets a small tick mark above each marker value. Helpful when used with rotation.
def initialize(*args)
self.default_type = args.shift if args.first.is_a?(Symbol)
options = args.shift.dup if args.first.is_a?(Hash)
raise ArgumentError, "The arguments provided are not supported." if args.size > 0
options ||= {}
self.theme = PrawnCharts::Themes::Default.new
self.layout = PrawnCharts::Layouts::Empty.new
self.value_formatter = PrawnCharts::Formatters::Number.new
self.key_formatter = PrawnCharts::Formatters::Number.new
%w(title x_legend y_legend theme layers default_type value_formatter point_markers point_markers_rotation point_markers_ticks layout key_formatter marks).each do |arg|
self.send("#{arg}=".to_sym, options.delete(arg.to_sym)) unless options[arg.to_sym].nil?
end
raise ArgumentError, "Some options provided are not supported: #{options.keys.join(' ')}." if options.size > 0
end
# Renders the graph in its current state into a PDF object.
#
# Options:
# size:: An array indicating the size you wish to render the graph. ( [x, y] )
# width:: The width of the rendered graph. A height is calculated at 3/4th of the width.
# theme:: Theme used to render graph for this render only.
# min_value:: Overrides the calculated minimum value used for the graph.
# max_value:: Overrides the calculated maximum value used for the graph.
# layout:: Provide a Layout object to use instead of the default.
def render(pdf,options = {})
options[:theme] ||= theme
options[:value_formatter] ||= value_formatter
options[:key_formatter] ||= key_formatter
options[:point_markers] ||= point_markers
options[:point_markers_rotation] ||= point_markers_rotation
options[:point_markers_ticks] ||= point_markers_ticks
options[:size] ||= (options[:width] ? [options[:width], (options.delete(:width) * 0.6).to_i] : [600, 360])
options[:title] ||= title
options[:x_legend] ||= x_legend
options[:y_legend] ||= y_legend
options[:layers] ||= layers
options[:min_value] ||= bottom_value(options[:padding] ? options[:padding] : nil)
options[:max_value] ||= top_value(options[:padding] ? options[:padding] : nil)
options[:percent_buffer] ||= options[:percent_buffer] || 0.1
options[:adjusted_max_value] ||= adjusted_bounds_values(options[:percent_buffer]).last
options[:adjusted_min_value] ||= adjusted_bounds_values(options[:percent_buffer]).first
options[:min_key] ||= bottom_key
options[:max_key] ||= top_key
options[:graph] ||= self
@at = options[:at] || [0,0]
@width = (options[:size] ? options[:size][0] : 600)
@height = (options[:size] ? options[:size][1] : 360)
pdf.bounding_box([@at[0],@at[1]], :width => @width, :height => @height) do
pdf.reset_text_marks
#pdf.text_mark ":#{id} centroid #{pdf.bounds.left+bounds[:x]+bounds[:width]/2.0,},#{pdf.bounds.bottom+bounds[:y]+bounds[:height]/2.0], :radius => 3}"
pdf.centroid_mark([pdf.bounds.left+pdf.bounds.width/2.0,pdf.bounds.bottom+pdf.bounds.height/2.0+pdf.bounds.height],:radius => 3)
pdf.crop_marks([pdf.bounds.left,pdf.bounds.bottom+pdf.bounds.height],pdf.bounds.width,pdf.bounds.height)
if !options[:layout].nil?
options[:layout].render(pdf,options)
else
self.layout.render(pdf,options)
end
end
end
def layout=(options)
raise ArgumentError, "Layout must include a #render(options) method." unless (options.respond_to?(:render) && options.method(:render).arity.abs > 0)
@layout = options
end
def component(id)
layout.component(id)
end
def remove(id)
layout.remove(id)
end
private
def internal_state
@internal_state ||= GraphState.new
end
end # Graph
end # PrawnChars |
class Messenger
attr_reader :record, :model, :attributes
def initialize(params, model)
@model = model
@attributes = attribute_array(params).to_h
if model == "Visit"
url = find_or_create_url
event = find_or_create_event
update_attributes(url, event)
@record = url.visits.new(attributes)
else
@record = eval(model).new(attributes)
end
record.save if valid_record
end
def message
if valid_record
{:identifier => record.identifier}.to_json if model == "Source"
elsif error == "can't be blank"
"Missing Parameters: #{specific_error}"
elsif specific_error == "Sha identifier has already been taken"
"Payload Has Already Been Received"
elsif error == "has already been taken"
"Non-unique Value: #{specific_error}"
end
end
def status
if valid_record
"200 OK"
elsif error == "can't be blank"
"400 Bad Request"
elsif error == "has already been taken"
"403 Forbidden"
end
end
private
def valid_record
record.valid?
end
def error
record.errors.messages.values.flatten.first
end
def specific_error
record.errors.full_messages.first
end
def underscore
self.gsub(/::/, '/').
gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
gsub(/([a-z\d])([A-Z])/,'\1_\2').
tr("-", "_").
downcase
end
def attribute_array(params)
params.to_a.map do |key, value|
[key.to_s.underscore.to_sym, value]
end
end
def find_or_create_url
url = Url.find_or_create_by(address: attributes[:url])
url.source_id = attributes[:source_id]
url.save if url.valid?
url
end
def find_or_create_event
event = Event.find_or_create_by(name: attributes[:event_name],
source_id: attributes[:source_id])
event.save if event.valid?
event
end
def update_attributes(url, event)
attributes.delete(:event_name)
attributes[:event_id] = event.id
attributes.delete(:url)
attributes[:url_id] = url.id
end
end
|
require 'rails_helper'
describe 'user manages images' do
before do
#@user = FactoryGirl.create(:user)
@album = FactoryGirl.create(:album)
end
it 'create a new image' do
user = @album.user
login_as(user, scope: :user)
visit root_path
click_link "Dashboard"
expect(page).to have_content("My Dashboard")
click_link "View Albums"
expect(page).to have_content(@album.title)
click_link "View Album"
click_link "Add Image"
image_path = 'spec/fixtures/files/example_image.jpg'
attach_file "image[album_image]",image_path
fill_in "image[title]", with: "New images"
fill_in "image[date_taken]", with: Date.yesterday
click_button "Add Image"
expect(page).to have_content("Image uploaded successfully!")
expect(page).to have_content(@album.title)
image = Image.last
expect(image).to have_attributes(
title: "New images",
album_id: @album.id,
date_taken: Date.yesterday,
album_image_file_name: "example_image.jpg"
)
end
end |
module Service
class MessageCreate < BaseService
step Transaction {
step :permit_params
step :create
}
def create
model = Message.create!(permit_params)
@errors += model.errors.full_messages if model.errors.present?
model
end
def permit_params
params.require(:message).permit(:sender, :body)
end
end
end
|
class AddParticipationDueToUsers < ActiveRecord::Migration
def change
add_column :users, :participation_due, :datetime
end
end
|
require 'rails_helper'
# require 'spec_helper'
RSpec.describe GroupsController, :type => :controller do
# describe GroupsController do
context "when user not logged in" do
describe "GET #index" do
it "redirects to login page" do
get :index
expect(response).to redirect_to new_user_session_path
end
end
end
context "when user logged in" do
let(:user) { FactoryGirl.create(:user) }
subject { FactoryGirl.create(:group, id: user) }
before do
sign_in user
end
describe "GET #index" do
it "render :index view" do
get :index
expect(response).to render_template :index
end
end
describe "GET #new" do
it "assigns the requested group to new group" do
get :new
expect(assigns(:group)).to be_new_record
end
it "renders the :new view" do
get :new
expect(response).to render_template :new
end
end
describe "POST #create" do
context "with valid attributes" do
it "creates new object" do
expect{
post :create, group: FactoryGirl.attributes_for(:group)
}.to change(Group, :count).by(1)
end
end
end
describe "GET #edit" do
it "assigns the requested group to subject" do
get :edit, id: subject
expect(assigns(:group)).to eq(subject)
end
it "renders the :edit view" do
get :edit, id: subject
expect(response).to render_template :edit
end
end
describe "PATCH #update" do
context "with valid attributes" do
it "updates object" do
expect{
patch :update, id: subject, group: { name: 'new_group' }
}.to change{ subject.reload.name }. to('new_group')
end
it "redirects to index path" do
patch :update, id: subject, group: { name: 'new_group' }
expect(response).to redirect_to groups_path
end
end
end
describe 'DELETE #destroy' do
before(:each) { @group = FactoryGirl.create :group }
it "deletes the group" do
expect {
delete :destroy, id: @group
}.to change(Group, :count).by(-1)
end
it "redirects to groups#index" do
delete :destroy, id: @group
expect(response).to redirect_to groups_path
end
end
end
end
|
require 'rspec'
require 'spec_helper'
describe 'Misil' do
it 'deberia almacenar vida cuando se instancia el objeto' do
misil = Misil.new 100, 45
expect(misil.vida).to eq 100
end
it 'deberia almacenar masa cuando se instancia el objeto' do
misil = Misil.new 100, 45
expect(misil.masa).to eq 45
end
it 'deberia tener 100 puntos de vida cuando se instancia el objeto' do
misil = Misil.new
expect(misil.vida).to eq 100
end
it 'deberia tener 100 puntos de masa cuando se instancia el objeto' do
misil = Misil.new
expect(misil.masa).to eq 100
end
it 'deberia contener un asteroide en un mapa cuando se instancia el objeto' do
misil = Misil.new 100, 20
expect(misil.efectos.key?(Asteroide)).to eq true
end
it 'deberia contener una bomba en un mapa cuando se instancia el objeto' do
misil = Misil.new 100, 20
expect(misil.efectos.key?(Bomba)).to eq true
end
it 'deberia contener una estrella en un mapa cuando se instancia el objeto' do
misil = Misil.new 100, 20
expect(misil.efectos.key?(Estrella)).to eq true
end
it 'deberia contener una nave en un mapa cuando se instancia el objeto' do
misil = Misil.new 100, 20
expect(misil.efectos.key?(Nave)).to eq true
end
it 'deberia contener un misil en un mapa cuando se instancia el objeto' do
misil = Misil.new 100, 20
expect(misil.efectos.key?(Misil)).to eq true
end
it 'deberia no estar vivo cuando su vida es nula' do
misil = Misil.new 0, 20
expect(misil.esta_vivo).to eq false
end
it 'deberia no estar vivo cuando su masa es nula' do
misil = Misil.new 60, 0
expect(misil.esta_vivo).to eq false
end
it 'deberia almacenar como minimo vida en 0' do
misil = Misil.new -15, 20
expect(misil.vida).to eq 0
end
it 'deberia almacenar como minimo masa en 0' do
misil = Misil.new -15, -20
expect(misil.masa).to eq 0
end
it 'deberia perder 100 puntos de vida cuando colisiona con una nave' do
misil = Misil.new 110, 20
nave = Nave.new 250, 15
misil.colisiona_con nave
expect(misil.vida).to eq 10
end
it 'deberia perder 100 puntos de vida cuando colisiona con otro misil' do
misil_1 = Misil.new 200, 20
misil_2 = Misil.new 110, 20
misil_1.colisiona_con misil_2
expect(misil_1.vida).to eq 100
end
it 'deberia hacerle perder 100 puntos de vida al otro misil cuando colisiona con otro misil' do
misil_1 = Misil.new 200, 20
misil_2 = Misil.new 110, 20
misil_1.colisiona_con misil_2
expect(misil_2.vida).to eq 10
end
it 'deberia no perder vida cuando colisiona con una bomba' do
misil = Misil.new 200, 20
bomba = Bomba.new 10, 80
misil.colisiona_con bomba
expect(misil.vida).to eq 200
end
it 'deberia no perder masa cuando colisiona con una bomba' do
misil = Misil.new 200, 20
bomba = Bomba.new 10, 80
misil.colisiona_con bomba
expect(misil.masa).to eq 20
end
it 'deberia no perder vida cuando colisiona con un asteroide' do
misil = Misil.new 200, 20
asteroide = Asteroide.new 70, 120
misil.colisiona_con asteroide
expect(misil.vida).to eq 200
end
it 'deberia no perder masa cuando colisiona con un asteroide' do
misil = Misil.new 200, 15
asteroide = Asteroide.new 70, 120
misil.colisiona_con asteroide
expect(misil.masa).to eq 15
end
it 'deberia no perder vida cuando colisiona con una estrella' do
misil = Misil.new 30, 5
estrella = Estrella.new 55, 300
misil.colisiona_con estrella
expect(misil.vida).to eq 30
end
it 'deberia no perder masa cuando colisiona con una estrella' do
misil = Misil.new 30, 5
estrella = Estrella.new 55, 300
misil.colisiona_con estrella
expect(misil.masa).to eq 5
end
it 'deberia poder agregar nuevos objetos espaciales y efectos asociados' do
misil = Misil.new
nave = Nave.new
misil.agregar_colision nave, "cualquier_efecto"
expect(misil.efectos[Nave]).to eq "cualquier_efecto"
end
it 'deberia poder quitar objetos espaciales y efectos asociados' do
misil = Misil.new
misil.quitar_colision Misil
expect(misil.efectos[Misil]).to eq nil
end
end
|
class CreateReviews < ActiveRecord::Migration[5.2]
def change
create_table :reviews do |t|
t.integer :user_id, index: true
t.integer :restaurant_id, index: true
t.integer :stars, null: false, limit: 1
t.text :comment
t.text :reply
t.datetime :visited_at
t.datetime :commented_at
t.datetime :replied_at
t.timestamps
end
end
end
|
class RacasController < ApplicationController
before_action :set_raca, only: [:show, :edit, :update, :destroy]
before_action :authenticate_usuario!
# GET /racas
# GET /racas.json
def index
@racas = Raca.all
end
# GET /racas/1
# GET /racas/1.json
def show
end
# GET /racas/new
def new
@raca = Raca.new
end
# GET /racas/1/edit
def edit
end
# POST /racas
# POST /racas.json
def create
@raca = Raca.new(raca_params)
respond_to do |format|
if @raca.save
format.html { redirect_to @raca, notice: 'Raca was successfully created.' }
format.json { render :show, status: :created, location: @raca }
else
format.html { render :new }
format.json { render json: @raca.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /racas/1
# PATCH/PUT /racas/1.json
def update
respond_to do |format|
if @raca.update(raca_params)
format.html { redirect_to @raca, notice: 'Raca was successfully updated.' }
format.json { render :show, status: :ok, location: @raca }
else
format.html { render :edit }
format.json { render json: @raca.errors, status: :unprocessable_entity }
end
end
end
# DELETE /racas/1
# DELETE /racas/1.json
def destroy
@raca.destroy
respond_to do |format|
format.html { redirect_to racas_url, notice: 'Raca was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_raca
@raca = Raca.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def raca_params
params.require(:raca).permit(:nome)
end
end
|
require 'test_helper'
require "authlogic/test_case" # include at the top of test_helper.rb
class CommentsControllerTest < ActionController::TestCase
setup do
@recipe = recipes(:one)
@my_comment = comments(:my_comment_about_pasta)
@gf_comment = comments(:girlfriend_comment_about_pasta)
end
setup :activate_authlogic
test "should create a comment" do
UserSession.create(users(:ben))
assert_difference('Comment.count', 1) do
post :create, comment: { title: "good", content: 'not so bad recipe', recipe_id: 1 }
end
end
test "should not create comment because no one is connected" do
assert_no_difference('Comment.count') do
post :create, comment: { title: "good", content: 'not so bad recipe', recipe_id: 1 }
end
end
test "should update comment" do
UserSession.create(users(:me))
patch :update, id: @my_comment, comment: { title: "good", content: 'not so bad recipe'}
assert_redirected_to recipe_path(@my_comment.recipe)
end
test "should not update comment because current_user is not the author" do
UserSession.create(users(:my_girlfriend))
patch :update, id: @my_comment, comment: { title: "good", content: 'not so bad recipe'}
assert_redirected_to '/'
end
test "should destroy comment" do
UserSession.create(users(:me))
assert_difference('Comment.count', -1) do
delete :destroy, id: @my_comment
end
end
test "should not destroy comment because current_user is not the author" do
UserSession.create(users(:ben))
assert_no_difference('Comment.count') do
delete :destroy, id: @my_comment
end
end
end
|
class NoticeMailer < ApplicationMailer
# Subject can be set in your I18n file at config/locales/en.yml
# with the following lookup:
#
# en.notice_mailer.sendmail_tsubuyakie.subject
#
def sendmail_tsubuyakie(tsubuyakie)
@tsubuyakie = tsubuyakie
mail to: "m.umecco@gmail.com",
subject: '【Tsubuyaky】新しい投稿がありました'
end
end
|
require 'rails_helper'
RSpec.describe Dish, type: :model do
describe "validations" do
it {should validate_presence_of :name}
it {should validate_presence_of :description}
end
describe "relationships" do
it {should belong_to :chef}
it {should have_many :dish_ingredients}
it {should have_many(:ingredients).through(:dish_ingredients)}
end
describe "Instance Methods" do
it "Calorie Count Method" do
bob = Chef.create!(name: "Bob")
pasta = Dish.create!(name: "Pasta", description: "Noodle Dish", chef_id: bob.id)
noodles = Ingredient.create!(name: "Noodles", calories: 50)
sause = Ingredient.create!(name: "Sause", calories: 100)
meatballs = Ingredient.create!(name: "Meatballs", calories: 150)
DishIngredient.create!(dish_id: pasta.id, ingredient_id: noodles.id)
DishIngredient.create!(dish_id: pasta.id, ingredient_id: sause.id)
DishIngredient.create!(dish_id: pasta.id, ingredient_id: meatballs.id)
expect(pasta.calorie_count).to eq(300)
end
end
end
|
class Coach < ActiveRecord::Base
belongs_to :user
has_many :testimonials
has_many :ratings
has_many :chats
has_many :scheduled_calls
after_create :delete_learner # To delete the learner account the coach doesn't need
def delete_learner
@user = User.find(self.user_id)
@user.learner.destroy
end
def average_rating
ratings.sum(:rating) / ratings.size
end
def ratings_count
@total = ratings.sum(:rating)
if @total >= 1000
@total = @total / 100
end
@total
end
end |
require 'rails_helper'
describe CourseApi::Ping do
describe 'get api/v1/ping' do
before { get('/api/v1/ping') }
it { expect(JSON.parse( response.body )).to eq 'pong' }
end
end |
describe ".are_we_there_yet?" do
it "prints out 'are we there yet?' four times every time the method is called" do
expect(are_we_there_yet?).to eq ("are we there yet?are we there yet?are we there yet?are we there yet?")
end
end
|
class Item < ApplicationRecord
default_scope { order(:item_level => :desc) }
validates :name, presence: true, length: { maximum: 100 }
validates :description, length: { maximum: 256 }
validates :item_level, presence: true, numericality: { only_integer: true }
has_many :auctions
belongs_to :bind, optional: true
def self.cached_find_by_id(item_id)
Rails.cache.fetch("item/#{item_id}", expires_in: 1.hours) do
Item.find_by_id(item_id)
end
end
def self.cached_create!(attributes)
item = Item.create!(attributes)
Rails.cache.write("item/#{item.id}", item)
item
end
end |
class Camp < ApplicationRecord
# association
belongs_to :admin_user , foreign_key: "user_id"
has_many :ratings, dependent: :destroy
# validation of presence of fields
validates_presence_of :name, :fees, :website, :course
# validation of lengths
validates_length_of :name, in: 3..40
validates_length_of :website, in: 10..100
validates_length_of :course, in: 10..100
validates_length_of :facebook, in: 6..100, allow_nil: true
validates_length_of :twitter, in: 6..100, allow_nil: true
# validation of ranges
validates_inclusion_of :employment_rate, in: 0..100, allow_nil: true
validates_inclusion_of :graduation_rate, in: 0..100, allow_nil: true
validates_inclusion_of :averge_salary, in: 0..1000000, allow_nil: true
validates_inclusion_of :fees, in: 0..50000
# validates uniequeness
validates :name, uniqueness: true
end
|
class ClientsController < ApplicationController
before_action :set_client, only: [:show, :edit, :update, :destroy]
def import
@client = Client
@import = Mudhead::Importer.new(@client, nil, {})
end
def do_import
@client = Client
@import = Mudhead::Importer.new(@client, params[:file], { before_batch_import: -> (importer) {
project_names = importer.chunk.map { |x| x[:project_id] }
projects = Project.where(name: project_names).pluck(:name, :id)
options = Hash[*projects.flatten]
importer.batch_replace(:project_id, options)
}})
@import.import
if @import.import_result.failed?
render :import
else
redirect_to clients_path, notice: 'Project was successfully created.'
end
end
# GET /clients
def index
@clients = Client.includes(:project).all
end
# GET /clients/1
def show
end
# GET /clients/new
def new
@client = Client.new
end
# GET /clients/1/edit
def edit
end
# POST /clients
def create
@client = Client.new(client_params)
if @client.save
redirect_to @client, notice: 'Client was successfully created.'
else
render :new
end
end
# PATCH/PUT /clients/1
def update
if @client.update(client_params)
redirect_to @client, notice: 'Client was successfully updated.'
else
render :edit
end
end
# DELETE /clients/1
def destroy
@client.destroy
redirect_to clients_url, notice: 'Client was successfully destroyed.'
end
private
# Use callbacks to share common setup or constraints between actions.
def set_client
@client = Client.includes(:project).find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def client_params
params.require(:client).permit(:name, :active, :project_id)
end
end
|
class Picture < AbstractModel
has_attached_file :content, :styles => {
:thumbnail => "150",
:large => "800x800>",
:medium => "400x400>"
}, :default_url => "/image/:style/default.gif"
belongs_to :image
validates_attachment_content_type :content, :content_type => /\Aimage\/.*\Z/
validates :content, presence: true
end
|
module Ricer::Plug::Params
class JoinedChannelParam < ChannelParam
def default_options; { online: '1', channels: '1', users: '0', connectors: '*', multiple: '0' }; end
end
end
|
describe 'adapter_riak' do
before :all do
require 'riak'
# We don't want Riak warnings in tests
Riak.disable_list_keys_warnings = true
end
moneta_build do
Moneta::Adapters::Riak.new(:bucket => 'adapter_riak')
end
moneta_specs ADAPTER_SPECS.without_increment.without_create
end
|
FactoryBot.define do
factory :retrospective do
id {Faker::Number.between(from: 1, to:50000)}
name { Faker::FunnyName.name }
position { Faker::Number.between }
team { FactoryBot.create(:team) }
end
end
|
require "pry"
class Game
attr_accessor :human_player, :enemies
def initialize(argu)
@human_player = HumanPlayer.new(argu)
@enemies = Array.new
4.times do |player|
player = Player.new("enemy#{player}")
@enemies.push(player)
end
end
def kill_player(player_dead)
@enemies.each do |x|
if player_dead == x.name
@enemies.delete(x)
end
end
end
def is_still_ongoing?
if @human_player.life_point > 0 && @enemies.length > 0
return true
else
return false
end
end
def show_players
@Human_player.show_state
puts "il reste #{@enemies.length} enemies"
end
end |
module Fangraphs
module Batters
extend self
extend Download
INDICES = { name: 1, ab: 2, sb: 3, bb: 4, so: 5, slg: 6, obp: 7, woba: 8, wrc: 9, ld: 10, gb: 11, fb: 12 }
DATA = "c,5,21,14,16,38,37,50,54,43,44,45"
SIZE = 13
PARAMS = [
{ version: "L", month: 13, data: DATA, size: SIZE, indices: INDICES },
{ version: "R", month: 14, data: DATA, size: SIZE, indices: INDICES },
{ version: "14", month: 2, data: DATA, size: SIZE, indices: INDICES }
]
def stats(season, team)
css = ".grid_line_regular"
@stats = {}
PARAMS.each do |params|
params[:year] = season.year
params[:fangraph_id] = team.fangraph_id
[0, 1].each do |rost|
params[:rost] = rost
url = build_url(params)
doc = download_file(url)
data = table_data(doc, css)
rows = build_rows(data, params)
add_stats(rows, params[:version])
end
end
return @stats
end
def add_stats(rows, version)
rows.each do |row|
name = row.delete(:name)
@stats[name] ||= {}
@stats[name][version] ||= {}
@stats[name][version].merge!(row)
end
end
def build_rows(data, params)
size = params[:size] + params[:rost]
indices = params[:indices].dup
indices.each do |key, index|
indices[key] += params[:rost] unless key == :name
end
rows = data.each_slice(size).map do |slice|
stat_array = indices.map do |key, index|
if [:name].include?(key)
value = slice[index].text
elsif [:ab, :bb, :sb, :so, :wrc].include?(key)
value = slice[index].to_i
elsif [:slg, :obp, :woba].include?(key)
value = slice[index].thou_i
elsif [:ld, :gb, :fb].include?(key)
value = slice[index].to_f
end
[key, value]
end
Hash[stat_array]
end
return rows
end
def build_url(params)
"http://www.fangraphs.com/leaders.aspx?pos=all&stats=bat&lg=all&qual=0&type=#{params[:data]}&season=#{params[:year]}&month=#{params[:month]}&season1=#{params[:year]}&ind=0&team=#{params[:fangraph_id]}&rost=#{params[:rost]}&age=0&filter=&players=0&page=1_50"
end
end
end
|
#!/usr/bin/env ruby
# encoding: UTF-8
require 'bundler/inline'
gemfile do
source 'https://rubygems.org'
gem 'multi_json', require: false
gem 'oj', require: false
gem 'fast_multi_json', path: '.'
end
# Adapted from https://raw.githubusercontent.com/ohler55/oj/39c975a048d89f42062bb542fae98109520b10eb/test/perf.rb
class Perf
def initialize()
@items = []
end
def add(title, op, &blk)
@items << Item.new(title, op, &blk)
end
def before(title, &blk)
@items.each do |i|
if title == i.title
i.set_before(&blk)
break
end
end
end
def run(iter)
base = Item.new(nil, nil) { }
base.run(iter, 0.0)
@items.each do |i|
i.run(iter, base.duration)
if i.error.nil?
puts "#{i.title}.#{i.op} #{iter} times in %0.3f seconds or %0.3f #{i.op}/sec." % [i.duration, iter / i.duration]
else
puts "***** #{i.title}.#{i.op} failed! #{i.error}"
end
end
summary()
end
def summary()
fastest = nil
slowest = nil
width = 6
@items.each do |i|
next if i.duration.nil?
width = i.title.size if width < i.title.size
end
iva = @items.clone
iva.delete_if { |i| i.duration.nil? }
iva = iva.sort_by { |i| i.duration }
puts
puts "Summary:"
puts "%*s time (secs) rate (ops/sec)" % [width, 'System']
puts "#{'-' * width} ----------- --------------"
iva.each do |i|
if i.duration.nil?
else
puts "%*s %11.3f %14.3f" % [width, i.title, i.duration, i.rate ]
end
end
puts
puts "Comparison Matrix\n(performance factor, 2.0 means row is twice as fast as column)"
puts ([' ' * width] + iva.map { |i| "%*s" % [width, i.title] }).join(' ')
puts (['-' * width] + iva.map { |i| '-' * width }).join(' ')
iva.each do |i|
line = ["%*s" % [width, i.title]]
iva.each do |o|
line << "%*.2f" % [width, o.duration / i.duration]
end
puts line.join(' ')
end
puts
end
class Item
attr_accessor :title
attr_accessor :op
attr_accessor :blk
attr_accessor :duration
attr_accessor :rate
attr_accessor :error
def initialize(title, op, &blk)
@title = title
@blk = blk
@op = op
@duration = nil
@rate = nil
@error = nil
@before = nil
end
def set_before(&blk)
@before = blk
end
def run(iter, base)
begin
GC.start
@before.call unless @before.nil?
start = Time.now
iter.times { @blk.call }
@duration = Time.now - start - base
@duration = 0.0 if @duration < 0.0
@rate = iter / @duration
rescue Exception => e
@error = "#{e.class}: #{e.message}"
end
end
end # Item
end # Perf
# Adapted from https://github.com/ohler55/oj/blob/39c975a048d89f42062bb542fae98109520b10eb/test/perf_compat.rb
require 'optparse'
require 'oj'
require 'fast_multi_json'
require 'multi_json'
$verbose = false
$indent = 0
$iter = 20000
$size = 0
opts = OptionParser.new
opts.on("-v", "verbose") { $verbose = true }
opts.on("-c", "--count [Int]", Integer, "iterations") { |i| $iter = i }
opts.on("-i", "--indent [Int]", Integer, "indentation") { |i| $indent = i }
opts.on("-s", "--size [Int]", Integer, "size (~Kbytes)") { |i| $size = i }
opts.on("-h", "--help", "Show this display") { puts opts; Process.exit!(0) }
files = opts.parse(ARGV)
def capture_error(tag, orig, load_key, dump_key, &blk)
begin
obj = blk.call(orig)
puts obj unless orig == obj
raise "#{tag} #{dump_key} and #{load_key} did not return the same object as the original." unless orig == obj
rescue Exception => e
$failed[tag] = "#{e.class}: #{e.message}"
end
end
$failed = {} # key is same as String used in tests later
# Verify that all packages dump and load correctly and return the same Object as the original.
capture_error('Oj:compat', $obj, 'load', 'dump') { |o| Oj.compat_load(Oj.dump(o, :mode => :compat)) }
capture_error('MultiJson', $obj, 'load', 'dump') { |o| MultiJson.load(MultiJson.dump(o)) }
capture_error('FastMultiJson', $obj, 'oj_load', 'dump') { |o| FastMultiJson.from_json(FastMultiJson.to_json(o)) }
capture_error('JSON::Ext', $obj, 'generate', 'parse') { |o|
require 'json'
require 'json/ext'
JSON.generator = JSON::Ext::Generator
JSON.parser = JSON::Ext::Parser
JSON.load(JSON.generate(o))
}
module One
module Two
module Three
class Empty
def initialize()
@a = 1
@b = 2
@c = 3
end
def eql?(o)
self.class == o.class && @a == o.a && @b = o.b && @c = o.c
end
alias == eql?
def as_json(*a)
{JSON.create_id => self.class.name, 'a' => @a, 'b' => @b, 'c' => @c }
end
def to_json(*a)
JSON.generate(as_json())
end
def self.json_create(h)
self.new()
end
end # Empty
end # Three
end # Two
end # One
$obj = {
'a' => 'Alpha', # string
'b' => true, # boolean
'c' => 12345, # number
'd' => [ true, [false, [-123456789, nil], 3.9676, ['Something else.', false], nil]], # mix it up array
'e' => { 'zero' => nil, 'one' => 1, 'two' => 2, 'three' => [3], 'four' => [0, 1, 2, 3, 4] }, # hash
'f' => nil, # nil
'g' => One::Two::Three::Empty.new(),
'h' => { 'a' => { 'b' => { 'c' => { 'd' => {'e' => { 'f' => { 'g' => nil }}}}}}}, # deep hash, not that deep
'i' => [[[[[[[nil]]]]]]] # deep array, again, not that deep
}
Oj.default_options = { :indent => $indent, :mode => :compat, :use_to_json => true, :create_additions => true, :create_id => '^o' }
if 0 < $size
s = Oj.dump($obj).size + 1
cnt = $size * 1024 / s
o = $obj
$obj = []
cnt.times do
$obj << o
end
end
puts '-' * 80
puts " ## Compat dump Performance"
perf = Perf.new()
unless $failed.has_key?('JSON::Ext')
perf.add('JSON::Ext', 'dump') { JSON.dump($obj) }
perf.before('JSON::Ext') { JSON.parser = JSON::Ext::Parser }
end
unless $failed.has_key?('MultiJson')
perf.add('MultiJson', 'dump') { MultiJson.dump($oj) }
end
unless $failed.has_key?('FastMultiJson')
perf.add('FastMultiJson', 'to_json') { FastMultiJson.to_json($oj) }
end
unless $failed.has_key?('Oj:compat')
perf.add('Oj:compat', 'dump_compat') { Oj.dump($oj, mode: :compat) }
end
perf.run($iter)
puts
puts '-' * 80
puts
$json = JSON.dump($obj)
puts '-' * 80
puts " ## Compat load Performance"
perf = Perf.new()
unless $failed.has_key?('JSON::Ext')
perf.add('JSON::Ext', 'load') { JSON.load($json) }
perf.before('JSON::Ext') { JSON.parser = JSON::Ext::Parser }
end
unless $failed.has_key?('MultiJson')
perf.add('MultiJson', 'load') { MultiJson.load($json) }
end
unless $failed.has_key?('FastMultiJson')
perf.add('FastMultiJson', 'from_json') { FastMultiJson.from_json($json) }
end
unless $failed.has_key?('Oj:compat')
perf.add('Oj:compat', 'load_compat') { Oj.load($json, mode: :compat) }
end
perf.run($iter)
puts
puts '-' * 80
puts
unless $failed.empty?
puts "The following packages were not included for the reason listed"
$failed.each { |tag,msg| puts "***** #{tag}: #{msg}" }
end
|
require 'active_record'
module Middleman
class ActiveRecordExtension < Extension
option :database_config, 'db/config.yml', 'The location of the YAML database configuration.'
option :database_environment, ENV.fetch('MN_ENV', :development).to_sym, 'The database environment to use.'
def initialize(app, options_hash = {}, &block)
super
ActiveRecord::Base.configurations = YAML.load(File.read(options[:database_config]))
ActiveRecord::Base.establish_connection(options[:database_environment].to_sym)
end
end
end
|
module RPX::TestHelper
private
def mock_response(code, body)
OpenStruct.new :code => code, :body => rpx_response(body)
end
def rpx_json(template)
JSON.parse rpx_response(template)
end
def rpx_response(template)
Rails.root.join("test", "fixtures", "rpx", "#{template}.json").read
end
def mapping(identifier = "http://twitter.com/id?=123456789")
RPX::Mapping.new identifier
end
def user_from(provider)
RPX::User.new rpx_json(provider)
end
end
|
require 'acfs/request/callbacks'
module Acfs
# Encapsulate all data required to make up a request to the
# underlaying http library.
#
class Request
attr_accessor :body, :format
attr_reader :url, :headers, :params, :data, :method, :operation
include Request::Callbacks
def initialize(url, options = {}, &block)
@url = URI.parse(url.to_s).tap do |_url|
@data = options.delete(:data) || nil
@format = options.delete(:format) || :json
@headers = options.delete(:headers) || {}
@params = options.delete(:params) || {}
@method = options.delete(:method) || :get
end.to_s
@operation = options.delete(:operation) || nil
on_complete(&block) if block_given?
end
def data?
!data.nil?
end
class << self
def new(*attrs)
return attrs[0] if attrs[0].is_a? self
super
end
end
end
end
|
class Parliament < Formula
include Language::Python::Virtualenv
desc "AWS IAM linting library"
homepage "https://github.com/duo-labs/parliament"
url "https://files.pythonhosted.org/packages/5e/9f/84fed753abbd4c77d6ab7243054eed9736a38872f77d31b454a07bfdfab9/parliament-1.4.1.tar.gz"
sha256 "f94ca078a90a56e8d22fb3c551daef7d6e9d4157e6032c7e7a1226d4280edd65"
license "BSD-3-Clause"
head "https://github.com/duo-labs/parliament.git", branch: "main"
bottle do
sha256 cellar: :any_skip_relocation, arm64_big_sur: "762b08b94a0f957235b731f9336e6d056ddf4feb83b78c301b50167eb9c1a36a"
sha256 cellar: :any_skip_relocation, big_sur: "1286d570bc5ac9ab3f58bc85e09ac8a32037324051ef94d241aaabc2d1dc09dc"
sha256 cellar: :any_skip_relocation, catalina: "a91474384d6b34cc0da2ed8bfff122f42a7681735b11f126e3c0599458676b51"
sha256 cellar: :any_skip_relocation, mojave: "c2ee834ce7f9c285e06951874cf79fa5d6b025d94f12dc4b4331d2657944615c"
sha256 cellar: :any_skip_relocation, x86_64_linux: "c9e92e0da8d144ca3e4f22a465dc696b87d2a793a6161016be0cbb34e2ec1f12"
end
depends_on "python@3.10"
depends_on "six"
resource "boto3" do
url "https://files.pythonhosted.org/packages/f8/8f/4cb0a5311637829d9ab817cc49fe002269a98aef50be4a1f68421e160698/boto3-1.18.57.tar.gz"
sha256 "56a4c68a4ee131527e8bd65ab71270b06d985e6687ef27e9dfa992250fcc4c15"
end
resource "botocore" do
url "https://files.pythonhosted.org/packages/21/f5/381d80faa4b3940be9f81c9c8eca9ea4b9a4df00505aa6efda278aacd4ba/botocore-1.21.57.tar.gz"
sha256 "4fd374e2dad91b2375db08e0c8a0bbd03b5e741b7dc4c5e730a544993cc46850"
end
resource "jmespath" do
url "https://files.pythonhosted.org/packages/3c/56/3f325b1eef9791759784aa5046a8f6a1aff8f7c898a2e34506771d3b99d8/jmespath-0.10.0.tar.gz"
sha256 "b85d0567b8666149a93172712e68920734333c0ce7e89b78b3e987f71e5ed4f9"
end
resource "json-cfg" do
url "https://files.pythonhosted.org/packages/70/d8/34e37fb051be7c3b143bdb3cc5827cb52e60ee1014f4f18a190bb0237759/json-cfg-0.4.2.tar.gz"
sha256 "d3dd1ab30b16a3bb249b6eb35fcc42198f9656f33127e36a3fadb5e37f50d45b"
end
resource "kwonly-args" do
url "https://files.pythonhosted.org/packages/ee/da/a7ba4f2153a536a895a9d29a222ee0f138d617862f9b982bd4ae33714308/kwonly-args-1.0.10.tar.gz"
sha256 "59c85e1fa626c0ead5438b64f10b53dda2459e0042ea24258c9dc2115979a598"
end
resource "python-dateutil" do
url "https://files.pythonhosted.org/packages/4c/c4/13b4776ea2d76c115c1d1b84579f3764ee6d57204f6be27119f13a61d0a9/python-dateutil-2.8.2.tar.gz"
sha256 "0123cacc1627ae19ddf3c27a5de5bd67ee4586fbdd6440d9748f8abb483d3e86"
end
resource "PyYAML" do
url "https://files.pythonhosted.org/packages/a0/a4/d63f2d7597e1a4b55aa3b4d6c5b029991d3b824b5bd331af8d4ab1ed687d/PyYAML-5.4.1.tar.gz"
sha256 "607774cbba28732bfa802b54baa7484215f530991055bb562efbed5b2f20a45e"
end
resource "s3transfer" do
url "https://files.pythonhosted.org/packages/88/ef/4d1b3f52ae20a7e72151fde5c9f254cd83f8a49047351f34006e517e1655/s3transfer-0.5.0.tar.gz"
sha256 "50ed823e1dc5868ad40c8dc92072f757aa0e653a192845c94a3b676f4a62da4c"
end
resource "urllib3" do
url "https://files.pythonhosted.org/packages/80/be/3ee43b6c5757cabea19e75b8f46eaf05a2f5144107d7db48c7cf3a864f73/urllib3-1.26.7.tar.gz"
sha256 "4987c65554f7a2dbf30c18fd48778ef124af6fab771a377103da0585e2336ece"
end
def install
virtualenv_install_with_resources
end
test do
assert_equal "MEDIUM - No resources match for the given action - - [{'action': 's3:GetObject',"\
" 'required_format': 'arn:*:s3:::*/*'}] - {'line': 1, 'column': 40, 'filepath': None}", \
pipe_output("#{bin}/parliament --string \'{\"Version\": \"2012-10-17\", \"Statement\": {\"Effect\": \"Allow\","\
" \"Action\": \"s3:GetObject\", \"Resource\": \"arn:aws:s3:::secretbucket\"}}\'").strip
end
end
|
# frozen_string_literal: true
require "spec_helper"
describe CmeFixListener::TradeCaptureReportRequester do
let(:klass) { described_class }
let(:instance) { klass.new(account) }
let(:account) do
{
"id" => 123,
"name" => "Account1",
"cmeUsername" => "USERNAME_SPEC",
"cmePassword" => "PASSWORD_SPEC",
"cmeEnvironment" => "production"
}
end
describe "#new_client_request" do
let(:header) { { "Content-Type" => "text/plain", "Accept-Encoding" => "gzip, deflate" } }
let(:body) { "body" }
let(:base_auth) do
{
basic_auth: {
username: "USERNAME_SPEC",
password: "PASSWORD_SPEC"
}
}
end
let(:response_body) { base_auth.merge(body: body, headers: header) }
subject(:response) { instance.new_client_request(nil) }
before { allow(instance).to receive(:request_body).with("1").and_return(body) }
context "when making a request" do
it "should send the correct type and header" do
expect_any_instance_of(klass).to receive(:post_client_request).with("1", header)
subject
end
end
context "when http request succeeds" do
it "should return the response" do
successful_httparty_response
subject
end
end
context "when http request fails" do
it "should retry once" do
failed_httparty_response
subject
end
end
end
describe "#existing_client_request" do
let(:token) { "123" }
let(:body) { "body" }
let(:header) { { "Content-Type" => "text/plain", "Accept-Encoding" => "gzip, deflate", "x-cme-token" => token } }
let(:base_auth) do
{
basic_auth: {
username: "USERNAME_SPEC",
password: "PASSWORD_SPEC"
}
}
end
let(:response_body) { base_auth.merge(body: body, headers: header) }
subject(:response) { instance.existing_client_request(token) }
before { allow(instance).to receive(:request_body).with("3").and_return(body) }
context "when making a request" do
it "should send the correct type and header" do
expect_any_instance_of(klass).to receive(:post_client_request).with("3", header)
subject
end
end
context "when http request succeeds" do
it "should return the response" do
successful_httparty_response
subject
end
end
context "when http request fails" do
it "should retry once" do
failed_httparty_response
subject
end
end
end
def failed_httparty_response
configurable_sleep_stub
allow(HTTParty).to receive(:post).with("https://services.cmegroup.com/cmestp/query", response_body).
and_raise(Net::ReadTimeout)
expect(response).to eq nil
expect(HTTParty).to have_received(:post).twice
end
def successful_httparty_response
allow(HTTParty).to receive(:post).with("https://services.cmegroup.com/cmestp/query", response_body).
and_return(:success)
expect(response).to eq :success
expect(HTTParty).to have_received(:post).once
end
def configurable_sleep_stub
allow(instance).to receive(:configurable_sleep).and_return(nil)
end
end
|
class HomesController < ApplicationController
def top
@posts = Post.all.order('created_at DESC').limit(3)
end
end
|
# Store visits to mongodb.
require "mongo"
require "bson"
class VisitStoreMongo
def initialize(mongo_client)
@client = mongo_client
end
def save(key, visit)
# Don't bother storing null or false values.
hash = visit.to_hash.reject!{|k,v| !v}
# Don't bother with id == "none" either.
if hash["id"] == "none"
hash.delete("id")
end
# Use the visit's time instead of the default current time in the
# document _id so visits sort by their time.
hash["_id"] = BSON::ObjectId.from_time(hash.delete("time"), unique: true)
begin
@client[key].insert_one(hash)
rescue => ex
puts "Failed to save visit: #{ex.inspect}"
end
end
def each_not(key, id, ip, &block)
@client[key].
find(id ? {id: {"$ne" => id}} : {ip: {"$ne" => ip}}).
sort("_id": -1).batch_size(30).each do |hash|
hash["time"] = hash.delete("_id").generation_time.to_i
yield(Visit.new(hash))
end
end
end
|
require 'test_helper'
class HubsControllerTest < ActionDispatch::IntegrationTest
setup do
@hub = hubs(:one)
end
test "should get index" do
get hubs_url
assert_response :success
end
test "should get new" do
get new_hub_url
assert_response :success
end
test "should create hub" do
assert_difference('Hub.count') do
post hubs_url, params: { hub: { name: @hub.name } }
end
assert_redirected_to hub_url(Hub.last)
end
test "should show hub" do
get hub_url(@hub)
assert_response :success
end
test "should get edit" do
get edit_hub_url(@hub)
assert_response :success
end
test "should update hub" do
patch hub_url(@hub), params: { hub: { name: @hub.name } }
assert_redirected_to hub_url(@hub)
end
test "should destroy hub" do
assert_difference('Hub.count', -1) do
delete hub_url(@hub)
end
assert_redirected_to hubs_url
end
end
|
class VideosController < ApplicationController
before_filter :authenticate_user!, except: [:index, :show]
before_filter :membership_required
# GET /videos
# GET /videos.json
def index
# @videos = Video.page(params[:page]).per_page(3)
@q = Video.search(params[:q])
@videos = @q.result(distinct: true).page(params[:page]).per_page(3)
@level_value = ["1","2","3"]
respond_to do |format|
format.html # index.html.erb
format.json { render json: @videos }
format.js
# do
# @loaded_video = render
# end
end
end
# GET /videos/1
# GET /videos/1.json
def show
@video = Video.find(params[:id])
@popular = FavoriteVideo.most_favorite_videos
@latest_comments = Comment.latest_comment
@comment = Comment.new
respond_to do |format|
format.html # show.html.erb
format.json { render json: @video }
end
end
end
|
class Qualification < ActiveRecord::Base
validates :title, presence: true
belong_to :doctor
end
|
# frozen_string_literal: true
require 'yaml'
require 'shellwords'
require 'tempfile'
require 'fileutils'
require 'kubernetes-deploy/common'
require 'kubernetes-deploy/concurrency'
require 'kubernetes-deploy/kubernetes_resource'
%w(
custom_resource
cloudsql
config_map
deployment
ingress
persistent_volume_claim
pod
network_policy
service
pod_template
pod_disruption_budget
replica_set
service_account
daemon_set
resource_quota
stateful_set
cron_job
job
custom_resource_definition
horizontal_pod_autoscaler
secret
).each do |subresource|
require "kubernetes-deploy/kubernetes_resource/#{subresource}"
end
require 'kubernetes-deploy/kubectl'
require 'kubernetes-deploy/kubeclient_builder'
require 'kubernetes-deploy/ejson_secret_provisioner'
require 'kubernetes-deploy/cluster_resource_discovery'
require 'kubernetes-deploy/template_sets'
require 'kubernetes-deploy/renderer'
module KubernetesDeploy
class DiffTask
def server_version
kubectl.server_version
end
def initialize(
namespace:, context:, current_sha:, logger: nil, kubectl_instance: nil, bindings: {},
selector: nil, template_paths: [], template_dir: nil
)
template_dir = File.expand_path(template_dir) if template_dir
template_paths = (template_paths.map { |path| File.expand_path(path) } << template_dir).compact
@logger = logger || KubernetesDeploy::FormattedLogger.build(namespace, context)
@template_sets = TemplateSets.from_dirs_and_files(paths: template_paths, logger: @logger)
@task_config = KubernetesDeploy::TaskConfig.new(context, namespace, @logger)
@bindings = bindings
@namespace = namespace
@namespace_tags = []
@context = context
@current_sha = current_sha
@kubectl = kubectl_instance
@selector = selector
end
def run(*args)
run!(*args)
true
rescue FatalDeploymentError
false
end
def run!(stream: STDOUT)
@logger.reset
@logger.phase_heading("Validating resources")
validate_configuration
resources = discover_resources
validate_resources(resources)
@logger.phase_heading("Running diff")
run_diff(resources, stream)
@logger.print_summary(:success)
rescue FatalDeploymentError => error
@logger.summary.add_action(error.message) if error.message != error.class.to_s
@logger.print_summary(:failure)
raise
end
private
def kubeclient_builder
@kubeclient_builder ||= KubeclientBuilder.new
end
def cluster_resource_discoverer
@cluster_resource_discoverer ||= ClusterResourceDiscovery.new(
namespace: @namespace,
context: @context,
logger: @logger,
namespace_tags: @namespace_tags
)
end
def ejson_provisioners
@ejson_provisoners ||= @template_sets.ejson_secrets_files.map do |ejson_secret_file|
EjsonSecretProvisioner.new(
namespace: @namespace,
context: @context,
ejson_keys_secret: ejson_keys_secret,
ejson_file: ejson_secret_file,
logger: @logger,
statsd_tags: @namespace_tags,
selector: @selector,
)
end
end
def validate_resources(resources)
KubernetesDeploy::Concurrency.split_across_threads(resources) do |r|
r.validate_definition(kubectl, selector: @selector)
end
resources.select(&:has_warnings?).each do |resource|
record_warnings(warning: resource.validation_warning_msg, filename: File.basename(resource.file_path))
end
failed_resources = resources.select(&:validation_failed?)
return unless failed_resources.present?
failed_resources.each do |r|
content = File.read(r.file_path) if File.file?(r.file_path) && !r.sensitive_template_content?
record_invalid_template(err: r.validation_error_msg, filename: File.basename(r.file_path), content: content)
end
raise FatalDeploymentError, "Template validation failed"
end
def secrets_from_ejson
ejson_provisioners.flat_map(&:resources)
end
def discover_resources
@logger.info("Discovering resources:")
resources = []
crds_by_kind = cluster_resource_discoverer.crds.group_by(&:kind)
@template_sets.with_resource_definitions(render_erb: true,
current_sha: @current_sha, bindings: @bindings) do |r_def|
crd = crds_by_kind[r_def["kind"]]&.first
r = KubernetesResource.build(namespace: @namespace, context: @context, logger: @logger, definition: r_def,
statsd_tags: @namespace_tags, crd: crd)
resources << r
@logger.info(" - #{r.id}")
end
secrets_from_ejson.each do |secret|
resources << secret
@logger.info(" - #{secret.id} (from ejson)")
end
resources.sort
rescue InvalidTemplateError => e
record_invalid_template(err: e.message, filename: e.filename, content: e.content)
raise FatalDeploymentError, "Failed to render and parse template"
end
def record_invalid_template(err:, filename:, content: nil)
debug_msg = ColorizedString.new("Invalid template: #{filename}\n").red
debug_msg += "> Error message:\n#{FormattedLogger.indent_four(err)}"
if content
debug_msg += if content =~ /kind:\s*Secret/
"\n> Template content: Suppressed because it may contain a Secret"
else
"\n> Template content:\n#{FormattedLogger.indent_four(content)}"
end
end
@logger.summary.add_paragraph(debug_msg)
end
def record_warnings(warning:, filename:)
warn_msg = "Template warning: #{filename}\n"
warn_msg += "> Warning message:\n#{FormattedLogger.indent_four(warning)}"
@logger.summary.add_paragraph(ColorizedString.new(warn_msg).yellow)
end
def validate_configuration()
errors = []
errors += kubeclient_builder.validate_config_files
errors += @template_sets.validate
if @namespace.blank?
errors << "Namespace must be specified"
end
if @context.blank?
errors << "Context must be specified"
end
unless errors.empty?
@logger.summary.add_paragraph(errors.map { |err| "- #{err}" }.join("\n"))
raise FatalDeploymentError, "Configuration invalid"
end
confirm_context_exists
confirm_namespace_exists
@logger.info("Using resource selector #{@selector}") if @selector
@namespace_tags |= tags_from_namespace_labels
@logger.info("All required parameters and files are present")
end
def confirm_context_exists
out, err, st = kubectl.run("config", "get-contexts", "-o", "name",
use_namespace: false, use_context: false, log_failure: false)
available_contexts = out.split("\n")
if !st.success?
raise FatalDeploymentError, err
elsif !available_contexts.include?(@context)
raise FatalDeploymentError, "Context #{@context} is not available. Valid contexts: #{available_contexts}"
end
confirm_cluster_reachable
@logger.info("Context #{@context} found")
end
def confirm_cluster_reachable
success = false
with_retries(2) do
begin
success = kubectl.version_info
rescue KubectlError
success = false
end
end
raise FatalDeploymentError, "Failed to reach server for #{@context}" unless success
TaskConfigValidator.new(@task_config, kubectl, kubeclient_builder, only: [:validate_server_version]).valid?
end
def confirm_namespace_exists
raise FatalDeploymentError, "Namespace #{@namespace} not found" unless namespace_definition.present?
@logger.info("Namespace #{@namespace} found")
end
def namespace_definition
@namespace_definition ||= begin
definition, _err, st = kubectl.run("get", "namespace", @namespace, use_namespace: false,
log_failure: true, raise_if_not_found: true, attempts: 3, output: 'json')
st.success? ? JSON.parse(definition, symbolize_names: true) : nil
end
rescue Kubectl::ResourceNotFoundError
nil
end
def tags_from_namespace_labels
return [] if namespace_definition.blank?
namespace_labels = namespace_definition.fetch(:metadata, {}).fetch(:labels, {})
namespace_labels.map { |key, value| "#{key}:#{value}" }
end
def kubectl
@kubectl ||= Kubectl.new(namespace: @namespace, context: @context, logger: @logger, log_failure_by_default: true)
end
def ejson_keys_secret
@ejson_keys_secret ||= begin
out, err, st = kubectl.run("get", "secret", EjsonSecretProvisioner::EJSON_KEYS_SECRET, output: "json",
raise_if_not_found: true, attempts: 3, output_is_sensitive: true, log_failure: true)
unless st.success?
raise EjsonSecretError, "Error retrieving Secret/#{EjsonSecretProvisioner::EJSON_KEYS_SECRET}: #{err}"
end
JSON.parse(out)
end
end
def with_retries(limit)
retried = 0
while retried <= limit
success = yield
break if success
retried += 1
end
end
def run_diff(resources, stream)
return if resources.empty?
if resources.length > 1
@logger.info("Running diff for following resources:")
resources.each do |r|
@logger.info("- #{r.id}")
end
else
resource = resources.first
@logger.info("Running diff for following resource #{resource.id}")
end
# We want to diff resources 1-by-1 for readability
resources.each do |r|
run_string = ColorizedString.new("Running diff on #{r.type} #{r.namespace}.#{r.name}:").green
@logger.blank_line
@logger.info(run_string)
output, err, diff_st = kubectl.run("diff", "-f", r.file_path, log_failure: true, fail_expected: true)
if output.blank?
no_diff_string = ColorizedString.new("Local and cluster versions are identical").yellow
@logger.info(no_diff_string)
end
if (Gem::Version.new(kubectl.client_version) > Gem::Version.new("1.18.0"))
# from kubectt 1.18.0, the diff command now returns -1 (not a success)
if diff_st.exitstatus == 1 || diff_st.exitstatus == 0
stream.puts output
next
end
else
# versions lower than 1.18
# Kubectl DIFF currently spits out exit code 1 in all cases - PR to customize that is open
# https://github.com/kubernetes/kubernetes/pull/82336
if diff_st.success? || err == "exit status 1"
stream.puts output
next
end
end
raise FatalDeploymentError, <<~MSG
Failed to diff resource: #{r.id}
#{err}
MSG
end
end
end
end
|
class CardTag < ApplicationRecord
belongs_to :tag
belongs_to :card
end
|
module Enumerated
# Wraps single enumerated definition declared in model.
class Definition
def initialize(model, attribute, declaration)
@model, @attribute, @declaration = model, attribute, declaration
raise ArgumentError, "Declared enumeration must be either Array or Hash." unless declaration.is_a?(Array) || declaration.is_a?(Hash)
end
def to_a(opts = {})
result = filtered for_select, opts
result = overridden result, opts
ordered result, opts
end
def label(key)
@declaration.is_a?(Hash) ? @declaration[key.to_sym] : resolve_label(key)
end
private
def resolve_label(key)
I18n.t key.to_s, :default => key.to_s.humanize, :scope => %w(activerecord enumerations) + [@model.downcase, @attribute]
end
def for_select
return @declaration.invert.to_a if @declaration.is_a?(Hash)
result = []
@declaration.each do |d|
result << [resolve_label(d), d]
end
result
end
def ordered(arr, opts)
return arr if opts.empty? || !opts.include?(:order)
ordered = []
opts[:order].each do |o|
ordered << arr.select { |a| a[1].to_sym == o.to_sym }[0]
end
ordered
end
def filtered(arr, opts)
return arr if opts.empty? || !(opts.include?(:except) || opts.include?(:only))
raise ArgumentError, "Cannot pass both :except and :only parameters!" if opts.include?(:except) && opts.include?(:only)
opts.include?(:except) ? except(arr, opts[:except]) : only(arr, opts[:only])
end
def except(arr, keys)
arr.reject { |a| keys.map(&:to_sym).include?(a[1].to_sym) }
end
def only(arr, keys)
arr.select { |a| keys.map(&:to_sym).include?(a[1].to_sym) }
end
def overridden(arr, opts)
return arr if opts.empty? || !opts.include?(:override)
opts[:override].each do |key, value|
arr.select { |a| a[1].to_sym == key.to_sym }[0][0] = value
end
arr
end
end
end |
require 'euler_helper.rb'
NAME ="Relatively prime"
DESCRIPTION ="Euler's Totient function, φ(n) [sometimes called the phi function], is used to determine the number of numbers less than n which are relatively prime to n. For example, as 1, 2, 4, 5, 7, and 8, are all less than nine and relatively prime to nine, φ(9)=6."
def fastphi(n)
list = factorize(n)
return list.first - 1 if list.size == 1
list.uniq!
list.inject(n) do |acc, i|
acc *= (i - 1)
acc /= i
end
end
res = nil
benchmark do
res =(2..1000000).inject({}) do |acc, i|
overput(i)
acc[i] = i.to_f / fastphi(i)
acc
end
end
benchmark do
max = res.values.max
puts res.select{|k,v| v == max}.inspect
end
|
class CreateUsers < ActiveRecord::Migration[5.2]
def change
create_table :users do |t|
t.string :name
t.string :provider
t.string :uid
t.string :omniauth_token
t.string :refresh_token
t.integer :expires_at
t.boolean :expires
t.string :name
t.string :nickname
t.string :email
t.string :image
t.integer :follower_count
## Trackable
t.integer :sign_in_count, default: 0, null: false
t.datetime :current_sign_in_at
t.datetime :last_sign_in_at
t.inet :current_sign_in_ip
t.inet :last_sign_in_ip
t.timestamps
end
add_index :users, :email, unique: true
add_index :users, :omniauth_token, unique: true
end
end
|
Rails.application.routes.draw do
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
root 'sessoes#new'
get 'login' => 'sessoes#new'
post 'login' => 'sessoes#create'
delete 'logout' => 'sessoes#destroy'
resources :estagiarios, :jornadas
get 'minhas_jornadas', to: 'jornadas#minhas_jornadas'
end
|
resource_group_name = attribute('resource_group_name', default: 'Belfast-Demo-VSTS', description: 'Name of the resource group to interogate')
location = attribute('location', default: 'westeurope')
title 'Belfast Demo Virtual Machine'
control 'Belfast Demo VM' do
impact 1.0
title 'Check the attributes of the Belfast demo vm'
describe azure_virtual_machine(group_name: resource_group_name, name: 'belfast-demo-vm') do
its('type') { should eq 'Microsoft.Compute/virtualMachines' }
its('location') { should cmp location }
# Ensure that the machine is from an Ubuntu image
its('publisher') { should cmp 'canonical' }
its('offer') { should cmp 'ubuntuserver' }
its('sku') { should cmp '16.04-LTS' }
# There should be no data disk attached to the machine
its('data_disk_count') { should eq 0 }
# The template sets authentication using an SSK key so password authentication should
# be disabled
it { should_not have_password_authentication }
it { should have_ssh_keys }
its('ssh_key_count') { should > 0 }
# There should be 2 nics attached to the machine
# these should be one for the AMA network and one for the customer
it { should have_nics }
its('nic_count') { should eq 1 }
its('connected_nics') { should include /belfast-demo-vm-nic/ }
# Ensure that boot diagnostics have been enabled
it { should_not have_boot_diagnostics }
# ensure the OSDisk is setup correctly
its('os_type') { should eq 'Linux' }
its('os_disk_name') { should eq 'belfast-demo-os-disk' }
it { should have_managed_osdisk }
its('create_option') { should eq 'FromImage' }
end
end
|
class Coin < ApplicationRecord
has_many :watchlist_coins
has_many :watchlists, through: :watchlist_coins
end
|
class ACMA
extend Conformist
column :name, 11 do |value|
value.match(/[A-Z]+$/)[0].upcase
end
column :callsign, 1
column :latitude, 15
end
class ACMA::Digital < ACMA
column :signal_type do
'digital'
end
end
|
#
# Cookbook Name:: cdap
# Library:: helpers
#
# Copyright © 2016-2017 Cask Data, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
module CDAP
module Helpers
#
# Return true if Explore is enabled
#
def cdap_explore?
return true if cdap_property?('explore.enabled') &&
node['cdap']['cdap_site']['explore.enabled'].to_s == 'true'
# Explore is enabled by default in 3.3+ (CDAP-4355)
return true if !cdap_property?('explore.enabled') &&
node['cdap']['version'].to_f >= 3.3
false
end
#
# Return true if Security is enabled
#
def cdap_security?
return true if cdap_property?('security.enabled') &&
node['cdap']['cdap_site']['security.enabled'].to_s == 'true'
false
end
#
# Return true if SSL is enabled
#
def cdap_ssl?
ssl_enabled =
if node['cdap']['version'].to_f < 2.5 && cdap_property?('security.server.ssl.enabled')
node['cdap']['cdap_site']['security.server.ssl.enabled']
elsif node['cdap']['version'].to_f < 4.0 && cdap_property?('ssl.enabled')
node['cdap']['cdap_site']['ssl.enabled']
elsif cdap_property?('ssl.external.enabled')
node['cdap']['cdap_site']['ssl.external.enabled']
# Now, do fallback ssl.enabled then security.server.ssl.enabled
elsif cdap_property?('ssl.enabled')
node['cdap']['cdap_site']['ssl.enabled']
elsif cdap_property?('security.server.ssl.enabled')
node['cdap']['cdap_site']['security.server.ssl.enabled']
end
ssl_enabled.to_s == 'true'
end
#
# Return true if property is configured as a Java Keystore
#
def cdap_ssl_jks?(property)
jks =
if cdap_property?(property, 'cdap_security')
node['cdap']['cdap_security'][property]
else
'JKS'
end
jks == 'JKS'
end
#
# Return hash with SSL options for JKS
#
def cdap_jks_opts(prefix)
ssl = {}
ssl['password'] = node['cdap']['cdap_security']["#{prefix}.ssl.keystore.password"]
ssl['keypass'] =
if cdap_property?("#{prefix}.ssl.keystore.keypassword")
node['cdap']['cdap_security']["#{prefix}.ssl.keystore.keypassword"]
else
ssl['password']
end
ssl['path'] = node['cdap']['cdap_security']["#{prefix}.ssl.keystore.path"]
ssl['common_name'] = node['cdap']['security']['ssl_common_name']
ssl
end
#
# Return hash with SSL options for OpenSSL
#
def cdap_ssl_opts(prefix = 'dashboard')
ssl = {}
ssl['keypath'] = node['cdap']['cdap_security']["#{prefix}.ssl.key"]
ssl['certpath'] = node['cdap']['cdap_security']["#{prefix}.ssl.cert"]
ssl['common_name'] = node['cdap']['security']['ssl_common_name']
ssl
end
#
# Return true if property is set
#
def cdap_property?(property, sitefile = 'cdap_site')
return true if node['cdap'].key?(sitefile) && node['cdap'][sitefile].key?(property)
false
end
end
end
# Load helpers
Chef::Recipe.send(:include, CDAP::Helpers)
Chef::Resource.send(:include, CDAP::Helpers)
|
# -*- encoding : utf-8 -*-
class PagesController < ApplicationController
before_filter :load_group,except: :see_page
before_action :set_page, only: [:show, :edit, :update, :destroy]
before_filter :authenticate_user!, except: [:see_page]
# GET /pages
# GET /pages.json
def index
@pages = @group.pages.all
end
# GET /pages/1
# GET /pages/1.json
def show
end
# GET /pages/new
def new
@page = @group.pages.build
end
# GET /pages/1/edit
def edit
end
# POST /pages
# POST /pages.json
def create
@page =@group.pages.new(page_params)
respond_to do |format|
if @page.save
format.html { redirect_to group_page_path(@group,@page), notice: 'Страниа успешно создана.' }
format.json { render action: 'show', status: :created, location: @page }
else
format.html { render action: 'new' }
format.json { render json: @page.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /pages/1
# PATCH/PUT /pages/1.json
def update
respond_to do |format|
if @page.update(page_params)
format.html { redirect_to group_page_path(@group,@page), notice: 'Страница успешно отредактирована.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @page.errors, status: :unprocessable_entity }
end
end
end
# DELETE /pages/1
# DELETE /pages/1.json
def destroy
if @page.group.color.present?
@page.group.update_attribute(:color, nil)
end
@page.destroy
respond_to do |format|
format.html { redirect_to group_pages_path(@group), notice: 'Страница успешно удалена.' }
format.json { head :no_content }
end
end
def see_page
@page = Page.where(address:params[:address]).last
@group = Group.find(@page.group_id)
render 'show'
end
private
# Use callbacks to share common setup or constraints between actions.
def set_page
@page = @group.pages.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def page_params
params.require(:page).permit(:title, :name, :body, :address, :group_id, :meta_des, :meta_key)
end
def load_group
@group = Group.find(params[:group_id])
end
end
|
require 'spec_helper'
describe 'organizational units' do
let(:organization_arn) do
output_for(:harness, 'organization_arn')
end
let(:organization) do
organizations_client.describe_organization.organization
end
let(:root) do
organizations_client.list_roots.roots[0]
end
context "builds organizational units one level deep" do
before(:all) do
provision({
organizational_units: [
{
name: "Fulfillment",
children: []
},
{
name: "Online",
children: []
}
]
})
end
it 'has organizational units under root' do
organizational_units =
organizations_client.list_organizational_units_for_parent(
parent_id: root.id
).organizational_units
expect(organizational_units.size).to(eq(2))
expect(organizational_units.map(&:name))
.to(include('Fulfillment', 'Online'))
end
end
context "build organizational units two levels deep" do
before(:all) do
provision({
organizational_units: [
{
name: "Fulfillment",
children: [
{
name: "Warehouse",
children: []
},
{
name: "Collections",
children: []
}
]
}
]
})
end
it 'has organizational units under first level' do
fulfillment_organizational_unit =
organizations_client.list_organizational_units_for_parent(
parent_id: root.id
).organizational_units[0]
child_organizational_units =
organizations_client.list_organizational_units_for_parent(
parent_id: fulfillment_organizational_unit.id
).organizational_units
expect(child_organizational_units.size).to(eq(2))
end
it 'outputs details of the created organizational units' do
organizational_units =
output_for(:harness, 'organizational_units')
organizational_unit_names =
organizational_units.map do |organizational_unit|
organizational_unit[:name]
end
expect(organizational_unit_names)
.to(contain_exactly("Fulfillment", "Warehouse", "Collections"))
end
end
context "build organizational units three levels deep" do
before(:all) do
provision({
organizational_units: [
{
name: "Fulfillment",
children: [
{
name: "Warehouse",
children: [
{
name: "London",
children: []
},
{
name: "Edinburgh",
children: []
}
]
}
]
}
]
})
end
it 'has organizational units under first level' do
fulfillment_organizational_unit =
organizations_client.list_organizational_units_for_parent(
parent_id: root.id
).organizational_units[0]
child_organizational_units =
organizations_client.list_organizational_units_for_parent(
parent_id: fulfillment_organizational_unit.id
).organizational_units
expect(child_organizational_units.size).to(eq(1))
end
it 'has organizational units under second level' do
fulfillment_organizational_unit =
organizations_client.list_organizational_units_for_parent(
parent_id: root.id
).organizational_units[0]
warehouse_organizational_unit =
organizations_client.list_organizational_units_for_parent(
parent_id: fulfillment_organizational_unit.id
).organizational_units[0]
child_organizational_units =
organizations_client.list_organizational_units_for_parent(
parent_id: warehouse_organizational_unit.id
).organizational_units
expect(child_organizational_units.size).to(eq(2))
end
it 'outputs details of the created organizational units' do
organizational_units =
output_for(:harness, 'organizational_units')
organizational_unit_names =
organizational_units.map do |organizational_unit|
organizational_unit[:name]
end
expect(organizational_unit_names)
.to(contain_exactly(
"Fulfillment",
"Warehouse",
"London",
"Edinburgh"))
end
end
end
|
class RemoveQ1FromCheck < ActiveRecord::Migration[5.2]
def change
remove_column :checks, :q1, :text
end
end
|
#
# specifying flor
#
# Tue Jan 24 07:42:13 JST 2017
#
require 'spec_helper'
describe Flor::Waiter do
before :all do
@waiter = Flor::Waiter.allocate
class << @waiter
public :expand_args
end
end
describe '#expand_args' do
it 'expands single points' do
expect(
@waiter.expand_args(wait: 'terminated')
).to eq([
[ [ nil, [ 'terminated' ] ] ],
nil,
'fail'
])
end
it 'expands single points with nid' do
expect(
@waiter.expand_args(wait: '0_0 task')
).to eq([
[ [ '0_0', [ 'task' ] ] ],
nil,
'fail'
])
end
it 'expands multiple points' do
expect(
@waiter.expand_args(wait: '0_0 task; terminated')
).to eq([
[
[ '0_0', [ 'task' ] ],
[ nil, [ 'terminated' ] ]
],
nil,
'fail'
])
end
it 'expands multiple points for a nid' do
expect(
@waiter.expand_args(wait: '0_0 task|cancel; terminated')
).to eq([
[
[ '0_0', [ 'task', 'cancel' ] ],
[ nil, [ 'terminated' ] ]
],
nil,
'fail'
])
end
it 'accepts comma or pipe to "or" points' do
expect(
@waiter.expand_args(wait: '0_0 task,cancel; 0_1 task|cancel')
).to eq([
[
[ '0_0', [ 'task', 'cancel' ] ],
[ '0_1', [ 'task', 'cancel' ] ]
],
nil,
'fail'
])
end
it 'accepts a timeout:' do
expect(
@waiter.expand_args(wait: '0_0 task', timeout: 12)
).to eq([
[ [ '0_0', [ 'task' ] ] ],
12,
'fail'
])
end
it 'accepts an on_timeout:' do
expect(
@waiter.expand_args(wait: '0_0 task', on_timeout: 'shutup')
).to eq([
[ [ '0_0', [ 'task' ] ] ],
nil,
'shutup'
])
end
end
end
|
module PhotosHelper
def get_image_url(photo)
if photo && photo.image.present?
photo.image.thumb("260x210#").url
# asset_path "no_restaurant.png"
else
asset_path "restaurant_default.png"
end
end
def get_image_cover_url(cover = nil)
if cover && cover.image.present?
cover.image.url
# asset_path "no_restaurant.png"
else
asset_path "restaurant_default.png"
end
end
def photo_status_formated(status)
result = ''
text = Photo::STATUS[status]
if status == 0
result = content_tag :span, text, class: 'label label-warning'
elsif status == 1
result = content_tag :span, text, class: 'label label-success'
else
result = content_tag :span, text, class: 'label label-danger'
end
return result.html_safe
end
end
|
# frozen_string_literal: true
class BooksController < ApplicationController
before_action :authenticate_user!
before_action :set_book, only: %i[show edit destroy update]
before_action :edit_auth, only: %i[edit update destroy]
def index
@book = Book.new
@books = Book.all.includes(:user)
@day_ratio = {}
@day_labels = []
6.downto(1) do |day|
@day_ratio.store("#{day}day_ago_count}", Book.created_day_ago(day).count)
@day_labels.push("#{day}日前")
end
@day_ratio.store("today_count", Book.created_today.count)
@day_labels.push("今日")
end
def show
@book_comment = BookComment.new
@book_comments = @book.book_comments
end
def edit; end
def update
if @book.update(book_params)
redirect_to book_path(@book.id)
else
render :edit
end
end
def create
@book = Book.new(book_params)
@book.user_id = current_user.id
if @book.save
redirect_to book_path(@book.id)
else
@books = Book.all.includes(:user)
render :index
end
end
def destroy
if @book.destroy
redirect_to books_path
else
render :show
end
end
private
def set_book
@book = Book.find(params[:id])
end
def book_params
params.require(:book).permit(:title, :body)
end
def edit_auth
redirect_to book_path(@book.id) unless current_user.id == @book.user.id
end
end
|
require 'rails_helper'
RSpec.describe "pet show page", type: :feature do
it "can complete deletion with DELETE and redirect" do
visit "/pets/#{@pet_1.id}"
click_link 'Delete'
expect(current_path).to eq('/pets')
expect(page).not_to have_content(@pet_1.name)
expect(page).not_to have_content(@pet_1.age)
expect(page).not_to have_content(@pet_1.sex)
end
end
|
require 'test_helper'
class SpousesControllerTest < ActionDispatch::IntegrationTest
setup do
@spouse = spouses(:one)
end
test "should get index" do
get spouses_url
assert_response :success
end
test "should get new" do
get new_spouse_url
assert_response :success
end
test "should create spouse" do
assert_difference('Spouse.count') do
post spouses_url, params: { spouse: { email: @spouse.email, employee_phone_number: @spouse.employee_phone_number, gross_income: @spouse.gross_income, height: @spouse.height, hp_number: @spouse.hp_number, ic_num: @spouse.ic_num, mail_add_1: @spouse.mail_add_1, mail_add_2: @spouse.mail_add_2, marital_status: @spouse.marital_status, name: @spouse.name, profession: @spouse.profession, race: @spouse.race, religion: @spouse.religion, status: @spouse.status, weight: @spouse.weight } }
end
assert_redirected_to spouse_url(Spouse.last)
end
test "should show spouse" do
get spouse_url(@spouse)
assert_response :success
end
test "should get edit" do
get edit_spouse_url(@spouse)
assert_response :success
end
test "should update spouse" do
patch spouse_url(@spouse), params: { spouse: { email: @spouse.email, employee_phone_number: @spouse.employee_phone_number, gross_income: @spouse.gross_income, height: @spouse.height, hp_number: @spouse.hp_number, ic_num: @spouse.ic_num, mail_add_1: @spouse.mail_add_1, mail_add_2: @spouse.mail_add_2, marital_status: @spouse.marital_status, name: @spouse.name, profession: @spouse.profession, race: @spouse.race, religion: @spouse.religion, status: @spouse.status, weight: @spouse.weight } }
assert_redirected_to spouse_url(@spouse)
end
test "should destroy spouse" do
assert_difference('Spouse.count', -1) do
delete spouse_url(@spouse)
end
assert_redirected_to spouses_url
end
end
|
module Genetic
class Mutator
def mutate(population, num_generations, fitness_proc)
1.upto(num_generations).each do |generation|
offspring = Population.new(fitness_proc: fitness_proc)
while offspring.count < population.count
parent1 = population.select
parent2 = population.select
if rand <= CROSSOVER_RATE
child1, child2 = parent1 & parent2
else
child1 = parent1
child2 = parent2
end
child1.mutate!
child2.mutate!
if POPULATION_SIZE.even?
offspring.chromosomes << child1 << child2
else
offspring.chromosomes << [child1, child2].sample
end
end
puts "Generation #{generation} - Average: #{population.average_fitness.round(2)} - Max: #{population.max_fitness}"
population = offspring
end
end
end
end
|
class AddMenuFieldsToPages < ActiveRecord::Migration
def change
add_column :pages, :show_menu, :boolean, :default => false
add_column :pages, :show_in_menu, :boolean, :default => false
end
end
|
class CreateEmoticons < ActiveRecord::Migration
def change
create_table :emoticons do |t|
t.string :name, null: false
t.text :image_data, null: false
t.boolean :active, null: false, default: true
t.timestamps
end
end
end
|
class AddTrialGoalsToModelActivityData < ActiveRecord::Migration
def self.up
add_column "pas_model_activity_modelruns", :trial_number, :integer
add_column "pas_model_activity_modelruns", :trial_goal, :text
end
def self.down
remove_column "pas_model_activity_modelruns", :trial_number
remove_column "pas_model_activity_modelruns", :trial_goal
end
end
|
require File.expand_path File.join(File.dirname(__FILE__), 'spec_helper')
describe SMG::HTTP::Model do
before :all do
@klass = Class.new {
include SMG::Resource
include SMG::HTTP
params "term" => "Portal"
site "http://store.steampowered.com"
}
end
describe "#uri_for" do
it "appends a path to the base URI" do
uri = @klass.send(:uri_for, "search")
uri.host.should == "store.steampowered.com"
uri.path.should == "/search"
uri.query_values.size.should == 1
uri.query_values["term"].should == "Portal"
end
it "appends a query to the base URI" do
uri = @klass.send(:uri_for, "search", {"cake" => "Lie"})
uri.host.should == "store.steampowered.com"
uri.path.should == "/search"
uri.query_values.size.should == 2
uri.query_values["term"].should == "Portal"
uri.query_values["cake"].should == "Lie"
end
end
SMG::HTTP::VERBS.each do |verb,klass|
it "proxy #{verb} to #http" do
@klass.should_receive(:http).with(verb, "/search", :options).and_return(:result)
@klass.send(verb, "/search", :options).should == :result
end
end
end
describe SMG::HTTP::Model, "#http" do
before :all do
@klass = Class.new {
include SMG::Resource
include SMG::HTTP
site "http://www.example.org"
}
end
SMG::HTTP::VERBS.each do |verb,klass|
describe "when HTTP method is #{verb.to_s.upcase}" do
before :each do
@response = mock("response", :body => "<response/>")
@request = mock("request", :perform => @response)
end
it "creates a proper SMG::HTTP::Request" do
SMG::HTTP::Request.should_receive(:new).with(klass, anything, anything).and_return(@request)
@klass.send(:http, verb, "/search")
end
it "creates an SMG::HTTP::Request with proper URI" do
@addressable = Addressable::URI.parse("http://www.example.org/path?qvalues=whatever")
SMG::HTTP::Request.should_receive(:new).with(anything, @addressable, anything).and_return(@request)
@klass.send(:http, verb, "/path", :query => {:qvalues => "whatever"})
end
it "creates an SMG::HTTP::Request with proper options" do
@headers = {"X-Test" => "true"}.freeze
SMG::HTTP::Request.should_receive(:new).with(anything, anything, :headers => @headers).and_return(@request)
@klass.send(:http, verb, "/path", :query => {:qvalues => "whatever"}, :headers => @headers)
end
it "attempts to parse response' body" do
SMG::HTTP::Request.should_receive(:new).with(any_args).and_return(@request)
@klass.should_receive(:parse).with("<response/>").and_return(:resource)
@klass.send(:http, verb, "/path").should == :resource
end
end
end
end
# EOF |
require "rails_helper"
RSpec.describe MessageStatus do
describe "#delivered?" do
it "is true if the message status is delivered" do
subject = described_class.new("delivered")
result = subject.delivered?
expect(result).to be(true)
end
it "is false if the message status is not delivered" do
subject = described_class.new("not-delivered")
result = subject.delivered?
expect(result).to be(false)
end
end
describe "#failed?" do
it "is true if the message status is failed" do
subject = described_class.new("failed")
result = subject.failed?
expect(result).to be(true)
end
it "is true if the message status is undelivered" do
subject = described_class.new("undelivered")
result = subject.failed?
expect(result).to be(true)
end
it "is false if the message status is not failed or undelivered" do
subject = described_class.new("not-failed")
result = subject.failed?
expect(result).to be(false)
end
end
end
|
require 'rspec'
require 'dessert'
=begin
Instructions: implement all of the pending specs (the `it` statements without blocks)! Be sure to look over the solutions when you're done.
=end
describe Dessert do
let(:cupcake) { Dessert.new("cupcake", 12, chef)}
let(:chef) { double("chef", name: "Gordon") }
describe "#initialize" do
it "sets a type" do
expect(cupcake.type).to eq("cupcake")
end
it "sets a quantity" do
expect(cupcake.quantity).to eq(12)
end
it "starts ingredients as an empty array" do
expect(cupcake.ingredients.size).to eq(0)
end
it "raises an argument error when given a non-integer quantity" do
expect { Dessert.new("cupcake", "one-two", "Gordon") }.to raise_error(ArgumentError)
end
end
describe "#add_ingredient" do
it "adds an ingredient to the ingredients array" do
cupcake.add_ingredient("sugar")
expect(cupcake.ingredients.size).to eq(1)
end
end
describe "#mix!" do
let(:ingredients) { ["sugar", "spice", "cherry"]}
it "shuffles the ingredient array" do
cupcake.mix!
expect(cupcake.ingredients).not_to eql(["sugar", "spice", "cherry"])
end
end
describe "#eat" do
it "subtracts an amount from the quantity" do
cupcake.eat(4)
expect(cupcake.quantity).to eq(8)
end
it "raises an error if the amount is greater than the quantity" do
expect { cupcake.eat(20) }.to raise_error("not enough left!")
end
end
describe "#serve" do
it "contains the titleized version of the chef's name" do
# expect(cupcake.serve).to include("Gordon")
allow(chef).to receive(:titleize).and_return("Chef Gordon the Great Baker")
expect(cupcake.serve).to include("Chef Gordon the Great Baker")
end
end
describe "#make_more" do
it "calls bake on the dessert's chef with the dessert passed in" do
expect(chef).to receive(:bake).with(cupcake)
cupcake.make_more
end
end
end
|
class WebhooksController < ApplicationController
skip_before_action :verify_authenticity_token
protect_from_forgery :except => :receive
before_action :check_allowed_ip, only: [:receive]
require 'membership'
include Membership
SECRET_KEY = ENV["PAYSTACK_PRIVATE_KEY"]
def receive
if check_allowed_ip == true
request_headers = request.headers
payload = JSON.parse(request.body.read)
data = JSON.generate(payload)
digest = OpenSSL::Digest.new('sha512')
hash = OpenSSL::HMAC.hexdigest(digest, SECRET_KEY, data)
unless hash != request_headers["x-paystack-signature"]
if payload['event'] == 'charge.success' && payload['data']['status'] == 'success'
member = get_member(payload)
event_charge_date = Date.strptime(payload['data']['paid_at']).to_date
if member && event_charge_date != member.account_detail.subscribe_date.to_date
if member.paystack_charges.empty? || member.paystack_charges.last.created_at.today? == false
amount = payload["data"]["amount"]
options = process_payload(payload, member)
ProcessWebhookJob.perform_later options
head :ok
else
head :unprocessable_entity
end
end
end
end
else
render status: 401, json: {
message: "Unauthorized"
}
end
end
def process_payload(payload, member)
amount = payload["data"]["amount"]
description = "Membership Renewal Paystack"
payload["member_id"] = member.id
payload["description"] = description
payload["amount"] = amount
options = payload.to_hash
return options
end
def get_member(payload)
customer_code = payload["data"]["customer"]["customer_code"]
member = Member.find_by(paystack_cust_code: customer_code)
return member
end
def retrieve_payment_method(member)
member.payment_method.payment_system
end
private
def check_allowed_ip
whitelisted = ['41.58.96.208', '52.31.139.75', '52.49.173.169', '52.214.14.220', '127.0.0.1']
if whitelisted.include? request.remote_ip
return true
else
return false
end
end
end
|
MTMD::FamilyCookBook::App.controllers :ingredient do
before do
@logic_class = MTMD::FamilyCookBook::IngredientActions.new(params)
end
get :as_array, :with => '(:q)' do
content_type 'application/json;charset=utf8'
@logic_class.ingredient_options.to_json
end
get :as_array_with_string_values, :with => '(:q)' do
content_type 'application/json;charset=utf8'
@logic_class.ingredient_string_options.to_json
end
get :index, :with => '(:page, :limit)' do
@pagination = pagination_from_params(@logic_class.params)
@items = @logic_class.ingredients(@pagination)
render 'ingredient/index'
end
get :new do
@ingredient = @logic_class.new
render 'ingredient/new'
end
post :create do
if @logic_class.ingredient_params[:title].blank?
flash[:error] = "Please provide a valid title!"
redirect_to url(:ingredient, :new)
return
end
ingredient = @logic_class.create
unless ingredient
flash[:error] = "An error has occurred!"
else
flash[:success] = "Ingredient has been created."
end
redirect_to url(:ingredient, :index)
end
get :edit, :with => '(:id)' do
@tabindex = @logic_class.tabindex
@ingredient = @logic_class.check_id
unless @ingredient
flash[:error] = "Please provide a valid ingredient id!"
redirect_to url(:ingredient, :index)
end
render 'ingredient/edit'
end
delete :destroy, :with => :id do
ingredient = @logic_class.check_id
unless ingredient
flash[:error] = "Please provide a valid ingredient id!"
redirect_to url(:ingredient, :index)
end
if ingredient.used_in_recipes.any?
flash[:error] = "The ingredient is still used in recipes! Please remove the references first!"
redirect_to url(:ingredient, :index)
end
if ingredient.used_in_shopping_lists.any?
flash[:error] = "The ingredient is still used in shopping lists! Please remove the references first!"
redirect_to url(:ingredient, :index)
end
status = @logic_class.destroy
if status == true
flash[:success] = "Ingredient has been deleted."
else
flash[:error] = "An error has occurred!"
end
redirect_to url(:ingredient, :index)
end
put :update, :with => :id do
ingredient = @logic_class.check_id
unless ingredient
flash[:error] = "Please provide a valid ingredient id!"
redirect_to url(:ingredient, :index)
end
status = @logic_class.update
if status == true
flash[:success] = "Ingredient has been save successfully."
else
flash[:message] = "Nothing has been saved/changed!"
end
redirect_to url(:ingredient, :index)
end
end
|
class ReviewSerializer < ActiveModel::Serializer
attributes :id, :title, :rating, :body, :user_id, :review_date
def review_date
"#{object.created_at.strftime("%B %d, %Y - %I:%M%P")}"
end
belongs_to :user
has_many :votes
end
|
class Recipe < ActiveRecord::Base
belongs_to :category
validates_presence_of :title, :ingredients, :instructions
end
|
require 'spec_helper'
describe 'MorrisChart' do
context 'when countable' do
context 'when monthly interval' do
before do
@chart = Chart.new(
name: 'example_chart',
type: 'countable',
default_interval: 'daily',
)
@stats = [
Stat.new(time: DateTime.new(2013, 1, 1), count: 1000),
Stat.new(time: DateTime.new(2013, 1, 2), count: 1200),
Stat.new(time: DateTime.new(2013, 2, 1), count: 1500),
]
@interval = 'monthly'
end
subject do
MorrisChart.new(
chart: @chart,
stats: @stats,
interval: @interval,
).to_hash
end
it 'should be correct hash' do
should eq({
element: 'chart',
data: [
{time: '2013-01', c: 2200},
{time: '2013-02', c: 1500},
],
xkey: 'time',
ykeys: ['c'],
labels: ['example_chart'],
xLabels: 'month',
})
end
end
end
context 'when uncountable' do
context 'when daily interval' do
before do
@chart = Chart.new(name: 'example_chart', type: 'uncountable')
@stats = [
Stat.new(time: DateTime.new(2013, 1, 1), count: 1000),
Stat.new(time: DateTime.new(2013, 1, 2), count: 1200),
Stat.new(time: DateTime.new(2013, 1, 3), count: 1500),
]
@interval = 'daily'
end
subject do
MorrisChart.new(
chart: @chart,
stats: @stats,
interval: @interval,
).to_hash
end
it 'should be correct hash' do
should eq({
element: 'chart',
data: [
{time: '2013-01-01', c: 1000},
{time: '2013-01-02', c: 1200},
{time: '2013-01-03', c: 1500},
],
xkey: 'time',
ykeys: ['c'],
labels: ['example_chart'],
xLabels: 'day',
})
end
end
context 'when monthly interval' do
before do
@chart = Chart.new(name: 'example_chart', type: 'uncountable')
@stats = [
Stat.new(time: DateTime.new(2013, 1, 1), count: 1000),
Stat.new(time: DateTime.new(2013, 2, 1), count: 1200),
Stat.new(time: DateTime.new(2013, 3, 1), count: 1500),
]
@interval = 'monthly'
end
subject do
MorrisChart.new(
chart: @chart,
stats: @stats,
interval: @interval,
).to_hash
end
it 'should be correct hash' do
should eq({
element: 'chart',
data: [
{time: '2013-01', c: 1000},
{time: '2013-02', c: 1200},
{time: '2013-03', c: 1500},
],
xkey: 'time',
ykeys: ['c'],
labels: ['example_chart'],
xLabels: 'month',
})
end
end
end
describe '#empty?' do
subject { MorrisChart.new(chart: chart, stats: stats, interval: 'daily').empty? }
let(:chart) { Chart.new }
context 'stats are empty' do
let(:stats) { [] }
it { should be_true }
end
context 'stats are not empty' do
let(:stats) { [Stat.new(time: DateTime.new(2013, 1, 1), count: 1000)] }
it { should be_false }
end
end
end
|
FactoryBot.define do
factory :link do
sequence(:name) { |n| "Link#{n}" }
sequence(:url) { |n| "https://www.testlink#{n}.com" }
linkable { create(:question) }
end
factory :gist, parent: :link do
sequence(:name) { |n| "Gist#{n}" }
sequence(:url) { |n| "https://gist.github.com/name/gist_id_#{n}" }
gist_body { 'GistBody' }
end
trait :invalid_link do
name { nil }
url { nil }
end
end
|
def greeting
name = gets "Hey! What is your name: "
puts "Hi #{name}. I am a calculator. \n
I can add, subtract, multiply, and divide.\n"
return name
end
def request_calculation_type
operation_selection = gets "Type 1 to add, 2 to subtract, 3 to multiply, or 4 to divide two numbers: "
if operation_selection == 1
return "add"
elsif operation_selection == 2
return "subtract"
elsif operation_selection == 3
return "multiply"
elsif operation_selection == 4
return "divide"
else return "error"
end
# This method performs the requested calculation
# It returns the result of the calculation
def calculate_answer(operator, a, b)
if operator == "add"
return result= a + b
elsif operator == "subtract"
return result = a - b
elsif operator == "multiply"
return result = a * b
elsif operator == "divide"
return result = a / b
end
end
name = greeting
run_calculator = 1
while run_calculator == 1
current_calculation = request_calculation_type()
if current_calculation == "error"
puts "I do not understand this type of calculation... Can we try again?"
else
first_number = gets "What is the first number you would you like to #{calc_type}: "
second_numer = gets "What is the second number you would like to #{calc_type}: "
answer = calculate_answer(current_calculation, first_number, second_number)
puts "The answer is #{answer}"
run_calculator = gets "Type 1 to run another calcution or 2 to end: "
end
end
ECHO is on.
|
module ApplicationHelper
def admin?
current_user && current_user.is_admin
end
end
|
class Coach < ActiveRecord::Base
belongs_to :team
belongs_to :association
end
|
require 'rails_helper'
RSpec.describe "As a visitor " do
describe "When I visit astronauts index page, " do
# (e.g. "Name: Neil Armstrong, Age: 37, Job: Commander")
it "I see a list of astronauts with name, age, and job for each" do
astronaut_1 = Astronaut.create!(name: "Neil Armstrong", age: 37, job: "Commander")
visit astronauts_path
within "#astronaut-#{astronaut_1.id}" do
expect(page).to have_content(astronaut_1.name)
expect(page).to have_content(astronaut_1.age)
expect(page).to have_content(astronaut_1.job)
end
end
# (e.g. "Average Age: 34")
it "the average age of all astronauts"
astronaut_1 = Astronaut.create!(name: "Neil Armstrong", age: 37, job: "Commander")
astronaut_2 = Astronaut.create!(name: "Arm Neilstrong", age: 34, job: "Assistant To The Regional Commander")
astronaut_3 = Astronaut.create!(name: "Strong Neilarm", age: 31, job: "Regional Commander")
visit astronauts_path
expect(page).to have_content("Average Age: 34")
end
end
end
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe CollectedCoin, type: :model do
it 'is valid with value and user' do
collected_coin = build(:collected_coin)
expect(collected_coin).to be_valid
end
context 'when validating' do
it { is_expected.to validate_presence_of(:value) }
it { is_expected.to validate_numericality_of(:value).only_integer }
it { is_expected.to validate_numericality_of(:value).is_less_than_or_equal_to(100_000) }
end
context 'when associating' do
it { is_expected.to belong_to(:user) }
end
context 'when calling methods' do
describe '#user_receive_trophy' do
let(:user) { create(:user) }
before { load "#{Rails.root}/db/seeds.rb" }
context 'when user reaches a collected_coin trophy value' do
it 'rewards the user with a collected_coin trophy' do
coin_trophy = Trophy.where(trophy_category: "collected_coins").find_by(value: 1)
create(:collected_coin, value: 100, user: user)
user.reload
expect(user.trophies).to include(coin_trophy)
end
it 'rewards the user with the correct collected_coin trophy' do
coin_trophy2 = Trophy.where(trophy_category: "collected_coins").find_by(value: 100)
create(:collected_coin, value: 99, user: user)
user.reload
expect(user.trophies).not_to include(coin_trophy2)
end
end
end
end
end
|
require 'nokogiri'
require 'open-uri'
require 'json'
require 'yaml'
require 'ostruct'
# Accepts an SVG (xml) file
# Expects a certain schema (Seating Chart generated from Adobe Illustrator)
# Creates an (AR) Section with Stack ID
# Creates (AR) Areas within those sections
module Tix
class ChartParser
SEATABLE_SECTION_ID = 'Sections'
def initialize(file, account_subdomain)
@file = file
@loaded_file = Nokogiri::XML(open(file))
@account = Account.find_or_create_by_subdomain(account_subdomain)
end
def filename
File.basename(@file, '.svg')
end
# Creates Hash of Area. Can be used with .create(area)
def parse_area(elem)
area = OpenStruct.new
area.type = elem.name
area.color = elem.attr 'fill'
case elem.name
when 'circle'
area.cx = elem.attr 'cx'
area.cy = elem.attr 'cy'
area.r = elem.attr 'r'
when 'text'
area.transform = elem.attr 'transform'
coords = /1 0 0 1 ([\d\.]+) ([\d\.]+)/.match(area.transform)
area.x = coords[1]
area.y = coords[2]
area.text = elem.inner_text
#puts "TEXT: #{elem.inner_text} X: #{area.x} Y: #{area.y}"
when 'rect'
area.x = elem.attr 'x'
area.y = elem.attr 'y'
area.width = elem.attr 'width'
area.height = elem.attr 'height'
when 'polygon', 'polyline'
area.points = elem.attr 'points'
end
area.marshal_dump
end
# Creates (AR) Section within (AR) Account
def parse_section(css, stack_index, seatable=false)
section_name = css.split('#')[-1]
puts " Section: #{section_name} Active: #{seatable.to_s} "
ActiveRecord::Base.silence do
section = @chart.sections.create( :label => section_name,
:seatable => seatable,
:index => stack_index )
# section.prices.create(:label => 'presale', :base => 10.00, :service => 3.00 )
# section.prices.create(:label => 'day_of', :base => 12.00, :service => 12.00 )
@loaded_file.css("#{css} circle, #{css} text, #{css} rect, #{css} polygon").each do |elem|
area_hash = parse_area(elem)
puts " #{area_hash[:type]} (Area)"
section.update_attributes(:color => area_hash[:color]) if section.color.blank?
area_hash.delete :color
section.areas.create( area_hash )
end
puts "Section color is #{section.color}"
end
end
def parse
unless self.valid?
@validation_errors << "Invalid format. Please check Thintix Chart Spec"
print_errors
return false
end
# Otherwise, get on with it...
# Create Chart
@chart = @account.charts.create(
:label => filename,
:width => @loaded_file.css('svg').attr('width'),
:height => @loaded_file.css('svg').attr('height'),
:master => true
)
puts "Creating Chart #{@chart.name}"
# Sections
idx = 0
# Background
parse_section('svg > g#Background', idx)
parse_section('svg > g#Background-Above', idx+=1)
# Sections (seatables)
@loaded_file.css('svg > g#Sections > g').each do |section|
section_id = section.attr('id')
parse_section("svg > g#Sections > g##{section_id}", idx+=1 , true)
end
# Foreground
parse_section('svg > g#Foreground', idx+=1)
end
def check_for_css(css)
unless @loaded_file.css(css).size > 0
@validation_errors << "Input needs an #{css}"
end
end
def check_excludes_css(css)
unless @loaded_file.css(css).size == 0
@validation_errors << "Input should not have an #{css}"
end
end
def print_errors
pretty_print_array_of_strings(@validation_errors) unless error_free?
end
def error_free?
@validation_errors.size == 0
end
def pretty_print_array_of_strings(array_of_strings)
unless error_free?
array_of_strings.each { |msg| puts msg }
else
puts "No messages"
end
end
def valid?
@validation_errors = []
# Has Background, Sections, Foreground groups as children of root
check_for_css('svg > g#Background')
check_for_css('svg > g#Sections')
check_for_css('svg > g#Foreground')
# Sections has multiple Section svg > g#Sections > g
check_for_css('svg > g#Sections > g')
print_errors
return error_free?
end
end
end |
module RSpec
module Mocks
RSpec.describe MessageExpectation, "has a nice string representation" do
let(:test_double) { double }
example "for a raw message expectation on a test double" do
expect(allow(test_double).to receive(:foo)).to have_string_representation(
"#<RSpec::Mocks::MessageExpectation #<Double (anonymous)>.foo(any arguments)>"
)
end
example "for a raw message expectation on a partial double" do
expect(allow("partial double".dup).to receive(:foo)).to have_string_representation(
'#<RSpec::Mocks::MessageExpectation "partial double".foo(any arguments)>'
)
end
example "for a message expectation constrained by `with`" do
expect(allow(test_double).to receive(:foo).with(1, a_kind_of(String), any_args)).to have_string_representation(
"#<RSpec::Mocks::MessageExpectation #<Double (anonymous)>.foo(1, a kind of String, *(any args))>"
)
end
RSpec::Matchers.define :have_string_representation do |expected_representation|
match do |object|
values_match?(expected_representation, object.to_s) && object.to_s == object.inspect
end
failure_message do |object|
"expected string representation: #{expected_representation}\n" \
" but got string representation: #{object.to_s}"
end
end
end
end
end
|
require 'rails_helper'
RSpec.describe Api::V1::ItemsController, type: :controller do
fixtures :items
describe "#index" do
it "serves all items' json" do
get :index, format: :json
expect(response.status).to eq(200)
expect(response.content_type).to eq "application/json"
body = JSON.parse(response.body)
first_item = body.first
second_item = body.last
expect(first_item["name"]).to eq items(:item_1).name
expect(first_item["description"]).to eq items(:item_1).description
expect(first_item["unit_price"]).to eq items(:item_1).unit_price.to_s
expect(first_item["merchant_id"]).to eq items(:item_1).merchant_id
expect(first_item["created_at"]).to eq "2012-03-27T14:53:59.000Z"
expect(first_item["updated_at"]).to eq "2012-03-27T14:53:59.000Z"
expect(second_item["name"]).to eq items(:item_2).name
expect(second_item["description"]).to eq items(:item_2).description
expect(second_item["unit_price"]).to eq items(:item_2).unit_price.to_s
expect(second_item["merchant_id"]).to eq items(:item_2).merchant_id
expect(second_item["created_at"]).to eq "2012-03-27T14:54:09.000Z"
expect(second_item["updated_at"]).to eq "2012-03-27T14:54:09.000Z"
end
end
describe "#show" do
it "serves a single items' json" do
get :show, format: :json, id: items(:item_1).id
expect(response.status).to eq(200)
expect(response.content_type).to eq "application/json"
body = JSON.parse(response.body)
expect(body["name"]).to eq items(:item_1).name
expect(body["description"]).to eq items(:item_1).description
expect(body["unit_price"]).to eq items(:item_1).unit_price.to_s
expect(body["merchant_id"]).to eq items(:item_1).merchant_id
expect(body["created_at"]).to eq "2012-03-27T14:53:59.000Z"
expect(body["updated_at"]).to eq "2012-03-27T14:53:59.000Z"
end
end
end
|
require 'rails_helper'
RSpec.describe Follow, type: :model do
let(:follow) { build :follow }
it '正常系' do
expect(follow.save).to be_truthy
end
it 'followeeの存在性チェック' do
follow.followee = nil
expect(follow.save).to be_falsy
end
it 'followerの存在性チェック' do
follow.follower = nil
expect(follow.save).to be_falsy
end
end
|
# frozen_string_literal: true
require 'test_helper'
class UserShowTest < ActionDispatch::IntegrationTest
# test "the truth" do
# assert true
# end
def setup
@inactive_user = users(:inactive)
@active_user = users(:archer)
end
test 'should display user when activated' do
get user_path(@active_user)
assert_response :success
assert_template 'users/show'
end
test 'should redirect when user not activated' do
get user_path(@inactive_user)
assert_response :redirect
assert assert_redirected_to root_url
end
end
|
class SubscriptionPlan < ApplicationRecord
has_many :subscription_plan_features
has_many :features, through: :subscription_plan_features
has_many :members
enum duration: [:daily, :weekly, :monthly, :quarterly, :annually]
enum organization_package: [:regular, :corporate, :insurance]
enum status: [:active, :deactivated]
validates_presence_of :plan_name, :cost, :duration, :description
validates :group_plan, :inclusion => {:in => [true, false]}
validates :recurring, :inclusion => {:in => [true, false]}
validates :no_of_group_members, presence: true, if: :group_plan?
scope :active_plans, -> {
where(status: 0)
}
def self.options_for_select
order('LOWER(plan_name)').map { |e| [e.plan_name, e.id]}
end
end
|
require 'compiler_helper'
module Alf
class Compiler
describe Default, "defaults" do
subject{
compiler.call(expr)
}
shared_examples_for 'the expected Defaults' do
it_should_behave_like "a traceable compiled"
it 'has a Defaults cog' do
expect(subject).to be_kind_of(Engine::Defaults)
end
it 'has the correct defaults' do
expect(subject.defaults.to_hash).to eq(b: 1)
end
end
context "when non strict" do
let(:expr){
defaults(an_operand(leaf), b: 1)
}
it_should_behave_like "the expected Defaults"
it 'has the correct sub-cog' do
expect(subject.operand).to be(leaf)
end
end
context "when strict" do
let(:expr){
defaults(an_operand(leaf), {b: 1}, strict: true)
}
it_should_behave_like "the expected Defaults"
it 'has a Clip sub-sub cog' do
expect(subject.operand).to be_kind_of(Engine::Clip)
expect(subject.operand.attributes).to eq(AttrList[:b])
end
end
end
end
end
|
class TasksController < ApplicationController
def create
@list = List.find(params[:list_id])
@task = @list.tasks.new(task_params)
respond_to do |format|
if @task.save
format.html { redirect_to @list, notice: 'Task was added' }
format.json { render :show, status: :created, location: @list }
format.js
else
format.html { redirect_to @list, alert: 'Please try again' }
format.json { render json: @task.errors, status: :unprocessable_entity }
end
end
end
def destroy
@task = Task.find(params[:id])
list = @task.list
@task.destroy
redirect_to list
end
def complete
@task = Task.find(params[:id])
list = @task.list
if @task[:completed] == false
@task.update_attribute(:completed, true)
redirect_to list, notice: "Task Completed"
else
@task.update_attribute(:completed, false)
redirect_to list
end
end
private
def task_params
params.require(:task).permit(:body)
end
end
|
require 'rails-pipeline/redis_forwarder'
require 'rails-pipeline/ironmq_publisher'
# Mix-in the IronMQ publisher into a RedisForwarder to create a
# class that will forward redis messages onto IronMQ
module RailsPipeline
class RedisIronmqForwarder < RedisForwarder
include IronmqPublisher
end
end
|
class ContactMailer < ApplicationMailer
default from: 'teplicy@medalak.ru'
def call_back_mail(contact)
@contact = contact
mail(to: 'teplicy@medalak.ru', subject: 'Обратный звонок')
end
end
|
#! /usr/bin/env ruby -S rspec
require 'spec_helper'
describe "the to_python_type function" do
let(:scope) { PuppetlabsSpec::PuppetInternals.scope }
it "should exist" do
Puppet::Parser::Functions.function("to_python_type").should == "function_to_python_type"
end
it "should raise a ParseError if there is less than 1 arguments" do
lambda { scope.function_to_python_type([]) }.should( raise_error(Puppet::ParseError))
end
it "should raise a ParseError if there are more than 1 arguments" do
lambda { scope.function_to_python_type([nil,nil]) }.should ( raise_error(Puppet::ParseError))
end
it "should convert a ruby bool into a string to a python bool" do
result = scope.function_to_python_type([true])
result.should(eq("True"))
end
it "should do nothing with a normal string" do
result = scope.function_to_python_type(["howdy"])
result.should(eq("howdy"))
end
it "should do nothing with a number" do
result = scope.function_to_python_type(["1238"])
result.should(eq("1238"))
end
it "should convert a ruby hash to a python hash" do
result = scope.function_to_python_type([{"key"=>"value"}])
result.should(eq("{'key':'value'}"))
end
end
|
require 'international_trade/currency_converter'
require 'international_trade/rate_hash'
require 'international_trade/transaction_iterator'
require 'international_trade/sales_totaler'
class InternationalTrade
attr_accessor :converter, :transactions
def initialize(arguments)
@converter = CurrencyConverter.new(arguments[:rates])
@transactions = TransactionIterator.new(arguments[:transactions])
@sales_totaler = SalesTotaler.new transactions: @transactions, converter: @converter
end
def compute_grand_total(sku, currency)
total = @sales_totaler.compute_grand_total sku.upcase, currency
total.to_s('F')
end
end |
class Bid < ActiveRecord::Base
belongs_to :user
belongs_to :product,counter_cache: true
belongs_to :bidder, :class_name => "User"
# before_save :convert_bid_to_cents
validate :higher_than_current?
validate :higher_than_minimum_bid?
validates :amount, :numericality => true
# def convert_bid_to_cents
# self.amount = (self.amount*100).to_i
# end
#
# def amount_in_dollars
# self.amount/100.0
# end
#
# def amount_in_cents
# self.amount*100
# end
def higher_than_minimum_bid?
if self.amount <= product.minimum_bid
errors.add(:amount,"too low cant be lower than minimum bid")
end
end
def higher_than_current?
if !Bid.where("amount > ? AND product_id = ?", amount, self.product.id).empty?
errors.add(:amount, "is too low! It can't be lower than the current bid, sorry.")
end
end
end
|
require 'rails_helper'
RSpec.describe User, type: :model do
it 'should start with 1000 points' do
new_user = FactoryGirl.create(:user)
expect(new_user.current_points).to eq(1000)
end
end
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
require 'yaml'
# Vagrantfile API/syntax version. Don't touch unless you know what you're doing!
VAGRANTFILE_API_VERSION = "2"
def symbolize_keys(hash)
hash.inject({}){|result, (key, value)|
new_key = case key
when String then key.to_sym
else key
end
new_value = case value
when Hash then symbolize_keys(value)
else value
end
result[new_key] = new_value
result
}
end
settings = YAML::load_file "settings.yml"
settings = symbolize_keys(settings)
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
config.vm.box = settings[:box_name]
config.vm.box_url = settings[:box_url]
if settings[:forwards]
settings[:forwards].each do |fname, forward|
config.vm.network :forwarded_port, guest: forward[:from], host: forward[:to]
end
end
config.vm.provider :vmware_fusion do |v|
v.vmx["memsize"] = settings[:ram]
v.vmx["numvcpus"] = settings[:proc]
end
config.vm.provider "virtualbox" do |v|
v.customize [ "modifyvm", :id, "--cpus", settings[:proc] ]
v.customize [ "modifyvm", :id, "--memory", settings[:ram] ]
end
config.vm.network :private_network, ip: settings[:ip]
config.vm.synced_folder "conf/", "/srv"
if settings[:synced_folders]
settings[:synced_folders].each do |sf_name, sf|
if settings[:vm_provider] == 'vmw'
config.vm.synced_folder sf[:host_path], sf[:guest_path_nfs], :nfs => true, :mount_options => ['nolock,vers=3,udp']
config.bindfs.bind_folder sf[:guest_path_nfs], sf[:guest_path],
:o => "nonempty"
else
config.vm.synced_folder sf[:host_path], sf[:guest_path], :nfs => true
end
end
end
config.vm.provision :salt do |salt|
salt.install_args = "v0.16.0"
salt.install_type = "git"
salt.minion_config = "conf/minion"
salt.run_highstate = true
salt.verbose = true
end
end
|
class CreateRLinks < ActiveRecord::Migration
def change
create_table :r_links do |t|
t.string :link
t.string :properties
t.timestamps
end
end
end
|
require 'minitest/autorun'
require_relative 'miner'
class Miner_test < Minitest::Test
# UNIT TESTS FOR METHOD increase_rubies(x,y)
# Equivalence classes:
# x and y = 0....infinity -> fake_rubies+=x and rubies+=y
# Tests if ruby counts are increased when both are incremented by the same value
def test_regular_increase
m = Miner.new(1)
fr = m.fake_rubies
r = m.rubies
m.increase_rubies(1,1)
assert_equal(fr+1,m.fake_rubies)
assert_equal(r+1,m.rubies)
end
# Tests if ruby counts are not increased when zero is passed
def test_no_increase
m = Miner.new(1)
fr = m.fake_rubies
r = m.rubies
m.increase_rubies(0,0)
assert_equal(fr,m.fake_rubies)
assert_equal(r,m.rubies)
end
# Tests if ruby counts are increased correctly when
# fake rubies and real rubies are incremented different amounts
def test_different_increase
m = Miner.new(1)
fr = m.fake_rubies
r = m.rubies
m.increase_rubies(1,2)
assert_equal(fr+2,m.fake_rubies)
assert_equal(r+1,m.rubies)
end
# UNIT TESTS FOR METHOD change_city(x)
# Equivalence classes:
# x = 0...infinity -> current_city = x
# Tests if successfully changes city of miner to 1
def test_normal_change
m = Miner.new(0)
m.change_city(1)
assert_equal(1,m.current_city)
end
# Tests if city of miner can be changed twice successfully
def test_change_twice
m = Miner.new(0)
m.change_city(1)
m.change_city(2)
assert_equal(2,m.current_city)
end
end
|
require 'socket'
require 'netlink/constants'
require 'netlink/message'
require 'netlink/message_decoder'
require 'netlink/types'
module Netlink
class Socket < ::Socket
SENDTO_SOCKADDR = Netlink::Sockaddr.new.to_binary_s.freeze
attr_reader :netlink_family
def initialize(netlink_family)
super(Netlink::PF_NETLINK, Socket::SOCK_RAW, netlink_family)
@netlink_family = netlink_family
@decoder = Netlink::MessageDecoder.for_family(netlink_family)
end
def bind(sockaddr=nil)
case sockaddr
when nil
sockaddr = Netlink::Sockaddr.new.to_binary_s
when Netlink::Sockaddr
sockaddr = sockaddr.to_binary_s
end
super(sockaddr)
end
# Subscribes to supplied multicast groups
def subscribe(*groups)
for group in groups
setsockopt(Netlink::SOL_NETLINK, Netlink::NETLINK_ADD_MEMBERSHIP, group)
end
end
# Unsubscribes from supplied multicast groups
def unsubscribe(*groups)
for group in groups
setsockopt(Netlink::SOL_NETLINK, Netlink::NETLINK_DROP_MEMBERSHIP, group)
end
end
def send_message(msg)
sendmsg(msg.encode, 0, SENDTO_SOCKADDR)
end
def receive_message
loop do
data = recvmsg
msg = @decoder.decode(data[0])
unless msg.nl_header.type == Netlink::NLMSG_NOOP
return msg
end
end
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.