text stringlengths 10 2.61M |
|---|
require 'spec_helper'
describe "Registering" do
let!(:setting) { create(:setting) }
let!(:game) { create(:game, name: "Clubs Frenzy") }
let!(:period) { create_list(:period, 4) }
let!(:user) { create(:user) }
context "unregistered visitors" do
it "should show the marketing page" do
visit root_path
page.should have_content("The most entertaining game for English football addicts")
end
it "should not allow access" do
visit newsitems_path
page.should_not have_content(I18n.t('.news.news_title'))
end
end
describe "registered users" do
context "regular users" do
before(:each) do
sign_in_as(user)
end
it "should show the dashboard" do
visit root_path
page.should have_content(I18n.t('.news.latest_news'))
end
it "should not show the frenzy administration page" do
visit frenzy_index_path
page.should_not have_content(I18n.t('frenzy.switch_participation'))
page.should have_content(I18n.t('.general.not_authorized'))
end
it "should show user small profile" do
visit root_path
page.should have_content(user.full_name)
end
end
context "admin users" do
before(:each) do
admin = create_user('admin')
sign_in_as(admin)
end
it "should show the dashboard" do
visit root_path
page.should have_content(I18n.t('.news.latest_news'))
end
it "should show user small profile" do
visit root_path
page.should have_content(user.full_name)
end
it "should show the frenzy administration page" do
visit frenzy_index_path
page.should have_content(I18n.t('frenzy.switch_participation'))
page.should_not have_content("You are not authorized to view that page")
end
end
end
end |
# frozen_string_literal: true
module FactoryBot
module Strategy
class FindOrCreate < FactoryBot::Strategy::Create
def result(evaluation)
database_attributes = evaluation.object.attribute_names.map(&:to_sym)
attribute_aliases = evaluation.object.attribute_aliases.keys.map(&:to_sym)
associations = evaluation.object.class.reflections.keys
where_attributes = evaluation.hash.dup.slice(*(database_attributes + attribute_aliases + associations))
instance = evaluation.object.class.where(where_attributes).first
if instance.present?
instance
else
super
end
end
end
end
end
FactoryBot.register_strategy(:find_or_create, FactoryBot::Strategy::FindOrCreate)
FactoryBot.allow_class_lookup = false
RSpec.configure do |config|
config.include FactoryBot::Syntax::Methods
config.before(:suite) do
begin
DatabaseCleaner.start
FactoryBot.lint
ensure
DatabaseCleaner.clean
end
end
end
|
class TimetablesController < ApplicationController
skip_before_action :authenticate_request
def index
@timetables = Timetable.all.select(:id,:weekday, :start_time, :end_time)
render json: @timetables
end
end
|
class Menu < ApplicationRecord
before_validation :set_empty_url
belongs_to :user
has_one :recipe
scope :recent, -> { order(schedule: :asc) }
private
def set_empty_url
self.url ||= ''
end
end
|
class OrderAddress
include ActiveModel::Model
attr_accessor :address_number, :area_id, :city, :house_number, :house_name, :phone_number, :user_id, :item_id, :token
ADDRESS_REGEX = /\A\d{3}-\d{4}\z/
PHONE_REGEX = /\A\d{10,11}\z/
with_options presence: true do
validates_format_of :address_number, with: ADDRESS_REGEX
validates :area_id, numericality: { other_than: 0 }
validates :city
validates :house_number
validates_format_of :phone_number, with: PHONE_REGEX
validates :user_id
validates :item_id
validates :token
end
def save
order = Order.create(user_id: user_id, item_id: item_id)
Address.create(address_number: address_number, area_id: area_id, city: city, house_number: house_number,
house_name: house_name, phone_number: phone_number, order_id: order.id)
end
end
|
class Route
attr_accessor :list, :first_station, :end_station
def initialize(first_station, end_station)
@first_station = first_station
@end_station = end_station
@list = [first_station, end_station]
end
def add_station_route(station)
list[-1] = station
list << end_station
end
def delete_station_route(station)
list.delete(station) if list.first.name != station.name && list.last.name != station.name
end
def route_list
list.each {|i| puts "Станция: #{i.name}." }
end
end |
require 'rails_helper'
describe 'deleting restaurants' do
context 'logged out' do
before do
Restaurant.create name: 'KFC', cuisine: 'Fast Food'
end
it 'cannot delete resturants' do
visit '/restaurants'
expect(page).not_to have_content 'Delete KFC'
end
end
context 'logged in as the restaurant creator' do
before do
user = User.create(email: 'test@test.com', password: '12345678', password_confirmation: '12345678')
login_as(user)
user.restaurants.create(name: 'KFC', cuisine: 'Fast Food')
end
it 'can delete restaurants' do
visit '/restaurants'
click_link 'Delete KFC'
expect(page).not_to have_content 'KFC'
expect(page).to have_content 'Restaurant successfully deleted'
end
end
context 'logged in as another user, not the restaurant creator' do
before do
user = User.create(email: 'test@test.com', password: '12345678', password_confirmation: '12345678')
another_user = User.create(email: 'test2@test.com', password: '12345678', password_confirmation: '12345678')
login_as(another_user)
user.restaurants.create(name: 'KFC', cuisine: 'Fast Food')
end
it 'cannot delete restaurants' do
visit '/restaurants'
click_link 'Delete KFC'
expect(page).to have_content 'Not your restaurant!'
expect(page).not_to have_content 'Restaurant successfully deleted'
end
end
end |
class Programming::TasksController < ApplicationController
before_filter :fix_params, only: [:new, :create, :update]
def index
@tasks = ProgrammingTask.all
end
def show
@task = ProgrammingTask.find_by_id(params[:id]) || not_found
end
def new
@task = ProgrammingTask.new
@task.programming_test_cases.build
@languages = ProgrammingLanguage.available
end
def create
@task = ProgrammingTask.new(params[:programming_task])
if @task.save
flash[:success] = "Programming Task Created!"
redirect_to @task
else
@languages = ProgrammingLanguage.available
render :new
end
end
def edit
@task = ProgrammingTask.find_by_id(params[:id]) || not_found
@languages = ProgrammingLanguage.available
end
def update
@task = ProgrammingTask.find_by_id(params[:id]) || not_found
if @task.update_attributes(params[:programming_task])
flash[:success] = "Programming Task Updated!"
redirect_to @task
else
@languages = ProgrammingLanguage.available
render :edit
end
end
def destroy
@task = ProgrammingTask.find_by_id(params[:id]) || not_found
@task.destroy
flash[:success] = "Programming Task Destroyed!"
redirect_to programming_tasks_path
end
private
def fix_params
ids = params[:programming_task][:programming_language_ids]
ids = ids.collect { |k, v| k unless v == '0' }
params[:programming_task][:programming_language_ids] = ids.compact
rescue
# m|n
end
end
|
class Member < ActiveRecord::Base
validates :name, :presence => true
validates :name, :uniqueness => true
validates :email, :presence => true
validates :email, :uniqueness => true
end
|
module ApplicationHelper
def T text, params = {}
t(text, params).capitalize
end
def f type, messages
flash[type] = messages
end
def glyphicon css
"<span class=\"glyphicon glyphicon-#{css}\" aria-hidden=\"true\"></span>".html_safe
end
def active_page(*paths)
active = false
paths.each { |path| active ||= current_page?(path) }
active ? "active" : ""
end
def has_error attribute
return "has-error" if flash[:danger] && flash[:danger].keys.include?(attribute)
end
end
|
class AddSiteToMember < ActiveRecord::Migration
def change
add_column :members, :personal_site, :string
add_column :members, :site2, :string
add_column :members, :site3, :string
end
end
|
#!/usr/bin/env ruby
# @package MiGA
# @license Artistic-2.0
$LOAD_PATH.push File.expand_path('../../lib', __FILE__)
$LOAD_PATH.push File.expand_path('../../lib', File.realpath(__FILE__))
require 'gfa'
input_gfa, input_gaf, output, degree, threads = ARGV
unless degree
$stderr.puts <<~HELP
gfa-add-gaf <input-gfa> <input-gaf> <output> <degree> [<pref> [<threads>]]
<input-gfa> Input GFA file to read
<input-gaf> Input GAF file to read
<output> Output GFA file to write
<degree> Maximum degree of separation between the segment set in the GAF
and any other included segments. If 0, only segments are
included. If 1, only the target segments, records linking to
them, and segments linked by those records. Any integer > 1
includes additional expansion rounds for those linked segments.
Use -1 to include the complete original GAF without subsetting.
<pref> A prefix to name all recorded paths
By default: Based on the GAF file name
<threads> If passed, parallelize process with these many threads
HELP
exit(1)
end
$stderr.puts "Loading GFA: #{input_gfa}"
gfa = GFA.load_parallel(input_gfa, (threads || 1).to_i)
$stderr.puts "Loading GAF: #{input_gaf}"
$stderr.puts "- Minimum identity: #{0.95}"
pref ||= File.basename(input_gaf, '.gaf').gsub(/[^!-)+-<>-~]/, '_')
segments = []
File.open(input_gaf, 'r') do |fh|
fh.each do |ln|
row = ln.chomp.split("\t")
opt = Hash[row[12..].map { |i| i.split(':', 2) }]
opt.each { |k, v| opt[k] = GFA::Field[v] }
next if opt['id'] && opt['id'].value < 0.95
gaf_path = row[5]
seg_names = []
gaf_path.scan(/[><]?[^><]+/).each do |seg|
seg_orient = seg.match?(/^</) ? '-' : '+'
seg_name = seg.sub(/^[><]/, '')
seg_names << "#{seg_name}#{seg_orient}"
segments << seg_name unless segments.include?(seg_name)
end
gfa << GFA::Record::Path.new(
"#{pref}_#{$.}", seg_names.join(','), opt['cg']&.value || '*'
)
end
end
$stderr.puts "- Found #{segments.size} linked segments"
degree = degree.to_i
if degree >= 0
$stderr.puts 'Subsetting graph'
gfa = gfa.subgraph(segments, degree: degree)
end
$stderr.puts "Saving GFA: #{output}"
gfa.save(output)
|
Rails.application.routes.draw do
namespace 'api' do
resources :holidays #Accede a la ruta /api/holidays
resources :users #Ruta para signup
resources :sessions #Ruta para signin
end
end
|
class Api::V1::UsersController < Api::ApiController
before_action :find_group, only: [:create]
def index
users = User.all
render json: users
end
def create
user = User.new(user_params)
if user.save
@group.users << user
render json: user, status: :created
else
render json: user.errors, status: :unprocessable_entity
end
end
protected
def user_params
params.require(:user).permit(:name, :email)
end
def find_group
@group = Group.find(params[:user][:group_id])
end
end
|
require 'active_model_serializers'
module ActiveModelSerializers
module Adapter
class SpreeAms < ActiveModelSerializers::Adapter::Json
def serializable_hash(options = nil)
options = serialization_options(options)
if options[:include_root]
serialized_hash = { root => serializable_array(options) }
else
serialized_hash = serializable_array(options)
end
serialized_hash[meta_key] = meta unless meta.blank?
serialized_hash = serialized_hash.merge(options.fetch(:pagination, {}))
self.class.transform_key_casing!(serialized_hash, instance_options)
end
def serializable_array(options)
Attributes.new(serializer, instance_options).serializable_hash(options)
end
end
end
end
|
# -*- encoding: utf-8 -*-
# stub: xclarity_client 0.6.5 ruby lib
Gem::Specification.new do |s|
s.name = "xclarity_client".freeze
s.version = "0.6.5"
s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib".freeze]
s.authors = ["Manasa Rao".freeze, "Rodney H. Brown".freeze]
s.bindir = "exe".freeze
s.date = "2018-10-22"
s.email = ["mrao@lenovo.com".freeze, "rbrown4@lenovo.com".freeze]
s.homepage = "https://github.com/lenovo/xclarity_client".freeze
s.rubygems_version = "2.6.14.1".freeze
s.summary = "Lenovo XClarity API Client".freeze
s.installed_by_version = "2.6.14.1" if s.respond_to? :installed_by_version
if s.respond_to? :specification_version then
s.specification_version = 4
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_development_dependency(%q<bundler>.freeze, ["~> 1.12"])
s.add_development_dependency(%q<rake>.freeze, ["~> 10.0"])
s.add_development_dependency(%q<rspec>.freeze, ["~> 3.0"])
s.add_development_dependency(%q<apib-mock_server>.freeze, ["~> 1.0.3"])
s.add_development_dependency(%q<webmock>.freeze, ["~> 2.1.0"])
s.add_runtime_dependency(%q<faraday>.freeze, ["~> 0.9"])
s.add_runtime_dependency(%q<faraday-cookie_jar>.freeze, ["~> 0.0.6"])
s.add_runtime_dependency(%q<httpclient>.freeze, ["~> 2.8.3"])
s.add_runtime_dependency(%q<uuid>.freeze, ["~> 2.3.8"])
s.add_runtime_dependency(%q<faker>.freeze, ["~> 1.8.3"])
s.add_runtime_dependency(%q<json-schema>.freeze, ["~> 2.8.0"])
else
s.add_dependency(%q<bundler>.freeze, ["~> 1.12"])
s.add_dependency(%q<rake>.freeze, ["~> 10.0"])
s.add_dependency(%q<rspec>.freeze, ["~> 3.0"])
s.add_dependency(%q<apib-mock_server>.freeze, ["~> 1.0.3"])
s.add_dependency(%q<webmock>.freeze, ["~> 2.1.0"])
s.add_dependency(%q<faraday>.freeze, ["~> 0.9"])
s.add_dependency(%q<faraday-cookie_jar>.freeze, ["~> 0.0.6"])
s.add_dependency(%q<httpclient>.freeze, ["~> 2.8.3"])
s.add_dependency(%q<uuid>.freeze, ["~> 2.3.8"])
s.add_dependency(%q<faker>.freeze, ["~> 1.8.3"])
s.add_dependency(%q<json-schema>.freeze, ["~> 2.8.0"])
end
else
s.add_dependency(%q<bundler>.freeze, ["~> 1.12"])
s.add_dependency(%q<rake>.freeze, ["~> 10.0"])
s.add_dependency(%q<rspec>.freeze, ["~> 3.0"])
s.add_dependency(%q<apib-mock_server>.freeze, ["~> 1.0.3"])
s.add_dependency(%q<webmock>.freeze, ["~> 2.1.0"])
s.add_dependency(%q<faraday>.freeze, ["~> 0.9"])
s.add_dependency(%q<faraday-cookie_jar>.freeze, ["~> 0.0.6"])
s.add_dependency(%q<httpclient>.freeze, ["~> 2.8.3"])
s.add_dependency(%q<uuid>.freeze, ["~> 2.3.8"])
s.add_dependency(%q<faker>.freeze, ["~> 1.8.3"])
s.add_dependency(%q<json-schema>.freeze, ["~> 2.8.0"])
end
end
|
# :nodoc:
class PassengerCar < Car
attr_reader :type
DEFAULT_SIZE = 50
def post_initialize
@type = :passenger
end
# def default_size
# 50
# end
def take_place
self.free_space = free_space - 1 if free_space > 0
end
end
|
def valid_palindrome(string)
return true if string.empty?
alpha_numeric_downcase_string = ""
string.each_char do |char|
if((char =~ /[[:alpha:]]/ )|| (char =~/[[:digit:]]/))
alpha_numeric_downcase_string += char.downcase
end
end
head_pointer = 0
tail_pointer = alpha_numeric_downcase_string.length - 1
while(head_pointer <= tail_pointer)
if alpha_numeric_downcase_string[head_pointer] != alpha_numeric_downcase_string[tail_pointer]
return false
end
head_pointer += 1
tail_pointer -= 1
end
return true
end
|
# encoding: UTF-8
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :set_post_params
before_filter :configure_permitted_parameters, if: :devise_controller?
rescue_from CanCan::AccessDenied do |exception|
redirect_to root_url, alert: t("labels.authorization.denied")
end
def set_post_params
resource = controller_name.singularize.to_sym
method = "#{resource}_params"
params[resource] &&= send(method) if respond_to?(method, true)
end
# Index Broadcrumpb
add_breadcrumb @breadcrump_index_name, :root_path
def not_own_object_redirection
raise ActiveRecord::RecordNotFound
end
# Parameters for Devise
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) << [:firstname, :lastname, :email, :roles_mask]
end
end
|
Rails.application.routes.draw do
devise_for :users
resources :users, :only => [:show]
resources :listings
root 'listings#index'
end
|
class Restaurant < ActiveRecord::Base
if Rails.env.development?
has_attached_file :image, :styles => { :medium => "200x", :thumb => "100x100>" }, :default_url => "default.gif"
else
has_attached_file :image, :styles => { :medium => "200x", :thumb => "100x100>" }, :default_url => "default.gif",
:storage => :dropbox,
:dropbox_credentials => Rails.root.join("config/dropbox.yml"),
:path => "tlcral/:id_:filename"
end
validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/
end
|
class UsersController < ApplicationController
def login
unless session[:current_user_id].nil? then
flash[:error] = "Please log out before attempting to log in."
redirect_to url_for(controller: :display, action: :home)
end
end
def logout
session[:current_user_id] = nil
redirect_to login_users_path
end
def new
# Comment the next line when in production
@user = User.new
# Uncomment the next six lines when in production
# if session[:current_user_id].nil? then
# flash[:error] = "You must be logged in."
# redirect_to login_users_path
# else
# @user = User.new
# end
end
def post_login
user = User.find_by_login params[:login]
if user && user.password_valid?(params[:password]) then
session[:current_user_id] = user.id
session[:user_first_name] = user.first_name
redirect_to url_for(controller: :display, action: :home)
else
flash[:error] = "Username and/or password is incorrect."
redirect_to login_users_path
end
end
def index
@users = User.all
end
def create
@user = User.new(user_params(params[:user]))
if @user.save then
redirect_to users_path
else
render new_user_path
end
end
private
def user_params(params)
return params.permit(:first_name, :last_name, :login, :password, :password_confirmation)
end
end |
require 'test_helper'
class Asciibook::Converter::ListingTest < Asciibook::Test
def test_convert_listing
doc = <<~EOF
[source]
----
def hello
puts "hello world!"
end
----
EOF
html = <<~EOF
<figure class="listing">
<pre>def hello
puts "hello world!"
end</pre>
</figure>
EOF
assert_convert_body html, doc
end
def test_convert_listing_with_attributes
doc = <<~EOF
[[id]]
[source, ruby]
.Title
----
def hello
puts "hello world!"
end
----
EOF
html = <<~EOF
<figure class="listing" id="id">
<figcaption>Title</figcaption>
<pre>def hello
puts "hello world!"
end</pre>
</figure>
EOF
assert_convert_body html, doc
end
def test_convert_listing_with_highlight
doc = <<~EOF
:source-highlighter: rouge
[[id]]
[source, ruby]
.Title
----
def hello
puts "hello world!"
end
----
EOF
html = <<~EOF
<figure class="listing" id="id">
<figcaption>Title</figcaption>
<pre class='rouge highlight'><code data-lang='ruby'><span class='k'>def</span> <span class='nf'>hello</span>
<span class='nb'>puts</span> <span class='s2'>\"hello world!\"</span>
<span class='k'>end</span></code></pre>
</figure>
EOF
assert_convert_body html, doc
end
end
|
class CreateLeads < ActiveRecord::Migration
def change
create_table :leads do |t|
t.string :name
t.string :email
t.string :phone
t.integer :site_id
t.integer :country_id
t.integer :language_id
t.string :ctoption_password
t.integer :account_balance
t.string :currency
t.string :from_db
t.timestamps
end
end
end
|
require 'rails_helper'
RSpec.describe FacebookController, :type => :controller do
describe '#create' do
before do
request.env['omniauth.auth'] = OmniAuth.config.mock_auth[:facebook]
end
it 'should create a new user via Facebook' do
expect(request.env['omniauth.auth']).to be_kind_of(Hash)
request.env['omniauth.auth']['credentials']['expires_at'] = Time.now + 1.week
post :create
expect(User.last.email_address).to eq("jeremy_rhvuhfx_wongwong@tfbnw.net")
end
end
end
|
class CreateUrlBuilderCampaignMediumships < ActiveRecord::Migration
def change
create_table :url_builder_campaign_mediumships do |t|
t.references :url_builder, index: true, foreign_key: true
t.references :campaign_medium, index: true, foreign_key: true
t.timestamps null: false
end
end
end
|
class Feed < ActiveRecord::Base
has_many :users, through: :subscriptions
has_many :posts
validates :type, presence: true
end
|
module Roby
module GUI
EVENT_CIRCLE_RADIUS = 3
TASK_EVENT_SPACING = 5
DEFAULT_TASK_WIDTH = 20
DEFAULT_TASK_HEIGHT = 10
ARROW_COLOR = Qt::Color.new('black')
ARROW_OPENING = 30
ARROW_SIZE = 10
TASK_BRUSH_COLORS = {
pending: Qt::Color.new('#6DF3FF'),
running: Qt::Color.new('#B0FFA6'),
success: Qt::Color.new('#E2E2E2'),
finished: Qt::Color.new('#E2A8A8'),
finalized: Qt::Color.new('#555555')
}
TASK_BRUSHES = Hash.new
TASK_BRUSH_COLORS.each do |name, color|
TASK_BRUSHES[name] = Qt::Brush.new(color)
end
TASK_PEN_COLORS = {
pending: Qt::Color.new('#6DF3FF'),
running: Qt::Color.new('#B0FFA6'),
success: Qt::Color.new('#E2E2E2'),
finished: Qt::Color.new('#E2A8A8'),
finalized: Qt::Color.new('#555555')
}
TASK_PENS = Hash.new
TASK_PEN_COLORS.each do |name, color|
TASK_PENS[name] = Qt::Pen.new(color)
end
TASK_NAME_COLOR = Qt::Color.new('black')
TASK_NAME_PEN = Qt::Pen.new(TASK_NAME_COLOR)
TASK_MESSAGE_COLOR = Qt::Color.new('#606060')
TASK_MESSAGE_PEN = Qt::Pen.new(TASK_MESSAGE_COLOR)
TASK_MESSAGE_MARGIN = 10
EVENT_NAME_COLOR = Qt::Color.new('black')
EVENT_NAME_PEN = Qt::Pen.new(EVENT_NAME_COLOR)
TASK_FONTSIZE = 10
PENDING_EVENT_COLOR = 'black' # default color for events
FIRED_EVENT_COLOR = 'green'
EVENT_FONTSIZE = 8
PLAN_LAYER = 0
TASK_LAYER = PLAN_LAYER + 20
EVENT_LAYER = PLAN_LAYER + 30
EVENT_PROPAGATION_LAYER = PLAN_LAYER + 40
FIND_MARGIN = 10
EVENT_CALLED = 1
EVENT_EMITTED = 2
EVENT_CALLED_AND_EMITTED = EVENT_CALLED | EVENT_EMITTED
EVENT_CONTROLABLE = 4
EVENT_CONTINGENT = 8
FAILED_EMISSION = 16
EVENT_STYLES = Hash.new
EVENT_STYLES[EVENT_CONTROLABLE | EVENT_CALLED] =
[Qt::Brush.new(Qt::Color.new(PENDING_EVENT_COLOR)),
Qt::Pen.new(Qt::Color.new(PENDING_EVENT_COLOR))]
EVENT_STYLES[EVENT_CONTROLABLE | EVENT_EMITTED] =
[Qt::Brush.new(Qt::Color.new(FIRED_EVENT_COLOR)),
Qt::Pen.new(Qt::Color.new(FIRED_EVENT_COLOR))]
EVENT_STYLES[EVENT_CONTROLABLE | EVENT_CALLED_AND_EMITTED] =
[Qt::Brush.new(Qt::Color.new(FIRED_EVENT_COLOR)),
Qt::Pen.new(Qt::Color.new(PENDING_EVENT_COLOR))]
EVENT_STYLES[EVENT_CONTINGENT | EVENT_EMITTED] =
[Qt::Brush.new(Qt::Color.new('white')), Qt::Pen.new(Qt::Color.new(FIRED_EVENT_COLOR))]
EVENT_STYLES[EVENT_CONTROLABLE | FAILED_EMISSION] =
[Qt::Brush.new(Qt::Color.new('red')), Qt::Pen.new(Qt::Color.new('red'))]
EVENT_STYLES[EVENT_CONTINGENT | FAILED_EMISSION] =
[Qt::Brush.new(Qt::Color.new('red')), Qt::Pen.new(Qt::Color.new('red'))]
TIMELINE_RULER_LINE_LENGTH = 10
end
end
|
require 'spec_helper'
describe "opendata_agents_parts_app", dbscope: :example do
let(:site) { cms_site }
let!(:parts) { create(:opendata_part_app) }
let(:index_path) { parts.url }
before do
create_once :opendata_node_search_app, basename: "app/search"
end
it "#index" do
page.driver.browser.with_session("public") do |session|
session.env("HTTP_X_FORWARDED_HOST", site.domain)
visit index_path
expect(current_path).to eq index_path
end
end
end
|
class Upload < ActiveRecord::Base
attr_accessor :file
validates_presence_of :city, :state
validates_numericality_of :latitude, greater_than_or_equal_to: -90, less_than_or_equal_to: 90
validates_numericality_of :longitude, greater_than_or_equal_to: -180, less_than_or_equal_to: 180
def self.import_csv(file_path)
failed = []
begin
SmarterCSV.process(file_path,{:chunk_size => 500}) do |chunk|
uploads = []
uploads = chunk.map{|r| Upload.new(r)}
failed << Upload.import(uploads, :validate => true).failed_instances
end
ensure
File.delete(file_path) if File.exist?(file_path)
end
return failed.flatten!
end
end
|
require 'spec_helper'
describe User do
let(:user) { FactoryGirl.build(:user) }
describe "#accounts" do
it "should return an array" do
user.accounts.class.should == Array
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)
Plan.create!(
amount: 0,
stripe_plan_id: Plan.stripe_plan_id.find_value(:free).value,
product_name: 'Free Plan',
)
Plan.create!(
amount: 1000,
stripe_plan_id: Plan.stripe_plan_id.find_value(:start).value,
product_name: 'Start Plan',
)
CURRENCY = 'jpy'
INTERVAL = 'month'
PRODUCT_TYPE = 'service'
# TODO:Planを作成時に同期する仕組みにできればベスト
# TODO:エラー処理
Plan.find_each do |plan|
Stripe::Plan.create(
id: plan.stripe_plan_id,
product: {
name: plan.product_name,
type: PRODUCT_TYPE
},
amount: plan.amount,
currency: CURRENCY,
interval: INTERVAL
)
end
|
module PageInmetrics
module Login
class Login < SitePrism::Page
set_url '/'
element :div_title, 'span[class*="title"]'
element :btn_cadastre_se, 'a[class*="tx"]'
element :input_user, '[name="username"]'
element :input_password, '[type="password"]'
element :btn_entrar, 'button[class*="btn"]'
def acessar_page_cadastro
wait_until_btn_cadastre_se_visible
btn_cadastre_se.click
end
def realizar_login(login)
dados = Manager.get_login(login)
input_user.set dados[:email]
input_password.set dados[:senha]
btn_entrar.click
end
end
end
end |
Rails.application.routes.draw do
namespace :api do
namespace :v1 do
root 'welcome#index'
resources :users, only: [:create, :index, :show]
resources :forums
resources :posts
resources :videos
resources :games
resources :comments
post '/login', to: 'auth#login'
get '/auto_login', to: 'auth#auto_login' #* USE MAYBE?!
get '/profile', to: 'users#profile'
get '/home', to: 'posts#home'
end
end
end
|
class CreateAcdAgents < ActiveRecord::Migration
def self.up
create_table :acd_agents do |t|
t.string :uuid
t.string :name
t.string :status
t.integer :automatic_call_distributor_id
t.datetime :last_call
t.integer :calls_answered
t.string :destination_type
t.integer :destination_id
t.timestamps
end
end
def self.down
drop_table :acd_agents
end
end
|
class Jasset < ActiveRecord::Base
mount_uploader :image, AssetUploader
validates_presence_of :title,:link_name,:link_uri
end |
require 'pry'
class Game
attr_accessor :board, :player_1, :player_2
WIN_COMBINATIONS = [ [0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[6,4,2]]
def initialize(player_1 = Players::Human.new("X"), player_2 = Players::Human.new("O"), board = Board.new)
@board = board
@player_1 = player_1
@player_2 = player_2
end
def current_player
@board.turn_count % 2 == 0 ? @player_1 : @player_2
end
def over?
draw? || won?
end
def won?
WIN_COMBINATIONS.detect do |combo|
@board.cells[combo[0]] == @board.cells[combo[1]] &&
@board.cells[combo[1]] == @board.cells[combo[2]] &&
@board.taken?(combo[0]+1)
end
end
def draw?
@board.full? && !won?
end
def winner
if winning_combo = won?
@winner = @board.cells[winning_combo[0]]
end
end
def turn
player = current_player
#<Players::Human:0x000000020bfde0>
# #def move(board)
# puts "Please Enter a move from 1 to 9"
# input = gets.chomp
# end
current_move = player.move(@board)
# will get output from user for example 2
# def valid_move?(pos)
# !taken?(pos) && pos.to_i.between?(1,9)
# end
if (!@board.valid_move?(current_move)) #will return true for a valid position , i
turn
else
puts "Turn: #{@board.turn_count}\n"
@board.display
@board.update(current_move, player)
puts "#{player.token} moved #{current_move}"
@board.display
end
end
def play
while !over?
turn
end
if won?
puts "Congratulations #{winner}!"
elsif draw?
puts "Cat's Game!"
end
end
##############################
end
|
#!/usr/bin/env ruby
#
# Powerful digit sum
# http://projecteuler.net/problem=56
#
# A googol (10**100) is a massive number: one followed by one-hundred zeros;
# 100**100 is almost unimaginably large: one followed by two-hundred zeros.
# Despite their size, the sum of the digits in each number is only 1.
#
# Considering natural numbers of the form, a**b, where a, b < 100, what is
# the maximum digital sum?
#
class Integer
def powerful_digit_sum
to_s.chars.map(&:to_i).inject(:+)
end
end
a = b = (1...100).to_a
p a.product(b).map {|a, b| (a**b).powerful_digit_sum }.max
# => 972
|
require 'menu_node'
class BluesFlingThreeController < ApplicationController
def registration
# TODO: Redirect through to the registration site.
end
private
# If no node has been set specifically we read the state from the request uri.
#
# TODO: A better mechanism for selecting the current URL
def current_menu_node(*args)
@current_menu_node ||= begin
request_path = args.first || request.path
# Find the deepest node in the menu matching that path. If that fails, return the first node.
#
# This has not been benchmarked and is purely random access at this point. It may make
# sense to b-tree the menu and work from that eventually.
#
# I skip the first element so that at no point do I consider root. It will always be the
# fallback node.
menu_root.flatten[1..-1].find { |n| n.url == request_path } || menu_root
end
end
helper_method :current_menu_node
# menu_root itself is the root node.
def menu_root
@menu_root ||= MenuNode.new do |root|
root.add 'Home', url: url_for(action: "index")
root.add 'Schedule', url: url_for(action: "schedule")
root.add 'Private lessons', url: url_for(action: "private_lessons")
root.add 'Instructors', url: url_for(action: "instructors")
root.add 'Register', url: url_for(action: "registration")
end
end
helper_method :menu_root
end
|
# Exercise 15: Reading Files
# https://learnrubythehardway.org/book/ex15.html
# Takes the first argument in the command line and stores as string in the variable filename
filename = ARGV.first
#gets method read the first line when the argument is a pth for a file
#filename = gets.chomp
puts filename
# open the file in the path "filename" and assign to the variable txt
txt = open(filename)
# Prints the path of the file and name
puts "Here's your file #{filename}"
#prints the content of the file
print txt.read
#close the file
txt.close()
# Ask for another file
# print "Type the filename again: "
# Stores the path of the file in a new variable
# file_again = $stdin.gets.chomp
# Open the file and assign it to a new variable
# txt_again = open(file_again)
# prints the content of the new file
# print txt_again.read
# Close the file
# txt_again.close()
|
require 'rails_helper'
RSpec.describe Game, type: :model do
let(:game) {create :game}
describe "validations" do
it "should not accept games without a name" do
game.name = nil
expect(game.save).to eq(false)
end
it "should not accept games without a player" do
game.white_player_id = game.black_player_id = nil
expect(game.save).to eq(false)
end
it "should not accept games where the two player IDs are the same" do
game.black_player_id = game.white_player_id = 5
expect(game.save).to eq(false)
end
it "should not accept games without a state" do
game.state = nil
expect(game.save).to eq(false)
end
it "should not accept games with a state that doesn't match one of the allowed values" do
game.state = "willy_nilly"
expect(game.save).to eq(false)
end
end
describe "DB constraints" do
it "should have white as unable to castle by default" do
expect(game.white_can_castle).to eq(false)
end
it "should have black as unable to castle by default" do
expect(game.black_can_castle).to eq(false)
end
it "should have white as next to move by default" do
expect(game.white_to_move).to eq(true)
end
it "should not allow a white player ID that doesn't correspond to a user" do
game = create :game
invalid_id = User.last.id + 1
game.white_player_id = invalid_id
expect{game.save}.to raise_error(ActiveRecord::InvalidForeignKey)
end
it "should not allow a black player ID that doesn't correspond to a user" do
game = create :game
invalid_id = User.last.id + 1
game.black_player_id = invalid_id
expect{game.save}.to raise_error(ActiveRecord::InvalidForeignKey)
end
end
describe "associations" do
it "should be associated with a user based on white_player_id" do
expect(game.white_player.class).to eq(User)
expect(game.white_player.id).to eq(game.white_player_id)
end
it "should be associated with a user based on black_player_id" do
expect(game.black_player.class).to eq(User)
expect(game.black_player.id).to eq(game.black_player_id)
end
it "should be associated with a number of pieces based on its ID" do
(1..2).each {create :piece, game_id: game.id}
game.pieces.each do |piece|
expect(piece).to be_kind_of(Piece)
expect(piece.game_id).to eq(game.id)
end
end
end
describe "scopes" do
it "should have an active scope that returns any games which have not yet ended in a draw or mate and no others" do
game_1 = create :game, state: "open"
game_2 = create :game, state: "white_in_check"
game_3 = create :game, state: "black_in_check"
game_4 = create :game, state: "white_in_mate"
active_games = Game.active
expect(active_games).to include(game_1)
expect(active_games).to include(game_2)
expect(active_games).to include(game_3)
Game.active.each do |game|
expect(game.state).to eq("open").or eq("white_in_check").or eq("black_in_check")
end
end
end
describe "Populate Board" do
it "should have correct number of pieces" do
expect(game.pieces.count).to eq (32)
end
it "should be empty on the squares" do
expect(game.pieces.where(rank: 3..6)).to eq([])
end
(1..8).each do |file|
it "should have a white pawn at rank 2, file #{file}" do
pieces = game.pieces.where(rank: 2 , file: file)
expect(pieces.count).to eq(1)
expect([pieces.first.type, pieces.first.color]).to eq(["Pawn", "white"])
end
it "should have a black pawn at rank 7, file #{file}" do
pieces = game.pieces.where(rank: 7 , file: file)
expect(pieces.count).to eq(1)
expect([pieces.first.type, pieces.first.color]).to eq(["Pawn", "black"])
end
end
{1 => "Rook", 2 => "Knight", 3 => "Bishop", 4 =>"Queen", 5 => "King", 6=> "Bishop", 7 => "Knight", 8 => "Rook"}.each do |file, type|
it "should have a correct type #{type} of white piece at rank 1, file #{file}" do
pieces = game.pieces.where(rank: 1 , file: file)
expect(pieces.count).to eq(1)
expect([pieces.first.type, pieces.first.color]).to eq([type, "white"])
end
it "should have a correct type #{type} of black piece at rank 8, file #{file}" do
pieces = game.pieces.where(rank: 8 , file: file)
expect(pieces.count).to eq(1)
expect([pieces.first.type, pieces.first.color]).to eq([type, "black"])
end
end
end
end
|
module Kuhsaft
class ImageSizeDelegator
def method_missing(method, *args, &block)
Kuhsaft::ImageSize.send(method, *args, &block)
rescue NoMethodError
super
end
end
class Engine < ::Rails::Engine
warn "[DEPRECATION] Kuhsaft has been replaced by qBrick. Please switch to qBrick as soon as possible."
isolate_namespace Kuhsaft
config.i18n.fallbacks = [:de]
config.i18n.load_path += Dir[Kuhsaft::Engine.root.join('config', 'locales', '**', '*.{yml}').to_s]
# defaults to nil
config.sublime_video_token = nil
# delegate image size config to ImageSize class
config.image_sizes = ImageSizeDelegator.new
initializer 'kuhsaft.initialize_haml_dependency_tracker' do
require 'action_view/dependency_tracker'
ActionView::DependencyTracker.register_tracker :haml, ActionView::DependencyTracker::ERBTracker
end
end
end
|
class User
attr_accessor :name
def initialize name="Foo"
@name = name
end
def == other
other.is_a?(self.class) && name == other.name
end
end
|
class AddFoundDescriptionToSearch < ActiveRecord::Migration
def change
add_column :searches, :found_description, :text
add_column :searches, :found_name, :string
add_column :searches, :found_email, :string
add_column :searches, :found_phone, :string
add_column :searches, :found_title, :string
add_column :searches, :found_location, :string
add_column :searches, :found_start_date, :datetime
add_column :searches, :found_end_date, :datetime
end
end
|
require_relative './marcxml'
require_relative './handle'
class Wip
attr_reader :handle, :marcxml, :marcxml_path
def initialize(path)
@marcxml_path = nil
@path = validate_path(path.dup)
@handle = get_handle
@marcxml = get_marcxml
end
private
def validate_path(path)
raise "directory does not exist: #{path}" unless File.exist?(path)
raise "directory is not readable: #{path}" unless File.readable?(path)
path
end
def get_handle
Handle.new(File.join(@path, 'handle'))
end
def get_marcxml
glob_str = File.join(@path, 'data', '*_marcxml.xml')
marcxml_paths = Dir.glob(glob_str)
raise "marcxml file count != 1" unless marcxml_paths.length == 1
@marcxml_path = marcxml_paths[0]
Marcxml.new(@marcxml_path)
end
end
|
require 'station'
describe Station do
let(:station){described_class.new('oxford', 1)}
it 'does have a name' do
expect(station.name).to eq 'oxford'
end
it 'does have a zone' do
expect(station.zone).to eq 1
end
end
|
class Tefl < ActiveRecord::Base
belongs_to :user
linkformat = /\A(http:\/\/|https:\/\/)\w+\.\w+/
validates :name, :uniqueness => :true
validates :link, :uniqueness => :true, :format => linkformat
end
|
module ActiveRecord
class Base
class << self
def forbid_implicit_checkout!
Thread.current[:active_record_forbid_implicit_connections] = true
end
def implicit_checkout_forbidden?
!!Thread.current[:active_record_forbid_implicit_connections]
end
def connection_with_forbid_implicit(*args, &block)
if implicit_checkout_forbidden? && !connection_handler.retrieve_connection_pool(self).active_connection?
message = 'Implicit ActiveRecord checkout attempted when Thread :force_explicit_connections set!'
# I want to make SURE I see this error in test output, even though
# in some cases my code is swallowing the exception.
$stderr.puts(message) if Rails.env.test?
fail ImplicitConnectionForbiddenError, message
end
connection_without_forbid_implicit(*args, &block)
end
alias_method_chain :connection, :forbid_implicit
end
end
# We're refusing to give a connection when asked for. Same outcome
# as if the pool timed out on checkout, so let's subclass the exception
# used for that.
ImplicitConnectionForbiddenError = Class.new(::ActiveRecord::ConnectionTimeoutError)
end
|
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :null_session
respond_to :json
rescue_from StandardError, with: :handle_exception
rescue_from Docker::Error::ServerError do |ex|
handle_exception(ex, :docker_connection_error)
end
def handle_exception(ex, message=nil, &block)
log_message = "\n#{ex.class} (#{ex.message}):\n"
log_message << " " << ex.backtrace.join("\n ") << "\n\n"
logger.error(log_message)
message = message.nil? ? ex.message : t(message, default: message)
block.call(message) if block_given?
# If we haven't already rendered a response, use default error handling
# logic
unless performed?
render json: { message: message }, status: :internal_server_error
end
end
def log_kiss_event(name, options)
KMTS.record(user_id, name, options)
rescue => ex
logger.warn(ex.message)
end
def user_id
User.instance.primary_email || panamax_id
end
def panamax_id
ENV['PANAMAX_ID'] || ''
end
def template_repo_provider
if id = params[:template_repo_provider].presence
TemplateRepoProvider.find(id)
else
TemplateRepoProvider.find_or_create_default_for(User.instance)
end
end
end
|
require "rails_helper"
describe CreatePodcast do
context ".create" do
let(:podcast) { create(:podcast) }
subject(:create_podcast) { described_class.create({collectionId: podcast.itunes_id}) }
it "enqueues" do
expect(GetEpisodesJob).to receive(:perform_later)
create_podcast
end
context "when podcast exists in database" do
let!(:podcast) { create(:podcast) }
it "retrieves podcast" do
expect{
subject
}.to_not change(Podcast, :count)
end
end
context "when podcast dpes not exists in database" do
it "retrieves podcast" do
expect{
subject
}.to change(Podcast, :count).by(1)
end
end
end
end
|
$:.push File.expand_path("../lib", __FILE__)
require 'sinatra/base'
require 'sequel'
require 'uuidtools'
require 'json'
require 'eventmachine'
require 'faye'
require 'ruby_melee'
class RubyMeleeApp < Sinatra::Base
PROD_DB_URL = ENV['RM_PROD_DB_URL']
set :public_folder, 'public'
def initialize
init_db
super
end
get '/' do
redirect '/index.html'
end
get '/new' do
# create a new melee
container_handle = warden_client.launch_container
melee = Melee.create :container_handle => container_handle, :content => "def print_time\n puts Time.now\nend\n\nprint_time"
@guid = melee.guid
redirect "/melee/#{@guid}"
end
get '/melee/*' do
melee = Melee.where(:guid => params[:splat]).first
halt 404 if melee.nil?
@guid = melee.guid
@content = melee.content
@client_guid = UUIDTools::UUID.random_create.to_s
erb :melee_layout do
erb :melee
end
end
post '/melee/*' do
melee = Melee.where(:guid => params[:splat]).first
halt 404 if melee.nil?
content_type :json
@guid = melee.guid
handle = melee.container_handle
melee.update :content => request.POST['content']
output, new_handle = warden_client.run handle, melee.content
melee.update :container_handle => new_handle if new_handle != handle
em_thread = Thread.new {
EM.run {
client = Faye::Client.new('http://faye.rubymelee.com/melee')
client.publish("/#{@guid}/update", { 'content' => melee.content, 'output' => output }.to_json )
client.disconnect
}
}
halt 200
end
:private
def init_db
# inspect ruby env
@db = ENV['RUBY_ENV'] == 'production' ? Sequel.connect(PROD_DB_URL) : Sequel.sqlite
@db.loggers << Logger.new($stdout)
Sequel.extension :migration
Sequel::Migrator.apply(@db, './migrations/')
require './models'
end
def warden_client
File.exist?('/tmp/warden.sock') ? RubyMelee::WardenClient : RubyMelee::FakeWardenClient
end
end |
class CareerCourse < ActiveRecord::Base
belongs_to :career
belongs_to :course
end
|
# spec/user_spec.rb
require 'rails_helper'
RSpec.describe User, type: :model do
describe ".create" do
context "given user is not yet logged in" do
it "has no user info" do
expect(User.new().email).to be_empty
end
end
end
describe "check email" do
context "given new user logged in" do
it "has an email" do
expect(User.new().email).to eql(auth.info.email)
end
end
end
end
|
module Bisu
class Config
def initialize(hash:)
@hash = hash.deep_symbolize
@hash.validate_structure!(CONFIG_STRUCT)
unless dict_struct = DICTIONARY_STRUCT[@hash[:dictionary][:type]]
raise ArgumentError.new("unknown dictionary type '#{@hash[:dictionary][:type]}'")
end
@hash[:dictionary].validate_structure!(dict_struct)
end
def to_h
@hash
end
def dictionary
@hash[:dictionary]
end
def type
@hash[:type]
end
def localize_files
@hash[:translate].each do |t|
@hash[:languages].each do |l|
downcase_locale = l[:locale].downcase.gsub("-", "_").gsub(" ", "_")
yield(t[:in], (t[:"out_#{downcase_locale}"] || t[:out]) % l, l[:language], l[:locale])
end
end
end
private
CONFIG_STRUCT = {
type: Hash,
elements: {
type: { type: String },
dictionary: { type: Hash, elements: {
type: { type: String }
} },
translate: { type: Array, elements: {
type: Hash, elements: {
in: { type: String },
out: { type: String }
}
} },
languages: { type: Array, elements: {
type: Hash, elements: {
locale: { type: String },
language: { type: String }
}
} }
}
}
GOOGLE_SHEET_STRUCT = {
type: Hash,
elements: {
type: { type: String },
sheet_id: { type: String },
keys_column: { type: String }
}
}
ONE_SKY_STRUCT = {
type: Hash,
elements: {
api_key: { type: String },
api_secret: { type: String },
project_id: { type: Integer },
file_name: { type: String }
}
}
DICTIONARY_STRUCT = {
"google_sheet" => GOOGLE_SHEET_STRUCT,
"one_sky" => ONE_SKY_STRUCT
}
end
end
|
Factory.define :user do |user|
user.name "Ted Rosen"
user.email "ted@rosen.net"
user.password "foobar"
user.password_confirmation "foobar"
end
|
Rails.application.routes.draw do
resources :locations, except: [:update, :edit, :destroy]
root 'locations#index'
end
|
module Admin
class EventsController < ApplicationController
def index
@search = Event.search(params[:q])
@events = @search.result(distinct: true)
end
def show
@event = Event.find(params[:id])
end
def new
@event = Event.new
end
def create
@event = Event.new(event_params)
respond_to do |format|
if @event.save
format.html { redirect_to admin_events_path, notice: 'Event was successfully created.' }
format.json { render action: 'show', status: :created, location: @event }
else
format.html { render action: 'new' }
format.json { render json: @events.errors, status: :unprocessable_entity }
end
end
end
private
def event_params
params.require(:event).permit(
:id,
:employee_id,
:store_id,
:starts_at,
:ends_at,
:pause,
:vacation,
:sick,
:comment
)
end
end
end |
module CassandraCQL
class Statement
def self.sanitize(statement, bind_vars=[])
return statement if bind_vars.empty?
bind_vars = bind_vars.dup
expected_bind_vars = statement.count("?")
raise Error::InvalidBindVariable, "Wrong number of bound variables (statement expected #{expected_bind_vars}, was #{bind_vars.size})" if expected_bind_vars != bind_vars.size
statement.gsub(/\?/) do
quote(cast_to_cql(bind_vars.shift))
end
end
end
end
module CassandraObject
module Connection
extend ActiveSupport::Concern
module ClassMethods
def cql
@@cql ||= CassandraCQL::Database.new(config.servers, {keyspace: config.keyspace}, config.thrift_options)
end
def execute_cql(cql_string, *bind_vars)
statement = CassandraCQL::Statement.sanitize(cql_string, bind_vars).force_encoding(Encoding::UTF_8)
ActiveSupport::Notifications.instrument("cql.cassandra_object", cql: statement) do
cql.execute statement
end
end
end
end
end
|
# A calendar event
class Event < ActiveRecord::Base
belongs_to :source
before_validation :ensure_organizer
validates_presence_of :title, :start_date, :end_date, :description, :organizer
include PgSearch
pg_search_scope :search_by_content, against: [:title,
:description,
:organizer]
def self.paginated(opts = {})
page = opts[:page]
per_page = opts[:per_page]
event = Event.arel_table
if page && per_page
self.paginate(page: page, per_page: per_page)
else
self.all
end
end
def self.filter_by_date(opts = {})
start_date = opts[:start_date]
end_date = opts[:end_date]
event = Event.arel_table
if start_date && end_date
self.where(event[:start_date].gt(start_date))
.where(event[:end_date].lt(end_date))
elsif start_date && !end_date
self.where(event[:start_date].gt(start_date))
elsif !start_date && end_date
self.where(event[:end_date].gt(end_date))
else
self.all
end
end
private
def ensure_organizer
self.organizer = source.name if organizer.nil?
end
end
|
class AddConfirmedByToWorkunit < ActiveRecord::Migration
def change
add_reference :workunits, :confirmed_by_id, index: true
end
end
|
FactoryGirl.define do
sequence :metasploit_model_author_name do |n|
"Metasploit::Model::Author #{n}"
end
trait :metasploit_model_author do
name { generate :metasploit_model_author_name }
end
end |
require "utley/version"
Dir[File.dirname(__FILE__) + '/utley/*.rb'].each {|file| require file }
module Utley
def self.publish events
events.each do |event|
subscribers = Utley::Subscriber.for(event)
subscribers.each do |subscriber|
subscriber.receive event
end
end
end
end
|
require 'httparty'
module DeepThought
module Scaler
def self.scale
if (ENV['RACK_ENV'] != 'development' && ENV['RACK_ENV'] != 'test') && (ENV['HEROKU_APP'] && ENV['HEROKU_APP'] != '') && (ENV['HEROKU_API_KEY'] && ENV['HEROKU_API_KEY'] != '')
if Delayed::Job.count > 0
scale_up
else
scale_down
end
end
end
private
def self.scale_up
options = {:body => {:type => 'worker', :qty => '1'}, :basic_auth => {:username => '', :password => ENV['HEROKU_API_KEY']}}
HTTParty.post("https://api.heroku.com/apps/#{ENV['HEROKU_APP']}/ps/scale", options)
end
def self.scale_down
options = {:body => {:type => 'worker', :qty => '0'}, :basic_auth => {:username => '', :password => ENV['HEROKU_API_KEY']}}
HTTParty.post("https://api.heroku.com/apps/#{ENV['HEROKU_APP']}/ps/scale", options)
end
Delayed::Backend::ActiveRecord::Job.class_eval do
after_destroy :after_destroy
def after_destroy
DeepThought::Scaler.scale
end
end
end
end
|
require File.expand_path "../test_helper", __FILE__
context "Rugged::Config tests" do
setup do
@repo = Rugged::Repository.new(test_repo('testrepo.git'))
end
test "can read the config file from repo" do
config = @repo.config
assert_equal 'false', config['core.bare']
assert_nil config['not.exist']
end
test "can read the config file from path" do
config = Rugged::Config.new(File.join(@repo.path, 'config'))
assert_equal 'false', config['core.bare']
end
test "can read the global config file" do
config = Rugged::Config.open_global
assert_not_nil config['user.name']
assert_nil config['core.bare']
end
test "can write config values" do
config = @repo.config
config['custom.value'] = 'my value'
config2 = @repo.config
assert_equal 'my value', config2['custom.value']
content = File.read(File.join(@repo.path, 'config'))
assert_match /value = my value/, content
end
test "can delete config values" do
config = @repo.config
config.delete('core.bare')
config2 = @repo.config
assert_nil config2.get('core.bare')
end
end
|
class CreateQuestions < ActiveRecord::Migration
def change
create_table :questions do |t|
t.text :answer
t.text :question
t.integer :question_id
t.integer :value
t.string :category_title
t.integer :category_id
t.date :airdate
t.timestamps null: false
end
end
end
|
Rails.application.routes.draw do
resources :shopping_carts
resources :orders
resources :users
resources :clothes
root to: 'clothes#home'
get '/home', to: 'clothes#home'
end
|
Rails.application.routes.draw do
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
resources :items
resources :authors
resources :tags
#get "items" => "items#index"
#get "items/:id" => "items#show"
#post "create" => "items#create"
#put "items" => "items#update"
#delete "items" => "items#destroy"
end
|
class Listitem < ActiveRecord::Base
validates :title, presence: true, length: {minimum: 5, maximum: 50}
validates :description, presence: true, length: {minimum: 5, maximum: 5000}
belongs_to :todolist
end
|
class RemoveDepartmentFromProperties < ActiveRecord::Migration
def change
remove_column :properties, :department
end
end
|
class AuditDigest
attr_accessor :audit,
:audit_report,
:audit_field,
:sample_group,
:audit_structure,
:audit_strc_type,
:user
def new_audit(audit_id)
raise ArgumentError unless audit_id.present?
audit = Audit.includes(audit_structure: [:sample_groups, :physical_structure]).find(audit_id)
Retrocalc::AuditJsonPresenter.new(audit).as_json
end
def audits_list
Audit.all.map do |audit|
Retrocalc::AuditJsonPresenter.new(audit, top_level_only: true)
end.as_json
end
def audit_fields_list
audit_fields_json = AuditField.uniq(:api_name).order(:id).map do |audit_field|
options = audit_field.field_enumerations.order(:display_order).pluck(:value)
{ name: audit_field.name,
value_type: audit_field.value_type,
api_name: audit_field.api_name,
options: options
}
end
render json: { audit_fields: audit_fields_json }
end
def structure_types_list
response = AuditStrcType.uniq(:api_name).order(:id).map do |audit_strc_type|
next if audit_strc_type.api_name == 'audit'
Retrocalc::StructureTypeJsonPresenter.new(audit_strc_type).as_json
end.compact
return response
end
end |
module IqSMS
class Message
def self.message_to_hash(message)
hash = {
clientId: message.client_id,
phone: message.phone,
text: message.text
}
hash[:wap_url] = message.wap_url if message.respond_to?(:wap_url) && message.wap_url.present?
hash[:sender] = message.sender if message.sender.present?
hash[:flash] = '1' if message.respond_to?(:flash) && message.flash.present?
hash
end
def self.message_to_hash_for_status(message)
{
clientId: message.client_id,
smscId: message.smsc_id
}
end
attr_reader :client_id,
:smsc_id,
:phone,
:text,
:wap_url,
:sender,
:flash,
:status
def initialize(client_id:,
phone:,
text:,
wap_url: nil,
sender: nil,
smsc_id: nil,
status: nil,
flash: false)
@client_id = client_id
@phone = phone
@text = text
@wap_url = wap_url
@sender = sender
@smsc_id = smsc_id
@status = MessageStatus.new(status: status, client_id: client_id, smsc_id: smsc_id)
@flash = flash
end
def flash?
@flash
end
def to_hash
self.class.message_to_hash(self)
end
end
end
|
class Admin::NewsController < ApplicationController
before_filter :require_admin
layout 'admin'
def index
@title = 'Nieuws'
@news = News.order("id desc").paginate :page => params[:page], :per_page => 50
end
def new
@news = News.new
end
def create
@news = News.new(params[:news].merge(:user_id => current_user.id))
if @news.save
redirect_to admin_news_index_path, notice: "Nieuws gemaakt"
else
render :new
end
end
def edit
@news = News.find(params[:id])
end
def update
@news = News.find(params[:id])
if @news.update_attributes(params[:news])
redirect_to admin_news_index_path, notice: "Nieuws bijgewerkt"
else
render :edit
end
end
end
|
# ==========================================================================
# Project: Lebowski Framework - The SproutCore Test Automation Framework
# License: Licensed under MIT license (see License.txt)
# ==========================================================================
module Lebowski
module Foundation
#
# Represents a SproutCore Core Query object. This proxy provides a subset of the
# functionality that the actual core query object has.
#
# The core query is obtained through a view object and requires a CSS selector.
# Based on the associated view and given selector, the core query object will
# then contain zero or more DOM elements that match the selector starting from
# the view's layer (read: root DOM element).
#
# For feature and integration testing, the use of the core query object may be
# too low-level. Rather, this object is handy for custom views that override
# the render method. By creating a proxy to the custom view you can then use
# this object to do some fine grained checks that you don't want to expose
# to the casual tester, for instance.
#
class CoreQuery
INVALID_HANDLE = -1
attr_reader :selector, # The CSS selector
:handle, # The handle to the remote core query object
:abs_path # The absolute path to the view this object comes from
#
# Creates an instance. Once created, it will have a handle to the remote
# core query object in order to perform subsequent calls. Call the done()
# method when this object is no longer used
#
# @param abs_path {String} a property path to the view the core query object will come from
# @param selector {String} a CSS selector. See SproutCore's CoreQuery object for more details
# @param driver {Object} driver to communicate with the selenium server
#
def initialize(abs_path, selector, driver)
@abs_path = abs_path
@selector = selector.nil? ? "" : selector
@driver = driver
@handle = INVALID_HANDLE
@size = 0
@handle = @driver.get_sc_core_query(abs_path, selector)
@size = @driver.get_sc_core_query_size(@handle) if has_handle?
end
#
# Returns the number of elements found by this core query object
#
def size()
return @size if has_handle?
return -1
end
#
# Checks if this object has a handle to the remote core query object
#
def has_handle?()
return (not @handle == INVALID_HANDLE)
end
#
# Will clean up this object when no longer used
#
def done()
@driver.sc_core_query_done(@handle)
@handle = INVALID_HANDLE
end
#
# Get an element at a given index. Returns an instance of DOMElement
#
# @param index {Number} returns element if this object has a handle and
# the index is within range
#
def [](index)
if has_handle? and (index > -1) and (index <= (@size - 1))
return Lebowski::Foundation::DOMElement.new @handle, index, @driver
end
return nil
end
#
# Used to iterate through each element in this object. The block provided
# will be provided to argments: the element and its index. You can use this
# method as follows:
#
# core_query.each do |element, index |
# ...
# end
#
def each(&block)
return if (not has_handle? or not block_given? or size <= 0)
for i in 0..size - 1 do
elem = Lebowski::Foundation::DOMElement.new @handle, i, @driver
yield elem, i
end
end
#
# Used to fetch elements from this object. The block provided
# is used to return an element that will be added to the array
# of elements to be returned. If the block does not return an
# element then the element will not be added to the resulting
# array. As an example:
#
# elements = core_query.fetch { |element, index| element if element.text == 'foo' }
#
# The result array will then contain all elements in the core query
# object that have text equal to 'foo'. if no elements match then
# an empty array is returned.
#
# The block provided is to have the following setup:
#
# do |element, index| OR { |element, index| ... }
# ...
# end
#
def fetch(&block)
return [] if not block_given?
elems = []
each do |elem, index|
result = yield elem, index
elems << result if not result.nil?
end
return elems
end
#
# Used to perform a check on the elements from this core query. The
# block provided is used to return true or false based of if the
# given element passed some condition. In addition to the block
# supplied to this method, you also pass in a condition about the
# check being perform, which can be one of the following:
#
# :all - Check that all elements meet the block's checks
# :any - Check that one or more elements meet the block's checks
# :none - Check that no elements meet the block's checks
# :one - Check that there is only one element that meets the block's checks
#
# If no condition argument is gien this :all is the default.
#
# Here is an example of how to use this method:
#
# meets_condition = core_query.check :all, do |elem, index|
# if elem.text == 'foo'
# true # element passes check
# else
# false # element does not pass check
# end
# end
#
# @see #all?
# @see #any?
# @see #none?
# @see #one?
#
def check(condition=nil, &block)
return false if not block_given?
counter = 0
each do |elem, index|
result = yield elem, index
counter = counter + 1 if result == true
end
case condition
when :all
return counter == size
when :any
return counter > 0
when :none
return counter == 0
when :one
return counter == 1
else
return counter == size
end
end
#
# Used to check if all of the element for this core query meet
# the conditions for the given block
#
# @see #check
#
def all?(&block)
check :all &block
end
#
# Used to check if any of the element for this core query meet
# the conditions for the given block
#
# @see #check
#
def any?(&block)
check :any &block
end
#
# Used to check if none of the element for this core query meet
# the conditions for the given block
#
# @see #check
#
def none?(&block)
check :none &block
end
#
# Used to check if there is only one element for this core query that
# meets the conditions for the given block
#
# @see #check
#
def one?(&block)
check :one &block
end
alias_method :element, :[]
end
end
end |
require 'ostruct'
module Midishark
module Parser
class Basic < Base
@@ip_match = /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/
@@full_match = /^(#{@@ip_match})\s+(#{@@ip_match})\s+(\d+)\s+(\d+)$/
# Public: Parses a basic input line in the format of:
#
# <srcip> <dstip> <srcport> <dstport>
def parse(line)
line.strip!
match = line.match(@@full_match)
return unless match
source_ip, destination_ip, source_port, destination_port = match[1..4]
OpenStruct.new(
:source_ip => source_ip,
:destination_ip => destination_ip,
:source_port => source_port.to_i,
:destination_port => destination_port.to_i
)
end
end
end
end
|
When(/^I open the homepage$/) do
@home.load
end |
class Chat < ActiveRecord::Base
scope :between, -> (sender_id,recipient_id) do
where("(chats.sender_id = ? AND chats.recipient_id =?) OR (chats.sender_id = ? AND chats.recipient_id =?)", sender_id,recipient_id, recipient_id, sender_id)
end
end
|
#!/usr/bin/env ruby
# encoding: utf-8
require 'yaml'
require_relative './board'
class Minesweeper
attr_reader :board
def initialize
@board = Board.new
end
def play
while (!@board.lost? && !@board.won?)
@board.display
puts "Enter 'r' to reveal and 'f' to flag a tile. Enter 's' if you want to save your game and return later."
action = gets.chomp
save if action == 's'
puts "Enter row number (1-9)."
row = gets.chomp.to_i
puts "Enter column number (1-9)."
col = gets.chomp.to_i
if action == "f"
@board.flag(row-1, col-1)
elsif action == "r"
@board.reveal(row-1, col-1)
end
end
finish
end
def save
p "Enter a file name"
file_name = gets.chomp
File.open(file_name, 'w') { |file| file.write(self.to_yaml)}
abort
end
def finish
@board.display_actual
puts @board.won? ? "You won!" : "You lost!"
end
end
if __FILE__ == $PROGRAM_NAME
p "Enter a save file if you would like to resume (else ENTER)."
save_file = gets.chomp
if save_file.empty?
game = Minesweeper.new
else
game = YAML::load_file(save_file)
end
game.play
end |
# frozen_string_literal: true
colors = []
print 'Введите цвет. Для окончания введите "stop": '
loop do
color = gets.chomp
break if color == 'stop'.downcase
print 'Еще?: '
colors << color
end
print colors.reject(&:empty?).uniq.sort
# p (colors & colors).reject(&:empty?)
|
module CVE
class Vulnerability
SOFTWARE_EXTRACT_REGEXP = Regexp.new('[(, ]([^(), ]+)')
def initialize(data)
unless data.instance_of?(Hash)
raise 'CVE Vulnerability needs to be initialized with a hash'
end
if malformed?(data)
raise 'CVE Vulnerability data is malformed'
end
@identifier = data[:identifier]
@date = data[:date]
@description = data[:description]
@link = data[:link]
@title = data[:title]
@affected_software = extract_software_from_title(data[:title])
end
attr_reader :identifier, :date, :description, :link, :title, :affected_software
def malformed?(data)
!(data.has_key?(:identifier) && data.has_key?(:date) && data.has_key?(:description) &&
data.has_key?(:link) && data.has_key?(:title))
end
def extract_software_from_title(title)
software = []
title.scan(SOFTWARE_EXTRACT_REGEXP) do |scan|
software << scan[0]
end
software.count == 0 ? nil : software
end
def affected_count
@affected_software.nil? ? 0 : @affected_software.count
end
def equal?(cve_item, strict=false)
return false unless cve_item.is_a?(Vulnerability)
if strict
return @identifier == cve_item.identifier && @link == cve_item.link && @date.utc.iso8601 == cve_item.date.utc.iso8601 &&
@title == cve_item.title && @description == cve_item.description
end
@identifier == cve_item.identifier && @link == cve_item.link
end
def to_s
"#{@title} - #{@link}"
end
def to_hash
{
:identifier => @identifier,
:title => @title,
:link => @link,
:description => @description,
:date => @date,
:affected_software => @affected_software
}
end
def inspect
"#<CVE::Vulnerability id=#{@identifier} affected=#{affected_count}>"
end
end
end
|
FactoryBot.define do
factory :editor do
user { FactoryBot.create(:user) }
end
end
|
class UserSerializer < ActiveModel::Serializer
attributes :id, :name
end
class CommentSerializer < ActiveModel::Serializer
attributes :id, :body
has_one :author, serializer: UserSerializer
end
class PostSerializer < ActiveModel::Serializer
attributes :id, :title, :body, :watch_count
has_many :comments, serializer: CommentSerializer
has_one :author, serializer: UserSerializer
end
|
require_relative 'line'
require_relative 'word'
require_relative 'text_box'
require_relative 'table'
require_relative 'table_column'
module ConditionedParser
module Model
# constructs and aggregates model data
class ModelBuilder
def self.build_line(words)
words.sort_by!(&:x_start)
Line.new(surrounding_box_for(words), words)
end
def self.build_lines(words, options = {})
# TODO: Spacing option
lines = []
words = words.dup
until words.empty?
new_line = [words.shift]
(new_line << words.select { |word| word.on_same_line?(new_line.last, options) }).flatten!
words.reject! { |word| word.on_same_line?(new_line.last, options) }
lines << build_line(new_line)
end
lines
end
def self.build_blocks_from_lines(lines, _options = {})
# TODO: outer distance option for blocks
[TextBox.new(surrounding_box_for(lines), lines)]
end
def self.build_blocks_from_words(words, options = {})
lines = build_lines(words)
build_blocks_from_lines(lines, options)
end
def self.build_table(table_words, table_region, column_definitions)
# Table rows are assumed to always be a line, hence row definitions
# do solely rely on actual content instead of outside definitions
content_as_lines = build_lines(table_words)
columns = build_table_columns(table_region, column_definitions)
Table.new(table_region.box, columns, content_as_lines)
end
def self.build_table_column(box, name, options)
TableColumn.new(box, name, options)
end
def self.build_table_columns(table_region, column_definitions)
current_col_x_start = table_region.x_start
column_definitions.each_with_object([]) do |col_def, cols|
col_box = define_box(current_col_x_start, table_region.y_start, current_col_x_start + col_def[:width], table_region.y_end)
cols << build_table_column(col_box, col_def[:name], col_def[:options])
current_col_x_start += col_def[:width]
end
end
def self.define_search_region(box)
# TODO: This is kind of a misuse of Regions to define search boxes
# It does not feel as though this part of the gem should be able to
# define stuff belonging to the templating
table_region = Region.new(:search)
table_region.box = box
table_region
end
def self.surrounding_box_for(content_elements)
{
x_start: content_elements.min_by(&:x_start).x_start,
x_end: content_elements.max_by(&:x_end).x_end,
y_start: content_elements.min_by(&:y_start).y_start,
y_end: content_elements.max_by(&:y_end).y_end
}
end
def self.define_box(x_start, y_start, x_end, y_end)
{
x_start: x_start,
y_start: y_start,
x_end: x_end,
y_end: y_end
}
end
end
end
end
|
module Categories
class Creator
attr_reader :errors
def initialize(params)
@params = params
@errors = []
end
def call
return category if category.save
errors << category.errors.full_messages
nil
end
private
attr_reader :params
def safe_params
params
.require(:category)
.permit(
:name,
:state
)
end
def category
@category ||= Category.new(safe_params.merge(vertical: vertical))
end
def vertical
@vertical ||= Vertical.find(params[:vertical_id])
end
end
end
|
require "application_system_test_case"
class ComicsTest < ApplicationSystemTestCase
setup do
@comic = comics(:one)
end
test "visiting the index" do
visit comics_url
assert_selector "h1", text: "Comics"
end
test "creating a Comic" do
visit comics_url
click_on "New Comic"
fill_in "Alt", with: @comic.alt
fill_in "Day", with: @comic.day
fill_in "Img", with: @comic.img
fill_in "Link", with: @comic.link
fill_in "Month", with: @comic.month
fill_in "News", with: @comic.news
fill_in "Num", with: @comic.num
fill_in "Safe title", with: @comic.safe_title
fill_in "Title", with: @comic.title
fill_in "Transcript", with: @comic.transcript
fill_in "Year", with: @comic.year
click_on "Create Comic"
assert_text "Comic was successfully created"
click_on "Back"
end
test "updating a Comic" do
visit comics_url
click_on "Edit", match: :first
fill_in "Alt", with: @comic.alt
fill_in "Day", with: @comic.day
fill_in "Img", with: @comic.img
fill_in "Link", with: @comic.link
fill_in "Month", with: @comic.month
fill_in "News", with: @comic.news
fill_in "Num", with: @comic.num
fill_in "Safe title", with: @comic.safe_title
fill_in "Title", with: @comic.title
fill_in "Transcript", with: @comic.transcript
fill_in "Year", with: @comic.year
click_on "Update Comic"
assert_text "Comic was successfully updated"
click_on "Back"
end
test "destroying a Comic" do
visit comics_url
page.accept_confirm do
click_on "Destroy", match: :first
end
assert_text "Comic was successfully destroyed"
end
end
|
class Rules
attr_accessor :failed, :fails
class Fails
def initialize
@fails = []
end
def add(failure)
@fails << failure
end
def to_s
# data structure is a little convoluted
# so i'm doing a lot of array access below to navigate
# the data structure
# FIXME by cleaning up the data struture to be cleaner
# FIXME by extracting this response template to a new function
if @fails[0] && @fails[0].length > 0
msg = %{\nThe following rules were violated.
}
@fails[0].each do |file|
msg += %{\nFile: #{file[:file_name]} matches the following rules. \n }
file.each do |failure|
coerced = failure[1][0]
fail_msg = coerced[:rule][:msg]
match_count = coerced[:matches].length unless coerced[:matches] == 0
if match_count
msg += %{ rule "#{fail_msg}" matches #{match_count} times \n }
end
end
end
msg
else
return ""
end
end
end
def initialize
@rules = []
@fails = Rules::Fails.new
end
def add(rule)
@rules << rule
end
def apply(file_set)
# return a array of simple options
results = []
file_set.each do |file|
next if File.directory? file
file_handle = File.new file
cur = { :file_name => file, :matches => [] }
@rules.collect do |rule|
file_handle.rewind
_mat = file_handle.grep rule[:rule]
if !_mat.nil? && _mat.length > 0
cur[:matches] << {:rule => rule, :matches => _mat}
end
end
if cur[:matches] && cur[:matches].length > 0
results << cur
self.failed = true
end
end
@fails.add results unless results.size == 0
## after all of this, i think we want @fails to be a little object with a to string on it
@fails
end
end
class Globs
# want to add root_dir as accessor
# as well as exclusions as a list
#class << self
def initialize( root_dir = "." )
@root_dir = root_dir
end
def scripts
list = %x(find #{@root_dir} -name "*js" | egrep -v "#{excludes}")
list.split /\n/
end
def views
list = %x(find #{@root_dir} -name "*js" -or -name "*erb" -or -name "*html" | egrep -v "#{excludes}")
list.split /\n/
end
def stylesheets
list = %x(find #{@root_dir} -name "*css" | egrep -v "#{excludes}")
list.split /\n/
end
private
def excludes
'(./vendor|tiny_mce/plugins|./test/static/fixtures/)'
end
#end
end
|
class Netty::HttpServer::Request
attr_accessor :content
def initialize(request)
@request = request
@content = ''
end
def method
@request.method
end
def uri
@request.uri
end
def contains_header(name)
@request.contains_header(name)
end
def get_header(name)
@request.get_header(name)
end
def headers
@request.headers
end
# def trailers
# end
def http_version
@request.protocol_version
end
def chunked?
@request.chunked?
end
end |
class AddBroadcastCountToSongs < ActiveRecord::Migration
def change
add_column :songs, :user_broadcasts_count, :integer, :default => 0
end
def add
# Updates every save
# Broadcast.all.each do |b|
# b.save
# end
end
end
|
class ResponseOption < ActiveRecord::Base
include RankedModel
belongs_to :question
belongs_to :factor
belongs_to :cheetah_factor
validates_presence_of :question_id
ranks :row_order, :with_same => :question_id
end
|
FactoryGirl.define do
factory :user do
sequence(:email) { |n| "link#{n}@hyrulecastle.com" }
first_name 'Link'
last_name 'Courage'
password 'zelda1212'
password_confirmation 'zelda1212'
end
end
|
class AttendeeTypesController < ApplicationController
# GET /attendee_types
# GET /attendee_types.xml
def index
@attendee_types = AttendeeType.all
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @attendee_types }
end
end
# GET /attendee_types/1
# GET /attendee_types/1.xml
def show
@attendee_type = AttendeeType.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @attendee_type }
end
end
# GET /attendee_types/new
# GET /attendee_types/new.xml
def new
@attendee_type = AttendeeType.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @attendee_type }
end
end
# GET /attendee_types/1/edit
def edit
@attendee_type = AttendeeType.find(params[:id])
end
# POST /attendee_types
# POST /attendee_types.xml
def create
@attendee_type = AttendeeType.new(params[:attendee_type])
respond_to do |format|
if @attendee_type.save
flash[:notice] = 'AttendeeType was successfully created.'
format.html { redirect_to(@attendee_type) }
format.xml { render :xml => @attendee_type, :status => :created, :location => @attendee_type }
else
format.html { render :action => "new" }
format.xml { render :xml => @attendee_type.errors, :status => :unprocessable_entity }
end
end
end
# PUT /attendee_types/1
# PUT /attendee_types/1.xml
def update
@attendee_type = AttendeeType.find(params[:id])
respond_to do |format|
if @attendee_type.update_attributes(params[:attendee_type])
flash[:notice] = 'AttendeeType was successfully updated.'
format.html { redirect_to(@attendee_type) }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @attendee_type.errors, :status => :unprocessable_entity }
end
end
end
# DELETE /attendee_types/1
# DELETE /attendee_types/1.xml
def destroy
@attendee_type = AttendeeType.find(params[:id])
@attendee_type.destroy
respond_to do |format|
format.html { redirect_to(attendee_types_url) }
format.xml { head :ok }
end
end
end
|
require 'test_helper'
class UserTest < ActiveSupport::TestCase
def setup
@user = User.new(name: "Example user", email: "PerfectEmail@example.com",
password: "password", password_confirmation: "password")
end
#basic inputs
test "vanilla user should be valid" do
assert @user.valid?
end
test "should not have name longer than 50 characters" do
@user.name = "f" * 51
assert_not @user.valid?
end
test "email should not be more than 100 characters" do
@user.email = "f" * 101
assert_not @user.valid?
end
test "email should be present" do
@user.email = " "
assert_not @user.valid?
end
test "name should be present" do
@user.name = " "
assert_not @user.valid?
end
#email formatting and uniqueness
test "should accept valid email addresses" do
valid_addresses = %w[joe@example.com BlAh@gmail.com MEMEME@memes.org
first.last@hentai.jp alice+bob@broscience.cn]
valid_addresses.each do |val_address|
@user.email = val_address
assert @user.valid?, "#{val_address.inspect} should be valid"
end
end
test "should reject invalid email addresses" do
invalid_addresses = %w[joe@example BlAhgmail.com MEMEME@memes.
firstlasthentaijp alice+bob@ blah!!no@gmail.com]
invalid_addresses.each do |inval_address|
@user.email = inval_address
assert_not @user.valid?, "#{inval_address.inspect} should be invalid"
end
end
test "email addresses should be unique" do
duplicate_user = @user.dup
duplicate_user.email = @user.email.upcase
@user.save
assert_not duplicate_user.valid?
end
test "password and confirmation should match" do
@user.password_confirmation = "password2"
assert_not @user.valid?
end
test "password should be at least 6 characters" do
@user.password = "great"
@user.password_confirmation = "great"
assert_not @user.valid?
end
test "password cannot be blank" do
@user.password = " "
@user.password_confirmation = " "
end
test "authenticated? should return false with nil digest" do
assert_not @user.authenticated?('')
assert_not @user.authenticated?(nil)
assert_not @user.authenticated?('well there isnt one here anyway')
end
end
|
module CommissionHub
module Awin
class Settings
attr_accessor :api_token, :publisher_id
attr_writer :base_uri
def base_uri
"#{@base_uri}/publishers/#{@publisher_id}"
end
end
end
end
|
class RendezvousRegistration < ActiveRecord::Base
belongs_to :user
has_many :attendees, :dependent => :destroy
has_many :transactions, :dependent => :destroy
accepts_nested_attributes_for :user
accepts_nested_attributes_for :attendees, :allow_destroy => true
accepts_nested_attributes_for :transactions, :allow_destroy => true
scope :current, -> { where(:year => Time.now.year) }
validate :validate_minimum_number_of_adults, unless: -> { status == 'cancelled' }
validate :validate_payment, unless: -> { status == 'cancelled' }
validates :paid_method, :inclusion => { :in => Rails.configuration.rendezvous[:payment_methods] }, :allow_blank => true
# validates :invoice_number, :uniqueness => true, :format => { :with => /\ARR20\d{2}-\d{3,4}\z/, :on => :new }, :allow_blank => true
validates :status, :inclusion => { :in => Rails.configuration.rendezvous[:registration_statuses] }
serialize :events, JSON
def validate_minimum_number_of_adults
if number_of_adults < 1
errors[:base] << "You must register at least one adult."
end
end
def validate_payment
if !paid_amount.nil?
if (paid_amount.to_f > total.to_f)
errors[:base] << "The paid amount is more than the owed amount."
end
end
end
def balance
total.to_f - paid_amount.to_f
end
def paid?
!(balance > 0.0)
end
def self.invoice_number
prefix = "CR#{Rails.configuration.rendezvous[:dates][:year]}"
previous_code = RendezvousRegistration.pluck(:invoice_number).last
if previous_code.blank?
next_number = 101
else
next_number = /-(\d+)\z/.match(previous_code)[1].to_i + 1
end
"#{prefix}-#{next_number}"
end
end
|
class ShakesChar
attr_accessor :name, :play, :gender, :age
def show_name
"My name is #{self.name}."
end
def show_play
"I was manifested in #{self.play}."
end
def show_gender
"I am a #{self.gender}."
end
def show_age
"I am #{self.age} years old."
end
def quote
"H're is what I speaketh: "
end
end
|
#!/usr/bin/env ruby
# frozen_string_literal: true
require 'pathname'
require 'matrix'
require_relative 'intcode'
require_relative 'utils'
def part_one(program)
game = Intcode.new program
game.execute!.outputs.each_slice(3).map(&:last).tally[2]
end
CHARS = {
0 => ' ',
1 => '█',
2 => '▒',
3 => '_',
4 => '.',
}.freeze
class Screen
def initialize(rows, cols)
@screen = Matrix.zero(rows, cols)
end
def []=(x, y, tile)
@screen[y, x] = tile
end
def display_lines
@screen.transpose.row_vectors.map do |row|
row.to_a.map { |e| CHARS[e] }.join
end
end
def find(tile)
@screen.each_with_index { |e, row, col| return [row, col] if e == tile }
nil
end
end
def part_two(program)
program[0] = 2
game = Intcode.new program
score = 0
screen = Screen.new(40, 25)
1.step do |tick|
game.execute!(false, true)
game.outputs.each_slice(3) do |x, y, tile|
if x == -1
score = tile
else
screen[y, x] = tile
end
end
game.outputs.clear
paddle = screen.find(3)
ball = screen.find(4)
d = ball[0] - paddle[0]
game.inputs << (d.zero? ? 0 : d / d.abs)
puts screen.display_lines.join("\n")
puts "Score: #{score} | Tick: #{tick} | Ball: #{ball} | Paddle: #{paddle}".ljust(80)
return score if screen.find(2).nil?
puts "\033[#{screen.display_lines.length + 2}A\r"
sleep 0.001
end
end
if $PROGRAM_NAME == __FILE__
puts 'https://adventofcode.com/2019/day/13'
program = read_program Pathname(__dir__).parent / 'data' / 'day_13.txt'
puts "Part One: #{part_one(program)}"
puts "Part Two: #{part_two(program)}"
end
|
VAGRANTFILE_API_VERSION = "2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
config.vm.box = "precise64"
config.vm.box_url = "http://files.vagrantup.com/precise64.box"
config.vm.provider "virtualbox" do |v|
v.memory = 2048
v.cpus = 4
end
config.vm.provision "shell", inline: "rm -fr /var/elasticsearch"
config.vm.provision "shell", inline: "mkdir /var/elasticsearch"
config.vm.provision "shell", inline: "cp /vagrant/elasticsearch.yml /var/elasticsearch"
config.vm.provision "docker" do |d|
# TODO: Fix image with working Marvel...
# d.build_image "/vagrant", args: "-t jinx/elasticsearch"
# d.run "jinx/elasticsearch",
d.run "dockerfile/elasticsearch",
args: "-p 9200:9200 -p 9300:9300 -v /var/elasticsearch:/data",
cmd: "/elasticsearch/bin/elasticsearch -Des.config=/data/elasticsearch.yml"
end
config.vm.network "forwarded_port", guest: 9200, host: 9200
config.vm.network "forwarded_port", guest: 9300, host: 9300
end
|
require "haml"
module TxiRailsHologram
# Public: A context for rendering HAML that knows about helpers from Rails,
# gems and the current application.
class RenderingContext
# Internal: Creates a new context into which we can render a chunk of HAML.
#
# Returns a properly-configured instance of ActionView::Base.
def self.create
# Create a new instance of ActionView::Base that has all of the helpers
# that our ApplicationController does. This allows us to use normal Rails
# helpers like `link_to`, most gem-provided helpers, and also custom
# application helpers like `svg_icon`.
view_context = ApplicationController.helpers
# Add named route support to our view context, so we can reference things
# like `root_path`.
class << view_context; include Rails.application.routes.url_helpers; end
# Create a new controller instance and give it a fake request; this vaguely
# mirrors what happens when Rails receives a request and routes it. This
# step allows us to use `simple_form_for`.
controller = ApplicationController.new
controller.request = ActionDispatch::TestRequest.new
view_context.request = controller.request
# Set up our view paths so that both `render` and gems that provide helpers
# that use `render` (e.g. kaminari) can work.
controller.append_view_path "app/views"
view_context.view_paths = controller.view_paths
view_context.controller = controller
# Add support for capturing HAML via the helpers module.
class << view_context; include Haml::Helpers; end
# This call is needed since we're outside the typical Rails setup. See:
# https://github.com/haml/haml/blob/88110b0607efca433c13bb1e339dcb1131edf010/lib/haml/helpers.rb#L56-L70
view_context.init_haml_helpers
ViewContextWrapper.new(view_context)
end
private_class_method :create
# Public: A Singleton instance of the context.
def self.instance
@instance ||= create
end
# Public: A decorator around an ActionView::Base object that provides some
# custom functionality around loading assets that are specific to this
# gem's host application. This allows us to account for variance in setup
# of CSS and JS files across projects.
class ViewContextWrapper < SimpleDelegator
# Public: The content that should be loaded in the <head> for the
# particular host application.
#
# Returns a String.
def application_specific_styleguide_head
render_assets(config["styleguide_head"], "lib/assets/_default_styleguide_head.html.haml")
end
# Public: The content that should be loaded in the foot (right before the
# closing </body> tag) of the particular host application.
#
# Returns a String.
def application_specific_styleguide_foot
render_assets(config["styleguide_foot"], "lib/assets/_default_styleguide_foot.html.haml")
end
private
# Internal: The configuration from the hologram_config.yml file of the
# host application.
#
# Returns a Hash.
def config
@config ||= YAML.load(File.read(Rails.root.join("hologram_config.yml")))
end
# Internal: Renders the HAML content at the app_file_path or fallback_path.
#
# app_file_path - A String path relative to the host application's
# Rails.root, e.g. `styleguide/assets/_head.html.haml`
# fallback_path - A String path relative to the gem's root, e.g.
# `lib/assets/_default_head.html.haml`
#
# Returns a String.
def render_assets(app_file_path, fallback_path)
if app_file_path
content = File.read(Rails.root.join(app_file_path))
else
gem_path = Bundler.rubygems.find_name("txi_rails_hologram").first.full_gem_path
content = File.read("#{gem_path}/#{fallback_path}")
end
engine = Haml::Engine.new(content)
engine.render(self)
end
end
end
end
|
# Die Class 1: Numeric
# I worked on this challenge [by myself, with: ]
# Myself
# I spent [] hours on this challenge.
# 0. Pseudocode
# Input: Number of sides on the die
# Output: A random number between 1 and the number of sides.
# Steps:
# take number of sides for dice
# return number of sides
# return random number between one and number of sides
# 1. Initial Solution
class Die
def initialize(sides)
if sides > 0
@dice_side = sides
else
raise ArgumentError.new("Wrong number of sides")
end
end
def sides
@dice_side
end
def roll
return rand(1..@dice_side)
end
end
die = Die.new(6)
die.sides
die.roll
# 3. Refactored Solution
class Die
def initialize(sides)
if sides > 0
@dice_side = sides
else
raise ArgumentError.new("Wrong number of sides")
end
end
def sides
@dice_side
end
def roll
return rand(1..@dice_side)
end
end
die = Die.new(6)
die.sides
die.roll
# 4. Reflection
=begin
What is an ArgumentError and why would you use one?
An argument error will stop a program from running and let the user or machine know that something went wrong. Ruby has ArgumentErrors built in, but you also have the ability to create your own. These can be used in a variety of ways. One common use would be to alert a user that they have entered something wrong that the program will be unable to run.
What new Ruby methods did you implement? What challenges and successes did you have in implementing them?
The new method that I used in this program was 'rand'. Rand generates a random number output. The challenge I had was just doing rand(@dice_side) without giving it a range. Once I realized that I needed to do it between 1 and dice_sides, I was able to successfully run the program.
What is a Ruby class?
A class in Ruby is how you can create a new object. It provides the structure for what that object should have or include.
Why would you use a Ruby class?
You would use a class for use in creating new objects. For example, you might want to create a person class, from this you would be able to pass in values and create a person as an object where you might take that persons weight, height, name, etc.
What is the difference between a local variable and an instance variable?
Local variables are created within a method and are therefor local to that method. They cannot be accessed or used outside of that method. An instance variable, however, is available for any method within a class.
Where can an instance variable be used?
Intance variables can be used when you want to access a variable within multiple methods of a class. If you are creating a program that will need to access information from one method to the next, they would be very useful.
=end |
# encoding: UTF-8
require 'mini_magick'
module MiniMagickProcessor
extend self
def image_to_tiff
tmp_file = Tempfile.new(["",".tif"])
cat = @instance || read_with_processor(@source.to_s)
cat.format("tif")
cat.crop("#{@w}x#{@h}+#{@x}+#{@y}") unless [@x, @y, @w, @h].compact == []
cat.write tmp_file.path.to_s
return tmp_file
end
def read_with_processor(path)
MiniMagick::Image.open(path.to_s)
end
def is_a_instance?(object)
object.class == MiniMagick::Image
end
end
|
#global variable for hash counter
$results = Hash.new 0
#Function to lowercase word and remove punctuation
def sanitize(word)
word.downcase.gsub(/[^a-z]/,'')
end
#Function to split each line into words separated by spaces
def break_line(line)
words = line.split
words.each do |word|
result = sanitize(word)
#increases the value based on the word (hash key)
$results[result] += 1
end
#return value to test against
$results
end
def topten(hashresults)
Hash[hashresults.sort_by {|k,v| -v}[0..9]]
end
#Guard so rspec won't run the executable section
if $0 == __FILE__
if ARGV.length != 1
puts "Please provide a filename"
exit;
end
filename = ARGV[0]
file = open filename
#processes file by line
file.each do |line|
break_line(line)
end
file.close #closes file
top = topten($results)
puts top
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.