text stringlengths 10 2.61M |
|---|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
clickbait = Category.create!(name: "Motivation")
clickbait.posts.create!(title: "10 Things Successful People Tell Themselves Every Morning")
clickbait.posts.create!(title: "Entrepreneurs Swear By This Product")
clickbait.posts.create!(title: "Learn This Meditation Technique And Develop Superpowers")
movies = Category.create!(name: "Movies")
movies.posts.create!(title: "But Does The Dog Die?")
movies.posts.create!(title: "2000s Actions Classics No One Remembers") |
class Question < ActiveRecord::Base
validates :user, presence: true
has_many :answers
belongs_to :user
end
|
Rails.application.routes.draw do
root "pages#index"
# Users
get "signup" => "users#new"
post "signup" => "users#create"
# Sessions
get "signin" => "sessions#new"
post "signin" => "sessions#create"
delete "signout" => "sessions#destroy"
get "about" => "pages#about"
end
|
class Offer < ApplicationRecord
belongs_to :business
belongs_to :offer_status
def self.parameters(param_hash,key)
param_hash.require(key).permit(
:business_id, :title, :description, :offer_status_id,
:start_from, :want_until, :work_at
)
end
def brothers
Offer.where(business_id: self.business_id).where.not(id: self.id)
end
end
|
module Chess
class Knight < Piece
register_as "N"
def end_squares(from, board)
offsets = [[1,2], [1,-2], [-1, 2], [-1, -2], [-2, -1], [-2, 1], [2, 1], [2, -1]]
gather_single_offsets(from, board, offsets)
end
end
end
|
module Builders
class CompletedReviewTurnaround < BaseService
def initialize(review)
@review = review
end
def call
::CompletedReviewTurnaround.create!(
review_request_id: @review.review_request_id,
value: caculate_completed_turnaround
)
end
def caculate_completed_turnaround
@review.opened_at.to_i - @review.pull_request.opened_at.to_i
end
end
end
|
require 'rails_helper'
RSpec.describe CompaniesHelper, type: :helper do
let!(:company) { create(:company) }
describe 'companies' do
let(:employee1) { create(:user) }
let(:employee2) { create(:user) }
let(:employee3) { create(:user) }
let!(:ma1) do
ma = create(:membership_application, :accepted,
user: employee1,
company_number: company.company_number)
ma.business_categories << create(:business_category, name: 'cat1')
ma
end
let!(:ma2) do
ma = create(:membership_application, :accepted,
user: employee2,
company_number: company.company_number)
ma.business_categories << create(:business_category, name: 'cat2')
ma
end
let!(:ma3) do
ma = create(:membership_application, :accepted,
user: employee3,
company_number: company.company_number)
ma.business_categories << create(:business_category, name: 'cat3')
ma
end
before(:all) do
expect(Company.count).to eq(0)
expect(MembershipApplication.count).to eq(0)
expect(User.count).to eq(0)
end
it '#last_category_name' do
expect(helper.last_category_name(company)).to eq 'cat3'
end
it '#list_categories' do
expect(helper.list_categories(company)).to eq 'cat1 cat2 cat3'
expect(helper.list_categories(company)).not_to include 'Träning'
end
end
describe '#full_uri' do
let(:company) { build(:company) }
it 'url starts with https://' do
company.website = 'https://example.com'
expect(helper.full_uri(company)).to eq "https://example.com"
end
it 'url starts with http://' do
company.website = 'http://example.com'
expect(helper.full_uri(company)).to eq "http://example.com"
end
it "url doesn't start with http" do
company.website = 'example.com'
expect(helper.full_uri(company)).to eq "http://example.com"
end
end
describe '#location_and_markers_for' do
it 'empty list of companies' do
expect(helper.location_and_markers_for([])).to eq([])
end
it 'one company (name is linked to the company)' do
co = build(:company)
markers = helper.location_and_markers_for([co])
expect(markers.count).to eq 1
expect(markers.first[:latitude]).to eq co.main_address.latitude
expect(markers.first[:longitude]).to eq co.main_address.longitude
expect(markers.first[:text]).to eq(helper.html_marker_text(co))
expect(markers.first[:text]).to include("#{link_to(co.name, co,target: '_blank')}")
end
it 'just show company name with no link for it' do
co = build(:company)
markers = helper.location_and_markers_for([co], link_name: false)
expect(markers.first[:text]).not_to include("#{link_to(co.name, co,target: '_blank')}")
end
end
describe '#html_marker_text' do
let(:co) { create(:company, company_number: '8776682406')}
it 'default links name to the company' do
marker_text = helper.html_marker_text(co)
expect(marker_text).to include( "#{link_to(co.name, co, target: '_blank')}" )
end
it 'name text = just the name (no link)' do
marker_text = helper.html_marker_text(co, name_html: co.name)
expect(marker_text).not_to include( "#{link_to(co.name, co, target: '_blank')}" )
end
end
describe '#address_visibility_array' do
let(:selection_array) do
[ [ I18n.t('address_visibility.street_address'), 'street_address' ],
[ I18n.t('address_visibility.post_code'), 'post_code'],
[ I18n.t('address_visibility.city'), 'city' ],
[ I18n.t('address_visibility.kommun'), 'kommun' ],
[ I18n.t('address_visibility.none'), 'none' ] ]
end
after(:each) do
I18n.locale = I18n.default_locale
end
it 'returns swedish selections array' do
I18n.locale = 'sv'
expect(selection_array[0][0]).to eq 'Gata'
expect(address_visibility_array).to match_array selection_array
end
it 'returns english selections array' do
I18n.locale = 'en'
expect(selection_array[0][0]).to eq 'Street'
expect(address_visibility_array).to match_array selection_array
end
end
describe '#show_address_fields' do
let(:admin) { create(:user, admin: true) }
let(:member) { create(:member_with_membership_app) }
let(:visitor) { build(:visitor) }
let(:company) { create(:company) }
let(:all_fields) do
[ { name: 'street_address', label: 'street', method: nil },
{ name: 'post_code', label: 'post_code', method: nil },
{ name: 'city', label: 'city', method: nil },
{ name: 'kommun', label: 'kommun', method: 'name' },
{ name: 'region', label: 'region', method: 'name' } ]
end
it 'returns all fields for admin user' do
# The helper method returns two values, so these will be in an array
expect(show_address_fields(admin, nil)).to match_array [ all_fields, true ]
end
it 'returns all fields for member associated with company' do
company = member.membership_applications[0].company
expect(show_address_fields(member, company))
.to match_array [ all_fields, true ]
end
it 'for visitor, returns fields consistent with address visibility' do
(0..Company::ADDRESS_VISIBILITY.length-1).each do |idx|
company.address_visibility = Company::ADDRESS_VISIBILITY[idx]
fields, visibility = show_address_fields(visitor, company)
expect(visibility).to be false
case company.address_visibility
when 'none'
expect(fields).to be nil
else
expect(fields).to match_array all_fields[idx, 5]
end
end
end
end
end
|
class TripLog < ActiveRecord::Base
belongs_to :car
belongs_to :driver
validates_presence_of :tripDate, :locationFrom, :locationTo, :departureTime, :arrivalTime, :mileageFrom, :mileageTo
validates_numericality_of :mileageFrom, :only_integer => true
validates_numericality_of :mileageTo, :only_integer => true
end
|
# == DESCRIPTION
# An expression database.
# = OVERVIEW
# When in doubt, you can always use ´.inspect´ on any object to get a full ist of
# available attributes
# = USAGE
# require 'expression-database'
# ExpressionDB::DBConnection.connect("mammal_expression") // Connects to the database (here: mammal_expression)
# dataset = ExpressionDB::Dataset.find(:first) // Retrieves the first dataset from the DB (usually the only one)
# dataset.samples.each do |sample|
# puts sample.name
# end
# // list all samples belonging to the dataset
#
# human = ExpressionDB::GenomeDb.find_by_name('homo_sapiens')
# human.genes.each do |gene|
# puts gene.stable_id
# gene.xref_samples.each do |x|
# puts "\t#{x.sample.name} #{x.fpkm}"
# end
# end
# // Go over all annotated genes and list expression values across all samples
#
# gene = ExpressionDB::Gene.find_by_stable_id('ENSG00000121101')
# gene.xref_samples.each do |xref|
# puts "{xref.sample.name} #{x.fpkm}"
# end
# // List all expression values for a given Ensembl gene
module ExpressionDB
# = DESCRIPTION
# GenomeDb is the table that holds information
# on the various genomes. Genomes have both ensembl_genes
# as well as cufflinks_genes (see below)
class GenomeDb < DBConnection
self.primary_key = "genome_db_id"
has_many :genes
has_many :cufflinks_genes
end
# = DESCRIPTION
# A dataset refers to a particular experiment
# the expression data was taken from. Datasets have samples, which
# are connected to ensembl_genes and cufflinks_genes with FPKM values
class Dataset < DBConnection
self.primary_key = 'dataset_id'
has_many :samples
has_many :cufflinks_genes
end
# = DESCRIPTION
# The source of the gene annotation - can be
# ensembl, rum, none
class Annotation < DBConnection
self.primary_key = 'annotation_id'
has_many :genes
has_many :cufflinks_genes
end
# = DESCRIPTION
# A sample refers to a particular tissue, from which reads
# were measured. Samples belong to datasets and are
# connected to genes and transcripts through
# xref_samples.
class Sample < DBConnection
self.primary_key = 'sample_id'
belongs_to :dataset, :foreign_key => "dataset_id"
has_many :xref_samples
end
# = DESCRIPTION
# A table holding information on annotated
# genes. Genes belong to genome_dbs and are connect to samples
# through xref_samples.
# = USAGE
# gene = ExpressionDB::Gene.find_by_stable_id('ENSG00000121101')
# gene.xref_samples.each do |xref|
# puts "#{x.sample.name} #{x.fpkm}"
# end
class Gene < DBConnection
self.primary_key = 'gene_id'
belongs_to :genome_db, :foreign_key => "genome_db_id"
belongs_to :annotation, :foreign_key => "annotation_id"
has_many :xref_samples, :foreign_key => 'source_id', :conditions => "source_type = 'gene'", :order => 'sample_id ASC'
has_many :xref_features, :foreign_key => 'source_id', :conditions => "source_type = 'gene'", :order => 'external_db_id ASC'
has_many :align_features, :foreign_key => 'source_id', :conditions => "source_type = 'gene'"
has_many :transcripts
# = DESCRIPTION
# Returns xrefs only for samples from a given dataset (ExpressionDB::Dataset object)
def xrefs_by_dataset(dataset)
return self.xref_samples.select{|x| x.sample.dataset == dataset }.sort_by{|x| x.sample.name}
end
# = DESCRIPTION
# Returns xrefs only for specific samples (ExpressionDB::Sample object required)
def xrefs_by_sample(sample)
return self.xref_samples.select{|x| x.sample == sample}
end
# = DESCRIPTION
# Collects all expression values for this gene within a given
# dataset and calculate the expression entropy as:
# S = -sum(Pi x ln(Pi)) with ...
def entropy_by_dataset(dataset)
xrefs = self.xrefs_by_dataset(dataset)
fpkms = xrefs.collect{|x| x.fpkm.to_f }
t = 0.0 # the summ of all expressions
fpkms.each {|f| t+= f }
p = [] # the values for each tissue as fraction of the total
xrefs.each do |xref|
e = xref.fpkm/t
e > 0.0 ? p << e*Math.log(e) : p << 0.0
end
answer = 0.0
p.each {|element| answer += element }
return answer*(-1)
end
end
# = DESCRIPTION
# A table holding information on EnsEMBL
# transcripts. Transcripts belong to ensembl_genes and
# are connected to samples through xref_samples
class Transcript < DBConnection
self.primary_key = 'transcript_id'
has_many :xref_samples, :foreign_key => 'source_id', :conditions => "source_type = 'transcript'", :order => 'sample_id ASC'
has_many :xref_features, :foreign_key => 'source_id', :conditions => "source_type = 'transcript'", :order => 'external_db_id ASC'
has_many :align_features, :foreign_key => 'source_id', :conditions => "source_type = 'transcript'"
belongs_to :gene
# = DESCRIPTION
# Returns xrefs only for samples from a given dataset (ExpressionDB::Dataset object)
def xrefs_by_dataset(dataset)
return self.xref_samples.select{|x| x.sample.dataset == dataset }.sort_by{|x| x.sample.name}
end
# = DESCRIPTION
# Returns xrefs only for specific samples (ExpressionDB::Sample object required)
def xrefs_by_sample(sample)
return self.xref_samples.select{|x| x.sample == sample}
end
end
# = DESCRIPTION
# A table holding cufflinks-predicted gene models.
# These models are *only* valid within the context of a given dataset.
# They are connected to sample through xref_samples
class CufflinksGene < DBConnection
self.primary_key = 'cufflinks_gene_id'
belongs_to :dataset, :foreign_key => 'dataset_id'
belongs_to :genome_db, :foreign_key => 'genome_db_id'
belongs_to :annotation, :foreign_key => 'annotation_id'
has_many :cufflinks_transcripts
has_many :xref_samples, :foreign_key => 'source_id', :conditions => "source_type = 'cufflinks_gene'", :order => 'sample_id ASC'
has_many :xref_features, :foreign_key => 'source_id', :conditions => "source_type = 'cufflinks_gene'", :order => 'external_db_id ASC'
has_many :align_features, :foreign_key => 'source_id', :conditions => "source_type = 'cufflinks_gene'"
# = DESCRIPTION
# Returns xrefs only for samples from a given dataset (ExpressionDB::Dataset object)
def xrefs_by_dataset(dataset)
return self.xref_samples.select{|x| x.sample.dataset == dataset }.sort_by{|x| x.sample.name}
end
# = DESCRIPTION
# Returns xrefs only for specific samples (ExpressionDB::Sample object required)
def xrefs_by_sample(sample)
return self.xref_samples.select{|x| x.sample == sample}
end
# = DESCRIPTION
# Collects all expression values for this gene within a given
# dataset and calculate the expression entropy as:
# S = -sum(Pi x ln(Pi)) with ...
def entropy_by_dataset(dataset)
xrefs = self.xrefs_by_dataset(dataset)
fpkms = xrefs.collect{|x| x.fpkm.to_f }
t = 0.0 # the summ of all expressions
fpkms.each {|f| t+= f }
p = [] # the values for each tissue as fraction of the total
xrefs.each do |xref|
e = xref.fpkm/t
e > 0.0 ? p << e*Math.log(e) : p << 0.0
end
answer = 0.0
p.each {|element| answer += element }
t = nil
return answer*(-1)
end
end
# = DESCRIPTION
# A table holding cufflinks-predicted transcript models.
# Transcripts belong to context-dependend cufflinks_genes.
# They are connected to sample through xref_samples
class CufflinksTranscript < DBConnection
self.primary_key = 'cufflinks_transcript_id'
belongs_to :cufflinks_gene
has_many :xref_samples, :foreign_key => 'source_id', :conditions => "source_type = 'cufflinks_transcript'"
has_many :xref_features, :foreign_key => 'source_id', :conditions => "source_type = 'cufflinks_transcript'", :order => 'external_db_id ASC'
has_many :align_features, :foreign_key => 'source_id', :conditions => "source_type = 'cufflinks_transcript'"
# = DESCRIPTION
# Returns xrefs only for samples from a given dataset (ExpressionDB::Dataset object)
def xrefs_by_dataset(dataset)
return self.xref_samples.select{|x| x.sample.dataset == dataset }.sort_by{|x| x.sample.name}
end
# = DESCRIPTION
# Returns xrefs only for specific samples (ExpressionDB::Sample object required)
def xrefs_by_sample(sample)
return self.xref_samples.select{|x| x.sample == sample}
end
end
# = DESCRIPTION
# Holds information on external databases
# Allows association of mapped features for annotations
class ExternalDb < DBConnection
self.primary_key = 'external_db_id'
has_many :xref_features
end
# = DESCRIPTION
# Links the different annotation tables to the external_db table
# Allows for mapping of aligned features (PFAM, BLAST, etc...)
class XrefFeature < DBConnection
self.primary_key = 'xref_feature_id'
belongs_to :external_db, :foreign_key => 'external_db_id'
belongs_to :gene, :class_name => "Gene", :foreign_key => 'source_id', :conditions => ["source_type = 'gene'"]
belongs_to :transcript, :class_name => "Transcript", :foreign_key => 'source_id', :conditions => ["source_type = 'transcript'"]
belongs_to :cufflinks_gene, :class_name => "CufflinksGene", :foreign_key => 'source_id', :conditions => ["source_type = 'cufflinks_gene'"]
belongs_to :cufflinks_transcript, :class_name => "CufflinksTranscript", :foreign_key => 'source_id', :conditions => ["source_type = 'cufflinks_transcript'"]
end
# = DESCRIPTION
# Links aligned features to genes and transcripts (e.g. miRNA target predictions)
class AlignFeature < DBConnection
self.primary_key = 'align_feature_id'
belongs_to :gene, :class_name => "Gene", :foreign_key => 'source_id', :conditions => ["source_type = 'gene'"]
belongs_to :transcript, :class_name => "Transcript", :foreign_key => 'source_id', :conditions => ["source_type = 'transcript'"]
belongs_to :cufflinks_gene, :class_name => "CufflinksGene", :foreign_key => 'source_id', :conditions => ["source_type = 'cufflinks_gene'"]
belongs_to :cufflinks_transcript, :class_name => "CufflinksTranscript", :foreign_key => 'source_id', :conditions => ["source_type = 'cufflinks_transcript'"]
end
# = DESCRIPTION
# Links the gene/transcript tables to samples.
# This table holds the expression data!
# = IMPORTANT
# This table links multiple tables to the sample table. Source tables are
# specified via the source_type column. Do not insert data unless specifying
# the *correct* source_type.
class XrefSample < DBConnection
self.primary_key = 'xref_id'
belongs_to :sample, :foreign_key => 'sample_id'
belongs_to :gene, :class_name => "Gene", :foreign_key => 'source_id', :conditions => ["source_type = 'gene'"]
belongs_to :transcript, :class_name => "Transcript", :foreign_key => 'source_id', :conditions => ["source_type = 'transcript'"]
belongs_to :cufflinks_gene, :class_name => "CufflinksGene", :foreign_key => 'source_id', :conditions => ["source_type = 'cufflinks_gene'"]
belongs_to :cufflinks_transcript, :class_name => "CufflinksTranscript", :foreign_key => 'source_id', :conditions => ["source_type = 'cufflinks_transcript'"]
end
# = DESCRIPTION
# Coordinates for repeat elements.
class Repeat < DBConnection
self.primary_keys :chr_name, :chr_start, :chr_end
end
# = DESCRIPTION
# Name of chromosomes and their length
class SeqRegion < DBConnection
self.primary_key = 'seq_region_id'
end
end
|
class CreateUserStories < ActiveRecord::Migration
def change
create_table :user_stories do |t|
t.string :title
t.text :description
t.text :criteria
t.integer :story_points
t.integer :priority
t.integer :estimated_hours
t.timestamps
end
end
end
|
Rails.application.routes.draw do
devise_for :users
resources :users
resources :posts#, only: [:index, :show]
get 'home(/:hello)', to: 'home#index' # скобки обозначают необязательность
root 'home#index'
get 'about', to:'home#about'
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
|
class ChangePasswordMutation < Mutations::BaseMutation
graphql_name 'ChangePassword'
argument :password, GraphQL::Types::String, required: true
argument :password_confirmation, GraphQL::Types::String, required: true, camelize: false
argument :reset_password_token, GraphQL::Types::String, required: false, camelize: false
argument :current_password, GraphQL::Types::String, required: false, camelize: false
argument :id, GraphQL::Types::Int, required: false
field :success, GraphQL::Types::Boolean, null: true
def resolve(**inputs)
user = User.reset_change_password(inputs)
raise user.errors.to_a.to_sentence(locale: I18n.locale) if !user.errors.empty?
{ success: true }
end
end
|
Gem::Specification.new do |s|
s.name = 'graphql_includable'
s.version = '1.0.0'
s.licenses = ['MIT']
s.summary = 'An ActiveSupport::Concern for GraphQL Ruby to eager-load query data'
s.authors = ['Dan Rouse', 'Josh Vickery', 'Jordan Hamill']
s.email = ['dan.rouse@squarefoot.com', 'jvickery@squarefoot.com', 'jordan@squarefoot.com']
s.files = Dir['lib/**/*'].keep_if { |file| File.file?(file) }
s.homepage = 'https://github.com/thesquarefoot/graphql_includable'
end
|
class WhySumbarsController < ApplicationController
# GET /why_sumbars
# GET /why_sumbars.json
def index
@why_sumbars = WhySumbar.all
@getting_theres = GettingThere.all
@where_to_stays = WhereToStay.all
@things_to_dos = ThingsToDo.all
@things_to_sees = ThingsToSee.all
@foods = Food.all
@transportations = Transportation.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @why_sumbars }
end
end
# GET /why_sumbars/1
# GET /why_sumbars/1.json
def show
@why_sumbar = WhySumbar.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @why_sumbar }
end
end
# GET /why_sumbars/new
# GET /why_sumbars/new.json
def new
@why_sumbar = WhySumbar.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @why_sumbar }
end
end
# GET /why_sumbars/1/edit
def edit
@why_sumbar = WhySumbar.find(params[:id])
end
# POST /why_sumbars
# POST /why_sumbars.json
def create
# @why_sumbar = current_user.why_sumbars.new(params[:why_sumbar])
@why_sumbar = WhySumbar.new(params[:why_sumbar])
@why_sumbar.user_id = current_user.id
respond_to do |format|
if @why_sumbar.save
format.html { redirect_to @why_sumbar, notice: 'Why sumbar was successfully created.' }
format.json { render json: @why_sumbar, status: :created, location: @why_sumbar }
else
format.html { render action: "new" }
format.json { render json: @why_sumbar.errors, status: :unprocessable_entity }
end
end
end
# PUT /why_sumbars/1
# PUT /why_sumbars/1.json
def update
@why_sumbar = WhySumbar.find(params[:id])
respond_to do |format|
if @why_sumbar.update_attributes(params[:why_sumbar])
format.html { redirect_to @why_sumbar, notice: 'Why sumbar was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @why_sumbar.errors, status: :unprocessable_entity }
end
end
end
# DELETE /why_sumbars/1
# DELETE /why_sumbars/1.json
def destroy
@why_sumbar = WhySumbar.find(params[:id])
@why_sumbar.destroy
respond_to do |format|
format.html { redirect_to why_sumbars_url }
format.json { head :no_content }
end
end
end
|
class Coder < ApplicationRecord
has_many :skillsets
has_many :languages, through: :skillsets
validates_presence_of :first_name, :last_name, :about, :looking_for, :img_url
end
|
require'pry'
class Artist
attr_accessor :name, :new_song, :songs
def initialize(name)
@songs = []
@name = name
end
def add_song(new_song)
self.songs << new_song
new_song.artist = self
end
def add_song_by_name(song_name)
@new_song = Song.new(song_name)
add_song(new_song)
end
def self.song_count
Song.all.count
end
end
# class Song
#
# attr_accessor :title, :artist
#
# @@all = []
#
# def initialize(title)
# @title = title
# @@all << self
# end
#
# def self.all
# @@all
# end
#
# end
#
# binding.pry
# 0
|
class Project < ActiveRecord::Base
has_many :tasks
belongs_to :user
end
|
require 'wsdl_mapper/svc_generation/operation_generator_base'
module WsdlMapper
module SvcGeneration
class OperationGenerator < OperationGeneratorBase
def generate_operation(service, port, op, result)
modules = get_module_names service.name
generate_op_input_body service, port, op, result
generate_op_input_header service, port, op, result
generate_op_output_header service, port, op, result
generate_op_output_body service, port, op, result
operation_s8r_generator.generate_operation_s8r service, port, op, result
operation_d10r_generator.generate_operation_d10r service, port, op, result
type_file_for op.name, result do |f|
f.requires operation_base.require_path
f.in_modules modules do
in_classes f, service.name.class_name, port.name.class_name do
generate_op_class f, service, port, op
end
end
end
end
def generate_op_class(f, service, port, op)
f.in_sub_class op.name.class_name, operation_base.name do
generate_op_ctr f, service, port, op
generate_new_input f, service, port, op
generate_new_output f, service, port, op
generate_input_s8r f, service, port, op
generate_output_s8r f, service, port, op
generate_input_d10r f, service, port, op
generate_output_d10r f, service, port, op
end
end
def generate_input_s8r(f, service, port, op)
name = service_namer.get_input_s8r_name(service.type, port.type, op.type).name
type_directory_name = namer.get_s8r_type_directory_name.name
f.in_def :input_s8r do
f.call :super
f.statement "@input_s8r ||= #{name}.new(#{type_directory_name})"
end
end
def generate_output_s8r(f, service, port, op)
name = service_namer.get_output_s8r_name(service.type, port.type, op.type).name
type_directory_name = namer.get_s8r_type_directory_name.name
f.in_def :output_s8r do
f.call :super
f.statement "@output_s8r ||= #{name}.new(#{type_directory_name})"
end
end
def generate_input_d10r(f, service, port, op)
name = service_namer.get_input_d10r_name(service.type, port.type, op.type).name
f.in_def :input_d10r do
f.call :super
f.statement "@input_d10r ||= #{name}"
end
end
def generate_output_d10r(f, service, port, op)
name = service_namer.get_output_d10r_name(service.type, port.type, op.type).name
f.in_def :output_d10r do
f.call :super
f.statement "@output_d10r ||= #{name}"
end
end
def generate_new_input(f, service, port, op)
f.in_def :new_input, 'header: {}', 'body: {}' do
f.call :super
header_name = service_namer.get_input_header_name(service.type, port.type, op.type)
body_name = service_namer.get_input_body_name(service.type, port.type, op.type)
header_args = get_header_parts(op.type.input).any? ? '**header' : ''
header = "#{header_name.name}.new(#{header_args})"
body_args = get_body_parts(op.type.input).any? ? '**body' : ''
body = "#{body_name.name}.new(#{body_args})"
f.call :new_message, header, body
end
end
def generate_new_output(f, service, port, op)
f.in_def :new_output, 'header: {}', 'body: {}' do
f.call :super
header_name = service_namer.get_output_header_name(service.type, port.type, op.type)
body_name = service_namer.get_output_body_name(service.type, port.type, op.type)
header_args = get_header_parts(op.type.output).any? ? '**header' : ''
header = "#{header_name.name}.new(#{header_args})"
body_args = get_body_parts(op.type.output).any? ? '**body' : ''
body = "#{body_name.name}.new(#{body_args})"
f.call :new_message, header, body
end
end
def generate_op_ctr(f, service, port, op)
f.in_def :initialize, 'api', 'service', 'port' do
f.call :super, 'api', 'service', 'port'
f.assignment '@name', op.property_name.attr_name.inspect
f.assignment '@operation_name', generate_name(op.type.name)
f.assignment '@soap_action', op.type.soap_action.inspect
f.literal_array '@requires', get_op_requires(service, port, op)
end
end
def get_op_requires(service, port, op)
requires = []
get_header_parts(op.type.input).each do |part|
next if WsdlMapper::Dom::BuiltinType.builtin? get_type_name(part.type).name
requires << part.name.require_path
end
get_body_parts(op.type.input).each do |part|
next if WsdlMapper::Dom::BuiltinType.builtin? get_type_name(part.type).name
requires << part.name.require_path
end
get_header_parts(op.type.output).each do |part|
next if WsdlMapper::Dom::BuiltinType.builtin? get_type_name(part.type).name
requires << part.name.require_path
end
get_body_parts(op.type.output).each do |part|
next if WsdlMapper::Dom::BuiltinType.builtin? get_type_name(part.type).name
requires << part.name.require_path
end
requires << namer.get_s8r_type_directory_name.require_path
requires << service_namer.get_input_header_name(service.type, port.type, op.type).require_path
requires << service_namer.get_input_body_name(service.type, port.type, op.type).require_path
requires << service_namer.get_output_header_name(service.type, port.type, op.type).require_path
requires << service_namer.get_output_body_name(service.type, port.type, op.type).require_path
requires << service_namer.get_input_s8r_name(service.type, port.type, op.type).require_path
requires << service_namer.get_input_d10r_name(service.type, port.type, op.type).require_path
requires << service_namer.get_output_s8r_name(service.type, port.type, op.type).require_path
requires << service_namer.get_output_d10r_name(service.type, port.type, op.type).require_path
requires.uniq.map(&:inspect)
end
def generate_op_output_header(service, port, op, result)
name = service_namer.get_output_header_name service.type, port.type, op.type
generate_header service, port, op, op.type.output, name, result
end
def generate_op_input_header(service, port, op, result)
name = service_namer.get_input_header_name service.type, port.type, op.type
generate_header service, port, op, op.type.input, name, result
end
def generate_header(service, port, op, in_out, name, result)
modules = get_module_names service.name
parts = get_header_parts in_out
type_file_for name, result do |f|
f.requires header_base.require_path
f.in_modules modules do
in_classes f, service.name.class_name, port.name.class_name, op.name.class_name do
generate_header_class f, name, parts
end
end
end
end
def generate_header_class(f, name, parts)
f.in_sub_class name.class_name, header_base.name do
generate_accessors f, parts
generate_ctr f, parts
end
end
def generate_op_input_body(service, port, op, result)
name = service_namer.get_input_body_name service.type, port.type, op.type
generate_body service, port, op, op.type.input, name, result
end
def generate_op_output_body(service, port, op, result)
name = service_namer.get_output_body_name service.type, port.type, op.type
generate_body service, port, op, op.type.output, name, result
end
def generate_body(service, port, op, in_out, name, result)
modules = get_module_names service.name
parts = get_body_parts in_out
type_file_for name, result do |f|
f.requires body_base.require_path
f.in_modules modules do
in_classes f, service.name.class_name, port.name.class_name, op.name.class_name do
generate_body_class f, name, parts
end
end
end
end
def generate_body_class(f, name, parts)
f.in_sub_class name.class_name, body_base.name do
generate_accessors f, parts
generate_ctr f, parts
end
end
def generate_accessors(f, parts)
f.attr_accessors(*parts.map { |p| p.property_name.attr_name })
end
def generate_ctr(f, parts)
f.in_def :initialize, *parts.map { |p| "#{p.property_name.attr_name}: nil" } do
parts.each do |p|
f.assignment p.property_name.var_name, p.property_name.attr_name
end
end
end
end
end
end
|
class Bid < ApplicationRecord
belongs_to :item
belongs_to :user
validates :price, presence: true, numericality: {greater_than: 1}
end
|
require 'spec_helper'
require 'raven/cli'
RSpec.describe Raven::CLI do
# avoid unexpectedly mutating the shared configuration object
let(:config) { Raven.configuration.dup }
context "when there's no error" do
it "sends an event" do
event = described_class.test(config.server, true, config)
expect(event).to be_a(Raven::Event)
hash = event.to_hash
expect(hash[:exception][:values][0][:type]).to eq("ZeroDivisionError")
expect(hash[:exception][:values][0][:value]).to eq("divided by 0")
end
it "logs correct values" do
logger = spy
allow_any_instance_of(Raven::Instance).to receive(:logger).and_return(logger)
event = described_class.test(config.server, true, config)
expect(logger).to have_received(:debug).with("Sending a test event:")
expect(logger).to have_received(:debug).with("-> event ID: #{event.id}")
expect(logger).to have_received(:debug).with("Done!")
end
end
context "when there's an error" do
before do
# make Configuration#sample_allowed? fail
config.sample_rate = 2.0
allow(Random::DEFAULT).to receive(:rand).and_return(3.0)
end
it "returns false" do
event = described_class.test(config.server, true, config)
expect(event).to eq(false)
end
it "logs correct values" do
logger = spy
allow_any_instance_of(Raven::Instance).to receive(:logger).and_return(logger)
described_class.test(config.server, true, config)
expect(logger).to have_received(:debug).with("Sending a test event:")
expect(logger).to have_received(:debug).with("An error occurred while attempting to send the event.")
expect(logger).not_to have_received(:debug).with("Done!")
end
end
context "when with custom environments config" do
let(:config) { Raven.configuration.dup }
before do
config.environments = %w(production test)
end
it "still sends the test event" do
event = Raven::CLI.test(config.server, true, config)
expect(event).to be_a(Raven::Event)
expect(config.errors).to be_empty
end
end
end
|
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'hadouken_game/version'
Gem::Specification.new do |spec|
spec.name = "hadouken_game"
spec.version = HadoukenGame::VERSION
spec.authors = ["Mario Idival", "Savia Freitas"]
spec.email = ["marioidival@gmail.com", "kakausf_15@hotmail.com"]
spec.summary = %q{Projeto para materia: programacao de computadores - IFRN}
spec.description = %q{Jogo de hakoudken do IFRN}
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.7"
spec.add_development_dependency "rake", "~> 10.0"
end
|
module Api
module V1
class RestaurantsController < ApplicationController
def index
restaurants = Restaurant.order(:name)
render json: {status: 'SUCCESS', message: 'Loaded Restaurants', data: restaurants}, status: :ok
end
def show
restaurant = Restaurant.find(params[:id])
render json: {status: 'SUCCESS', message: 'Loaded Restaurant', data: restaurant}, status: :ok
end
def menus
restaurant = Restaurant.find(params[:id]).menus.collect
render json: {status: 'SUCCESS', message: 'Loaded Restaurants Menus', data: restaurant}, status: :ok
end
def items
restaurant = Restaurant.find(params[:id]).menus.collect
menus = Array.new
restaurant_name = {name: Restaurant.find(params[:id]).name}
menus.push restaurant_name
restaurant.each do |menu|
params[:id] = menu.id
items = {title: menu.title, items: Menu.find(params[:id]).items.collect}
menus.push items
end
menus
render json: {status: 'SUCCESS', message: 'Loaded Restaurants Menus', data: menus}, status: :ok
end
def create
restaurant = Restaurant.new(restaurant_params)
if(restaurant.save)
render json: {status: 'SUCCESS', message: 'Saved Restaurant', data: restaurant}, status: :ok
else
render json: {status: 'ERROR', message: 'Restaurant not saved', data: restaurant.errors}, status: :unprocessable_entity
end
end
def destroy
restaurant = Restaurant.find(params[:id])
restaurant.destroy
render json: {status: 'SUCCESS', message: 'Deleted Restaurant', data: restaurant}, status: :ok
end
def update
restaurant = Restaurant.find(params[:id])
if restaurant.update(restaurant_params)
render json: {status: 'SUCCESS', message: 'Updated Restaurant', data: restaurant}, status: :ok
else
render json: {status: 'ERROR', message: 'Restaurant not updated', data: restaurant.errors}, status: :unprocessable_entity
end
end
private
def restaurant_params
params.permit(:name,:id)
end
end
end
end |
require 'helper'
describe 'getting all of my batches' do
let(:username) { String.generate }
let(:password) { String.generate }
subject { Esendex.new(username, password) }
let(:count) { 40 }
let(:batches) { Batches.generate(count) }
let(:response_body) { batches.to_xml }
before {
stub_request(:get, "https://#{username}:#{password}@api.esendex.com/v1.1/messagebatches?")
.with(query: {"count" => 25, "startIndex" => 0},
headers: {"User-Agent" => Esendex::Client::USER_AGENT})
.to_return(status: 200, body: response_body)
stub_request(:get, "https://#{username}:#{password}@api.esendex.com/v1.1/messagebatches?")
.with(query: {"count" => 25, "startIndex" => 25},
headers: {"User-Agent" => Esendex::Client::USER_AGENT})
.to_return(status: 200, body: Batches.generate(0).to_xml)
}
it 'returns an Enumerable that iterates over my batches' do
returned_batches = subject.batches.entries
returned_batches.size.must_equal count
returned_batches.zip(batches) do |returned, expected|
returned.id.must_equal expected.id
returned.created_at.must_equal expected.created_at
returned.batch_size.must_equal expected.batch_size
returned.persisted_batch_size.must_equal expected.persisted_batch_size
returned.status.must_equal expected.status.status
returned.account_reference.must_equal expected.account_reference
returned.created_by.must_equal expected.created_by
returned.name.must_equal expected.name
end
end
end
|
require "rake"
namespace :snapshotar do
desc "list available snapshots"
task list: :environment do
file = ARGV.last
task file.to_sym do ; end
p "# Snapshotar: Listing available snapshots"
p Snapshotar.list
end
desc "create a snapshots"
task create: :environment do
file = ARGV.last
task file.to_sym do ; end
file = nil if file.downcase == "snapshotar:create"
p "# Snapshotar: Creating snapshots #{file}"
p Snapshotar.create(file)
end
desc "load a snapshots"
task load: :environment do
file = ARGV.last
task file.to_sym do ; end
file = nil if file.downcase == "snapshotar:load"
p "# Snapshotar: Loading snapshot #{file}"
p Snapshotar.load(file)
end
desc "delete a snapshots"
task delete: :environment do
file = ARGV.last
task file.to_sym do ; end
file = nil if file.downcase == "snapshotar:delete"
p "# Snapshotar: Listing deleting snapshot #{file}"
p Snapshotar.delete(file)
end
end
|
require 'rails_helper'
RSpec.describe User, type: :model do
context 'two users with the same email' do
before (:each) do
@user1 = User.create({ name: 'test',
email: 'test@test.com',
password: '12345678',
password_confirmation: '12345678'
})
@user2 = User.create({ name: 'test',
email: 'test@test.com',
password: '12345678',
password_confirmation: '12345678' })
end
it 'it should save just one of the users' do
users = User.count
expect(users).to be(1)
end
it "returns the name of user1" do
expect(@user1.name).to eq("test")
end
end
context 'two users with different email' do
before (:each) do
@user1 = User.create({ name: 'test',
email: 'test1@test.com',
password: '12345678',
password_confirmation: '12345678' })
@user2 = User.create({ name: 'test',
email: 'test2@test.com',
password: '12345678',
password_confirmation: '12345678' })
end
it 'it should save both of them' do
users = User.count
expect(users).to be(2)
end
it "returns the names of users" do
expect(@user1.name).to eq(@user2.name)
end
end
end
|
class SurveysController < ApplicationController
before_action :set_survey_template, only: [:new, :show, :create, :edit, :update, :destroy]
before_action :set_survey, only: [:show, :edit, :update, :destroy]
def index
@surveys = Survey.all
end
def show
end
def new
@survey = @survey_template.surveys.new
end
def edit
end
def create
@survey = current_user.surveys.build(survey_params)
@survey.survey_template_id = params[:survey_template_id]
respond_to do |format|
if @survey.save
format.html { redirect_to root_url, notice: 'Survey was successfully created.' }
format.json { redirect_to root_url, status: :created, location: @survey }
else
format.html { render :new }
format.json { render json: @survey.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if @survey.update(survey_params)
format.html { redirect_to root_url, notice: 'Survey was successfully updated.' }
format.json { render :show, status: :ok, location: @survey }
@survey = Survey.new(answer: params[:answer])
@survey.save
else
format.html { render :edit }
format.json { render json: @survey.errors, status: :unprocessable_entity }
end
end
end
def destroy
@survey.destroy
respond_to do |format|
format.html { redirect_to root_url, notice: 'Survey was successfully destroyed.' }
format.json { head :no_content }
end
end
private
def set_survey
@survey = Survey.find(params[:id])
end
def set_survey_template
@survey_template = SurveyTemplate.find(params[:survey_template_id])
end
def survey_params
params.require(:survey).permit(:answer)
end
end
|
class Assignment < ActiveRecord::Base
has_many :assignment_family_members
has_many :family_members, through: :assignment_family_members
has_many :assignment_needs
has_many :needs, through: :assignment_needs
has_many :assignment_rewards
has_many :rewards, through: :assignment_rewards
belongs_to :owner, class_name: "FamilyMember"
end
|
# This file is part of PacketGen
# See https://github.com/sdaubert/packetgen for more informations
# Copyright (C) 2016 Sylvain Daubert <sylvain.daubert@laposte.net>
# This program is published under MIT license.
# frozen_string_literal: true
module PacketGen
module Header
class DHCP
# define DHCP Options.
# keys are option type, value are arrays containing option names
# as strings, and a hash passed to {Option#initialize}.
# @since 2.7.0
DHCP_OPTIONS = {
1 => ['subnet_mask', length: 4, v: IP::Addr],
2 => ['time_zone'],
3 => ['router', length: 4, v: IP::Addr],
4 => ['time_server', length: 4, v: IP::Addr],
5 => ['IEN_name_server', length: 4, v: IP::Addr],
6 => ['name_server', length: 4, v: IP::Addr],
7 => ['log_server', length: 4, v: IP::Addr],
8 => ['cookie_server', length: 4, v: IP::Addr],
9 => ['lpr_server', length: 4, v: IP::Addr],
12 => ['hostname'],
14 => ['dump_path'],
15 => ['domain'],
17 => ['root_disk_path'],
23 => ['default_ttl'],
24 => ['pmtu_timeout'],
28 => ['broadcast_address', length: 4, v: IP::Addr],
40 => ['NIS_domain'],
41 => ['NIS_server', length: 4, v: IP::Addr],
42 => ['NTP_server', length: 4, v: IP::Addr],
43 => ['vendor_specific'],
44 => ['NetBIOS_server', length: 4, v: IP::Addr],
45 => ['NetBIOS_dist_server', length: 4, v: IP::Addr],
50 => ['requested_addr', length: 4, v: IP::Addr],
51 => ['lease_time', length: 4, v: Types::Int32, value: 43_200],
53 => ['message-type', length: 1, v: Types::Int8],
54 => ['server_id', length: 4, v: IP::Addr],
55 => ['param_req_list'],
56 => ['error_message'],
57 => ['max_dhcp_size', length: 2, v: Types::Int16, value: 1_500],
58 => ['renewal_time', length: 4, v: Types::Int32, value: 21_600],
59 => ['rebinding_time', length: 4, v: Types::Int32, value: 37_800],
60 => ['vendor_class_id'],
61 => ['client_id'],
64 => ['NISplus_domain'],
65 => ['NISplus_server', length: 4, v: IP::Addr],
69 => ['SMTP_server', length: 4, v: IP::Addr],
70 => ['POP3_server', length: 4, v: IP::Addr],
71 => ['NNTP_server', length: 4, v: IP::Addr],
72 => ['WWW_server', length: 4, v: IP::Addr],
73 => ['finger_server', length: 4, v: IP::Addr],
74 => ['IRC_server', length: 4, v: IP::Addr]
}.freeze
# Class to indicate DHCP options end
class End < Types::Int8
def initialize(value=255)
super
end
def to_human
self.class.to_s.sub(/.*::/, '').downcase
end
alias human_type to_human
end
# Class to indicate padding after DHCP options
class Pad < End
def initialize(value=0)
super
end
end
# DHCP option
#
# A DHCP option is a {Types::TLV TLV}, so it has:
# * a {#type} ({Types::Int8}),
# * a {#length} ({Types::Int8}),
# * and a {#value}. Defalt type is {Types::String} but some options
# may use more suitable type (by example, a {IP::Addr} for +router+
# option).
# @author Sylvain Daubert
class Option < Types::TLV
# Option types
TYPES = Hash[DHCP_OPTIONS.to_a.map { |type, ary| [type, ary[0]] }]
# @param [Hash] options
# @option options [Integer] :type
# @option options [Integer] :length
# @option options [String] :value
def initialize(options={})
super
return unless DHCP_OPTIONS.key?(self.type)
h = DHCP_OPTIONS[self.type].last
return unless h.is_a? Hash
h.each do |k, v|
self.length = v if k == :length
if k == :v
self[:value] = v.new
self.value = options[:value] if options[:value]
end
end
end
# @private
alias private_read read
# Populate object from a binary string
# @param [String] str
# @return [Option,End,Pad] may return another object than itself
def read(str)
read_type = str[0].unpack('C').first
if read_type.zero?
Pad.new.read(str)
elsif read_type == 255
End.new.read(str)
elsif DHCP_OPTIONS.key?(read_type)
Option.new(DHCP_OPTIONS[read_type][1] || {}).private_read(str)
else
super
end
end
# @since 2.7.0
# @return [true]
def human_types?
true
end
# Get human-readable type
# @return [String]
def human_type
if DHCP_OPTIONS.key?(type)
DHCP_OPTIONS[type].first.dup
else
type.to_s
end
end
# @return [String]
def to_human
s = human_type
if length > 0
s << if value.respond_to? :to_human
":#{value.to_human}"
elsif self[:value].is_a? Types::Int
":#{self.value.to_i}"
else
":#{value.inspect}"
end
end
s
end
end
end
end
end
|
class AddScoreToEvents < ActiveRecord::Migration[5.2]
def change
add_column :events, :scraped_score, :string
add_column :events, :team_a_score, :integer
add_column :events, :team_b_score, :integer
end
end
|
require 'rails_helper'
describe DefaultHealthAttribute, type: :model do
it { should belong_to(:target_type) }
end
|
require 'yt/models/base'
require 'yt/models/policy_rule'
module Yt
module Models
# Provides methods to interact with YouTube ContentID policies.
# A policy resource specifies rules that define a particular usage or
# match policy that a partner can associate with an asset or claim.
# @see https://developers.google.com/youtube/partner/docs/v1/policies
class Policy < Base
def initialize(options = {})
@data = options[:data]
end
# @return [String] the ID that YouTube assigns and uses to uniquely
# identify the policy.
has_attribute :id
# @return [String] the policy’s name.
has_attribute :name
# @return [String] the policy’s description.
has_attribute :description
# @return [String] the time the policy was updated.
has_attribute :updated_at, type: Time, from: :time_updated
# @return [Array<PolicyRule>] a list of rules that specify the action
# that YouTube should take and may optionally specify the conditions
# under which that action is enforced.
has_attribute :rules do |rules|
rules.map{|rule| PolicyRule.new data: rule}
end
end
end
end |
# == Route Map
#
# Prefix Verb URI Pattern Controller#Action
# session_new GET /session/new(.:format) session#new
# login POST /login(.:format) session#create
# DELETE /login(.:format) session#destroy
# GET /login(.:format) session#new
# edit_users GET /users/edit(.:format) users#edit
# users GET /users(.:format) users#index
# POST /users(.:format) users#create
# new_user GET /users/new(.:format) users#new
# user GET /users/:id(.:format) users#show
# PATCH /users/:id(.:format) users#update
# PUT /users/:id(.:format) users#update
# DELETE /users/:id(.:format) users#destroy
# GET /databases/:database_id/:auth(.:format) databases#shareview
# database_shareedit GET /databases/:database_id/shareedit(.:format) databases#shareedit
# database_table_table_relations GET /databases/:database_id/tables/:table_id/table_relations(.:format) table_relations#index
# POST /databases/:database_id/tables/:table_id/table_relations(.:format) table_relations#create
# new_database_table_table_relation GET /databases/:database_id/tables/:table_id/table_relations/new(.:format) table_relations#new
# edit_database_table_table_relation GET /databases/:database_id/tables/:table_id/table_relations/:id/edit(.:format) table_relations#edit
# database_table_table_relation GET /databases/:database_id/tables/:table_id/table_relations/:id(.:format) table_relations#show
# PATCH /databases/:database_id/tables/:table_id/table_relations/:id(.:format) table_relations#update
# PUT /databases/:database_id/tables/:table_id/table_relations/:id(.:format) table_relations#update
# DELETE /databases/:database_id/tables/:table_id/table_relations/:id(.:format) table_relations#destroy
# database_table_fields GET /databases/:database_id/tables/:table_id/fields(.:format) fields#index
# POST /databases/:database_id/tables/:table_id/fields(.:format) fields#create
# new_database_table_field GET /databases/:database_id/tables/:table_id/fields/new(.:format) fields#new
# edit_database_table_field GET /databases/:database_id/tables/:table_id/fields/:id/edit(.:format) fields#edit
# database_table_field GET /databases/:database_id/tables/:table_id/fields/:id(.:format) fields#show
# PATCH /databases/:database_id/tables/:table_id/fields/:id(.:format) fields#update
# PUT /databases/:database_id/tables/:table_id/fields/:id(.:format) fields#update
# DELETE /databases/:database_id/tables/:table_id/fields/:id(.:format) fields#destroy
# database_tables GET /databases/:database_id/tables(.:format) tables#index
# POST /databases/:database_id/tables(.:format) tables#create
# new_database_table GET /databases/:database_id/tables/new(.:format) tables#new
# edit_database_table GET /databases/:database_id/tables/:id/edit(.:format) tables#edit
# database_table GET /databases/:database_id/tables/:id(.:format) tables#show
# PATCH /databases/:database_id/tables/:id(.:format) tables#update
# PUT /databases/:database_id/tables/:id(.:format) tables#update
# DELETE /databases/:database_id/tables/:id(.:format) tables#destroy
# databases GET /databases(.:format) databases#index
# POST /databases(.:format) databases#create
# new_database GET /databases/new(.:format) databases#new
# edit_database GET /databases/:id/edit(.:format) databases#edit
# database GET /databases/:id(.:format) databases#show
# PATCH /databases/:id(.:format) databases#update
# PUT /databases/:id(.:format) databases#update
# DELETE /databases/:id(.:format) databases#destroy
# relationships GET /relationships(.:format) relationships#index
# POST /relationships(.:format) relationships#create
# new_relationship GET /relationships/new(.:format) relationships#new
# edit_relationship GET /relationships/:id/edit(.:format) relationships#edit
# relationship GET /relationships/:id(.:format) relationships#show
# PATCH /relationships/:id(.:format) relationships#update
# PUT /relationships/:id(.:format) relationships#update
# DELETE /relationships/:id(.:format) relationships#destroy
# root GET / generator#index
# GET /generator/:id(.:format) generator#create
# GET /generator/tutorial/:id(.:format) generator#tutorial
# GET /generator/qr/:id(.:format) generator#qr
#
Rails.application.routes.draw do
get 'session/new'
post '/login' => 'session#create'
delete '/login' => 'session#destroy'
get '/login' => 'session#new'
resources :users, :except => [:edit] do
collection do
get 'edit' => 'users#edit'
end
end
resources :databases do
get '/shareedit' => 'databases#shareedit'
get '/:auth' => 'databases#shareview'
resources :tables do
resources :table_relations
resources :fields
end
end
resources :relationships
root :to => 'generator#index'
get '/generator/:id' => 'generator#create'
get '/generator/tutorial/:id' => 'generator#tutorial'
get '/generator/qr/:id' => 'generator#qr'
end
|
module Farandula
class Seat
attr_accessor :cabin, :place
def initialize(
cabin = nil,
place = nil
)
@cabin = cabin
@place = place
end
def to_s
"cabin #{cabin}, place code #{place}."
end
end
end
|
#
# Cookbook Name:: neobundle
# Recipe:: default
#
BUNDLE_HOME = "/home/" + node["neobundle"]["user"] + "/.vim/bundle"
USER = node["neobundle"]["user"]
GROUP = node["neobundle"]["group"]
directory BUNDLE_HOME do
owner USER
group GROUP
mode 744
action :create
recursive true
end
git BUNDLE_HOME + "/neobundle.vim/" do
user USER
group GROUP
repository "git://github.com/Shougo/neobundle.vim"
revision "master"
action :checkout
end
bash "chown" do
cwd BUNDLE_HOME
code "chown -R " << USER << ":" << GROUP << " " << BUNDLE_HOME << "&&" << "chmod -R 744 " << BUNDLE_HOME
end
template ".vimrc" do
path BUNDLE_HOME + "/../../.vimrc"
source "vimrc.erb"
owner USER
group GROUP
mode 00774
end
#errorのためコメントアウト
#package 'ctags'
|
require 'rails_helper'
RSpec.describe Student, type: :model do
it "should have a number" do
expect(subject).to have_attribute(:number)
end
it "should have a first name" do
expect(subject).to have_attribute(:first_name)
end
it "should have a last name" do
expect(subject).to have_attribute(:last_name)
end
it "is invalid without a number, first name, or last name" do
expect(subject).to be_invalid
end
it "is valid with a number, first name, and last name" do
subject.number = "2015051701"
subject.first_name = "John"
subject.last_name = "Smith"
expect(subject).to be_valid
end
end
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure("2") do |config|
config.vm.box = "ubuntu/xenial64"
config.vm.box_check_update = false
config.vm.network "public_network"
config.vm.synced_folder ".", "/var/www/rank"
config.vm.provision "shell", inline: <<-SHELL
set -ex
sudo su
ln -f -s /var/www/rank/misc/ubuntu.list /etc/apt/sources.list
mkdir -p /root/.pip
ln -f -s /var/www/rank/misc/pip.conf /root/.pip/pip.conf
apt-get update
apt-get -y install python3-pip
pip3 install Fabric3
cd /var/www/rank
fab provision
SHELL
end
|
module BankingCodeChallenge
class Account
attr_reader :number, :bank, :balance, :holder
def initialize number, bank, balance, holder="anonymous"
@number = number
@bank = bank
@balance = balance
@holder = holder
end
def depositMoney amount
@balance += amount
end
def takeOutMoney amount
@balance -= amount
end
end
end
|
module Ricer::Plugins::Core
class Tee < Ricer::Plugin
trigger_is :tee
permission_is :responsible
has_usage '<target[online=1]> <..text..>'
def execute(targets, text)
targets.each do |target|
target.send_message(text)
end
end
end
end
|
# input: string
# output: array of substrings
# rules:
# Explicit requirements:
# - every palindrom possibility in a string is output to an array
# (reminder: a palindrom is a word taht reads the same forward
# and backkward)
# - palindroms are case sensitive
# Algorithm:
# - initialize a result variable to an empty array
# - create an array named substring_arr that contains all of the
# substrings of the input string that are at least 2 characters long.
# - loop through the words in the substring_arr array
# - if the word is a palindrome, append it to the result array
# - return the result array
# for each starting index from 0 through the next to last index position
# for each substring length from 2 until there are no substrings of that length
# extract teh subsrting of the indicated length starting at the indicate index position
# end of inner loop
# end of outer loop
def substrings(str)
result = []
starting_index = 0;
while (starting_index <= str.length - 2)
num_chars = 2
while(num_chars <= str.length - starting_index)
substring = str.slice(starting_index, num_chars)
result << substring
num_chars += 1
end
starting_index += 1
end
result
end
def is_palindrome?(str)
str == str.reverse
end
def palindrome_substrings(str)
result = []
substrings_arr = substrings(str)
substrings_arr.each do |substring|
result << substring if is_palindrome?(substring)
end
result
end
p palindrome_substrings("supercalifragilisticexpialidocious")
p palindrome_substrings("abcddcbA")
p palindrome_substrings("palindrome")
p palindrome_substrings("") |
require "rails_helper"
describe ApplicationController, type: :controller do
before do
setup_application_instance
end
describe "valid application instance api token" do
before do
admin_api_permissions = {
default: [
"administrator", # Internal (non-LTI) role
"urn:lti:sysrole:ims/lis/SysAdmin",
"urn:lti:sysrole:ims/lis/Administrator",
],
common: [],
LIST_ACCOUNTS: [],
}
@application_instance.application.update(canvas_api_permissions: admin_api_permissions)
@user = FactoryBot.create(:user)
allow(controller).to receive(:current_user).and_return(@user)
@user.add_to_role("urn:lti:role:ims/lis/Learner")
@user.save!
@user_token = AuthToken.issue_token({ user_id: @user.id })
@user_token_header = "Bearer #{@user_token}"
request.headers["Authorization"] = @user_token_header
end
controller do
include CanvasSupport
before_action :protect_canvas_api
def index
result = canvas_api.proxy(params[:lms_proxy_call_type], params.to_unsafe_h, request.body.read)
response.status = result.code
render plain: result.body
end
end
it "provides access to the canvas api for an administrator" do
admin = FactoryBot.create(:user)
admin.add_to_role("administrator")
admin.save!
allow(controller).to receive(:current_user).and_return(admin)
get :index, params: {
lti_key: @application_instance.lti_key,
lms_proxy_call_type: "LIST_ACCOUNTS",
}, format: :json
expect(response).to have_http_status(:success)
end
it "prohibits a user from accessing the canvas api" do
user = FactoryBot.create(:user)
user_token = AuthToken.issue_token({ user_id: user.id })
user_token_header = "Bearer #{user_token}"
allow(controller).to receive(:current_user).and_return(user)
request.headers["Authorization"] = user_token_header
get :index, params: {
lti_key: @application_instance.lti_key,
lms_proxy_call_type: "LIST_ACCOUNTS",
}, format: :json
expect(response).to have_http_status(:forbidden)
end
it "doesn't allow access to forbidden API endpoints" do
get :index, params: {
lti_key: @application_instance.lti_key,
lms_proxy_call_type: "LIST_ACCOUNTS_FOR_COURSE_ADMINS",
}, format: :json
expect(response).to have_http_status(:forbidden)
end
it "doesn't allow access to forbidden API endpoints when application instances doesn't have an API token" do
@application_instance.update(canvas_token: nil)
get :index, params: {
lti_key: @application_instance.lti_key,
lms_proxy_call_type: "LIST_ACCOUNTS_FOR_COURSE_ADMINS",
}, format: :json
expect(response).to have_http_status(:forbidden)
end
end
describe "valid user api token" do
before do
@user = FactoryBot.create(:user)
allow(controller).to receive(:current_user).and_return(@user)
canvas_api_permissions = {
default: [
"administrator", # Internal (non-LTI) role
"urn:lti:sysrole:ims/lis/SysAdmin",
"urn:lti:sysrole:ims/lis/Administrator",
"urn:lti:role:ims/lis/Learner",
],
common: [],
LIST_ACCOUNTS: [],
}
@application_instance.application.update(canvas_api_permissions: canvas_api_permissions)
@application_instance.update(canvas_token: nil)
@authentication = FactoryBot.create(
:authentication,
provider_url: UrlHelper.scheme_host_port(@application_instance.site.url),
refresh_token: "asdf",
)
@user.authentications << @authentication
@user.add_to_role("urn:lti:role:ims/lis/Learner")
@user.save!
@user_token = AuthToken.issue_token({ user_id: @user.id })
@user_token_header = "Bearer #{@user_token}"
request.headers["Authorization"] = @user_token_header
end
describe "use application_instance.auth_precedence" do
controller do
include CanvasSupport
before_action :protect_canvas_api
def index
result = canvas_api.proxy(params[:lms_proxy_call_type], params.to_unsafe_h, request.body.read)
response.status = result.code
render plain: result.body
end
end
it "provides access to the canvas api" do
get :index, params: { lti_key: @application_instance.lti_key, lms_proxy_call_type: "LIST_ACCOUNTS" }, format: :json
expect(response).to have_http_status(:success)
end
end
describe "prefer user authentication" do
before do
canvas_api_permissions = {
default: [
"administrator", # Internal (non-LTI) role
"urn:lti:sysrole:ims/lis/SysAdmin",
"urn:lti:sysrole:ims/lis/Administrator",
"urn:lti:role:ims/lis/Learner",
],
common: [],
LIST_ACCOUNTS: [],
}
@application_instance.application.update(
canvas_api_permissions: canvas_api_permissions,
oauth_precedence: "global,application_instance,course,user",
)
@application_instance.update(canvas_token: "afaketoken")
@authentication = FactoryBot.create(
:authentication,
provider_url: UrlHelper.scheme_host_port(@application_instance.site.url),
refresh_token: "qwerty",
)
@user.authentications << @authentication
@application_instance.authentications << @authentication
@application_instance.save!
end
controller do
include CanvasSupport
before_action :protect_canvas_api
def index
api = canvas_api(prefer_user: true)
render json: api
end
end
it "provides access to the canvas api using the user's authentication" do
get :index, params: { lti_key: @application_instance.lti_key, lms_proxy_call_type: "LIST_ACCOUNTS" }, format: :json
expect(response).to have_http_status(:success)
json = JSON.parse(response.body)
expect(@user.authentications.pluck(:id).include?(json["authentication"]["id"])).to be true
end
end
end
describe "user with canvas_oauth_user" do
before do
@user = FactoryBot.create(:user)
allow(controller).to receive(:current_user).and_return(@user)
canvas_api_permissions = {
default: [],
common: [],
LIST_ACCOUNTS: ["canvas_oauth_user"],
}
@application_instance.application.update(canvas_api_permissions: canvas_api_permissions)
@application_instance.update(canvas_token: nil)
@authentication = FactoryBot.create(
:authentication,
provider_url: UrlHelper.scheme_host_port(@application_instance.site.url),
refresh_token: "asdf",
)
@user.add_to_role("canvas_oauth_user")
@user.save!
@user_token = AuthToken.issue_token({ user_id: @user.id })
@user_token_header = "Bearer #{@user_token}"
request.headers["Authorization"] = @user_token_header
end
controller do
include CanvasSupport
before_action :protect_canvas_api
def index
result = canvas_api.proxy(params[:lms_proxy_call_type], params.to_unsafe_h, request.body.read)
response.status = result.code
render plain: result.body
end
end
it "provides access to the canvas api using the user's token" do
@user.authentications << @authentication
get :index, params: {
lti_key: @application_instance.lti_key,
lms_proxy_call_type: "LIST_ACCOUNTS",
}, format: :json
expect(response).to have_http_status(:success)
end
it "denies access to the canvas api when user doesn't have a token even if application instance does have a token" do
@application.oauth_precedence = "user"
@application.save!
@application_instance.authentications << @authentication
get :index, params: {
lti_key: @application_instance.lti_key,
lms_proxy_call_type: "LIST_ACCOUNTS",
}, format: :json
expect(response).to have_http_status(:unauthorized)
end
end
describe "check context" do
before do
@user = FactoryBot.create(:user)
allow(controller).to receive(:current_user).and_return(@user)
canvas_api_permissions = {
default: [
"urn:lti:role:ims/lis/Instructor",
],
common: [],
LIST_ACCOUNTS: [],
}
@application_instance.application.update(canvas_api_permissions: canvas_api_permissions)
@application_instance.update(canvas_token: nil)
@authentication = FactoryBot.create(
:authentication,
provider_url: UrlHelper.scheme_host_port(@application_instance.site.url),
refresh_token: "asdf",
)
@user.authentications << @authentication
@context_id = "123456"
@user.add_to_role("urn:lti:role:ims/lis/Instructor", @context_id)
@user.save!
@user_token = AuthToken.issue_token({ user_id: @user.id, context_id: @context_id })
@user_token_header = "Bearer #{@user_token}"
request.headers["Authorization"] = @user_token_header
end
controller do
include CanvasSupport
before_action :protect_canvas_api
def index
result = canvas_api.proxy(params[:lms_proxy_call_type], params.to_unsafe_h, request.body.read)
response.status = result.code
render plain: result.body
end
end
it "provides access to the canvas api" do
get :index, params: {
lti_key: @application_instance.lti_key,
lms_proxy_call_type: "LIST_ACCOUNTS",
context_id: @context_id,
}, format: :json
expect(response).to have_http_status(:success)
end
end
describe "no api token for application instance or user" do
before do
@user = FactoryBot.create(:user)
allow(controller).to receive(:current_user).and_return(@user)
@user.add_to_role("urn:lti:role:ims/lis/Learner")
@user.save!
canvas_api_permissions = {
default: [
"administrator", # Internal (non-LTI) role
"urn:lti:sysrole:ims/lis/SysAdmin",
"urn:lti:sysrole:ims/lis/Administrator",
"urn:lti:role:ims/lis/Learner",
],
common: [],
LIST_ACCOUNTS: [],
}
@application_instance.application.update(canvas_api_permissions: canvas_api_permissions)
@application_instance.update(canvas_token: nil)
@user_token = AuthToken.issue_token({ user_id: @user.id })
@user_token_header = "Bearer #{@user_token}"
end
controller do
include CanvasSupport
before_action :protect_canvas_api
def index
result = canvas_api.proxy(params[:lms_proxy_call_type], params.to_unsafe_h, request.body.read)
response.status = result.code
render plain: result.body
end
end
it "returns an authorization required if it can't find a canvas api token" do
request.headers["Authorization"] = @user_token_header
get :index, params: {
lti_key: @application_instance.lti_key,
lms_proxy_call_type: "LIST_ACCOUNTS",
}, format: :json
result = JSON.parse(response.body)
expect(result["message"]).to eq("Unable to find valid Canvas API Token.")
expect(result["canvas_authorization_required"]).to eq(true)
end
end
end
|
FactoryBot.define do
factory :story do
name { "the name" }
description { "the description" }
column
due_date { Time.zone.now + 10.days }
status { "open" }
end
end
|
# frozen_string_literal: true
# rubocop:todo all
require 'lite_spec_helper'
require 'support/shared/server_selector'
describe Mongo::ServerSelector::SecondaryPreferred do
let(:name) { :secondary_preferred }
include_context 'server selector'
let(:default_address) { 'test.host' }
it_behaves_like 'a server selector mode' do
let(:secondary_ok) { true }
end
it_behaves_like 'a server selector with sensitive data in its options'
it_behaves_like 'a server selector accepting tag sets'
it_behaves_like 'a server selector accepting hedge'
describe '#initialize' do
context 'when max_staleness is provided' do
let(:options) do
{ max_staleness: 95 }
end
it 'sets the max_staleness option' do
expect(selector.max_staleness).to eq(options[:max_staleness])
end
end
end
describe '#==' do
context 'when max staleness is the same' do
let(:options) do
{ max_staleness: 90 }
end
let(:other) do
described_class.new(options)
end
it 'returns true' do
expect(selector).to eq(other)
end
end
context 'when max staleness is different' do
let(:other_options) do
{ max_staleness: 100 }
end
let(:other) do
described_class.new(other_options)
end
it 'returns false' do
expect(selector).not_to eq(other)
end
end
end
describe '#to_mongos' do
context 'tag sets provided' do
let(:tag_sets) do
[ tag_set ]
end
it 'returns a read preference formatted for mongos' do
expect(selector.to_mongos).to eq(
{ :mode => 'secondaryPreferred', :tags => tag_sets }
)
end
end
context 'tag sets not provided' do
it 'returns secondaryPreferred' do
selector.to_mongos.should == {mode: 'secondaryPreferred'}
end
end
context 'max staleness not provided' do
let(:expected) do
{ :mode => 'secondaryPreferred' }
end
it 'returns secondaryPreferred' do
selector.to_mongos.should == {mode: 'secondaryPreferred'}
end
end
context 'max staleness provided' do
let(:max_staleness) do
60
end
let(:expected) do
{ :mode => 'secondaryPreferred', maxStalenessSeconds: 60 }
end
it 'returns a read preference formatted for mongos' do
expect(selector.to_mongos).to eq(expected)
end
end
context 'hedge provided' do
let(:hedge) { { enabled: true } }
it 'returns a formatted read preference' do
expect(selector.to_mongos).to eq({ mode: 'secondaryPreferred', hedge: { enabled: true } })
end
end
context 'hedge not provided' do
let(:hedge) { nil }
it 'returns secondaryPreferred' do
selector.to_mongos.should == {mode: 'secondaryPreferred'}
end
end
end
describe '#select_in_replica_set' do
context 'no candidates' do
let(:candidates) { [] }
it 'returns an empty array' do
expect(selector.send(:select_in_replica_set, candidates)).to be_empty
end
end
context 'single primary candidates' do
let(:candidates) { [primary] }
it 'returns array with primary' do
expect(selector.send(:select_in_replica_set, candidates)).to eq([primary])
end
end
context 'single secondary candidate' do
let(:candidates) { [secondary] }
it 'returns array with secondary' do
expect(selector.send(:select_in_replica_set, candidates)).to eq([secondary])
end
end
context 'primary and secondary candidates' do
let(:candidates) { [primary, secondary] }
let(:expected) { [secondary, primary] }
it 'returns array with secondary first, then primary' do
expect(selector.send(:select_in_replica_set, candidates)).to eq(expected)
end
end
context 'secondary and primary candidates' do
let(:candidates) { [secondary, primary] }
let(:expected) { [secondary, primary] }
it 'returns array with secondary and primary' do
expect(selector.send(:select_in_replica_set, candidates)).to eq(expected)
end
end
context 'tag sets provided' do
let(:tag_sets) do
[ tag_set ]
end
let(:matching_primary) do
make_server(:primary, :tags => server_tags, address: default_address)
end
let(:matching_secondary) do
make_server(:secondary, :tags => server_tags, address: default_address)
end
context 'single candidate' do
context 'primary' do
let(:candidates) { [primary] }
it 'returns array with primary' do
expect(selector.send(:select_in_replica_set, candidates)).to eq([primary])
end
end
context 'matching_primary' do
let(:candidates) { [matching_primary] }
it 'returns array with matching primary' do
expect(selector.send(:select_in_replica_set, candidates)).to eq([matching_primary])
end
end
context 'matching secondary' do
let(:candidates) { [matching_secondary] }
it 'returns array with matching secondary' do
expect(selector.send(:select_in_replica_set, candidates)).to eq([matching_secondary])
end
end
context 'secondary' do
let(:candidates) { [secondary] }
it 'returns an empty array' do
expect(selector.send(:select_in_replica_set, candidates)).to be_empty
end
end
end
context 'multiple candidates' do
context 'no matching secondaries' do
let(:candidates) { [primary, secondary, secondary] }
it 'returns an array with the primary' do
expect(selector.send(:select_in_replica_set, candidates)).to eq([primary])
end
end
context 'one matching secondary' do
let(:candidates) { [primary, matching_secondary] }
it 'returns an array of the matching secondary, then primary' do
expect(selector.send(:select_in_replica_set, candidates)).to eq(
[matching_secondary, primary]
)
end
end
context 'two matching secondaries' do
let(:candidates) { [primary, matching_secondary, matching_secondary] }
let(:expected) { [matching_secondary, matching_secondary, primary] }
it 'returns an array of the matching secondaries, then primary' do
expect(selector.send(:select_in_replica_set, candidates)).to eq(expected)
end
end
context 'one matching secondary and one matching primary' do
let(:candidates) { [matching_primary, matching_secondary] }
let(:expected) {[matching_secondary, matching_primary] }
it 'returns an array of the matching secondary, then the primary' do
expect(selector.send(:select_in_replica_set, candidates)).to eq(expected)
end
end
end
end
context 'high latency servers' do
let(:far_primary) { make_server(:primary, :average_round_trip_time => 0.100, address: default_address) }
let(:far_secondary) { make_server(:secondary, :average_round_trip_time => 0.113, address: default_address) }
context 'single candidate' do
context 'far primary' do
let(:candidates) { [far_primary] }
it 'returns array with primary' do
expect(selector.send(:select_in_replica_set, candidates)).to eq([far_primary])
end
end
context 'far secondary' do
let(:candidates) { [far_secondary] }
it 'returns an array with the secondary' do
expect(selector.send(:select_in_replica_set, candidates)).to eq([far_secondary])
end
end
end
context 'multiple candidates' do
context 'local primary, local secondary' do
let(:candidates) { [primary, secondary] }
it 'returns an array with secondary, then primary' do
expect(selector.send(:select_in_replica_set, candidates)).to eq([secondary, primary])
end
end
context 'local primary, far secondary' do
let(:candidates) { [primary, far_secondary] }
it 'returns an array with the secondary, then primary' do
expect(selector.send(:select_in_replica_set, candidates)).to eq([far_secondary, primary])
end
end
context 'local secondary' do
let(:candidates) { [far_primary, secondary] }
let(:expected) { [secondary, far_primary] }
it 'returns an array with secondary, then primary' do
expect(selector.send(:select_in_replica_set, candidates)).to eq(expected)
end
end
context 'far primary, far secondary' do
let(:candidates) { [far_primary, far_secondary] }
let(:expected) { [far_secondary, far_primary] }
it 'returns an array with secondary, then primary' do
expect(selector.send(:select_in_replica_set, candidates)).to eq(expected)
end
end
context 'two near servers, one far secondary' do
context 'near primary, near secondary, far secondary' do
let(:candidates) { [primary, secondary, far_secondary] }
let(:expected) { [secondary, primary] }
it 'returns an array with near secondary, then primary' do
expect(selector.send(:select_in_replica_set, candidates)).to eq(expected)
end
end
context 'two near secondaries, one far primary' do
let(:candidates) { [far_primary, secondary, secondary] }
let(:expected) { [secondary, secondary, far_primary] }
it 'returns an array with secondaries, then primary' do
expect(selector.send(:select_in_replica_set, candidates)).to eq(expected)
end
end
end
end
end
end
end
|
# == Schema Information
#
# Table name: vacancies
#
# id :integer not null, primary key
# title :string(255)
# salary_cents :integer default(0), not null
# contacts :string(255)
# valid_through :date
# created_at :datetime
# updated_at :datetime
#
FactoryGirl.define do
factory :vacancy do
title 'Ruby on Rails'
salary_cents 120_000_000
contacts 'Moscow'
valid_through Date.today
end
end
|
module RSence
require 'erb'
require 'yaml'
# @private ARGVParser is the "user interface" as a command-line argument parser.
# It parses the command-line arguments and sets up things accordingly.
class ARGVParser
# Returns true if one of the 'start' -type commands were supplied
# and the environment seems valid.
def startable?; @startable; end
# Parses an argument of the 'help' command
def parse_help_argv
if @argv.length >= 2
help_cmd = @argv[1].to_sym
else
help_cmd = :help_main
end
help( help_cmd )
exit
end
# Creates the default and initial @args hash.
def init_args
@args = {
:env_path => Dir.pwd,
:conf_files => [ ], # --conf
:debug => false, # -d --debug
:verbose => false, # -v --verbose
:log_fg => false, # -f --log-fg
:trace_js => false, # --trace-js
:trace_delegate => false, # --trace-delegate
:port => nil, # --port
:addr => nil, # --addr --bind
:server => nil, # --server
:reset_ses => false, # -r --reset-sessions
:autoupdate => false, # -a --auto-update
:latency => 0, # --latency
:say => false, # -S --say
:http_delayed_start => nil, # --http-delayed-start
# client_pkg (not supported yet)
:client_pkg_no_gzip => false, # --disable-gzip
:client_pkg_no_obfuscation => false, # --disable-obfuscation
:client_pkg_no_whitespace_removal => false, # --disable-jsmin
:suppress_build_messages => true, # --build-report
}
end
# Sets various debug-related options on.
def set_debug
@args[:debug] = true
@args[:verbose] = true
@args[:autoupdate] = true
@args[:client_pkg_no_obfuscation] = true
@args[:client_pkg_no_whitespace_removal] = true
@args[:suppress_build_messages] = false
end
# Set the verbose argument on
def set_verbose
@args[:verbose] = true
end
# Set the foreground logging argument on
def set_log_fg
@args[:log_fg] = true
end
# Sets the session reset argument on
def set_reset_ses
@args[:reset_ses] = true
end
# Sets the auto-update argument on
def set_autoupdate
@args[:autoupdate] = true
end
# Sets the speech synthesis argument on
def set_say
@args[:say] = true
end
# Error message when an invalid environment is encountered, exits.
def invalid_env( env_path=false )
env_path = @args[:env_path] unless env_path
puts ERB.new( @strs[:messages][:invalid_environment] ).result( binding )
exit
end
# Error message when an invalid option is encountered, exits.
def invalid_option(arg,chr=false)
if chr
puts ERB.new( @strs[:messages][:invalid_option_chr] ).result( binding )
else
puts ERB.new( @strs[:messages][:invalid_option] ).result( binding )
end
exit
end
require 'rsence/argv/startup_argv'
require 'rsence/argv/status_argv'
require 'rsence/argv/save_argv'
require 'rsence/argv/initenv_argv'
require 'rsence/argv/help_argv'
require 'rsence/argv/env_check'
require 'rsence/argv/test_port'
include ArgvUtil
# Returns the version of RSence
def version; @version; end
# Returns the command the process was started with.
def cmd; @cmd; end
# Returns the parsed optional arguments
def args; @args; end
# Top-level argument parser, checks for command and calls sub-parser, if valid command.
def parse_argv
if @argv.empty?
puts @strs[:help][:help_help]
exit
else
cmd = @argv[0].to_sym
cmd = :help if [:h, :'-h', :'--help', :'-help'].include? cmd
end
if @cmds.include?(cmd)
@cmd = cmd
unless [:help, :version].include?( cmd )
puts "RSence #{@version} -- Ruby #{RUBY_VERSION}"
end
if cmd == :help
parse_help_argv
elsif cmd == :version
puts version
exit
elsif [:run,:start,:stop,:restart].include? cmd
parse_startup_argv
elsif cmd == :status
parse_status_argv
elsif cmd == :save
parse_save_argv
elsif cmd == :initenv or cmd == :init
parse_initenv_argv
end
else
puts @strs[:help][:unknown] + cmd.to_s.inspect
puts @strs[:help][:help_help]
exit
end
end
# The constructor sets the @startable flag as false. Use the #parse method with ARGV as the argument to start parsing the ARGV.
def initialize
@startable = false
# The RSence version string, read from the VERSION file in
# the root directory of RSence.
@version = File.read( File.join( SERVER_PATH, 'VERSION' ) ).strip
# Makes various commands available depending on the platform.
# The status/start/stop/restart/save -commands depend on an operating
# system that fully implements POSIX standard signals.
# These are necessary to send signals to the background process.
if not RSence.pid_support?
@cmds = [ :run, :init, :initenv, :version, :help ]
else
@cmds = [ :run, :status, :start, :stop, :restart, :save,
:init, :initenv, :version, :help ]
end
help_avail_cmds = @cmds.map{|cmd|cmd.to_s}.join("\n ")
# Load the strings from the strings file.
strs_path = File.join( SERVER_PATH, 'conf',
'rsence_command_strings.yaml' )
strs_data = File.read( strs_path )
strs_data = ERB.new( strs_data ).result( binding )
@strs = YAML.load( strs_data )
@strs[:help][:run] += @strs[:help][:path]+@strs[:help][:options]
@strs[:help][:start] += @strs[:help][:path]+@strs[:help][:options]
@strs[:help][:stop] += @strs[:help][:path]+@strs[:help][:options]
@strs[:help][:restart] += @strs[:help][:path]+@strs[:help][:options]
@strs[:help][:status] += @strs[:help][:path]
@strs[:help][:save] += @strs[:help][:path]
end
# Entry point for ARGV parsing
def parse( argv )
@argv = argv
parse_argv
end
end
# @private The ARGVParser instance and its startup
@@argv_parser = ARGVParser.new
@@argv_parser.parse( ARGV )
end
|
class Workgroup < ActiveRecord::Base
belongs_to :manager, :class_name => 'User', :foreign_key => 'manager_id'
has_many :workgroup_user_selections
has_many :users, :through => :workgroup_user_selections
has_many :workgroup_region_selections
has_many :regions, :through => :workgroup_region_selections
has_many :workgroup_type_selections
has_many :types, through: :workgroup_type_selections
end
|
class RemoveSenderFromMessages < ActiveRecord::Migration
def change
remove_reference :messages, :sender, index: true
end
end
|
require 'byebug'
require_relative('questions_database')
class Users
attr_reader :id
attr_accessor :fname, :lname
# Class Methods
def self.all
all_users = QuestionsDatabase.instance.execute(<<-SQL)
SELECT
*
FROM
users
SQL
all_users.map {|user| Users.new(user) }
end
def self.get_by_name(fname, lname)
users = QuestionsDatabase.instance.execute(<<-SQL, fname, lname)
SELECT
*
FROM
users
WHERE
fname = ? AND lname = ?
SQL
Users.new(users.first)
end
def self.get_by_id(id)
users = QuestionsDatabase.instance.execute(<<-SQL, id)
SELECT
*
FROM
users
WHERE
id = ?
SQL
return Users.new(users.first) if users.length > 0
return nil
end
def self.exists?(user)
users = QuestionsDatabase.instance.execute(<<-SQL, user.id)
SELECT
*
FROM
users
WHERE
id = ?
SQL
!users.empty?
end
# For User Object
def initialize(options)
@fname = options["fname"]
@lname = options["lname"]
@id = options["id"]
end
def create
raise "User Already Exists!" if Users.exists?(self)
QuestionsDatabase.instance.execute(<<-SQL, @fname, @lname)
INSERT INTO
users (fname, lname)
VALUES
(?, ?)
SQL
@id = QuestionsDatabase.instance.last_insert_row_id
end
def update
raise "User Does Not Exist!" unless Users.exists?(self)
QuestionsDatabase.instance.execute(<<-SQL, @fname, @lname, @id)
UPDATE
users
SET
fname = ?, lname = ?
WHERE
id = ?
SQL
end
def delete
raise "User Does Not Exist!" unless Users.exists?(self)
QuestionsDatabase.instance.execute(<<-SQL, @id)
DELETE FROM
users
WHERE
id = ?
SQL
end
end
# find_by_id
|
#!/usr/bin/env ruby
require 'pry'
# https://adventofcode.com/2021/day/5
# --- Day 5: Hydrothermal Venture ---
# You come across a field of hydrothermal vents on the ocean floor! These vents constantly produce large, opaque clouds, so it would be best to avoid them if possible.
# They tend to form in lines; the submarine helpfully produces a list of nearby lines of vents (your puzzle input) for you to review. For example:
# 0,9 -> 5,9
# 8,0 -> 0,8
# 9,4 -> 3,4
# 2,2 -> 2,1
# 7,0 -> 7,4
# 6,4 -> 2,0
# 0,9 -> 2,9
# 3,4 -> 1,4
# 0,0 -> 8,8
# 5,5 -> 8,2
# Each line of vents is given as a line segment in the format x1,y1 -> x2,y2 where x1,y1 are the coordinates of one end the line segment and x2,y2 are the coordinates of the other end. These line segments include the points at both ends. In other words:
# An entry like 1,1 -> 1,3 covers points 1,1, 1,2, and 1,3.
# An entry like 9,7 -> 7,7 covers points 9,7, 8,7, and 7,7.
# For now, only consider horizontal and vertical lines: lines where either x1 = x2 or y1 = y2.
# So, the horizontal and vertical lines from the above list would produce the following diagram:
# .......1..
# ..1....1..
# ..1....1..
# .......1..
# .112111211
# ..........
# ..........
# ..........
# ..........
# 222111....
# In this diagram, the top left corner is 0,0 and the bottom right corner is 9,9. Each position is shown as the number of lines which cover that point or . if no line covers that point. The top-left pair of 1s, for example, comes from 2,2 -> 2,1; the very bottom row is formed by the overlapping lines 0,9 -> 5,9 and 0,9 -> 2,9.
# To avoid the most dangerous areas, you need to determine the number of points where at least two lines overlap. In the above example, this is anywhere in the diagram with a 2 or larger - a total of 5 points.
# Consider only horizontal and vertical lines. At how many points do at least two lines overlap?
class Grid
attr :lines
attr :x_max, :y_max
# attr_accessor :first_board_wins
attr :grid
attr :cross_points
attr :ignore_diag
def initialize(lines)
@lines = lines
@lines.each do |l|
puts l
end
find_max_x_y
puts "x_max=#{@x_max} y_max=#{@y_max}"
@grid = Array.new(@x_max + 1)
puts "@grid.length=#{@grid.length}"
@grid.each_with_index do |g, i|
@grid[i] = Array.new(@y_max + 1, '.')
end
@cross_points = 0
@ignore_diag = true
end
def map_vents(ignore_diag)
@ignore_diag = ignore_diag
print_grid
mark_lines
print_grid
count_cross_points
puts "cross_points #{@cross_points}"
end
def find_max_x_y
@x_max = 0
@y_max = 0
@lines.each do |l|
mx = [l.x1, l.x2].max
@x_max = [@x_max, mx].max
my = [l.y1, l.y2].max
@y_max = [@y_max, my].max
end
# todo add 1 to x,y max?
# @x_max += 1
# @y_max += 1
end
def print_grid
return if @x_max > 20
row = ' '
(0..@x_max).each do |x|
row += x.to_s
end
puts row
@grid.each_with_index do |g1, x|
row = ''
g1.each_with_index do |g2, y|
row += @grid[x][y]
end
puts x.to_s+ ' ' +row
end
end
def count_cross_points
cross = 0
@grid.each_with_index do |g1, x|
g1.each_with_index do |g2, y|
if @grid[x][y] != '.' && @grid[x][y].to_i > 1
cross += 1
end
end
end
puts "cross=#{cross}"
end
def mark_lines()
@lines.each do |l|
fill_in_line(l)
# if l.horizontal? || l.vertical?
# #puts "marking x1=#{l.x1} y1=#{l.y1} x2=#{l.x2} y2=#{l.y2}"
# #puts "marking #{l}"
# # @grid[l.x1][l.y1] = '1'
# # @grid[l.x2][l.y2] = '1'
# fill_in_line(l)
# else
# puts "#{l} is not horizontal or vertical"
# end
end
end
def mark_point(y, x)
if @grid[y][x] == '.'
puts "#{x} #{y} = #{@grid[x][y]} -> 1"
@grid[y][x] = '1'
else
if @grid[y][x].to_i == 1
@cross_points += 1
end
v = @grid[y][x].to_i
v += 1
puts "#{x} #{y} = #{@grid[x][y]} -> #{v}"
@grid[y][x] = v.to_s
end
end
def fill_in_line(l)
if l.horizontal?
puts "marking horizontal #{l}"
x1,y = l.start
x2,y = l.end
(x1..x2).each do |x|
mark_point(y, x)
# if @grid[y][x] == '.'
# puts "#{x} #{y} = #{@grid[x][y]} -> 1"
# @grid[y][x] = '1'
# else
# if @grid[y][x].to_i == 1
# @cross_points += 1
# end
# v = @grid[y][x].to_i
# v += 1
# puts "#{x} #{y} = #{@grid[x][y]} -> #{v}"
# @grid[y][x] = v.to_s
# end
end
print_grid
elsif l.vertical?
puts "marking vertical #{l}"
x,y1 = l.start
x,y2 = l.end
(y1..y2).each do |y|
mark_point(y, x)
# if @grid[y][x] == '.'
# puts "#{x} #{y} = #{@grid[x][y]} -> 1"
# @grid[y][x] = '1'
# else
# if @grid[y][x].to_i == 1
# @cross_points += 1
# end
# v = @grid[y][x].to_i
# v += 1
# puts "#{x} #{y} = #{@grid[x][y]} -> #{v}"
# @grid[y][x] = v.to_s
# end
end
print_grid
else
return if @ignore_diag
puts "marking diagonal #{l}"
x1,y1 = l.start
x2,y2 = l.end
# which way are we going, down left or up right
if x1 < x2 && y1 < y2
y = y1
(x1..x2).each do |x|
mark_point(y, x)
y += 1
end
else
y = y1
(x1..x2).each do |x|
mark_point(y, x)
y -= 1
end
end
print_grid
end
end
end
class Line
attr_accessor :x1,:x2,:y1,:y2
def initialize(input_line)
first,last = input_line.gsub(' ', '').split('->')
x1,y1 = first.split(',')
x2,y2 = last.split(',')
@x1 = x1.to_i
@y1 = y1.to_i
@x2 = x2.to_i
@y2 = y2.to_i
end
def horizontal?
# 1,1 2,1 3,1
#
# y stays same
#
# ....
# .111.
# ....
# ....
#
@y1 == @y2
end
def vertical?
# 1,1 1,2 1,3
#
# x stays same
#
# ....
# .1..
# .1..
# .1..
#
@x1 == @x2
end
def start
if horizontal?
x = [@x1, @x2].min
y = y1
puts "start horizontal #{x} #{y}"
elsif vertical?
x = @x1
y = [@y1,@y2].min
puts "start vertical #{x} #{y}"
else
if (@x1 < @x2 && @y1 < @y2) || (@x1 >= @x2 && @y1 >= @y2)
# diag line going top left to bot right
x = [@x1,@x2].min
y = [@y1,@y2].min
else
x = [@x1,@x2].min
y = [@y1,@y2].max
end
puts "start diagonal #{x} #{y}"
end
return x,y
end
def end
if horizontal?
x = [@x1, @x2].max
y = @y1
puts "end horizontal #{x} #{y}"
elsif vertical?
x = @x1
y = [@y1,@y2].max
puts "end vertical #{x} #{y}"
else
if (@x1 < @x2 && @y1 < @y2) || (@x1 >= @x2 && @y1 >= @y2)
# diag line going top left to bot right
x = [@x1,@x2].max
y = [@y1,@y2].max
else
x = [@x1,@x2].max
y = [@y1,@y2].min
end
puts "end diagonal #{x} #{y}"
end
return x,y
end
def to_s
"#{@x1} #{@y1} -> #{@x2} #{@y2}"
end
end
def read_input(file_name)
file = File.open(file_name)
input_data = file.read
lines = []
input_data.each_line do |line|
l = Line.new(line.chomp!)
lines << l
puts "line=#{line} Line=#{l}"
end
puts "input_data: #{lines.length} lines"
g = Grid.new(lines)
g
end
def write_output(file_name, output)
#File.write(file_name, output.join("\n"), mode: 'w')
end
def part1(input_file)
grid = read_input(input_file)
ignore_diag = true
grid.map_vents(ignore_diag)
end
def part2(input_file)
grid = read_input(input_file)
ignore_diag = false
grid.map_vents(ignore_diag)
end
puts ""
puts "part 1 sample"
part1('aoc_05_2021_input_sample.txt')
puts ""
puts "part 1"
part1('aoc_05_2021_input.txt')
puts ""
puts "part 2 sample"
part2('aoc_05_2021_input_sample.txt')
puts ""
puts "part 2"
part2('aoc_05_2021_input.txt')
|
class Yogies < ActiveRecord::Base
#has_one :image, dependent: :destroy
belongs_to :image
has_many :users
def self.by_count
result = []
Rails.cache.fetch( 'index', :expires_in => 1.minutes ) do
yogies = group( :title ).count.sort_by {|key, value| value}.reverse.take(5)
yogies.each do |yogy|
title = yogy[0]
count = yogy[1]
# 최적 이미지 4개 추출, 지금은 최신 순
best_image_ids = Yogies.where( { title: title } ).order( 'created_at desc' ).limit(4).map{ |yogy| yogy.image_id }
result << { title: title,
count: count,
images: Image.where( { id: best_image_ids } ).available_images.order( 'view_count desc').order( 'created_at desc' )
}
end
result
end
end
def self.by_title( title, season = nil, year = nil )
cache_key = "yogies_by_title_#{title}_#{season}_#{year}"
Rails.cache.fetch( cache_key, :expires_in => 1.minutes ) do
condition = { yogies: {title: title} }
images_condition = { deleted: 0, dislike: 0..(ENV["BLIND_LIMIT"].to_i - 1) }
images_condition[:season] = season unless season.blank?
images_condition[:year] = year unless year.blank?
condition[:images] = images_condition unless images_condition.blank?
Yogies.includes( :image ).where( condition ).order( 'images.view_count desc').order( 'yogies.created_at desc' )
end
end
def self.extra( yogies )
seasons = []
years = []
yogies.each do |yogy|
begin
exif = JSON.parse(yogy.image.exif, :symbolize_names => true)
years << exif[:create_date].split(":")[0].to_i
rescue
end
seasons << yogy.image.season unless yogy.image.season.blank?
end
{ seasons: seasons.uniq.sort,
years: years.uniq.sort.reverse,
}
end
def self.extra_by_images( images )
seasons = []
years = []
images.each do |image|
begin
exif = JSON.parse(image.exif, :symbolize_names => true)
years << exif[:create_date].split(":")[0].to_i
rescue
end
seasons << image.season unless image.season.blank?
end
{ seasons: seasons.uniq.sort,
years: years.uniq.sort.reverse,
}
end
def to_param
title
end
end
|
class ApplicationController < ActionController::Base
protect_from_forgery
HUMAN_VERIFY = []
helper_method :current_user
helper_method :current_or_guest_user
helper_method :logging_in
rescue_from CanCan::AccessDenied do |e|
redirect_to root_path, alert: 'Sorry, you can\'t access that page'
end
def current_or_guest_user
if current_user
current_user
else
guest_user
end
end
private
def guest_user
@cached_guest_user ||= User.find(session[:guest_user_id] ||= create_guest_user.id)
rescue ActiveRecord::RecordNotFound # if session[:guest_user_id] invalid
session[:guest_user_id] = nil
guest_user
end
def logging_in
guest_user.destroy
session[:guest_user_id] = nil
session[:user_id] = current_user.id
guest_user.games.each do |game|
if game.player_1_id == guest_user.id
game.player_1_id = current_user.id
end
if game.player_2_id == guest_user.id
game.player_2_id = current_user.id
end
game.save
end
end
def create_guest_user
destroy_old_guests
u = User.create(:username => "guest#{Time.now.to_i}#{rand(100)}", :email => "guest_#{Time.now.to_i}#{rand(100)}", :password => "password", :password_confirmation => "password")
u.save!(:validate => false)
session[:guest_user_id] = u.id
session[:user_id] = u.id
return u
end
def destroy_old_guests
guests = User.where(role: "guest")
guests.each do |guest|
if guest.updated_at < (Time.now - 1.day)
guest.destroy
end
end
end
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
rescue ActiveRecord::RecordNotFound
session[:user_id] = nil
end
end |
class Owner < ApplicationRecord
has_many :restaurants
has_many :reviews, through: restaurants
has_secure_password
validates :first_name, presence:true
validates :last_name, presence:true
validates :email, uniqueness: true, presence:true
end
|
FactoryGirl.define do
factory :member do
first_name
last_name
email
active true
birthdate "1979-02-10"
cell_phone "555-555-1212"
password 'password'
factory :avatar do
avatar_file_name { 'profile.png' }
avatar_content_type { 'image/png' }
avatar_file_size { 8 }
end
address
after(:build) do |m|
m.generate_member_number
end
factory :admin do
is_admin true
end
end
end
|
#aksdfjskasdasdaasdasda
class ListNode
attr_accessor :val, :next
def initialize(val)
@val = val
@next = nil
end
end
def getIntersectionNode(headA, headB)
a_nodes = {}
current_a = headA
while current_a
a_nodes[current_a] = current_a
current_a = current_a.next
end
current_b = headB
while current_b
return current_b if a_nodes[current_b]
current_b = current_b.next
end
nil
end
def find_repeated_dna_sequences(s)
hash=Hash.new(0)
(0..s.length-10).each do |start_idx|
seq=s[start_idx..start_idx+9]
hash[seq]+=1
end
p hash
dup_hash = hash.select {|k,v| v>1 }
dup_hash.keys
end
|
# A triangle is classified as follows:
# equilateral All 3 sides are of equal length
# isosceles 2 sides are of equal length, while the 3rd is different
# scalene All 3 sides are of different length
# To be a valid triangle, the sum of the lengths of the two shortest sides must
# be greater than the length of the longest side, and all sides must have
# lengths greater than 0: if either of these conditions is not satisfied, the
# triangle is invalid.
# Write a method that takes the lengths of the 3 sides of a triangle as
# arguments, and returns a symbol :equilateral, :isosceles, :scalene, or
# :invalid depending on whether the triangle is equilateral, isosceles,
# scalene, or invalid.
def is_valid_triangle(s1, s2, s3)
new_arr = [s1, s2, s3]
new_arr.sort!
if new_arr[0] + new_arr[1] <= new_arr[2]
false
else
true
end
end
def triangle(side1, side2, side3)
if is_valid_triangle(side1, side2, side3)
if side1 == side2 && side2 == side3
p :equilateral
elsif side1 == side2 || side2 == side3 || side3 == side1
p :isosceles
else
p :scalene
end
else
p :invalid
end
end
p triangle(3, 3, 3) == :equilateral
p triangle(3, 3, 1.5) == :isosceles
p triangle(3, 4, 5) == :scalene
p triangle(0, 3, 3) == :invalid
p triangle(3, 1, 1) == :invalid |
When /^(.+?) receives acknowledge from (.+?)$/ do |destination, source|
wait_or_fail 'Acknowledge not received within time' do
$routers[destination.to_sym][:acks].include? source.to_sym
end
end
When /^(.+?) receives from (.+?) message "(.+?)"$/ do |destination, source, message|
wait_for_message(destination, source, 15, message, $receive_timeout)
end
When /^(.+?) receives back message "(.+?)"$/ do |source, message|
wait_for_undelivered_message(source, message, $receive_timeout)
end
When /^(.+?) does not (.+?) (.*?)$/ do |a, noun, b|
success = false
begin
step "#{a} #{noun}s #{b}"
success = true
rescue
end
fail 'Somehow step succeeded' if success
end
When /^"(.+?)" route is (.+?)$/ do |message, route|
fail "Different route - #{$messages[message].map(&:to_s).join(', ')}" unless compare_routes(make_route(route), $messages[message])
end
When /^route contains (.+?)$/ do |route|
pending
end
When /^(.+?) broadcasts data (.+?)$/ do |node, data|
wait_for_data(node, nil, data, $receive_timeout)
end
When /^(.+?) transmits to (.+?) data (.+?)$/ do |source, destination, data|
wait_for_data(source, destination, data, $receive_timeout)
end
When /^(.+?) is broadcasted from (.+?)$/ do |type, node|
data = case type
when 'node'
'FESS'
when 'graph'
'FB.*?SS'
else
fail 'Unknown packet type!'
end
step "#{node} broadcasts data #{data}"
end
|
class ContactMailer < ActionMailer::Base
default from: "ben@bytenel.com"
def new_message(message)
@message = message
mail(to: 'nelson.ben.c@gmail.com', subject: @message.subject)
end
end
|
require 'lights/hobject'
class Scene < HObject
attr_reader :id, :name, :active, :lights
def initialize(id,data = {})
super(data)
@id = id
@name = data["name"]
@active = data["active"]
@lights = data["lights"]
end
def data
data = {}
data["name"] = @name if @name
data["active"] = @active if @active
data["lights"] = @lights if @lights
data
end
end
|
class AddScenarioStatusesToBuildStats < ActiveRecord::Migration
def change
add_column :build_stats, :num_failed_bugs_scenarios, :integer
add_column :build_stats, :num_pending_bugs_scenarios, :integer
end
end
|
class Api::V1::CommentsController < ApplicationController
before_action :authenticate_api_v1_user!
before_action :set_comment, only: [:update]
authorize_resource
skip_forgery_protection
def create
@post = Post.find_by id: params[:post_id]
unless @post.present?
return render_error "post not found", :unprocessable_entity
end
@comment = Comment.new comment_params
@comment.post = @post
@comment.user = current_api_v1_user
if @comment.save
return render json: {}, status: :ok
else
return render_model_errors @comment
end
end
def update
unless @comment.present?
return render_error "comment not found", :unprocessable_entity
end
if @comment.update comment_params
return render json: {}, status: :ok
else
return render_model_errors @comment
end
end
private
def comment_params
params.require(:comment).permit(
:body
)
rescue ActionController::ParameterMissing
{}
end
def set_comment
@comment = Comment.find params[:id]
rescue ActiveRecord::RecordNotFound
@comment = nil
end
end
|
class ChangeRoomTypeIdToRoomId < ActiveRecord::Migration
def change
change_table :bookings do |t|
t.rename :room_type_id, :room_id
end
end
end
|
module Bootsy
class ImageGallery < ActiveRecord::Base
belongs_to :bootsy_resource, polymorphic: true
has_many :images, dependent: :destroy
scope :destroy_orphans, ->(time_limit) { where('created_at < ? AND bootsy_resource_id IS NULL', time_limit).destroy_all }
end
end
|
class Atlas < ActiveRecord::Base
attr_accessible :user_id, :name, :types, :types_attributes, :type_count, :realm, :realm_attributes, :tag
belongs_to :user
has_many :sizes, :dependent => :destroy
has_many :types, :dependent => :destroy
has_many :reports, :dependent => :destroy
has_many :events, :dependent => :destroy
has_many :tags, :dependent => :destroy
has_many :cases, :dependent => :destroy
belongs_to :realm, :class_name => 'Tag'
accepts_nested_attributes_for :types, :allow_destroy => true
accepts_nested_attributes_for :realm, :allow_destroy => true
validates_presence_of :name, :message => "You must give a name to this atlas."
def add_type
t = Type.new
self.types << t
end
end
|
# Add your annotations, line by line, to the code below using code comments.
# Try to focus on using correct technical vocabulary.
# Use the # to create a new comment
# Build a Bear
# defines the method build_a_bear with five arguements
def build_a_bear(name, age, fur, clothes, special_power)
# defines method variables using argument input
# defines interpolated string
greeting = "Hey partner! My name is #{name} - will you be my friend?!"
# defines variable with array of argument data
demographics = [name, age]
# defines interpolated string
power_saying = "Did you know that I can #{special_power}?"
# defines a hash for a built_bear and continues to use arguments given by the above method
built_bear = {
'basic_info' => demographics,
'clothes' => clothes,
'exterior' => fur,
'cost' => 49.99, # is a fixed float variable, does not change based on method arguments
'sayings' => [greeting, power_saying, "Goodnight my friend!"],
'is_cuddly' => true, # is a fixed boolean variable
}
return built_bear # tells the program the method should output the built_bear variable once the method
#finishes running that uses all the information given when calling the method
# denotes the end of the function code block
end
# calls the method build_a_bear and gives five arguments in the appropriate format for each data type [string, integer, string, array, string]
build_a_bear('Fluffy', 4, 'brown', ['pants', 'jorts', 'tanktop'], 'give you nightmares')
build_a_bear('Sleepy', 2, 'purple', ['pajamas', 'sleeping cap'], 'sleeping in')
# FizzBuzz
# defines the method fizzbuzz with three arguments to be inserted
def fizzbuzz(num_1, num_2, range)
# each loop that will iterate across an array created using the starting value 1
# an inclusive range operator and arguement input to define the range of integers in the array
(1..range).each do |i|
if i % num_1 === 0 && i % num_2 === 0 # if the modulo of the current iterative integer(i) and both input integers = 0,
# the method puts fizzbuzz
puts 'fizzbuzz'
elsif i % num_1 === 0 # if only the modulo of i and num_1 = 0 the method puts fizz
puts 'fizz'
elsif i % num_2 === 0 # if only the modulo of i and num_2 = 0 the method puts buzz
puts 'buzz'
else # for all other input value results, the method prints the integer being iterated(i)
puts i
end # designated the end of the if, elsif, else methods
end # designated the end of the each loop
end # designates the end of the fizzbuzz method
# calls the fizzbuzz method for a range of 1 - 100, using 3 as num_1 and 5 as num_2
fizzbuzz(3, 5, 100)
# calls the fizzbuzz method for a range of 1 - 400, using 5 as num_1 and 8 as num_2
fizzbuzz(5, 8, 400)
|
And(/^the bag '(.*)' is staged in the accrual root named '(.*)' at path '(.*)'$/) do |bag_name, root_name, path|
StorageManager.instance.accrual_roots.at(root_name).copy_tree_to(path, FixtureFileHelper.storage_root, FixtureFileHelper.complete_bag_key(bag_name))
end
And(/^I should see the accrual form and dialog$/) do
expect(page).to have_selector('form#add-files-form')
expect(page).to have_selector('#add-files-dialog')
end
And(/^I should not see the accrual form and dialog$/) do
expect(page).not_to have_selector('form#add-files-form')
expect(page).not_to have_selector('#add-files-dialog')
end
Then(/^the cfs directory with path '(.*)' should have an accrual job with (\d+) files? and (\d+) director(?:y|ies)$/) do |path, file_count, directory_count|
cfs_directory = CfsDirectory.find_by(path: path)
accrual_job = Workflow::AccrualJob.find_by(cfs_directory_id: cfs_directory.id)
expect(accrual_job.workflow_accrual_files.count).to eql(file_count.to_i)
expect(accrual_job.workflow_accrual_directories.count).to eql(directory_count.to_i)
end
Then(/^the cfs directory with path '(.*)' should have an accrual job with (\d+) keys?$/) do |path, key_count|
cfs_directory = CfsDirectory.find_by(path: path)
accrual_job = Workflow::AccrualJob.find_by(cfs_directory_id: cfs_directory.id)
expect(accrual_job.workflow_accrual_keys.count).to eql(key_count.to_i)
end
And(/^the cfs directory with path '(.*)' should have an accrual job with (\d+) minor conflicts? and (\d+) serious conflicts?$/) do |path, minor_conflict_count, serious_conflict_count|
cfs_directory = CfsDirectory.find_by(path: path)
accrual_job = Workflow::AccrualJob.find_by(cfs_directory_id: cfs_directory.id)
expect(accrual_job.workflow_accrual_conflicts.not_serious.count).to eql(minor_conflict_count.to_i)
expect(accrual_job.workflow_accrual_conflicts.serious.count).to eql(serious_conflict_count.to_i)
end
Then(/^the cfs directory with path '(.*)' should not have an accrual job$/) do |path|
cfs_directory = CfsDirectory.find_by(path: path)
accrual_job = Workflow::AccrualJob.find_by(cfs_directory_id: cfs_directory.id)
expect(accrual_job).to be_nil
end
When /^I select accrual action '([^']*)'$/ do |action|
steps %Q(
When I go to the dashboard
And I click on 'Accruals'
And within '#accruals' I click on 'Actions'
And within '#accruals' I click on '#{action}'
And I wait 1 second
When delayed jobs are run)
end
When /^I select accrual action '([^']*)' with comment '([^']*)'$/ do |action, comment|
steps %Q(
When I go to the dashboard
And I click on 'Accruals'
And within '#accruals' I click on 'Actions'
And within '#accruals' I click on '#{action}'
And I fill in fields:
| Comment | #{comment} |
And within '#accrual_comment_form' I click on 'Submit'
And I wait 0.5 seconds
When delayed jobs are run
And I wait 0.5 seconds)
end
Then /^accrual assessment for the cfs directory with path '(.*)' has (\d+) files?, (\d+) director(?:y|ies), (\d+) minor conflicts?, and (\d+) serious conflicts?$/ do |path, file_count, directory_count, minor_conflict_count, serious_conflict_count|
steps %Q(
Then the cfs directory with path '#{path}' should have an accrual job with #{file_count} files and #{directory_count} directories
When delayed jobs are run
Then the cfs directory with path '#{path}' should have an accrual job with #{file_count} files and #{directory_count} directories
And the cfs directory with path '#{path}' should have an accrual job with #{minor_conflict_count} minor conflicts and #{serious_conflict_count} serious conflicts)
end
Then /^accrual assessment for the cfs directory with path '(.*)' has a zero file '(.*)'$/ do |cfs_directory_path, zero_file_path|
cfs_directory = CfsDirectory.find_by(path: cfs_directory_path)
accrual_job = Workflow::AccrualJob.find_by(cfs_directory_id: cfs_directory.id)
expect(accrual_job.empty_file_report.each_line.detect {|line| line.chomp == zero_file_path}).to be_truthy
end
When /^I navigate to my accrual data for bag '(.*)' at path '(.*)'$/ do |bag_name, path|
steps %Q(
When the bag '#{bag_name}' is staged in the accrual root named 'staging-1' at path '#{path}'
And I view the bit level file group with title 'Dogs'
And I click on 'Run'
And I click consecutively on:
| Add files | staging-1 | dogs |
And within '#add-files-form' I click on 'data')
end
Given(/^there is an accrual workflow job awaiting admin approval$/) do
FactoryBot.create(:workflow_accrual_job, state: 'admin_approval')
end |
module IControl::Management
##
# The CRLDPConfiguration interface enables you to manage CRLDP PAM configuration.
class CRLDPConfiguration < IControl::Base
set_id_name "config_names"
##
# Adds/associates servers to this CRLDP configurations.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [String[]] :servers The servers to add to the CRLDP configurations.
def add_server(opts)
opts = check_params(opts,[:servers])
super(opts)
end
##
# Creates this CRLDP configurations.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [String[]] :servers The list of servers to be assigned to each of the configurations.
def create(opts)
opts = check_params(opts,[:servers])
super(opts)
end
##
# Deletes all CRLDP configurations.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
def delete_all_configurations
super
end
##
# Deletes this CRLDP configurations.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
def delete_configuration
super
end
##
# Gets the number of seconds before a CRL entry expires and is deleted from the CRL
# cache.
# @rspec_example
# @return [long]
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
def cache_timeout
super
end
##
# Gets the number of seconds to wait for server's response before concluding that the
# server is down.
# @rspec_example
# @return [long]
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
def connection_timeout
super
end
##
# Gets a list of all CRLDP configurations.
# @rspec_example
# @return [String]
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
def list
super
end
##
# Gets the lists of servers this CRLDP configurations are associated with.
# @rspec_example
# @return [String[]]
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
def server
super
end
##
# Gets the number of seconds to wait between updates.
# @rspec_example
# @return [long]
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
def update_interval
super
end
##
# Gets the states indicating whether reuse the issuer.
# @rspec_example
# @return [EnabledState]
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
def use_issuer_state
super
end
##
# Gets the version information for this interface.
# @rspec_example
# @return [String]
def version
super
end
##
# Removes all servers from this CRLDP configurations.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
def remove_all_servers
super
end
##
# Removes servers from this CRLDP configurations.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [String[]] :servers The servers to remove from the CRLDP configurations.
def remove_server(opts)
opts = check_params(opts,[:servers])
super(opts)
end
##
# Sets the number of seconds before a CRL entry expires and is deleted from the CRL
# cache.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [long] :timeouts The timeouts used by the configurations.
def set_cache_timeout(opts)
opts = check_params(opts,[:timeouts])
super(opts)
end
##
# Sets the number of seconds to wait for server's response before concluding that the
# server is down.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [long] :timeouts The connection timeouts used by the configurations.
def set_connection_timeout(opts)
opts = check_params(opts,[:timeouts])
super(opts)
end
##
# Sets the number of seconds to wait between updates.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [long] :intervals The update intervals used by the configurations.
def set_update_interval(opts)
opts = check_params(opts,[:intervals])
super(opts)
end
##
# Sets the states indicating whether to reuse the issuer.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [IControl::Common::EnabledState] :states The states of the specified configurations.
def set_use_issuer_state(opts)
opts = check_params(opts,[:states])
super(opts)
end
end
end
|
require 'test_helper'
require 'minitest/mock'
class OrderTest < ActiveSupport::TestCase
test "opening_hours blank" do
@order = orders(:one)
assert @order.send(:check_open_status)
end
test "put of opening_hours" do
@order = orders(:one)
Time.stub :now, Time.parse('2014-05-24 10:00:00') do
assert @order.send(:check_open_status)
end
end
test "order offline" do
@order = orders(:one)
store = @order.store
store.order_offline = true
assert @order.send(:check_open_status)
end
test "order offline false and opening_hours blank" do
@order = orders(:one)
assert @order.send(:check_open_status)
end
test "order offline false and out of opening_hours" do
@order = orders(:three)
Time.stub :now, Time.parse('2014-05-24 08:00:00') do
assert_not @order.send(:check_open_status)
end
end
test "block customer" do
@order = orders(:four)
assert_equal @order.send(:check_customer), false
end
test "calculate amount" do
@order = orders(:four)
amount = @order.calculate_amount.to_s
assert_equal '1.0', amount
end
test "calculate amount with shipping_charge" do
@order = orders(:five)
amount = @order.calculate_amount.to_s
assert_equal '11.0', amount
end
test "total price" do
@order = orders(:five)
price = @order.total_price.to_s
assert_equal '1.0', price
end
test 'waiting payment' do
@order = orders(:one)
@order.address = 'haha'
@order.contact = 'haha'
@order.phone = '18600000000'
@order.payment_option = 'wechat'
assert @order.save
# begin
# @order.waiting_payment!
# rescue
# p @order.message
# end
# p @order
# # p @order.calculate_amount
# assert_raises AASM::InvalidTransition do
# @order.waiting_payment!
# end
assert @order.waiting_payment!
assert_equal 'require_payment', @order.status
end
test 'submit with cash payment' do
@order = orders(:one)
@order.address = 'haha'
@order.contact = 'haha'
@order.phone = '18600000000'
@order.payment_option = 'cash'
assert @order.save
@order.stub :order_submit, true do
assert @order.submit!
assert_equal 'sent', @order.status
end
end
end
|
require 'rails_helper'
RSpec.describe ApplicationHelper, type: :helper do
describe '#markdown' do
it "calls Redcarpet's #render method" do
expect_any_instance_of(Redcarpet::Markdown).to receive(:render) { '' }
helper.markdown('simple text')
end
it 'initializes Markdown only once' do
expect(Redcarpet::Markdown).to receive(:new).once.and_call_original
helper.markdown('simple text')
helper.markdown('simple text')
end
it 'returns safe HTML' do
expect(helper.markdown('simple text')).to be_html_safe
end
it 'outputs simple text in a paragraph' do
expect(helper.markdown('simple text')).to eq("<p>simple text</p>\n")
end
it 'escapes HTML tags' do
expect(helper.markdown('<em>text</em>')).to eq("<p><em>text</em></p>\n")
end
it 'converts Markdown to HTML' do
expect(helper.markdown('**bold**')).to eq("<p><strong>bold</strong></p>\n")
end
it 'converts one new line to a break tags' do
expect(helper.markdown("new\nline")).to eq("<p>new<br>\nline</p>\n")
end
it 'converts two consecutive new lines to a new paragraph' do
expect(helper.markdown("new\n\nline")).to eq("<p>new</p>\n\n<p>line</p>\n")
end
end
describe '#navbar_links' do
it 'returns questions, quiz and random' do
expect(helper.navbar_links.keys).to eq [:questions, :quiz, :random]
end
it 'returns a URI for each link' do
helper.navbar_links.each do |_, item|
expect(item[:uri]).not_to be_blank
end
end
context 'when on specific controller#action' do
before do
allow(helper).to receive(:controller_name) { controller_name }
allow(helper).to receive(:action_name) { action_name }
end
context 'Questions#[any]' do
let(:controller_name) { 'questions' }
it "sets 'questions' as the active item" do
expect(helper.navbar_links.select { |_, item| item[:active] }.keys).to eq [:questions]
end
end
context 'Quiz#[any but random]' do
let(:controller_name) { 'quiz' }
it "sets 'quiz' as the active item" do
expect(helper.navbar_links.select { |_, item| item[:active] }.keys).to eq [:quiz]
end
end
context 'Quiz#random' do
let(:controller_name) { 'quiz' }
let(:action_name) { 'random' }
it "sets 'random' as the active item" do
expect(helper.navbar_links.select { |_, item| item[:active] }.keys).to eq [:random]
end
end
end
end
end
|
FactoryGirl.define do
factory :boat, class: Boat do
user
association :category, factory: :boat_category
boat_type
currency
engine_model
engine_manufacturer
drive_type
country
fuel_type
vat_rate
manufacturer
model
extra
sequence(:name) { |n| "boat-name-#{n}" }
sequence(:slug) { |n| "boat-slug-#{n}" }
deleted_at nil
new_boat false
location 'United Kingdom, Chichester, West Sussex'
year_built 2000
price 100_000
length_m 10
offer_status "available"
status :active
end
factory :extra do
sequence(:description) { |n| "Description #{n}" }
sequence(:short_description) { |n| "Short Description #{n}" }
end
factory :boat_category do
sequence(:name) { |n| "category-#{n}" }
end
factory :boat_type do
sequence(:name) { |n| "boat_type_name-#{n}" }
sequence(:slug) { |n| "boat_type_slug-#{n}" }
end
factory :currency do
name 'USD'
rate 1.4161
symbol '$'
sequence(:position)
trait :eur do
name 'EUR'
symbol '€'
rate 1.2553
end
trait :gbp do
name 'GBP'
symbol '£'
rate 1
end
end
factory :fuel_type do
sequence(:name) { |n| "fuel-#{n}" }
end
factory :vat_rate do
sequence(:name) { |n| "vat-#{n}" }
end
factory :engine_model do
sequence(:name) { |n| "engine-model-#{n}" }
end
factory :engine_manufacturer do
sequence(:name) { |n| "engine_manufacturer-#{n}" }
display_name nil
end
factory :drive_type do
sequence(:name) { |n| "drive_type-#{n}" }
end
factory :model do
manufacturer
sequence(:name) { |n| "model-#{n}" }
sequence(:slug) { |n| "model-slug-#{n}" }
sailing 0
end
factory :manufacturer do
sequence(:name) { |n| "manufacturer-#{n}" }
sequence(:slug) { |n| "manufacturer-#{n}" }
end
factory :country do
iso "US"
name "United States of America"
slug "united-states-of-america"
country_code 1
suspicious false
end
factory :user do
sequence(:email) { |n| "user#{n}@test.com" }
sequence(:password) { |n| "user#{n}@test.com" }
sign_in_count 1
current_sign_in_at Time.current
last_sign_in_at Time.current
current_sign_in_ip '127.0.0.1'
last_sign_in_ip '127.0.0.1'
title "Mr."
role 99 # admin
first_name "first"
last_name "last"
sequence(:username) { |n| "user#{n}" }
sequence(:slug) { |n| "user-#{n}" }
email_confirmed true
active true
updated_by_admin true
end
factory :saved_search do
user
alert true
year_min 2008
year_max 2016
length_min 1
length_max 10
length_unit 'm'
price_min 100
price_max 200
currency 'GBP'
order 'price_asc'
models ['2']
manufacturers ['1']
q 'query'
ref_no 'RB12312'
first_found_boat_id 1
boat_type 'Power'
countries ['90']
end
factory :user_alert do
user
favorites true
saved_searches true
suggestions true
newsletter true
enquiry true
end
factory :broker_info do
user
discount 0.0
sequence(:website) { |n| "website-#{n}" }
sequence(:description) { |n| "description-#{n}" }
sequence(:email) { |n| "email-#{n}@test.com" }
# sequence(:additional_email) { |n| "email-#{n}@test.com" }
sequence(:contact_name) { |n| "contact-name-#{n}" }
lead_min_price 5
lead_max_price 300
payment_method "none"
end
factory :batch_upload_job do
url ''
end
end
|
class AttributesFormatService < ApplicationService
def initialize(table, attributes, attributes_type, key = '')
# attributes_type ['key', 'array']
# if type = 'key' need to define key parameter
@table = table
@table_structure = table_structure
@attributes = attributes
@attributes_type = attributes_type
@records_array = []
@key = key
end
def call
format_records
@records_array
end
private
def format_records
@attributes.each { |record| format_record_attributes(record) }
end
def format_record_attributes(record)
format_attributes = {}
attributes_array(record).each do |attribute|
format_attributes.merge!(record_attribute(attribute))
end
@records_array.push format_attributes
end
def tables_library
folder = "#{Rails.root}/lib/tables_columns_rules/*.json"
CollectJsonsService.call(folder)
end
def table_structure
tables_library["#{@table}"]
end
def record_attribute(attribute)
reference = table_reference(attribute)
value = attribute_value(attribute)
reference ? {"#{reference}": "#{value}"} : {}
end
def table_reference(column)
@table_structure[column['code']]
end
def attribute_value(attribute)
attribute['value'] === 'null' ? nil : attribute['value']
end
def attributes_array(record)
case @attributes_type
when 'key'
record["#{@key}"]
when 'array'
record
else
[]
end
end
end
|
class SessionsController < ApplicationController
def new
if current_user
status_redirect
end
end
def create
user = User.find_by(email: params[:email])
if user.nil? || !user.authenticate(params[:password])
flash[:error] = "Log in information incorrect, please try again."
redirect_to request.referrer
elsif user.authenticate(params[:password])
session[:user_id] = user.id
flash[:success] = "Hello, #{user.name}, you are now logged in."
status_redirect
end
end
def destroy
session.delete(:user_id)
session.delete(:cart)
flash[:success] = "You have successfully logged out!"
redirect_to '/'
end
private
def status_redirect
redirect_to '/admin/dashboard' if current_user.admin?
redirect_to '/merchant/dashboard' if current_user.merchant?
redirect_to '/profile' if current_user.user?
end
end
|
require 'test/unit'
# def solution(s)
# (('a'..'z').to_a & s.downcase.split(' ')).length == 26 ? 'pangram' : 'not pangram'
# end
def solution(s)
s = s.downcase.split('')
r = s & ('a'..'z').to_a
r.length == 26 ? 'pangram' : 'not pangram'
end
class Tests < Test::Unit::TestCase
def test_simple
assert_equal(solution('We promptly judged antique ivory buckles for the next prize'), 'pangram')
end
def test_simple2
assert_equal(solution('We promptly judged antique ivory buckles for the prize'), 'not pangram')
end
def test_simple3
assert_equal(solution(('A'..'Z').to_a.join), 'pangram')
end
end
|
class CreateRestaurants < ActiveRecord::Migration
def change
create_table :restaurants do |t|
t.integer :owner_id, null: false
t.text :description, null: false
t.string :name, null: false
t.string :address, null: false
t.integer :price_range, null: false
t.float :lat
t.float :lng
t.time :opening
t.time :closing
t.integer :seats
t.string :img_url
t.string :phone
t.text :menu
t.timestamps null: false
end
add_index :restaurants, :owner_id
end
end
|
require 'test_helper'
class SiteLayoutTest < ActionDispatch::IntegrationTest
def setup
@user = users(:test_user)
end
test "layout links" do
get root_path
assert_template 'static_pages/home'
assert_select "a[href=?]", root_path
assert_select "a[href=?]", posts_path
assert_select "a[href=?]", login_path
end
test "layout links after login" do
get login_path
post login_path, params: { session: { email: @user.email,
password: 'password' } }
assert is_logged_in?
follow_redirect!
assert_select "a[href=?]", users_path
assert_select "a[href=?]", user_path
assert_select "a[href=?]", logout_path
end
end
|
require 'prawn'
require './card'
require './page'
require 'prawn/measurement_extensions'
class PdfPrinter < Prawn::Document
def initialize
super(
:page_size => [450.mm, 320.mm],
:margin => 0,
:page_layout => :portrait
)
define_grid(:columns => 4, :rows => 6)
end
def save_as(file)
render_file(file)
end
def add_page(page)
start_new_page
(0..3).each do |row|
(0..5).each do |col|
grid(col, row).bounding_box do
draw_table
end
end
end
end
private
def draw_table
c = Card.new
table = make_table (c.to_a)
table.draw
end
end
|
class Course < ActiveRecord::Base
has_many :enrollments, primary_key: :id, foreign_key: :course_id,
class_name: "Enrollment"
belongs_to :prereq, primary_key: :id, foreign_key: :prereq_id, class_name: "Course" #if course has a prereq
belongs_to :teacher, primary_key: :id, foreign_key: :instructor_id, class_name: "User"
end
|
require 'csv'
require_relative 'movie'
class MovieColletion
def initialize(text_file)
@collection = parse_txt_file(text_file)
end
def parse_txt_file(filename)
name = filename.nil? ? 'movies.txt' : filename
if name == 'movies.txt'
CSV.read(name, col_sep: '|')
.map { |m| Movie.new(m) }
else
[]
end
end
def all
@collection
end
def sort_by(film)
@collection.select { |m| m.send(film) }
.sort_by { |m| m.send(film) }
end
def filter(filters)
filters.reduce(@collection) { |filtered, (key, value)| filtered.select { |m| m.send(key).include?(value)} }
end
def stats(stats_arguments)
arguments_hash_list = Hash[stats_arguments.values.collect { |item| [item, nil] }]
stats_arguments.map { |key, value| arguments_hash_list[value] = @collection.select { |movie| movie.send(key).include?(value)}.length }
arguments_hash_list['all'] = arguments_hash_list.values.inject { |sum, n| sum + n }
arguments_hash_list
end
end
x = MovieColletion.new('movies.txt')
puts x.stats(genre: 'Comedy', actors: 'Brad Pitt')
|
module OperationMacros
# Runs a trailblazer op and raises an exception if it fails. Use when you
# know that your test data is good and that a failed op means that you wrote
# the test wrong (or the op is broken.)
def run!(op, *args)
result = op.(*args)
if result.failure?
message = "op #{op} was expected to succeed, but it failed.\n\n Args: #{args.join(', ')}"
message << "\n\n result['error']: #{result['error']}" if result['error']
# FIXME this only works if the contract uses ActiveModel validations as
# opposed to dry-validation
if (contract = result['contract.default'])
if contract.errors.any?
message << "\n\n contract.default errors: #{contract.errors}"
end
end
raise message
end
result
end
end
|
module KoiVMRuby
NIL_ = 0
BOOL_ = 1
INTEGER_ = 2
FLOAT_ = 3
STRING_ = 4
HASH_ = 5
FUNCTION_ = 16
end |
describe "Integer" do
context "when calling next" do
it "should return the next integer" do
1.next.should eq 2
2.next.should eq 3
end
it "should return the previous integer" do
1.pred.should eq 0
0.pred.should eq -1
end
it "should tell whether the number is even or not" do
1.even?.should eq false
4.even?.should eq true
end
it "should tell whether the number is odd or not" do
3.odd?.should eq true
2.odd?.should eq false
end
end
end |
require 'spec_helper'
require 'baby_squeel/nodes/node'
describe BabySqueel::Nodes::Function do
subject(:node) {
described_class.new(
Arel::Nodes::NamedFunction.new('coalesce', [
Post.arel_table[:id],
42
])
)
}
it 'has math operators' do
expect((node + 5) * 5).to produce_sql('(coalesce("posts"."id", 42) + 5) * 5')
end
end
|
require 'bouncer/strategies/shared/profile'
module Bouncer
module Strategies
class Token < ::Warden::Strategies::Base
def valid?
auth.provided? && auth.valid?
end
def store?
false
end
def authenticate!
user = Bouncer::User.new({
profile: profile,
session: {
token: encrypted_token,
checked_at: DateTime.now
}
})
fail!('Invalid user') and return unless user.valid?
success! user
rescue ::JWT::ExpiredSignature, ::JWT::DecodeError => e
fail!(e.message)
rescue Bouncer::JWT::MissingKeysetError => e
Bouncer.reset_keyset_cache!
fail!(e.message)
end
private
def profile
@profile ||= encrypted_token.payload.slice *Shared::Profile::ATTRS
end
def encrypted_token
@token ||= Bouncer::Tokens::Encrypted.new(auth.params)
end
def auth
@auth ||= Rack::Auth::AbstractRequest.new(env)
end
end
end
end
|
require 'spec_helper'
describe Intown::Configuration do
it "should set an app_id" do
Intown.configure do |config|
config.app_id = "my_app"
end
Intown.configuration.app_id.should == "my_app"
end
end
|
class Comment < ActiveRecord::Base
belongs_to :post
belongs_to :user
validates_presence_of :content, :length => { :minimum => 5, :maximum => 2000}
end |
require File.dirname(__FILE__) + '/../../../../spec_helper'
require File.dirname(__FILE__) + '/../../shared/constants'
require 'openssl'
describe "OpenSSL::X509::Certificate#serial" do
it 'is 0 by default' do
x509_cert = OpenSSL::X509::Certificate.new
x509_cert.serial.should == 0
end
it 'returns the serial' do
# TODO: Create public pem with serial
x509_cert = OpenSSL::X509::Certificate.new(X509Constants::X509CERT)
x509_cert.serial.should == X509Constants::X509Serial
end
end
describe "OpenSSL::X509::Certificate#serial=" do
before :each do
@x509_cert = OpenSSL::X509::Certificate.new
end
it 'returns the argument' do
n = 20
(@x509_cert.serial=(n)).should equal(n)
end
it 'raises TypeError if argument is nil' do
lambda { @x509_cert.serial = nil }.should raise_error(TypeError)
end
it 'raises TypeError if argument is not a OpenSSL::BN' do
m = mock(10).should_not_receive(:to_int)
lambda { @x509_cert.serial = m }.should raise_error(TypeError)
end
end
|
class Station < DynamicModel
attr_accessor :name, :line, :division, :latitude, :longitude
attr_reader :id
def self.all
rows = DB[:conn].execute("SELECT * FROM stations")
# we need to create instances
rows.map do |row|
self.send(:new_from_row, row)
end
end
def self.table_name
self.to_s.downcase + "s"
end
def self.find(id)
station_row = DB[:conn].execute("SELECT * FROM stations WHERE id = ?", id)[0]
if station_row
self.send(:new_from_row, station_row)
end
end
def self.find_by(attributes)
conditions = conditions_from_hash(attributes)
values = attributes.values
sql = <<-SQL
SELECT * from stations
WHERE #{conditions}
SQL
station_row = DB[:conn].execute(sql, *values)[0]
if station_row
self.send(:new_from_row, station_row)
end
end
def self.delete(id)
station = self.find(id)
station.delete
end
private
def mass_assign_attributes(attributes)
attributes.each do |k, v|
setter_method = "#{k}="
if self.respond_to?(setter_method)
self.send(setter_method, v)
end
end
end
def insert_record
sql = <<-ANYTHING
INSERT INTO stations (name, line, division, latitude, longitude)
VALUES (?, ?, ?, ?, ?)
ANYTHING
DB[:conn].execute(sql, self.name, self.line, self.division, self.latitude, self.longitude)
@id = DB[:conn].execute("SELECT last_insert_rowid() FROM stations")[0][0]
self
end
def update_record
sql = <<-SQL
UPDATE stations
SET name = ?, line = ?, division = ?, latitude = ?, longitude = ?
WHERE id = ?
SQL
DB[:conn].execute(sql, self.name, self.line, self.division, self.latitude, self.longitude, self.id)
self
end
def delete_record
sql = <<-SQL
DELETE FROM stations
WHERE id = ?
SQL
DB[:conn].execute(sql, self.id)
@id = nil
self
end
def self.new_from_row(station_row)
station = self.new(station_row)
station.instance_variable_set(:@id, station_row["id"])
station
end
def self.conditions_from_hash(attributes)
attributes.inject([]) do |acc, (k,v)|
acc.push("#{k} = ?")
end.join(" AND ")
end
end
|
class Location < ApplicationRecord
has_and_belongs_to_many :eventdates
around_update :set_eventdate_delta_flags
validates_presence_of :building, :room
scope :active, -> { where(defunct: false) }
scope :buildings, -> { active.order(building: :asc).select(:building).distinct.pluck(:building) }
scope :building, -> (building) { active.where(building: building).order(room: :asc) }
scope :sorted, -> { order(id: :asc) }
def to_s
"#{building} - #{room}"
end
private
def set_eventdate_delta_flags
was_changed = self.changed?
yield
if was_changed
eventdates.each do |eventdate|
eventdate.delta = true
eventdate.save
end
end
end
end
|
# encoding: utf-8
require 'spec_helper'
describe TTY::Table::Columns, 'column widths' do
let(:header) { ['h1', 'h2', 'h3', 'h4'] }
let(:rows) { [['a1', 'a2', 'a3', 'a4'], ['b1', 'b2', 'b3', 'b4']] }
let(:table) { TTY::Table.new(header, rows) }
subject { described_class.new(renderer) }
context 'with basic renderer' do
let(:renderer) { TTY::Table::Renderer::Basic.new(table) }
it 'calculates columns natural width' do
expect(subject.natural_width).to eq(11)
end
it 'calculates miminimum columns width' do
expect(subject.minimum_width).to eq(7)
end
end
context 'with ascii renderer' do
let(:renderer) { TTY::Table::Renderer::ASCII.new(table) }
it 'calculates columns natural width' do
expect(subject.natural_width).to eq(13)
end
it 'calculates miminimum columns width' do
expect(subject.minimum_width).to eq(9)
end
end
end
|
#
# Cookbook Name:: goapp
# Recipe:: default
#
#
# Get the current version of GO if it is installed
#
ruby_block "test_go_version" do
only_if { ::File.exists?("/usr/local/go/bin/go") }
block do
lines = %x(/usr/local/go/bin/go version)
lines.chop
node.set[:govn][:govnv] = lines.chop
end
end
#
# Exit the installation if GO is already installed
#
return if node.normal[:govn][:govnv] == node.default[:govn][:govers]
#
# Get the golang install file
#
execute "fetch_go_media" do
command "cd /tmp; wget https://storage.googleapis.com/golang/go1.6.1.linux-amd64.tar.gz "
end
#
# unzip the gz file to the default golang installation directory /usr/local
#
execute "unzip_go_media" do
command " tar -C /usr/local -xzf /tmp/go1.6.1.linux-amd64.tar.gz"
end
#
# remove the zip file.
#
execute "clean_go_media" do
command "rm /tmp/go1.6.1.linux-amd64.tar.gz"
end
#
# Configure the environment variables
#
cookbook_file "/etc/profile.d/golang.csh" do
source "golang.csh"
mode '0755'
action :create
end
cookbook_file "/etc/profile.d/golang.sh" do
source "golang.sh"
mode '0755'
action :create
end
#
# create the workspace to put the GO app into
#
directory "/usr/local/go/workspace" do
action :create
end
|
class ChangeTypeAccesoVehicular < ActiveRecord::Migration[5.0]
def up
change_table :locations do |t|
t.change :acceso_vehicular, :boolean
end
end
def down
change_table :locations do |t|
t.change :acceso_vehicular, :string
end
end
end
|
FactoryBot.define do
factory :coupon, class: Coupon do
name {Faker::Alphanumeric.alphanumeric}
code {Faker::Alphanumeric.alphanumeric}
percent_off {rand(5..15)}
association :merchant
end
end
|
# frozen_string_literal: true
module Interactor
class Base
SUCCESS_RESPONSE = ::OpenStruct.new(success?: true)
class Result
attr_reader :value, :error
def initialize(value = nil, error = nil)
@value = value
@error = error
end
def success?
@error.nil?
end
def failure?
@error.present?
end
end
class Failure < ::RuntimeError
attr_reader :code, :message
def initialize(code, message)
@code = code
@message = message
super()
end
end
attr_reader :args
def initialize(arguments)
@args = ::OpenStruct.new(arguments)
end
def fail!(code = 'UNKNOWN_ERROR', message = '')
logger.error(code.to_s) if message.empty?
logger.error("#{code} (#{message})") if message.present?
raise ::Interactor::Base::Failure.new(code, message)
end
def logger
::Rails.logger
end
def cached(key, expires_in = 5.minutes, &block)
::Rails.cache.fetch(key, expires_in: expires_in, &block)
end
def self.perform(arguments = {})
run(arguments, false)
end
def self.perform!(arguments = {})
run(arguments, true).value
end
def self.prettify(errors)
errors.map { |e| "#{e.path} #{e.text}" }.join(', ')
end
def self.run(arguments, unwrapped)
arguments = arguments.to_h.symbolize_keys
start = ::Time.now.to_f
instance = new(arguments)
instance.logger.debug("#{self.name} started")
begin
instance.validate!
result = ::Interactor::Base::Result.new(instance.perform)
rescue ::ApplicationInteractor::Failure => e
result = ::Interactor::Base::Result.new(nil, e.code)
raise e if unwrapped
end
total = (::Time.now.to_f - start) * 1000
instance.logger.debug("#{self.name} finished in #{total.round(2)} ms")
result
end
def self.expects(&block)
@expects ||= (block.present? ? ::Dry::Validation::Contract(&block) : nil)
end
def validate!
return if self.class.expects.nil?
result = self.class.expects.call(args.to_h)
if result.success?
@args = ::OpenStruct.new(result.to_h)
else
fail!('INVALID_ARGUMENTS', self.class.prettify(result.errors))
end
end
end
end
|
class AddDescriptionToLists < ActiveRecord::Migration
def change
add_column :lists, :description, :text
end
end
|
class AddIndexToStatementMovements < ActiveRecord::Migration[5.2]
def change
add_index :statement_movements, [:statement_id, :movement_id], unique: true
end
end
|
require 'spec_helper'
describe MessageCenter::Message, :type => :model do
before do
@entity1 = FactoryGirl.create(:user)
@entity2 = FactoryGirl.create(:user)
@receipt1 = MessageCenter::Service.send_message(@entity2, @entity1, "Body","Subject")
@receipt2 = MessageCenter::Service.reply_to_all(@receipt1, @entity2, "Reply body 1")
@receipt3 = MessageCenter::Service.reply_to_all(@receipt2, @entity1, "Reply body 2")
@receipt4 = MessageCenter::Service.reply_to_all(@receipt3, @entity2, "Reply body 3")
@message1 = @receipt1.notification
@message4 = @receipt4.notification
@conversation = @message1.conversation
end
it "should have right recipients" do
expect(@receipt1.notification.recipients.count).to eq(2)
expect(@receipt2.notification.recipients.count).to eq(2)
expect(@receipt3.notification.recipients.count).to eq(2)
expect(@receipt4.notification.recipients.count).to eq(2)
end
it "should be able to be marked as deleted" do
expect(@receipt1.deleted).to eq(false)
@message1.mark_as_deleted @entity1
expect(@message1.receipt_for(@entity1).deleted?).to eq(true)
end
end
|
class Contest < ActiveRecord::Base
has_many :challenges
def self.current
find_by_is_active!(true)
end
def duration_in_seconds
duration_in_minutes * 60
rescue
0
end
def seconds_left
end_time - Time.now.to_i
rescue
0
end
def end_time
start_time + duration_in_seconds
end
def in_hours
Time.at(seconds_left).utc.strftime("%H:%M:%S")
end
end |
class TestBuilder
attr_reader :html, :passed_tests, :failed_tests
def initialize(output)
@html = []
@passed_tests = 0
@failed_tests = 0
to_html(output)
end
private
def to_html(output)
raise 'No test results to show' if output.nil?
output.split("<:LF:>").each do |value|
tag = value.split("::>")
message = tag[1]
x = if tag[0].start_with?("<DESCRIBE")
write_desribe(message)
elsif tag[0].start_with?("<PASSED")
@passed_tests += 1
write_it(:'it.passed', message)
elsif tag[0].start_with?("<FAILED")
@failed_tests += 1
write_it(:'it.failed', message)
else
''
end
end
end
def write_it(symbol, message)
block = []
tag = symbol.to_s == 'it.passed' ? 'Passed:' : 'Failed:'
block << "<br>"
block << "<div class=\"#{symbol}\">"
block << "<h3>#{tag} </h3> #{message}"
block << '</div>'
@html << block
end
def write_desribe(message)
block = []
block << "<br>"
block << '<div class="description-level">'
block << "<h3>#{message}</h3>"
block << '</div>'
@html << block
end
end
|
FactoryBot.define do
factory :company do
name {|n| "company_#{n}"}
system_name {|n| "company_#{n}"}
deployments {[FactoryBot.create(:deployment)]}
cluster { FactoryBot.create(:cluster) }
csm_info { FactoryBot.create(:csm_info)}
end
factory :deployment do
name {|n| "deployment_#{n}"}
end
factory :cluster do
name {|n| "cluster_#{n}"}
end
factory :csm_info do
email {|n| "email_#{n}"}
name {|n| "name_#{n}"}
end
factory :plugin do
name {|n| "plugin_#{n}"}
after(:create) do |plugin|
create(:company, entity: company)
end
end
factory :event do
event_name {|n| "event#{n}"}
event_system_name {|n| "event#{n}"}
start_date {"2020-10-09".to_date}
end_date {"2020-10-12".to_date}
creation_date {DateTime.now}
purge_date {DateTime.now+14.days}
card_no { "PS-123"}
company {FactoryBot.create(:company)}
event_type { FactoryBot.create(:event_type)}
end
factory :event_type do
event_type {|n| "event type#{n}"}
end
end
|
# When events are imported from an .xls or .xlsx file, time_from_start for some split_times
# may be off by :01 in either direction as a result of rounding problems in Excel.
# The following rake tasks are designed to correct for these rounding errors.
namespace :round do
desc 'For a given event_id, rounds intermediate times_from_start that end in :59 or :01 to :00'
task :hardrock_style, [:event_id] => :environment do |_, args|
start_time = Time.current
event = Event.find_by(id: args[:event_id])
abort("Aborted: Event id #{args[:event_id]} not found") unless event
puts "Located event: #{event.name}"
split_times = event.split_times.intermediate
.where('mod(cast(split_times.time_from_start as integer), 60) IN (1, 59)')
puts "Found #{split_times.size} split times that need rounding"
$stdout.sync = true
split_times.each do |st|
if st.update(time_from_start: st.time_from_start.round_to_nearest(1.minute))
print '.'
else
print 'X'
end
end
elapsed_time = Time.current - start_time
puts "\nFinished round:hardrock_style for event: #{event.name} in #{elapsed_time} seconds"
end
desc 'For a given organization_id, performs round:hardrock_style on all events associated with the organization'
task :organization_events, [:org_id] => :environment do |_, args|
start_time = Time.current
organization = Organization.find_by(id: args[:org_id])
abort("Aborted: Organization id #{args[:org_id]} not found") unless organization
puts "Located organization: #{organization.name}"
events = organization.events
puts "Located #{events.size} events for #{organization.name}"
organization.events.each do |event|
Rake::Task['round:hardrock_style'].reenable
Rake::Task['round:hardrock_style'].invoke(event.id)
end
elapsed_time = Time.current - start_time
puts "\nFinished round:organization_events in #{elapsed_time} seconds"
end
end |
$: << File.dirname(__FILE__) + '/../lib/'
require 'test/spec'
$WARNING = ""
class Object
def warn(msg)
$WARNING << msg.to_s
super msg
end
end
class Test::Spec::Should
def _warn
_wrap_assertion {
begin
old, $-w = $-w, nil
$WARNING = ""
self.not.raise
$WARNING.should.blaming("no warning printed").not.be.empty
ensure
$-w = old
end
}
end
end
# Hooray for meta-testing.
module MetaTests
class ShouldFail < Test::Spec::CustomShould
def initialize
end
def assumptions(block)
block.should.raise(Test::Unit::AssertionFailedError)
end
def failure_message
"Block did not fail."
end
end
class ShouldSucceed < Test::Spec::CustomShould
def initialize
end
def assumptions(block)
block.should.not.raise(Test::Unit::AssertionFailedError)
end
def failure_message
"Block raised Test::Unit::AssertionFailedError."
end
end
class ShouldBeDeprecated < Test::Spec::CustomShould
def initialize
end
def assumptions(block)
block.should._warn
$WARNING.should =~ /deprecated/
end
def failure_message
"warning was not a deprecation"
end
end
def fail
ShouldFail.new
end
def succeed
ShouldSucceed.new
end
def deprecated
ShouldBeDeprecated.new
end
end
module TestShoulds
class EmptyShould < Test::Spec::CustomShould
end
class EqualString < Test::Spec::CustomShould
def matches?(other)
object == other.to_s
end
end
class EqualString2 < Test::Spec::CustomShould
def matches?(other)
object == other.to_s
end
def failure_message
"yada yada yada"
end
end
def empty_should(obj)
EmptyShould.new(obj)
end
def equal_string(str)
EqualString.new(str)
end
def equal_string2(str)
EqualString2.new(str)
end
end
context "test/spec" do
include MetaTests
specify "has should.satisfy" do
lambda { should.satisfy { 1 == 1 } }.should succeed
lambda { should.satisfy { 1 } }.should succeed
lambda { should.satisfy { 1 == 2 } }.should fail
lambda { should.satisfy { false } }.should fail
lambda { should.satisfy { false } }.should fail
lambda { 1.should.satisfy { |n| n % 2 == 0 } }.should fail
lambda { 2.should.satisfy { |n| n % 2 == 0 } }.should succeed
end
specify "has should.equal" do
lambda { "string1".should.equal "string1" }.should succeed
lambda { "string1".should.equal "string2" }.should fail
lambda { "1".should.equal 1 }.should fail
lambda { "string1".should == "string1" }.should succeed
lambda { "string1".should == "string2" }.should fail
lambda { "1".should == 1 }.should fail
end
specify "has should.raise" do
lambda { lambda { raise "Error" }.should.raise }.should succeed
lambda { lambda { raise "Error" }.should.raise RuntimeError }.should succeed
lambda { lambda { raise "Error" }.should.not.raise }.should fail
lambda { lambda { raise "Error" }.should.not.raise(RuntimeError) }.should fail
lambda { lambda { 1 + 1 }.should.raise }.should fail
lambda { lambda { raise "Error" }.should.raise(Interrupt) }.should fail
end
specify "has should.raise with a block" do
lambda { should.raise { raise "Error" } }.should succeed
lambda { should.raise(RuntimeError) { raise "Error" } }.should succeed
lambda { should.not.raise { raise "Error" } }.should fail
lambda { should.not.raise(RuntimeError) { raise "Error" } }.should fail
lambda { should.raise { 1 + 1 } }.should fail
lambda { should.raise(Interrupt) { raise "Error" } }.should fail
end
specify "should.raise should return the exception" do
ex = lambda { raise "foo!" }.should.raise
ex.should.be.kind_of RuntimeError
ex.message.should.match(/foo/)
end
specify "has should.be.an.instance_of" do
lambda {
lambda { "string".should.be_an_instance_of String }.should succeed
}.should.be deprecated
lambda {
lambda { "string".should.be_an_instance_of Hash }.should fail
}.should.be deprecated
lambda { "string".should.be.instance_of String }.should succeed
lambda { "string".should.be.instance_of Hash }.should fail
lambda { "string".should.be.an.instance_of String }.should succeed
lambda { "string".should.be.an.instance_of Hash }.should fail
end
specify "has should.be.nil" do
lambda { nil.should.be.nil }.should succeed
lambda { nil.should.be nil }.should succeed
lambda { nil.should.be_nil }.should.be deprecated
lambda { nil.should.not.be.nil }.should fail
lambda { nil.should.not.be nil }.should fail
lambda { lambda { nil.should.not.be_nil }.should fail }.should.be deprecated
lambda { "foo".should.be.nil }.should fail
lambda { "bar".should.be nil }.should fail
lambda { "foo".should.not.be.nil }.should succeed
lambda { "bar".should.not.be nil }.should succeed
end
specify "has should.include" do
lambda { [1,2,3].should.include 2 }.should succeed
lambda { [1,2,3].should.include 4 }.should fail
lambda { {1=>2, 3=>4}.should.include 1 }.should succeed
lambda { {1=>2, 3=>4}.should.include 2 }.should fail
end
specify "has should.be.a.kind_of" do
lambda { Array.should.be.kind_of Module }.should succeed
lambda { "string".should.be.kind_of Object }.should succeed
lambda { 1.should.be.kind_of Comparable }.should succeed
lambda { Array.should.be.a.kind_of Module }.should succeed
lambda { "string".should.be.a.kind_of Class }.should fail
lambda {
lambda { "string".should.be_a_kind_of Class }.should fail
}.should.be deprecated
lambda { Array.should.be_a_kind_of Module }.should.be deprecated
lambda { "string".should.be_a_kind_of Object }.should.be deprecated
lambda { 1.should.be_a_kind_of Comparable }.should.be deprecated
end
specify "has should.match" do
lambda { "string".should.match(/strin./) }.should succeed
lambda { "string".should.match("strin") }.should succeed
lambda { "string".should =~ /strin./ }.should succeed
lambda { "string".should =~ "strin" }.should succeed
lambda { "string".should.match(/slin./) }.should fail
lambda { "string".should.match("slin") }.should fail
lambda { "string".should =~ /slin./ }.should fail
lambda { "string".should =~ "slin" }.should fail
end
specify "has should.be" do
thing = "thing"
lambda { thing.should.be thing }.should succeed
lambda { thing.should.be "thing" }.should fail
lambda { 1.should.be(2, 3) }.should.raise(ArgumentError)
end
specify "has should.not.raise" do
lambda { lambda { 1 + 1 }.should.not.raise }.should succeed
lambda { lambda { 1 + 1 }.should.not.raise(Interrupt) }.should succeed
lambda {
begin
lambda {
raise ZeroDivisionError.new("ArgumentError")
}.should.not.raise(RuntimeError, StandardError, Comparable)
rescue ZeroDivisionError
end
}.should succeed
lambda { lambda { raise "Error" }.should.not.raise }.should fail
end
specify "has should.not.satisfy" do
lambda { should.not.satisfy { 1 == 2 } }.should succeed
lambda { should.not.satisfy { 1 == 1 } }.should fail
end
specify "has should.not.be" do
thing = "thing"
lambda { thing.should.not.be "thing" }.should succeed
lambda { thing.should.not.be thing }.should fail
lambda { thing.should.not.be thing, thing }.should.raise(ArgumentError)
end
specify "has should.not.equal" do
lambda { "string1".should.not.equal "string2" }.should succeed
lambda { "string1".should.not.equal "string1" }.should fail
end
specify "has should.not.match" do
lambda { "string".should.not.match(/sling/) }.should succeed
lambda { "string".should.not.match(/string/) }.should fail
lambda { "string".should.not.match("strin") }.should fail
lambda { "string".should.not =~ /sling/ }.should succeed
lambda { "string".should.not =~ /string/ }.should fail
lambda { "string".should.not =~ "strin" }.should fail
end
specify "has should.throw" do
lambda { lambda { throw :thing }.should.throw(:thing) }.should succeed
lambda { lambda { throw :thing2 }.should.throw(:thing) }.should fail
lambda { lambda { 1 + 1 }.should.throw(:thing) }.should fail
end
specify "has should.not.throw" do
lambda { lambda { 1 + 1 }.should.not.throw }.should succeed
lambda { lambda { throw :thing }.should.not.throw }.should fail
end
specify "has should.respond_to" do
lambda { "foo".should.respond_to :to_s }.should succeed
lambda { 5.should.respond_to :to_str }.should fail
lambda { :foo.should.respond_to :nx }.should fail
end
specify "has should.be_close" do
lambda { 1.4.should.be.close 1.4, 0 }.should succeed
lambda { 0.4.should.be.close 0.5, 0.1 }.should succeed
lambda {
lambda { 1.4.should.be_close 1.4, 0 }.should succeed
}.should.be deprecated
lambda {
lambda { 0.4.should.be_close 0.5, 0.1 }.should succeed
}.should.be deprecated
lambda {
float_thing = Object.new
def float_thing.to_f
0.2
end
float_thing.should.be.close 0.1, 0.1
}.should succeed
lambda { 0.4.should.be.close 0.5, 0.05 }.should fail
lambda { 0.4.should.be.close Object.new, 0.1 }.should fail
lambda { 0.4.should.be.close 0.5, -0.1 }.should fail
end
specify "multiple negation works" do
lambda { 1.should.equal 1 }.should succeed
lambda { 1.should.not.equal 1 }.should fail
lambda { 1.should.not.not.equal 1 }.should succeed
lambda { 1.should.not.not.not.equal 1 }.should fail
lambda { 1.should.equal 2 }.should fail
lambda { 1.should.not.equal 2 }.should succeed
lambda { 1.should.not.not.equal 2 }.should fail
lambda { 1.should.not.not.not.equal 2 }.should succeed
end
specify "has should.<predicate>" do
lambda { [].should.be.empty }.should succeed
lambda { [1,2,3].should.not.be.empty }.should succeed
lambda { [].should.not.be.empty }.should fail
lambda { [1,2,3].should.be.empty }.should fail
lambda { {1=>2, 3=>4}.should.has_key 1 }.should succeed
lambda { {1=>2, 3=>4}.should.not.has_key 2 }.should succeed
lambda { nil.should.bla }.should.raise(NoMethodError)
lambda { nil.should.not.bla }.should.raise(NoMethodError)
end
specify "has should.<predicate>?" do
lambda { [].should.be.empty? }.should succeed
lambda { [1,2,3].should.not.be.empty? }.should succeed
lambda { [].should.not.be.empty? }.should fail
lambda { [1,2,3].should.be.empty? }.should fail
lambda { {1=>2, 3=>4}.should.has_key? 1 }.should succeed
lambda { {1=>2, 3=>4}.should.not.has_key? 2 }.should succeed
lambda { nil.should.bla? }.should.raise(NoMethodError)
lambda { nil.should.not.bla? }.should.raise(NoMethodError)
end
specify "has should <operator> (>, >=, <, <=, ===)" do
lambda { 2.should.be > 1 }.should succeed
lambda { 1.should.be > 2 }.should fail
lambda { 1.should.be < 2 }.should succeed
lambda { 2.should.be < 1 }.should fail
lambda { 2.should.be >= 1 }.should succeed
lambda { 2.should.be >= 2 }.should succeed
lambda { 2.should.be >= 2.1 }.should fail
lambda { 2.should.be <= 1 }.should fail
lambda { 2.should.be <= 2 }.should succeed
lambda { 2.should.be <= 2.1 }.should succeed
lambda { Array.should === [1,2,3] }.should succeed
lambda { Integer.should === [1,2,3] }.should fail
lambda { /foo/.should === "foobar" }.should succeed
lambda { "foobar".should === /foo/ }.should fail
end
$contextscope = self
specify "is robust against careless users" do
lambda {
$contextscope.specify
}.should.raise(ArgumentError)
lambda {
$contextscope.specify "foo"
}.should.raise(ArgumentError)
lambda {
$contextscope.xspecify
}.should.raise(ArgumentError)
lambda {
$contextscope.xspecify "foo"
}.should.not.raise(ArgumentError) # allow empty xspecifys
lambda {
Kernel.send(:context, "foo")
}.should.raise(ArgumentError)
lambda {
context "foo" do
end
}.should.raise(Test::Spec::DefinitionError)
end
specify "should detect warnings" do
lambda { lambda { 0 }.should._warn }.should fail
lambda { lambda { warn "just a test" }.should._warn }.should succeed
end
specify "should message/blame faults" do
begin
2.should.blaming("Two is not two anymore!").equal 3
rescue Test::Unit::AssertionFailedError => e
e.message.should =~ /Two/
end
begin
2.should.messaging("Two is not two anymore!").equal 3
rescue Test::Unit::AssertionFailedError => e
e.message.should =~ /Two/
end
begin
2.should.blaming("I thought two was three").not.equal 2
rescue Test::Unit::AssertionFailedError => e
e.message.should =~ /three/
end
begin
2.should.blaming("I thought two was three").not.not.not.equal 3
rescue Test::Unit::AssertionFailedError => e
e.message.should =~ /three/
end
lambda {
lambda { raise "Error" }.should.messaging("Duh.").not.raise
}.should.raise(Test::Unit::AssertionFailedError).message.should =~ /Duh/
end
include TestShoulds
specify "should allow for custom shoulds" do
lambda { (1+1).should equal_string("2") }.should succeed
lambda { (1+2).should equal_string("2") }.should fail
lambda { (1+1).should.pass equal_string("2") }.should succeed
lambda { (1+2).should.pass equal_string("2") }.should fail
lambda { (1+1).should.be equal_string("2") }.should succeed
lambda { (1+2).should.be equal_string("2") }.should fail
lambda { (1+1).should.not equal_string("2") }.should fail
lambda { (1+2).should.not equal_string("2") }.should succeed
lambda { (1+2).should.not.not equal_string("2") }.should fail
lambda { (1+1).should.not.pass equal_string("2") }.should fail
lambda { (1+2).should.not.pass equal_string("2") }.should succeed
lambda { (1+1).should.not.be equal_string("2") }.should fail
lambda { (1+2).should.not.be equal_string("2") }.should succeed
lambda {
(1+2).should equal_string("2")
}.should.raise(Test::Unit::AssertionFailedError).message.should =~ /EqualString/
lambda { (1+1).should equal_string2("2") }.should succeed
lambda { (1+2).should equal_string2("2") }.should fail
lambda {
(1+2).should equal_string2("2")
}.should.raise(Test::Unit::AssertionFailedError).message.should =~ /yada/
lambda {
(1+2).should.blaming("foo").pass equal_string2("2")
}.should.raise(Test::Unit::AssertionFailedError).message.should =~ /foo/
lambda {
nil.should empty_should(nil)
}.should.raise(NotImplementedError)
lambda { nil.should :break, :now }.should.raise(ArgumentError)
lambda { nil.should.not :pass, :now }.should.raise(ArgumentError)
lambda { nil.should.not.not :break, :now }.should.raise(ArgumentError)
end
xspecify "disabled specification" do
# just trying
end
xspecify "empty specification"
context "more disabled" do
xspecify "this is intentional" do
# ...
end
specify "an empty specification" do
# ...
end
xcontext "even more disabled" do
specify "we can cut out" do
# ...
end
specify "entire contexts, now" do
# ...
end
end
end
end
context "setup/teardown" do
setup do
@a = 1
@b = 2
end
setup do
@a = 2
end
teardown do
@a.should.equal 2
@a = 3
end
teardown do
@a.should.equal 3
end
specify "run in the right order" do
@a.should.equal 2
@b.should.equal 2
end
end
context "before all" do
before(:all) { @a = 1 }
specify "runs parent before all" do
@a.should == 1
end
end
context "nested teardown" do
context "nested" do
specify "should call local teardown then parent teardown" do
@a = 3
end
teardown do
@a = 2
end
end
teardown do
@a.should.equal 2
@a = 1
end
after(:all) do
@a.should.equal 1
end
end
context "before all" do
context "nested" do
before(:all) do
@a = 2
end
specify "should call parent then local" do
@a.should.equal 2
@b.should.equal 2
end
end
before(:all) do
@a = 1
@b = 2
end
end
context "after all" do
context "after nested" do
after(:all) do
@a = 2
end
specify "should call local then parent" do
self.after_all
@a.should.equal 1
@b.should.equal 2
end
end
after(:all) do
@b = @a
@a = 1
end
end
module ContextHelper
def foo
42
end
end
context "contexts" do
include ContextHelper
FOO = 42
$class = self.class
specify "are defined in class scope" do
lambda { FOO }.should.not.raise(NameError)
FOO.should.equal 42
$class.should.equal Class
end
specify "can include modules" do
lambda { foo }.should.not.raise(NameError)
foo.should.equal 42
end
end
class CustomTestUnitSubclass < Test::Unit::TestCase
def test_truth
assert true
end
end
context "contexts with subclasses", CustomTestUnitSubclass do
specify "use the supplied class as the superclass" do
self.should.be.a.kind_of CustomTestUnitSubclass
end
end
xcontext "xcontexts with subclasses", CustomTestUnitSubclass do
specify "work great!" do
self.should.be.a.kind_of CustomTestUnitSubclass
end
end
shared_context "a shared context" do
specify "can be included several times" do
true.should.be true
end
behaves_like "yet another shared context"
end
shared_context "another shared context" do
specify "can access data" do
@answer.should.be 42
end
end
shared_context "yet another shared context" do
specify "can include other shared contexts" do
true.should.be true
end
end
context "Shared contexts" do
shared_context "a nested context" do
specify "can be nested" do
true.should.be true
end
end
setup do
@answer = 42
end
behaves_like "a shared context"
it_should_behave_like "a shared context"
behaves_like "a nested context"
behaves_like "another shared context"
ctx = self
specify "should raise when the context cannot be found" do
should.raise(NameError) {
ctx.behaves_like "no such context"
}
end
end
|
require 'gosu'
module Pomodoro
module Gui
class Window < Gosu::Window
IMAGE_ASSETS = {
background: "assets/images/background.png",
pomodoro: "assets/images/pomodoro.png",
occupied: "assets/images/occupied.png",
rest: "assets/images/rest.png"
}
AUDIO_ASSETS = {
start: "assets/sounds/start.wav",
rest: "assets/sounds/rest.wav"
}
FONT_ASSETS = {
font: "assets/fonts/roboto.ttf",
bold: "assets/fonts/roboto_bold.ttf"
}
def initialize(options={})
super 304, 488
@images = {}
@audio = {}
@interval = options[:interval]
@rest = options[:rest]
@state = 0
@cycles = 0
self.caption = "Pomodoro GUI"
self.load_assets
self.reset_timer
end
def launch!
self.show
end
def draw
@images[:background].draw(0, 0, 0)
@images[:pomodoro].draw(32, 16, 1)
if @state == 0
@images[:occupied].draw(104, 364, 1)
else
@images[:rest].draw(104, 364, 1)
end
@font.draw("Pomodoro ##{@cycles.to_s.rjust(2, '0')}", 78, 268, 3, 1, 1, Gosu::Color::BLACK)
@font_time.draw("#{(@t + @seconds).strftime('%M:%S')}", 92, 292, 3, 1, 1, @timer_colour)
end
def update
if @seconds == 0
@state = @state == 0 ? 1 : 0
self.reset_timer
else
@tick += 1
if @tick == 60
@seconds -= 1
@tick = 0
end
end
end
def needs_cursor?
true
end
protected
def load_assets
IMAGE_ASSETS.each do |key, value|
@images[key] = Gosu::Image.new(File.join(Pomodoro::Gui.root, "..", value))
end
AUDIO_ASSETS.each do |key, value|
@audio[key] = Gosu::Song.new(self, File.join(Pomodoro::Gui.root, "..", value))
end
@font = Gosu::Font.new(self, File.join(Pomodoro::Gui.root, "..", FONT_ASSETS[:font]), 32)
@font_time = Gosu::Font.new(self, File.join(Pomodoro::Gui.root, "..", FONT_ASSETS[:bold]), 64)
end
def reset_timer
if @state == 0
@seconds = @interval * 60
@timer_colour = Gosu::Color::RED
@cycles += 1
@audio[:start].play
else
@seconds = @rest * 60
@timer_colour = Gosu::Color::GREEN
@audio[:rest].play
end
@t = Time.new(0)
@tick = 0
end
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.