text stringlengths 10 2.61M |
|---|
class Shuttle::User
# API for accessing information on the current and other users.
attr_accessor :id, :name, :short_name, :sortable_name, :primary_email, :login_id
attr_accessor :sis_user_id, :sis_login_id
attr_accessor :avatar_url, :calendar, :time_zone, :locale
attr_accessor :saved
def initialize(*args)
if args.length == 1 && args.first.kind_of?(Hash)
args.first.each { |k,v| send("#{k}=",v) }
end
@saved = false
end
def saved?
return @saved
end
# TODO This should be moved to the Account api
# @!method list_users(account_id)
# Retrieve the list of users associated with this account.
# @param [Integer] account_id the id of the account to query
def list_users
# GET /api/v1/accounts/:account_id/users
end
# @!method create(account_id, canvas_user)
# Create and return a new user and pseudonym for an account.
# @param [Integer] account_id the id of the account where we want to create the user
# @param [Canvas::User] canvas_user a new, unsaved Canvas::User object
def self.create(account_id, canvas_user)
# TODO Validate our canvas user object for fields below
request = Shuttle::API::Request.new
request.method = 'POST'
request.endpoint = "/api/v1/accounts/#{account_id}/users"
request.body = {
"user" => {
# Optional | The full name of the user. This name will be used by teacher for grading.
"name" => "#{canvas_user.name}",
# Optional | User’s name as it will be displayed in discussions, messages, and comments.
"short_name" => "#{canvas_user.short_name}",
# Optional | User’s name as used to sort alphabetically in lists.
"sortable_name" => "#{canvas_user.sortable_name}",
# Optional | The time zone for the user. Allowed time zones are listed in The Ruby on Rails documentation.
"time_zone" => "#{canvas_user.time_zone || 'Eastern Time (US & Canada)'}",
# Optional | The user’s preferred language as a two-letter ISO 639-1 code. Current supported languages are English (“en”) and Spanish (“es”).
"locale" => "#{canvas_user.locale || 'en'}"
},
"pseudonym" => {
# User’s login ID.
"unique_id" => "#{canvas_user.login_id || canvas_user.primary_email}",
# Optional | Integer | SIS ID for the user’s account. To set this parameter, the caller must be able to manage SIS permissions.
"sis_user_id" => "#{canvas_user.sis_user_id}",
# Optional, 0|1 | Integer | Send user notification of account creation if set to 1.
"send_confirmation" => 0
}
}.to_json
response = request.fire!
return response
end
# @!method edit(canvas_user)
# Modify an existing user. To modify a user’s login, see the documentation for logins.
# @param [Canvas::User] canvas_user the canvas user object to edit
def self.edit(canvas_user)
request = Shuttle::API::Request.new
request.method = 'PUT'
request.endpoint = "/api/v1/users/#{canvas_user.id}"
request.body = {
"user" => {
# Optional | The full name of the user. This name will be used by teacher for grading.
"name" => "#{canvas_user.name}",
# Optional | User’s name as it will be displayed in discussions, messages, and comments.
"short_name" => "#{canvas_user.short_name}",
# Optional | User’s name as used to sort alphabetically in lists.
"sortable_name" => "#{canvas_user.sortable_name}",
# Optional | The time zone for the user. Allowed time zones are listed in The Ruby on Rails documentation.
"time_zone" => "#{canvas_user.time_zone || 'Eastern Time (US & Canada)'}",
# Optional | The user’s preferred language as a two-letter ISO 639-1 code. Current supported languages are English (“en”) and Spanish (“es”).
"locale" => "#{canvas_user.locale || 'en'}"
#TODO user[avatar][token]
#TODO user[avatar][url]
},
}.to_json
response = request.fire!
return response
end
# @!method delete(account_id, user_id)
# Delete a user record from Canvas.
# @param [Integer] account_id the id of the account where we want to delete the user
# @param [Integer] user_id the id of the user to delete
def self.delete
request = Shuttle::API::Request.new
request.method = 'DELETE'
request.endpoint = "/api/v1/accounts/#{account_id}/users/#{id}"
end
# @!method save
# Save and return a new user and pseudonym for an account.
def save
response = Shuttle::User.create(2, self)
if response[0] == '200'
return true
else
return false
end
end
# @!method update
# Modify an existing user. To modify a user’s login, see the documentation for logins.
def update
response = Shuttle::User.edit(self)
if response[0] == '200'
return true
else
return false
end
end
# @!method destroy
# Delete a user record from Canvas.
def destroy
# call delete for current object
end
# @!method all
# Returns all users
def self.all
end
# @!method get_by_canvas_id(user_id)
# Returns user profile data, including user id, name, and profile pic.
# @param [Integer] user_id the id of the user to find
def self.get_by_canvas_id(user_id)
request = Shuttle::API::Request.new
request.method = 'GET'
request.endpoint = "/api/v1/users/#{user_id}/profile"
response = request.fire!
if response[0] == '200'
return Shuttle::User.new(response[1])
end
end
# @!method get_by_sis_id(sis_id)
# Returns user profile data, including user id, name, and profile pic.
# @param [Integer] sis_id the id of the user to find
def self.get_by_sis_id(sis_id)
request = Shuttle::API::Request.new
request.method = 'GET'
request.endpoint = "/api/v1/users/sis_user_id:#{sis_id}/profile"
response = request.fire!
if response[0] == '200'
return Shuttle::User.new(response[1])
end
end
# @!method get_or_create_by_canvas_id(user_id)
# Gets the user with the corresponding Canvas user id, or initializes a new, unsaved user if no matches are found.
# Either way, returns a Canvas::User object.
# @param [Integer] user_id the id of the user to find
def self.get_or_create_by_canvas_id(user_id)
end
# @!method get_or_create_by_sis_id(sis_id)
# Gets the user with the corresponding SIS user id, or initializes a new, unsaved user if no matches are found.
# Either way, returns a Canvas::User object.
# @param [Integer] sis_id the id of the user to find
def self.get_or_create_by_sis_id(sis_id)
user_query = Shuttle::User.get_by_sis_id(sis_id)
if user_query.is_a? Shuttle::User
user = user_query
user.saved = true
return user
else
user = Shuttle::User.new
user.sis_user_id = sis_id
user.saved = false
return user
end
end
# @!method list_activity_stream
# Returns the current user’s global activity stream, paginated.
def list_activity_stream
# GET /api/v1/users/self/activity_stream
# GET /api/v1/users/activity_stream
end
# @!method list_todos
# Returns the current user’s list of todo items, as seen on the user dashboard.
def list_todos
# GET /api/v1/users/self/todo
end
# @!method upload
# Upload a file to the user’s personal files section.
def upload
# POST /api/v1/users/:user_id/files
end
# @!method follow
# Follow this user.
# If the current user is already following the target user, nothing happens.
# The target user must have a public profile in order to follow it.
def follow
# PUT /api/v1/users/:user_id/followers/self
end
# @!method unfollow
# Stop following this user.
# If the current user is not already following the target user, nothing happens.
def unfollow
# DELETE /api/v1/users/:user_id/followers/self
end
# @!method list_avatar_options
# Retrieve the possible user avatar options that can be set with the user update endpoint.
def list_avatar_options
# GET /api/v1/users/:user_id/avatars
end
# @!method list_user_page_views
# Return the user’s page view history in json format, similar to the available CSV download.
def list_user_page_views
# GET /api/v1/users/:user_id/page_views
end
end
|
class User < ApplicationRecord
has_many :reviews
has_many :reservations
has_many :restaurants, through: :reservations
end
|
class CreateExactTargetMessages < ActiveRecord::Migration
def self.up
create_table :exact_target_messages do |t|
t.column :type, :string
t.column :request, :string, :limit => ExactTargetMessage::REQUEST_MAX_LENGTH,
:null => false
t.column :response, :string, :limit => ExactTargetMessage::RESPONSE_MAX_LENGTH
t.column :target_type, :string, :limit => ExactTargetMessage::TARGET_TYPE_MAX_LENGTH
t.column :target_id, :bigint
t.column :status, :enum, ExactTargetMessage::STATUS_DB_OPTS
t.column :tries, :int, :default => 0
t.column :next_try_at, :datetime
t.column :max_tries, :int, :default => 3
t.column :system_name, :enum, ExactTargetMessage::SYSTEM_NAME_DB_OPTS
t.column :action, :string, :limit => ExactTargetMessage::ACTION_MAX_LENGTH,
:null => false
t.column :job_id, :string, :limit => ExactTargetMessage::JOB_ID_MAX_LENGTH
t.column :created_at, :datetime
t.column :updated_at, :datetime
t.column :prereq_message_id, :bigint
t.column :error_number, :string, :limit => 24
end
end
def self.down
drop_table :exact_target_messages
end
end
|
class MedicalCat < ApplicationRecord
has_paper_trail
belongs_to :professional_detail
has_many :hospital_admission_histories, dependent: :destroy
accepts_nested_attributes_for :hospital_admission_histories
rails_admin do
create do
field :professional_detail_id, :enum do
enum do
ProfessionalDetail.all.collect {|p| [p.user.army_no, p.id]}
end
end
field :date
field :nature_of_emergency
field :permanent
field :period_year
field :period_month
field :hospitalized
field :shape , :enum do
enum do
MasterShape.all.collect{ |p| [p.title, p.title]}
end
end
end
edit do
field :professional_detail_id, :enum do
enum do
ProfessionalDetail.all.collect {|p| [p.user.army_no, p.id]}
end
end
field :date
field :nature_of_emergency
field :permanent
field :period_year
field :period_month
field :hospitalized
field :shape , :enum do
enum do
MasterShape.all.collect{ |p| [p.title, p.title]}
end
end
end
end
end
|
#!/usr/bin/env ruby
require "git"
log = Dir.home + "/.push_dotfiles.log"
dotfiles_dir = Dir.home + "/dotfiles/"
File.open(log, "a") do |file|
file.puts "\n---\n"
file.puts "Attempted push at " + Time.now.to_s
begin
dotfiles = Git.init(dotfiles_dir)
dotfiles.add(:all=>true)
dotfiles.commit_all("Automated push at " + Time.now.to_s)
dotfiles.push
file.puts "Push successful"
rescue Git::GitExecuteError
file.puts "Nothing to push"
end
file.puts "End of push"
end
|
class AddProductTags < ActiveRecord::Migration[5.2]
def change
create_table :product_tags do |t|
t.string :name
t.integer :product_tag_group_id
end
create_table :product_tag_groups do |t|
t.string :name
end
create_table :product_tag_aliases do |t|
t.integer :product_tag_id
t.string :alias
end
end
end |
class Page < ActiveRecord::Base
belongs_to :project
has_attached_file :picture, styles: { large: "1000x565>", medium: "300x300>", thumb: "100x100>" },
:path => ":rails_root/private/images/:id/:style.:extension",
:url => "#{ActionController::Base.relative_url_root}/image_server/:id/:style/:extension"
validates_attachment :picture, content_type: { content_type: ["image/jpg", "image/jpeg", "image/png", "image/gif"] }
def self.list_pages(project_id)
Page.where(:project_id => project_id).order(:page_order)
end
def self.get_page_for_id(admin_user_id, page_id)
pages = Page.joins(:project => [:team => [:members]]).where('pages.id = ? and admin_users.id = ?', page_id, admin_user_id)
if pages.count > 0
return pages.first
else
return nil
end
end
def self.get_page(project_id, page_id)
pages = Page.where(:project_id => project_id, :id => page_id)
if pages.count > 0
return pages.first
else
return nil
end
end
def self.prepare_new_page(project_id)
p = self.new
o = Page.where(:project_id => project_id).maximum(:page_order)
p.page_order = o.present? ? o + 1 : 1
p.indent = 1
p.project_id = project_id
return p
end
def self.update_order_and_indent(hash_orders, hash_indents)
Page.all.each do |page|
order = hash_orders[page.id.to_s]
indent = hash_indents[page.id.to_s]
page.page_order = order.present? ? Integer(order) : nil
page.indent = indent.present? ? Integer(indent) : nil
page.save!
end
end
def self.has_next(project_id, order)
self.find_next_page(project_id, order).count == 0 ? false : true
end
def self.has_previous(project_id, order)
self.find_previous_page(project_id, order).length == 0 ? false : true
end
def self.find_next_page(project_id, order)
Page.where('project_id = ? and page_order > ?', project_id, order).order('page_order, created_at').limit(1)
end
def self.find_previous_page(project_id, order)
Page.where('project_id = ? and page_order < ?', project_id, order).order('page_order DESC, created_at').limit(1)
end
end
|
class CreatePieces < ActiveRecord::Migration
def change
create_table :pieces do |t|
t.belongs_to :model
t.belongs_to :size
t.float :price, precision: 8, scale: 2
t.timestamps null: false
end
end
end
|
class CreateImages < ActiveRecord::Migration
def change
create_table :images do |t|
t.string :path
t.integer :object_id
t.string :object_type, limit: 50
t.timestamps null: false
end
end
end
|
class <%= class_name %>Controller < PublicRescue::PublicErrorsController
# 404
def not_found
end
# 500
def internal_server_error
end
def conflict
render :action => :internal_server_error
end
def not_implemented
render :action => :internal_server_error
end
def method_not_allowed
render :action => :internal_server_error
end
# 422
def unprocessable_entity
end
end |
require "spec_helper"
describe Player do
let(:player) { Player.new }
it "initializes with 10 lives" do
expect(player.lives).to eq 10
end
it "allows you to set lives" do
player = Player.new(5)
expect(player.lives).to eq 5
end
describe "#new_guess" do
it "creates a Guess object and sends to Game" do
end
end
describe "#lose_life!" do
it "decrements lives" do
player.lose_life!
expect(player.lives).to eq 9
end
end
describe "#dead?" do
it "returns true when player has no lives" do
player = Player.new(0)
expect(player.dead?).to eq true
end
it "returns false if player has lives" do
expect(player.dead?).to eq false
end
end
end |
class OptionsMcq < ApplicationRecord
belongs_to :options
belongs_to :mcqs
end
|
class CardSetSerializer < ActiveModel::Serializer
# cache key: 'card_set'
attributes :id, :name, :release_date, :code
has_many :cards
end
|
require 'bundler/setup'
require 'sexpistol'
require 'pry'
require 'tilt'
require 'erb'
def rest(expression)
copy = expression.dup
copy.shift
copy
end
module Ugh
class BashLiteral
def initialize(expr)
@expr = expr
end
def to_bash
@expr.to_s
end
end
module Util
def self.parse_string(program)
Sexpistol.new.parse_string(program)
end
def self.dashes_to_underscore(sym)
sym.to_s.gsub('-', '_')
end
def self.quote_string(str)
"\"#{str}\""
end
def self.rest(arr)
dup = arr.dup
dup.shift
dup
end
def self.random_string
(0...20).map { (65 + rand(26)).chr }.join
end
def self.function_name
@counter ||= 0
@counter = @counter + 1
"function_#{@counter.to_s}"
end
end
module StdLib
def self.echo(expr)
"echo #{expr}"
end
def self.def(key, value)
"#{key}=#{value}"
end
def self.dollar(variable)
"$#{variable}".gsub(/"/, '')
end
def self.eval(expr)
"\`#{expr}\`"
end
def self.apply(function_name, expressions)
"#{function_name} #{expressions.join(' ')}"
end
def self.pipe(expressions)
expressions.join(' | ')
end
def self.defn(function_name, function_args, function_body)
template = Tilt::ERBTemplate.new('templates/defn.erb', trim: '-')
ctx = self
str = template.render(self, {
function_name: function_name,
function_args: function_args,
function_body: function_body
})
str
end
def self.local(key, value)
"local #{StdLib::def(key, value)}"
end
def self.make_conditional(operator)
Proc.new do |left, right|
"[ #{left} #{operator} #{right} ]"
end
end
def self.eq(left, right)
make_conditional("-eq").call(left, right)
end
def self.ne(left, right)
make_conditional("-ne").call(left, right)
end
def self.gt(left, right)
make_conditional("-gt").call(left, right)
end
def self.ge(left, right)
make_conditional("-ge").call(left, right)
end
def self.le(left, right)
make_conditional("-eq").call(left, right)
end
def self.if(condition, true_block, false_block)
template = Tilt::ERBTemplate.new('templates/if.erb', trim: '-')
ctx = self
str = template.render(self, {
condition: condition,
true_block: true_block,
false_block: false_block
})
str
end
def self.deflist(list_name, items)
"#{list_name}=(#{items})"
end
def self.get(list_name, index)
"${#{list_name}[#{index}]}"
end
def self.set(list_name, index, value)
"#{list_name}[#{index}]=#{value}"
end
def self.length(list_name)
"${##{list_name}[@]}"
end
def self.append(list_name, items)
"#{list_name}=(\"${#{list_name}[@]}\" #{items.join(' ')})"
end
def self.each(items, function_name, function_args, function_body)
function = StdLib::defn(function_name, function_args, function_body)
str = <<-END.gsub(/^ {6}/, '')
for i in #{items}; do
#{function_name} $i
done
END
[function, str.rstrip].join("\n")
end
def self.str(items)
items
end
def self._do(expressions)
template = Tilt::ERBTemplate.new('templates/do.erb', trim: '-')
ctx = self
str = template.render(self, {
expressions: expressions
})
end
end
class Interpreter
def transpile(program)
expressions = Util::parse_string(program)
result = []
result << "#!/bin/bash"
result << ""
expressions.each do |expression|
bash = expression_to_bash(expression)
result << bash
end
return result.join("\n")+"\n"
end
def expression_to_bash(expression)
return Util::quote_string(expression) if expression.is_a?(String)
return expression.to_bash if expression.is_a?(BashLiteral)
return expression.to_s if expression.is_a?(Symbol)
return expression if expression.is_a?(Integer)
case expression[0]
when :echo
expr = expression_to_bash(expression[1])
StdLib::echo(expr)
when :def
key = Util::dashes_to_underscore(expression[1])
value = expression_to_bash(expression[2])
StdLib::def(key, value)
when :dollar
variable = expression_to_bash(
BashLiteral.new(
Util::dashes_to_underscore(expression_to_bash(expression[1]))
)
)
StdLib::dollar(variable)
when :eval
expr = expression_to_bash(expression[1])
StdLib::eval(expr)
when :apply
function_name = Util::dashes_to_underscore(expression[1])
expression.shift
expression.shift
expressions = expression.map {|expr| expression_to_bash(expr)}
StdLib::apply(function_name, expressions)
when :pipe
expressions = Util::rest(expression).map do |expr|
expression_to_bash(expr)
end
StdLib::pipe(expressions)
when :defn
# arguments are *not* defined in function
if expression.length == 3
function_name = Util::dashes_to_underscore(expression[1])
function_args = []
function_body = expression_to_bash(expression[2])
StdLib::defn(function_name, function_args, function_body)
# arguments are defined in function
elsif expression.length == 4
function_name = Util::dashes_to_underscore(expression[1])
function_args = expression[2]
function_body = expression_to_bash(expression[3])
StdLib::defn(function_name, function_args, function_body)
end
when :do
expressions = rest(expression)
expressions.map! {|expr| expression_to_bash(expr)}
StdLib::_do(expressions)
when :local
key = Util::dashes_to_underscore(expression[1])
value = expression_to_bash(expression[2])
StdLib::local(key, value)
when :eq
left = Util::quote_string(expression_to_bash(expression[1]))
right = Util::quote_string(expression_to_bash(expression[2]))
StdLib::eq(left, right)
when :ne
left = Util::quote_string(expression_to_bash(expression[1]))
right = Util::quote_string(expression_to_bash(expression[2]))
StdLib::ne(left, right)
when :gt
left = Util::quote_string(expression_to_bash(expression[1]))
right = Util::quote_string(expression_to_bash(expression[2]))
StdLib::gt(left, right)
when :lt
left = Util::quote_string(expression_to_bash(expression[1]))
right = Util::quote_string(expression_to_bash(expression[2]))
StdLib::lt(left, right)
when :le
left = Util::quote_string(expression_to_bash(expression[1]))
right = Util::quote_string(expression_to_bash(expression[2]))
StdLib::le(left, right)
when :if
condition = expression_to_bash(expression[1])
true_block = expression_to_bash(expression[2])
false_block = nil
if expression[3]
false_block = expression_to_bash(expression[3])
end
StdLib::if(condition, true_block, false_block).rstrip
when :deflist
list_name = Util::dashes_to_underscore(expression[1])
expression.shift
expression.shift
items = expression_to_bash(expression)
StdLib::deflist(list_name, items)
when :get
list_name = Util::dashes_to_underscore(expression[1])
index = expression_to_bash(expression[2])
StdLib::get(list_name, index)
when :set
list_name = Util::dashes_to_underscore(expression[1])
index = expression_to_bash(expression[2])
value = expression_to_bash(expression[3])
StdLib::set(list_name, index, value)
when :inspect
list_name = Util::dashes_to_underscore(expression[1])
StdLib::get(list_name, "@")
when :length
list_name = Util::dashes_to_underscore(expression[1])
StdLib::length(list_name)
when :append
list_name = Util::dashes_to_underscore(expression[1])
expression.shift # remove :append
expression.shift # remove list name
items = expression.map {|expr| expression_to_bash(expr)}
StdLib::append(list_name, items)
when :lambda
function_name = Util::function_name
function_args = expression[1]
function_body = expression_to_bash(expression[2])
StdLib::defn(function_name, function_args, function_body).rstrip
when :each
items = expression_to_bash(expression[1])
function = expression[2]
function_name = Util::function_name
function_args = function[1]
function_body = expression_to_bash(function[2])
StdLib::each(items, function_name, function_args, function_body).rstrip
when :str
chunks = rest(expression)
chunks.map! {|expr| expression_to_bash(expr)}
chunks.join
else
expressions = expression.map {|expr| expression_to_bash(expr)}
expressions.join(' ')
end
end
end
end
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe ScoresController, type: :controller do
before do
@user = FactoryBot.create(:user)
@score = FactoryBot.create(:score, user: @user)
session[:user_id] = @user.id
end
describe 'GET #index' do
it 'returns http success' do
get :index
expect(response).to have_http_status(:success)
end
end
describe 'GET #show' do
it 'returns http success' do
get :show, params: { id: @score.id }
expect(response).to have_http_status(:success)
end
end
describe 'GET #new' do
it 'returns http success' do
get :new
expect(response).to have_http_status(:success)
end
end
describe 'GET #edit' do
it 'returns http success' do
get :edit, params: { id: @score.id }
expect(response).to have_http_status(:success)
end
end
describe 'POST #edit' do
it 'returns http redirect' do
post :update, params: { id: @score.id,
score: {
wakeup_on: '2017-08-20',
score: 3,
reason: 'foo',
cause: 'bar'
} }
expect(response).to have_http_status(302)
end
end
describe 'DELETE #destroy' do
context 'visible score' do
it 'returns http redirect' do
delete :destroy, params: { id: @score.id }
expect(response).to have_http_status(302)
end
end
end
end
|
class CourtsController < ApplicationController
def show
@court = Court.find(show_params[:id])
render layout: false
end
private
def show_params
params.permit(:id)
end
end |
class FplService
class << self
def base_url
"https://fantasy.premierleague.com"
end
def update_gameweek_score(player_ids, gw)
Parallel.each(player_ids, in_threads: 8) do |player_id|
score = gameweek_score(player_id, gw)
FplPlayer.find_by(fpl_id: player_id).update_attributes("gw_#{gw}": score)
end
end
# Queries: https://fantasy.premierleague.com/drf/entry/#{player_id}
# Response from api:
# {
# "entry": {
# "id": 2857018,
# "player_first_name": "Pratik",
# "player_last_name": "Bothra",
# "name": "Class on Grass",
# "started_event": 1,
# "player": 3692207
# },
# "leagues": {
# }
# }
# Input: PlayerId. Example: 2857018
# Response:
# {"id"=>2857018,
# "player_first_name"=>"Pratik",
# "player_last_name"=>"Bothra",
# "name"=>"Class on Grass"
# }
def fetch_player_info(player_id)
player_info_api = base_url + "/drf/entry/#{player_id}"
response = HTTParty.get(player_info_api)
entry = JSON.parse(response.body)["entry"]
entry.slice("id", "player_first_name", "player_last_name", "name")
end
# TODO: Request/Response
def gameweek_score(player_id, gameweek)
player_gw_api = base_url + "/drf/entry/#{player_id}/event/#{gameweek}/picks"
response = HTTParty.get(player_gw_api)
JSON.parse(response.body)["entry_history"]["points"]
end
end
end
|
class MapQuest
class Request < RestClient::Resource
RestClient.log =
Object.new.tap do |proxy|
def proxy.<<(message)
Rails.logger.info message
end
end
# The base url of the mapquest api
API_ROOT = 'http://%smapquestapi.com/%s/v%s/%s'
def initialize(method)
isOMQ = method[:omq] ? "open." : ""
super API_ROOT % [isOMQ, method[:location], method[:version], method[:call]]
end
def query(params)
get :params => params
end
end
end
|
class Donation < ApplicationRecord
belongs_to :donor, class_name: "User", foreign_key: "donor_id"
belongs_to :dancer, class_name: "User", foreign_key: "dancer_id"
validates :amount, presence: true, numericality: { greater_than: 0 }
validates :donor_id, :dancer_id, presence: true
def date
created_at.to_date.to_s
end
end
|
class EventsController < ApplicationController
def index
@title = 'I nostri eventi'
@breadcrumb = '<span class="current_crumb">Eventi</span>'
@events = Event.all
@first = Event.first()
end
def show
@event = Event.find(params[:id])
@title = @event.name
@breadcrumb = '<a href=' + events_path + '>Eventi</a><span class="current_crumb">' + @event.name + '</span>'
@next = Event.first(:conditions => ['id > ?', params[:id]])
@previous = Event.last(:conditions => ['id < ?', params[:id]])
@partners = @event.partners
end
def new
@title = 'Nuovo Evento'
@event = Event.new
end
def edit
@title = 'Modifica Evento'
@event = Event.find(params[:id])
end
def create
#Carica l'immagine selezionata sul server
if(params[:event][:image_url])
image_io = params[:event][:image_url]
File.open(Rails.root.join('app','assets','images','events', image_io.original_filename), 'wb') do |file|
file.write(image_io.read)
end
params[:event][:image_url] = image_io.original_filename
#Se non è stata selezionata un'immagine viene caricata un'immagine di default
else
params[:event][:image_url] = 'missing.png'
end
@event = Event.new(params[:event])
respond_to do |format|
if @event.save
format.html { redirect_to admin_events_path, notice: 'Evento inserito con successo.' }
format.json { render json: @event, status: :created, location: @event }
else
format.html { render action: "new" }
format.json { render json: @event.errors, status: :unprocessable_entity }
end
end
end
def update
@event = Event.find(params[:id])
#Se è stata selezionata una nuova immagine la carica sul server
if(params[:event][:image_url])
image_io = params[:event][:image_url]
File.open(Rails.root.join('app','assets','images','events', image_io.original_filename), 'wb') do |file|
file.write(image_io.read)
end
params[:event][:image_url] = image_io.original_filename
end
respond_to do |format|
if @event.update_attributes(params[:event])
format.html { redirect_to admin_events_path, notice: 'Evento aggiornato con successo.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @event.errors, status: :unprocessable_entity }
end
end
end
def destroy
@event = Event.find(params[:id])
@event.destroy
respond_to do |format|
format.html { redirect_to admin_events_path }
format.json { head :no_content }
end
end
end
|
class ApplicationHelper::Button::GenericObjectDefinitionButtonButtonGroupNew < ApplicationHelper::Button::Basic
def visible?
@actions_node || @record.kind_of?(GenericObjectDefinition)
end
end
|
class Array
def into(n = 3)
groups = []
n.times { groups << [] }
elements = self
counter = 0
while !elements.empty? do
groups[counter % n] << elements.shift
counter += 1
end
groups
end
end
|
class Main
helpers do
def cached_file_id( uploader )
uploader.file.path.gsub(uploader.cache_dir + '/', '')
end
def generate_unique_filename( filename )
[ UUID.sha1, File.extname(filename).downcase ].join
end
def assert_valid_cache_id!( cache_id )
unless cache_id.match(Format::CARRIER_WAVE_CACHE_ID)
raise "Not a valid cache id #{cache_id}"
end
end
def assert_valid_filename!( filename )
unless filename.match(Format::CARRIER_WAVE_FILENAME)
raise "Not a valid filename #{filename}"
end
end
end
get '/tmp/uploads/:cache_id/:filename' do |cache_id, filename|
assert_valid_cache_id!( cache_id )
assert_valid_filename!( filename )
send_file root_path("tmp", "uploads", cache_id, filename),
:disposition => 'inline'
end
post '/uploader' do
content_type 'text/plain'
logger.debug "-----> Receiving upload in /uploader"
uploader = PhotoUploader.new
begin
if params[:item][:photo_url].present?
logger.debug "-----> Photo URL given (#{params[:item][:photo_url]})"
uploader.cache!( StreamedFile.new(params[:item][:photo_url]) )
else
logger.debug "-----> Photo file given (#{params[:item][:photo][:filename]})"
params[:item][:photo][:filename] =
generate_unique_filename( params[:item][:photo][:filename] )
uploader.cache!(params[:item][:photo])
end
rescue CarrierWave::IntegrityError, CarrierWave::ProcessingError
logger.debug " ! Got an error while processing"
{ errors: 'processing error' }.to_json
else
data = {
thumb: uploader.thumb.url,
original: uploader.large.url,
filename: cached_file_id(uploader),
title: sprintf('%.15s...', uploader.filename),
}
logger.debug "-----> Returning response: #{data.inspect}"
data.to_json
end
end
end
|
#encoding: utf-8
class Cache
include Mongoid::Document
include Mongoid::Timestamps
store_in collection: "cache", database: "dishgo"
field :website, type: String
field :menu, type: String
field :network_menu, type: String
field :api_menu, type: Hash, default: {}
belongs_to :restaurant, index: true
def self.rebuild_all
Cache.all.each do |cache|
restaurant = cache.restaurant
if !restaurant
cache.destroy
else
restaurant.cache_job
end
end
end
end |
require 'test_helper'
class DoorsControllerTest < ActionDispatch::IntegrationTest
include Devise::Test::IntegrationHelpers
def setup
user = FactoryBot.create(:user)
sign_in user
@door = FactoryBot.create(:door, organization: user.organization)
end
test "#index" do
get doors_path
res = JSON.parse(response.body)
assert_equal(1, res.length)
assert_equal(@door.id, res[0]["id"])
end
test "#show" do
get door_path(@door.id)
res = JSON.parse(response.body)
assert_equal(@door.id, res["id"])
end
end
|
class CreateDb < ActiveRecord::Migration
@@test_fulltext_migrations = false
def self.up
## User
create_table :users do |t|
t.column :email, :string, :null => false, :limit => User::EMAIL_MAX_LENGTH
t.column :screen_name, :string, :limit => User::SCREEN_NAME_MAX_LENGTH
t.column :auth_email, :string, :null => false, :limit => User::EMAIL_MAX_LENGTH
t.column :auth_screen_name, :string, :limit => User::SCREEN_NAME_MAX_LENGTH
t.column :display_id, :string, :null => false, :limit => User::DISPLAY_ID_MAX_LENGTH
t.column :crypted_password, :string, :null => false,
:limit => User::CRYPTED_PASSWORD_MAX_LENGTH
t.column :salt, :string, :null => false, :limit => User::SALT_MAX_LENGTH
t.column :remember_me, :boolean, :null => false, :default => false
t.column :email_conf_token, :string, :null => true,
:limit => User::EMAIL_CONFIRMATION_TOKEN_MAX_LENGTH,
:default => 'MANUALLY INSERTED'
t.column :account_status, :enum, :limit => User::ACCOUNT_STATUS_ENUM_VALUES,
:default => :active
t.column :author_status, :enum, :null => false,
:limit => User::AUTHOR_STATUS_ENUM_VALUES, :default => :contributor
t.column :admin, :boolean, :null => false, :default => false
t.column :created_at, :datetime
t.column :updated_at, :datetime
t.column :gender, :char, :null => false, :limit => User::GENDER_MAX_LENGTH
t.column :date_of_birth, :date, :null => true
t.column :zip_code, :string, :null => true, :limit => User::ZIP_CODE_MAX_LENGTH
t.column :us_user, :boolean, :null => false, :default => true
t.column :country, :string, :null => true, :limit => User::COUNTRY_MAX_LENGTH
t.column :city, :string, :null => true, :limit => User::CITY_MAX_LENGTH
t.column :state, :string, :null => true, :limit => User::STATE_MAX_LENGTH
t.column :postal_code, :string, :null => true,
:limit => User::POSTAL_CODE_MAX_LENGTH
t.column :accept_terms, :boolean, :null => false, :default => false
t.column :first_name, :string, :null => true, :limit => User::FIRST_NAME_MAX_LENGTH
t.column :last_name, :string, :null => true, :limit => User::FIRST_NAME_MAX_LENGTH
end
add_index :users, [:auth_email], :unique
add_index :users, [:auth_screen_name]
add_index :users, [:display_id], :unique
## AnonymousToken
create_table :anonymous_tokens do |t|
t.column :value, :string, :null => false, :limit => 36
t.column :created_at, :datetime
t.column :updated_at, :datetime
t.column :session_id, :string, :null => false, :limit => 32
t.column :user_id, :bigint, :null => true
end
## Source
create_table :sources do |t|
t.column :name, :string, :null => false, :limit => Source::MAX_NAME_LIMIT
end
Source.create :name => Source::NAME_VIEWPOINTS
Source.create :name => Source::NAME_USER
## Category
create_table :categories, :fulltext => true do |t|
t.column :name, :string, :null => false, :limit => Category::NAME_MAX_LENGTH
t.column :active, :boolean, :null => false, :default => false
t.column :source_id, :integer, :null => false
end
add_index :categories, :name
# insert the root node by hand since validation would bong the name
execute "INSERT INTO categories (name, active, source_id) " \
"VALUES ('#{Category::ROOT_NAME}', 1, #{Source["viewpoints"].id})"
## CategoryRelationship
create_table :category_relationships do |t|
t.column :broader_than_category_id, :integer, :null => false
t.column :narrower_than_category_id, :integer, :null => false
t.column :broader_than_is_primary, :boolean, :null => false, :default => true
end
add_index :category_relationships, :broader_than_category_id
add_index :category_relationships, :narrower_than_category_id
## CategoryTag
create_table :category_tags do |t|
t.column :category_id, :integer, :null => false
t.column :kind, :enum, :limit => AbstractTag::KIND_ENUM_VALUES, :default => :pro, :null => false
t.column :value, :string, :limit => AbstractTag::VALUE_MAX_LENGTH, :null => false
t.column :sort_order, :integer, :null => false
end
## CategoryAttribute
create_table :category_attributes do |t|
t.column :category_id, :bigint, :null => false
t.column :name, :string, :null => false
t.column :sort_order, :integer, :null => false
end
## Product
#create_table :products do |t|
create_table :products do |t|
t.column :category_id, :bigint, :null => false
t.column :brand, :string, :limit => Product::BRAND_MAX_LENGTH,
:null => true
t.column :title, :string, :limit => Product::TITLE_MAX_LENGTH,
:null => false
t.column :description, :string, :limit => Product::DESCRIPTION_MAX_LENGTH,
:null => false
t.column :model_number, :string, :limit => Product::MODEL_NUMBER_MAX_LENGTH,
:null => true
t.column :source_id, :integer, :null => false
t.column :created_at, :datetime
t.column :updated_at, :datetime
end
add_index :products, :category_id
## Review
create_table :reviews do |t|
t.column :display_id, :string, :null => false, :limit => Review::DISPLAY_ID_MAX_LENGTH
t.column :product_id, :integer, :null => false
t.column :user_id, :integer, :null => false
t.column :sound_bite, :string, :range => Review::SOUND_BITE_MAX_LENGTH, :null => false
t.column :content, :text, :null => false
t.column :points, :integer, :null => false
t.column :created_at, :datetime
t.column :updated_at, :datetime
t.column :recommend, :boolean, :default => false
t.column :comments_count, :integer, :default => 0
end
add_index :reviews, :product_id
add_index :reviews, :user_id
add_index :reviews, :display_id, :unique
## ReviewTag
create_table :review_tags do |t|
t.column :review_id, :integer, :null => false
t.column :kind, :enum, :limit => AbstractTag::KIND_ENUM_VALUES, :default => :pro, :null => false
t.column :value, :string, :limit => AbstractTag::VALUE_MAX_LENGTH, :null => false
t.column :sort_order, :integer, :null => false
end
# TODO AJA review indexes
add_index :review_tags, [:review_id, :kind]
create_table :review_comments do |t|
#create_table :review_comments do |t|
t.column :user_id, :integer, :null => false
t.column :review_id, :integer, :null => false
t.column :text, :text, :null => false
t.column :created_at, :datetime
t.column :updated_at, :datetime
end
create_table :category_questions do |t|
t.column :category_id, :integer, :null => false
t.column :text, :string, :null => false
t.column :created_at, :datetime
t.column :updated_at, :datetime
t.column :sort_order, :integer, :null => false
end
create_table :review_photos do |t|
# t.column :name, :string
# the subdirectory under the photo loading dirs that this file was put in.
t.column :directory, :string
# track the file base name sep, so that they are globally
# unique, not just unique in their local directory. will
# make it easier to move them later. this is without size indicators
# and without file extensions.
t.column :file_base_name, :string
# Rather than use booleans to denote the existance of a file,
# and relying on convention to figure its name, this model
# stores the full name of each created file. the only convention
# is that all three are in the same directory.
t.column :file_full_size_name, :string
t.column :file_mid_size_name, :string
t.column :file_thumbnail_name, :string
# the direct mime type of the files referenced above.
t.column :content_type, :string, :null => false
t.column :review_id, :integer, :null => false
t.column :source_id, :integer, :null => false
t.column :sort_order, :integer
t.column :caption, :text
t.column :alt_text, :text
end
create_table :review_answers do |t|
t.column :category_question_id, :integer, :null => false
t.column :review_id, :integer, :null => false
t.column :text, :string, :null => true
t.column :created_at, :datetime
t.column :updated_at, :datetime
end
create_table :user_review_annotations do |t|
t.column :user_id, :integer, :null => false
t.column :review_id, :integer, :null => false
t.column :useful, :boolean
t.column :inappropriate, :boolean
t.column :inappropriate_reason, :string, :limit => 500
t.column :created_at, :datetime
t.column :updated_at, :datetime
end
add_index :user_review_annotations, [:user_id, :review_id], :unique
add_index :user_review_annotations, [:review_id]
create_table :user_product_annotations do |t|
t.column :user_id, :integer, :null => false
t.column :product_id, :integer, :null => false
t.column :owned, :boolean, :null => false, :default => false
t.column :created_at, :datetime
t.column :updated_at, :datetime
end
add_index :user_product_annotations, [:user_id, :product_id], :unique
add_index :user_product_annotations, [:product_id]
create_table :zip_codes do |t|
t.column :detail_code, :string, :limit => 1
t.column :zip_code, :string, :limit => 5
t.column :city_state_key, :string, :limit => 6
t.column :zip_classification_code, :string, :limit => 1
t.column :city_state_name, :string, :limit => 28
t.column :city_state_name_abbreviation, :string, :limit => 13
t.column :city_state_name_facility_code, :string, :limit => 1
t.column :city_state_name_indicator, :string, :limit => 1
t.column :last_line_city_key, :string, :limit => 6
t.column :last_line_city_preferred_name, :string, :limit => 28
t.column :city_delivery_indicator, :string, :limit => 1
t.column :cart_rate_mail_indicator, :string, :limit => 1
t.column :unique_zip_code_indicator, :string, :limit => 1
t.column :finance_number, :string, :limit => 6
t.column :state_abbreviation, :string, :limit => 2
t.column :county_number_fips_code, :string, :limit => 3
t.column :county, :string, :limit => 25
t.column :latitude, :decimal, :precision => 7, :scale => 4
t.column :longitude, :decimal, :precision => 8, :scale => 4
t.column :area_code, :string, :limit => 15
t.column :time_zone, :string, :limit => 2
t.column :elevation, :string, :limit => 5
t.column :persons_per_household, :string, :precision => 4, :scale => 2
t.column :population_of_zip_code, :string, :limit => 8
t.column :area_of_county_in_sq_miles, :string, :limit => 6
t.column :households_per_zip_code, :string, :limit => 8
t.column :whites_per_zip_code, :string, :limit => 8
t.column :blacks_per_zip_code, :string, :limit => 8
t.column :hispanic_per_zip_code, :string, :limit => 8
t.column :income_per_household_per_county, :string, :limit => 8
t.column :average_house_value_per_county, :string, :limit => 8
end
add_index :zip_codes, [:zip_code]
create_table :invitations do |t|
t.column :token, :string, :limit => Invitation::TOKEN_MAX_LENGTH
t.column :email, :string, :null => false, :limit => Invitation::EMAIL_MAX_LENGTH
t.column :first_name, :string, :null => false, :limit => Invitation::FIRST_NAME_MAX_LENGTH
t.column :last_name, :string, :null => false, :limit => Invitation::LAST_NAME_MAX_LENGTH
t.column :sender_user_id, :bigint, :null => false
t.column :invitee_user_id, :bigint
t.column :created_at, :datetime
t.column :sent_at, :datetime
t.column :errored_at, :datetime
end
add_index :invitations, [:token]
# test entries for the migration fulltext_ mods
if (@@test_fulltext_migrations)
create_table :dummy_table, :fulltext => true do |t|
t.column :category_question_id, :integer, :null => false
t.column :review_id, :integer, :null => false
t.column :text, :string, :null => true, :limit => 256
t.column :created_at, :datetime
t.column :updated_at, :datetime
end
add_column :dummy_table, :fake_text, :text
puts "should have reindexed"
puts "should have dropped/created triggers"
add_column :dummy_table, :fake_date, :datetime
puts "should not have reindexed"
puts "should have dropped/created triggers"
change_column :dummy_table, :fake_text, :datetime
puts "should have reindexed"
change_column :dummy_table, :fake_date, :text
puts "should have reindexted"
change_column :dummy_table, :created_at, :integer
puts "should not have reindexed"
remove_column :dummy_table, :fake_date
puts "should have reindexed"
puts "should have dropped/created triggers"
rename_table :dummy_table, :bad_dummy_table
puts "should have new indexes and new triggers"
puts "should have dropped/created triggers"
rename_column :bad_dummy_table, :text, :answer_text
puts "should have reindexed"
puts "should have dropped/created triggers"
rename_column :bad_dummy_table, :created_at, :answered_at
puts "should not have reindexed"
puts "should have dropped/created triggers"
end
end # end of self.up
def self.down
drop_table :invitations
drop_table :zip_codes
drop_table :user_review_annotations
drop_table :user_product_annotations
drop_table :category_questions
drop_table :review_answers
drop_table :review_comments
drop_table :review_photos
drop_table :review_tags
drop_table :reviews
drop_table :products
drop_table :category_attributes
drop_table :category_tags
drop_table :category_relationships
drop_table :categories
drop_table :sources
drop_table :anonymous_tokens
drop_table :users
if (@@test_fulltext_migrations)
drop_table :bad_dummy_table
end
end # end of self.down
end
|
When(/^the current date is after the due date$/) do
on(PaymentsDetailsPage).due_date_element.visible?.should be true
(Date.today.to_s > Date.parse(on(PaymentsDetailsPage).due_date).to_s).should be true
end
And(/^current balance is between the minimum payment allowed amount and the maximum payment allowed amount$/) do
current_balance = on(PaymentsDetailsPage).cur_balance_value
current_balance = current_balance.delete('$').to_f
current_balance.should be > 0.00
current_balance.should be <= 1000000.00
end
Then(/^enable the current balance payment option$/) do
on(PaymentsDetailsPage).cur_balance_element.enabled?.should be true
end
When(/^the due date is not available$/) do
on(PaymentsDetailsPage).pay_to_account_element.select data_for(:payment_noncycled_multi_acct_login)['non_cycled_account']
on(PaymentsDetailsPage).due_date.should eq '(Pending first billing cycle)'
end |
#!/run/nodectl/nodectl script
# Add IP addresses to all local VPS configs on the current node.
require 'nodectld/standalone'
require 'ipaddress'
db = NodeCtld::Db.new
cfg = nil
vps_id = nil
db.prepared(
'SELECT vpses.id AS vps_id, pools.filesystem, netifs.name AS netif,
ips.ip_addr AS route_addr, ips.prefix AS route_prefix,
ips.class_id, ips.max_tx, ips.max_rx,
host.ip_addr AS route_via_addr
FROM vpses
INNER JOIN network_interfaces netifs ON netifs.vps_id = vpses.id
LEFT JOIN ip_addresses ips ON ips.network_interface_id = netifs.id
LEFT JOIN networks nets ON nets.id = ips.network_id
LEFT JOIN host_ip_addresses host ON host.id = ips.route_via_id
INNER JOIN dataset_in_pools dips ON dips.id = vpses.dataset_in_pool_id
INNER JOIN pools ON pools.id = dips.pool_id
WHERE vpses.object_state < 3 AND vpses.node_id = ?
ORDER BY vpses.id, netifs.id, nets.ip_version, ips.order',
$CFG.get(:vpsadmin, :node_id)
).each do |row|
if cfg.nil? || vps_id != row['vps_id']
cfg.save if cfg
cfg = NodeCtld::VpsConfig.open(row['filesystem'], row['vps_id'])
vps_id = row['vps_id']
puts "VPS #{vps_id}"
end
unless cfg.network_interfaces.detect { |n| n.name == row['netif'] }
puts " > #{row['netif']}"
cfg.network_interfaces << NodeCtld::VpsConfig::NetworkInterface.new(row['netif'])
end
# The VPS may not have any IP addresses
next unless row['route_addr']
netif = cfg.network_interfaces[row['netif']]
addr = IPAddress.parse("#{row['route_addr']}/#{row['route_prefix']}")
if netif.has_route_for?(addr)
puts " found #{row['route_addr']}/#{row['route_prefix']}"
else
puts " added #{row['route_addr']}/#{row['route_prefix']}"
netif.add_route(NodeCtld::VpsConfig::Route.new(
addr,
row['route_via_addr'],
row['class_id'],
row['max_tx'],
row['max_rx'],
))
end
end
cfg.save if cfg
|
# encoding: UTF-8
#
# Copyright © 2012-2015 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 Coopr
# configuration constants
PROVISIONER_SERVER_URI = 'provisioner.server.uri'.freeze
PROVISIONER_BIND_IP = 'provisioner.bind.ip'.freeze
PROVISIONER_BIND_PORT = 'provisioner.bind.port'.freeze
PROVISIONER_REGISTER_IP = 'provisioner.register.ip'.freeze
PROVISIONER_DAEMONIZE = 'provisioner.daemonize'.freeze
PROVISIONER_DATA_DIR = 'provisioner.data.dir'.freeze
PROVISIONER_WORK_DIR = 'provisioner.work.dir'.freeze
PROVISIONER_CAPACITY = 'provisioner.capacity'.freeze
PROVISIONER_HEARTBEAT_INTERVAL = 'provisioner.heartbeat.interval'.freeze
PROVISIONER_LOG_DIR = 'provisioner.log.dir'.freeze
PROVISIONER_LOG_ROTATION_SHIFT_AGE = 'provisioner.log.rotation.shift.age'.freeze
PROVISIONER_LOG_ROTATION_SHIFT_SIZE = 'provisioner.log.rotation.shift.size'.freeze
PROVISIONER_LOG_LEVEL = 'provisioner.log.level'.freeze
PROVISIONER_WORKER_POLL_INTERVAL = 'provisioner.worker.poll.interval'.freeze
PROVISIONER_WORKER_POLL_ERROR_INTERVAL = 'provisioner.worker.poll.error.interval'.freeze
TRUST_CERT_PATH = 'trust.cert.path'.freeze
TRUST_CERT_PASS = 'trust.cert.pass'.freeze
# api version
PROVISIONER_API_VERSION = 'v2'.freeze
end
|
# frozen_string_literal: true
# rubocop:todo all
require 'spec_helper'
# this test performs direct network connections without retries.
# In case of intermittent network issues, retry the entire failing test.
describe Mongo::Socket::SSL do
retry_test
clean_slate_for_all
require_tls
let(:host_name) { 'localhost' }
let(:socket) do
described_class.new('127.0.0.1', default_address.port,
host_name, 1, :INET, ssl_options.merge(
connect_timeout: 2.4))
end
let(:ssl_options) do
SpecConfig.instance.ssl_options
end
let (:key_string) do
File.read(SpecConfig.instance.local_client_key_path)
end
let (:cert_string) do
File.read(SpecConfig.instance.local_client_cert_path)
end
let (:ca_cert_string) do
File.read(SpecConfig.instance.local_ca_cert_path)
end
let(:key_encrypted_string) do
File.read(SpecConfig.instance.client_encrypted_key_path)
end
let(:cert_object) do
OpenSSL::X509::Certificate.new(cert_string)
end
let(:key_object) do
OpenSSL::PKey.read(key_string)
end
describe '#human_address' do
it 'returns the address and tls indicator' do
addr = socket.instance_variable_get(:@tcp_socket).remote_address
expect(socket.send(:human_address)).to eq("#{addr.ip_address}:#{addr.ip_port} (#{default_address}, TLS)")
end
end
describe '#connect!' do
context 'when TLS context hooks are provided' do
# https://github.com/jruby/jruby-openssl/issues/221
fails_on_jruby
let(:proc) do
Proc.new do |context|
if BSON::Environment.jruby?
context.ciphers = ["AES256-SHA256"]
else
context.ciphers = ["AES256-SHA"]
end
end
end
before do
Mongo.tls_context_hooks = [ proc ]
end
after do
Mongo.tls_context_hooks.clear
end
it 'runs the TLS context hook before connecting' do
if ENV['OCSP_ALGORITHM']
skip "OCSP configurations use different certificates which this test does not handle"
end
expect(proc).to receive(:call).and_call_original
socket
# Even though we are requesting a single cipher in the hook,
# there may be multiple ciphers available in the context.
# All of the ciphers should match the requested one (using
# OpenSSL's idea of what "match" means).
socket.context.ciphers.each do |cipher|
unless cipher.first =~ /SHA256/ || cipher.last == 256
raise "Unexpected cipher #{cipher} after requesting SHA-256"
end
end
end
end
context 'when a certificate is provided' do
context 'when connecting the tcp socket is successful' do
it 'connects to the server' do
expect(socket).to be_alive
end
end
context 'when connecting the tcp socket raises an exception' do
it 'raises an exception' do
expect_any_instance_of(::Socket).to receive(:connect).and_raise(Mongo::Error::SocketTimeoutError)
expect do
socket
end.to raise_error(Mongo::Error::SocketTimeoutError)
end
end
end
context 'when a certificate and key are provided as strings' do
let(:ssl_options) do
{
:ssl => true,
:ssl_cert_string => cert_string,
:ssl_key_string => key_string,
:ssl_verify => false
}
end
it 'connects to the server' do
expect(socket).to be_alive
end
end
context 'when certificate and an encrypted key are provided as strings' do
require_local_tls
let(:ssl_options) do
{
:ssl => true,
:ssl_cert_string => cert_string,
:ssl_key_string => key_encrypted_string,
:ssl_key_pass_phrase => SpecConfig.instance.client_encrypted_key_passphrase,
:ssl_verify => false
}
end
it 'connects to the server' do
expect(socket).to be_alive
end
end
context 'when a certificate and key are provided as objects' do
let(:ssl_options) do
{
:ssl => true,
:ssl_cert_object => cert_object,
:ssl_key_object => key_object,
:ssl_verify => false
}
end
it 'connects to the server' do
expect(socket).to be_alive
end
end
context 'when the certificate is specified using both a file and a PEM-encoded string' do
let(:ssl_options) do
super().merge(
:ssl_cert_string => 'This is a random string, not a PEM-encoded certificate'
)
end
# since the lower priority option is clearly invalid we verify priority by checking that it connects
it 'discards the value of :ssl_cert_string' do
expect(socket).to be_alive
end
end
context 'when the certificate is specified using both a file and an object' do
let(:ssl_options) do
super().merge(
:ssl_cert_object => 'This is a string, not a certificate'
)
end
# since the lower priority option is clearly invalid we verify priority by checking that it connects
it 'discards the value of :ssl_cert_object' do
expect(socket).to be_alive
end
end
context 'when the certificate is specified using both a PEM-encoded string and an object' do
let(:ssl_options) do
{
:ssl => true,
:ssl_cert_string => cert_string,
:ssl_cert_object => 'This is a string, not a Certificate',
:ssl_key => SpecConfig.instance.client_key_path,
:ssl_verify => false
}
end
# since the lower priority option is clearly invalid we verify priority by checking that it connects
it 'discards the value of :ssl_cert_object' do
expect(socket).to be_alive
end
end
context 'when the key is specified using both a file and a PEM-encoded string' do
let(:ssl_options) do
super().merge(
:ssl_key_string => 'This is a normal string, not a PEM-encoded key'
)
end
# since the lower priority option is clearly invalid we verify priority by checking that it connects
it 'discards the value of :ssl_key_string' do
expect(socket).to be_alive
end
end
context 'when the key is specified using both a file and an object' do
let(:ssl_options) do
super().merge(
:ssl_cert_object => 'This is a string, not a key'
)
end
# since the lower priority option is clearly invalid we verify priority by checking that it connects
it 'discards the value of :ssl_key_object' do
expect(socket).to be_alive
end
end
context 'when the key is specified using both a PEM-encoded string and an object' do
let(:ssl_options) do
{
:ssl => true,
:ssl_cert => SpecConfig.instance.client_cert_path,
:ssl_key_string => key_string,
:ssl_key_object => 'This is a string, not a PKey',
:ssl_verify => false
}
end
# since the lower priority option is clearly invalid we verify priority by checking that it connects
it 'discards the value of :ssl_key_object' do
expect(socket).to be_alive
end
end
context 'when a certificate is passed, but it is not of the right type' do
let(:ssl_options) do
cert = "This is a string, not an X.509 Certificate"
{
:ssl => true,
:ssl_cert_object => cert,
:ssl_key => SpecConfig.instance.local_client_key_path,
:ssl_verify => false
}
end
it 'raises a TypeError' do
expect do
socket
end.to raise_exception(TypeError)
end
end
context 'when the hostname is incorrect' do
let(:host_name) do
'incorrect_hostname'
end
context 'when the hostname is verified' do
let(:ssl_options) do
SpecConfig.instance.ssl_options.merge(ssl_verify: false, ssl_verify_hostname: true)
end
it 'raises an error' do
lambda do
socket
end.should raise_error(Mongo::Error::SocketError, /TLS handshake failed due to a hostname mismatch/)
end
end
context 'when the hostname is not verified' do
let(:ssl_options) do
SpecConfig.instance.ssl_options.merge(ssl_verify: false, ssl_verify_hostname: false)
end
it 'does not raise an error' do
lambda do
socket
end.should_not raise_error
end
end
end
# Note that as of MRI 2.4, Creating a socket with the wrong key type raises
# a NoMethodError because #private? is attempted to be called on the key.
# In jruby 9.2 a TypeError is raised.
# In jruby 9.1 a OpenSSL::PKey::PKeyError is raised.
context 'when a key is passed, but it is not of the right type' do
let(:ssl_options) do
key = "This is a string not a key"
{
:ssl => true,
:ssl_key_object => key,
:ssl_cert => SpecConfig.instance.client_cert_path,
:ssl_verify => false
}
end
let(:expected_exception) do
if SpecConfig.instance.jruby?
if RUBY_VERSION >= '2.5.0'
# jruby 9.2
TypeError
else
# jruby 9.1
OpenSSL::OpenSSLError
end
else
# MRI
if RUBY_VERSION >= '3.1.0'
TypeError
else
NoMethodError
end
end
end
it 'raises a NoMethodError' do
expect do
socket
end.to raise_exception(expected_exception)
end
end
context 'when a bad certificate/key is provided' do
shared_examples_for 'raises an exception' do
it 'raises an exception' do
expect do
socket
end.to raise_exception(*expected_exception)
end
end
context 'mri' do
require_mri
context 'when a bad certificate is provided' do
let(:expected_exception) do
if RUBY_VERSION >= '3.1.0'
# OpenSSL::X509::CertificateError: PEM_read_bio_X509: no start line
OpenSSL::X509::CertificateError
else
# OpenSSL::X509::CertificateError: nested asn1 error
[OpenSSL::OpenSSLError, /asn1 error/i]
end
end
let(:ssl_options) do
super().merge(
:ssl_cert => CRUD_TESTS.first,
:ssl_key => nil,
)
end
it_behaves_like 'raises an exception'
end
context 'when a bad key is provided' do
let(:expected_exception) do
# OpenSSL::PKey::PKeyError: Could not parse PKey: no start line
[OpenSSL::OpenSSLError, /Could not parse PKey/]
end
let(:ssl_options) do
super().merge(
:ssl_cert => nil,
:ssl_key => CRUD_TESTS.first,
)
end
it_behaves_like 'raises an exception'
end
end
context 'jruby' do
require_jruby
# On JRuby the key does not appear to be parsed, therefore only
# specifying the bad certificate produces an error.
context 'when a bad certificate is provided' do
let(:ssl_options) do
super().merge(
:ssl_cert => CRUD_TESTS.first,
:ssl_key => nil,
)
end
let(:expected_exception) do
# java.lang.ClassCastException: org.bouncycastle.asn1.DERApplicationSpecific cannot be cast to org.bouncycastle.asn1.ASN1Sequence
# OpenSSL::X509::CertificateError: parsing issue: malformed PEM data: no header found
[OpenSSL::OpenSSLError, /malformed pem data/i]
end
it_behaves_like 'raises an exception'
end
end
end
context 'when a CA certificate is provided' do
require_local_tls
context 'as a path to a file' do
let(:ssl_options) do
super().merge(
:ssl_ca_cert => SpecConfig.instance.local_ca_cert_path,
:ssl_verify => true
)
end
it 'connects to the server' do
expect(socket).to be_alive
end
end
context 'as a string containing the PEM-encoded certificate' do
let(:ssl_options) do
super().merge(
:ssl_ca_cert_string => ca_cert_string,
:ssl_verify => true
)
end
it 'connects to the server' do
expect(socket).to be_alive
end
end
context 'as an array of Certificate objects' do
let(:ssl_options) do
cert = [OpenSSL::X509::Certificate.new(ca_cert_string)]
super().merge(
:ssl_ca_cert_object => cert,
:ssl_verify => true
)
end
it 'connects to the server' do
expect(socket).to be_alive
end
end
context 'both as a file and a PEM-encoded parameter' do
let(:ssl_options) do
super().merge(
:ssl_ca_cert => SpecConfig.instance.local_ca_cert_path,
:ssl_ca_cert_string => 'This is a string, not a certificate',
:ssl_verify => true
)
end
# since the lower priority option is clearly invalid we verify priority by checking that it connects
it 'discards the value of :ssl_ca_cert_string' do
expect(socket).to be_alive
end
end
context 'both as a file and as object parameter' do
let(:ssl_options) do
super().merge(
:ssl_ca_cert => SpecConfig.instance.local_ca_cert_path,
:ssl_ca_cert_object => 'This is a string, not an array of certificates',
:ssl_verify => true
)
end
it 'discards the value of :ssl_ca_cert_object' do
expect(socket).to be_alive
end
end
context 'both as a PEM-encoded string and as object parameter' do
let(:ssl_options) do
cert = File.read(SpecConfig.instance.local_ca_cert_path)
super().merge(
:ssl_ca_cert_string => cert,
:ssl_ca_cert_object => 'This is a string, not an array of certificates',
:ssl_verify => true
)
end
it 'discards the value of :ssl_ca_cert_object' do
expect(socket).to be_alive
end
end
end
context 'when CA certificate file is not what server cert is signed with' do
require_local_tls
let(:server) do
ClientRegistry.instance.global_client('authorized').cluster.next_primary
end
let(:connection) do
Mongo::Server::Connection.new(server, ssl_options.merge(socket_timeout: 2))
end
context 'as a file' do
let(:ssl_options) do
SpecConfig.instance.test_options.merge(
ssl: true,
ssl_cert: SpecConfig.instance.client_cert_path,
ssl_key: SpecConfig.instance.client_key_path,
ssl_ca_cert: SpecConfig.instance.ssl_certs_dir.join('python-ca.crt').to_s,
ssl_verify: true,
)
end
it 'fails' do
connection
expect do
connection.connect!
end.to raise_error(Mongo::Error::SocketError, /SSLError/)
end
end
end
context 'when CA certificate file contains multiple certificates' do
require_local_tls
let(:server) do
ClientRegistry.instance.global_client('authorized').cluster.next_primary
end
let(:connection) do
Mongo::Server::Connection.new(server, ssl_options.merge(socket_timeout: 2))
end
context 'as a file' do
let(:ssl_options) do
SpecConfig.instance.test_options.merge(
ssl: true,
ssl_cert: SpecConfig.instance.client_cert_path,
ssl_key: SpecConfig.instance.client_key_path,
ssl_ca_cert: SpecConfig.instance.multi_ca_path,
ssl_verify: true,
)
end
it 'succeeds' do
connection
expect do
connection.connect!
end.not_to raise_error
end
end
end
context 'when a CA certificate is not provided' do
require_local_tls
let(:ssl_options) do
super().merge(
:ssl_verify => true
)
end
local_env do
{ 'SSL_CERT_FILE' => SpecConfig.instance.local_ca_cert_path }
end
it 'uses the default cert store' do
expect(socket).to be_alive
end
end
context 'when the client certificate uses an intermediate certificate' do
require_local_tls
let(:server) do
ClientRegistry.instance.global_client('authorized').cluster.next_primary
end
let(:connection) do
Mongo::Server::Connection.new(server, ssl_options.merge(socket_timeout: 2))
end
context 'as a path to a file' do
context 'standalone' do
let(:ssl_options) do
SpecConfig.instance.test_options.merge(
ssl_cert: SpecConfig.instance.second_level_cert_path,
ssl_key: SpecConfig.instance.second_level_key_path,
ssl_ca_cert: SpecConfig.instance.local_ca_cert_path,
ssl_verify: true,
)
end
it 'fails' do
# This test provides a second level client certificate to the
# server *without* providing the intermediate certificate.
# If the server performs certificate verification, it will
# reject the connection (seen from the driver as a SocketError)
# and the test will succeed. If the server does not perform
# certificate verification, it will accept the connection,
# no SocketError will be raised and the test will fail.
connection
expect do
connection.connect!
end.to raise_error(Mongo::Error::SocketError)
end
end
context 'bundled with intermediate cert' do
# https://github.com/jruby/jruby-openssl/issues/181
require_mri
let(:ssl_options) do
SpecConfig.instance.test_options.merge(
ssl: true,
ssl_cert: SpecConfig.instance.second_level_cert_bundle_path,
ssl_key: SpecConfig.instance.second_level_key_path,
ssl_ca_cert: SpecConfig.instance.local_ca_cert_path,
ssl_verify: true,
)
end
it 'succeeds' do
connection
expect do
connection.connect!
end.not_to raise_error
end
end
end
context 'as a string' do
context 'standalone' do
let(:ssl_options) do
SpecConfig.instance.test_options.merge(
ssl_cert: nil,
ssl_cert_string: File.read(SpecConfig.instance.second_level_cert_path),
ssl_key: nil,
ssl_key_string: File.read(SpecConfig.instance.second_level_key_path),
ssl_ca_cert: SpecConfig.instance.local_ca_cert_path,
ssl_verify: true,
)
end
it 'fails' do
connection
expect do
connection.connect!
end.to raise_error(Mongo::Error::SocketError)
end
end
context 'bundled with intermediate cert' do
# https://github.com/jruby/jruby-openssl/issues/181
require_mri
let(:ssl_options) do
SpecConfig.instance.test_options.merge(
ssl: true,
ssl_cert: nil,
ssl_cert_string: File.read(SpecConfig.instance.second_level_cert_bundle_path),
ssl_key: nil,
ssl_key_string: File.read(SpecConfig.instance.second_level_key_path),
ssl_ca_cert: SpecConfig.instance.local_ca_cert_path,
ssl_verify: true,
)
end
it 'succeeds' do
connection
expect do
connection.connect!
end.not_to raise_error
end
end
end
end
context 'when client certificate and private key are bunded in a pem file' do
require_local_tls
let(:server) do
ClientRegistry.instance.global_client('authorized').cluster.next_primary
end
let(:connection) do
Mongo::Server::Connection.new(server, ssl_options.merge(socket_timeout: 2))
end
let(:ssl_options) do
SpecConfig.instance.ssl_options.merge(
ssl: true,
ssl_cert: SpecConfig.instance.client_pem_path,
ssl_key: SpecConfig.instance.client_pem_path,
ssl_ca_cert: SpecConfig.instance.local_ca_cert_path,
ssl_verify: true,
)
end
it 'succeeds' do
connection
expect do
connection.connect!
end.not_to raise_error
end
end
context 'when ssl_verify is not specified' do
require_local_tls
let(:ssl_options) do
super().merge(
:ssl_ca_cert => SpecConfig.instance.local_ca_cert_path
).tap { |options| options.delete(:ssl_verify) }
end
it 'verifies the server certificate' do
expect(socket).to be_alive
end
end
context 'when ssl_verify is true' do
require_local_tls
let(:ssl_options) do
super().merge(
:ssl_ca_cert => SpecConfig.instance.local_ca_cert_path,
:ssl_verify => true
)
end
it 'verifies the server certificate' do
expect(socket).to be_alive
end
end
context 'when ssl_verify is false' do
let(:ssl_options) do
super().merge(
:ssl_ca_cert => 'invalid',
:ssl_verify => false
)
end
it 'does not verify the server certificate' do
expect(socket).to be_alive
end
end
context 'when OpenSSL allows disabling renegotiation 'do
before do
unless OpenSSL::SSL.const_defined?(:OP_NO_RENEGOTIATION)
skip 'OpenSSL::SSL::OP_NO_RENEGOTIATION is not defined'
end
end
it 'disables TLS renegotiation' do
expect(socket.context.options & OpenSSL::SSL::OP_NO_RENEGOTIATION).to eq(OpenSSL::SSL::OP_NO_RENEGOTIATION)
end
end
end
describe '#readbyte' do
before do
allow_message_expectations_on_nil
allow(socket.socket).to receive(:read) do |length|
socket_content[0, length]
end
end
context 'with the socket providing "abc"' do
let(:socket_content) { "abc" }
it 'should return 97 (the byte for "a")' do
expect(socket.readbyte).to eq(97)
end
end
context 'with the socket providing "\x00" (NULL_BYTE)' do
let(:socket_content) { "\x00" }
it 'should return 0' do
expect(socket.readbyte).to eq(0)
end
end
context 'with the socket providing no data' do
let(:socket_content) { "" }
let(:remote_address) { socket.instance_variable_get(:@tcp_socket).remote_address }
let(:address_str) { "#{remote_address.ip_address}:#{remote_address.ip_port} (#{default_address}, TLS)" }
it 'should raise EOFError' do
expect do
socket.readbyte
end.to raise_error(Mongo::Error::SocketError).with_message("EOFError: EOFError (for #{address_str})")
end
end
end
end
|
require 'spec_helper'
describe ChunkyPNG::Palette do
it "should preserve the palette correctly" do
filename = resource_file('palette1.png')
image = ChunkyPNG::Image.from_file(filename)
pal = image.palette
# The palette should not get reduced simply becayuse the colors are unused
# or duplicated.
pal.size.should > 3
end
end |
class PollsController < ApplicationController
before_filter :check_admin_key_and_load_poll, :only => [:edit, :update, :destroy]
before_filter :load_poll_and_ballot, :only => [:show]
# GET /polls
def index
@polls = Poll.all
end
# GET /polls/1
def show
end
# GET /polls/new
def new
@poll = Poll.new
end
# GET /polls/1/edit
def edit
end
# POST /polls
def create
@poll = Poll.new(params[:poll])
if @poll.save
redirect_to poll_admin_path(:poll_id => @poll.id, :owner_key => @poll.owner_key, :only_path => false), notice: 'Poll was successfully created.'
else
render action: "new"
end
end
# PUT /polls/1
def update
if @poll.update_attributes(params[:poll])
redirect_to @poll, notice: 'Poll was successfully updated.'
else
render action: "edit"
end
end
# DELETE /polls/1
def destroy
@poll.destroy
redirect_to polls_url
end
end
|
step "a table of :x units wide by :y units high" do |x, y|
@table = Table.new(x.to_i, y.to_i)
end
step "a robot" do
@robot = Robot.new(@table)
end
step "a robot placed at :x,:y facing north" do |x, y|
@robot = Robot.new(@table)
position = Position.new(x.to_i, y.to_i)
orientation = Orientation::NORTH
placement = Placement.new(@table, position, orientation)
@robot.place(placement)
end
step "the robot moves" do
@robot.move
end
step "the robot turns right" do
@robot.right
end
step "the robot turns left" do
@robot.left
end
step "the robot should be at :x,:y facing :orientation" do |x, y, orientation|
expect(@robot.placement.position).to eq(Position.new(x.to_i, y.to_i))
expect(@robot.placement.orientation).to eq(Orientation.from_name(orientation))
end
step "the robot should not be placed" do
expect(@robot.placement).to be nil
end |
module MembersHelper
#VARIABLES
@@accept = "application/vnd.mx.api.v1+json"
@@content_type = "application/json"
@@base_url = "https://int-api.mx.com"
def list_institutions(page = 1, records_per_page = 1000)
HTTP.headers(:accept => @@accept)
.basic_auth(:user => ENV["API_USERNAME"] ,
:pass => ENV["API_PASSWORD"])
.get("#{@@base_url}/institutions", params: { :page => page,
:records_per_page => records_per_page})
.parse["institutions"]
end
end
|
require "rails_helper"
Capybara.register_driver :selenium do |app|
Capybara::Selenium::Driver.new(app, :browser => :chrome)
end
describe 'User', js: true do
context 'New User' do
it 'can click the signup link and be directed to sigup page' do
visit root_path
within(:css, "p.navbar-text") do
click_on('Sign up')
end
page.has_content?('Email')
end
it 'allows you to sign up and enter your email and password and redirects you to your profile' do
visit root_path
within(:css, "p.navbar-text") do
click_on('Sign up')
end
fill_in "Email", with: "bison@bison.com"
fill_in "Password", with: "password"
fill_in "Password confirmation", with: "password"
within(:css, "form") do
click_on('Sign up')
end
page.has_content?('Your Workouts')
end
end
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
user1 = User.create({username: 'Simon'})
user2 = User.create({username: 'Miyuki'})
notes1 = [
{body: 'Ipsam adipisci libero laudantium voluptas veniam rerum aliquid quasi.'},
{body: 'Aut quia sit aperiam consectetur deleniti esse quia nulla qui. Et velit dolor. Et natus tenetur veritatis quisquam tenetur tenetur repellendus omnis iste. Molestiae velit mollitia similique laudantium consequatur dolorem laboriosam et nihil. Adipisci consectetur sapiente. Sapiente vel excepturi at et harum nam.'},
{body: 'Quia magnam sequi nostrum non voluptatibus.'},
{body: 'Sint dolor magni sit molestias vitae voluptatum quos. Impedit a iure rerum debitis nostrum est minus rerum atque. Quam officiis et iusto ut. Sed fuga enim accusamus ullam quo dolorem a doloremque debitis. Officia qui fuga et. Quaerat natus ipsum et quo.'},
]
notes2 = [
{body: 'Optio consequatur vero perspiciatis ratione rerum rerum.'},
{body: 'Architecto illo pariatur et.'},
{body: 'Aliquam est officia sed voluptatem placeat. Facilis blanditiis omnis velit est et voluptas sequi. Occaecati modi et quasi consequatur. Est sunt iste eum voluptas.'},
{body: 'Cupiditate blanditiis similique aliquid ipsum.'},
{body: 'Facere explicabo possimus velit voluptatibus tempora accusamus quisquam atque. Quo et omnis suscipit ut nesciunt dolore sunt cumque et. Repellat placeat doloremque ea. Recusandae illum quisquam qui. Dolor voluptas et nihil qui dignissimos.'},
]
notes1.each {|note|
user1.notes.create(note)
}
notes2.each {|note|
user2.notes.create(note)
} |
class Event < ActiveRecord::Base
belongs_to :user
has_many :parameters
accepts_nested_attributes_for :parameters, :allow_destroy => true
end
|
module Hexagonal
module Runners
class DeleteRunner
pattr_initialize :listener, :user, :id
delegate :unauthorized, :deleted_successfully, to: :listener
attr_writer :policy, :repository
def run
authorize!
delete!
deleted_successfully target
rescue Hexagonal::Errors::UnauthorizedException => ex
unauthorized(ex)
end
private
def authorize!
fail! unless policy.delete?
end
def fail!
fail Hexagonal::Errors::UnauthorizedException, 'Unauthorized', caller
end
def delete!
mediator.call
end
def target
@target ||= repository.find id
end
end
end
end
|
#
# Cookbook Name:: volumes
# Description:: Format the volumes listed in node[:volumes]
# Recipe:: format
# Author:: Philip (flip) Kromer - Infochimps, Inc
#
# Copyright 2011, Philip (flip) Kromer - Infochimps, 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.
#
# mkfs.xfs requires a -f option to be passed in when formatting over
# an existing file system.
mkfs_options = { "xfs" => "-f" }
volumes(node).each do |vol_name, vol|
Chef::Log.info(vol.inspect)
next unless vol.formattable?
if not vol.ready_to_format? then Chef::Log.info("Skipping format of volume #{vol_name}: not formattable (#{vol.inspect})") ; next ; end
format_filesystem = execute "/sbin/mkfs -t #{vol.fstype} #{mkfs_options[vol.fstype].to_s} #{vol.device} -L #{vol.name}" do
not_if "eval $(blkid -o export #{vol.device}); test $TYPE = '#{vol.fstype}'"
action :nothing
end
format_filesystem.run_action(:run)
# don't even think about formatting again
vol.formatted!
end
|
class Admin::SettingsController < Admin::ApplicationController
load_and_authorize_resource
helper_method :permission
def index
if request.post?
if !params[:setting].blank?
Setting.app_name = params[:setting][:app_name]
Setting.app_keywords = params[:setting][:app_keywords]
Setting.app_description = params[:setting][:app_description]
Setting.admin_PageSize = params[:setting][:admin_PageSize]
end
redirect_to :admin_root, :notice => t("helpers.messages.setting")
end
end
private
def self.permission
return Setting.name, "permission.controllers.admin.settings"
end
end |
xml.instruct!
xml.DenikReferendum do
@articles.each do |article|
next if article.name.nil? or article.perex.nil? or article.text.nil? or article.publish_date.nil?
xml.Article do
xml.ArtID article.id
xml.date article.publish_date.to_formatted_s(:cz_date)
xml.title article.name
xml.perex article.perex
xml.body do
xml.cdata! article.text
end
xml.author article.author.full_name unless article.author.nil?
xml.section article.section.name unless article.section.nil?
xml.url detail_article_url(pretty_id(article))
end
end
end
|
module Searches
class TwitterUserService
class << self
def find_tweets_for(source)
last = source.last.try(&:provider_id)
params = "from:#{source.key} -rt"
TwitterProvider.client.search(params).take(100).each do |tweet|
break if reached_limit? tweet.id, last
begin
make_a_item_using!(tweet, source)
rescue => e
Rails.logger.info "--- ERROR at #{self}: #{e.message} ---\n"
end
end
end
private
def reached_limit?(id, last)
id.to_s.eql?(last)
end
def make_a_item_using!(tweet, source)
ActiveRecord::Base.transaction do
post = Micropost.create provider_id: tweet.id,
text: tweet.text,
source: source,
status: MicropostStatus::PENDING
attach_clubs_to post, from: source
attach_content_to post, from: tweet
end
end
def attach_content_to(post, from:)
from.media.each do |item|
Medium.create do |m|
m.micropost = post
m.remote_file_url = item.media_url_https.to_s
end
end
end
def attach_clubs_to(post, from:)
post.trollers << Troller.new(trollerable: from.troller)
post.targets << Target.new(targetable: from.target)
end
end
end
end
|
require 'active_record/base'
module Kantox
module Refactory
module Model
class PinceNez
attr_reader :model, :children
# Defines unique records percent to decide whether grouping might be interesting on that column
# @default 10 whether total amount of records divided by unique records number is less or equal to ten,
# the column will be considered interesting for grouping by
GROUP_FACTOR = 10
# @param [String|Symbol|::ActiveRecord::Reflection] model
def initialize model
m = case model
when ::String, ::Symbol then model.clever_constantize
when ::ActiveRecord::Reflection::ThroughReflection,
::ActiveRecord::Reflection::MacroReflection
model.model_class
else model.respond_to?(:ancestors) ? model : model.class # FIXME better way to understand if we got an instance???
end
unless m && m < ::ActiveRecord::Base
binding.pry
fail ArgumentError.new("#{self.class.name}#initialize expects a descendant of ActiveRecord::Base as an argument. Got: #{model}")
end
@model = m
end
def name
@model.name
end
# @return [TrueClass|FalseClass] true if a model has no children (no `:has_many` assoc,) false otherwise
def leaf?
reflections([:has_many, :has_and_belongs_to_many]).empty?
end
# Returns a hash, accumulating/grouping methods representing dates,
# string fields that might be grouped, data interpreted as series, keys and the rest.
# @return [Hash] { date: [..], group: [..], series: [..], keys: [..], garbage: [..] }
def columns eager_group = true
(@columns ||= sort_columns(@model.columns)).tap { |_| group_columns! if eager_group }
end
# @return [String]
def crawl count_through = true
@children ||= reflections([:has_one, :belongs_to]).inject({}) do |memo, (name, r)|
!count_through && r.is_a?(::ActiveRecord::Reflection::ThroughReflection) ?
memo : memo.tap { |m| m[name] = { reflection: r, pince_nez: PinceNez.new(r) } }
end
end
def to_s
"#<#{self.class}:#{'0x%016x' % (self.__id__ << 1)} #{exposed_to_s}>"
end
def inspect
# "#<#{self.class}:#{'0x%016x' % (self.__id__ << 1)} #{exposed_inspect}>"
"#<★PinceNez #{@model.name} labels=#{columns(false)[:labels].map(&:name)}>"
end
protected
def exposed_to_s
crawl.map do |name, rinfo|
[name, rinfo[:pince_nez].model.name ]
end.to_h
end
def exposed_inspect_full
{
properties: exposed_inspect,
reflections: @model.reflections.map do |name, r|
[name, { name: r.name, macro: r.macro, options: r.options, ar: r.active_record.name }]
end.to_h,
columns: @columns
}
end
private
def reflections types, inverse = false # :nodoc:
@model.reflections.select { |_, v| inverse ^ [*types].include?(v.macro) }
end
def sort_columns columns
columns.inject({ date: [], group: {}, series: [], keys: [], labels: [], garbage: [], grouped: false }) do |memo, column|
case column.type
when :datetime then memo[:date]
when :integer then memo[column.name == 'id' || column.name[-3..-1] == '_id' ? :keys : :series]
when :string then memo[column.name =~ /(?<=[^a-z]|\A)name(?=[^a-z]|\z)/ ? :labels : :garbage]
else memo[:garbage]
end << column
memo
end
end
# Builds `group` columns
# @return [Hash] @columns
def group_columns!
fail 'Lame programmer error' unless @columns.is_a? Hash
unless @columns[:grouped]
total = @model.count
%i(keys labels garbage).each do |k|
@columns[:group][k] = @columns[k].select do |col|
@model.group(col.name.to_sym).count.count * 100 / GROUP_FACTOR < total
end
end
@columns[:grouped] = true
end
@columns
end
end
end
end
end
|
class DailyDigest
attr_reader :mailing_list
def initialize
@mailing_list = Person.where(daily_digest: true)
end
def send_digest
mailing_list.each do |person|
updated_conversations = retrieve_updated_conversations(person)
unless updated_conversations.empty?
Notifier.daily_digest(person, updated_conversations).deliver
end
end
end
def retrieve_updated_conversations(person)
time_range = (Time.now.midnight - 1.day)..Time.now.midnight
conversations = Conversation.includes(:subscriptions).where('subscriptions.person_id' => person, 'conversations.updated_at' => time_range)
end
end |
require 'rails_helper'
RSpec.describe "citizens/edit", type: :view do
before(:each) do
@citizen = assign(:citizen, create(:citizen))
end
it "renders the edit citizen form" do
render
assert_select "form[action=?][method=?]", citizen_path(@citizen), "post" do
assert_select "input[name=?]", "citizen[full_name]"
assert_select "input[name=?]", "citizen[cpf]"
assert_select "input[name=?]", "citizen[email]"
assert_select "input[name=?]", "citizen[birthdate]"
assert_select "input[name=?]", "citizen[phone]"
assert_select "input[name=?]", "citizen[status]"
end
end
end
|
require File.expand_path(File.join(File.dirname(__FILE__), "..", "test_helper.rb"))
module Core
class EnrichedStringTest < ActiveSupport::TestCase
setup do
I18n.locale = Rich::I18n::Engine.init :nl
end
test "current locale" do
assert_equal I18n.locale, :nl
end
test "to_output" do
Rich::I18n::Engine.enable_enriched_output = true
# assert_equal "<i18n data-value=\"meer\" data-key=\"word.more\" data-derivative_key=\"More\" data-locale=\"nl\" data-i18n_translation=\"Meer\"></i18n>", "More".t.to_output
end
end
end |
# frozen_string_literal: true
class UpdateLessonSkillSummariesToVersion2 < ActiveRecord::Migration[5.2]
def change
update_view :lesson_skill_summaries, version: 2, revert_to_version: 1
end
end
|
class BoatTypesController < ApplicationController
def index
redirect_to controller: 'boats', action: 'index'
end
def show
@boat_type = BoatType.find_by(slug: params[:id])
redirect_to root_path and return if !@boat_type
fixed_params = params.slice(:order, :page).merge(
params[:id] == 'RIB' ? {q: 'RIB'} : {boat_type_id: @boat_type.id}
)
@boats = Rightboat::BoatSearch.new.do_search(params: fixed_params).results
end
end
|
class Admin::SeetingsController < InheritedResources::Base
def new
@seeting = Seeting.new(company_id: @current_company.id)
end
def update
update! do |success, failure|
success.html { redirect_to edit_adimin_seeting(@seeting) }
end
end
def create
@seeting = Seeting.new(permitted_params.merge(company_id: @current_company.id))
if @seeting.save
redirect_to edit_admin_seeting_path(@seeting)
else
render :edit
end
end
private
def permitted_params
params.require(:seeting).permit(:company_id, :person_kind, :person_name, :address, :zipcode, :neighborhood, :state, :city, :cpf_cnpj, :registry_number)
end
end |
require 'rails_helper'
RSpec.describe Item, type: :model do
before do
@item = FactoryBot.build(:item)
end
describe '商品出品登録' do
context '商品出品登録がうまくいくとき' do
it "すべての項目が存在すれば登録できる" do
expect(@item).to be_valid
end
end
context '商品出品登録がうまくいかないとき' do
it "画像が空だと出品できない" do
@item.image = nil
@item.valid?
expect(@item.errors.full_messages).to include("Image can't be blank")
end
it "商品名が空だと出品できない" do
@item.name = nil
@item.valid?
expect(@item.errors.full_messages).to include("Name can't be blank")
end
it "商品説明が空だと出品できない" do
@item.decription = nil
@item.valid?
expect(@item.errors.full_messages).to include("Decription can't be blank")
end
it "カテゴリーが空だと出品できない" do
@item.category_id = 1
@item.valid?
expect(@item.errors.full_messages).to include("Category must be other than 1")
end
it "商品の状態が空だと出品できない" do
@item.status_id = 1
@item.valid?
expect(@item.errors.full_messages).to include("Status must be other than 1")
end
it "配送料の負担が空だと出品ができない" do
@item.shopping_cost_id = 1
@item.valid?
expect(@item.errors.full_messages).to include("Shopping cost must be other than 1")
end
it "発送元の地域が空だと出品できない" do
@item.shopping_area_id = 1
@item.valid?
expect(@item.errors.full_messages).to include("Shopping area must be other than 1")
end
it "発送までの日数が空だと登録できない" do
@item.shopping_days_id = 1
@item.valid?
expect(@item.errors.full_messages).to include("Shopping days must be other than 1")
end
it "価格が空だと出品できない" do
@item.price = nil
@item.valid?
expect(@item.errors.full_messages).to include("Price can't be blank")
end
it "価格が300以下だと出品できない" do
@item.price = 200
@item.valid?
expect(@item.errors.full_messages).to include("Price must be greater than or equal to 300")
end
it "価格が9999999以上だと出品できない" do
@item.price = 99999999
@item.valid?
expect(@item.errors.full_messages).to include("Price must be less than or equal to 9999999")
end
end
end
end
|
require_relative 'test_helper'
module AdequateSerializer
class Associations < Minitest::Spec
def test_no_associations
peggy = Person.new
PersonSerializer.new(peggy).associations.must_equal({})
end
def test_entity_association
peggy = Person.new
roger = Person.new(id: 2, name: 'Roger', occupation: 'Chief')
peggy.superior = roger
expected = { superior: PersonSerializer.new(roger, root: false).as_json }
PersonSerializer.new(peggy, includes: :superior).associations
.must_equal expected
end
def test_collection_association
peggy = Person.new
daniel = Person.new(id: 3, name: 'Daniel', occupation: 'Agent')
jack = Person.new(id: 4, name: 'Jack', occupation: 'Agent')
peggy.colleagues = [daniel, jack]
expected = {
colleagues: Collection.new([daniel, jack], root: false).as_json
}
PersonSerializer.new(peggy, includes: :colleagues).associations
.must_equal expected
end
def test_multiple_associations
peggy = Person.new
roger = Person.new(id: 2, name: 'Roger', occupation: 'Chief')
peggy.superior = roger
daniel = Person.new(id: 3, name: 'Daniel', occupation: 'Agent')
jack = Person.new(id: 4, name: 'Jack', occupation: 'Agent')
peggy.colleagues = [daniel, jack]
expected = {
colleagues: Collection.new([daniel, jack], root: false).as_json,
superior: PersonSerializer.new(roger, root: false).as_json
}
PersonSerializer.new(peggy, includes: [:colleagues, :superior])
.associations
.must_equal expected
end
def test_nested_associations
peggy = Person.new
roger = Person.new(id: 2, name: 'Roger', occupation: 'Chief')
daniel = Person.new(id: 3, name: 'Daniel', occupation: 'Agent')
peggy.colleagues = [daniel]
daniel.superior = roger
expected = {
colleagues: Collection.new([daniel], root: false, includes: :superior)
.as_json
}
PersonSerializer.new(peggy, includes: [colleagues: :superior])
.associations
.must_equal expected
end
def test_default_associations
peggy = Person.new
roger = Person.new(id: 2, name: 'Roger', occupation: 'Chief')
peggy.superior = roger
daniel = Person.new(id: 3, name: 'Daniel', occupation: 'Agent')
jack = Person.new(id: 4, name: 'Jack', occupation: 'Agent')
peggy.colleagues = [daniel, jack]
expected = {
colleagues: Collection.new([daniel, jack], root: false).as_json,
superior: PersonSerializer.new(roger, root: false).as_json
}
AssociationsSerializer.new(peggy, includes: [:colleagues, :superior])
.associations
.must_equal expected
end
def test_association_override
peggy = Person.new
daniel = Person.new(id: 1, name: 'Daniel', occupation: 'Agent')
jack = Person.new(id: 4, name: 'Jack', occupation: 'Agent')
peggy.colleagues = [daniel, jack]
expected = {
colleagues: Collection.new([jack], root: false).as_json
}
OverrideAssociationSerializer.new(peggy, includes: :colleagues)
.associations
.must_equal expected
end
def test_association_is_nil
peggy = Person.new
peggy.colleagues = Relation.new(Person, [])
expected = { superior: nil, colleagues: [] }
PersonSerializer.new(peggy, includes: [:superior, :colleagues])
.associations
.must_equal expected
end
def test_no_duplicated_associations
peggy = Person.new
peggy.colleagues = Relation.new(Person, [])
expected = { superior: nil, colleagues: [] }
AssociationsSerializer.new(peggy, includes: [:superior, :colleagues])
.associations
.must_equal expected
end
def test_includes_over_default_associations
peggy = Person.new
roger = Person.new(id: 2, name: 'Roger', occupation: 'Chief')
daniel = Person.new(id: 3, name: 'Daniel', occupation: 'Agent')
peggy.colleagues = [daniel]
daniel.superior = roger
expected = {
colleagues: Collection.new([daniel], root: false, includes: :superior)
.as_json,
superior: nil
}
AssociationsSerializer.new(peggy, includes: [colleagues: :superior])
.associations
.must_equal expected
end
end
end
|
class Course < ApplicationRecord
def star_number
self.star.blank? ? 1 : self.star
end
def cover
self.image.blank? ? "default.png" : self.image
end
end
|
class AvatarAdapter
attr_accessor :user, :client
def initialize(user)
@user = user
end
def client
@client ||= begin
Twitter::REST::Client.new(
consumer_key: Rails.application.secrets.twitter_api,
consumer_secret: Rails.application.secrets.twitter_secret)
end
end
def image_url
client.user(user.twitter_handle).profile_image_uri(:bigger).to_s
end
end
|
require 'pry'
class SongsController < ApplicationController
get '/songs' do
@songs = Song.all
erb :"songs/index"
end
get '/songs/new' do
erb :"songs/new"
end
post '/songs' do
song = params[:song]
genres = song[:genres]
title = song[:title]
artist_name = song[:artist]
song = Song.new(title: title)
song.artist = Artist.find_or_create_by(name: artist_name)
genres.each do |genre|
song.genres << Genre.find_or_create_by(name: genre)
end
song.save
end
get '/songs/:slug' do
@song = Song.find_by_slug(params[:slug])
erb :"songs/show"
end
get "/songs/:id/edit" do
@song = Song.find_by(id: params[:id])
@action_url = "/#{@song.id}" if @song
erb :"songs/new"
end
patch '/songs/:id' do
song = params[:song]
genres = song[:genres]
title = song[:title]
artist_name = song[:artist]
song = Song.find_by(id: params[:id])
song.title = title
song.artist = Artist.find_or_create_by(name: artist_name)
song.genres.clear
genres.each_with_index do |genre, i|
g = Genre.find_or_create_by(name: genre) unless genre.empty?
song.genres << g unless g.nil?
end
song.save
redirect to "/songs/#{song.id}"
end
delete "/songs/:id" do
song = Song.find_by(id: params[:id])
song.destroy
redirect to "/songs"
end
end
|
require 'childprocess'
require 'shellwords'
module BankScrapToolkit
class Mitmproxy
TEMPLATE = <<-TEMPLATE.freeze
from __future__ import print_function
import json, sys
def start(context, argv):
context.output = open(argv[1], 'w')
context.join = None
print('[', file=context.output)
def done(context):
print(']', file=context.output)
context.output.close()
def response(context, flow):
str = json.dumps(flow.get_state())
if context.join:
print(',', file=context.output)
else:
context.join = True
print(str, file=context.output)
context.output.flush()
TEMPLATE
COMMAND = 'mitmproxy'.freeze
def initialize(port, filter = nil)
@script = ::Tempfile.new('mitmproxy-script')
@script.write(TEMPLATE)
@script.close
@output = ::Tempfile.new('mitmproxy-output')
@mitmproxy = ::ChildProcess.new(self.class::COMMAND,
'-z',
'-w', @output.path,
'-p', port.to_s,
*Array(filter)
)
@mitmproxy.io.inherit!
end
def start
@mitmproxy.start
@mitmproxy.wait
rescue Errno::ECHILD
false
end
def flows
@flows ||= BankScrapToolkit::Flow.parse(output_stream)
end
def output_stream
tmp = Tempfile.new('mitmdump')
output = ::ChildProcess.new('mitmdump',
'-nr', @output.path,
'-s', "#{@script.path} #{tmp.path}")
tmp.close
output.start
output.wait or raise 'could not export stream'
tmp.open
end
def stop
@mitmproxy.stop
end
end
end
|
# Determines purchase permissions for a user and IAP environment.
class PurchaseEnvironmentPolicy
# Assuming only itunes for now I guess
APPLE_TEST_ACCOUNTS = ['flyflyerson@gmail.com', 'apply_cvsxqwq_appleton@tfbnw.net']
class Error < StandardError
attr_reader :user, :receipt
def initialize(user:, receipt:)
@user = user
@receipt = receipt
super("User #{@user.id} may not create a purchase using the provided \
receipt from the iTunes #{receipt.itunes_environment} environment.")
end
end
# Returns false if the user is not allowed to create a purchase with the
# receipt.
def call(user:, receipt:)
@user = user
@receipt = receipt
receipt_matches_environment? || APPLE_TEST_ACCOUNTS.include?(@user.email)
end
def call!(user:, receipt:)
if !call(user: user, receipt: receipt)
raise Error.new(user: user, receipt: receipt)
end
end
def receipt_matches_environment?
return false if Rails.env.production? && @receipt.sandbox?
return true
end
end
|
class WordsController < PrivateController
def index
@words = Word.search(params[:word])
@word = Word.new(params.require(:word).permit(:text)) if params[:word].present?
@word = Word.new if !params[:word].present?
end
def new
@word = Word.new()
end
def create
# 登録する
@word = Word.new(params.require(:word).permit(:text))
if @word.save
#保存されたら @targetの詳細画面にリダイレクト
redirect_to action: 'index'
else
render 'not saved'
end
end
def edit
@word = Word.find(params[:id])
end
def update
word = Word.find(params[:id])
word.text = params[:word][:text]
if word.save
redirect_to action: 'index'
else
render 'not saved'
end
end
def destroy
word = Word.find(params[:id])
word.destroy
redirect_to action: 'index'
end
end
|
require 'time'
feature 'Showing the list of all peeps' do
before(:each) do
user = User.create(email: 'alice@example.com',
password: 'aliali',
username: 'useruser',
name: 'alice')
Peep.create(text: 'I am a peep',
date: Time.parse('2016-02-14 09:00:00'),
user: user)
end
scenario 'I can see the list of all peeps if I am not logged in' do
visit '/'
expect(page.status_code).to eq(200)
expect(page).to have_content('I am a peep')
end
end |
class Game
attr_reader :game_id,
:season,
:type,
:date_time,
:away_team_id,
:home_team_id,
:away_goals,
:home_goals
def initialize(game_data)
@game_id = game_data[:game_id].to_i
@season = game_data[:season].to_s
@type = game_data[:type]
@date_time = game_data[:date_time]
@away_team_id = game_data[:away_team_id]
@home_team_id = game_data[:home_team_id]
@away_goals = game_data[:away_goals].to_i
@home_goals = game_data[:home_goals].to_i
end
end
|
class GameBoard
def initialize
random_no = rand(5)
change_locations [random_no, random_no + 1, random_no + 2]
end
def check_yourself num
num = num.to_i
if @locations.include?(num)
@guessed << num unless @guessed.include?(num)
@no_of_hits += 1
if @locations.all? {|e| @guessed.include?(e)}
puts 'End'
return 'kill'
else
puts 'Hit'
end
else
puts 'Miss'
end
end
def change_locations loc
@locations = loc
@guessed = []
@no_of_hits = 0
end
def play
is_alive = true
no_of_guesses = 0
while is_alive
print 'Enter a number: '
STDOUT.flush
user_guess = gets.chomp
result = check_yourself user_guess
no_of_guesses += 1
if result == 'kill'
is_alive = false
puts "You took #{no_of_guesses} guesses"
end
end
initialize
end
end
if __FILE__ == $PROGRAM_NAME
gb = GameBoard.new
gb.play
end
|
require 'spec_helper'
describe Nymphia::DSL do
describe '#run' do
context 'when -f is given' do
subject(:cli) { Nymphia::CLI.new(['-f', 'examples/base.rb']) }
it 'contains nymphia header in stdout' do
expect { subject.run }.to output(/# This config is generated by Nymphia/).to_stdout_from_any_process
end
end
context 'when -o is given' do
let(:argv) { ['-f', 'examples/base.rb', '-o', 'tmp/config'] }
subject(:cli) { Nymphia::CLI.new(argv) }
before { subject.run }
after { File.delete('tmp/config') }
it 'puts to result to `config` file' do
expect(File.read('tmp/config')).to include '# This config is generated by Nymphia'
end
end
context 'without any options' do
subject(:cli) { Nymphia::CLI.new([]) }
it 'contains nymphia header in stdout' do
expect { subject.run }.to raise_error(ArgumentError)
end
end
end
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ :name => 'Chicago' }, { :name => 'Copenhagen' }])
# Mayor.create(:name => 'Daley', :city => cities.first)
User.create(email: "demo@email.com", password: "lamepress", roles_mask: "7")
issue = Issue.create(number: 1, published: true, date: Date.today, cover: File.new("#{Rails.root}/public/issue.png", "r"), pdf: File.new("#{Rails.root}/public/issue.pdf", "r"))
Setting.create(meta_key: "current_issue", meta_value: "#{issue.id}")
Setting.create(meta_key: "block_placement", meta_value: "top")
Setting.create(meta_key: "block_placement", meta_value: "left")
Setting.create(meta_key: "block_placement", meta_value: "right")
Block.create(position: 1, name: "cover", mode: "cover", partial: "cover", placement: "left")
block_top = Block.create(position: 1, name: "menu", mode: "navigator", partial: "menu", placement: "top")
category = Category.create(name: "Category", issued: 1)
Navigator.create(name: "Category", block_id: block_top.id, position: 1, navigatable_type: "Category", navigatable_id: category.id)
article = Article.create(title: "Lamepress CMS", published: true, category_id: category.id, issue_id: issue.id, date: Date.today, html: "Lamepress is a Content System Managment for issuing magazines/newspapers. It's written in Ruby language and rails framework. The deal of Lamepress is to make building and managing of magazines/newspapers as simple and easy as possible, also to give readers an easy way to browse current and older issues. Lamepress is under MIT Liecense.")
article.create_ordering(issue_pos: 1, cat_pos: 1)
|
class Gem::Commands::RepoCommand < Gem::Command
def initialize
super("repo", "Open github repository")
end
def execute
repo = options[:args].first
system "open http://github.com/#{repo}"
end
end |
require 'rails_helper'
feature 'signing-up' do
scenario 'visitor is able to sign up' do
visit root_path
within('#new_user') do
fill_in('First name', :with => 'Foo')
fill_in('Last name', :with => 'Bar')
fill_in('Email', :with => 'foo@bar.com')
fill_in('Password', :with => 'foobar123')
fill_in('Password confirmation', :with => 'foobar123')
find('#user_birthday_2i').click
find('#user_birthday_3i').click
find('#user_birthday_1i').click
find("#user_gender_female").set(true)
click_on('Sign Up')
end
expect(page).to have_content('User was successfully created.')
end
end
feature 'login' do
let(:user) { create(:user) }
scenario 'visitor is able to login' do
user
visit root_path
#within(:css, '')
fill_in('Email', :with => 'foo@bar.com')
fill_in('Password', :with => 'foobar123')
click_on('Sign Up')
expect(page).to have_content('You have successfully signed in.')
end
end
feature 'logout' do
let(:user){ create(:user) }
scenario 'logged in user can log out' do
user
log_in(user)
expect(page).to have_link('Logout', href: session_path)
click_link('Logout')
expect(page).to have_link('Login', href: new_session_path)
end
end
|
require "administrate/base_dashboard"
class ExtraPageDashboard < Administrate::BaseDashboard
# ATTRIBUTE_TYPES
# a hash that describes the type of each of the model's fields.
#
# Each different type represents an Administrate::Field object,
# which determines how the attribute is displayed
# on pages throughout the dashboard.
ATTRIBUTE_TYPES = {
user: Field::BelongsTo,
id: Field::Number,
extra_pages: Field::Number,
extra_page1: Field::Text,
extra_page2: Field::Text,
extra_page3: Field::Text,
extra_page4: Field::Text,
extra_page5: Field::Text,
extra_page6: Field::Text,
created_at: Field::DateTime,
updated_at: Field::DateTime,
is_complete: Field::Boolean,
}.freeze
# COLLECTION_ATTRIBUTES
# an array of attributes that will be displayed on the model's index page.
#
# By default, it's limited to four items to reduce clutter on index pages.
# Feel free to add, remove, or rearrange items.
COLLECTION_ATTRIBUTES = [
:user,
:id,
:updated_at,
:is_complete
].freeze
# SHOW_PAGE_ATTRIBUTES
# an array of attributes that will be displayed on the model's show page.
SHOW_PAGE_ATTRIBUTES = [
:user,
:id,
:extra_pages,
:extra_page1,
:extra_page2,
:extra_page3,
:extra_page4,
:extra_page5,
:extra_page6,
:created_at,
:updated_at,
:is_complete,
].freeze
# FORM_ATTRIBUTES
# an array of attributes that will be displayed
# on the model's form (`new` and `edit`) pages.
FORM_ATTRIBUTES = [
:user,
:extra_pages,
:extra_page1,
:extra_page2,
:extra_page3,
:extra_page4,
:extra_page5,
:extra_page6,
:is_complete,
].freeze
# Overwrite this method to customize how extra pages are displayed
# across all pages of the admin dashboard.
#
# def display_resource(extra_page)
# "ExtraPage ##{extra_page.id}"
# end
end
|
require('pg')
require('pry-byebug')
require_relative('../db/sql_runner')
class Book
attr_accessor :id, :title, :author_id, :buy_price, :sell_price
def initialize(options)
@id = options['id'].to_i
@title = options['title']
@author_id = options['author_id']
@buy_price = options['buy_price'].to_f
@sell_price = options['sell_price'].to_f
end
def save()
sql = "INSERT INTO books (
title,
author_id,
buy_price,
sell_price) VALUES (
'#{@title}',
'#{@author_id}',
#{@buy_price},
#{@sell_price})
RETURNING * "
book_info = run_sql(sql)
@id = book_info.first['id'].to_i
end
def author()
sql = "SELECT * FROM authors WHERE id = #{@author_id}"
author_info = run_sql(sql)
author = Author.new(author_info.first)
return author
end
def self.all
sql = "SELECT * FROM books"
books_info = run_sql(sql)
books = books_info.map {|book| Book.new(book)}
return books
end
def self.find(id)
sql = "SELECT * FROM books WHERE id = #{id}"
books = run_sql(sql)
result = Book.new(books.first)
return result
end
def self.update(options)
sql = "UPDATE books SET
title = '#{options['title']}',
author_id = #{options['author_id']},
buy_price = #{options['buy_price']},
sell_price = #{options['sell_price']}
WHERE id = #{options['id']}"
run_sql(sql)
end
def self.delete(id)
sql = "DELETE FROM books WHERE id = #{id}"
run_sql(sql)
end
def gross_profit
gross_profit = @sell_price - @buy_price
return (gross_profit)
end
def mark_up_percent()
gross_profit_margin = @sell_price - @buy_price
markup_percentage = (gross_profit_margin / @buy_price) * 100
return markup_percentage.round
end
end
|
# == Schema Information
#
# Table name: alerts
#
# id :bigint not null, primary key
# severity :integer default("info"), not null
# start_date :datetime
# end_date :datetime
# alertable_type :string
# alertable_id :bigint
# created_at :datetime not null
# updated_at :datetime not null
#
class Alert < ApplicationRecord
has_rich_text :message
belongs_to :alertable, polymorphic: true
enum severity: [:info, :primary, :success, :warning, :danger]
validates :severity, presence: true
def self.active
where("start_date <= ? AND end_date >= ?", Time.current, Time.current)
end
end
|
require 'spec_helper'
describe DataColumn do
# let(:array) { [1, 0, nil] }
let!(:column) { DataColumn.new([1, 0, nil])}
describe "sum" do
it "should return the sum of the non-nil values" do
column.sum.should == 1
end
end
describe "count" do
it "should return the number of non-nil values" do
column.count.should == 2
end
end
describe "mean" do
it "should return the average of the non-nil values" do
column.mean.should == 0.5
end
end
describe "median" do
it "should return the median of the non-nil values" do
column2 = DataColumn.new([nil, 0.1, 0.2, 0.3, 1000000, 0.0])
column.median.should == 0.5
column2.median.should == 0.2
end
end
describe "stdev" do
it "should return the sample standard deviation of the non-nil values" do
column.stdev.should be_within(0.01).of(1 / (2 ** 0.5))
end
end
describe "<<" do
it "should append to the column" do
column << 2
column.should == DataColumn.new([1,0,nil,2])
end
end
describe "to_a" do
it "should return the underlying array" do
column.to_a.should == [1,0,nil]
end
end
describe "bucketter" do
it "should return a bucketter that can classify the column entries evenly into categories" do
col1 = DataColumn.new([nil, 13, 14, 2, 3, 4, 5, 6, nil, 8, 9, 10, nil, 11.5, 12, nil])
bucketter = col1.bucketter(3)
bucketter.cutoffs.should == [5.5, 10.75]
bucketter.bucket(2).should == '(-Infinity, 5.5]'
bucketter.bucket(5).should == bucketter.bucket(2)
bucketter.bucket(6).should == '(5.5, 10.75]'
bucketter.bucket(10).should == bucketter.bucket(6)
bucketter.bucket(11).should == '(10.75, Infinity)'
bucketter.bucket(14).should == bucketter.bucket(11)
bucketter.bucket(nil).should == 'nil'
end
end
describe "#distribution" do
it "should return a sample distribution function of the data column" do
col = DataColumn.new([7, 7.2, 7.2, 8, 10, -1, 1.9, 2, 2.1, 3])
dist = col.sample_distribution
dist.proportion_under(-1.5).should == 0
dist.proportion_under(2.05).should == 0.3
dist.proportion_under(3).should == 0.4
dist.proportion_under(7.2).should == 0.6
dist.proportion_under(11).should == 1
end
it "should use the order, if given, on the data column values" do
col = DataColumn.new([:bad, nil, :good, :good, 100])
order = lambda{ |x,y| [:good, 100, "Hello, World!", nil, :bad].index(x) <=>
[:good, 100, "Hello, World!", nil, :bad].index(y) }
dist = col.sample_distribution(order)
dist.proportion_under(:good).should == 0
dist.proportion_under(100).should == 0.4
dist.proportion_under("Hello, World!").should == 0.6
dist.proportion_under(nil).should == 0.6
end
end
describe "#cast" do
it "should convert a string to a boolean if I tell it to" do
col = DataColumn.new(["true", "false", nil])
col.cast!(:boolean)
col.to_a.should == [true, false, nil]
end
it "should convert a string to a symbol if I tell it to" do
col = DataColumn.new(["one", "two", "three", nil])
col.cast!(:categorical)
col.to_a.should == [:one, :two, :three, nil]
end
it "should convert a string to a float if I tell it to" do
col = DataColumn.new(["0.01", "1", "-0.1", "-2", nil])
col.cast!(:numeric)
col.to_a.should == [0.01, 1, -0.1, -2, nil]
end
it "should not panic if we call this twice" do
col = DataColumn.new(["true"])
col.cast!(:boolean)
col.cast!(:boolean)
col.to_a.should == [true]
end
end
end |
# frozen_string_literal: true
class AddMlidsToChapters < ActiveRecord::Migration[6.0]
def up
execute <<~SQL
CALL update_records_with_unique_mlids('chapters', 2, 'organization_id');
SQL
end
def down
execute <<~SQL
ALTER TABLE chapters DROP COLUMN mlid;
SQL
end
end
|
require 'rails_helper'
RSpec.describe "Doctors", type: :request do
describe "GET /doctors" do
it "Recieve Status 200 in /GET Doctors" do
get doctors_path
expect(response).to have_http_status(200)
end
it "Recieve a JSON Array response in /GET Doctors" do
get doctors_path
parsed_body = JSON.parse(response.body)
expect(parsed_body.class).to eq(Array)
end
end
describe "POST /doctors" do
it "Recieve Status 201 in /POST Doctors" do
specialties = Specialty.create([{name: "Test Specialty 1"},{name: "Test Specialty 2"}])
post doctors_path(doctor: {name: "Doctor Test", crm:"crm test", phone: "phone_test", specialty_ids:[specialties[0].id,specialties[1].id]})
expect(response).to have_http_status(201)
end
end
end
|
module GithubLabels
LABELS_AND_COLOURS = {
"beginner friendly":"C2E0C6",
"Good First Issue":"D02AD6",
"Type: Question":"CC317C",
"Type: Feature/Redesign":"84B6EB",
"Type: Documentation":"5319E7",
"Type: Content Change":"663399",
"Type: Bug":"E11D21",
"Status: On Hold":"E11D21",
"Status: In Progress":"CCCCCC",
"Status: Duplicate":"FEF2C0",
"Status: Complete":"00FF2F",
"Status: Blocked":"E11D21",
"Help Wanted":"128A0C",
"hacktoberfest":"ffa500",
"Priority: Medium":"FBCA04",
"Priority: Low":"009800",
"Priority: Immediate Need":"000000",
"Priority: High":"EB6420",
"Priority: Critical":"E11D21",
"Needs: More Detail":"B60205",
"Needs: Copy/Content":"D4C5F9"
}
end
|
module TwirpRails
module ActiveRecordExtension
extend ActiveSupport::Concern
class_methods do
# Using to set twirp class used by to_twirp method
# @example
# twirp_message TwirpModel
def twirp_message(message_class)
@twirp_message = message_class
end
def twirp_message_class
@twirp_message = @twirp_message.constantize if @twirp_message.is_a?(String)
@twirp_message
end
def to_twirp(*args)
all.map { |entity| entity.to_twirp(*args) }
end
end
# Converts to twirp hash,
# @return [Hash] of attributes
# used by relation method to_twirp
# @param [Array|Class] fields_or_class - array of converted fields or message class to
def to_twirp(*fields_or_class)
if fields_or_class.empty? && self.class.twirp_message_class
to_twirp_as_class(self.class.twirp_message_class)
elsif fields_or_class.one? && fields_or_class.first.is_a?(Class)
to_twirp_as_class(fields_or_class.first)
elsif fields_or_class.any?
to_twirp_as_fields(fields_or_class)
else
attributes
end
end
private
def to_twirp_as_class(klass)
unless klass.respond_to?(:descriptor)
raise "Class #{klass} must be a protobuf message class"
end
# TODO performance optimization needed
to_twirp_as_fields(klass.descriptor.map &:name)
end
def to_twirp_as_fields(fields)
fields.each_with_object({}) do |field, h|
h[field] = attributes.fetch(field) { public_send(field) }
end
end
end
end
if defined? ActiveRecord::Base
ActiveRecord::Base.include TwirpRails::ActiveRecordExtension
end
|
shared_examples "a class highjacker" do
context 'class highjacking' do
let(:highjacked_class_name) { "Liquid::#{described_class.demodulized_name}" }
def highjacked_class
highjacked_class_name.split('::').inject(Object) { |klass, const_name| klass.const_get(const_name) }
end
after :each do
described_class.unload!
end
let!(:original_class_id) { highjacked_class.object_id }
it 'should be able to replace original class' do
expect{
described_class.load!
}.to change{ highjacked_class.object_id }.from(original_class_id).to(described_class.object_id)
end
it 'should be able to restore original class' do
described_class.load!
expect{
described_class.unload!
}.to change{ highjacked_class.object_id }.from(described_class.object_id).to(original_class_id)
end
end
end
|
class AddShippingCurrenciesToProducts < ActiveRecord::Migration
def change
add_column :products, :usd_domestic_shipping, :decimal, :precision => 8, :scale => 2
add_column :products, :usd_foreign_shipping, :decimal, :precision => 8, :scale => 2
rename_column :products, :domestic_shipping, :cad_domestic_shipping
rename_column :products, :foreign_shipping, :cad_foreign_shipping
end
end
|
class City < ActiveRecord::Base
has_many :neighborhoods
has_many :listings, through: :neighborhoods
extend Searchable
include Searchable::ListingHelpers
end
|
class Game
attr_reader :player1, :player2, :turn
def initialize(player1, player2)
@player1 = player1
@player2 = player2
@turn = 1
end
def attack
if @turn == 1
@turn = 2
attack_p2
else
@turn = 1
attack_p1
end
end
private
def attack_p1
@player1.reduce_hp
end
def attack_p2
@player2.reduce_hp
end
end
|
require 'spec_helper'
require 'erb'
describe TmuxStatus::Wrappers::Ifconfig do
before do
string = File.read("spec/fixtures/ifconfig_iface_#{iface_status}.txt")
template = ERB.new(string)
output = template.result(binding)
described_class.any_instance.stubs(ifconfig: output)
end
context 'when ppp0 interface is found' do
let(:iface_status) { :found }
let(:downloaded_bytes) { 1024 * 1024 * 23 }
let(:uploaded_bytes) { 1024 * 1024 * 5 }
it { should be_up }
its(:downloaded) { should eq(downloaded_bytes) }
its(:uploaded) { should eq(uploaded_bytes) }
end
context 'when ppp0 interface is not found' do
let(:iface_status) { :not_found }
it { should_not be_up }
its(:downloaded) { should be_nil }
its(:uploaded) { should be_nil }
end
end
|
require 'nokogiri'
module Peel
class Item
attr_accessor :uid, :arg, :valid, :autocomplete, :title, :subtitle, :mod_subtitles, :icon, :type, :object
def initialize(title, opts = {})
if title.length == 0 then raise ArgumentError.new('title must be non-zero') end
@uid = opts[:uid]
@arg = opts[:arg]
@valid = opts[:valid] != nil ? opts[:valid] : true
@autocomplete = opts[:autocomplete]
@title = title
@subtitle = opts[:subtitle]
@mod_subtitles = opts[:mod_subtitles] != nil ? opts[:mod_subtitles] : {}
@icon = opts[:icon]
@type = opts[:type] ? opts[:type] : 'default'
@object = opts[:object]
self
end
def add_to_xml(xml)
xml.item(:uid => @uid,
:arg => @arg,
:valid => @valid ? 'yes' : 'no',
:type => @type) {
xml.title @title
xml.subtitle @subtitle
@mod_subtitles.each_pair {|key, value| xml.subtitle(value, :mod => key)}
}
end
end
end
|
# frozen_string_literal: true
module Videos
# Service to get video
class GetService
def initialize(article, user)
@video = article
@user = user
end
def perform
Response::Success.new(@video)
end
private
def raise_errors
render nothing: true, status: 404 unless @video.status == 'published'
end
end
end
|
# This class is responsible for handling
# Requests from Com::Nbos::Core::MediaController.
# It will create the request based on Controller request params and
# send that request to Wavelabs API server and return the response back.
# While sending respose back to receiver it will create the virtual models
# from Com::Nbos::Api::DataModels
class WavelabsClientApi::Client::Api::Core::MediaApi < WavelabsClientApi::Client::Api::Core::BaseApi
MEDIA_URI = "/api/media/v0/media"
def get_media(user_id, media_for, access_token)
url_path = base_api_url(MEDIA_URI)
query_params = { :id => user_id, :mediafor => media_for}
api_response = send_request_with_token("get", url_path, access_token, nil, query_params)
build_media_response(api_response)
end
def upload_media(file_path, media_for, access_token, user_id)
url_path = base_api_url(MEDIA_URI)
query_params = { :id => user_id,
:mediafor => media_for
}
body = {:file => File.new(file_path)}
api_response = send_request_with_token("post", url_path, access_token, body, query_params)
File.delete(file_path) if !file_path.include?("/spec/support/")
build_media_response(api_response)
end
def build_media_response(api_response)
begin
if api_response.code == 200
media_model = create_media_model(api_response.parsed_response)
{status: 200, media: media_model}
end
rescue StandardError
message_model = create_message_model(nil)
message_model.message = "Internal Server Error Please Try After Some Time."
{ status: 500, message: message_model}
end
end
end |
class Brand < ActiveRecord::Base
has_and_belongs_to_many :stores
validates(:name, {:presence => true, :length => {:maximum => 100}})
end
|
require 'rspec'
require 'arabic_numeral'
#Test cases:
#Convert Arabic Number to Roman Numeral
#Number Numeral
#1 I
#3 III
#9 IX
#1066 MLXVI
#1989 MCMLXXXIX
RSpec.describe ArabicNumeral do
#Test error case
it 'to_roman_numeral errors out on unknown numbers' do
bad_arabic_number = ArabicNumeral.new(-1)
expect(bad_arabic_number.to_roman_numeral).to eq("Unknown number -1")
end
it 'convert_zero returns empty string' do
arabic_number = ArabicNumeral.new(0)
expect(arabic_number.convert_zero).to eq("")
end
#Test single character Roman numerals
it 'convert_ones converts number 1 to I correctly' do
arabic_number = ArabicNumeral.new(1)
expect(arabic_number.convert_ones(1)).to eq("I")
end
it 'convert_five coverts number 5 to V correctly' do
arabic_number = ArabicNumeral.new(5)
expect(arabic_number.convert_five).to eq("V")
end
it 'convert_tens converts number 10 to X correctly' do
arabic_number = ArabicNumeral.new(10)
expect(arabic_number.convert_tens(10)).to eq("X")
end
it 'convert_fifty converts number 50 to L correctly' do
arabic_number = ArabicNumeral.new(50)
expect(arabic_number.convert_fifty).to eq("L")
end
it 'convert_hundreds converts number 100 to C correctly' do
arabic_number = ArabicNumeral.new(100)
expect(arabic_number.convert_hundreds(100)).to eq("C")
end
it 'convert_five_hundred converts number 500 to D correctly' do
arabic_number = ArabicNumeral.new(500)
expect(arabic_number.convert_five_hundred).to eq("D")
end
it 'convert_thousands converts number 1000 to M correctly' do
arabic_number = ArabicNumeral.new(1000)
expect(arabic_number.convert_thousands(1000)).to eq("M")
end
it 'to_roman_numeral converts number 1 to I correctly' do
arabic_number = ArabicNumeral.new(1)
expect(arabic_number.to_roman_numeral).to eq("I")
end
it 'to_roman_numeral converts number 5 to V correctly' do
arabic_number = ArabicNumeral.new(5)
expect(arabic_number.to_roman_numeral).to eq("V")
end
it 'to_roman_numeral converts number 10 to X correctly' do
arabic_number = ArabicNumeral.new(10)
expect(arabic_number.to_roman_numeral).to eq("X")
end
it 'to_roman_numeral converts number 50 to L correctly' do
arabic_number = ArabicNumeral.new(50)
expect(arabic_number.to_roman_numeral).to eq("L")
end
it 'to_roman_numeral converts number 100 to C correctly' do
arabic_number = ArabicNumeral.new(100)
expect(arabic_number.to_roman_numeral).to eq("C")
end
it 'to_roman_numeral converts number 500 to D correctly' do
arabic_number = ArabicNumeral.new(500)
expect(arabic_number.to_roman_numeral).to eq("D")
end
it 'to_roman_numeral converts number 1000 to M correctly' do
arabic_number = ArabicNumeral.new(1000)
expect(arabic_number.to_roman_numeral).to eq("M")
end
#Test basic subtraction cases (4 is IV, 9 is IX, etc)
it 'to_roman_numeral converts 4 to IV correctly' do
arabic_number = ArabicNumeral.new(4)
expect(arabic_number.to_roman_numeral).to eq("IV")
end
it 'to_roman_numeral converts 9 to IX correctly' do
arabic_number = ArabicNumeral.new(9)
expect(arabic_number.to_roman_numeral).to eq("IX")
end
it 'to_roman_numeral converts 40 to XL correctly' do
arabic_number = ArabicNumeral.new(40)
expect(arabic_number.to_roman_numeral).to eq("XL")
end
it 'to_roman_numeral converts 90 to XC correctly' do
arabic_number = ArabicNumeral.new(90)
expect(arabic_number.to_roman_numeral).to eq("XC")
end
it 'to_roman_numeral converts 400 to CD correctly' do
arabic_number = ArabicNumeral.new(400)
expect(arabic_number.to_roman_numeral).to eq("CD")
end
it 'to_roman_numeral converts 900 to CM correctly' do
arabic_number = ArabicNumeral.new(900)
expect(arabic_number.to_roman_numeral).to eq("CM")
end
it 'convert_four converts 4 to IV correctly' do
arabic_number = ArabicNumeral.new(4)
expect(arabic_number.convert_four).to eq("IV")
end
it 'convert_nine converts 9 to IX correctly' do
arabic_number = ArabicNumeral.new(9)
expect(arabic_number.convert_nine).to eq("IX")
end
it 'convert_forty converts 40 to XL correctly' do
arabic_number = ArabicNumeral.new(40)
expect(arabic_number.convert_forty).to eq("XL")
end
it 'convert_ninety converts 90 to XC correctly' do
arabic_number = ArabicNumeral.new(90)
expect(arabic_number.convert_ninety).to eq("XC")
end
it 'convert_four_hundred converts 400 to CD correctly' do
arabic_number = ArabicNumeral.new(400)
expect(arabic_number.convert_four_hundred).to eq("CD")
end
it 'convert_nine_hundred converts 900 to CM correctly' do
arabic_number = ArabicNumeral.new(900)
expect(arabic_number.convert_nine_hundred).to eq("CM")
end
#Test repeating characters work correctly
it 'to_roman_numeral converts number 2 to II correctly' do
arabic_number = ArabicNumeral.new(2)
expect(arabic_number.to_roman_numeral).to eq("II")
end
it 'to_roman_numeral converts number 3 to III correctly' do
arabic_number = ArabicNumeral.new(3)
expect(arabic_number.to_roman_numeral).to eq("III")
end
it 'to_roman_numeral converts 20 to XX correctly' do
arabic_number = ArabicNumeral.new(20)
expect(arabic_number.to_roman_numeral).to eq("XX")
end
it 'to_roman_numeral converts number 30 to XXX correctly' do
arabic_number = ArabicNumeral.new(30)
expect(arabic_number.to_roman_numeral).to eq("XXX")
end
it 'to_roman_numeral converts 200 to CC correctly' do
arabic_number = ArabicNumeral.new(200)
expect(arabic_number.to_roman_numeral).to eq("CC")
end
it 'to_roman_numeral converts number 300 to CCC correctly' do
arabic_number = ArabicNumeral.new(300)
expect(arabic_number.to_roman_numeral).to eq("CCC")
end
it 'to_roman_numeral converts 2000 to MM correctly' do
arabic_number = ArabicNumeral.new(2000)
expect(arabic_number.to_roman_numeral).to eq("MM")
end
it 'to_roman_numeral converts number 3000 to MMM correctly' do
arabic_number = ArabicNumeral.new(3000)
expect(arabic_number.to_roman_numeral).to eq("MMM")
end
#Larger test cases from problem description
it 'to_roman_numeral converts 1066 to MLXVI' do
arabic_number = ArabicNumeral.new(1066)
expect(arabic_number.to_roman_numeral).to eq("MLXVI")
end
it 'to_roman_numeral converts 1989 to MCMLXXXIX' do
arabic_number = ArabicNumeral.new(1989)
expect(arabic_number.to_roman_numeral).to eq("MCMLXXXIX")
end
#Interesting edge cases
it 'to_roman_numeral converts 42 to XLII' do #Must include this somewhere :-)
arabic_number = ArabicNumeral.new(42)
expect(arabic_number.to_roman_numeral).to eq("XLII")
end
it 'to_roman_numeral converts 49 to XLIX' do
arabic_number = ArabicNumeral.new(49)
expect(arabic_number.to_roman_numeral).to eq("XLIX")
end
it 'to_roman_numeral converts 88 to LXXXVIII' do #Most repeating characters under 100
arabic_number = ArabicNumeral.new(88)
expect(arabic_number.to_roman_numeral).to eq("LXXXVIII")
end
it 'to_roman_numeral converts 99 to XCIX' do
arabic_number = ArabicNumeral.new(99)
expect(arabic_number.to_roman_numeral).to eq("XCIX")
end
it 'to_roman_numeral converts 150 to CL' do
arabic_number = ArabicNumeral.new(150)
expect(arabic_number.to_roman_numeral).to eq("CL")
end
it 'to_roman_numeral converts 499 to CDXCIX' do
arabic_number = ArabicNumeral.new(499)
expect(arabic_number.to_roman_numeral).to eq("CDXCIX")
end
it 'to_roman_numeral converts 888 to DCCCVXXXVIII' do #Most repeating characters under 1000
arabic_number = ArabicNumeral.new(888)
expect(arabic_number.to_roman_numeral).to eq("DCCCLXXXVIII")
end
it 'to_roman_numeral converts 999 to CMXCIX' do
arabic_number = ArabicNumeral.new(999)
expect(arabic_number.to_roman_numeral).to eq("CMXCIX")
end
it 'to_roman_numeral converts 1500 to MD' do
arabic_number = ArabicNumeral.new(1500)
expect(arabic_number.to_roman_numeral).to eq("MD")
end
it 'to_roman_numeral converts 3888 to MMMDCCCLXXXVIII' do #Most characters we can do with current character set
arabic_number = ArabicNumeral.new(3888)
expect(arabic_number.to_roman_numeral).to eq("MMMDCCCLXXXVIII")
end
it 'to_roman_numeral converts 3999 to MMMCMXCIX' do #Largest number we can handle with current set
arabic_number = ArabicNumeral.new(3999)
expect(arabic_number.to_roman_numeral).to eq("MMMCMXCIX")
end
end
|
class CreateSchemaGamedesk < ActiveRecord::Migration[5.2]
def change
execute "CREATE SCHEMA IF NOT EXISTS gamedesk"
end
end
|
# -*- encoding: utf-8 -*-
module OpenCalais
module Configuration
VALID_OPTIONS_KEYS = [
:api_key,
:adapter,
:endpoint,
:user_agent
].freeze
# this you need to get from open calais - go register!
DEFAULT_API_KEY = nil
# Adapters are whatever Faraday supports - I like excon alot, so I'm defaulting it
DEFAULT_ADAPTER = :excon
# The api endpoint to get REST info from opencalais
DEFAULT_ENDPOINT = 'https://api-eit.refinitiv.com/permid/calais'.freeze
# The value sent in the http header for 'User-Agent' if none is set
DEFAULT_USER_AGENT = "OpenCalais Ruby Gem #{OpenCalais::VERSION}".freeze
attr_accessor(*VALID_OPTIONS_KEYS)
# Convenience method to allow for global setting of configuration options
def configure
yield self
end
def self.extended(base)
base.reset!
end
class << self
def keys
VALID_OPTIONS_KEYS
end
end
def options
options = {}
VALID_OPTIONS_KEYS.each { |k| options[k] = send(k) }
options
end
# Reset configuration options to their defaults
def reset!
self.api_key = DEFAULT_API_KEY
self.adapter = DEFAULT_ADAPTER
self.endpoint = DEFAULT_ENDPOINT
self.user_agent = DEFAULT_USER_AGENT
self
end
end
end
|
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
helper_method :current_user, :signed_in?, :sign_in, :sign_out, :auth
def current_user
return nil unless session[:session_token]
@current_user ||= User.find_by(session_token: session[:session_token])
end
def signed_in?
!!current_user
end
def sign_in(user)
session[:session_token] = user.reset_session_token!
end
def sign_out
current_user.reset_session_token!
session[:session_token] = nil
@current_user = nil
end
def auth
{
cloud_name: dkk7qjv7c,
api_key: '499866761334525',
api_secret: G2OgkVTeeJGjkn6cNo6a9U7TYG0
}
end
end
|
class PostsController < ApplicationController
before_action :set_post, only: [:show, :edit, :update, :destroy]
before_action :set_course
before_action :authenticate_admin!, only: [:create, :update, :destroy]
def index
end
def show
end
def new
@post = @course.posts.new(params[:post])
@post.admin = current_admin
end
def edit
end
def create
@course.posts.sort { |a, b| a.order <=> b.order }
last_post = @course.posts.last
@post = @course.posts.new(post_params)
if !last_post.nil?
@post.order = last_post.order + 1
else
@posts.order = 1
end
@post.admin = current_admin
if @post.save
redirect_to [@course, @post], notice: 'Post was successfully created.'
else
render :new
end
end
def update
if @post.update(post_params)
redirect_to [@course, @post], notice: 'Post was successfully updated.'
else
render :edit
end
end
def destroy
@post.destroy
redirect_to course_path(@course), notice: 'Course post was successfully destroyed.'
end
private
def set_post
@post = Post.friendly.find(params[:id])
end
def set_course
@course = Course.friendly.find(params[:course_id])
end
def post_params
params.require(:post).permit(:name, :content)
end
end
|
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe Slack::RealTime::Store do
it 'can be initialized with an empty hash' do
store = described_class.new(Hashie::Mash.new)
expect(store.self).to be_nil
expect(store.groups.count).to eq 0
expect(store.team).to be_nil
expect(store.teams.count).to eq 0
end
it 'includes event handlers from superclass' do
Slack::RealTime::Stores::Store.on :channel_created, &proc {}
expect(described_class.events.key?('channel_created')).to be true
end
end
|
require 'github/markup'
class TaggedMarkdown < Struct.new(:string, :section_class)
def to_markdown
string.to_markdown.to_s rescue string.to_s
end
def to_html
'<section class="%s">%s</section>' % [Rack::Utils.escape_html(section_class), render_markdown(to_markdown)]
end
def render_markdown(s)
GitHub::Markup.render('section.markdown', s.to_s)
end
end |
class ChangePartsQuantity < ActiveRecord::Migration[5.0]
def change
change_column :parts, :quantity, :decimal
end
end
|
class User < ApplicationRecord
validates :name, presence: true
validates :email, presence: true, format: { with: /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i, message: "Email invalid" },
uniqueness: { case_sensitive: false },
length: { minimum: 4, maximum: 254 }
validates :email, uniqueness: true
has_secure_password
def User.digest string
cost = if ActiveModel::SecurePassword.min_cost
BCrypt::Engine::MIN_COST
else
BCrypt::Engine.cost
end
BCrypt::Password.create string, cost: cost
end
end
|
require 'mechanize'
module AmazonSellerCentral
class Mechanizer
MASQUERADE_AGENTS = ['Mac Safari', 'Mac FireFox', 'Linux Firefox', 'Windows IE 9']
attr_reader :agent
def initialize
@logged_in = false
end
def login_email
AmazonSellerCentral.configuration.login_email
end
def login_password
AmazonSellerCentral.configuration.login_password
end
def agent
@agent ||= Mechanize.new {|ag| ag.user_agent_alias = MASQUERADE_AGENTS[rand(MASQUERADE_AGENTS.size)] }
end
def last_page
agent.current_page
end
def login_to_seller_central
return true if @logged_in
page = agent.get('https://sellercentral.amazon.com/gp/homepage.html')
form = page.form_with(:name => 'signinWidget')
begin
form['username'] = login_email
form['password'] = login_password
p = form.submit
if p =~ /better protect/ # capcha!
raise CapchaPresentError.new("Holy CAPCHA Batman!")
end
@logged_in = !!( p.body =~ /Logout/ && p.body =~ /Manage Inventory/ )
rescue StandardError => e
File.open("/tmp/seller_central_#{Time.now.to_i}.html","wb") do |f|
f.write page.body
end
raise e
end
end
def follow_link_with(options)
raise AgentResetError unless last_page
link = last_page.link_with(options)
raise LinkNotFoundError unless link
agent.click(link)
end
def reset!
@agent = nil
@logged_in = false
#@last_page = nil
end
class LinkNotFoundError < StandardError; end
class AgentResetError < StandardError; end
class CapchaPresentError < StandardError; end
end
end
|
class SubscriptionsController < ApplicationController
before_action :authenticate_user!
before_action :find_media, only: [:create, :destroy]
def index
media = Media.where(user_ids: current_user.id).page(subscription_params[:page])
data = render_to_string partial: 'media/subscription', collection: media
render json: {status: 200, data: data}
end
def create
if @media.users << current_user
render json: { status: 200, msg: 'OK.'}
end
end
def destroy
if @media.users.delete(current_user)
render json: {status: 200, msg: 'OK.'}
end
end
private
def find_media
@media = Media.find(subscription_params[:id])
end
def subscription_params
params.permit(:page, :id)
end
end
|
class PagesController < ApplicationController
def about
@title = 'Sobre nosotros'
@content = 'Somos una empresa que lleva 38 años en el mercado.'
end
end
|
class Category < ActiveRecord::Base
belongs_to :bookmark_file
has_many :categories, dependent: :destroy
belongs_to :category
has_many :links, dependent: :destroy
def self.match?(str)
/\<H\d.*\>(.*)\<\/H\d\>/.match str
end
def self.match_ending?(str)
/\<\/DL/.match str
end
def parse(str)
md = /ADD_DATE\=\"(\d+)\"/.match str
self.add = Time.at( md ? md[1].to_i : 0 )
md = /LAST_MODIFIED\=\"(\d+)\"/.match str
self.last_modified = md ? Time.at(md[1].to_i) : nil
md = /(\"|1)\>(.*)\<\/H/.match str
self.name = md ? md[2] : nil
end
alias_method :bmf, :bookmark_file
def bookmark_file
path[-1].bmf
end
def path
p = [].unshift (c = self)
until c.bmf
c = c.category
p.unshift c
end
p
end
alias_method :cs, :categories
def categories(*opt)
opt[0] == :r ? categories_recurse : cs
end
def categories_recurse
cs = []
r = -> c { cs << c ; subcs = c.categories ; subcs.each &r unless subcs.empty? }
categories.each &r
cs
end
alias_method :ls, :links
def links(*opt)
opt[0] == :r ? links_recurse : ls
end
def links_recurse
arr = ls.to_a
categories.each { |c| arr.concat c.links(:r) }
arr
end
end
|
class UserGridWithCustomizedFormFieldsWindow < MasterWindow
js_properties :title => "User grid with customized form fields"
def default_config
{
:name => "User grid with customized form fields",
:width => 500,
:height => 350,
:minimizable => true,
:maximizable => true,
:persistence => true,
:icon_cls => "users",
:items => [{
:class_name => "UserGridWithCustomizedFormFields",
:header => false, :border => true
}]
}
end
end
|
require 'csv'
require_relative 'csv_file'
require_relative 'game_statistics'
require_relative 'game_team'
require_relative 'game'
require_relative 'team'
require_relative 'team_statistics'
require_relative 'season_statistics'
require_relative 'league_statistics'
class StatTracker
include Csv
attr_reader :game_table,
:team_table,
:game_team_table,
:locations
def initialize(locations = {})
@locations = locations
@game_table = {}
@team_table = {}
@game_team_table = []
csv_game_files
csv_team_files
csv_game_team_files
@team_statistics = TeamStatistics.new(@game_table, @team_table, @game_team_table)
@game_statistics = GameStatistics.new(@game_table)
@league_statistics = LeagueStatistics.new(@game_table, @team_table)
@season_statistics = SeasonStatistics.new(@game_table, @team_table, @game_team_table)
end
def self.from_csv(locations)
StatTracker.new(locations)
end
def team_info(team_id)
@team_statistics.team_info(team_id)
end
def best_season(team_id)
@team_statistics.best_season(team_id)
end
def worst_season(team_id)
@team_statistics.worst_season(team_id)
end
def average_win_percentage(team_id)
@team_statistics.average_win_percentage(team_id)
end
def most_goals_scored(team_id)
@team_statistics.most_goals_scored(team_id)
end
def fewest_goals_scored(team_id)
@team_statistics.fewest_goals_scored(team_id)
end
def favorite_opponent(team_id)
@team_statistics.favorite_opponent(team_id)
end
def rival(team_id)
@team_statistics.rival(team_id)
end
def highest_total_score
@game_statistics.highest_total_score
end
def lowest_total_score
@game_statistics.lowest_total_score
end
def percentage_home_wins
@game_statistics.percentage_home_wins
end
def percentage_visitor_wins
@game_statistics.percentage_visitor_wins
end
def percentage_ties
@game_statistics.percentage_ties
end
def count_of_games_by_season
@game_statistics.count_of_games_by_season
end
def average_goals_per_game
@game_statistics.average_goals_per_game
end
def average_goals_by_season
@game_statistics.average_goals_by_season
end
def count_of_teams
@league_statistics.count_of_teams
end
def best_offense
@league_statistics.best_offense
end
def worst_offense
@league_statistics.worst_offense
end
def highest_scoring_visitor
@league_statistics.highest_scoring_visitor
end
def highest_scoring_home_team
@league_statistics.highest_scoring_home_team
end
def lowest_scoring_visitor
@league_statistics.lowest_scoring_visitor
end
def lowest_scoring_home_team
@league_statistics.lowest_scoring_home_team
end
def winningest_coach(season)
@season_statistics.winningest_coach(season)
end
def worst_coach(season)
@season_statistics.worst_coach(season)
end
def most_accurate_team(season)
@season_statistics.most_accurate_team(season)
end
def least_accurate_team(season)
@season_statistics.least_accurate_team(season)
end
def most_tackles(season)
@season_statistics.most_tackles(season)
end
def fewest_tackles(season)
@season_statistics.fewest_tackles(season)
end
end
|
require_relative 'spec_helper'
require_relative '../tile_bag'
# KNK: I had initially thought that we'd want to start with a hash, where the keys are the letters and the values are the number of that particular tile. However, after chatting with Danielle, I think that the collection instance variable SHOULD actually be an array and that we use the shuffle and pop methods (I think you had that idea too), and that way we don't have to keep track of the number of each letter, we just have an array of the letters.
# Also, this will give weight to each letter based on how many of that letter we started with.
# The hash I created can be a constant -- it's a new tile bag's original set.
# The @collection instance variable should be an array and it can be created from the constant hash.
module Scrabble
describe TileBag do
let(:tiles){TileBag.new}
describe "#initialize" do
it "should be an instance of TileBag" do
# strategy: each instance of TileBag sets up new collection of tiles in a hash, where the key is the letter, and the value is the number of tiles of that letter.
# each of the methods on TileBag is an instance method (called on the new instance of TileBag.
tiles.must_be_instance_of(TileBag)
end
it "should respond to .collection with a array of tiles" do
# using attribute reader, @collection = collection, returns array
tiles.collection.must_be_kind_of(Array)
end
it "should include an 'A'" do
#should have another test in here that checks that the hash is populated with letters and has values of the number of tiles of that letter.
tiles.collection.must_include("A")
end
it "should start with 98 tiles" do
#upon initialization, there should be a full set of 98 tiles.
tiles.collection.length.must_equal(98)
end
end
describe "#draw_tiles(num)" do
it "should return the number of default tiles" do
# Strategy: create method with parameter 'num' that returns 'num' tiles and values by implementing 'tile.sample(num)' since each instance creates its own hash.
# draw_tiles method should update the value of the tile.collection hash (subtract one from the value of the tile drawn)
# this should return equal number of default tiles and the collection array should then reflect self - num of tiles drawn.
tiles.draw_tiles(7).must_be_kind_of(Array)
end
it "should return the same number of tiles that you asked for" do
#check that the array returned from this method is the correct length.
tiles_drawn = tiles.draw_tiles(7)
tiles_drawn.length.must_equal(7)
end
end
describe "#tiles_remaining" do
it "should return the number of tiles left in the bag" do
#returns the number of tiles left in the bag, not an array.
tiles.draw_tiles(5) #start with 98 tiles, remove 5 with draw_tiles method.
tiles.tiles_remaining.must_equal(93) #should now have 93 left.
end
end
end
end
|
class ChangeColumnName < ActiveRecord::Migration
def change
rename_column :activities, :hours, :hours
end
end
|
json.array!(@lendings) do |lending|
json.extract! lending, :id, :day_borrow, :day_estimated_return, :day_actual_return, :media_id, :user_id, :review
json.url lending_url(lending, format: :json)
end
|
class Links::Misc::DobberLineCombinations < Links::Base
def site_name
"Dobber Hockey"
end
def description
"Line Combinations"
end
def url
"http://www.dobberhockey.com/frozenpool_last3gamelines.php"
end
def group
3
end
def position
0
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.