text stringlengths 10 2.61M |
|---|
module OTerm
#
class CommandError < Exception
def initialize(cmd)
super("#{cmd} is not a valid command")
end
end # CommandError
end # OTerm
|
FactoryBot.define do
factory :question do
title "MyString"
kind "MyString"
poll nil
end
end
|
class Genre < ActiveRecord::Base
has_many :restaurant_genres
has_many :restaurants, through: :restaurant_genre
validates :name, presence: true
validates :order, presence: true, numericality: true
end
|
class AddNameToUser < ActiveRecord::Migration
def change
add_column :users, :nickname, :string
add_column :users, :firstname, :string
add_column :users, :lastname, :string
add_index :users, :nickname
add_index :users, :firstname
add_index :users, :lastname
end
end
|
# frozen_string_literal: true
require_relative '../ferry-seat-planner'
RSpec.describe SeatingSimulator do
describe 'generate_next_state' do
let(:simulator) { SeatingSimulator.new }
specify do
tile_state = TileState.new(
tiles: TileCreator.create(seat_data: [
'L.LL.LL.LL'.split(''),
'LLLLLLL.LL'.split(''),
'L.L.L..L..'.split(''),
'LLLL.LL.LL'.split(''),
'L.LL.LL.LL'.split(''),
'L.LLLLL.LL'.split(''),
'..L.L.....'.split(''),
'LLLLLLLLLL'.split(''),
'L.LLLLLL.L'.split(''),
'L.LLLLL.LL'.split('')
])
)
expected_next_tile_state = TileState.new(
tiles: TileCreator.create(seat_data: [
'#.##.##.##'.split(''),
'#######.##'.split(''),
'#.#.#..#..'.split(''),
'####.##.##'.split(''),
'#.##.##.##'.split(''),
'#.#####.##'.split(''),
'..#.#.....'.split(''),
'##########'.split(''),
'#.######.#'.split(''),
'#.#####.##'.split('')
])
)
expect(simulator.generate_next_state(tile_state: tile_state)).to eq expected_next_tile_state
end
specify do
tile_state = TileState.new(
tiles: TileCreator.create(seat_data: [
'#.##.##.##'.split(''),
'#######.##'.split(''),
'#.#.#..#..'.split(''),
'####.##.##'.split(''),
'#.##.##.##'.split(''),
'#.#####.##'.split(''),
'..#.#.....'.split(''),
'##########'.split(''),
'#.######.#'.split(''),
'#.#####.##'.split('')
])
)
expected_next_tile_state = TileState.new(
tiles: TileCreator.create(seat_data: [
'#.LL.L#.##'.split(''),
'#LLLLLL.L#'.split(''),
'L.L.L..L..'.split(''),
'#LLL.LL.L#'.split(''),
'#.LL.LL.LL'.split(''),
'#.LLLL#.##'.split(''),
'..L.L.....'.split(''),
'#LLLLLLLL#'.split(''),
'#.LLLLLL.L'.split(''),
'#.#LLLL.##'.split('')
])
)
expect(simulator.generate_next_state(tile_state: tile_state)).to eq expected_next_tile_state
end
end
end
RSpec.describe TileState do
describe 'num_occupied_seats' do
let(:tile_state) {
described_class.new(tiles: [
[Tile.new(type: :seat, occupied: true), Tile.new(type: :floor, occupied: false), Tile.new(type: :seat, occupied: true)],
[Tile.new(type: :seat, occupied: false), Tile.new(type: :floor, occupied: false), Tile.new(type: :floor, occupied: false)],
[Tile.new(type: :seat, occupied: true), Tile.new(type: :seat, occupied: false), Tile.new(type: :seat, occupied: true)]
])
}
specify do
expect(tile_state.num_occupied_seats).to eq 4
end
end
end |
require "aethyr/core/actions/commands/asave"
require "aethyr/core/registry"
require "aethyr/core/input_handlers/admin/admin_handler"
module Aethyr
module Core
module Commands
module Asave
class AsaveHandler < Aethyr::Extend::AdminHandler
def self.create_help_entries
help_entries = []
command = "asave"
see_also = nil
syntax_formats = ["ASAVE"]
aliases = nil
content = <<'EOF'
Sorry no help has been written for this command yet
EOF
help_entries.push(Aethyr::Core::Help::HelpEntry.new(command, content: content, syntax_formats: syntax_formats, see_also: see_also, aliases: aliases))
return help_entries
end
def initialize(player)
super(player, ["asave"], help_entries: AsaveHandler.create_help_entries)
end
def self.object_added(data)
super(data, self)
end
def player_input(data)
super(data)
case data[:input]
when /^asave$/i
$manager.submit_action(Aethyr::Core::Actions::Asave::AsaveCommand.new(@player, {}))
end
end
private
end
Aethyr::Extend::HandlerRegistry.register_handler(AsaveHandler)
end
end
end
end
|
# @param {Integer} num_courses
# @param {Integer[][]} prerequisites
# @return {Boolean}
def can_finish(num_courses, prerequisites)
graph = Array.new(num_courses) {[]}
for pairs in prerequisites
crs = pairs[0]
preq = pairs[1]
graph[preq].append(crs)
end
indegree = Array.new(num_courses) {0}
for neighbors in graph do
for neighbor in neighbors do
indegree[neighbor] += 1
end
end
queue = Queue.new
for i in 0..(num_courses-1) do
queue.enq(i) if indegree[i] == 0
end
courses_taken = 0
until queue.empty?
cur_course = queue.deq
courses_taken += 1
for depended_course in graph[cur_course]
indegree[depended_course] -= 1
queue.enq depended_course if indegree[depended_course] == 0
end
end
if courses_taken == num_courses
return true
else
return false
end
end
p can_finish(4, [[1,0], [2, 0], [3, 1], [3, 2], [0, 3]]) |
require_relative "tile"
require "byebug"
class Board
attr_accessor :grid
def self.from_file(file_name)
lines = File.readlines(file_name).map(&:chomp)
grid = []
lines.each_with_index do |line, row_num|
line_numbers = line.split("").map(&:to_i)
line_int = []
line_numbers.each_with_index do |num, col_num|
subgrid = [row_num/3, col_num/3]
line_int << Tile.new(num, row_num, col_num, subgrid)
end
# p line_int
grid << line_int
end
self.new(grid)
end
def initialize(grid)
@grid = grid
# assign_tile_groups
end
# def assign_tile_groups
# grid.each
# end
def [](*pos)
grid[pos.first][pos.last]
end
def []=(*pos, val)
self[*pos].value = val unless self[*pos].given
end
def horizontal
" " + "- " * 12 + " "
end
def render
system("clear")
puts horizontal
grid.each_with_index do |row, row_idx|
print "| "
(0..8).each do |col_idx|
print self[row_idx, col_idx].to_s
print "| " if (col_idx%3 == 2)
end
puts
puts horizontal if (row_idx%3==2)
end
end
def arr_solved?(arr)
arr.all? do |row|
row.map(&:value).sort == (1..9).to_a
end
end
def rows_solved?
arr_solved?(grid)
end
def cols_solved?
cols = grid.transpose
arr_solved?(cols)
end
def create_subgrids
subgrids = []
(0..6).step(3).each do |top_left_row|
(0..6).step(3).each do |top_left_col|
subgrid = []
(0..2).each do |row_inc|
(0..2).each do |col_inc|
subgrid << self[top_left_row + row_inc, top_left_col + col_inc]
end
end
subgrids << subgrid
end
end
subgrids
end
def subgrids_solved?
arr_solved?(create_subgrids)
end
def solved?
rows_solved? && cols_solved? && subgrids_solved?
end
def create_1_to_9_hash(arr)
counts = Hash.new(0)
arr.each do |val|
counts[val] += 1
end
counts.delete(0)
counts
end
def digit_occurs_more_than_once(counts)
counts.any? {|val, count| count > 1}
end
def arr_error?(arr)
arr.any? do |row|
row_of_nums = row.map(&:value)
counts = create_1_to_9_hash(row_of_nums)
# p counts
digit_occurs_more_than_once(counts)
end
end
def row_error?
arr_error?(grid)
end
def col_error?
arr_error?(grid.transpose)
end
def subgrids_error?
arr_error?(create_subgrids)
end
def print_possible_values
grid.flatten.each do |tile|
p tile.possible_values
end
end
def reduce_possible_values
end
end
|
require 'rails_helper'
describe Types::PostType do
types = GraphQL::Define::TypeDefiner.instance
it 'defines a field id of type ID!' do
expect(subject).to have_field(:id).that_returns(!types.ID)
end
it 'defines a field title of type String!' do
expect(subject).to have_field(:title).that_returns(!types.String)
end
it 'defines a field content of type String!' do
expect(subject).to have_field(:content).that_returns(!types.String)
end
it 'defines a field updated_at of type String!' do
expect(subject).to have_field(:updated_at).that_returns(!types.String)
end
it 'defines a field user of type Types::UserType!' do
expect(subject).to have_field(:user).that_returns(!Types::UserType)
end
end
|
require 'spec_helper'
describe BidsController do
include Devise::TestHelpers
def login
@user = User.create!(name: 'example', email: 'example@domain.com', password: 'example1', password_confirmation: 'example1')
sign_in @user
end
context "#new" do
it 'should redirect to login page' do
get :new, review_request_id: 1
response.should redirect_to new_user_session_path
end
it 'should show the form' do
login
review_request = ReviewRequest.new(title: 'review'){|rr| rr.requestor = @user; rr.save!}
get :new, review_request_id: review_request.id
response.should render_template :new
assigns(:bid).review_request.should == review_request
end
end
context '#create' do
it "redirects to login page" do
post :create
response.should redirect_to new_user_session_path
end
it 'cannot create a bid on its own review request' do
login
review_request = ReviewRequest.new(title: 'review'){|rr| rr.requestor = @user; rr.save!}
post :create, bid: { review_request_id: review_request.id, bid_amount: 100 }
response.status.should == 401
end
it 'creates a bid' do
login
other_user = User.create!(name: 'other', email: 'other@domain.com', password: 'other1', password_confirmation: 'other1')
review_request = ReviewRequest.new(title: 'review'){|rr| rr.requestor = other_user; rr.save!}
post :create, bid: { review_request_id: review_request.id, bid_amount: 100, bid_message: 'Interested' }
response.should redirect_to review_request_path(review_request)
bid = assigns(:bid)
bid.bidder.should == @user
bid.review_request.should == review_request
bid.bid_amount.should == 100
bid.bid_message.should == 'Interested'
end
it 'sends an email notification to the requestor' do
login
requestor = User.create!(name: 'other', email: 'other@domain.com', password: 'other1', password_confirmation: 'other1')
review_request = ReviewRequest.new(title: 'review'){|rr| rr.requestor = requestor; rr.save!}
mail = mock()
BidNotifier.should_receive(:new_bid).and_return(mail)
mail.should_receive(:deliver)
post :create, bid: { review_request_id: review_request.id, bid_amount: 100, bid_message: 'Interested' }
end
end
context "#update" do
it 'redirects to the login page' do
put :update, id: 1
response.should redirect_to new_user_session_path
end
it 'cannot update another bidders bid' do
login
other_user = User.create!(name: 'other', email: 'other@domain.com', password: 'other1', password_confirmation: 'other1')
bid = Bid.new(bid_amount: 100, bid_message: 'Interested'){|b| b.bidder = other_user; b.review_request_id = 1; b.save!}
put :update, id: bid.id, bid: { bid_amount: 130 }
response.status.should == 401
bid.reload
bid.bid_amount.should == 100
end
it 'can update her own bid' do
login
other_user = User.create!(name: 'other', email: 'other@domain.com', password: 'other1', password_confirmation: 'other1')
review_request = ReviewRequest.new(title: 'review'){|rr| rr.requestor = other_user; rr.save!}
bid = Bid.new(bid_amount: 100, bid_message: 'Interested'){|b| b.bidder = @user; b.review_request = review_request; b.save!}
put :update, id: bid.id, bid: { bid_amount: 130 }
bid.reload
bid.bid_amount.should == 130
response.should redirect_to review_request_path(review_request)
end
it 'sends an email notification on a bid update' do
login
other_user = User.create!(name: 'other', email: 'other@domain.com', password: 'other1', password_confirmation: 'other1')
review_request = ReviewRequest.new(title: 'review'){|rr| rr.requestor = other_user; rr.save!}
bid = Bid.new(bid_amount: 100, bid_message: 'Interested'){|b| b.bidder = @user; b.review_request = review_request; b.save!}
mail = mock()
BidNotifier.should_receive(:bid_updated).and_return(mail)
mail.should_receive(:deliver)
put :update, id: bid.id, bid: { bid_amount: 130 }
end
end
context "#show" do
it 'responds with unauthorized unless the user is the bidder' do
login
other_user = User.create!(name: 'other', email: 'other@domain.com', password: 'other1', password_confirmation: 'other1')
review_request = ReviewRequest.new(title: 'review'){|rr| rr.requestor = other_user; rr.save!}
bid = Bid.new(bid_amount: 100, bid_message: 'Interested'){|b| b.bidder = other_user; b.review_request = review_request; b.save!}
get :show, id: bid.id
response.status.should == 401
end
it 'should let the bidder see its details' do
login
other_user = User.create!(name: 'other', email: 'other@domain.com', password: 'other1', password_confirmation: 'other1')
review_request = ReviewRequest.new(title: 'review'){|rr| rr.requestor = other_user; rr.save!}
bid = Bid.new(bid_amount: 100, bid_message: 'Interested'){|b| b.bidder = @user; b.review_request = review_request; b.save!}
get :show, id: bid.id
response.status.should == 200
response.should render_template :show
end
end
end
|
# BoardGameGeekLoader.rb
# GeekSearch
#
# Created by Guillaume Garcera on 08/12/09.
# Copyright 2009 __MyCompanyName__. All rights reserved.
class BoardGameGeekLoader
@@base_url = "http://www.boardgamegeek.com/xmlapi/search?search=%1"
#request delegate methods
# called when request is fininshed
# we can parse the response to get the search result now
def parse(receivedData)
result = []
doc = NSXMLDocument.alloc.initWithData(receivedData,
options:NSXMLDocumentValidate,
error:nil)
if doc
games = doc.nodesForXPath("*/boardgame", error: nil)
NSLog("Found : #{games.size} games")
results = games.map do |g|
game_id = g.attributeForName("objectid").stringValue
NSLog("game id : #{game_id}");
{
:name => g.nodesForXPath("name", error: nil).first.stringValue(),
:url => NSURL.URLWithString("http://www.boardgamegeek.com/boardgame/#{game_id}")
}
end
end
end
end |
Dado("que eu esteja na pagina principal") do
#Acessando o site
acessar = AcessarSite.new
acessar.load
#Logando na conta
logar_task = LogarTask.new
logar_task.log_in
end
Quando("acessar o menu criar nova task") do
#Clicando em nova task
novatask = NovaTask.new
novatask.load
#Criando nova task
criartask = CriarTask.new
criartask.Criar
end
#Confirmando criação da task
Entao("nova task criada com sucesso") do
assert_text 'Task criada com sucesso'
end
#Acessando o menu editar task
Quando("acessar o menu editar task") do
clicar_editar = ClicarEditar.new
clicar_editar.load
end
#Confirmando a edição da task
Entao("uma task editada com sucesso") do
assert_text "Task editada com sucesso"
end
#Deletando uma task
Quando("acessar o menu deletar task") do
deletar = DeleteTask.new
deletar.DeleteTask
end
#Confirmando a exclusão de uma task
Entao("task deletada com sucesso") do
assert_text "Task deletada com sucesso"
end |
# define santa class
class Santa_01
end
# create instance of santa class for speak
# add line to define speak method
# print "Ho ho ho! Haaaaapy Holidays!"
# end method
greeting = Santa_01.new
def speak
puts "Ho ho ho! Haaaaapy Holidays!"
end
# print speak method
puts speak
# create instance of Santa class for treats
# add line to define cookies method
# print "That was a good <parameter>!"
# end method
treats = Santa_01.new
def food(cookie)
puts "That was a good #{cookie}!"
end
# print eat_milk_and_cookies method
puts food("snickerdoodle")
# create instance of Santa class for initialize
# add line to define initialize method
# print "Initializing Santa instance..."
# end method
init = Santa_01.new
def initializing
puts "Initializing Santa instance..."
end
# print initialize method
puts initializing
# define method with attributes of gender and ethnicity
# list attributes
#end method
# define method listing reindeer array
# list array within attribute
# end method
# define method with age as a parameter
# default age attribute to 0
# end method
# define about method
# print ethnicity and gender
# end method
# define method that will age Santa by 1 year
# add one year to Santa age
# end method
# define getter that will list Santa age
# print age
# end method
# define
# define method that will state Santa dissatisfaction with reindeer
# print "Santa is mad at #{reindeer}"
# end method
# define method that will move reindeer to end of array
# move reindeer to end of array
# end method
# define method that will print current gender
# print gender
# end method
# define setter that will enable Santa to reassign gender
# have variable equal gender attribute
# end method
# define getter that will print ethnicity attribute
# print ethnicity
# end method
class Santa_02
def initialize(gender, ethnicity)
@gender = gender
@ethnicity = ethnicity
end
def reindeer
@reindeer_ranking = []
reindeer = "Rudolph Dasher Dancer Prancer Vixen Comet Cupid Donner Blitzen"
array = reindeer.split(' ')
array.each do |reindeer_ranking|
end
end
def reindeer_ranking
reindeer
end
def get_mad_at(index)
index = index.to_i
bad_deer = reindeer_ranking[index]
puts "Santa is mad at" + " " + bad_deer
puts bad_deer + " " + "will be moved to the end of the list"
deer_array = reindeer_ranking.rotate(-index)
p deer_array
end
def age
@age = 0
end
def celebrate_birthday(new_age)
@age = new_age
end
def ethnicity
@ethnicity
end
def gender
@gender
end
def gender=(gender_update)
@gender = gender_update
end
def age
@age
end
end
# write out driver code showing Santa diversity
# create new instance equalled to a variable
# specify attributes in parentheses
# print "This Santa is"
# call about method
puts "Santa_01"
firstsanta = Santa_02.new("male", "Filipino")
puts "This Santa is #{firstsanta.gender} and #{firstsanta.ethnicity}"
firstsanta.celebrate_birthday(1)
puts "This Santa is now #{firstsanta.age} years old"
puts "Santa_02"
secondsanta = Santa_02.new("non-binary", "Indian")
secondsanta.gender = "gender fluid"
puts "This Santa is #{secondsanta.gender} and #{secondsanta.ethnicity}"
puts "Santa_03"
thirdsanta = Santa_02.new("female", "Mixed Race")
puts "This Santa is #{thirdsanta.gender} and #{thirdsanta.ethnicity}"
puts "Santa_04"
fourthsanta = Santa_02.new("male", "Black")
fourthsanta.gender = "trans male"
puts "This Santa is #{fourthsanta.gender} and #{fourthsanta.ethnicity}"
puts "Reindeer ranking"
santahasdeer = Santa_02.new("non-binary", "European")
puts "This Santa is the oldest known Santa and #{santahasdeer.gender} and #{santahasdeer.ethnicity}"
puts "This is Santa's current reindeer ranking"
p santahasdeer.reindeer_ranking
santahasdeer.get_mad_at(4)
# Santa class with attr_reader and attr_accessor
class Santa
attr_reader :ethnicity
attr_accessor :gender
attr_accessor :age
def initialize(gender, ethnicity)
@gender = gender
@ethnicity = ethnicity
end
def reindeer
@reindeer_ranking = []
reindeer = "Rudolph Dasher Dancer Prancer Vixen Comet Cupid Donner Blitzen"
array = reindeer.split(' ')
array.each do |reindeer_ranking|
end
end
def reindeer_ranking
reindeer
end
def get_mad_at(index)
index = index.to_i
bad_deer = reindeer_ranking[index]
puts "Santa is mad at" + " " + bad_deer
puts bad_deer + " " + "will be moved to the end of the list"
deer_array = reindeer_ranking.rotate(-index)
p deer_array
end
end
puts "Santa_01"
firstsanta = Santa.new("male", "Filipino")
puts "This Santa is #{firstsanta.gender} and #{firstsanta.ethnicity}"
firstsanta.age = 1
puts "This Santa is now #{firstsanta.age} years old"
puts "Santa_02"
secondsanta = Santa.new("non-binary", "Indian")
secondsanta.gender = "gender fluid"
puts "This Santa is #{secondsanta.gender} and #{secondsanta.ethnicity}"
puts "Santa_03"
thirdsanta = Santa.new("female", "Mixed Race")
puts "This Santa is #{thirdsanta.gender} and #{thirdsanta.ethnicity}"
puts "Santa_04"
fourthsanta = Santa.new("male", "Black")
fourthsanta.gender = "trans male"
puts "This Santa is #{fourthsanta.gender} and #{fourthsanta.ethnicity}"
puts "Reindeer ranking"
santahasdeer = Santa.new("non-binary", "European")
puts "This Santa is the oldest known Santa and #{santahasdeer.gender} and #{santahasdeer.ethnicity}"
puts "This is Santa's current reindeer ranking"
p santahasdeer.reindeer_ranking
santahasdeer.get_mad_at(4)
puts "Random Santa Generator"
santas = []
example_genders = ["agender", "female", "bigender", "male", "female", "gender fluid"]
example_ethnicities = ["Black", "Latino", "white", "Japanese-African", "Filipino", "Mixed", "Pacific Islander", "Malay", "Chinese", "Mexican", "Inuit"]
age_range = (0..140).to_a
example_genders.length.times do |i|
santas << Santa.new(example_genders.sample, example_ethnicities.sample)
end
santas.each do |generate|
generate.age = age_range.sample
puts "This Santa is #{generate.ethnicity}, #{generate.gender}, and #{generate.age} years old"
end |
module Aggregator::Instagrams
def get_instagrams_by_tag(search_term, num=5)
first_hit = Instagram.tag_search(search_term).first
instas = Instagram.tag_recent_media(first_hit.name).first(num)
instas.map do |i|
{
name: i.user.full_name,
likes: i.likes.count,
image: i.images.standard_resolution.url,
caption_text: i.caption.text,
# passes date string in Unix timestamp
created_at: Time.at(i.created_time.to_i).to_date,
id: i.id,
link: i.link
}
end
end
def get_instagrams_by_username(name, num=5)
Instagram.user_search(name).first(num)
end
end |
module Rails
class Sources
require_relative "sources/version"
def self.establish(required: false, retries: 10, fallback: 30.seconds, global: true)
connection || new(required: required, retries: retries, fallback: fallback, global: global).connection
end
def self.connection
@connection
end
def self.connection=(value)
@connection = value
end
def initialize(required:, retries:, fallback:, global:)
return if global && self.class.connection
@global = global
self.connection = connect
rescue StandardError => exception
retries -= 1 unless required
logger.error(exception)
logger.debug(exception.backtrace.join("\n"))
sleep(fallback) and retry if required || retries.zero?
end
def connection
if @global
self.class.connection
else
@connection
end
end
def connection=(value)
if @global
self.class.connection = value
else
@connection = value
end
end
private def open?
raise NoMethodError, "missing implementation"
end
private def closed?
!open?
end
private def connect
raise NoMethodError, "missing implementation"
end
private def logger
if Rails.logger then Rails.logger else Logger.new STDOUT end
end
end
end
|
require 'fizzbuzz.rb'
class FizzBuzz::Engine
# FIXME: It is Numeric type pollution .
class ::Numeric
def fizz?
self % 3 == 0 && self % 5 != 0
end
def buzz?
self % 3 != 0 && self % 5 == 0
end
def fizzbuzz?
self % 3 == 0 && self % 5 == 0
end
end
def valid_range?(range)
range.size != 0 && range.first >= 1
end
def generate(range)
raise ArgumentError.new("Invalid range") unless valid_range?(range)
range.map {|number|
if number.fizz?
"Fizz"
elsif number.buzz?
"Buzz"
elsif number.fizzbuzz?
"Fizz Buzz"
else
number
end
}
end
end
|
module Hippo::TransactionSets
module HIPAA_835
class L2100 < Hippo::TransactionSets::Base
loop_name 'L2100' #Claim Payment Information
#Claim Payment Information
segment Hippo::Segments::CLP,
:name => 'Claim Payment Information',
:minimum => 1,
:maximum => 1,
:position => 100
#Claim Adjustment
segment Hippo::Segments::CAS,
:name => 'Claim Adjustment',
:minimum => 0,
:maximum => 99,
:position => 200
#Patient Name
segment Hippo::Segments::NM1,
:name => 'Patient Name',
:minimum => 1,
:maximum => 1,
:position => 290,
:defaults => {
'NM101' => 'QC',
'NM102' => '1'
}
#Insured Name
segment Hippo::Segments::NM1,
:name => 'Insured Name',
:minimum => 0,
:maximum => 1,
:position => 300,
:defaults => {
'NM101' => 'IL'
}
#Corrected Patient/Insured Name
segment Hippo::Segments::NM1,
:name => 'Corrected Patient/Insured Name',
:minimum => 0,
:maximum => 1,
:position => 310,
:defaults => {
'NM101' => '74'
}
#Service Provider Name
segment Hippo::Segments::NM1,
:name => 'Service Provider Name',
:minimum => 0,
:maximum => 1,
:position => 320,
:defaults => {
'NM101' => '82'
}
#Crossover Carrier Name
segment Hippo::Segments::NM1,
:name => 'Crossover Carrier Name',
:minimum => 0,
:maximum => 1,
:position => 330,
:defaults => {
'NM101' => 'TT',
'NM102' => '2'
}
#Corrected Priority Payer Name
segment Hippo::Segments::NM1,
:name => 'Corrected Priority Payer Name',
:minimum => 0,
:maximum => 1,
:position => 340,
:defaults => {
'NM101' => 'PR',
'NM102' => '2'
}
#Other Subscriber Name
segment Hippo::Segments::NM1,
:name => 'Other Subscriber Name',
:minimum => 0,
:maximum => 1,
:position => 350,
:defaults => {
'NM101' => 'GB'
}
#Inpatient Adjudication Information
segment Hippo::Segments::MIA,
:name => 'Inpatient Adjudication Information',
:minimum => 0,
:maximum => 1,
:position => 370
#Outpatient Adjudication Information
segment Hippo::Segments::MOA,
:name => 'Outpatient Adjudication Information',
:minimum => 0,
:maximum => 1,
:position => 380
#Other Claim Related Identification
segment Hippo::Segments::REF,
:name => 'Other Claim Related Identification',
:minimum => 0,
:maximum => 5,
:position => 400
#Rendering Provider Identification
segment Hippo::Segments::REF,
:name => 'Rendering Provider Identification',
:minimum => 0,
:maximum => 10,
:position => 450
#Statement From or To Date
segment Hippo::Segments::DTM,
:name => 'Statement From or To Date',
:minimum => 0,
:maximum => 2,
:position => 500
#Coverage Expiration Date
segment Hippo::Segments::DTM,
:name => 'Coverage Expiration Date',
:minimum => 0,
:maximum => 1,
:position => 505,
:defaults => {
'DTM01' => '036'
}
#Claim Received Date
segment Hippo::Segments::DTM,
:name => 'Claim Received Date',
:minimum => 0,
:maximum => 1,
:position => 510,
:defaults => {
'DTM01' => '050'
}
#Claim Contact Information
segment Hippo::Segments::PER,
:name => 'Claim Contact Information',
:minimum => 0,
:maximum => 2,
:position => 600,
:defaults => {
'PER01' => 'CX'
}
#Claim Supplemental Information
segment Hippo::Segments::AMT,
:name => 'Claim Supplemental Information',
:minimum => 0,
:maximum => 13,
:position => 620
#Claim Supplemental Information Quantity
segment Hippo::Segments::QTY,
:name => 'Claim Supplemental Information Quantity',
:minimum => 0,
:maximum => 14,
:position => 640
#Service Payment Information
loop Hippo::TransactionSets::HIPAA_835::L2110,
:name => 'Service Payment Information',
:minimum => 0,
:maximum => 999,
:position => 700
end
end
end
|
module TimeFormat
def short_with_zone
strftime('%Y-%m-%d %H:%M')
end
end
class ActiveSupport::TimeWithZone
include TimeFormat
end
class Time
include TimeFormat
end |
class Booking < ApplicationRecord
belongs_to :skill
belongs_to :user
has_many :reviews, dependent: :nullify
validates :starts_at, presence: true
validates :duration, presence: true
end
|
require_relative "utils"
require 'colorize'
require 'clamp'
require 'filewatcher'
require 'net/http'
class InitCommand < Clamp::Command
def execute
# check for existing Livefile
unless File.exists?('Livefile')
# load template
template = get_livefile_template
# save the template to a Livefile
File.open('Livefile', 'w') { |file|
file.write(template)
}
log "Livefile created"
else
log_error 'Livefile already exists!'
end
end
end
class WatchCommand < Clamp::Command
def execute
# read Livefile
livefile = load_livefile
# start watching folders
log "Watching folders for changes"
livefile['folders'].each do |folder|
log "\t#{folder}"
end
puts
FileWatcher.new(livefile['folders']).watch do |filename|
log "Updated " + filename
# call control url to reload on changes
puma_control_url = livefile['puma']['control'] + "/restart?token=" + livefile['puma']['token']
result = Net::HTTP.get(URI.parse(puma_control_url))
log "\tserver restart"
end
end
end
class SinatraLiveCommand < Clamp::Command
puts "\nSinatra (live)\n".light_blue
self.default_subcommand = 'watch'
subcommand 'watch', 'Start watching for changes (default)', WatchCommand
subcommand 'init', 'Create default Livefile.', InitCommand
end
SinatraLiveCommand.run
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Singer, type: :model do
it_should_behave_like 'PaperTrail enabled'
it { is_expected.to have_many(:melodies) }
describe 'バリデーション' do
it { is_expected.to validate_presence_of(:name) }
end
end
|
require "rspec"
require_relative "../../business/models/email"
describe Email do
it "comparing two different emails" do
expect(Email.new("first@example.com"))
.to_not eq Email.new("second@example.com")
end
it "comparing two equivalent emails" do
expect(Email.new("first@example.com"))
.to eq Email.new("FIRST@example.com")
end
it "should handle nil values" do
expect(Email.new(nil).to_s).to be_empty
end
it "loading a raw email" do
expect(Email.load("first@example.com")).to be_an Email
end
it "dumping an email" do
email = Email.new("first@example.com")
expect(Email.dump(email)).to eq "first@example.com"
end
it "trying to dumping a nil email" do
expect(Email.dump(nil)).to be_nil
end
end
|
class ComputerPlayer
attr_reader :mark, :console
def initialize(args = {})
@mark = args[:mark]
end
def get_input(board, open_tiles)
random_move(open_tiles)
end
def make_move(board, mark, input)
board.make_move(mark, input)
end
def random_move(open_tiles)
arr = convert_hash_to_array(open_tiles)
number_of_potential_moves = arr.length
index = random_index(number_of_potential_moves)
arr[index][0] + 1
end
def convert_hash_to_array(open_tiles)
open_tiles.to_a
end
def random_index(highest_index)
0 + rand(highest_index)
end
end
|
class Api::UsersController < ApplicationController
before_filter :authenticate_user!, :except => [:user,:user_feed,:user_posts,:post,:post_comments, :destroy_follower]
#GET
def show
if params[:id] == "me"
@user = current_user
else
@user = User.find_by_slug_or_id(params[:id])
end
raise FourOhFour if @user.nil?
render '/api/response'
end
def feed
if params[:id] == "me"
@user = current_user
else
@user = User.find_by_slug_or_id(params[:id])
end
raise FourOhFour if @user.nil?
if params[:after]
@posts = @user.feed
elsif
@posts = @user.feed
else
@posts = @user.feed
end
render '/api/response'
end
def posts
limit = 10
if params[:id] == "me"
@user = current_user
else
@user = User.find_by_slug_or_id(params[:id])
end
raise FourOhFour if @user.nil?
if params[:after]
after = params[:after].to_f
@posts = @user.posts_after(after,limit)
elsif
params[:before]
before = params[:before].to_f
@posts = @user.posts_before(before,limit)
else
@posts = @user.posts.limit(limit).all
end
render '/api/response'
end
#POST
def edit
if params[:id] != "me" && params[:id] != current_user.id
#TODO: error handling
render :text => '500', :status => 500
return
end
@user = current_user
@user.twitter_avatar_url = params[:avatar] unless !params.key?(:avatar)
@user.name = params[:name] unless !params.key?(:name)
@user.fb_crosspost_pages = params[:fb_crosspost_pages] unless !params.key?(:fb_crosspost_pages)
@user.tw_crosspost = params[:tw_crosspost] unless !params.key?(:tw_crosspost)
@user.save
render 'api/response'
end
def create_follower
#raise if @user = current_user
user = User.find_by_slug_or_id(params[:id])
user.followers << current_user
render 'api/response'
end
#DELETE
def destroy_follower
#raise if @user = current_user
@user = User.find_by_slug_or_id(params[:id])
@user.followers.delete(current_user)
render 'api/response'
end
end
|
class Artist < ActiveRecord::Base
has_many :songs
belongs_to :genre #belongs_to is always singular, there is also a 'belongs_to_many'
end
|
class FranchiseSerializer < ActiveModel::Serializer
attributes :id, :name, :medium, :average_rating, :ratings_count, :url, :your_rating
has_many :ratings
def average_rating
object.average_rating
end
def ratings_count
object.count_ratings
end
def url
"/franchises/#{object.id}"
end
def your_rating
current_user.rating_by_franchise(object)
end
end
|
class RenameColumnTechologyTypeToTechnologyTypeInTechnologies < ActiveRecord::Migration[6.0]
def change
rename_column :technologies, :techology_type, :technology_type
end
end
|
module ImageHelper
def convert_2D_to_1D(x,y)
raise OutofBound if x >= width or y >= height
x + (y * width)
end
def convert_1D_to_2D(index)
raise OutofBound if index > ((width * height )-1)
[index % width,index / width ]
end
class OutofBound < Exception
end
end
|
class AddOptionsToTitles < ActiveRecord::Migration[5.0]
def change
add_column :titles, :options, :string
add_column :records, :option, :string
end
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
require 'faker'
10.times do
dog = Dog.create!(dog_name: Faker::GreekPhilosophers.name, city_id: Faker::Number.between(1, 10))
end
10.times do
dogsitter = Dogsitter.create!(name: Faker::RuPaul.queen, city_id: Faker::Number.between(1, 10))
end
10.times do
stroll = Stroll.create!(dog_id: Faker::Number.between(1, 10), dogsitter_id: Faker::Number.between(1, 10))
end
10.times do
city = City.create!(city_name: Faker::Address.city)
end |
class ChangeColumnNameFromNotablePeople < ActiveRecord::Migration[5.2]
def change
rename_column :notable_people, :name, :person_name
end
end
|
class RemoveReligionIdFromPost < ActiveRecord::Migration
def change
remove_column :posts, :religion_id
end
end
|
class ApiCache < ActiveRecord::Base
EXPIRES_IN = 24.hours
belongs_to :user
validates_formatting_of :endpoint, using: :url
def self.get(endpoint)
Rails.cache.fetch(endpoint, expires_in: EXPIRES_IN) do
response = Faraday.get(endpoint)
response.body
end
end
def get
Rails.cache.fetch("#{user_id}/#{endpoint}", expires_in: settings[:expires_in] || ::EXPIRES_IN) do
response = Faraday.get(endpoint)
response.body
end
end
end
|
# name: disable-hide-presence
# version: 1.0.2
# authors: buildthomas
enabled_site_setting :disable_hide_presence_enabled
register_asset "stylesheets/disable-hide-presence.scss"
after_initialize do
# Intercept requests to update preferences
module UserUpdaterInterceptor
def update(attributes = {})
if SiteSetting.disable_hide_presence_enabled
# Delete entry and pass on if plugin enabled
attributes.delete(:hide_profile_and_presence)
end
super(attributes)
end
end
UserUpdater.send(:prepend, UserUpdaterInterceptor)
# Intercept requests to open profiles
module GuardianInterceptor
def can_see_profile?(user)
if SiteSetting.disable_hide_presence_enabled
# Overwrite implementation of can_see_profile? to not use presence setting
return !user.blank?
end
# Use default if plugin disabled
super(user)
end
end
Guardian.send(:prepend, GuardianInterceptor)
end
|
# frozen_string_literal: true
# Connects to Amazon's S3 service
class S3Service
@client ||= Aws::S3::Client.new
# Returns the response body text
def self.download(file_path)
resp = @client.get_object(bucket: ENV['SAMPLE_BUCKET'], key: file_path)
resp.body&.read
rescue Aws::S3::Errors::NoSuchKey, Aws::S3::Errors::NotFound, Aws::S3::Errors::BadRequest
nil
end
def self.exists_in_s3(remote_path, bucket = ENV['S3_DOWNLOAD_BUCKET_NAME'])
object = Aws::S3::Object.new(bucket_name: bucket, key: remote_path)
object.exists?
end
end
|
Gem::Specification.new do |s|
s.name = 'bgg-parser'
s.version = '0.0.4'
s.date = '2015-04-16'
s.summary = "Parses BoardGameGeek API"
s.description = "Parses JSON from the bgg-api gem, and creates model objects"
s.authors = ["Peter Mueller","Elizabeth Blackburn"]
s.email = ['peter.kh.mueller@gmail.com','e.r.blackburn@gmail.com']
s.files = ["lib/bgg-parser.rb"]
s.homepage = 'https://github.com/cbus-sea-lions-2015/bgg-parser'
s.license = 'MIT'
end
|
class CreateComments < ActiveRecord::Migration
def change
create_table :comments do |t|
t.string :name, :limit => 100, :null => false
t.string :email, :limit => 100, :null => false
t.string :url, :limit => 255, :null => false
t.boolean :active, :default => false, :null => false
t.string :body, :null => false
t.references :post
t.timestamps
end
add_index :comments, :post_id
end
end
|
#!/usr/bin/ruby -w
# -*- coding: UTF-8 -*-
# var
a = "aaaaaaaaaaaaaaaaaaaaaaaaaa"
puts a
a = 1
puts a
a = true
puts a
## if else
if a == false
p "a=true"
else
p "a=false"
end
## String.length
puts 'aa'.length
puts "ruby for jing".length
puts "中文"
puts "aa".include?('a')
## Array
array = [1,2,3,4]
puts array[1]
hash = {
"key"=>"a",
"value"=>"b"
}
puts hash["key"]
## Hash.new()
hash = Hash.new()
hash[:key] = "aa"
hash[:value] = 123
puts hash[:value]
## unless,until,while
i = 1
unless i <=16
puts i
#i++
end
i = 1
until i<=16
puts i
i = i + 1
end
i = 1
while i <= 16
puts i
i = i + 1
end
## def function_methods
## apply params
def aa(param)
puts "this is method to print 'aa'_" + param
end
## invoke aa_useParam
aa('kkkkkkkk')
if nil
puts 'nil'
end
i = "13"
puts i.to_i
puts "1abc".to_i
def some_method(number)
number = 7 # this is implicitly returned by the method
end
a = 5
some_method(a)
puts a |
module Registration
# Choose subscription period
def self.subscription_selection(screen_id)
return xml_skeleton("menu", "Période de souscription:", [["1", "Jour"], ["2", "Semaine"], ["3", "Mois"]], 0, "continue", screen_id)
end
def self.question_type_selection(screen_id)
return xml_skeleton("menu", "Choix du questionnaire:", [["1", "Révision scolaire"], ["2", "Culture générale"]], 1, "continue", screen_id)
end
def self.select_academic_level(screen_id)
return xml_skeleton("menu", "Niveau scolaire:", [["1", "6ème"], ["2", "5ème"], ["3", "4ème"], ["4", "3ème"], ["5", "2nde"], ["6", "1ère"], ["7", "Tle"]], 1, "continue", screen_id)
end
def self.confirm_registration(session, screen_id)
question_type = session.question_type
subscription = session.subscription
return xml_skeleton("menu", "Vous avez opté pour MOOV REVISION - #{question_type.name}#{session.academic_level ? ' niveau: ' + session.academic_level.name : ''}. Vous serez débité de #{subscription.price} FCFA. Inscription valable pour #{subscription.duration} jour#{(subscription.duration > 1) ? 's' : ''}", [["1", "Confirmer"], ["2", "Annuler"]], 1, "continue", screen_id)
end
def self.validate_registration(screen_id)
return xml_skeleton("form", "Bienvenue au jeu MOOV REVISION. Votre inscription a bien été prise en compte. Répondez aux questions, cumulez le maximum de points et gagnez de nombreux lots.", [], 0, "end", screen_id)
end
def self.cancel_registration(screen_id)
return xml_skeleton("form", "Vous avez annulé votre souscription au jeu MOOV REVISION. Répondez aux questions, cumulez le maximum de points et gagnez de nombreux lots.", [], 0, "end", screen_id)
end
def self.xml_skeleton(screen_type, text, menu_options, back_link, session_op, screen_id)
text = URI.escape(text)
#text = text.force_encoding("utf-8")
unless menu_options.blank?
my_menu = get_menu(menu_options)
end
return "<?xml version='1.0' encoding='utf-8'?>
<response>
<screen_type>#{screen_type}</screen_type>
<text>#{text}</text>
#{my_menu}
<back_link>#{back_link}</back_link>
<home_link>0</home_link>
<session_op>#{session_op}</session_op>
<screen_id>#{screen_id}</screen_id>
</response>
"
end
def self.get_menu(menu_options)
my_menu = "<options>"
menu_options.each do |menu_option|
my_menu << "<option choice = '#{menu_option[0]}'>#{menu_option[1]}</option>"
end
my_menu << "</options>"
end
end
|
require 'spec_helper'
describe UsersController do
describe "GET /users" do
it 'routes to users#index' do
get('/users').should route_to(controller: 'users', action: 'index')
end
end
describe "POST /users" do
it 'routes to users#create' do
post('/users').should route_to(controller: 'users', action: 'create')
end
end
describe "GET /users/new" do
it 'routes to users#new' do
get('/users/new').should route_to(controller: 'users', action: 'new')
end
end
describe "GET /users/:id/edit" do
it 'routes to users#edit' do
get('/users/1/edit').should route_to(controller: 'users', action: 'edit', id: '1')
end
end
describe "GET /users/:id" do
it 'routes to users#show' do
get('/users/1').should route_to(controller: 'users', action: 'show', id: '1')
end
end
describe "PUT /users/:id" do
it 'routes to users#update' do
put('/users/1').should route_to(controller: 'users', action: 'update', id: '1')
end
end
describe "DELETE /users/:id" do
it 'routes to users#destroy' do
delete('/users/1').should route_to(controller: 'users', action: 'destroy', id: '1')
end
end
end
|
class AdminController < ApplicationController
before_filter :check_user
before_filter :get_campaign, :only => [ :campaign, :delete_campaign, :undelete_campaign, :feature_campaign, :unfeature_campaign ]
def index
end
def campaigns
@campaigns = Campaign.all.order("created_at DESC")
end
def campaign
end
def delete_campaign
@campaign.delete
message("Campaign Deleted!")
redirect_to("/admin/campaign/#{@campaign.id}")
end
def undelete_campaign
@campaign.deleted_at = nil
@campaign.save
message("Campaign UnDeleted!")
redirect_to("/admin/campaign/#{@campaign.id}")
end
def feature_campaign
@campaign.feature
@campaign.save
message("Campaign Featured!")
redirect_to("/admin/campaign/#{@campaign.id}")
end
def unfeature_campaign
@campaign.unfeature
@campaign.save
message("Campaign UnFeatured!")
redirect_to("/admin/campaign/#{@campaign.id}")
end
def users
@users = User.all.order("created_at DESC")
end
def user
@user = User.find(params[:user_id])
end
private
def check_user
if signed_in? && current_user.is_admin?
@admin = current_user
else
raise ActionController::RoutingError.new('Not Found')
end
end
def get_campaign
@campaign = Campaign.with_deleted.find(params[:campaign_id])
end
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
# User.destroy_all
Timeline.destroy_all
Event.destroy_all
# USER SEED DATA
# emily = User.create(username: "Emily", email: "e@email.com", password_digest: "asdf")
# TIMELINE SEED DATA
beatles_albums = Timeline.create(title: "Beatles Albums", description: "A timeline showing the Beatles' discography")
emily_life = Timeline.create(title: "Emily's Life...So Far", description: "A timeline of major events in Emily's life")
# EVENT SEED DATA
please_please_me = Event.create(year: 1963, title: "Please Please Me", description: "First album with Apple Records", timeline_id: beatles_albums.id)
with_the_beatles = Event.create(year: 1963, title: "With the Beatles", description: "Another one", timeline_id: beatles_albums.id)
introducting_the_beatles = Event.create(year: 1964, title: "Introducing...The Beatles", description: "Another album released to fan acclaim", timeline_id: beatles_albums.id)
meet_the_beatles = Event.create(year: 1964, title: "Meet the Beatles", description: "First record with Capitol Records", timeline_id: beatles_albums.id)
hard_days_night = Event.create(year: 1964, title: "Hard Days Night", description: "Beatles release their fan-favorite to much acclaim", timeline_id: beatles_albums.id)
revolver = Event.create(year: 1967, title: "Revolver", description: "Another fan favorite released", timeline_id: beatles_albums.id)
birth = Event.create(year: 1979, title: "Birth", description: "Emily is born", timeline_id: emily_life.id)
kindergarten = Event.create(year: 1984, title: "First Day of School", description: "Emily attends her first day of kindergarten", timeline_id: emily_life.id)
hs_grad = Event.create(year: 1997, title: "Graduates from HS", description: "Emily graduates from high school and starts college", timeline_id: emily_life.id)
marriage = Event.create(year: 2015, title: "Wedding Day", description: "Emily marries Irena", timeline_id: emily_life.id) |
# frozen_string_literal: true
ActiveAdmin.register Document do
menu :priority => 12
permit_params :file, :event_type, :file_name, :url
controller do
def create
@document = Document.new
@document = document_attributes
if @document.save
redirect_to admin_document_path(@document)
else
render :new
end
end
def document_attributes
attrs = params[:document]
@document[:event_type] = attrs[:event_type]
@document[:file_name] = attrs['file_name']
# attrs['url'] = Google document url
# Eg: url = https://docs.google.com/document/d/DrqT7Iu4U/edit
@document[:url] = attrs['url']
# Connet's to google client, retrieves the google document and save's to 'file' column with pdf format.
@document[:file] = @document.google_document
@document
end
def update
@document = Document.where(id: params[:id]).first
@document = document_attributes
if @document.save
redirect_to admin_document_path(@document)
else
render :edit
end
end
end
# Reorderable Index Table
index do
column :event_type
column :file_name
column :created_at
column :updated_at
column :links do |resource|
links = ''.html_safe
if controller.action_methods.include?('show')
links += link_to I18n.t('active_admin.view'), resource_path(resource), :class => "member_link view_link"
end
if controller.action_methods.include?('edit')
links += link_to I18n.t('active_admin.edit'), edit_resource_path(resource), :class => "member_link edit_link"
end
if controller.action_methods.include?('destroy')
links += link_to I18n.t('active_admin.delete'), resource_path(resource), :method => :delete,
data: { confirm: 'Are you sure you want to delete this Content?' }, :class => "member_link delete_link"
end
links
end
end
form do |f|
f.inputs "Create MyLibraryNyc Documents" do
f.input :event_type, collection: Document::EVENTS, include_blank: false
f.input :file_name
f.input :url
end
f.actions
end
show do
attributes_table do
row :event_type
row :file_name
row :file do |f|
link_to("Download #{f.file_name}.pdf", download_pdf_admin_documents_path(f))
end
end
end
# Download document from show page.
collection_action :download_pdf, method: :get do
document = Document.find(params['format'])
send_data(document.file, filename: "#{document.file_name}.pdf", type: "application/pdf")
end
controller do
# Setting up Strong Parameters
# You must specify permitted_params within your document ActiveAdmin resource which reflects a document's expected params.
def permitted_params
params.permit document: [:file, :event_type, :url, :created_at, :updated_at]
end
end
end
|
module UdaciListErrors
class InvalidItemError < StandardError
end
class IndexExceedsListSize < StandardError
end
class InvalidPriorityValue < StandardError
end
end
|
module Services
class SlackNotifier
attr_reader :notification, :options
def initialize(notification, options={})
@notification = notification
@options = options
end
def call
notify
end
private
def notify
channel.ping notification.to_s
end
def channel
@channel ||= ::Slack::Notifier.new AppConfig.slack.webhook_url,
channel: AppConfig.slack.default_channel,
username: 'WebinariumApp',
color: '#0092ca'
end
end
end
|
class Member < ActiveRecord::Base
belongs_to :group
validates_presence_of :name, :email, :group
def to_param
"#{id}-#{name.parameterize}"
end
def path(action = nil)
url = []
url << action unless action.nil?
url << group.project
url << group
url << self
url
end
end
|
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable, :trackable, :omniauthable, :omniauth_providers => [:google_oauth2]
has_many :events
def self.from_omniauth(auth)
user = User.where(:provider => auth.try(:provider) || auth["provider"], :uid => auth.try(:uid) || auth["uid"]).first
if user
return user
else
registered_user = User.where(:provider=> auth.try(:provider) || auth["provider"], :uid=> auth.try(:uid) || auth["uid"]).first || User.where(:email=> auth.try(:info).try(:email) || auth["info"]["email"]).first
if registered_user
unless registered_user.provider == (auth.try(:provider) || auth["provider"]) && registered_user.uid == (auth.try(:uid) || auth["provider"])
registered_user.update_attributes(:provider=> auth.try(:provider) || auth["provider"], :uid=> auth.try(:uid) || auth["uid"])
end
return registered_user
else
user = User.new(:provider => auth.try(:provider) || auth["provider"], :uid => auth.try(:uid) || auth["uid"])
user.email = auth.try(:info).try(:email) || auth["info"]["email"]
user.password = Devise.friendly_token[0,20]
user.first_name = auth.info.name.split(" ")[0]
user.last_name = auth.info.name.split(" ")[1]
user.access_token = auth.credentials.token
user.expires_at = auth.credentials.expires_at
user.refresh_token = auth.credentials.refresh_token
user.save
puts user
end
user
end
end
def expired?
expires_at < Time.current.to_i
end
def name
"#{self.first_name} #{self.last_name}"
end
end
|
require 'minarai/recipe'
require 'minarai/loaders/base'
require 'minarai/loaders/variable_loader'
require 'minarai/variable'
module Minarai
module Loaders
class RecipeLoader < Base
def initialize(path, variable_path: nil)
super(path)
@variable_path = variable_path
end
private
def loaded_class
Minarai::Recipe
end
def has_variable_path?
!@variable_path.nil?
end
def binding_for_erb
variables.to_mash.binding
end
def variables
@variables ||= begin
if has_variable_path?
Minarai::Loaders::VariableLoader.new(@variable_path).load
else
Minarai::Variable.new({})
end
end
end
end
end
end
|
require "rspec"
require 'spec_helper.rb'
TTCP_EXECUTABLE = File.expand_path('../../bin/ttcp', __FILE__)
def test_ttcp(options = '')
`DRY_RUN=YES #{TTCP_EXECUTABLE} #{options} 2>&1`
end
describe "Command Line Option Parsing" do
it "ttcp fails without -t or -r" do
test_ttcp
$?.should_not == 0
end
it "ttcp fails with both -t and -r" do
test_ttcp '-t -r'
$?.should_not == 0
end
it "ttcp fails without a host with -t" do
test_ttcp '-t'
$?.should_not == 0
end
it "ttcp is ok with a host and -t" do
test_ttcp '-t HOST'
$?.should == 0
end
it "ttcp is ok with -r and no host" do
test_ttcp '-r'
$?.should == 0
end
specify "ttcp prints out the version" do
version = test_ttcp '--version'
version.chomp.should == TTCP::VERSION
end
end
|
class Api::V4::Analytics::OverdueListsController < Api::V4::AnalyticsController
def show
respond_to do |format|
format.csv do
@patient_summaries =
PatientSummaryQuery.call(assigned_facilities: [current_facility], only_overdue: false)
.includes(:latest_bp_passport, :current_prescription_drugs)
.order(risk_level: :desc, next_appointment_scheduled_date: :desc, id: :asc)
send_data render_to_string("show"), filename: download_filename
end
end
end
private
def download_filename
"overdue-patients_#{current_facility.name.parameterize}_#{Time.current.strftime("%d-%b-%Y-%H%M%S")}.csv"
end
end
|
class Category < ActiveRecord::Base
# relationships
has_many :products, dependent: :destroy
# validations
validates :name, presence: true, length: { minimum: 2 }
end
|
class SportTeam
attr_accessor(:name, :players, :coach)
attr_reader(:points)
def initialize(input_name, input_players, input_coach)
@name = input_name
@players = input_players
@coach = input_coach
@points = 0
def add_player(player)
return @players << player
end
def check_player(name)
for player in @players
if player == name
return true
end
end
end
def add_points(result)
if result.downcase == "win"
@points += 3
end
end
# def get_name()
# return @name
# end
#
# def get_players()
# return @players
# end
#
# def get_coach()
# return @coach
# end
#
# def set_coach_name(new_coach)
# @coach = new_coach
# end
#
end
end
|
module MemosHelper
# general
def health(memo)
health = 100 - decay_multiplier(memo) * decay_diff(memo)
health = 1 if health < 1
health = 100 if health > 100
health
end
def health_inc(memo, num_errors)
newDecay = Time.now - num_errors.days
increase = ((newDecay - memo.health_decay) / 1.day).round
increase = 0 if increase < 0
increase
end
def health_bar(memo)
if memo.practice_disabled
"<div class='progress progress-disabled'><div class='bar' style='width: 100%'></div></div>".html_safe
else
h = health memo
c = health_color memo
"<div class='progress progress-#{c} progress-striped active'><div class='bar' style='width: #{h}%'></div></div>".html_safe
end
end
def show_word_list(list)
h(list).gsub(/\r?\n/, '<br/>').html_safe
end
def within_acceptable_error_margin(wrong, missed)
(wrong.count <= acceptable_error_margin) and (missed.count <= acceptable_error_margin)
end
def acceptable_error_margin()
2
end
# Show page
def show_health()
h = health @memo
c = health_text_color @memo
"<span class='text-#{c}'>#{h}%</span>".html_safe
end
# Results page
def show_regained_health()
regained = health(@memo) - @prev_health
show = "<div class='text'>"
if @prev_health == 100
show << "<strong> Your health bar is already full </strong>"
else
show << "<span class='text-error'>" if regained.zero?
show << "<span class='text-success'>" unless regained.zero?
show << "<strong>Health replenished: #{regained}%</strong>"
show << "<p><strong>You made too many mistakes.</strong></p>" if regained.zero?
show << "</span>" if regained.zero?
end
show << "</div>"
show.html_safe
end
def show_prac_time()
show = "<div class='text'>"
show << "Session completed in <strong>#{@prac_time}</strong> seconds."
if within_acceptable_error_margin(@wrong_words, @missed_words)
if @prev_time.nil? or @prev_time > @prac_time
show << "<span class='text-success'><br/><strong>That's a new record!</strong></span>"
else
prac_time_diff = (@prac_time - @prev_time).round 1
show << "<p>#{prac_time_diff} seconds slower than your best...</p>"
end
else
show << "<p>Try again with fewer mistakes...</p>"
end
show << "</div>"
show.html_safe
end
# Index page
def color_memo_row(memo)
color = health_text_color memo
return color unless color == "success" or memo.practice_disabled
""
end
def show_word_count(memo)
memo.word_list.split.count
end
# # memo-status (index page)
def show_total_word_count()
return 0 if @memos.blank?
@memos.inject(0) { |acc, m| acc + m.word_list.split.count }
end
def show_total_practice_count()
return 0 if @memos.blank?
@memos.inject(0) { |acc, m| acc + m.num_practices }
end
def show_average_health()
return 0 if @memos.blank?
tot = @memos.inject(0) do |acc, m|
if m.practice_disabled
acc
else
acc + health(m)
end
end
avg = tot / @memos.reject { |m| m.practice_disabled == true }.count
c = "success"
c = "warning" if avg <= 75
c = "error" if avg <= 25
"<span class='text-#{c}'>#{avg}%</span>".html_safe
end
def show_average_word_time()
time_total = @memos.inject(0) { |acc, m| if m.best_time then acc + m.best_time else acc end }
memos_words_with_time = @memos.inject(0) { |acc, m| if m.best_time then acc + m.word_list.split(/\r?\n/).size else acc end }
unless memos_words_with_time.zero?
avg_time = time_total / memos_words_with_time
"#{"%.1f" % avg_time} s"
else
"n/a"
end
end
private
def health_color(memo)
health = health(memo)
color = "success"
color = "warning" if health <= 75
color = "danger" if health <= 25
color
end
def health_text_color(memo)
health_color(memo).gsub("danger", "error")
end
def decay_diff(memo)
((Time.now - memo.health_decay) / 1.day).to_i
end
def decay_multiplier(memo)
n = memo.num_practices
return 5 if n <= 5
return 4 if n <= 10
return 3 if n <= 15
return 2 if n <= 20
1
end
end
|
class User < ActiveRecord::Base
has_many :contacts
validates_presence_of :name
end
|
module GroupDocs
class Signature::Recipient < Api::Entity
STATUSES = {
:none => -1,
:waiting => 0,
:notified => 1,
:delegated => 2,
:rejected => 3,
:signed => 4,
}
# @attr [String] id
attr_accessor :id
# @attr [String] email
attr_accessor :email
# @attr [String] firstName
attr_accessor :firstName
# @attr [String] lastName
attr_accessor :lastName
# @attr [String] nickname
attr_accessor :nickname
# @attr [String] roleId
attr_accessor :roleId
# @attr [String] order
attr_accessor :order
# @attr [Symbol] status
attr_accessor :status
# added in release 1.7.0
# @attr [String] userGuid
attr_accessor :userGuid
# @attr [String] statusMessage
attr_accessor :statusMessage
# @attr [String] statusDateTime
attr_accessor :statusDateTime
# @attr [Double] delegatedRecipientId
attr_accessor :delegatedRecipientId
# @attr [String] signatureFingerprint
attr_accessor :signatureFingerprint
# @attr [String] signatureHost
attr_accessor :signatureHost
# @attr [String] signatureLocation
attr_accessor :signatureLocation
# @attr [String] signatureBrowser
attr_accessor :signatureBrowser
# @attr [String] embedUrl
attr_accessor :embedUrl
# @attr [String] comment
attr_accessor :comment
# Human-readable accessors
alias_accessor :first_name, :firstName
alias_accessor :last_name, :lastName
alias_accessor :role_id, :roleId
# added in release 1.7.0
alias_accessor :user_guid, :userGuid
alias_accessor :status_message, :statusMessage
alias_accessor :status_date_time, :statusDateTime
alias_accessor :delegated_recipient_id, :delegatedRecipientId
alias_accessor :signature_fingerprint, :signatureFingerprint
alias_accessor :signature_host, :signatureHost
alias_accessor :signature_location, :signatureLocation
alias_accessor :signature_browser, :signatureBrowser
alias_accessor :embed_url, :embedUrl
#
# Converts status to human-readable format.
# @return [Symbol]
#
def status
STATUSES.invert[@status]
end
end # Signature::Recipient
end # GroupDocs
|
class ApplicationController < ActionController::Base
# protect_from_forgery
# Probably Dangerous D:
rescue_from CanCan::AccessDenied do |exception|
redirect_to root_url , alert: "You can't access this page"
end
protected
def after_sign_in_path_for(resource)
feeds_path
end
# below method requires a 'user edit' path and page set up to word - have left method as a reminder
# def after_new_user_registration_path_for(resource)
# edit_user_path
# end
end
|
class User < ApplicationRecord
has_many :recipes, dependent: :destroy
has_many :moods, through: :recipes
validates :name, uniqueness: true, presence: true
# validates :age, numericality: { greater_than: 20, message: "must be 21 or older. Try again next time. "}, presence: true
# validates :budget, numericality: { less_than: 500, message: "must be less than $500. "}, presence: true
has_secure_password
end
|
require './config/environment.rb'
describe Post do
subject(:post) { Post.new }
let(:vote) { Vote.new }
let(:comment) {Comment.new}
describe "associations" do
it "should be able to get its vote" do
expect { post.votes }.not_to raise_error
end
it "should be able to get its comment" do
expect { post.comments}.not_to raise_error
end
end
end
describe Vote do
subject(:vote){Vote.new}
let(:post){Post.new}
describe "associations" do
it "should be able to get its post" do
expect { vote.post }.not_to raise_error
end
end
end
describe Comment do
subject(:comment){Comment.new}
let(:post){Post.new}
describe "associations" do
it "should be able to get its post" do
expect { comment.post }.not_to raise_error
end
end
end
|
# A Nested Array to Model a Bingo Board SOLO CHALLENGE
# I spent [#] hours on this challenge.
# Release 0: Pseudocode
# Outline:
# Create a method to generate a letter ( b, i, n, g, o) and a number (1-100)
#generate random number 0-4 and use it as index to select a a letter from (b,i,n,g,o)
#generate rangom number 0-100
# Check the called column for the number called.
#iterate through each row anc check each column for the number
# If the number is in the column, replace with an 'x'
#If there is a match replace with X
# Display a column to the console
#Print letter corresponding to index column
# Display the board to the console (prettily)
#Print each row
# Initial Solution
class BingoBoard
def initialize(board)
@bingo_board = board
end
def Call
@col_num = rand(0..4)
bingo_array = ["B", "I", "N", "G", "O"]
@letter = bingo_array[@col_num]
@num = rand(100)
@call = "#{@letter}#{@num}"
end
def Check
@bingo_board.each{|row|
if row[@col_num] == @num
row[@col_num] = "X"
end
}
end
def Display
@bingo_board.each{|row|
row.each{|num|
print "#{num}"
}
puts
}
end
end
# Refactored Solution
#DRIVER CODE (I.E. METHOD CALLS) GO BELOW THIS LINE
board = [[47, 44, 71, 8, 88],
[22, 69, 75, 65, 73],
[83, 85, 97, 89, 57],
[25, 31, 96, 68, 51],
[75, 70, 54, 80, 83]]
new_game = BingoBoard.new(board)
5.times do
p new_game.Call
new_game.Check
new_game.Display
end
#Reflection
# Does your call method return a letter and a number?yes
# Does your check method replace the number with a string if the number is present?Yes
# Does your check method not replace anything if the number is not present?Yes
# Does the board display to the console correctly? You can check this using your eyes.Yes
# How difficult was pseudocoding this challenge? What do you think of your pseudocoding style?The outline was there so it was not too bad.
# What are the benefits of using a class for this challenge?The ability to pass instance variables to different methods
# How can you access coordinates in a nested array?Array[index][sub_index]
# What methods did you use to access and modify the array?.each methods
# Give an example of a new method you learned while reviewing the Ruby docs. Based on what you see in the docs, what purpose does it serve, and how is it called?.times to use as a loop.
# How did you determine what should be an instance variable versus a local variable?local variables were used only in my .each methods for iteration purposes
# What do you feel is most improved in your refactored solution?
|
#!/usr/bin/ruby
require_relative "SampleWeightsDAO"
class SampleWeights
def initialize(id, chloroform_weight = 0, bromoform_weight = 0, bromodichloromethane_weight = 0, dibromichloromethane_weight = 0)
@id = id
@chloroform_weight = chloroform_weight
@bromoform_weight = bromoform_weight
@bromodichloromethane_weight = bromodichloromethane_weight
@dibromichloromethane_weight = dibromichloromethane_weight
end
attr_reader :id
attr_reader :chloroform_weight
attr_reader :bromoform_weight
attr_reader :bromodichloromethane_weight
attr_reader :dibromichloromethane_weight
def self.find(weight_id)
begin
connection = Mysql2::Client.new(:host => "localhost", :username => "carjam", :password => "XYZ") #consider external connection pooling for extensibility
dao = SampleWeightsDAO.new(connection)
if(weight_id)
return dao.findWhereIdEquals(weight_id)
else
return dao.findAll()
end
rescue Mysql2::Error => e
puts e.errno
puts e.error
ensure
connection.close if connection
end
end
end
|
module UserSchoolsHelper
def admin_add_school_button
if current_user.has_role?(:admin)
link_to user_schools_url(@user), class: "button is-link is-small" do
"<i class='fa fa-user'></i>".html_safe + "| Add user to a new school |" + "<i class='fas fa-school'></i>".html_safe
end
end
end
end |
# frozen_string_literal: true
require "spec_helper"
module Decidim
module Participations
describe ParticipationVote do
subject { participation_vote }
let!(:organization) { create(:organization) }
let!(:feature) { create(:feature, organization: organization, manifest_name: "participations") }
let!(:participatory_process) { create(:participatory_process, organization: organization) }
let!(:author) { create(:user, organization: organization) }
let!(:participation) { create(:participation, feature: feature, author: author) }
let!(:participation_vote) { build(:participation_vote, participation: participation, author: author) }
it "is valid" do
expect(participation_vote).to be_valid
end
it "has an associated author" do
expect(participation_vote.author).to be_a(Decidim::User)
end
it "has an associated participation" do
expect(participation_vote.participation).to be_a(Decidim::Participations::Participation)
end
it "validates uniqueness for author and participation combination" do
participation_vote.save!
expect do
create(:participation_vote, participation: participation, author: author)
end.to raise_error(ActiveRecord::RecordInvalid)
end
context "when no author" do
before do
participation_vote.author = nil
end
it { is_expected.to be_invalid }
end
context "when no participation" do
before do
participation_vote.participation = nil
end
it { is_expected.to be_invalid }
end
context "when participation and author have different organization" do
let(:other_author) { create(:user) }
let(:other_participation) { create(:participation) }
it "is invalid" do
participation_vote = build(:participation_vote, participation: other_participation, author: other_author)
expect(participation_vote).to be_invalid
end
end
context "when participation is rejected" do
let!(:participation) { create(:participation, :rejected, feature: feature, author: author) }
it { is_expected.to be_invalid }
end
end
end
end
|
class PrincePostProcessor
attr_accessor :text, :footnotes
def self.process_directory(digit="")
text = File.new("output/#{digit}/index.html").read
text = PrincePostProcessor.new(text).process
File.open("output/#{digit}/prince_index.html", 'w') do |f|
f << text
end
end
def initialize(text)
@text = text
@footnotes = {}
@counter = 0
end
def anchor_regex
%r{<a.*?href="#(fn_.*?)".*?</a>}
end
def data_regex
%r{<li\s*id="(.*?)">.*?<p>(.*?)</p>.*?</li>}m
end
def all_footnotes_regex
%r{<div class="footnotes">.*?</div>}m
end
def reverse_footnote_regex
%r{<a\s?href="#fn.*?class="reversefootnote".*?>.*?</a>}
end
def ulysses_media_regex
%r{<img src="Media\/(.*).png".*\/>}
end
def process
@text.gsub!(reverse_footnote_regex, "")
@text.scan(data_regex) do |match|
footnotes[match[0]] = match[1]
end
@text.gsub!(anchor_regex) do |match_string|
%{<span class="footnote">#{footnotes[$1]}</span>}
end
@text.gsub!(ulysses_media_regex) do |match_string|
filename = $1
filename = File.basename(filename, ".png").split(".")[0 .. -2].join(".")
result = %{<img src="images/#{filename}.png" style="height:90%;width:90%;" />}
result
end
@text.gsub!(all_footnotes_regex, "")
text
end
end
|
require 'rails_helper'
describe Point, type: :model do
describe '#create' do
before do
@user = create(:user)
end
context 'can save' do
it "すべてのデータがあり正常に登録できる" do
point = build(:point,user_id: @user.id)
expect(point).to be_valid
end
end
context 'can not save' do
it "ユーザーIDがないためエラーになる" do
point = build(:card)
point.valid?
expect(point.errors[:user]).to include("must exist")
end
end
end
end
|
#!/usr/bin/env ruby
require "rubygems"
require "ecology"
require "multi_json"
if ARGV.size == 0
$stderr.puts <<USAGE
Usage: with_ecology [-simple] <ecology-name>.ecology[.erb] <binary> [<args>]
Use "-simple" to exclude ECOLOGY_property_LENGTH and _TYPE fields.
USAGE
exit -1
end
@exclude_fields = false
ARGS = ["-simple"]
arg = ARGV.shift
while ARGS.include?(arg)
if arg == "-simple"
@exclude_fields = true
arg = ARGV.shift
end
end
arg = ARGV.shift if arg == "--"
Ecology.read(arg)
def export_prefix_key_value(prefix, key, value)
env_var_name = "#{prefix}#{key}"
type = case value
when Fixnum
"int"
when String
"string"
when Float
"float"
when TrueClass
"bool"
when FalseClass
"bool"
when NilClass
"null"
else
"unknown"
end
ENV[env_var_name] = value.to_s
unless @exclude_fields
ENV[env_var_name + "_TYPE"] = type
ENV[env_var_name + "_LENGTH"] = value.to_s.length.to_s
end
end
def export_properties(data, prefix)
data.each do |key, value|
if value.is_a?(Hash)
export_properties(value, "#{prefix}#{key}_")
elsif value.is_a?(Array)
export_prefix_key_value prefix, key, MultiJSON.encode(value)
else
export_prefix_key_value prefix, key, value
end
end
end
export_properties(Ecology.data, "ECOLOGY_")
exec ARGV.join(" ")
|
class Entry < ActiveRecord::Base
belongs_to :collection
attr_accessible :total
validates :total, presence: true,
numericality: { only_integer: true,
greater_than_or_equal_to: 0 }
end
|
require "application_system_test_case"
class PresentationdetailsTest < ApplicationSystemTestCase
setup do
@presentationdetail = presentationdetails(:one)
end
test "visiting the index" do
visit presentationdetails_url
assert_selector "h1", text: "Presentationdetails"
end
test "creating a Presentationdetail" do
visit presentationdetails_url
click_on "New Presentationdetail"
fill_in "Dtpresent", with: @presentationdetail.dtpresent
fill_in "Fostudy", with: @presentationdetail.fostudy
fill_in "Prdetails", with: @presentationdetail.prdetails
fill_in "Price", with: @presentationdetail.price
fill_in "Prname", with: @presentationdetail.prname
fill_in "Tdescription", with: @presentationdetail.tdescription
fill_in "Tname", with: @presentationdetail.tname
fill_in "Typepresent", with: @presentationdetail.typepresent
click_on "Create Presentationdetail"
assert_text "Presentationdetail was successfully created"
click_on "Back"
end
test "updating a Presentationdetail" do
visit presentationdetails_url
click_on "Edit", match: :first
fill_in "Dtpresent", with: @presentationdetail.dtpresent
fill_in "Fostudy", with: @presentationdetail.fostudy
fill_in "Prdetails", with: @presentationdetail.prdetails
fill_in "Price", with: @presentationdetail.price
fill_in "Prname", with: @presentationdetail.prname
fill_in "Tdescription", with: @presentationdetail.tdescription
fill_in "Tname", with: @presentationdetail.tname
fill_in "Typepresent", with: @presentationdetail.typepresent
click_on "Update Presentationdetail"
assert_text "Presentationdetail was successfully updated"
click_on "Back"
end
test "destroying a Presentationdetail" do
visit presentationdetails_url
page.accept_confirm do
click_on "Destroy", match: :first
end
assert_text "Presentationdetail was successfully destroyed"
end
end
|
module Egnyte
class Client
def file(path)
File::find(@session, path)
end
end
class File < Item
def download
stream.read
end
def download_version(entry_id)
stream(:entry_id => entry_id).read
end
# use opts to provide lambdas
# to track the streaming download:
#
# :content_length_proc
# :progress_proc
def stream( opts={} )
file_content_path = "#{fs_path('fs-content')}#{Egnyte::Helper.normalize_path(path)}"
file_content_path += "?entry_id=#{opts[:entry_id]}" if opts[:entry_id]
@session.streaming_download(file_content_path, opts )
end
def delete
@session.delete("#{fs_path}#{path}")
end
def self.find(session, path)
path = Egnyte::Helper.normalize_path(path)
file = File.new({
'path' => path
}, session)
parsed_body = session.get("#{file.fs_path}#{path}")
raise FileExpected if parsed_body['is_folder']
file.update_data(parsed_body)
end
end
end
|
require 'aethyr/core/objects/game_object'
require 'aethyr/core/objects/traits/readable'
#A simple object for testing Readable module.
#
#===Info
# writable (Boolean)
class Scroll < GameObject
include Readable
def initialize(*args)
super(*args)
@generic = "scroll"
@movable = true
@short_desc = "a plain scroll"
@long_desc = "This is simply a long piece of paper rolled up into a tight tube."
@alt_names = ["plain scroll"]
info.writable = true
end
end
|
# This file was generated by GoReleaser. DO NOT EDIT.
class Localroast < Formula
desc "Localroast quickly stubs a HTTP server"
homepage "https://github.com/caalberts/localroast"
version "0.4.0"
bottle :unneeded
if OS.mac?
url "https://github.com/caalberts/localroast/releases/download/v0.4.0/localroast_0.4.0_Darwin_x86_64.tar.gz"
sha256 "6e7dea5347ed76a4a137406b66eff3fcb6296485ccecaa22eb8fa9520083ec3b"
elsif OS.linux?
if Hardware::CPU.intel?
url "https://github.com/caalberts/localroast/releases/download/v0.4.0/localroast_0.4.0_Linux_x86_64.tar.gz"
sha256 "3774f0c94b2539772673afff84805623d153ed837cb12e7412876259e4a29246"
end
end
def install
bin.install "localroast"
end
test do
system "#{bin}/localroast version"
end
end
|
class ConsultantExamMailer < ApplicationMailer
def invite(sender, user)
@sender = sender
@user = user
set_locale
from = "#{@sender.name} <#{FROM_EMAIL}>"
mail(from: from, reply_to: @sender.email, to: @user.email, subject: _('Invitation to consultant exam'))
end
end
|
class AddImage2ToRefineryCafeteriaCategories < ActiveRecord::Migration
def change
add_column :refinery_cafeteria_categories, :image2_id, :integer
add_column :refinery_cafeteria_categories, :image3_id, :integer
end
end
|
class AddNewsletterTogglesToUser < ActiveRecord::Migration
def change
add_column :users, :all_newsletters, :boolean, default: true
end
end
|
class EventPolicy < ApplicationPolicy
# Todos podem ver evento e calendário
def show?
true
end
def calendar?
true
end
# Apenas Admin e Gestor de eventos GLOBAL podem criar e deletar
def create?
(user.is_admin? or user.is_event_admin?) if user
end
def new?
(user.is_admin? or user.is_event_admin?) if user
end
def destroy?
(user.is_admin? or user.is_event_admin?) if user
end
def archive?
(user.is_admin? or user.is_event_admin?) if user
end
def unarchive?
(user.is_admin? or user.is_event_admin?) if user
end
def roles?
(user.is_admin? or user.is_event_admin?) if user
end
# Para edição, o gestor de eventos LOCAL do evento em questão tem permissão também
def update?
can_manage_event? if user
end
def edit?
can_manage_event? if user
end
def emails?
can_manage_event? or user.is_volunteer? if user
end
def attendance?
can_manage_event? or user.is_volunteer? if user
end
# Método do Participations controller
def record_attendance?
can_manage_event? if user
end
private
def can_manage_event?
return true if (user.is_admin? or user.is_event_admin?)
return true if user.has_role? :event_admin, record
end
end
|
class Admin::ConfsController < Admin::BaseController
before_action :set_conf, only: [:show, :edit, :update, :destroy]
def index
@confs = Conf.all
respond_with(:admin, @confs)
end
def show
respond_with(:admin, @conf)
end
def new
@conf = Conf.new
respond_with(:admin, @conf)
end
def edit
end
def create
@conf = Conf.create(conf_params)
respond_with(:admin, @conf)
end
def update
@conf.update_attributes(conf_params)
respond_with(:admin, @conf)
end
def destroy
@conf.destroy
respond_with(:admin, @conf)
end
private
def set_conf
@conf = Conf.find(params[:id])
end
def conf_params
params.require(:conf).permit(:name, :value)
end
end
|
require File.expand_path('../spec_helper.rb', __FILE__)
describe SyslogHelpers::Priority do
describe "severities" do
it "should return all of the severities" do
SyslogHelpers::Priority.severities.should == { 0 => 'emerg',
1 => 'alert',
2 => 'crit',
3 => 'err',
4 => 'warning',
5 => 'notice',
6 => 'info',
7 => 'debug' }
end
end
describe "severity_for_priority" do
it "should return the severity for the priority" do
SyslogHelpers::Priority.severity_for_priority(150).should == 'info'
end
end
describe "facility_for_priority" do
it "should return the facility for the priority" do
SyslogHelpers::Priority.facility_for_priority(150).should == 'local2'
end
end
describe "data_for_priority" do
it "should return the data for the priority" do
SyslogHelpers::Priority.data_for_priority(150).should == { 'facility' => 'local2', 'severity' => 'info' }
end
end
describe "facilities" do
it "should return all of the facilities" do
SyslogHelpers::Priority.facilities.should == { 0 => 'kern',
1 => 'user',
2 => 'mail',
3 => 'daemon',
4 => 'auth',
5 => 'syslog',
6 => 'lpr',
7 => 'news',
8 => 'uucp',
9 => 'cron',
10 => 'authpriv',
11 => 'ftp',
12 => 'ntp',
13 => 'audit',
14 => 'alert',
15 => 'clock',
16 => 'local0',
17 => 'local1',
18 => 'local2',
19 => 'local3',
20 => 'local4',
21 => 'local5',
22 => 'local6',
23 => 'local7' }
end
end
describe "priority_map" do
it "should return the priority map data" do
priority_map_data = { 0 => { 'facility' => 'kern', 'severity' => 'emerg' }, 1 => { 'facility' => 'kern', 'severity' => 'alert' },
2 => { 'facility' => 'kern', 'severity' => 'crit' }, 3 => { 'facility' => 'kern', 'severity' => 'err' },
4 => { 'facility' => 'kern', 'severity' => 'warning' }, 5 => { 'facility' => 'kern', 'severity' => 'notice' },
6 => { 'facility' => 'kern', 'severity' => 'info' }, 7 => { 'facility' => 'kern', 'severity' => 'debug' },
8 => { 'facility' => 'user', 'severity' => 'emerg' }, 9 => { 'facility' => 'user', 'severity' => 'alert' },
10 => { 'facility' => 'user', 'severity' => 'crit' }, 11 => { 'facility' => 'user', 'severity' => 'err' },
12 => { 'facility' => 'user', 'severity' => 'warning' }, 13 => { 'facility' => 'user', 'severity' => 'notice' },
14 => { 'facility' => 'user', 'severity' => 'info' }, 15 => { 'facility' => 'user', 'severity' => 'debug' },
16 => { 'facility' => 'mail', 'severity' => 'emerg' }, 17 => { 'facility' => 'mail', 'severity' => 'alert' },
18 => { 'facility' => 'mail', 'severity' => 'crit' }, 19 => { 'facility' => 'mail', 'severity' => 'err' },
20 => { 'facility' => 'mail', 'severity' => 'warning' }, 21 => { 'facility' => 'mail', 'severity' => 'notice' },
22 => { 'facility' => 'mail', 'severity' => 'info' }, 23 => { 'facility' => 'mail', 'severity' => 'debug' },
24 => { 'facility' => 'daemon', 'severity' => 'emerg' }, 25 => { 'facility' => 'daemon', 'severity' => 'alert' },
26 => { 'facility' => 'daemon', 'severity' => 'crit' }, 27 => { 'facility' => 'daemon', 'severity' => 'err' },
28 => { 'facility' => 'daemon', 'severity' => 'warning' }, 29 => { 'facility' => 'daemon', 'severity' => 'notice' },
30 => { 'facility' => 'daemon', 'severity' => 'info' }, 31 => { 'facility' => 'daemon', 'severity' => 'debug' },
32 => { 'facility' => 'auth', 'severity' => 'emerg' }, 33 => { 'facility' => 'auth', 'severity' => 'alert' },
34 => { 'facility' => 'auth', 'severity' => 'crit' }, 35 => { 'facility' => 'auth', 'severity' => 'err' },
36 => { 'facility' => 'auth', 'severity' => 'warning' }, 37 => { 'facility' => 'auth', 'severity' => 'notice' },
38 => { 'facility' => 'auth', 'severity' => 'info' }, 39 => { 'facility' => 'auth', 'severity' => 'debug' },
40 => { 'facility' => 'syslog', 'severity' => 'emerg' }, 41 => { 'facility' => 'syslog', 'severity' => 'alert' },
42 => { 'facility' => 'syslog', 'severity' => 'crit' }, 43 => { 'facility' => 'syslog', 'severity' => 'err' },
44 => { 'facility' => 'syslog', 'severity' => 'warning' }, 45 => { 'facility' => 'syslog', 'severity' => 'notice' },
46 => { 'facility' => 'syslog', 'severity' => 'info' }, 47 => { 'facility' => 'syslog', 'severity' => 'debug' },
48 => { 'facility' => 'lpr', 'severity' => 'emerg' }, 49 => { 'facility' => 'lpr', 'severity' => 'alert' },
50 => { 'facility' => 'lpr', 'severity' => 'crit' }, 51 => { 'facility' => 'lpr', 'severity' => 'err' },
52 => { 'facility' => 'lpr', 'severity' => 'warning' }, 53 => { 'facility' => 'lpr', 'severity' => 'notice' },
54 => { 'facility' => 'lpr', 'severity' => 'info' }, 55 => { 'facility' => 'lpr', 'severity' => 'debug' },
56 => { 'facility' => 'news', 'severity' => 'emerg' }, 57 => { 'facility' => 'news', 'severity' => 'alert' },
58 => { 'facility' => 'news', 'severity' => 'crit' }, 59 => { 'facility' => 'news', 'severity' => 'err' },
60 => { 'facility' => 'news', 'severity' => 'warning' }, 61 => { 'facility' => 'news', 'severity' => 'notice' },
62 => { 'facility' => 'news', 'severity' => 'info' }, 63 => { 'facility' => 'news', 'severity' => 'debug' },
64 => { 'facility' => 'uucp', 'severity' => 'emerg' }, 65 => { 'facility' => 'uucp', 'severity' => 'alert' },
66 => { 'facility' => 'uucp', 'severity' => 'crit' }, 67 => { 'facility' => 'uucp', 'severity' => 'err' },
68 => { 'facility' => 'uucp', 'severity' => 'warning' }, 69 => { 'facility' => 'uucp', 'severity' => 'notice' },
70 => { 'facility' => 'uucp', 'severity' => 'info' }, 71 => { 'facility' => 'uucp', 'severity' => 'debug' },
72 => { 'facility' => 'cron', 'severity' => 'emerg' }, 73 => { 'facility' => 'cron', 'severity' => 'alert' },
74 => { 'facility' => 'cron', 'severity' => 'crit' }, 75 => { 'facility' => 'cron', 'severity' => 'err' },
76 => { 'facility' => 'cron', 'severity' => 'warning' }, 77 => { 'facility' => 'cron', 'severity' => 'notice' },
78 => { 'facility' => 'cron', 'severity' => 'info' }, 79 => { 'facility' => 'cron', 'severity' => 'debug' },
80 => { 'facility' => 'authpriv', 'severity' => 'emerg' }, 81 => { 'facility' => 'authpriv', 'severity' => 'alert' },
82 => { 'facility' => 'authpriv', 'severity' => 'crit' }, 83 => { 'facility' => 'authpriv', 'severity' => 'err' },
84 => { 'facility' => 'authpriv', 'severity' => 'warning' }, 85 => { 'facility' => 'authpriv', 'severity' => 'notice' },
86 => { 'facility' => 'authpriv', 'severity' => 'info' }, 87 => { 'facility' => 'authpriv', 'severity' => 'debug' },
88 => { 'facility' => 'ftp', 'severity' => 'emerg' }, 89 => { 'facility' => 'ftp', 'severity' => 'alert' },
90 => { 'facility' => 'ftp', 'severity' => 'crit' }, 91 => { 'facility' => 'ftp', 'severity' => 'err' },
92 => { 'facility' => 'ftp', 'severity' => 'warning' }, 93 => { 'facility' => 'ftp', 'severity' => 'notice' },
94 => { 'facility' => 'ftp', 'severity' => 'info' }, 95 => { 'facility' => 'ftp', 'severity' => 'debug' },
96 => { 'facility' => 'ntp', 'severity' => 'emerg' }, 97 => { 'facility' => 'ntp', 'severity' => 'alert' },
98 => { 'facility' => 'ntp', 'severity' => 'crit' }, 99 => { 'facility' => 'ntp', 'severity' => 'err' },
100 => { 'facility' => 'ntp', 'severity' => 'warning' }, 101 => { 'facility' => 'ntp', 'severity' => 'notice' },
102 => { 'facility' => 'ntp', 'severity' => 'info' }, 103 => { 'facility' => 'ntp', 'severity' => 'debug' },
104 => { 'facility' => 'audit', 'severity' => 'emerg' }, 105 => { 'facility' => 'audit', 'severity' => 'alert' },
106 => { 'facility' => 'audit', 'severity' => 'crit' }, 107 => { 'facility' => 'audit', 'severity' => 'err' },
108 => { 'facility' => 'audit', 'severity' => 'warning' }, 109 => { 'facility' => 'audit', 'severity' => 'notice' },
110 => { 'facility' => 'audit', 'severity' => 'info' }, 111 => { 'facility' => 'audit', 'severity' => 'debug' },
112 => { 'facility' => 'alert', 'severity' => 'emerg' }, 113 => { 'facility' => 'alert', 'severity' => 'alert' },
114 => { 'facility' => 'alert', 'severity' => 'crit' }, 115 => { 'facility' => 'alert', 'severity' => 'err' },
116 => { 'facility' => 'alert', 'severity' => 'warning' }, 117 => { 'facility' => 'alert', 'severity' => 'notice' },
118 => { 'facility' => 'alert', 'severity' => 'info' }, 119 => { 'facility' => 'alert', 'severity' => 'debug' },
120 => { 'facility' => 'clock', 'severity' => 'emerg' }, 121 => { 'facility' => 'clock', 'severity' => 'alert' },
122 => { 'facility' => 'clock', 'severity' => 'crit' }, 123 => { 'facility' => 'clock', 'severity' => 'err' },
124 => { 'facility' => 'clock', 'severity' => 'warning' }, 125 => { 'facility' => 'clock', 'severity' => 'notice' },
126 => { 'facility' => 'clock', 'severity' => 'info' }, 127 => { 'facility' => 'clock', 'severity' => 'debug' },
128 => { 'facility' => 'local0', 'severity' => 'emerg' }, 129 => { 'facility' => 'local0', 'severity' => 'alert' },
130 => { 'facility' => 'local0', 'severity' => 'crit' }, 131 => { 'facility' => 'local0', 'severity' => 'err' },
132 => { 'facility' => 'local0', 'severity' => 'warning' }, 133 => { 'facility' => 'local0', 'severity' => 'notice' },
134 => { 'facility' => 'local0', 'severity' => 'info' }, 135 => { 'facility' => 'local0', 'severity' => 'debug' },
136 => { 'facility' => 'local1', 'severity' => 'emerg' }, 137 => { 'facility' => 'local1', 'severity' => 'alert' },
138 => { 'facility' => 'local1', 'severity' => 'crit' }, 139 => { 'facility' => 'local1', 'severity' => 'err' },
140 => { 'facility' => 'local1', 'severity' => 'warning' }, 141 => { 'facility' => 'local1', 'severity' => 'notice' },
142 => { 'facility' => 'local1', 'severity' => 'info' }, 143 => { 'facility' => 'local1', 'severity' => 'debug' },
144 => { 'facility' => 'local2', 'severity' => 'emerg' }, 145 => { 'facility' => 'local2', 'severity' => 'alert' },
146 => { 'facility' => 'local2', 'severity' => 'crit' }, 147 => { 'facility' => 'local2', 'severity' => 'err' },
148 => { 'facility' => 'local2', 'severity' => 'warning' }, 149 => { 'facility' => 'local2', 'severity' => 'notice' },
150 => { 'facility' => 'local2', 'severity' => 'info' }, 151 => { 'facility' => 'local2', 'severity' => 'debug' },
152 => { 'facility' => 'local3', 'severity' => 'emerg' }, 153 => { 'facility' => 'local3', 'severity' => 'alert' },
154 => { 'facility' => 'local3', 'severity' => 'crit' }, 155 => { 'facility' => 'local3', 'severity' => 'err' },
156 => { 'facility' => 'local3', 'severity' => 'warning' }, 157 => { 'facility' => 'local3', 'severity' => 'notice' },
158 => { 'facility' => 'local3', 'severity' => 'info' }, 159 => { 'facility' => 'local3', 'severity' => 'debug' },
160 => { 'facility' => 'local4', 'severity' => 'emerg' }, 161 => { 'facility' => 'local4', 'severity' => 'alert' },
162 => { 'facility' => 'local4', 'severity' => 'crit' }, 163 => { 'facility' => 'local4', 'severity' => 'err' },
164 => { 'facility' => 'local4', 'severity' => 'warning' }, 165 => { 'facility' => 'local4', 'severity' => 'notice' },
166 => { 'facility' => 'local4', 'severity' => 'info' }, 167 => { 'facility' => 'local4', 'severity' => 'debug' },
168 => { 'facility' => 'local5', 'severity' => 'emerg' }, 169 => { 'facility' => 'local5', 'severity' => 'alert' },
170 => { 'facility' => 'local5', 'severity' => 'crit' }, 171 => { 'facility' => 'local5', 'severity' => 'err' },
172 => { 'facility' => 'local5', 'severity' => 'warning' }, 173 => { 'facility' => 'local5', 'severity' => 'notice' },
174 => { 'facility' => 'local5', 'severity' => 'info' }, 175 => { 'facility' => 'local5', 'severity' => 'debug' },
176 => { 'facility' => 'local6', 'severity' => 'emerg' }, 177 => { 'facility' => 'local6', 'severity' => 'alert' },
178 => { 'facility' => 'local6', 'severity' => 'crit' }, 179 => { 'facility' => 'local6', 'severity' => 'err' },
180 => { 'facility' => 'local6', 'severity' => 'warning' }, 181 => { 'facility' => 'local6', 'severity' => 'notice' },
182 => { 'facility' => 'local6', 'severity' => 'info' }, 183 => { 'facility' => 'local6', 'severity' => 'debug' },
184 => { 'facility' => 'local7', 'severity' => 'emerg' }, 185 => { 'facility' => 'local7', 'severity' => 'alert' },
186 => { 'facility' => 'local7', 'severity' => 'crit' }, 187 => { 'facility' => 'local7', 'severity' => 'err' },
188 => { 'facility' => 'local7', 'severity' => 'warning' }, 189 => { 'facility' => 'local7', 'severity' => 'notice' },
190 => { 'facility' => 'local7', 'severity' => 'info' }, 191 => { 'facility' => 'local7', 'severity' => 'debug' }
}
SyslogHelpers::Priority.priority_map.should == priority_map_data
end
end
end
|
class LocationSetting < ActiveRecord::Base
attr_accessible :user_id, :name, :notification_method,
:pace_min, :pace_max, :distance_min, :distance_max, :latitude,
:longitude, :address, :search_radius
belongs_to :user
validates_presence_of :name, :notification_method,
:pace_min, :pace_max, :distance_min, :distance_max,
:search_radius, :address
validates_uniqueness_of :name, :scope => :user_id
validates_numericality_of :search_radius, greater_than: 0, less_than_or_equal_to: 10
validates_numericality_of :pace_max, :greater_than_or_equal_to => :pace_min,
:message => "must be greater than or equal to pace min"
validates_numericality_of :distance_max, :greater_than_or_equal_to => :distance_min,
:message => "must be greater than or equal to distance min"
before_validation :set_lat_lng
before_save :format_search_radius
def email?
(self.notification_method == "2") || (self.notification_method == "4")
end
def sms?
(self.notification_method == "3") || (self.notification_method == "4")
end
private
def set_lat_lng
if address.present? && address_changed?
latlng = Geocoder.coordinates(address)
if latlng.is_a?(Array)
self.latitude, self.longitude = latlng[0], latlng[1]
else
errors.add :base, "Address is invalid"
end
end
end
def format_search_radius
self.search_radius = search_radius.round(2)
end
end
|
module IndexHunter
class Display
class << self
def query(query)
puts "------------------------------------------------\n\n"
puts "Please replace variables with mock data in the following query : \n\n"
puts "if the query is fine, just press Enter \n\n"
puts "------------------------------------------------\n\n"
puts query
puts "------------------------------------------------\n\n"
ask_user_for_input(query)
end
def show_indexes(indexes)
puts "Here are the indexes we suggest : \n"
puts "------------------------------------------------\n"
puts indexes.to_s
puts "------------------------------------------------ \n\n"
puts "You can change them, if you think you can do better :) \n\n"
puts "When you are happy, just press Enter to proceed to benchmark \n\n"
eval(ask_user_for_input(indexes.to_s))
end
def user_info(text)
puts "-------------------------"
puts text
puts "-------------------------"
end
def should_keep_index?
valid = false
while !valid
puts "-----------------------------------------------------\n"
puts "Do you want to keep the Indexes or roll them back ?\n\n"
puts "-----------------------------------------------------\n"
puts "Y to keep, N to rollback\n\n"
keep_index = STDIN.gets.chomp
valid = true if (keep_index == "Y") || (keep_index == "N")
end
keep_index == "Y"
end
private
def ask_user_for_input(prefill)
Readline.pre_input_hook = -> {
Readline.insert_text(prefill)
Readline.redisplay
}
Readline.readline("Please modify if necessary : ")
end
end
end
end
|
# A queue that will not accept data it has already contained in the past
class UniqueQueue
def initialize
@queue = Array.new
@history = Array.new
end
def push_if_not_duplicate(data)
if !@history.include?(data)
@queue.push(data)
@history.push(data)
end
end
def pop_first
f = @queue.first
@queue.delete_at(0)
return f
end
def size
@queue.size
end
def to_s
@queue.inspect
end
def history
@history
end
end
|
class SurveyResultsController < ApplicationController
# GET /survey_results
# GET /survey_results.json
filter_access_to :all
def index
@survey_results = SurveyResult.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @survey_results }
end
end
# GET /survey_results/1
# GET /survey_results/1.json
def show
@survey_result = SurveyResult.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @survey_result }
end
end
# GET /survey_results/new
# GET /survey_results/new.json
def new
@survey_result = SurveyResult.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @survey_result }
end
end
# GET /survey_results/1/edit
def edit
@survey_result = SurveyResult.find(params[:id])
end
# POST /survey_results
# POST /survey_results.json
def create
@survey_result = SurveyResult.new(params[:survey_result])
respond_to do |format|
if @survey_result.save
format.html { redirect_to @survey_result, notice: 'Survey result was successfully created.' }
format.json { render json: @survey_result, status: :created, location: @survey_result }
else
format.html { render action: "new" }
format.json { render json: @survey_result.errors, status: :unprocessable_entity }
end
end
end
# PUT /survey_results/1
# PUT /survey_results/1.json
def update
@survey_result = SurveyResult.find(params[:id])
respond_to do |format|
if @survey_result.update_attributes(params[:survey_result])
format.html { redirect_to @survey_result, notice: 'Survey result was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @survey_result.errors, status: :unprocessable_entity }
end
end
end
# DELETE /survey_results/1
# DELETE /survey_results/1.json
def destroy
@survey_result = SurveyResult.find(params[:id])
@survey_result.destroy
respond_to do |format|
format.html { redirect_to survey_results_url }
format.json { head :no_content }
end
end
end
|
NUM_REGEX = /\A\d+\Z/
ID_REGEX = /\A[a-zA-Z\*\/\+\-\*\/\<\>\=](\w)*\Z/
# This module contains the lexical scanner and
# data structure classes related to scanner: tokens
# and positions.
class EofReached < StandardError
end
class ScanException < StandardError
end
class Token
attr_reader :ttype, :pos, :value
def initialize(ttype, pos, value=nil)
@ttype = ttype
@value = value
@pos = pos
end
end
class Scanner
def initialize(input)
@input = input
@pos = PositionTracker.new
end
# Scan the next token, returns nil when
# EOF is reached
def scan
begin
skip_garbage
get_next_token
rescue EofReached => eof
return nil
end
end
#Gives the next char. The next char is available in the input
#after this (it's pushed back)
def peek
next_c = @input.getc
raise EofReached.new unless next_c
@input.ungetc(next_c)
next_c
end
def nextchar
char = @input.getc
@pos.advance(char)
char
end
def pushback(char)
@input.ungetc(char)
@pos.goback(char)
end
def get_next_token
next_c = peek
case next_c.chr
when "(" then handle_lparen
when ")" then handle_rparen
when '"' then handle_string
when NUM_REGEX then handle_num
when ID_REGEX then handle_id
else raise ScanException.new("Unexpected char " + next_c.chr)
end
end
def handle_lparen
nextchar
Token.new(:lparen, @pos.current_pos)
end
def handle_rparen
nextchar
Token.new(:rparen, @pos.current_pos)
end
def handle_num
numstr = nextchar.chr
tokenpos = @pos.current_pos
while Scanner.matches_number(numstr) do
next_c = nextchar
eof_check(next_c, "number")
numstr += next_c.chr
end
pushback(next_c)
Token.new(:number, tokenpos, Integer(numstr[0..-2]))
end
def handle_id
idstr = nextchar.chr
tokenpos = @pos.current_pos
while Scanner.matches_id(idstr) do
next_c = nextchar
eof_check(next_c, "identifier")
idstr += next_c.chr
end
pushback(next_c)
Token.new(:id, tokenpos, idstr[0..-2].strip)
end
def handle_string
tokenpos = @pos.current_pos
nextchar #skip the start doublequote
next_c = nextchar
eof_check(next_c, "string")
token_val = ""
while next_c != ?" do
token_val += next_c.chr
next_c = nextchar
eof_check(next_c, "string")
end
Token.new(:string, tokenpos, token_val)
end
def eof_check(char, typestr)
raise ScanException.new("Unexpected eof in the middle of a #{typestr}") unless char
end
#Skips comments and whitespaces
def skip_garbage
next_c = peek
while true
if is_whitespace(next_c)
skip_whitespaces
elsif next_c == ?;
skip_comments
else
break
end
next_c = peek
end
end
def skip_whitespaces
next_c = nextchar_eof
while is_whitespace(next_c) do
next_c = nextchar_eof
end
pushback(next_c)
end
def skip_comments
next_c = nextchar_eof
while next_c == ?; or next_c != ?\n do
next_c = nextchar_eof
end
end
def is_whitespace(c)
[?\s, ?\t, ?\r, ?\n].include?(c)
end
#Like nextchar, but throws EofReached when EOF reached
def nextchar_eof
next_c = nextchar
raise EofReached.new unless next_c
next_c
end
def Scanner.matches_number(token)
NUM_REGEX =~ token
end
def Scanner.matches_id(token)
ID_REGEX =~ token
end
end
class Position
attr_reader :line, :column
def initialize(line, column)
@line = line
@column = column
end
def to_s
"#{@line}, #{@column}"
end
end
class PositionTracker
attr_reader :line, :column
def initialize
@line = 1
@column = 0
@prevcolumn = nil
end
def current_pos
Position.new(@line, @column)
end
def advance(char)
if char == ?\n
@line += 1
@prevcolumn = @column
@column = 0
else
@column += 1
end
end
def goback(char)
if char == ?\n
@line -=1
@column = @prevcolumn
else
@column -=1
end
nil
end
end
|
class ArgumentsTheorem < ActiveRecord::Base
belongs_to :theorem
belongs_to :argument
before_create do
unless self.order
self.order = self.argument.theorems.count
end
end
end
|
class ProductsController < ApplicationController
def create
@product = Category.find(params['category_id'])
.products
.build(product_params)
@product.save
redirect_to @product.category
end
def destroy
Product.find(params[:id]).destroy
redirect_to Category.find(params[:category_id])
end
def product_params
params.require('product').permit(%I[name price])
end
end
|
board = [
['1', 'x', '3'],
['o', '5', 'o'],
['7', '8', 'o']
]
winner = nil
def print_board(board)
puts
puts ' ' + board[0][0] + ' | ' + board[0][1] + ' | ' + board[0][2]
puts '-----------'
puts ' ' + board[1][0] + ' | ' + board[1][1] + ' | ' + board[1][2]
puts '-----------'
puts ' ' + board[2][0] + ' | ' + board[2][1] + ' | ' + board[2][2]
puts
end
def player_move
puts "Enter your symbol (x or o) or q to quit"
sym = gets.chomp
puts "Enter the number of the square (1-9)"
squ = gets.chomp
end
def check_for_winner(board)
# win within a row
board[0].uniq.length == 1 ||
board[1].uniq.length == 1 ||
board[2].uniq.length == 1 ||
# win within a column
board[0][0] == board [1][0] && board[0][0] == board[2][0] ||
board[0][1] == board [1][1] && board[0][1] == board[2][1] ||
board[0][2] == board [1][2] && board[0][2] == board[2][2] ||
# win on a diagonal
board[0][0] == board [1][1] && board[0][0] == board[2][2] ||
board[2][0] == board [1][1] && board[2][0] == board[0][2]
end
until winner
print_board(board)
player_move
winner = check_for_winner(board)
break if winner
end
|
class CreateUsers < ActiveRecord::Migration[6.0]
def change
create_table :users do |t|
t.string :full_name, null: false, limit: 200
t.string :document, null: false, limit: 11
t.string :address, null: false, limit: 200
t.date :birthday, null: false
t.string :gender, null: false, limit: 1
t.string :password, null: false, limit: 8
t.string :token, null: false, limit: 100
end
add_index :users, :document, unique: true
add_index :users, :token, unique: true
end
end
|
# frozen_string_literal: true
# == Schema Information
#
# Table name: products
#
# id :bigint not null, primary key
# maker :string not null
# name :string not null
# price :integer not null
# created_at :datetime not null
# updated_at :datetime not null
# slot_id :bigint
#
# Indexes
#
# index_products_on_slot_id (slot_id)
#
# Foreign Keys
#
# fk_rails_... (slot_id => slots.id)
#
class Product < ApplicationRecord
belongs_to :slot
has_many :purchases
end
|
require 'spec_helper'
describe 'User images api' do
let(:user) { FactoryGirl.create :user }
let(:file) { fixture_file_upload('public/uploads/test.jpg', 'image/jpg') }
let(:parameters) { params_hash }
it 'get new image info' do
post '/api/user_images.json', parameters
expect(response).to have_http_status :created
expect(response.content_type).to eq 'application/json'
# expect(json['status']).to eq 201
image = UserImage.last
image_parameters = { user_id: user.id, image_id: image.id }
test_image_like 1, :created, image_parameters
test_image_like 0, :no_content, image_parameters
end
it 'fail validation' do
parameters[:user_image][:image] = ''
post '/api/user_images', parameters
expect(response).to have_http_status :unprocessable_entity
expect(response.content_type).to eq 'application/json'
# expect(json['status']).to eq 422
end
def test_image_like(val, message, options = {})
post '/api/update_like', options
expect(ImagesLike.count).to eq val
expect(response).to have_http_status message
end
def params_hash
{
user_image: {
image: file,
description: 'test',
user_id: user.id,
coordinates: [0, 0]
}
}
end
end
|
json.array!(@medications) do |medication|
json.extract! medication, :id, :name, :dose, :frequency
json.url medication_url(medication, format: :json)
end
|
class Goal < ActiveRecord::Base
belongs_to :user
TYPES = [
['be', 'que quiero ser'],
['do', 'que quiero hacer'],
['have', 'que quiero tener'],
['travel', 'a donde quiero viajar'],
['share', 'que quiero compartir'],
['worry_not', 'de que no me quiero preocupar'],
]
validates :goal_type, inclusion: {in: TYPES.map{ |pairs| pairs[0] } }
scope :by_user, -> (user) { where(user_id: user.id) }
scope :type_be, -> { where(goal_type: 'be') }
scope :type_do, -> { where(goal_type: 'do') }
scope :type_have, -> { where(goal_type: 'have') }
scope :type_travel, -> { where(goal_type: 'travel') }
scope :type_share, -> { where(goal_type: 'share') }
scope :type_worry_not, -> { where(goal_type: 'worry_not') }
end
|
class AddColumnsToUsers < ActiveRecord::Migration[5.0]
def change
add_column :users, :phone, :string
add_column :users, :points, :int, default: 0
add_column :users, :address, :string
add_column :users, :visit_count, :int, default: 0
end
end
|
require 'rails_helper'
# will need to be updated for AJAX
describe "a logged in authorized youtube user" do
context "viewing a user video" do
xit "can dislike the video", :vcr do
user = stub_login_user
YoutubeUser.create(user_id: user.id, token: ENV['token'], account_number: ENV['account_number'])
other_user = User.create(email: "wtag@uoregon.edu", first_name: "willie", last_name: "taggart", username: "dosomething", password: "pass")
piece = other_user.pieces.create(composer_first: "jacques", composer_last: "ibert", title: "concertino da camera", yt_link: "https://www.youtube.com/watch?v=g3c025V9zuM", yt_uid: "g3c025V9zuM")
visit user_piece_path(other_user, piece)
find(:xpath, "//a[@href='/youtube/dislikes?id=g3c025V9zuM&piece=#{piece.id}&vid_owner=#{other_user.id}']").click
expect(page).to have_content("Disliked!")
expect(current_path).to eq(user_piece_path(other_user, piece))
end
end
end
|
class Post < ActiveRecord::Base
# attr_accessible :title, :body
belongs_to :user
has_many :comments
has_many :reposts
has_many :hash_tags
has_many :admires
has_one :media
mount_uploader :avatar, DocumentUploader
process_in_background :avatar
validates_length_of :body, maximum: 170
after_create :process_hashtags
after_create :process_media
def process_hashtags
hashtag_regex = /\B#\w\w+/
text_hashtags = self.body.to_s.scan(hashtag_regex)
text_hashtags.each do |tag|
hashtag = HashTag.where(name: tag)
if !hashtag.empty?
hashtag = hashtag.first
hashtag.update_attributes(count: hashtag.count+=1)
else
HashTag.create name: tag, post_id: self.id, count: 1
end
end
end
def process_media
media_regex = /(?:.be\/|\/watch\?v=|\/(?=p\/))([\w\/\-]+)/
media_urls = self.body.to_s.scan(media_regex).flatten
if !media_urls.blank?
media_urls.each do |youtube|
self.media = Media.create(name: "YouTube", url: "//www.youtube.com/embed/#{youtube}")
break
end
end
media1 = /(?:http:\/\/)?(?:www\.)?(?:youporn\.com)\/(?:watch)?(.+)/
media_urls = self.body.to_s.scan(media1).flatten
if !media_urls.blank?
media_urls.each do |youtube|
self.media = Media.create(name: "YouPorn", url: "//www.youporn.com/embed#{youtube}")
break
end
end
media2 = /(?:http:\/\/)?(?:www\.)?(?:redtube\.com)\/(?:watch)?(.+)/
media_urls = self.body.to_s.scan(media2).flatten
if !media_urls.blank?
media_urls.each do |youtube|
self.media = Media.create(name: "RedTube", url: "//embed.redtube.com/player/?id=#{youtube}&style=redtube")
break
end
end
media3 = /(?:http:\/\/)?(?:www\.)?(?:pornhub\.com)\/(?:watch)?(.+)/
media_urls = self.body.to_s.scan(media3).flatten
if !media_urls.blank?
media_urls.each do |youtube|
youtube= youtube.gsub('view_video.php?viewkey=','')
self.media = Media.create(name: "PornHub", url: "//www.pornhub.com/embed/#{youtube}")
break
end
end
end
end
|
class AddIndexToClimbs < ActiveRecord::Migration
def change
add_index :climbs, :name
add_index :climbs, :type
add_index :climbs, :rating
add_index :climbs, :integer_rating
add_index :climbs, :height
add_index :climbs, :pitches
end
end
|
class FixerApiService
BASE_URL = Settings[:fixer_api][:base_url]
ACCESS_KEY = Settings[:fixer_api][:access_key]
# @raise [JSON::ParserError, Faraday::ConnectionFailed]
# @return [Hash]
def get_currency!
raw_body = Faraday.new(url: BASE_URL, params: {access_key: ACCESS_KEY})
.get('/api/latest').body
body = JSON.parse raw_body
body[:warning] = "Unfortunately, we cannot provide rates for custom currency due to the service's free plan"
body.except('success', 'timestamp')
end
end |
class User < ActiveRecord::Base
has_many :groups, :through => :memberships
has_many :memberships
has_many :achievements, :through => :user_achievements
has_many :user_achievements
belongs_to :gem, :class_name => "Achievement"
has_one :feed, :as => :source
has_many :feed_item_model_refs, :as => :referenced_model, :class_name => "FeedItem"
has_many :feed_item_user_refs, :class_name => "FeedItem"
has_many :achievement_creator_refs, :class_name => "Achievement"
has_many :friendships
has_many :friends, :through => :friendships
has_many :inverse_friendships, :class_name => "Friendship", :foreign_key => "friend_id"
has_many :inverse_friends, :through => :inverse_friendships, :source => :user
has_many :banned_by_refs, :class_name => "Membership"
has_many :presenter_refs, :class_name => "UserAchievement"
ROLES = %w[super_admin]
after_create :create_feed_for_user
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable, :lockable and :timeoutable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# paperclip attribute ( for file associations / uploads )
has_attached_file :avatar, :styles => { :thumb => "50x50#", :original => "300x300>"},
:default_url => 'no-image-:style.png',
:storage => :s3,
:s3_credentials => "#{Rails.root.to_s}/config/s3.yml",
:path => "Users/:id/Avatar/:style.:extension"
attr_accessible :email, :password, :password_confirmation, :remember_me, :avatar, :name
email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates( :email, :presence => true,
:format => { :with => email_regex },
:uniqueness => { :case_sensitive => false })
validates( :name, :presence => true )
# paperclip upload validations
validates_attachment_size :avatar, :less_than => 5.megabytes, :message => "File must be smaller than 5MB"
validates_attachment_content_type :avatar, :content_type => ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'],
:message => "Can only upload jpeg, jpg, png and gif file types"
def make_super_admin!
self.role = User::ROLES[0]
self.save
end
def revoke_super_admin!
self.role = nil
self.save
end
def create_feed_for_user
self.create_feed
end
def self.search(search)
if search
find(:all, :conditions => ['name LIKE ?', "%#{search}%"])
else
find(:all)
end
end
def has_friend?(friend)
@friendship = Friendship.find_by_user_id_and_friend_id(self.id, friend.id)
if @friendship.nil?
@friendship = Friendship.find_by_user_id_and_friend_id(friend.id, self.id)
if @friendship.nil?
return nil
else
return @friendship
end
else
return @friendship
end
end
def request_achievement( achievement )
if( achievement != nil && self.user_achievements.exists?( :achievement_id => achievement.id ) == false )
@user_achievement = self.user_achievements.create( :status => UserAchievement::STATES[:Pending], :achievement_id => achievement.id )
else
return false
end
end
def has_pending_achievement?( achievement )
self.user_achievements.exists?( :achievement_id => achievement.id, :status => UserAchievement::STATES[:Pending] )
end
def has_earned_achievement?( achievement )
self.user_achievements.exists?( :achievement_id => achievement.id, :status => UserAchievement::STATES[:Awarded] )
end
def has_denied_achievement?( achievement )
self.user_achievements.exists?( :achievement_id => achievement.id, :status => UserAchievement::STATES[:Denied] )
end
# def create_gem
# self.create_gemslot
#end
end
|
class MessagesController < ApplicationController
def create
result = Messages::Create.call(message_params: message_params)
respond_to do |format|
format.js { NewMessageJob.perform_later(result.message) }
format.html { redirect_to_room_path }
end
end
private
def message_params
params.require(:message).permit(:content).merge(
user_id: current_user.id,
room_id: current_room.id
)
end
def current_room
@current_room ||= find_room
end
def find_room
ctx = Rooms::FindBySecretId.call(room_secret_id: params[:room_secret_id])
ctx.room
end
def redirect_to_room_path
redirect_to room_path(
user_secret_id: current_user.secret_id,
room_secret_id: current_room.secret_id
)
end
end
|
# == Schema Information
#
# Table name: restaurants
#
# id :integer not null, primary key
# name :string
# cuisine_id :integer
# accept_10_bis :boolean
# max_delivery_time :integer
# created_at :datetime not null
# updated_at :datetime not null
# address :string
# lon :float
# lat :float
#
FactoryGirl.define do
factory :restaurant do
association :cuisine
name 'Pam-pam'
address 'Abn Gabirol 30 TLV'
max_delivery_time 5
end
trait :aroma do
name 'Aroma'
address 'Kaplan 5 TLV'
max_delivery_time 4
end
trait :oshi_oshi do
name 'Oshi-Oshi'
address 'Dizingof 17 TLV'
max_delivery_time 30
end
end
|
class User < ActiveRecord::Base
has_many :posts
validates :username, :presence => { :message => "아이디를 반드시 입력하셔야 합니다."}
validates :username, :presence => { :message => "이미 존재하는 아이디 입니다.", :case_sensitive => false}
validates :password, :length => { :minimum => 6, :too_short => "최소 6자 이상으로 만들어주세요."}
end
|
class BikeModels < Netzke::Basepack::Grid
def configure(c)
super
c.model = "BikeModel"
c.title = "Models"
c.force_fit = true
c.data_store = {auto_load: false}
c.scope = lambda { |rel| rel.where(:bike_brand_id => session[:selected_bike_brand_id]);}
c.strong_default_attrs = {
:bike_brand_id => session[:selected_bike_brand_id]
}
c.columns = [
{ :name => :model }
]
c.prohibit_update = true if cannot? :update, BikeModel
c.prohibit_create = true if cannot? :create, BikeModel
c.prohibit_delete = true if cannot? :delete, BikeModel
end
#override with nil to remove actions
def default_bbar
bbar = [ :search ]
bbar.concat [ :apply ] if can? :update, BikeModel
bbar.concat [ :add_in_form ] if can? :create, BikeModel
bbar
end
end
|
class RandomUploader < CarrierWave::Uploader::Base
def filename
"#{secure_token(10)}.#{File.extname(original_filename)}" if original_filename.present?
end
protected
def secure_token(length=16)
var = :"@#{mounted_as}_secure_token"
model.instance_variable_get(var) or model.instance_variable_set(var, SecureRandom.hex(length/2))
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.