text stringlengths 10 2.61M |
|---|
require 'rails_helper'
RSpec.describe Event, type: :model do
subject do
described_class.new(
title: 'Anything',
description: 'Anything',
date: DateTime.now,
location: 'Anything'
)
end
describe 'Validations' do
it 'is not valid without valid attributes or creator' do
expect(subject).to_not be_valid
end
it 'is not valid without a title' do
subject.title = nil
expect(subject).to_not be_valid
end
it 'is not valid without a description' do
subject.description = nil
expect(subject).to_not be_valid
end
it 'is not valid without a location' do
subject.location = nil
expect(subject).to_not be_valid
end
it 'is not valid without a date' do
subject.date = nil
expect(subject).to_not be_valid
end
end
describe 'Associations' do
it { should belong_to(:creator).without_validating_presence }
it { should have_many(:attendances) }
it { should have_many(:invited_users).through(:attendances) }
end
end
|
class View < ApplicationRecord
belongs_to :movie
validates :count_date, presence: true
validates :count, presence: true, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
def diff
previous_view = View.where(movie_id: movie_id).where('count_date < ?', count_date).order('count_date DESC').first
if previous_view
return count - previous_view.count
else
return count
end
end
end
|
require 'rails_helper'
RSpec.describe "/cards", type: :request do
let(:user) { User.create(admin: false, email: "email@admin.pl", password: "123blabla345") }
before(:each) do
sign_in(user)
end
describe 'GET /show' do
it 'renders a successful response' do
cart = Cart.create!
get cart_url(cart)
expect(response).to be_successful
end
end
describe 'PATCH /update' do
it 'renders a successful response' do
cart = Cart.create!(user: user)
product = Product.create(name: 'test', price: 12.12, quantity: 12)
patch cart_url(id: cart.id, cart: { quantity: 3, product_id: product.id })
expect(response).to be_successful
expect(cart.reload.product_items.first.quantity).to eq 3
expect(cart.reload.product_items.first.name).to eq 'test'
end
end
describe 'DELETE /destroy' do
it 'renders a successful response' do
cart = Cart.create!(user: user)
ProductItem.create(name: 'test', cart: cart)
delete cart_url(cart.id)
expect(cart.reload.product_items.size.zero?).to eq true
end
end
end
|
require 'rails_helper'
describe Api::V1::ConcertsController do
# GET /api/v1/concerts
describe 'GET #index' do
subject(:http_request) { get :index }
let!(:concert) { create_list(:concert, 3) }
before do
http_request
end
it 'responds with ok status code' do
expect(response).to have_http_status(:ok)
end
it 'validat count response' do
expect(JSON(response.body).count).to be 3
end
end
# POST /api/v1/concerts + Key
describe 'POST #create' do
subject(:http_request) { post :create, params: params }
let(:params) do
{
concert: {
name: 'Arjona',
city: 'Medellin'
}
}
end
context 'when user not logged in' do
before { http_request }
it 'responds with unauthorized status code' do
expect(response).to have_http_status(:unauthorized)
end
end
context 'when user is are logged in' do
# TODO: user login, for get http request
# include_context 'authenticated user'
# before { http_request }
# it 'responds with created status code' do
# expect(response).to have_http_status(:created)
# end
end
end
end
|
module Fog
module Hetznercloud
VERSION = '0.0.2'.freeze
end
end
|
class ExternalIncomePresenter < SimpleDelegator
def amount
ActionController::Base.helpers.number_to_currency(super, unit: "£")
end
def oda_funding
(super) ? "Yes" : "No"
end
end
|
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
private
def current_user
#FIXME: fake login
@current_user ||= if User.exists?
User.first
else
User.create(name: "Ohno Shin'ichi", author: Author.create(name: "shin1ohno"))
end
end
helper_method :current_user
end
|
require 'rubygems'
require 'mongrel-soap/rpc/standaloneServer'
HOST = 'localhost'
PORT = '8080'
SERVER_NAME = 'Spire Monitor'
NAMESPACE = 'spire:monitor'
begin
class SpireMonitorServer < MongrelSOAP::RPC::StandaloneServer
def initialize(*args)
super(*args)
add_method(self, 'get_xml')
end
def get_xml(date = Time.now.strftime('%d.%m.%Y'))
date = Date.parse(date).strftime("%d.%m.%Y")
filename = File.dirname(__FILE__) + "/xml/#{date}.xml"
if File.exists?(filename)
return File.read(filename)
else
return 'Spire Monitor has no data for this date. Sorry.'
end
end
end
server = SpireMonitorServer.new(SERVER_NAME, NAMESPACE, HOST, PORT)
trap('INT'){server.shutdown}
server.start
rescue => err
puts err.message
end
|
class SessionsController < ApplicationController
def new
end
# Define a new class method authenticate_with_credentials on the User model.
# It will take as arguments: the email address and password the user typed into the login form,
# And return: an instance of the user (if successfully authenticated), or nil (otherwise).
def create
if user = User.authenticate_with_credentials(params[:email], params[:password])
session[:user_id] = user.id
redirect_to :root
else
redirect_to :new
end
end
def destroy
session[:user_id] = nil
redirect_to login_path
end
end
|
require 'spec_helper'
describe PdfUtils do
describe "toc" do
it "should return an array of toc entries" do
PdfUtils.should_receive(:run_command).with(:pdftk, "stub.pdf dump_data").and_return(
"BookmarkTitle: Content\nBookmarkLevel: 1\nBookmarkPageNumber: 3\nBookmarkTitle: Intro\nBookmarkLevel: 2\nBookmarkPageNumber: 4")
PdfUtils::toc('stub.pdf').should eql([["Content",1,3], ["Intro",2,4]])
end
it "should not add an toc entry with page number < 1" do
PdfUtils.stub(:run_command => "BookmarkTitle: Content\nBookmarkLevel: 1\nBookmarkPageNumber: 0")
PdfUtils::toc('stub.pdf').should be_empty
end
it "should be empty if the document has no toc data" do
PdfUtils.should_receive(:run_command).with(:pdftk, "stub.pdf dump_data").and_return(
"InfoKey: Creator\nInfoValue: The Pragmatic Bookshelf")
PdfUtils::toc('stub.pdf').entries.should be_empty
end
end
describe "slice" do
it "should slice into a new pdf" do
sliced_path = Tempfile.new('sliced').path
PdfUtils::slice(fixture_file_path('marketing.pdf'), 2, 3, sliced_path)
PdfUtils::info(sliced_path).pages.should eql(2)
end
it "should slice the given file" do
sliced_path = duplicate_fixture_file('marketing.pdf').path
PdfUtils::slice!(sliced_path, 2, 3)
PdfUtils::info(sliced_path).pages.should eql(2)
end
it "should raise an error if pdftk fails to slice the pdf" do
lambda {
PdfUtils::slice('does/not/exist.pdf', 2, 3, 'does/not/exist/either.pdf')
}.should raise_error(RuntimeError)
end
end
describe "watermark" do
before :each do
@pdf_path = fixture_file_path('marketing.pdf')
end
it "should watermark into a new pdf" do
watermarked_path = Tempfile.new('watermarked').path
PdfUtils::watermark(@pdf_path, watermarked_path) do |pdf|
pdf.text "WATERMARKED PDF", :align => :center, :size => 8
end
pdf_text = PdfUtils::to_text(watermarked_path)
pdf_text.should include('WATERMARKED PDF')
pdf_text.should include('Beltz Verlag Weinheim')
end
it "should watermark the given file" do
watermarked_path = duplicate_fixture_file('marketing.pdf').path
PdfUtils::watermark!(watermarked_path) do |pdf|
pdf.text "WATERMARKED PDF", :align => :center, :size => 8
end
pdf_text = PdfUtils::to_text(watermarked_path)
pdf_text.should include('WATERMARKED PDF')
pdf_text.should include('Beltz Verlag Weinheim')
end
it "should pass options to the watermark pdf" do
Prawn::Document.should_receive(:generate).with(anything, :page_size => [25, 25])
PdfUtils::watermark(@pdf_path, Tempfile.new('target').path, :page_size => [25, 25]) {}
end
end
describe "annotate" do
before :each do
@pdf_path = fixture_file_path('page.pdf')
@annotations = [{
:Type => :Annot,
:Subtype => :Text,
:Name => :Comment,
:Rect => [10, 10, 34, 34],
:Contents => 'Dies ist eine Notiz.',
:C => PdfUtils::Color.new('fdaa00').to_pdf,
:M => Time.now,
:F => 4
}]
end
it "should annotate into a new pdf" do
annotated_path = Tempfile.new('annotated').path
PdfUtils::annotate(@pdf_path, @annotations, annotated_path)
annotations = PdfUtils::annotations(annotated_path)
annotations.should have(1).item
annotations.first[:Contents].should eql('Dies ist eine Notiz.')
end
end
describe "thumbnail" do
it "should create a thumbnail of the given page" do
source = fixture_file_path('marketing.pdf')
target = File.join(Dir.tmpdir, 'marketing.png')
FileUtils.rm(target) if File.exists?(target)
PdfUtils::thumbnail(source, :page => '3', :target => target)
File.should be_exists(target)
end
end
describe "snapshot" do
it "should rasterize the given page" do
path = duplicate_fixture_file('marketing.pdf').path
original_info = PdfUtils::info(path)
PdfUtils::snapshot!(path, :page => 2)
info = PdfUtils::info(path)
info.pages.should eql(1)
info.page_width. should be_close(original_info.page_width , 1.0)
info.page_height.should be_close(original_info.page_height, 1.0)
info.page_format.should eql(original_info.page_format)
end
end
end |
module Mote
# Basic document class for representing documents in a
# mongo db collection
class Document
class << self
def db
Mote.db
end
# Following the standard that a document is singular but a collection is plural
#
# @example Document
# Book #=> Books
#
# @return [String] Pluralized and lowercase collection name based off the model name
def collection_name
self.to_s.pluralize.downcase
end
# Return the raw MongoDB collection for the model from the Ruby Driver
def collection
@collection ||= self.db.collection(self.collection_name)
end
# Proxy a MongoDB Driver find call
#
# @see Mongo::Collection#find
# @see https://github.com/banker/mongo-ruby-driver/blob/master/lib/mongo/collection.rb#L68-130
def find(selector={}, options={})
Mote::Cursor.new self, collection.find(selector, options)
end
# Proxy a call to the MongoDB driver to find_one and return a <Mote::Document>
# for the result that is found if any
#
# @see Mongo::Collection#find_one
# @see https://github.com/banker/mongo-ruby-driver/blob/master/lib/mongo/collection.rb#L132-154
def find_one(selector={}, options={})
return nil unless doc = self.collection.find_one(selector, options)
self.new(doc, false)
end
# Find all of the documents in a collection
def all(options={})
find({}, options)
end
# Quickly create a document, inserting it to the collection immediately
#
# @param [Hash] doc_hash Hash which represents the document to be inserted
def create(doc_hash)
doc = self.new(doc_hash, true)
doc.insert
return doc
end
# Remove a document based on the query provided from the model's collection
#
# @param [BSON::ObjectId, Hash] query The query to find the document(s) to remove
# @param [Hash] opts Optional hash of options to send to the Mongo driver
#
# @see Mongo::Collection#remove
def remove(query, opts={})
query = object_id_query(query) if query.is_a? BSON::ObjectId
collection.remove(query, opts)
end
# Remove a document from the model's collection based on the query provided
# When given an BSON::ObjectId, a query will be generated for the ObjectId to remove
# a specific document
#
# @example
# Book.remove(BSON::ObjectId("4d76497204af5c0a81000001"))
#
#
# Provides a means for checking if a Mote module was included into the model class
#
# @example
#
# class Book < Mote::Document
# include Mote::Keys
# end
#
# Book.keys? #=> true
# Book.callbacks? #=> false
def method_missing(method_id, *args, &block)
if Mote::MOTE_MODULES.collect { |m| m.to_s.downcase + "?" }.include? method_id.to_s
module_name = method_id.to_s.gsub(/\?/, '').capitalize
include? Mote.const_get(module_name)
else
super
end
end
private
# Generates a simple hash query to query a document by its _id property when
# given a BSON::ObjectId
#
# @example object_id_query(BSON::ObjectId("4d76497204af5c0a81000001"))
# { _id: BSON::ObjectId(BSON::ObjectId("4d76497204af5c0a81000001")) }
#
# @param BSON::ObjectId
# @return Hash
def object_id_query(object_id)
{ _id: object_id }
end
end
attr_accessor :is_new
def initialize(doc_hash=Hash.new, is_new=true)
instantiate_document doc_hash
self.is_new = is_new
end
# Method to instantiate the document hash. Override this method
# if you wish to instantiate the document differently
#
# @param [Hash] hash Hash which defines the document
def instantiate_document(hash)
self.doc = hash.stringify_keys
end
def doc=(hash)
@doc = hash
end
def doc
@doc
end
def [](k)
@doc[k.to_s]
end
def []=(k,v)
@doc[k.to_s] = v
end
def is_new?
self.is_new == true
end
def as_json(options={})
serialize(options)
end
def to_json(options={})
as_json(options)
end
# Compare Mote::Documents based off the _id of the document
#
# @param [Document] other The other document to compare with
def ==(other)
return false unless other.is_a?(self.class)
@doc["_id"] == other["_id"]
end
# Makes an insert call to the database for the instance of the document
#
# @return [BSON::ObjectID] The id of the newly created object
def insert
return false unless is_new?
_id = self.class.collection.insert prepare_for_insert
@doc["_id"] = _id
self.is_new = false
return _id
end
# Update the document in the database with either a provided document
# or use the instance's document
#
# @param [<Mote::Document>] update_doc Optional document to update with
# @param [Hash] opts Options to send to the Mongo Driver along with the update
def update(update_doc=@doc, opts={})
return false if is_new?
update_doc = prepare_for_insert update_doc
default_options = {
:query => { _id: @doc["_id"] },
:update => update_doc,
:new => true
}
@doc = self.class.collection.find_and_modify default_options.merge(opts)
instantiate_document(@doc)
@doc
end
# Saves the current state of the document into the database
def save
is_new? ? insert : update
end
# Provide access to document keys through method missing
#
# @example
# class Book < Mote::Document; end
#
# @book = Book.new
# @book["title"] = "War and Peace"
# @book.title #=> "War and Peace"
def method_missing(method_name, *args, &block)
if @doc and @doc.include? method_name.to_s
@doc[method_name.to_s]
else
super
end
end
# Takes a document and ensure's that it is ready for insertion or update into the
# collection. Override this method to alter the document before saving into the database
#
# @return [Hash] Hash to insert / update in the database with
def prepare_for_insert(doc=@doc)
doc
end
private
# Serialize a Mote::Document
#
# The basis for this method was borrowed from ActiveModel's Serialization#serializable_hash
# @see ActiveSupport::Serialization#serialiazable_hash
#
# Allows the user to specify methods on the model to call when serializing
#
# == Note
# Only one of the 2 exclusion options (only or except) will be used, the 2 cannot be passed together
# If both are passed, only will take precedence
#
# @param [Hash] options Options to serialize with
# @option options [Symbol, Array <Symbol>] :only Specify specific attributes to include in serialization
# @option options [Symbol, Array <Symbol>] :except Specify methods to exclude during serialization
# @option options [Symbol, Array <Symbol>] :methods Model instance methods to call and include their result in serialization
def serialize(options=nil)
options ||= {}
keys = @doc.keys
only = Array.wrap(options[:only]).map(&:to_s)
except = Array.wrap(options[:except]).map(&:to_s)
if only.any?
keys &= only
elsif except.any?
keys -= except
end
method_names = Array.wrap(options[:methods]).map { |n| n if respond_to?(n) }.compact
Hash[(keys + method_names).map { |n| [n.to_s, send(n)] }]
end
end
end
|
#coding : utf-8
class Result
attr_accessor :code, :data
def initialize
@code = ResultCode::ERROR
end
end |
# frozen_string_literal: true
# Run this migration from the active-storage-changes code branch.
class MigrateToActiveStorageLocations
def perform
model_map = {Course => :gpx, Effort => :photo, Partner => :banner, Person => :photo}
model_map.each do |model, attribute|
migrate_data(attribute, model)
end
end
private
def migrate_data(attribute, model)
model.where.not("#{attribute}_file_name": nil).find_each do |resource|
name = resource.send("#{attribute}_file_name")
content_type = resource.send("#{attribute}_content_type")
url = resource.send(attribute).service_url
resource.send(attribute.to_sym).attach(io: open(url),
filename: name,
content_type: content_type)
end
end
end
|
module TrainingsHelper
def display_index_header
# 2021-01-16 02 moved the training sessions workout name, race title from the app/views/trainings/index.html.erb
if @workout
content_tag(:h2,"Training Sessions for the #{@workout.name} workout")
elsif @race
tag.h2("Training Sessions for the #{@race.title} race")
else
content_tag(:h1, "All Training Sessions")
end
end
def display_date(t) # 2021-01-17 moved here from app/views/trainings/index.html.erb
"on #{t.datetime}" if t.date
end
def display_feeling(t) # 2021-01-17 moved here from app/views/trainings/index.html.erb
"and felt: #{t.feeling}" if !t.feeling.empty?
end
def workout_form_option(form_builder) # 2021-01-17 moved here from app/views/trainings/new.html.erb
if @workout # 2021-01-15
content_tag(:p, "Workout: #{@workout.name}")
else
# 2021-01-17 moved the "select a workout" and "create a workout" to app/views/trainings/_workoutform.html.erb
render partial: "workoutform", locals: {f: form_builder}
# 2021-01-17 added a render partial
end
end
end
|
require_relative './repository'
require_relative './models'
require_relative './order'
require_relative './order_item'
require_relative './data_loader'
require_relative './table_drawer'
class Grocery
def call
repo = Repository.new(DataLoader.load_products, DataLoader.load_discounts)
loop do
pp('Please enter all the items purchased separated by a comma')
order_string = gets.strip
product_names = order_string.split(',')
.map(&:downcase)
.map(&:strip)
products = product_names.map do |name|
repo.products.find { |p| p.name.downcase == name }
end
products = products.reject(&:nil?)
order = Order.new(products, repo)
headers = %w[Item Quantity Price]
rows = order.items.map do |item|
[item.product.name, item.quantity, to_dollars(item.price)]
end
TableDrawer.new(
headers,
rows,
to_dollars(order.price_with_discount),
to_dollars(order.discount)
).call
end
end
private
def to_dollars(value)
"$#{value / 100.0}"
end
end
|
class Message
include Mongoid::Document
field :text
belongs_to :user
embedded_in :conversation
end
|
class RemoveTmIdFromTrademarks < ActiveRecord::Migration[5.2]
def change
remove_column :trademarks, :tm_id, :integer
end
end
|
# -*- encoding : utf-8 -*-
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# email :string(255) default(""), not null
# encrypted_password :string(255) default(""), not null
# reset_password_token :string(255)
# reset_password_sent_at :datetime
# remember_created_at :datetime
# sign_in_count :integer default(0)
# current_sign_in_at :datetime
# last_sign_in_at :datetime
# current_sign_in_ip :string(255)
# last_sign_in_ip :string(255)
# created_at :datetime not null
# updated_at :datetime not null
# nik :string(255)
# balance :decimal(6, 2) default(0.0), not null
# confirmation_token :string(255)
# confirmed_at :datetime
# confirmation_sent_at :datetime
# unconfirmed_email :string(255)
# roles_mask :integer
# configApp_id :integer
# -*- encoding : utf-8 -*-
class User < ActiveRecord::Base
require 'role_model'
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :confirmable
include RoleModel
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me, :nik, :balance, :configApp_id
# attr_accessible :title, :body
validates(:nik, presence: true)
has_many :payments
has_many :orders
has_many :lotts
belongs_to :configApp
accepts_nested_attributes_for :orders
before_validation :set_roles
# optionally set the integer attribute to store the roles in,
# :roles_mask is the default
roles_attribute :roles_mask
# declare the valid roles -- do not change the order if you add more
# roles later, always append them at the end!
roles :admin, :editor, :guest
private
def set_roles
self.roles = [:guest] if self.roles.empty?
end
def self.usearch(search)
if search
find(:all, :conditions => ['nik LIKE ?' , "%#{search}%"] )
else
find(:all, :conditions => ['nik LIKE ?' , "777dfgdg"] ) # при первом обращении ищет пользователя 777dfgdg
end
end
end
|
class AddIndexesToTransactions < ActiveRecord::Migration
def change
add_index :transactions, :client_id
add_index :transactions, :purchaser_id
add_index :transactions, :device_id
end
end
|
# frozen_string_literal: true
require 'spec_helper'
describe XeroExporter::Executor do
context '#create_credit_note_payment' do
it 'should create an credit_note if there are lines for one' do
initial_state = {
create_credit_note: {
state: 'complete',
credit_note_id: 'xyz',
amount: 500.0
}
}
executor, state = create_executor(initial_state: initial_state) do |e, api|
expect(api).to receive(:put).with('Payments', anything) do |_, params|
expect(params.dig('Account', 'Code')).to eq e.receivables_account
expect(params.dig('CreditNote', 'CreditNoteID')).to eq 'xyz'
expect(params['Amount']).to eq 500.0
expect(params['Reference']).to eq e.reference
{
'Payments' => [{
'PaymentID' => 'payment-id-4444',
'Amount' => 500.00
}]
}
end
end
executor.create_credit_note_payment
expect(state[:create_credit_note_payment][:state]).to eq 'complete'
expect(state[:create_credit_note_payment][:payment_id]).to eq 'payment-id-4444'
expect(state[:create_credit_note_payment][:amount]).to eq 500.0
expect(@logger_string_io.string).to include 'Running create_credit_note_payment task'
expect(@logger_string_io.string).to include 'Creating payment for credit note xyz for 500.0'
expect(@logger_string_io.string).to include 'Using receivables account: 020'
end
it 'should not create an payment if there are no lines' do
initial_state = {
create_credit_note: {
state: 'complete'
}
}
executor, state = create_executor(initial_state: initial_state)
executor.create_credit_note_payment
expect(state[:create_credit_note_payment][:state]).to eq 'complete'
expect(state[:create_credit_note_payment][:payment_id]).to be nil
expect(state[:create_credit_note_payment][:amount]).to be nil
expect(@logger_string_io.string).to include 'Running create_credit_note_payment task'
expect(@logger_string_io.string).to include 'Not adding a payment because the amount ' \
'is not present or not positive'
end
end
end
|
# frozen_string_literal: true
class BlogComment < ApplicationRecord
belongs_to :user
belongs_to :blog
# 250文字以内
validates :comment, presence: true, length: { minimum: 1, maximum: 250 }
end
|
class BlogEntriesController < ApplicationController
before_action :set_blog_entry, only: [:show, :edit, :update, :destroy]
# GET /blog_entries
# GET /blog_entries.json
def index
@blog_entries = BlogEntry.all
end
# GET /blog_entries/1
# GET /blog_entries/1.json
def show
# This is how you demonstrate the belongs_to :blog association
@blog = @blog_entry.blog # Child-parent relationship 'belongs to'
@user = @blog_entry.user
# This nil check is necessary to make sure all the div's are valid
if @user == nil
@user_empty = true
end
@comments = @blog_entry.blogcomments
# Class Assignment
# ----------------
# display the LAST comment for a given blog entry
@last_comment = @comments.last
# using the activerecord method LAST alone returns an object which is not an array
# To do this you need to get rid of the loop
# using the method LAST(1) returns an array which has the last comment
end
# GET /blog_entries/new
def new
@blog_entry = BlogEntry.new
end
# GET /blog_entries/1/edit
def edit
end
# POST /blog_entries
# POST /blog_entries.json
def create
@blog_entry = BlogEntry.new(blog_entry_params)
respond_to do |format|
if @blog_entry.save
format.html { redirect_to @blog_entry, notice: 'Blog entry was successfully created.' }
format.json { render action: 'show', status: :created, location: @blog_entry }
else
format.html { render action: 'new' }
format.json { render json: @blog_entry.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /blog_entries/1
# PATCH/PUT /blog_entries/1.json
def update
respond_to do |format|
if @blog_entry.update(blog_entry_params)
format.html { redirect_to @blog_entry, notice: 'Blog entry was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @blog_entry.errors, status: :unprocessable_entity }
end
end
end
# DELETE /blog_entries/1
# DELETE /blog_entries/1.json
def destroy
@blog_entry.destroy
respond_to do |format|
format.html { redirect_to blog_entries_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_blog_entry
@blog_entry = BlogEntry.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def blog_entry_params
params.require(:blog_entry).permit(:user_id, :blog_id, :category, :subject, :entries, :num_entries)
end
end
|
require 'active_record'
require 'delayed_job_active_record'
require 'deep_thought/app'
require 'deep_thought/api'
require 'deep_thought/models/deploy'
require 'deep_thought/models/project'
require 'deep_thought/models/state'
require 'deep_thought/models/user'
require 'deep_thought/deployer'
require 'deep_thought/deployer/shell'
require 'deep_thought/ci_service'
require 'deep_thought/ci_service/janky'
require 'deep_thought/notifier'
require 'deep_thought/scaler'
require 'deep_thought/version'
module DeepThought
def self.setup(settings)
env = settings['RACK_ENV'] ||= 'development'
if env != "production"
settings["DATABASE_URL"] ||= "postgres://deep_thought@localhost/deep_thought_#{env}"
end
database = URI(settings["DATABASE_URL"])
settings["DATABASE_ADAPTER"] ||= "postgresql"
connection = {
:adapter => settings["DATABASE_ADAPTER"],
:encoding => "utf8",
:database => database.path[1..-1],
:pool => 5,
:username => database.user,
:password => database.password,
:host => database.host,
:port => database.port
}
ActiveRecord::Base.establish_connection(connection)
BCrypt::Engine.cost = 12
if settings['CI_SERVICE']
DeepThought::CIService.setup(settings)
end
end
def self.app
@app ||= Rack::Builder.app {
map '/' do
run DeepThought::App
end
map '/deploy/' do
run DeepThought::Api
end
}
end
DeepThought::Deployer.register_adapter('shell', DeepThought::Deployer::Shell)
DeepThought::CIService.register_adapter('janky', DeepThought::CIService::Janky)
end
|
desc 'Start the rails server in debugging mode'
task :server do
sh 'rails server --debugger', :verbose => false
end
|
module Givdo
class Error
include ActiveModel::Model
include ActiveModel::Serialization
attr_accessor :status, :code, :title, :detail, :meta
def initialize(params = {})
super(params)
@status = Rack::Utils::SYMBOL_TO_STATUS_CODE[params[:status]].to_s
end
end
end
|
class AddIndustriesToAccountants < ActiveRecord::Migration[5.2]
def change
add_column :accountants, :industries, :string
end
end
|
class Player < ActiveRecord::Base
has_secure_password
acts_as_mappable :lat_column_name => :latitude,
:lng_column_name => :longitude
before_save :has_lat_long
validates :username, presence: true
has_many :player_sports
has_many :player_positions
has_many :player_teams
has_many :positions, through: :player_positions
has_many :sports, through: :player_sports
has_many :teams, through: :player_teams
has_many :media, as: :showable
def self.validate_via_provider(auth)
@player = Player.find_by(provider: auth[:provider], uid: auth[:uid])
@player = Player.new(provider: auth[:provider], uid: auth[:uid]) unless @player
@player.username = auth[:info][:name]
if @player.new_record?
@player.password = SecureRandom.uuid()
@player.phone = '122345689'
@player.save
end
@player
end
def has_positions?
self.positions.any?
end
def has_media?
self.media.any?
end
def parse_address
address = self.address
city = self.city
state = self.state
zip = self.zip
address = "#{address} #{city} #{state} #{zip}"
end
def lat_long
# OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE
if self.latitude == nil && self.longitude == nil
addr = URI.escape(parse_address)
res = HTTParty.get("https://maps.googleapis.com/maps/api/geocode/json?address=#{addr}&key=AIzaSyC7dmZEFn1tJOy7zeVH2Hce3tF8U0_MnIg")
lat = res["results"][0]["geometry"]["location"]["lat"]
lng = res["results"][0]["geometry"]["location"]["lng"]
self.update(latitude: lat, longitude: lng)
end
end
def has_lat_long
if self.address && self.latitude == nil && self.longitude == nil
lat_long
elsif self.address == nil
end
end
def map_string
"&markers=color:red%7Clabel:" + "#{self.username.first}" +"%7C" + "#{self.latitude.to_f.to_s}," + "#{self.longitude.to_f.to_s}"
end
end
|
class TransactionsController < ApplicationController
before_action :authenticate_user!
def new
@trans = Transaction.new
end
end
|
class VMatrizPeriodoPago < ActiveRecord::Base
self.table_name='v_matriz_periodo_pago'
scope :ordenado_01, -> {order('periodo, mes, documento, orden')}
end
|
class Company < ApplicationRecord
belongs_to :user
has_many :customers, dependent: :destroy
has_many :quotes, through: :customers
has_many :bills, through: :customers
has_many :services, dependent: :destroy
validates :name, presence: { message: "Champ incorrect ou incomplet" }
validates :address, presence: { message: "Champ incorrect ou incomplet" }
validates :postcode, presence: { message: "Champ incorrect ou incomplet" }
validates :city, presence: { message: "Champ incorrect ou incomplet" }
validates :phone, presence: { message: "Champ incorrect ou incomplet" }
validates :email, presence: { message: "Champ incorrect ou incomplet" }
validates :siret, presence: { message: "Champ incorrect ou incomplet" }
validates :siret, presence: { message: "Champ incorrect ou incomplet" }
validates :tva, presence: { message: "Champ incorrect ou incomplet" }
def nb_quotes
self.quotes.count
end
def nb_bills
self.bills.count
end
def nb_quotes_per_customer(customer)
self.quotes.where(customer: customer).count
end
def nb_bills_per_customer(customer)
self.bills.where(customer: customer).count
end
end
|
class AddRemarkToMatches < ActiveRecord::Migration
def change
add_column :matches, :remark, :text, after: :password
end
end
|
# encoding: utf-8
class InvoicesReport < Prawn::Document
def to_pdf(bill_array, bill_course)
if bill_course != ''
title = "Vorschau Kurs " + Course.find(bill_course).course_name
else
title = "Vorschau aller laufenden Kurse"
end
fulltext = ""
fullamount = ""
fulltotal = 0.0
font_size 24
text title
font_size 10
table_content = [["<b>EZ</b>", "<b>Name</b>", "<b>Rechnungstext</b>", "<b>Betrag</b>", "<b>Total</b>"]]
bill_array.each do |bill|
fulltext = ""
fullamount = ""
row = []
row << bill.nr
row << bill.lastname.to_s + ", " + bill.firstname.to_s
fulltext = fulltext + bill.text1 if !bill.text1.blank?
fulltext = fulltext + "\n" + bill.text2 if !bill.text2.blank?
fulltext = fulltext + "\n" + bill.text3 if !bill.text3.blank?
fulltext = fulltext + "\n" + bill.text4 if !bill.text4.blank?
row << fulltext
fullamount = fullamount + bill.amount1 if !bill.amount1.blank?
fullamount = fullamount + "\n" + bill.amount2 if !bill.amount2.blank?
fullamount = fullamount + "\n" + bill.amount3 if !bill.amount3.blank?
fullamount = fullamount + "\n" + bill.amount4 if !bill.amount4.blank?
row << fullamount
fulltotal = fulltotal.to_f + bill.total.to_f
row << bill.total
table_content << row
end
table(table_content, :header => true, :row_colors => ["F0F0F0", "FFFFFF"], :cell_style => { :inline_format => true })
text "\n\n"
text "Totalsumme: " + fulltotal.to_s
render
end
end
|
require "application_system_test_case"
class MealIngredientsTest < ApplicationSystemTestCase
setup do
@meal_ingredient = meal_ingredients(:one)
end
test "visiting the index" do
visit meal_ingredients_url
assert_selector "h1", text: "Meal Ingredients"
end
test "creating a Meal ingredient" do
visit meal_ingredients_url
click_on "New Meal Ingredient"
fill_in "Ingredient", with: @meal_ingredient.ingredient_id
fill_in "Meal", with: @meal_ingredient.meal_id
fill_in "Quantity", with: @meal_ingredient.quantity
fill_in "Unit", with: @meal_ingredient.unit
click_on "Create Meal ingredient"
assert_text "Meal ingredient was successfully created"
click_on "Back"
end
test "updating a Meal ingredient" do
visit meal_ingredients_url
click_on "Edit", match: :first
fill_in "Ingredient", with: @meal_ingredient.ingredient_id
fill_in "Meal", with: @meal_ingredient.meal_id
fill_in "Quantity", with: @meal_ingredient.quantity
fill_in "Unit", with: @meal_ingredient.unit
click_on "Update Meal ingredient"
assert_text "Meal ingredient was successfully updated"
click_on "Back"
end
test "destroying a Meal ingredient" do
visit meal_ingredients_url
page.accept_confirm do
click_on "Destroy", match: :first
end
assert_text "Meal ingredient was successfully destroyed"
end
end
|
module Rednode
class EventEmitter
attr_accessor :_events
def emit(e, *args)
return unless @_events
case notify = @_events[e]
when V8::Function
notify.methodcall(self, *args)
when V8::Array
notify.each {|listener| listener.methodcall(self, *args) if listener}
else
return false
end
return true
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)
User.create!(email: "example@railstutorial.org",
password: "foobar",
password_confirmation: "foobar")
99.times do |n|
email = "example-#{n+1}@railstutorial.org"
password = "password"
User.create!(email: email,
password: password,
password_confirmation: password)
end
users = User.order(:created_at).take(6)
120.times do
activity = Faker::Lorem.sentence(5)
type_gained = Faker::Boolean.boolean
number = Faker::Number.decimal(2, 2)
date = Faker::Time.between(120.days.ago, Date.today, :all)
users.each { |user| user.calories.create!(activity: activity,
type_gained: type_gained,
number: number,
date: date) }
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)
Item.destroy_all
Recipe.destroy_all
avocado = Item.create(name: 'Avocado', benefits: 'Avocados are a great source of biotin, which is part of the B complex vitamins. Biotin is known to help prevent dry skin when applied topically. It can also help prevent brittle hair and nails.')
olive_oil = Item.create(name: 'Olive Oil', benefits: 'Naturally, olive oil is packed with anti-aging antioxidants and hydrating squalene, making it superb for hair, skin, and nails.')
honey = Item.create(name: 'Honey', benefits: 'Honey is rich in vitamins, minerals, antioxidants, probiotics, amino acids, and enzymes that protect, soften, and nourish skin and hair. Honey also has natural antiseptic, antibacterial, and anti-inflammatory properties to help cleanse and sooth skin, hair, and scalp.' )
Recipe.create(
[{
title: 'Preshampoo Hair Treatment',
ingredients: 'Olive Oil',
instructions: 'First, warm the olive oil in the microwave or in hot water. Then apply it generously to the ends of hair and scalp. Leave it in for up to 10 to 20 minutes, and then shampoo it out.',
item_id: olive_oil.id
},
{
title: 'Avocado Mask',
ingredients: '1 ripe avocado, 1/3 cup plain yogurt, 2 teaspoons honey, 1 tablespoon lemon juice, optional: 2 tbsp rolled oats',
instructions: 'Add all ingredients to a blender, and blend until smooth. Wash face with a cleanser, dry and then apply mask liberally to face and neck. Let sit on face for 20 minutes. Wash mask off face and follow-up with your typical skincare routine.',
item_id: avocado.id
},
{
title: 'Hydrating Hair Mask',
ingredients: '1/2 cup raw honey and 1/4 cup olive oil',
instructions: 'In a small bowl, mix together the honey and olive oil. Heat in the microwave for a few seconds. You want the mixture to be warm, NOT HOT. Apply to dry hair from scalp to ends and leave on for 10-20 minutes. Rinse well and shampoo to remove remaining mask.',
item_id: honey.id
}]
) |
class Post < ActiveRecord::Base
attr_accessible :message, :title
has_many :comments, :dependent => :destroy
validates :title, :presence => true
validates :message, :presence => true
scope :recent, -> { Post.order('created_at DESC').limit(10) }
end
|
# This migration comes from keppler_capsules (originally 20180802184329)
class CreateKepplerCapsulesCapsuleFields < ActiveRecord::Migration[5.2]
def change
create_table :keppler_capsules_capsule_fields do |t|
t.string :name_field
t.string :format_field
t.integer :capsule_id
t.timestamps
end
end
end
|
class SubmissionCreator
attr_reader :return_hash
def initialize(submission)
@return_hash = {}
@movie = Movie.find(submission.movie_id)
@return_hash[:id] = @movie.id
field = submission.field
value = submission.value
if forbidden.include?(field)
raise ActiveRecord::AttributeNotFoundError
end
if !@movie.has_attribute?(field)
raise ActiveRecord::AttributeNotFoundError
else
@movie.set_field(field, value)
if @movie.save
@return_hash[:success] = true
submission.destroy!
end
end
end
private
def forbidden
[:id]
end
end
|
require 'csv'
namespace :loader do
desc 'Load Players from CSV'
task load_players: :environment do
ActiveRecord::Base.transaction do
csv_text = ENV["RAILS_ENV"] == 'test' ? File.read('test/lib/tasks/data/players.csv') : File.read('lib/tasks/data/players.csv')
csv = CSV.parse(csv_text, headers: true)
csv.each do |row|
mappings = {
first_name: row['nameFirst'],
last_name: row['nameLast'],
birth_year: row['birthYear'],
identifier: row['playerID']
}
PlayerLoader.new(mappings).load
end
end
end
desc 'Load Batting from CSV'
task load_batting: :environment do
ActiveRecord::Base.transaction do
csv_text = ENV["RAILS_ENV"] == 'test' ? File.read('test/lib/tasks/data/batting.csv') : File.read('lib/tasks/data/batting.csv')
csv = CSV.parse(csv_text, headers: true)
csv.each do |row|
BattingLoader.new(csv_row: row).load
end
end
end
end
|
class CreateReports < ActiveRecord::Migration[6.1]
def change
create_table :reports do |t|
t.date :date_report
t.string :do_today
t.string :problem
t.string :do_tomorrow
t.bigint :course_user_id
t.timestamps
end
add_foreign_key :reports, :course_users
end
end
|
# require 'pry'
class GameTeam
attr_accessor :game_id,
:team_id,
:HoA,
:won,
:settled_in,
:head_coach,
:goals,
:shots,
:hits,
:pim,
:powerPlayOpportunities,
:powerPlayGoals,
:faceOffWinPercentage,
:giveaways,
:takeaways
def initialize(gt_info)
@game_id = gt_info[:game_id]
@team_id = gt_info[:team_id]
@HoA = gt_info[:HoA]
@won = gt_info[:won]
@settled_in = gt_info[:settled_in]
@head_coach = gt_info[:head_coach]
@goals = gt_info[:goals]
@shots = gt_info[:shots]
@hits = gt_info[:hits]
@pim = gt_info[:pim]
@powerPlayOpportunities = gt_info[:powerPlayOpportunities]
@powerPlayGoals = gt_info[:powerPlayGoals]
@faceOffWinPercentage = gt_info[:faceOffWinPercentage]
@giveaways = gt_info[:giveaways]
@takeaways = gt_info[:takeaways]
end
end
|
#==============================================================================
# +++ MOG - MONSTER BOOK (v1.9) +++
#==============================================================================
# By Moghunter
# https://atelierrgss.wordpress.com/
#==============================================================================
# Sistema que permite verificar os parâmetros dos inimigos derrotados,
# o que inclui o battleback e a música de batalha.
#
#==============================================================================
# Para chamar o script use o comando abaixo.
#
# monster_book
#
#==============================================================================
module MOG_MONSTER_BOOK
#Ocultar inimigos especificos da lista de inimigos.
HIDE_ENEMIES_ID = []
#Ativar a música de batalha.
PLAY_MUSIC = true
#Definição da palavra Completado.
COMPLETED_WORD = "Completed"
#Ativar o Monster Book no Menu.
MENU_COMMAND = true
#Nome do comando apresentado no menu.
MENU_COMMAND_NAME = "Bestiary"
#Definição da opacidade da janela
WINDOW_OPACITY = 255
end
$imported = {} if $imported.nil?
$imported[:mog_monster_book] = true
#==============================================================================
# ■ Game_System
#==============================================================================
class Game_System
attr_accessor :bestiary_defeated
attr_accessor :bestiary_battleback
attr_accessor :bestiary_music
#--------------------------------------------------------------------------
# ● Initialize
#--------------------------------------------------------------------------
alias mog_monster_book_initialize initialize
def initialize
@bestiary_defeated = []; @bestiary_battleback = []; @bestiary_music = []
mog_monster_book_initialize
end
end
#==============================================================================
# ■ Game Interpreter
#==============================================================================
class Game_Interpreter
#--------------------------------------------------------------------------
# ● Monster Book
#--------------------------------------------------------------------------
def monster_book
SceneManager.call(Monster_Book)
end
end
#==============================================================================
# ■ Spriteset_Battle
#==============================================================================
class Spriteset_Battle
#--------------------------------------------------------------------------
# ● Initialize
#--------------------------------------------------------------------------
alias mog_bestiary_initialize initialize
def initialize
mog_bestiary_initialize
$game_system.bestiary_battleback[0] = [battleback1_name,battleback2_name]
end
end
#==============================================================================
# ■ Game_Enemy
#==============================================================================
class Game_Enemy < Game_Battler
attr_accessor :enemy_id
#--------------------------------------------------------------------------
# ● Die
#--------------------------------------------------------------------------
alias mog_monster_book_die die
def die
mog_monster_book_die
check_monster_book if !MOG_MONSTER_BOOK::HIDE_ENEMIES_ID.include?(@enemy_id)
end
#--------------------------------------------------------------------------
# ● Check Monster Book
#--------------------------------------------------------------------------
def check_monster_book
if $game_system.bestiary_defeated[@enemy_id] == nil
$game_system.bestiary_defeated[@enemy_id] = 0
$game_system.bestiary_battleback[@enemy_id] = $game_system.bestiary_battleback[0]
$game_system.bestiary_music[@enemy_id] = $game_system.battle_bgm
end
$game_system.bestiary_defeated[@enemy_id] += 1
end
end
#==============================================================================
# ■ Window_Monster_Status
#==============================================================================
class Window_Monster_Status < Window_Selectable
#--------------------------------------------------------------------------
# ● Initialize
#--------------------------------------------------------------------------
def initialize(enemy)
super(0, Graphics.height - 128, Graphics.width, 128)
self.opacity = MOG_MONSTER_BOOK::WINDOW_OPACITY
self.z = 300; refresh(enemy) ; activate
end
#--------------------------------------------------------------------------
# ● Refresh
#--------------------------------------------------------------------------
def refresh(enemy)
self.contents.clear
if $game_system.bestiary_defeated[enemy.id] == nil
self.contents.draw_text(0,0 , 180, 24, "No Data",0)
else
change_color(system_color)
w_max = 50
ex = 16
self.contents.draw_text(0,0 , w_max, 24, Vocab::param(0),0)
self.contents.draw_text(0,24 * 1 , w_max, 24, Vocab::param(1),0)
self.contents.draw_text(0,24 * 2 , w_max, 24, Vocab::param(2),0)
self.contents.draw_text(0,24 * 3 , w_max, 24, Vocab::param(3),0)
self.contents.draw_text(128,24 * 0 , w_max, 24, Vocab::param(4),0)
self.contents.draw_text(128,24 * 1 , w_max, 24, Vocab::param(5),0)
self.contents.draw_text(128,24 * 2 , w_max, 24, Vocab::param(6),0)
self.contents.draw_text(128,24 * 3 , w_max, 24, Vocab::param(7),0)
self.contents.draw_text(256,24 * 0 , w_max, 24, "Exp",0)
self.contents.draw_text(384,24 * 0 , w_max, 24, Vocab::currency_unit,0)
self.contents.draw_text(256,24 * 1 , w_max, 24, "Treasure",0)
change_color(normal_color,true)
w_max2 = 64
#HP
self.contents.draw_text(32 + ex,0 , w_max2, 24, enemy.params[0],2)
#MP
self.contents.draw_text(32 + ex,24 * 1 , w_max2, 24, enemy.params[1],2)
#ATK
self.contents.draw_text(32 + ex,24 * 2 ,w_max2 , 24, enemy.params[2],2)
#Def
self.contents.draw_text(32 + ex,24 * 3 , w_max2, 24, enemy.params[3],2)
#Mag Power
self.contents.draw_text(160 + ex,24 * 0 , w_max2, 24, enemy.params[4],2)
#Mag Def
self.contents.draw_text(160 + ex,24 * 1 , w_max2, 24, enemy.params[5],2)
#Agility
self.contents.draw_text(160 + ex,24 * 2 , w_max2, 24, enemy.params[6],2)
#Luck
self.contents.draw_text(160 + ex,24 * 3 , w_max2, 24, enemy.params[7],2)
#EXP
self.contents.draw_text(280,24 * 0 , 96, 24, enemy.exp,2)
#Gold
self.contents.draw_text(400,24 * 0 , 96, 24, enemy.gold,2)
#Drop Items
tr = 0
for i in enemy.drop_items
next if i.kind == 0
tr += 1
tr_name = $data_items[i.data_id] if i.kind == 1
tr_name = $data_weapons[i.data_id] if i.kind == 2
tr_name = $data_armors [i.data_id] if i.kind == 3
draw_icon(tr_name.icon_index, 336, 24 * tr)
self.contents.draw_text(368,24 * tr , 160, 24, tr_name.name.to_s,0)
end
end
end
end
#==============================================================================
# ■ Window_Monster_List
#==============================================================================
class Window_Monster_List < Window_Selectable
include MOG_MONSTER_BOOK
#------------------------------------------------------------------------------
# ● Initialize
#------------------------------------------------------------------------------
def initialize(data)
super(Graphics.width - 232, 64, 232, Graphics.height - 192)
self.opacity = WINDOW_OPACITY
self.z = 301; @index = -1; @data = data; @data_max = 0
@item_max = @data.size; refresh(data); select(0) ; activate
end
#------------------------------------------------------------------------------
# ● Refresh
#------------------------------------------------------------------------------
def refresh(data)
self.contents.clear
return if @item_max < 1
self.contents = Bitmap.new(width - 32, @item_max * 24)
@item_max.times do |i| draw_item(i) end
end
#------------------------------------------------------------------------------
# ● draw_item MAX
#------------------------------------------------------------------------------
def check_item_max
$data_enemies.compact.each {|i| @data_max += 1 if !HIDE_ENEMIES_ID.include?(i.id)}
end
#------------------------------------------------------------------------------
# ● draw_item
#------------------------------------------------------------------------------
def draw_item(index)
x = 0
y = index / col_max * 24
n_index = index + 1
if $game_system.bestiary_defeated[@data[index].id] == nil
monster_name = "No Data"
defeated = " ---- "
change_color(normal_color,false)
else
monster_name = @data[index].name
change_color(normal_color,true)
end
check_item_max
d = @data_max > 99 ? "%03d" : @data_max > 9 ? "%02d" : "%01d"
text = sprintf(d, n_index).to_s + " - "
self.contents.draw_text(x,y , 56, 24, text,0)
self.contents.draw_text(x + 56,y , 140, 24, monster_name,0)
end
#------------------------------------------------------------------------------
# ● Item Max
#------------------------------------------------------------------------------
def item_max
return @item_max == nil ? 0 : @item_max
end
end
#==============================================================================
# ■ Window_Monster_Comp
#==============================================================================
class Window_Monster_Comp < Window_Selectable
include MOG_MONSTER_BOOK
#--------------------------------------------------------------------------
# ● Initialize
#--------------------------------------------------------------------------
def initialize
super(Graphics.width - 232 ,0, 232, 64)
self.opacity = MOG_MONSTER_BOOK::WINDOW_OPACITY
self.z = 300; @data_max = 0; refresh; activate
end
#--------------------------------------------------------------------------
# ● Check Completition
#--------------------------------------------------------------------------
def check_completion
$data_enemies.compact.each {|i| @data_max += 1 if !HIDE_ENEMIES_ID.include?(i.id)}
comp = $game_system.bestiary_defeated.compact.size
@completed = COMPLETED_WORD + " " + comp.to_s + "/" + @data_max.to_s
end
#--------------------------------------------------------------------------
# ● Refresh
#--------------------------------------------------------------------------
def refresh
self.contents.clear ; check_completion
self.contents.draw_text(0,0, 160, 24, @completed.to_s,0)
end
end
#==============================================================================
# ■ Monster_Book
#==============================================================================
class Monster_Book
include MOG_MONSTER_BOOK
#--------------------------------------------------------------------------
# ● Main
#--------------------------------------------------------------------------
def main
execute_setup
Graphics.transition(10)
execute_loop
execute_dispose
end
#--------------------------------------------------------------------------
# ● Execute Loop
#--------------------------------------------------------------------------
def execute_loop
loop do
Graphics.update ; Input.update ; update
break if SceneManager.scene != self
end
end
#--------------------------------------------------------------------------
# ● Execute
#--------------------------------------------------------------------------
def execute_setup
load_data ; execute_dispose ; create_background ; create_window_guide
create_enemy_sprite ; create_battleback ; @music = [nil,nil,nil]
refresh_bgm
end
#------------------------------------------------------------------------------
# ● Initialize
#------------------------------------------------------------------------------
def load_data
BattleManager.save_bgm_and_bgs ; @data = []
$data_enemies.compact.each {|i| @data.push(i) if !HIDE_ENEMIES_ID.include?(i.id)}
end
#--------------------------------------------------------------------------
# ● Execute Dispose
#--------------------------------------------------------------------------
def execute_dispose
return if @windows_guide == nil
Graphics.freeze ; @windows_guide.dispose ; @windows_guide = nil
@windows_status.dispose
@enemy_sprite.bitmap.dispose if !@enemy_sprite.bitmap.nil?
@enemy_sprite.dispose ; dispose_battleback
@background.bitmap.dispose ; @background.dispose
@battleback1.dispose ; @battleback2.dispose
@window_comp.dispose ; BattleManager.replay_bgm_and_bgs
end
#--------------------------------------------------------------------------
# ● Dispose_battleback
#--------------------------------------------------------------------------
def dispose_battleback
if @battleback1.bitmap != nil
@battleback1.bitmap.dispose ; @battleback1.bitmap = nil
end
if @battleback2.bitmap != nil
@battleback2.bitmap.dispose ; @battleback2.bitmap = nil
end
end
#--------------------------------------------------------------------------
# ● Create Background
#--------------------------------------------------------------------------
def create_background
@background = Sprite.new
@background.bitmap = Cache.system("war_of_the_equestria_by_ziom05-d5quvbl")
@background.z = -1
end
#--------------------------------------------------------------------------
# ● Create Window Guide
#--------------------------------------------------------------------------
def create_window_guide
@windows_guide = Window_Monster_List.new(@data)
@enemy = @data[@windows_guide.index]
@windows_status = Window_Monster_Status.new(@enemy)
@window_comp = Window_Monster_Comp.new
@old_index = @windows_guide.index
@org_pos = [@windows_guide.x,@windows_guide.y]
@fade_time = 60
end
#--------------------------------------------------------------------------
# ● Create Enemy Sprite
#--------------------------------------------------------------------------
def create_enemy_sprite
@enemy_sprite = Sprite.new ; @enemy_sprite.z = 100
@enemy_sprite_org = @enemy_sprite.x ; refresh_enemy_sprite
end
#--------------------------------------------------------------------------
# ● Create_Battleback
#--------------------------------------------------------------------------
def create_battleback
@battleback1 = Sprite.new ; @battleback1.z = 1 ; @battleback1.opacity = 0
@battleback2 = Sprite.new ; @battleback2.z = 2 ; @battleback2.opacity = 0
@old_battleback = [nil,nil] ; refresh_batteback
end
#--------------------------------------------------------------------------
# ● Update
#--------------------------------------------------------------------------
def update
@windows_guide.update ; update_command ; update_animation
refresh if @old_index != @windows_guide.index
end
#--------------------------------------------------------------------------
# ● Update Animation
#--------------------------------------------------------------------------
def update_animation
update_battleback_animation ; update_enemy_sprite_animation
end
#--------------------------------------------------------------------------
# ● Update Enemy Sprite Animation
#--------------------------------------------------------------------------
def update_enemy_sprite_animation
@enemy_sprite.opacity += 15
return if @enemy_sprite.x == @enemy_sprite_org
@enemy_sprite.x += 15
@enemy_sprite.x = @enemy_sprite_org if @enemy_sprite.x >= @enemy_sprite_org
end
#--------------------------------------------------------------------------
# ● Update Battleback Animation
#--------------------------------------------------------------------------
def update_battleback_animation
if @old_battleback == nil
@battleback1.opacity -= 10
else
@battleback1.opacity += 10
end
@battleback2.opacity = @battleback1.opacity
end
#--------------------------------------------------------------------------
# ● Update Command
#--------------------------------------------------------------------------
def update_command
if Input.trigger?(Input::B)
Sound.play_cancel ; SceneManager.return
elsif Input.trigger?(Input::C)
Sound.play_ok
end
end
#--------------------------------------------------------------------------
# ● Refresh Animation
#--------------------------------------------------------------------------
def refresh
@old_index = @windows_guide.index ; @enemy = @data[@windows_guide.index]
@windows_status.refresh(@enemy)
refresh_bgm ; refresh_enemy_sprite ; refresh_batteback
end
#--------------------------------------------------------------------------
# ● Refresh Animation
#--------------------------------------------------------------------------
def refresh_enemy_sprite
if @enemy_sprite.bitmap != nil
@enemy_sprite.bitmap.dispose ; @enemy_sprite.bitmap = nil
end
if $game_system.bestiary_defeated[@enemy.id] != nil
@enemy_sprite.bitmap = Cache.battler(@enemy.battler_name, @enemy.battler_hue)
sx = [Graphics.width - 232,Graphics.width / 2]
@enemy_sprite_org = (sx[0] / 2) - (@enemy_sprite.bitmap.width / 2)
@enemy_sprite.x = -@enemy_sprite.bitmap.width
@enemy_sprite.y = sx[1] - @enemy_sprite.bitmap.height
@enemy_sprite.opacity = 0
end
end
#--------------------------------------------------------------------------
# ● BGM Refresh
#--------------------------------------------------------------------------
def refresh_bgm
return unless MOG_MONSTER_BOOK::PLAY_MUSIC
if $game_system.bestiary_music[@enemy.id] != nil and
(@music[0] != $game_system.bestiary_music[@enemy.id].name or
@music[1] != $game_system.bestiary_music[@enemy.id].volume or
@music[2] != $game_system.bestiary_music[@enemy.id].pitch)
m = $game_system.bestiary_music[@enemy.id]
@music = [m.name, m.volume, m.pitch] ; RPG::BGM.stop
Audio.bgm_play("Audio/BGM/" + m.name, m.volume, m.pitch) rescue nil
end
end
#--------------------------------------------------------------------------
# ● Refresh Battleback
#--------------------------------------------------------------------------
def refresh_batteback
if $game_system.bestiary_battleback[@enemy.id] != nil and
(@old_battleback[0] != $game_system.bestiary_battleback[@enemy.id][0] or
@old_battleback[1] != $game_system.bestiary_battleback[@enemy.id][1])
@old_battleback = [$game_system.bestiary_battleback[@enemy.id][0], $game_system.bestiary_battleback[@enemy.id][1]]
dispose_battleback ; @battleback1.opacity = 0 ; @battleback2.opacity = 0
if $game_system.bestiary_battleback[@enemy.id][0] != nil
@battleback1.bitmap = Cache.battleback1($game_system.bestiary_battleback[@enemy.id][0])
else
@battleback1.bitmap = Cache.battleback1("")
end
if $game_system.bestiary_battleback[@enemy.id][1] != nil
@battleback2.bitmap = Cache.battleback2($game_system.bestiary_battleback[@enemy.id][1])
else
@battleback2.bitmap = Cache.battleback2("")
end
end
end
end
if MOG_MONSTER_BOOK::MENU_COMMAND
#==============================================================================
# ■ Window Menu Command
#==============================================================================
class Window_MenuCommand < Window_Command
#------------------------------------------------------------------------------
# ● Add Main Commands
#------------------------------------------------------------------------------
alias mog_bestiary_add_main_commands add_main_commands
def add_main_commands
mog_bestiary_add_main_commands
add_command(MOG_MONSTER_BOOK::MENU_COMMAND_NAME, :bestiary, main_commands_enabled)
end
end
#==============================================================================
# ■ Scene Menu
#==============================================================================
class Scene_Menu < Scene_MenuBase
#------------------------------------------------------------------------------
# ● Create Command Windows
#------------------------------------------------------------------------------
alias mog_bestiary_create_command_window create_command_window
def create_command_window
mog_bestiary_create_command_window
@command_window.set_handler(:bestiary, method(:Monster_Book))
end
#------------------------------------------------------------------------------
# ● Monster Book
#------------------------------------------------------------------------------
def Monster_Book
SceneManager.call(Monster_Book)
end
end
end
|
class PhysicalGene
attr_reader :alleles
def initialize
@alleles = []
NUMBER_OF_ALLELES.times do |i|
@alleles << PhysicalAllele.new(self, i)
end
end
def to_s
total_gather_plants = 0
total_gather_insects = 0
total_gather_fish = 0
total_attack = 0
total_armor = 0
total_camouflage = 0
total_speed = 0
total_dominance = 0
total_cost = 0
total_nutrition = 0
total_dominance = 0
@alleles.each do |allele|
total_gather_plants += allele.gather_plants
total_gather_insects += allele.gather_insects
total_gather_fish += allele.gather_fish
total_attack += allele.attack
total_armor += allele.armor
total_camouflage += allele.camouflage
total_speed += allele.speed
total_dominance += allele.dominance
total_cost += allele.cost
total_nutrition += allele.nutrition
total_dominance += allele.dominance
end
puts "total_gather_plants = #{(total_gather_plants / NUMBER_OF_ALLELES).round(2)}"
puts "total_gather_insects = #{(total_gather_insects / NUMBER_OF_ALLELES).round(2)}"
puts "total_gather_fish = #{(total_gather_fish / NUMBER_OF_ALLELES).round(2)}"
puts "total_attack = #{(total_attack / NUMBER_OF_ALLELES).round(2)}"
puts "total_armor = #{(total_armor / NUMBER_OF_ALLELES).round(2)}"
puts "total_camouflage = #{(total_camouflage / NUMBER_OF_ALLELES).round(2)}"
puts "total_speed = #{(total_speed / NUMBER_OF_ALLELES).round(2)}"
puts "total_dominance = #{(total_dominance / NUMBER_OF_ALLELES).round(2)}"
puts "total_nutrition = #{(total_nutrition / NUMBER_OF_ALLELES).round(2)}"
puts "total_cost = #{(total_cost / NUMBER_OF_ALLELES).round(2)}"
end
end
|
require 'rails_helper'
describe 'user can access job show page from company show page' do
scenario 'user can navigate to job show page by clicking link' do
category = Category.create(title: "Tech")
company = Company.create!(name: "Spoogle")
job = company.jobs.create!(title: "Killer Whale Killer", level_of_interest: 98, city: "Bethel", category_id: category.id)
visit company_jobs_path(company)
click_on "Killer Whale Killer"
expect(current_path).to eq(job_path(job))
end
end
|
class SettingsController < ApplicationController
def index
end
def ajax_update_profile
is_success = true
name = params[:name].strip
email = params[:email].strip
begin
raise ::Yogy::Exceptions::InternalError.new "name or email blank. current_user.id => #{current_user.id}" if name.blank? or email.blank?
current_user.name = name
current_user.email = email
current_user.save!
rescue => e
Rails.logger.error( e )
is_success = false
end
render :json => {
is_success: is_success,
}
end
def ajax_delete_me
is_success = true
begin
Image.transaction do
Image.where( user_id: current_user.id ).update_all( deleted: 1 )
User.destroy( current_user.id )
end
rescue => e
Rails.logger.error( e )
is_success = false
end
render :json => {
is_success: is_success,
}
end
end
|
json.array! @explore_posts do |explore_post|
json.id explore_post.id
json.username explore_post.user.username
json.image asset_path(explore_post.image.url)
json.caption explore_post.caption
json.created_at explore_post.created_at
json.comments explore_post.comments
json.likes explore_post.user_likes
json.userImg asset_path(explore_post.user.image.url)
end
|
require './lib/match.rb'
class User
@@users = []
attr_accessor :id, :matches, :current_match, :name, :client
def initialize(name: "Anonymous", client: nil)
@client = client
@name = name
@id = self.object_id
@matches = []
@current_match = nil
save
end
def save
@@users << self
@@users.uniq!
end
def self.find(id)
@@users.each { |user| return user if user.id == id }
return nil
end
def add_match(match)
@current_match = match
@matches << match
@matches.uniq!
end
def end_current_match
@current_match = nil
end
def self.all
@@users
end
def self.clear
@@users = []
end
def match_in_progress?
@current_match != nil && !@current_match.game.game_over?
end
end
class NullUser
attr_accessor :id, :matches, :current_match, :name, :client
def initialize
@current_match = nil
@matches = []
end
def end_current_match
end
def self.find(id)
NullUser.new
end
def save
end
def add_match(match)
end
def self.all
[]
end
def self.clear
end
def current_match_in_progress?
end
def ==(nulluser)
nulluser.is_a? NullUser
end
end
|
require_relative '../../lib/parser/parser'
require_relative '../../lib/dom/dom'
describe CodeObject::Converter, "#to_code_object" do
context "Parsing tokens.js" do
before do
Dom.clear
stream = File.read File.expand_path('../../js-files/tokens.js', __FILE__)
comments = Parser::Parser.new(stream).parse
@objects = comments.map {|comment| comment.to_code_object }.compact
end
it "should have built three objects" do
@objects.length.should == 3
end
describe "First CodeObject" do
subject { @objects[0] }
it "should be a function named 'say_hello'" do
subject.is_a?(CodeObject::Function).should == true
subject.name.should == "say_hello"
end
it "should have a 'public'-token" do
subject.token(:public).nil?.should == false
subject.token(:public).length.should == 1
end
it "should have one param 'foo'" do
subject.params.length.should == 1
subject.params.first.should_be_named_typed_token("foo", ["String"], "some parameter\n")
end
it "should have a return value" do
subject.returns.length.should == 1
subject.returns.first.should_be_typed_token(['String', 'Integer'], "returns a string \"hello\"\n")
end
end
describe "Second CodeObject" do
subject { @objects[1] }
it "should be an Object named 'FOO'" do
subject.is_a?(CodeObject::Object).should == true
subject.name.should == "FOO"
end
end
describe "Third CodeObject" do
subject { @objects[2] }
it "should be an Function named 'some_function'" do
subject.is_a?(CodeObject::Function).should == true
subject.name.should == "some_function"
end
it "should be flagged as constructor" do
subject.constructor?.should == true
end
it "should contain one param 'parameter1'" do
subject.params.length.should == 1
subject.params.first.should_be_named_typed_token("parameter1", ["String"], "The first parameter\n")
end
end
end
end
|
class AddArtistIdOldSecondaryToArtists < ActiveRecord::Migration
def change
add_column :artists, :artist_id_old_secondary, :integer
end
end
|
# frozen_string_literal: true
module Admin
class AttachmentsController < BaseController
def destroy
@attachment = Attachment.find(params[:id])
authorize @attachment
@attachment.destroy
redirect_to edit_admin_course_path(@attachment.course)
end
end
end
|
require 'pp' # pretty print
require 'ostruct'
# Input from this file will be received from view, sent to controller, and then to this file.
class ConfigSlot
# Class variables
@@n = OpenStruct.new
def self.n
@@n
end
@@m = OpenStruct.new
def self.m
@@m
end
@@l = OpenStruct.new
def self.l
@@l
end
@@symbol = Hash.new
def self.symbol
@@symbol
end
# 1) Define the maximum number of prizes for each prize category
n.prize_total = 2
m.prize_total = 2
l.prize_total = 2
# 2) Set the symbols needed to run the game
symbol_count = n.prize_total + m.prize_total + l.prize_total + 1
for i in 1..symbol_count
symbol[:"s#{i}"] = nil # symbol assignment, e.g. '7'
end
symbol[:s1] = 'space'
# temp, this needs to be input driven
symbol[:s2] = '7'
symbol[:s3] = 'bar'
symbol[:s4] = 'bell'
symbol[:s5] = 'cherry'
symbol[:s6] = 'star'
symbol[:s7] = 'x'
# 3) Define the paylines, probability of occuring with the proper tokens
n.payline_prob_array = [0.03, 0.02]
m.payline_prob_array = [0.04, 0.05]
l.payline_prob_array = [0.06, 0.07]
n.payline_prob = Hash.new
m.payline_prob = Hash.new
l.payline_prob = Hash.new
n.symbol = Hash.new
m.symbol = Hash.new
l.symbol = Hash.new
# Setting symbols and defining paylines, triple of assigned symbol to payline is the winner
for i in 1..n.prize_total
n.payline_prob[:"n#{i}"] = n.payline_prob_array[i-1]
n.symbol[:"n#{i}"] = :"s#{i+1}" # i + 1 to skip over space
end
for i in 1..m.prize_total
m.payline_prob[:"m#{i}"] = m.payline_prob_array[i-1]
m.symbol[:"m#{i}"] = :"s#{i+1+n.prize_total}"
end
for i in 1..l.prize_total
l.payline_prob[:"l#{i}"] = l.payline_prob_array[i-1]
l.symbol[:"l#{i}"] = :"s#{i+1+n.prize_total+m.prize_total}"
end
# 4) Define the prizes, how do I make a general hash with these specific keys and they will be
# filled in from the form?
n.prize = Hash.new
m.prize = Hash.new
l.prize = Hash.new
# prize definitions
for i in 1..n.prize_total
n.prize[:"n#{i}"] = { business_id: :b1, business_name: 'cashbury', prize_name: "prize_n#{i}", prize_value: 5, prize_cost: 1,
prize_group: 'n', prize_type: 'item', max_spend: 1, max_quantity: 1 }
end
for i in 1..m.prize_total
m.prize[:"m#{i}"] = { business_id: :b2, business_name: 'blue bottle', prize_name: "prize_m#{i}", prize_value: 3, prize_cost: 1,
prize_group: 'm', prize_type: 'item', max_spend: 1, max_quantity: 1 }
end
for i in 1..l.prize_total
l.prize[:"l#{i}"] = { business_id: :b3, business_name: 'starbucks', prize_name: "prize_l#{i}", prize_value: 2, prize_cost: 1,
prize_group: 'l', prize_type: 'credit', max_spend: 1, max_quantity: 1 }
end
# business info
@@business = OpenStruct.new
def self.business
@@business
end
business.log = Hash.new
business.log[:b1] = { business_name: 'cashbury', prizes_issued: 0, total_value: 0, total_cost: 0, user_winners: Array.new, gross_margin: 0.25}
business.log[:b2] = { business_name: 'blue_bottle', prizes_issued: 0, total_value: 0, total_cost: 0, user_winners: Array.new, gross_margin: 0.3}
business.log[:b3] = { business_name: 'starbucks', prizes_issued: 0, total_value: 0, total_cost: 0, user_winners: Array.new, gross_margin: 0.2}
# 5) Assign or auto-assign the prize to an available payline in the group
# from form in View, assign prize to payline :n1, etc.
# 6) coin distribution and user definition, use percentages, see new info
@@user = OpenStruct.new
def self.user
@@user
end
user.count = 100 # can change, a percentage of the user population will contain a percentage of the credits. generate distribution and users dynamically.
user.n_credits = Hash.new
user.nm_credits = Hash.new
user.nml_credits = Hash.new
user.log = Hash.new
@@credit = OpenStruct.new
def self.credit
@@credit
end
credit.total = 33000 # this number of tokens reflects a game cycle
credit.distribution = Hash.new
credit.distribution[:n] = 0.2
credit.distribution[:nm] = 0.6
credit.distribution[:nml] = 0.2
credit.rate_per_day = 1000
for i in 1..user.count
user.n_credits[:"u#{i}"] = credit.rate_per_day / user.count * credit.distribution[:n]
user.nm_credits[:"u#{i}"] = credit.rate_per_day / user.count * credit.distribution[:nm]
user.nml_credits[:"u#{i}"] = credit.rate_per_day / user.count * credit.distribution[:nml]
user.log[:"u#{i}"] = {wins: 0, value: 0}
end
=begin
token = OpenStruct.new
token.nml_percentage = 1.0
token.nm_percentage = 0.0
=end
end
|
class CreateExamRoomPracticeExams < ActiveRecord::Migration
def change
create_table :exam_room_practice_exams do |t|
t.integer "exam_code_id", :null => false
t.integer "user_id", :null => false
t.integer "time_taken", :null => false
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.integer "num_questions", :null => false
t.integer "num_correct_answers", :null => false
t.integer "num_incorrect_answers", :null => false
t.integer "num_skipped_answers", :null => false
t.integer "time_taken", :null => false
t.integer "num_questions_attempted", :null => false
t.boolean "legal_read", :null => false
end
end
end
|
# frozen_string_literal: true
ConsoleCreep.setup do |config|
# == Enabled
#
# If ConsoleCreep should be enabled for the current environment.
#
# Default:
# config.enabled = Rails.env.production?
#
# config.enabled = Rails.env.staging? || Rails.env.production?
#
# == Authorization
#
# How you want to handle a user logging into Rails Console. Defaults
# to a `:devise` strategy, which allows you to login with an email/password combo.
#
# Default:
# config.authorization = :devise
#
# You can optionally set the class of the Devise user that is presumed to be an admin, or
# have an admin flag.
#
# config.authorization = :devise, { class: "AdminUser" }
#
# Or use a proc to check if the record is an admin record:
#
# config.authorization = :devise, { class: "User", if: ->(user) { user.admin? } }
#
# == Store
#
# Where the logs of commands, results, and errors are stored. Options are `:logger` and `:database`.
# Defaults to `:logger` and writing to `log/console.log`.
#
# Default:
# config.store = :logger
#
# Change the file:
# config.store = :logger, { file: Rails.root.join("log/creep.log") }
#
# Or log everything to the database. This assumes you have a model called `ConsoleCreepLog`. See README.md for a migration.
# config.store = :database
#
# Change the model:
# config.store = :database, { model: "ConsoleLog" }
#
# Skip storing certain parts of the console process (options are `:command`, `:result`, and `:error`)
# config.store = :database, { model: "ConsoleLog", except: [:result] }
#
# == Welcome Message
#
# Set the welcome message. Use a proc or something that responds to `#call`.
#
# Default:
# config.welcome = ->(user) { puts "\n Welcome #{user.email}!\n\nReminder: These sessions are recorded." }
#
# == Skip logging for a specific user
#
# Optionally skip logging for a specific authenticated user. Send it anything that responds to `#call`.
#
# Default:
# config.log_for_user = ->(user) { true }
# == Filtering out specific results
#
# Pass an array of filter objects — an object that responds to `.call` and accepts arguments of `user`, `command`, `result`, `error`,
# and return false if you want to exclude it from being stored by your `store`.
#
# Default:
# config.filters << ->(user, command, result, error) { true }
#
# Ignore everything that's an error:
# config.filters << ->(user, command, result, error) { error.present? }
#
# log_for_user takes precedence.
end
|
class Api::V4::PatientController < PatientAPIController
skip_before_action :validate_current_patient, only: [:activate, :login]
skip_before_action :authenticate, only: [:activate, :login]
def activate
passport = PatientBusinessIdentifier.find_by(
identifier: passport_id,
identifier_type: "simple_bp_passport"
)
patient = passport&.patient
return head :not_found unless patient.present? && patient.latest_mobile_number.present?
authentication = PassportAuthentication.find_or_create_by!(patient_business_identifier: passport)
unless authentication.otp_valid?
authentication.reset_otp
authentication.save!
end
unless Flipper.enabled?(:fixed_otp)
SendPatientOtpSmsJob.perform_later(authentication)
end
head :ok
end
def login
passport = PatientBusinessIdentifier.find_by(
identifier: passport_id,
identifier_type: "simple_bp_passport"
)
patient = passport&.patient
return head :unauthorized unless patient.present?
authentication = PassportAuthentication.find_by!(patient_business_identifier: passport)
if authentication.validate_otp(otp)
render json: access_token_response(authentication), status: :ok
else
head :unauthorized
end
end
def show
end
private
def passport_id
params.require(:passport_id)
end
def otp
params.require(:otp)
end
def access_token_response(authentication)
{
patient: {
id: authentication.patient.id,
access_token: authentication.access_token,
passport: {
id: authentication.patient_business_identifier.identifier,
shortcode: authentication.patient_business_identifier.shortcode
}
}
}
end
end
|
require 'spec_helper'
describe Calculator::Evaluator do
before do
@evaluator = Calculator::Evaluator.new
end
context 'addition' do
it ' should add two integers' do
expect(@evaluator.evaluate_string('10 + 20')).to eq 30
end
it 'add three integers' do
expect(@evaluator.evaluate_string('1 + 2 + 3')).to eq 6
end
it 'add an integer and a float' do
expect(@evaluator.evaluate_string('10.5 + 2')).to eq 12.5
end
end
context 'subtraction' do
it 'should subtract two integers' do
expect(@evaluator.evaluate_string('10 - 2')).to eq 8
end
it 'should subtract three integers' do
expect(@evaluator.evaluate_string('10 - 2 - 4')).to eq 4
end
end
context 'multiplication' do
it 'should multiply two integers' do
expect(@evaluator.evaluate_string('10 * 2')).to eq 20
end
it 'should multiply three integers' do
expect(@evaluator.evaluate_string('10 * 2 * 5')).to eq 100
end
end
context 'division' do
it 'should divide two integers' do
expect(@evaluator.evaluate_string('10 / 2')).to eq 5
end
it 'should divide two integers and a float' do
expect(@evaluator.evaluate_string('10.0 / 2 / 2')).to eq 2.5
end
end
end
|
json.array!(@profiles) do |profile|
json.extract! profile, :id, :name, :cpf, :description, :mobile, :zipcode, :address, :number, :complement, :neighborhood, :city, :state
json.url client_profile_url(profile, format: :json)
json.owner profile.owner, :id, :email, :name, :image, :mon, :tue, :wed, :thu, :fri, :sat, :sun, :start, :end, :time_per_client
end
|
class Score # because Results::Score conflicts with a testing class... :/
def initialize(event)
@event = event
end
attr_reader :event
# normalized scores should all ensure:
# 1. the largest values are the best. by sorting desc the best finisher
# should be first.
# 2. unrecorded scores should not conflict with any actually recorded scores.
# 3. unrecorded scores should be rankable and be considered as the worst result of the field.
def to_raw(normalized)
if timed?
raw_timed_score(normalized)
else
raw_weight_or_reps_score(normalized)
end
end
def to_est_raw(normalized)
# the only difference with to_raw will be that we won't use a time cap "C+N" format.
if timed?
est_raw_timed_score(normalized)
else
to_raw(normalized)
end
end
def to_normalized(raw)
if timed?
- normalize_time_score_ms(raw)
else
normalize_weight_or_reps_score(raw)
end
end
def to_est_normalized(raw)
if time_capped?(raw)
- est_normalized_time_score_ms(raw)
else
to_normalized(raw)
end
end
def time_capped?(raw)
timed? && !! (raw =~ /c(\+(\d+))?/i)
end
delegate :reps, to: :event
private
delegate :timed?, :time_cap_ms, to: :event
NO_SCORE_RECORDED = /^(?:\s*|---|DNF|WD|CUT|MED|--)$/
MAXIMUM_POSTGRESQL_INTEGER = 2_147_483_647
def normalized_time_capped?(normalized)
time_cap_ms && (- normalized) > time_cap_ms
end
def est_raw_timed_score(normalized)
ChronicDuration.output(- (normalized / 1_000.0), format: :chrono)
end
def raw_timed_score(normalized)
if normalized_time_capped?(normalized)
difference = - (normalized + time_cap_ms)
"C+#{difference / 1_000}"
else
est_raw_timed_score(normalized)
end
end
def raw_weight_or_reps_score(normalized)
normalized.to_s
end
def normalize_time_score_ms(raw_score)
if raw_score.nil? || raw_score =~ NO_SCORE_RECORDED
MAXIMUM_POSTGRESQL_INTEGER
elsif time_capped?(raw_score)
# unless estimating, always assume 1_000 ms per penalty unit
time_cap_ms + (penalty_units(raw_score) * 1_000)
else
parse_ms(raw_score)
end
end
def est_normalized_time_score_ms(raw_score)
time_cap_ms + penalty_ms(raw_score)
end
def penalty_units(raw)
raw =~ /c(\+(\d+))?/i
$1.to_i
end
def normalize_weight_or_reps_score(raw_score)
if raw_score =~ NO_SCORE_RECORDED
-1
end
raw_score =~ /(\d+)/
$1.to_i
end
# the finest granularity that HQ current records are tenths of seconds but that's an awkward unit and it might be
# a good idea to future proof ourselves against refinements.
def parse_ms(time)
(ChronicDuration.parse(time) * 1_000).to_i
end
def penalty_ms(raw)
remaining_units = penalty_units(raw)
if reps
if reps.is_a?(Array)
result = 0
reps.reverse.each do |_reps, raw_s_per_rep|
ms_per_rep = parse_ms(raw_s_per_rep)
if _reps > remaining_units
return result + remaining_units * ms_per_rep
else
remaining_units -= _reps
result += _reps * ms_per_rep
end
end
else
ms_per_rep = time_cap_ms / reps.to_f
remaining_units * ms_per_rep
end
else
remaining_units * 1_000 # assume one second / rep
end
end
end |
DB = Sequel.sqlite
DB.create_table! :customers do
primary_key :id
String :firstname
String :lastname
String :department
end
|
json.array!(@book_repositories) do |book_repository|
json.extract! book_repository, :id, :name
json.url book_repository_url(book_repository, format: :json)
end
|
class Person < ApplicationRecord
def full_name
"#{self.first_name} #{self.last_name}"
end
def self.by_first_name
order(:first_name)
end
def attributes
"#{self.age}
#{self.hair_color}
#{self.eye_color}
#{self.gender}"
end
end |
module CoreExtensions
module String
module Harmonizer
def harmonized(*methods)
return unless is_a?(::String) && present?
str = strip
methods.map { |m| harmonize_method(m) }
.each do |hash|
method, arguments = hash.values
next unless method.present? && str.respond_to?(method)
tmp = str.__send__(method, *arguments)
str = tmp if tmp.is_a?(::String)
end
str.freeze
end
private
def harmonize_method(m)
return m if valid_hash(m)
method = nil
arguments = []
if m.is_a?(::Symbol) || m.is_a?(::String)
method = m.to_sym
elsif m.is_a?(::Array) && m.present?
method = m.first.to_sym
arguments = m[1..-1]
end
{ method: method, arguments: arguments }
end
def valid_hash(m)
m.is_a?(::Hash) && m.key?(:method) && m.key?(:arguments)
end
end
end
end
|
class AddBasicAuthToSettings < ActiveRecord::Migration[5.1]
def change
add_column :settings, :login, :string
add_column :settings, :password, :string
end
end
|
class MessageResponse::Fixity < MessageResponse::Base
def pass_through_id_key
'cfs_file_id'
end
def pass_through_class_key
'cfs_file_class'
end
def self.incoming_queue
::CfsFile.incoming_queue
end
def success_method
:on_fixity_success
end
def failure_method
:on_fixity_failure
end
def unrecognized_method
:on_fixity_unrecognized
end
def checksums
self.parameter_field('checksums')
end
def md5
self.checksums['md5']
end
def sha1
self.checksums['sha1']
end
def found?
self.parameter_field('found')
end
end |
require 'spec_helper'
#TODO: replace all these doubles with VCR
describe DealsController do
describe "GET #index" do
let(:meta) { double :meta }
before :each do
CentreService.stub(:fetch).with('bondijunction').and_return double :response, body: {name: 'Centre name'}
DealService.stub(:fetch).with(centre: 'bondijunction', campaign_code: 'halloween', state: "published", rows: 50).and_return("DEAL JSON")
DealService.stub(:build).with("DEAL JSON").and_return(['Deal', 'Deal1'])
CampaignService.stub(:fetch).with(centre: 'bondijunction').and_return("CAMPAIGN JSON")
CampaignService.stub(:build).with("CAMPAIGN JSON").and_return(['Campaign', 'Campaign'])
controller.stub(:eager_load_stores)
get :index, centre_id: 'bondijunction', campaign_code: 'halloween'
end
it "populates an array of deals" do
expect(assigns(@deals)['deals']).to eql(['Deal', 'Deal1'])
end
it "renders the :index view" do
response.should render_template :index
end
describe "gon" do
let(:gon) { double(:gon, meta: Meta.new) }
context "when google content experiment param is not present" do
it "assigns nil google_content_experiment variable" do
controller.stub(:gon).and_return(gon)
gon.should_receive(:push).with(google_content_experiment: nil, centre_id: "bondijunction")
get :index, centre_id: 'bondijunction', campaign_code: 'halloween'
end
end
context "when google content experiment param is present" do
it "assigns the param value to google_content_experiment variable" do
controller.stub(:gon).and_return(gon)
gon.should_receive(:push).with(google_content_experiment: '1', centre_id: "bondijunction")
get :index, centre_id: 'bondijunction', campaign_code: 'halloween', gce_var: 1
end
end
end
it "adds title to meta" do
meta.should_receive(:push).with({
page_title: "Deals, Sales & Special Offers available at Centre name",
description: "Find the best deals, sales and great offers on a variety of products and brands at Centre name"
})
controller.stub(:meta).and_return(meta)
get :index, centre_id: 'bondijunction', campaign_code: 'halloween'
end
end
describe "GET #show" do
let(:centre_id) { 'bondijunction' }
let(:store_service_id) { 12 }
let(:deal_store) { double(:deal_store, store_service_id: store_service_id, centre_id: centre_id) }
let(:store) { double(:store).as_null_object }
let(:deal_1) {
# FIXME: Drinking too much Koolaid with all these mocks. Minimally,
# removed 'as_null_object' calls since it can mask malformed models.
double(:deal,
title: 'Deal title',
description: 'Some description',
available_to: DateTime.new( Time.now.year+1, 01, 01 ),
deal_stores: [ deal_store ],
published?: true,
meta: {}
)
}
let(:deal_2) {
double(:deal,
meta: 'deal meta',
title: 'Deal title',
description: 'Some description',
available_to: DateTime.new( Time.now.year+1, 01, 01 ),
deal_stores: [ deal_store ],
published?: true,
meta: {}
)
}
let(:meta) { double :meta }
before :each do
CentreService.stub(:fetch).with(centre_id).and_return double :response, body: {}
DealService.stub(:fetch).with("1").and_return("DEAL JSON")
StoreService.stub(:fetch).with(store_service_id).and_return("STORE JSON")
StoreService.stub(:build).with("STORE JSON").and_return(store)
DealService.stub(:build).with("DEAL JSON").and_return(deal_1)
get :show, id: 1, centre_id: 'bondijunction', retailer_code: 'for-tracking'
end
it "assigns the requested deal" do
expect(assigns(@deal)['deal']).to eql(deal_1)
end
it "assigns the requested store" do
expect(assigns(@store)['store']).to eql(store)
end
it "renders the :show template" do
expect(response).to render_template :show
end
describe "gon" do
let(:gon) { double(:gon, meta: Meta.new) }
context "when google content experiment param is not present" do
it "assigns nil google_content_experiment variable" do
controller.stub(:gon).and_return(gon)
gon.should_receive(:push).with(google_content_experiment: nil, centre_id: "bondijunction")
gon.should_receive(:push).with(centre: {}, stores: [store])
get :show, id: 1, centre_id: 'bondijunction', retailer_code: 'for-tracking'
end
end
context "when google content experiment param is present" do
it "assigns the param value to google_content_experiment variable" do
controller.stub(:gon).and_return(gon)
gon.should_receive(:push).with(google_content_experiment: "1", centre_id: "bondijunction")
gon.should_receive(:push).with(centre: {}, stores: [store])
get :show, id: 1, centre_id: 'bondijunction', retailer_code: 'for-tracking', gce_var: 1
end
end
end
it "adds title to meta" do
DealService.stub(:build).with("DEAL JSON").and_return(deal_2)
meta.should_receive(:push).with(deal_2.meta)
meta.should_receive(:push).with({
title: "#{deal_2.title} from #{store.name}",
page_title: "#{deal_2.title} from #{store.name} at ",
description: "At , find #{ deal_2.title } - ends #{ deal_2.available_to.strftime("%Y-%m-%d") }"
})
controller.stub(:meta).and_return(meta)
get :show, id: 1, centre_id: 'bondijunction', retailer_code: 'for-tracking'
end
context "when a deal expired" do
let( :expired_deal ) do
Hashie::Mash.new(
state: 'expired',
deal_stores: [ deal_store ]
)
end
before( :each ) do
DealService.stub( :build ).and_return( expired_deal )
get :show, id: 1, centre_id: 'bondijunction', retailer_code: 'for-tracking'
end
it "returns four uh-oh! four" do
expect( response.response_code ).to eq( 404 )
end
end
end
end
|
class IndexAllGems < ActiveRecord::Migration
def change
add_index :all_gems, :name
add_index :all_gems, :version
end
end
|
require 'test_helper'
class YasaisControllerTest < ActionDispatch::IntegrationTest
setup do
@yasai = yasais(:one)
end
test "should get index" do
get yasais_url
assert_response :success
end
test "should get new" do
get new_yasai_url
assert_response :success
end
test "should create yasai" do
assert_difference('Yasai.count') do
post yasais_url, params: { yasai: { name: @yasai.name, quantity: @yasai.quantity } }
end
assert_redirected_to yasai_url(Yasai.last)
end
test "should show yasai" do
get yasai_url(@yasai)
assert_response :success
end
test "should get edit" do
get edit_yasai_url(@yasai)
assert_response :success
end
test "should update yasai" do
patch yasai_url(@yasai), params: { yasai: { name: @yasai.name, quantity: @yasai.quantity } }
assert_redirected_to yasai_url(@yasai)
end
test "should destroy yasai" do
assert_difference('Yasai.count', -1) do
delete yasai_url(@yasai)
end
assert_redirected_to yasais_url
end
end
|
require 'test_helper'
class HomeControllerTest < ActionDispatch::IntegrationTest
include Devise::Test::IntegrationHelpers
def setup
menus(:week2).make_current!
sign_in users(:kyle)
end
test "get home" do
get '/'
assert_redirected_to '/menu'
end
test "signout" do
get "/signout"
assert_redirected_to '/'
end
end
|
module ValidationHelper
def valid_money?(amount)
if valid_money_format?(amount)
money = remove_currency_unit_and_cents(amount)
place_values = separate_into_place_values(money)
validate_place_value_sizes(place_values)
else
false
end
end
def remove_currency_unit_and_cents(amount)
remove_cents(remove_currency_unit(amount))
end
def valid_card_number_format?(number)
number =~ /^\.{3}\d{4}$/
end
def date_format_mmddyyyy?(date)
date =~ /^\d{1,2}\/\d{2}\/\d{4}$/
end
def date_format_mmddyy?(date)
date =~ /^\d{1,2}\/\d{2}\/\d{2}$/
end
def remove_currency_unit(amount)
amount.delete("-$")
end
def remove_cents(amount)
amount.split(".").first
end
def valid_money_format?(amount)
amount =~ /^-?\$[\d,]+\.\d{2}$/
end
def descending?(array)
array == array.sort { |b, a| b<=>a }
end
private
def separate_into_place_values(money)
money.split(",")
end
def validate_place_value_sizes(place_values)
## This verifies that the number of digits between commas is correct.
## Everything but the first place value should have 3 digits.
return false if place_values.empty?
return false unless place_values[0].size <= 3
place_values[1, place_values.length].each { |place_value| return false if place_value.size > 3 }
true
end
end |
namespace :tweets do
desc "Import tweets from CSV"
task :import_csv => :environment do
require 'csv'
csv_file_path = "#{Rails.root}/lib/assets/tweets.csv"
CSV.foreach(csv_file_path, headers: true) do |row|
t = Tweet.create!({
id: row["tweet_id"],
in_reply_to_status_id: row["in_reply_to_status_id"],
in_reply_to_user_id: row["in_reply_to_user_id"],
tweet_timestamp: row["timestamp"],
source: row["source"],
text: row["text"],
retweeted_status_id: row["retweeted_status_id"],
retweeted_status_user_id: row["retweeted_status_user_id"],
retweeted_status_timestamp: row["retweeted_status_timestamp"]
})
end
end
end |
class Mission < ApplicationRecord
validates:content,{presence:true,length:{maximum:140}}
end
|
class TeamPolicy < ApplicationPolicy
class Scope < Scope
def resolve
scope.joins(:memberships).where("memberships.user_id = ?", user.id)
end
end
def create?
return true
end
def status?
return record.owner == user
end
def show?
return record.users.include?(user)
end
def update?
return record.owner == user
end
end
|
# Basic superclass for resources, which provides for serialization of the resource
# in standard media types.
#
# You need to override get_data to return a JSON-able data structure.
module Resourced
class SerializedWithType
include Base
def initialize(uri, data, type, application_context)
@uri = uri
@serialization_data = data
@serialization_type = type
@application_context = application_context
end
end
end
|
require 'spec_helper'
describe "Wine Pages" do
subject { page }
describe "index" do
before { visit wines_path }
it { should have_selector('title', text: 'All Wines') }
it { should have_selector('h1', text: 'All Wines') }
describe "wine pagination" do
before(:all) { 50.times { FactoryGirl.create(:wine) } }
after(:all) { Wine.delete_all}
it { should have_selector('div.pagination') }
it "should list each wine" do
Wine.all.each do |wine|
page.should have_selector('a', text: wine.name)
end
end
end
end
describe "details page" do
let(:wine) { FactoryGirl.create(:wine) }
before { visit wine_path(wine) }
it { should have_selector('title', text: wine.name) }
it { should have_selector('h1', text: wine.name) }
it { should have_selector('p', integer: wine.year) }
it { should have_selector('p', text: wine.description) }
end
end |
class CreateConversations < ActiveRecord::Migration[5.2]
def change
create_table :conversations do |t|
t.string :channel, null: false
t.string :mode, null: false, comment: 'public, private'
t.string :status, null: false, comment: 'openning, closed'
t.datetime :expire_at, null: false
t.timestamps
end
end
end
|
class ChangeFirstNameLastNameInReaderToNullFalse < ActiveRecord::Migration
def up
change_column :readers, :first_name, :string, null: false
change_column :readers, :last_name, :string, null: false
end
def down
change_column :reader, :first_name, :string
change_column :reader, :first_name, :string
end
end
|
#Given a list of numbers in an array,
#replace all the numbers with the product of all
#other numbers. Do this in O(n) time without using division.
def productify(arr)
lower = [1]
upper = [1]
result = []
arr[0..-2].each.with_index do |el, i|
lower << lower[-1] * arr[i]
end
i = arr.length - 1
while i > 0
upper << upper[-1] * arr[i]
i -= 1
end
i = 0
j = arr.length - 1
while i < arr.length
result << lower[i] * upper[j]
i += 1
j -= 1
end
result
end
def prodcutify1(arr)
result = Array.new(arr.length){1}
lower = 1
upper = 1
1.upto(arr.length-1) do |i|
lower = lower * arr[i-1]
result[i] = lower * result[-1]
end
(arr.length-2).downto(0) do |i|
upper = upper * arr[i + 1]
result[i] = result[i] * upper
end
result
end
p prodcutify1([2,3,4,5]) |
require 'rails_helper'
RSpec.describe PostsController, type: :controller do
before(:each) do
@user = User.create(login: 'akxcv')
@post = Post.create(user: @user, title: DEFAULT_TITLE,
content: DEFAULT_CONTENT, ip: DEFAULT_IP)
end
describe 'POST #create' do
it 'responds successfully if input is valid and creates a post' do
expect do
post :create, params: post_params
end.to change { Post.count }.by 1
expect(response).to have_http_status 200
expect(response.body).to eq(expected_response)
end
it 'creates a new user if one does not exist' do
post :create, params: post_params(login: 'alexey')
expect(response).to have_http_status 200
expect(response.body).to eq(expected_response(login: 'alexey'))
end
it 'returns 422 if user login is not valid' do
post :create, params: post_params(login: 'in.valid')
expect(response).to have_http_status 422
expect(response.body).to be_empty
end
it 'returns 422 if post title is not valid' do
post :create, params: post_params(title: 'four')
expect(response).to have_http_status 422
expect(response.body).to be_empty
end
it 'returns 422 if post content is not valid' do
post :create, params: post_params(content: 'four')
expect(response).to have_http_status 422
expect(response.body).to be_empty
end
it 'returns 422 if ip is not valid' do
post :create, params: post_params(ip: 'gibberish')
expect(response).to have_http_status 422
expect(response.body).to be_empty
end
it 'returns 422 if no data specified' do
post :create
expect(response).to have_http_status 422
end
end
describe 'POST #rate' do
it 'responds successfully if rating is valid and creates a rating' do
expect do
post :rate, params: rating_params
end.to change { Rating.count }.by 1
expect(response).to have_http_status 200
expect(response.body).to eq 4.0.to_json
end
it 'returns 422 if rating is invalid' do
post :rate, params: rating_params(value: 0)
expect(response).to have_http_status 422
expect(response.body).to be_empty
end
it 'returns 422 if post does not exist' do
post :rate, params: rating_params(post_id: -1)
expect(response).to have_http_status 422
expect(response.body).to be_empty
end
it 'returns a valid average rating' do
post :rate, params: rating_params(value: 2)
expect(response.body).to eq 2.0.to_json
post :rate, params: rating_params(value: 4)
expect(response.body).to eq 3.0.to_json
post :rate, params: rating_params(value: 3)
expect(response.body).to eq 3.0.to_json
post :rate, params: rating_params(value: 1)
expect(response.body).to eq 2.5.to_json
end
it 'returns 422 if no data specified' do
post :rate
expect(response).to have_http_status 422
end
end
describe 'GET #top' do
before(:each) do
@posts = []
100.times do
@posts << Post.create(user: @user, title: DEFAULT_TITLE,
content: DEFAULT_CONTENT, ip: DEFAULT_IP)
end
1000.times do
post = @posts.sample
value = rand(5) + 1
Rating.create(post: post, value: value)
post.update_average_rating(value)
end
end
it 'returns top N posts' do
test_top_for_quantity(5)
test_top_for_quantity(50)
test_top_for_quantity(34)
end
it 'returns 422 if N < 1' do
get :top, params: { quantity: 0 }
expect(response).to have_http_status 422
expect(response.body).to be_empty
end
it 'returns 422 if not data specified' do
get :top
expect(response).to have_http_status 422
end
end
private
def post_params(params = {})
login = params[:login] || @user.login
title = params[:title] || DEFAULT_TITLE
content = params[:content] || DEFAULT_CONTENT
ip = params[:ip] || DEFAULT_IP
{
author: login,
title: title,
content: content,
ip: ip
}
end
def expected_response(params = {})
title = params[:title] || DEFAULT_TITLE
content = params[:content] || DEFAULT_CONTENT
{
post: {
title: title,
content: content,
average_rating: 0.0
}
}.to_json
end
def rating_params(params = {})
post_id = params[:post_id] || @post.id
value = params[:value] || 4
{
post_id: post_id,
value: value
}
end
def test_top_for_quantity(quantity)
get :top, params: { quantity: quantity }
expect(response).to have_http_status 200
posts = JSON.parse(response.body)['posts']
expect(posts.length).to eq quantity # Assuming quantity < count
test_top_ratings posts
end
def test_top_ratings(posts)
previous_rating = 5
posts.each do |post|
current_rating = post['average_rating']
expect(current_rating).to be <= previous_rating
previous_rating = current_rating
end
end
end
|
Rack::Attack.throttle('sessions', :limit => 6, :period => 60.seconds) do |req|
req.params['email'] if req.path == '/sessions.json' && req.post?
end
Rack::Attack.blacklisted_response = lambda do |env|
# Using 503 because it may make attacker think that they have successfully
# DOSed the site. Rack::Attack returns 403 for blacklists by default
[ 503, {}, ['Blocked']]
end
Rack::Attack.throttled_response = lambda do |env|
# name and other data about the matched throttle
body = [
env['rack.attack.matched'],
env['rack.attack.match_type'],
env['rack.attack.match_data']
].inspect
# Using 503 because it may make attacker think that they have successfully
# DOSed the site. Rack::Attack returns 429 for throttling by default
[ 503, {}, [body]]
end
# ab -n 100 -c 1 -p post_data -T 'application/x-www-form-urlencoded' http://localhost:9292/sessions
|
require "spec_helper"
module FourScore
describe Game do
let (:korben) { Player.new({name: "Korben", token: "X"}) }
let (:leeloo) { Player.new({name: "Leeloo", token: "O"}) }
let (:game) { Game.new([korben, leeloo]) }
describe "PUBLIC METHODS" do
context "#initialize" do
it "assigns players" do
expect(game.current_player.name).to eq 'Korben'
expect(game.next_player.name).to eq 'Leeloo'
end
end
end
describe "PRIVATE METHODS" do
context "#switch_players" do
it "switches players' turns" do
game.send(:switch_players)
expect(game.current_player.name).to eq 'Leeloo'
expect(game.next_player.name).to eq 'Korben'
end
end
context "#move_prompt" do
it "outputs a string to prompt the current player" do
expect(game.send(:move_prompt).class).to eq String
expect(game.send(:move_prompt).include?(game.current_player.name)).to eq true
end
end
context "#open_prompt" do
it "outputs a string to prompt for an open column" do
expect(game.send(:open_prompt, 1).include?('1')).to eq true
expect(game.send(:open_prompt, 1).include?('open')).to eq true
end
end
end
end
end
|
class Api::BaseController < ActionController::Metal
abstract!
def metal_render_json(json, options = {})
json = ActiveSupport::JSON.encode(json) unless json.respond_to?(:to_str)
json = "#{options[:callback]}(#{json})" unless options[:callback].blank?
self.content_type ||= Mime::JSON
self.response_body = json
end
end
|
require 'test_helper'
class AccountPatTypesControllerTest < ActionController::TestCase
setup do
@account_pat_type = account_pat_types(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:account_pat_types)
end
test "should get new" do
get :new
assert_response :success
end
test "should create account_pat_type" do
assert_difference('AccountPatType.count') do
post :create, account_pat_type: { name: @account_pat_type.name, surg_hosp_form_id: @account_pat_type.surg_hosp_form_id }
end
assert_redirected_to account_pat_type_path(assigns(:account_pat_type))
end
test "should show account_pat_type" do
get :show, id: @account_pat_type
assert_response :success
end
test "should get edit" do
get :edit, id: @account_pat_type
assert_response :success
end
test "should update account_pat_type" do
patch :update, id: @account_pat_type, account_pat_type: { name: @account_pat_type.name, surg_hosp_form_id: @account_pat_type.surg_hosp_form_id }
assert_redirected_to account_pat_type_path(assigns(:account_pat_type))
end
test "should destroy account_pat_type" do
assert_difference('AccountPatType.count', -1) do
delete :destroy, id: @account_pat_type
end
assert_redirected_to account_pat_types_path
end
end
|
class FoodInformationsController < ApplicationController
before_action :set_food_information, only: [:show, :edit, :update, :destroy]
# GET /food_informations
# GET /food_informations.json
def index
@food_informations = FoodInformation.all
end
# GET /food_informations/1
# GET /food_informations/1.json
def show
end
# GET /food_informations/new
def new
@food_information = FoodInformation.new
end
# GET /food_informations/1/edit
def edit
end
# POST /food_informations
# POST /food_informations.json
def create
@food_information = FoodInformation.new(food_information_params)
respond_to do |format|
if @food_information.save
format.html { redirect_to @food_information, notice: 'Food information was successfully created.' }
format.json { render :show, status: :created, location: @food_information }
else
format.html { render :new }
format.json { render json: @food_information.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /food_informations/1
# PATCH/PUT /food_informations/1.json
def update
respond_to do |format|
if @food_information.update(food_information_params)
format.html { redirect_to @food_information, notice: 'Food information was successfully updated.' }
format.json { render :show, status: :ok, location: @food_information }
else
format.html { render :edit }
format.json { render json: @food_information.errors, status: :unprocessable_entity }
end
end
end
# DELETE /food_informations/1
# DELETE /food_informations/1.json
def destroy
@food_information.destroy
respond_to do |format|
format.html { redirect_to food_informations_url, notice: 'Food information was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_food_information
@food_information = FoodInformation.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def food_information_params
params.require(:food_information).permit(:food_id, :description, :detail, :address, :phone_number)
end
end
|
class Cyclist
attr_accessor :name, :team, :type
def initialize(name, team, type)
@team = team
@type = type
@name = name
end
def present
puts "The cyclist #{@name} from the team #{@team} is a #{@type}"
end
end
cyclist = Cyclist.new('Alejandro Valverde', :Movistar, :Puncheur)
cyclist.present |
class Planet
# attr_accessor
attr_reader :name, :diameter, :year_length, :distance_from_the_sun, :number_of_moons, :attributes
def initialize(name, diameter, year_length, distance_from_the_sun, number_of_moons)
@name = name
@diameter = diameter #in miles
@year_length = year_length #in Earth days
@distance_from_the_sun = distance_from_the_sun #in Astrological Units
@number_of_moons = number_of_moons
end
# Prints all the info of a given planet
def print_all_info
return "#{@name}\n" +
" - #{@name} has a diameter of #{@diameter} miles.\n" +
" - #{@name} has a year length of #{year_length} Earth days.\n" +
" - #{@name} is #{@distance_from_the_sun} Astrological Units away from the sun.\n" +
" - #{@name} has #{@number_of_moons} number of moons.\n\n"
end
# Takes in another Planet class and calculates the distance between them in Astrological Units
def distance_from(planet)
return "#{(@distance_from_the_sun - planet.distance_from_the_sun).abs}AU"
end
end
# End of Planet Class #
class SolarSystem
attr_reader :planets, :age
def initialize(planets, age)
@planets = planets
@age = age
end
# Takes in a new Planet object and adds to this SolarSystem
def add_planet(new_planet)
@planets.push(new_planet)
end
# Returns the number of planets
def num_planets
return @planets.length
end
# Returns a String of all the planets in enumerated form
def list_planets
string = ""
@planets.length.times do |planet_index|
string += "#{planet_index + 1}. #{@planets[planet_index].name}\n"
end
return string
end
# Give an index for a planet in the solar system and return it's local year compared to solar system
def planet_local_year(index)
return @age / @planets[index].year_length
end
end
# End of SolarSystem class #
# Methods Outside The Defined Classes
# Takes in a number and returns back the same number only when user gives a valid number
# Or else they're prompted to type in a valid number
def force_valid_num(num)
until num == num.to_f.to_s || num == num.to_i.to_s
print "That is not a number. Please enter a valid number: "
num = gets.chomp
end
return num
end
# Interface for user to find out more about each planet with a numbered selection
def planet_observatory_interface(solar_system)
puts "\nWelcome to the Planet Observatory!"
puts "Please select a number to find out more about a planet!"
puts solar_system.list_planets
puts "#{solar_system.planets.length + 1}. Exit"
print "Enter number of choice: "
user_choice = gets.chomp.to_i
# Until the user picks "Exit"'s number
until user_choice == solar_system.planets.length + 1
# If user picks a valid number
if(user_choice >= 1 && user_choice <= solar_system.planets.length)
puts solar_system.planets[user_choice - 1].print_all_info
puts "\nWould you like to learn more about the other planets? "
print "Please enter another number of your choice: "
else
print "\nThat's an invalid value. Please enter a number between 1 and #{solar_system.planets.length + 1}: "
end
user_choice = gets.chomp.to_i
end
puts "Thanks for using the Planet Observatory!"
puts "\n==============\n\n"
end
# Takes in a solar system and adds a planet to it using an interface
def create_planet_interface(solar_system)
puts "Create a new planet!"
print " What's the name of the planet? "
new_name = gets.chomp
print " What's the diameter (in miles)? "
new_diameter = force_valid_num(gets.chomp).to_f
print " How many Earth days does it take for it to go around the sun? "
new_year_length = force_valid_num(gets.chomp).to_f
print " How far is it from the sun (in AU)? "
new_distance = force_valid_num(gets.chomp).to_f
print " How many moons does it have? "
new_num_moon = force_valid_num(gets.chomp).to_i
new_planet = Planet.new(new_name, new_diameter, new_year_length, new_distance, new_num_moon)
solar_system.add_planet(new_planet)
puts "\nHere's the updated list with your new planet!\n"
puts solar_system.list_planets
puts "\n==============\n"
end
planet_array = [
Planet.new(
"Mercury",
3032,
87.97,
0.39,
0
),
Planet.new(
"Venus",
7520.8,
224.7,
0.723,
0
),
Planet.new(
"Earth",
7917.5,
365.26,
1,
1
),
Planet.new(
"Mars",
4212,
686.69,
1.524,
2
),
Planet.new(
"Jupiter",
86881.4,
4331.98,
5.203,
67
),
Planet.new(
"Saturn",
72367.4,
10760.56,
9.539,
62
),
Planet.new(
"Uranus",
31518,
30685.49,
19.18,
27
),
Planet.new(
"Neptune",
30599,
60191.2,
30.06,
13
),
]
our_solar_system = SolarSystem.new(planet_array, 4_600_000_000)
create_planet_interface(our_solar_system)
planet_observatory_interface(our_solar_system)
puts "Optional Enhancement: Distance From The Sun"
rand_index1 = rand(our_solar_system.planets.length)
rand_index2 = rand(our_solar_system.planets.length)
puts "The distance between #{our_solar_system.planets[rand_index1].name} and #{our_solar_system.planets[rand_index2].name} is..."
puts "#{our_solar_system.planets[rand_index1].distance_from(our_solar_system.planets[rand_index2])}\n"
puts "\nOptional Enhancement: Planet's Local Year Method"
puts "This solar system is #{our_solar_system.age} years old"
random_planet_index = rand(our_solar_system.planets.length)
puts "Relatively, #{our_solar_system.planets[random_planet_index].name}'s local year is:"
puts "#{'%.2f' % our_solar_system.planet_local_year(random_planet_index)}"
#Optional
# [X] - Ensure that the each planet has a @distance_from_the_sun attribute.
# Using this data, add a method to determine the distance from any other planet (assuming planets are in a straight line from the sun)
# [X] - Give your solar system an age (in earth years).
# [X] - Define a method that returns the local year of the planet based on it's rotation since the beginning of the solar system
# Just create a birth year.
# Ex. solar system is 40 years old.
# 40 / year_length = current year of planet
|
class Game < ApplicationRecord
has_many :players, through: :game_outcomes
has_many :game_outcomes, dependent: :destroy
end
|
# frozen_string_literal: true
class AddForeignKeyToReferenceDocumentsReferenceId < ActiveRecord::Migration[6.1]
def change
safety_assured do
add_foreign_key :reference_documents, :references, name: :fk_reference_documents__reference_id__references__id
end
end
end
|
################################################################################
#
# Copyright (C) 2006 Peter J Jones (pjones@pmade.com)
# Copyright (C) 2010 Michael D Garriss (mgarriss@gmail.com)
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
################################################################################
require 'net/http'
require 'pathname'
require 'scrapes/cache'
################################################################################
module Scrapes
################################################################################
# Try to suck down a URI
class Crawler
################################################################################
# The cache object that this crawler is using
attr_accessor :cache
################################################################################
# The optional log object that this crawler is using
attr_accessor :log
################################################################################
# Create a new crawler for the given session
def initialize (session)
@session = session
@log = nil
@verbose = 0
@delay = 0.5
@cache = Cache.new
end
################################################################################
# Fetch a URI, using HTTP GET unless you supply <tt>post</tt>.
def fetch (uri, post={}, headers={})
@session.refresh
uri = URI.parse(@session.absolute_uri(uri))
post.empty? and cached = @cache.check(uri)
@log.info((cached ? 'C ' : 'N ') + uri.to_s) if @log
return cached if cached # FIXME
sleep(@delay) if @delay != 0
path = uri.path.dup
path << "/" if path.empty?
path << "?" + uri.query if uri.query
req = post.empty? ? Net::HTTP::Get.new(path) : Net::HTTP::Post.new(path)
req.set_form_data(post) unless post.empty?
req['Cookie'] = @session.cookies.to_header
headers.each {|k,v| req[k] = v}
res = Net::HTTP.new(uri.host, uri.port).start {|http| http.request(req)}
if @verbose >= 2
STDERR.puts "-----------------------------------------------"
STDERR.puts res.class
res.each_header {|k,v| STDERR.puts "#{k}: #{v}"}
end
# FIXME, what to do about more than one cookie
@session.cookies.from_header(res['set-cookie']) if res.key?('set-cookie')
case res
when Net::HTTPRedirection
@session.base_uris[-1] = @session.absolute_uri(res['location'])
res = fetch(res['location'], {}, headers)
end
post.empty? and @cache.update(uri, res.body)
res
end
end
################################################################################
end
################################################################################
|
require File.expand_path('../../lib/parser',__FILE__)
require File.expand_path('../../lib/spec',__FILE__)
def extract(text)
return LinkScanner.new(text).extract
end
describe "parser" do
context "no links" do
it "returns an empty array for no text" do
expect_equal extract(''), []
end
it "returns an empty array given some text" do
expect_equal extract('body'), []
end
end
it "extracts a single link" do
expect extract('[[article]]').include? 'article'
end
it "extracts another link" do
expect extract('[[bacon]]').include? 'bacon'
end
it "extracts links with spaces" do
expect extract('[[another article]]').include? 'another article'
end
it "extracts two links" do
expect_equal extract('[[one]] [[two]]'), ['one', 'two']
end
end
|
require 'vizier/arguments/file'
describe Vizier::FileArgument do
before do
@argument = Vizier::FileArgument.new(:test)
@me = File::expand_path(__FILE__)
@rel = %r{^#{ENV["PWD"]}/(.*)}.match(@me)[1]
@subject = mock("Subject")
end
it "should complete with me" do
@argument.complete([], @me[0..-2], @subject).list.should eql([@me])
end
it "should complete with relative path" do
@argument.complete([], @rel[0..-2], @subject).list.should eql([@rel])
end
it "should complete with relative dir" do
completions = @argument.complete([], File::dirname(@rel) + "/", @subject).list
completions.should_not == []
end
it "should complete at root dir" do
completions = @argument.complete([], "/et", @subject).list
completions.find_all{|cmpl| %r{./.} =~ cmpl}.should == []
completions.should include("/etc/")
end
it "should complete with list if prefix empty" do
@argument.complete([], "", @subject).list.should_not be_empty
end
it "should validate me" do
@argument.validate(@me, @subject).should eql(true)
end
it "should validate absolute paths" do
@argument.validate(File.expand_path(@me), @subject).should eql(true)
end
it "should not validate garbage" do
@argument.validate("somegarbage", @subject).should eql(false)
end
it "should not validate directory" do
@argument.validate(File.dirname(@me), @subject).should eql(false)
end
end
|
require 'spec_helper'
require 'rails_helper'
require Rails.root.join("spec/helpers/restaurant_helper.rb")
describe RestaurantsController, "test" do
context "Disable toggle action" do
before :each do
@admin = create(:user)
@admin.update_column(:admin_role, true)
@user1 = create(:user)
@restaurant = create(:restaurant, {user_id: @user1.id})
end
it "case 1: Not login, go to page sign in" do
xhr :post, "disable_toggle", :format => "js", id: @restaurant.slug
response.should redirect_to(new_user_session_path)
end
it "case 2: login, owner, go to home page" do
sign_in @user1
xhr :post, "disable_toggle", :format => "js", id: @restaurant.slug
response.should redirect_to('/')
end
it "case 3: login, admin, restaurant is enable, toggle successful to disable" do
sign_in @admin
xhr :post, "disable_toggle", :format => "js", id: @restaurant.slug
expect(@restaurant.reload.disabled).to eq true
end
it "case 4: login, admin, restaurant is disable, toggle successful to enable" do
@restaurant.update_column(:disabled, true)
sign_in @admin
xhr :post, "disable_toggle", :format => "js", id: @restaurant.slug
expect(@restaurant.reload.disabled).to eq false
end
end
end |
require 'spec_helper'
describe TMDBParty::Person do
let :person do
HTTParty::Parser.call(fixture_file('megan_fox.json'), :json).first
end
let(:megan) { TMDBParty::Person.new(person, TMDBParty::Base.new('key')) }
describe "attributes" do
it "should have a score when coming from search results" do
TMDBParty::Person.new({'score' => '0.374527342'}, TMDBParty::Base.new('key')).score.should == 0.374527342
end
it "should have an id" do
megan.id.should == 19537
end
it "should have a name" do
megan.name.should == "Megan Fox"
end
it "should have a popularity" do
megan.popularity.should == 3
end
it "should have a url" do
megan.url.should == "http://www.themoviedb.org/person/19537"
end
it "should have a biography" do
megan.biography.should be_a(String)
end
it "should have a birthplace" do
megan.birthplace.should == "Oakridge, TN"
end
it "should have a birthday" do
megan.birthday.should == Date.new(1986, 5, 16)
end
describe "biography" do
it "should have proper newlines" do
megan.biography.should include("\n")
end
it "should properly get HTML tags" do
# HTTParty does not parse the encoded hexadecimal properly. It does not consider 000F to be a hex, but 000f is
megan.biography.should include("<b>Career</b>")
end
end
end
end |
#!/usr/bin/env ruby
input_file = ARGV.first
# will append blindly to positions.csv
positions_file = "data/positions.csv"
require 'fileutils'
FileUtils.mkdir_p "data"
if input_file.nil? or input_file == ""
puts "Provide the input_file of the CSV file with disbursement details as an argument."
exit
end
unless File.exists?(input_file)
puts "Couldn't locate #{input_file}."
exit
end
unless File.exists?(positions_file)
puts "Couldn't locate #{positions_file}. Creating one now."
system "touch #{positions_file}"
end
require 'csv'
i = 0
CSV.open(positions_file, "a") do |positions|
CSV.foreach(input_file, :encoding => 'windows-1251:utf-8') do |row|
category = row[4]
if category.upcase == 'PERSONNEL COMPENSATION'
name = row[8] ? row[8].strip : ''
title = row[11] ? row[11].strip : ''
quarter = row[2] ? row[2].strip : ''
bioguide_id = row[0] ? row[0].strip : ''
office_name = row[1] ? row[1].strip.gsub("2017 ","") : ''
office_name = office_name.gsub('--','')
if title.size > 0
positions << [name, title, quarter, bioguide_id, office_name]
else
puts "[#{i}] No title for #{name}, skipping"
end
i += 1
puts "Read #{i} rows..." if i % 50000 == 0
end
end
end
puts "Finished appending #{i} new staffer position records from #{input_file} to #{positions_file}."
|
require 'jwshinroma/poopable'
require 'jwshinroma/physical/body'
require 'jwshinroma/physical/appendage'
module Jwshinroma
class Dog < Mammal
include Poopable
include Physical::Body
include Physical::Appendage
attr_reader :name
def initialize name
@name = name
end
def noise
'bark'
end
end
end
|
require File.expand_path('rm_vx_data')
module ReportSettings
REPORT_TOKEN = ''
ERR_BACKTRACE = false
MAP_POSITION = true
BATTLE_STATE = true
SYSTEM_VERSION = true
GAME_VERSION = true
PARTY_MEMBERS = true
INSTALL_ID = true
API_URL = 'http//francescobosso.altervista.org/rpgm/send_report.php'
end
module ReportSender
include ReportSettings
#--------------------------------------------------------------------------
# *
#--------------------------------------------------------------------------
def self.send
return if $game_settings && !$game_settings[:report_errors]
submit_post_request(api_url, prepare_request)
end
#--------------------------------------------------------------------------
# *
# @return [String]
#--------------------------------------------------------------------------
def self.api_url
API_URL
end
#--------------------------------------------------------------------------
# *
# @return [Hash]
#--------------------------------------------------------------------------
def self.prepare_request
request = {}
request[:err_name] = $!.message
request[:message] = $!.backtrace[0].to_s
request[:backtrace] = get_backtrace if ERR_BACKTRACE
if $game_system
get_map_info(request) if MAP_POSITION
get_battle_state(request) if BATTLE_STATE
request[:version] = game_version if GAME_VERSION
request[:system] = system_version if SYSTEM_VERSION
request[:inst_id] = $game_settings[:install_id] if INSTALL_ID
else
request[:no_init] = 1
end
request
end
#--------------------------------------------------------------------------
# *
#--------------------------------------------------------------------------
def self.get_backtrace
backtrace = ''
$!.backtrace.each {|trace|
backtrace += trace.to_s + '\n'
}
backtrace
end
#--------------------------------------------------------------------------
# *
#--------------------------------------------------------------------------
def self.get_map_info(request)
return if $game_map.nil?
request[:map_id] = $game_map.map_id
request[:m_x] = $game_player.x
request[:m_y] = $game_player.y
end
#--------------------------------------------------------------------------
# *
#--------------------------------------------------------------------------
def self.get_battle_state(request)
return unless $game_party
return unless $game_party.in_battle?
request[:troop_id] = $game_troop.troop_id
request[:turn] = $game_troop.turn_count
end
#--------------------------------------------------------------------------
# *
#--------------------------------------------------------------------------
def self.game_version
return nil unless $game_system
$game_system.game_version.to_s
end
#--------------------------------------------------------------------------
# *
#--------------------------------------------------------------------------
def self.system_version
Win.version
end
end
module SceneManager
class << self
alias run_safe run
end
#--------------------------------------------------------------------------
# *
#--------------------------------------------------------------------------
def self.run
begin
run_safe
rescue Exception
ReportSender.send unless ($TEST || $!.message == '')
raise
end
end
end
class Game_Troop < Game_Unit
attr_accessor :troop_id
end
module DataManager
class << self
alias reps_cgo create_game_objects
end
#--------------------------------------------------------------------------
# *
#--------------------------------------------------------------------------
def self.create_game_objects
reps_cgo
return if $game_settings[:install_id]
$game_settings[:install_id] = random_install_id
end
#--------------------------------------------------------------------------
# *
#--------------------------------------------------------------------------
def self.random_install_id
str1 = String.random.upcase
str2 = String.random.upcase
str3 = String.random.upcase
str4 = String.random.upcase
sprintf('%s-%s-%s-%s', str1, str2, str3, str4)
end
end |
class Ship
DIRECTIONS = {E: [0, 1, 0], S: [1, 0, 90], W: [0, -1, 180], N: [-1, 0, 270]}
DIRECTION_ANGLES = {0 => :E, 90 => :S, 180 => :W, 270 => :N}
def initialize(filename)
@row = 0
@col = 0
@direction = :E
@instructions = IO.readlines(filename).map{|line| [line[0].to_sym, line[1..-1].to_i]}
end
def distance
@row.abs + @col.abs
end
def move_all
@instructions.each do |action, distance|
move(action, distance)
end
self
end
def move(action, distance)
if DIRECTIONS.keys.include?(action)
@row += DIRECTIONS[action][0]*distance
@col += DIRECTIONS[action][1]*distance
elsif action == :F
@row += DIRECTIONS[@direction][0]*distance
@col += DIRECTIONS[@direction][1]*distance
elsif action == :L
rotate_angle(-1*distance)
elsif action == :R
rotate_angle(distance)
else
raise "Invalid move #{action} #{distance}"
end
#puts "#{@row}, #{@col}, #{@direction}"
end
def rotate_angle(angle)
current_angle = DIRECTIONS[@direction][2]
current_angle = ((current_angle + angle) % 360)
@direction = DIRECTION_ANGLES[current_angle]
end
end
puts Ship.new('test.txt').move_all.distance
puts Ship.new('input.txt').move_all.distance
class ShipWithWaypoint < Ship
def initialize(filename)
super
@wayrow = -1
@waycol = 10
end
def move(action, distance)
if action == :F
@row += @wayrow*distance
@col += @waycol*distance
elsif DIRECTIONS.keys.include?(action)
@wayrow += DIRECTIONS[action][0]*distance
@waycol += DIRECTIONS[action][1]*distance
elsif action == :L
rotate_left(distance)
elsif action == :R
rotate_right(distance)
else
raise "Invalid move #{action} #{distance}"
end
#puts "#{@row}, #{@col}, #{@direction}"
end
def rotate_right(angle)
return if angle == 0
@wayrow, @waycol = [@waycol, -1*@wayrow]
rotate_right(angle - 90)
end
def rotate_left(angle)
return if angle == 0
@wayrow, @waycol = [-1*@waycol, @wayrow]
rotate_left(angle - 90)
end
end
puts ShipWithWaypoint.new('test.txt').move_all.distance
puts ShipWithWaypoint.new('input.txt').move_all.distance
|
=begin
HIT ed EVA custom
v1.0
Serve per cambiare i valori iniziali di mira ed evasione.
=end
#==============================================================================
# ** Impostazioni
#==============================================================================
module H87_HitConfig
# Parametri di mira iniziali
Hits = {
2 => -10,#Monica
3 => 2, #Antonio
5 => 1,#Maria
6 => -15,#Cira
8 => -1,#Claudio
9 => 1,#Michele
13=> -15,#Larsa
14=> -2,#Dante
}
# Parametri di evasione iniziali
Evas = {
1 => -1,#fra
3 => -1,#anto
8 => 1,#clau
}
end
#==============================================================================
# ** H87_CustomHit
#==============================================================================
module H87_CustomHit
#-----------------------------------------------------------------------------
# * restituisce il modificatore di mira
#-----------------------------------------------------------------------------
def self.hit_modifier(actor_id)
hits(actor_id) ? hits(actor_id) : 0
end
#-----------------------------------------------------------------------------
# * restituisce il modificatore di evasione
#-----------------------------------------------------------------------------
def self.eva_modifier(actor_id)
eva(actor_id) ? eva(actor_id) : 0
end
#-----------------------------------------------------------------------------
# * restituisce la mira configurata
#-----------------------------------------------------------------------------
def self.hits(actor_id); H87_HitConfig::Hits[actor_id]; end
#-----------------------------------------------------------------------------
# * restituisce l'evasione configurata
#-----------------------------------------------------------------------------
def self.eva(actor_id); H87_HitConfig::Evas[actor_id]; end
end
#==============================================================================
# ** Game_Actor
#==============================================================================
class Game_Actor < Game_Battler
alias :base_native_hit :native_hit
alias :base_native_eva :native_eva
#-----------------------------------------------------------------------------
# * alias della mira
#-----------------------------------------------------------------------------
def native_hit
base_native_hit + H87_CustomHit.hit_modifier(self.id)
end
#-----------------------------------------------------------------------------
# * alias dell'evasione
#-----------------------------------------------------------------------------
def native_eva
base_native_eva + H87_CustomHit.eva_modifier(self.id)
end
end
|
require 'rails_helper'
require 'generator_spec'
RSpec.describe TwirpGenerator, type: :generator do
destination File.expand_path('../../tmp/dummy', __dir__)
arguments %w[test]
before(:all) do
prepare_destination
FileUtils.cp_r File.expand_path('../dummy', __dir__), File.expand_path('../../tmp', __dir__)
run_generator
end
it 'detect test_api.proto a correct handler with full package name' do
assert_file 'app/rpc/pkg/subpkg/test_api_handler.rb', /class Pkg::Subpkg::TestAPIHandler/ do |handler|
assert_instance_method :get_name, handler
end
end
end
|
Rails.application.routes.draw do
root 'pages#home' # root path
get '*path' => redirect('/') # redirect to root if any other url is entered
end
|
class Event < ApplicationRecord
geocoded_by :city
after_validation :geocode, if: :city_changed?
scope :after, -> (date) { where('date > ?', date) }
scope :before, -> (date) { where('date < ?', date) }
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.