text stringlengths 10 2.61M |
|---|
class Api::V1::PartyDataController < Api::V1::BaseController
before_action :set_collection
def data
json = {
attend: @collection.post_in.value,
success: @collection.success.value,
fail: @collection.post_in.value - @collection.success.value,
leftTicket: @collection.maximum - @collection.admissions.all.size,
rate: (@collection.success.value.to_f * 100.00 / @collection.post_in.value.to_f).round(2),
status: Party.status,
start_at: Party.start_at_humanize
}
render json: json
end
def list
render json: @collection.name_list
end
def change_status
(Party.can_attend?) ? (Party.fin) : (Party.start)
render json: {status: 200}
end
def change_rate
Party.rate = params[:newRate]
render json: {status: 200}
end
def status
render json: !!(Party.can_attend?)
end
private
def set_collection
@collection = Collection.find Party.collection_id
end
end |
class PacketSpam
attr_accessor :enabled, :callAfter, :callBefore, :dependencies
def initialize(mother)
@parent = mother
@enabled = true
@callAfter = false
@callBefore = true
@dependencies = {
'author' => 'Lynx',
'version' => '1.0',
'hook_type' => 'game'
}
@packets = [
'u#sp', 's#upc', 's#uph', 's#upf', 's#upn',
's#upb', 's#upa', 's#upe', 's#upp', 's#upl',
'l#ms', 'b#br', 'j#jr', 'u#se', 'u#sa', 'u#sg',
'sma', 'u#sb', 'u#gp', 'u#ss', 'u#sq',
'u#sj', 'u#sl', 'u#sg', 'm#sm', 'u#sf'
]
end
def handleSendJoke(data, client)
self.checkPacketSpam(client, 'u#sj')
end
def handleJoinRoom(data, client)
self.checkPacketSpam(client, 'j#jr')
end
def handleUserHeartbeat(data, client)
self.checkPacketSpam(client, 'u#h')
end
def handleSendPosition(data, client)
self.checkPacketSpam(client, 'u#sp')
end
def handleSendFrame(data, client)
self.checkPacketSpam(client, 'u#sf')
end
def handleSendEmote(data, client)
self.checkPacketSpam(client, 'u#se')
end
def handleSendQuickMessage(data, client)
self.checkPacketSpam(client, 'u#sq')
end
def handleSendAction(data, client)
self.checkPacketSpam(client, 'u#sa')
end
def handleSendSafeMessage(data, client)
self.checkPacketSpam(client, 'u#ss')
end
def handleSendGuideMessage(data, client)
self.checkPacketSpam(client, 'u#sg')
end
def handleSendMascotMessage(data, client)
self.checkPacketSpam(client, 'u#sma')
end
def handleUpdatePlayerColor(data, client)
self.checkPacketSpam(client, 's#upc')
end
def handleUpdatePlayerHead(data, client)
self.checkPacketSpam(client, 's#uph')
end
def handleUpdatePlayerFace(data, client)
self.checkPacketSpam(client, 's#upf')
end
def handleUpdatePlayerNeck(data, client)
self.checkPacketSpam(client, 's#upn')
end
def handleUpdatePlayerBody(data, client)
self.checkPacketSpam(client, 's#upb')
end
def handleUpdatePlayerHand(data, client)
self.checkPacketSpam(client, 's#upa')
end
def handleUpdatePlayerFeet(data, client)
self.checkPacketSpam(client, 's#upe')
end
def handleUpdatePlayerPhoto(data, client)
self.checkPacketSpam(client, 's#upp')
end
def handleUpdatePlayerPin(data, client)
self.checkPacketSpam(client, 's#upl')
end
def handleSendMessage(data, client)
self.checkPacketSpam(client, 'm#sm')
end
def handleMailSend(data, client)
self.checkPacketSpam(client, 'l#ms')
end
def handleBuddyRequest(data, client)
self.checkPacketSpam(client, 'b#br')
end
def handleGetPlayer(data, client)
self.checkPacketSpam(client, 'u#gp')
end
def checkPacketSpam(client, packetType)
if @packets.include?(packetType) != false
if client.spamFilter.has_key?(packetType) != true
client.spamFilter[packetType] = 0
end
currTime = Time.now
timeStamp = currTime
if client.lastPacket.has_key?(packetType) != true
client.lastPacket[packetType] = timeStamp
end
timeDiff = (TimeDifference.between(Time.parse(client.lastPacket[packetType].to_s), Time.now).in_seconds).round
if timeDiff < 6
if client.spamFilter[packetType] < 10
client.spamFilter[packetType] += 1
end
if client.spamFilter[packetType] >= 10
return @parent.sock.handleRemoveClient(client.sock)
end
else
client.spamFilter[packetType] = 1
end
client.lastPacket[packetType] = timeStamp
end
end
end
|
require_relative 'container'
class LoginPage < Container
URL = "https://www.phptravels.net/login"
def open
@browser.goto URL
self
end
def login_as(user, pass)
user_field.set user
password_field.set pass
login_button.click
next_page = BookingPage.new(@browser)
Watir::Wait.until { next_page.loaded? }
next_page
end
private
def user_field
@browser.text_field(type: 'email')
end
def password_field
@browser.text_field(type: 'password')
end
def login_button
@browser.button(type: 'submit')
end
end |
class Employee::LeaveApplicationsController < Employee::BaseController
def index
@leave_applications = @user.leave_applications.page(params[:page])
end
def new
@leave_application = @user.leave_applications.build
end
end |
# Portions Originally Copyright (c) 2008-2011 Brian Lopez - http://github.com/brianmario
# See MIT-LICENSE
require "rubygems" unless defined?(Gem)
require "benchmark" unless defined?(Benchmark)
require "stringio" unless defined?(StringIO)
if !defined?(RUBY_ENGINE) || RUBY_ENGINE !~ /jruby/
begin
require "yajl"
rescue LoadError
puts "INFO: yajl-ruby not installed"
end
else
puts "INFO: skipping yajl-ruby on jruby"
end
require_relative "../../ffi_yajl"
begin
require "json" unless defined?(JSON)
rescue LoadError
puts "INFO: json gem not installed"
end
begin
require "oj"
rescue LoadError
puts "INFO: oj gem not installed"
end
module FFI_Yajl
class Benchmark
class Encode
def run
# filename = ARGV[0] || 'benchmark/subjects/ohai.json'
filename = File.expand_path(File.join(File.dirname(__FILE__), "subjects", "ohai.json"))
hash = File.open(filename, "rb") { |f| FFI_Yajl::Parser.parse(f.read) }
times = ARGV[1] ? ARGV[1].to_i : 1000
puts "Starting benchmark encoding #{filename} #{times} times\n\n"
::Benchmark.bmbm do |x|
x.report("FFI_Yajl::Encoder.encode (to a String)") do
times.times { FFI_Yajl::Encoder.encode(hash) }
end
ffi_string_encoder = FFI_Yajl::Encoder.new
x.report("FFI_Yajl::Encoder#encode (to a String)") do
times.times { ffi_string_encoder.encode(hash) }
end
if defined?(Oj)
x.report("Oj.dump (to a String)") do
times.times { Oj.dump(hash) }
end
end
if defined?(Yajl::Encoder)
x.report("Yajl::Encoder.encode (to a String)") do
times.times { Yajl::Encoder.encode(hash) }
end
io_encoder = Yajl::Encoder.new
x.report("Yajl::Encoder#encode (to an IO)") do
times.times { io_encoder.encode(hash, StringIO.new) }
end
string_encoder = Yajl::Encoder.new
x.report("Yajl::Encoder#encode (to a String)") do
times.times { string_encoder.encode(hash) }
end
end
if defined?(JSON)
x.report("JSON.generate") do
times.times { JSON.generate(hash) }
end
x.report("JSON.fast_generate") do
times.times { JSON.fast_generate(hash) }
end
end
end
end
end
end
end
|
# desc "Explaining what the task does"
# task :momentum_cms do
# # Task goes here
# end
namespace :momentum_cms do
namespace :fixture do
desc 'Import a site via fixtures'
task :import => :environment do |t|
source = ENV['SOURCE']
site = ENV['SITE']
if source.blank?
puts "SOURCE expected, but not provided, run `#{t.name} SOURCE=demo-site`"
puts "Where:"
puts "\t SOURCE is a fixture folder under #{MomentumCms.configuration.site_fixtures_path}"
exit 1
end
MomentumCms::Fixture::Importer.new({ source: source, site: site }).import!
end
desc 'Export a site to fixtures'
task :export => :environment do |t|
site = ENV['SITE']
target = ENV['TARGET']
if target.blank? || site.blank?
puts "SITE and TARGET expected, but not provided, run `#{t.name} TARGET=demo-site SITE=demo-site`"
puts "Where:"
puts "\t TARGET is a fixture folder under #{MomentumCms.configuration.site_fixtures_path}"
puts "\t SITE is a site with in the application, identified by the unique identifier"
exit 1
end
MomentumCms::Fixture::Exporter.new({ target: target, site: site }).export!
end
end
namespace :development do
desc 'Import an example site'
task :import_example_site => :environment do
@site = MomentumCms::Site.where(label: 'Example Site', host: 'localhost', identifier: 'example-a').first_or_create!
MomentumCms::Fixture::Template::Importer.new('example-a', @site).import!
MomentumCms::Fixture::Page::Importer.new('example-a', @site).import!
MomentumCms::Page.find_each do |page|
content = MomentumCms::Content.where(
page: page,
label: "#{page.label}-#{I18n.locale}",
content: "Lorem Ipsum, this is the content page for #{page.label}-#{I18n.locale}"
)
content = if content.first.nil?
content.create!
else
content.first!
end
[:en, :fr, :es].each do |locale|
I18n.locale = locale
content.label = "#{page.label}-#{I18n.locale}"
content.save!
end
MomentumCms::Page.order(:id).to_a.each do |p|
p.save
end
end
end
end
end
|
module Ann
module Helpers
# A simple extension to ActionView's form builder that makes easy display
# error messages for each attribute in the form.
#
# Usage:
# <%= ann_form_for record, class: 'form', url: url_for(record) do |f| %>
# <%= f.label :name %>
# <%= f.text_field :name %>
# <%= f.error_message :name %>
# <% end %>
class FormBuilder < ActionView::Helpers::FormBuilder
def error_message(attribute, options = {})
return if object.errors.empty?
@template.content_tag(:p, object.errors.full_messages_for(attribute).first, options)
end
end
end
end
|
class TruckCartConnection < ActiveRecord::Base
belongs_to :cart
belongs_to :truck
scope :finished, -> { where(status: "finished") }
end
|
class House < ApplicationRecord
has_many :trains
accepts_nested_attributes_for :trains
end
|
# encoding: UTF-8
# Copyright 2012 Twitter, Inc
# http://www.apache.org/licenses/LICENSE-2.0
module TwitterCldr
module Segmentation
class RuleSet
class << self
def create(locale, boundary_type, options = {})
new(locale, StateMachine.instance(boundary_type, locale), options)
end
end
attr_reader :locale, :state_machine
attr_accessor :use_uli_exceptions
alias_method :use_uli_exceptions?, :use_uli_exceptions
def initialize(locale, state_machine, options)
@locale = locale
@state_machine = state_machine
@use_uli_exceptions = options.fetch(
:use_uli_exceptions, false
)
end
def each_boundary(cursor, stop = cursor.length)
return to_enum(__method__, cursor, stop) unless block_given?
until cursor.position >= stop || cursor.eos?
state_machine.handle_next(cursor)
yield cursor.position if suppressions.should_break?(cursor)
end
end
def boundary_type
state_machine.boundary_type
end
private
def suppressions
@suppressions ||= if use_uli_exceptions?
Suppressions.instance(boundary_type, locale)
else
NullSuppressions.instance
end
end
end
end
end
|
class Survey < ActiveRecord::Base
extend BaseModel
belongs_to :user
has_many :questions
accepts_nested_attributes_for :questions, :allow_destroy => true
### Constants
HIDDEN_COLUMNS = ["created_at", "updated_at", "last_update", "status", "nation_id"]
def save_responses(params)
nation_id = params["nation_id"]
survey_id = params["id"]
survey = Survey.find(survey_id)
params.each do |key, value|
if survey.questions.where(:name => key).count > 0
question_id = survey.questions.where(:name => key).first.id
Response.new(:nation_id => nation_id, :answer => value, :question_id => question_id).save
end
end
end
def responses
Hash[respondents.collect { |id| [id, answers(id) ] } ]
end
def answers(nation_id)
questions.collect { |q| q.last_response(nation_id) } <<
questions.last.responses.nation(nation_id).first.created_at
end
def respondents
if questions.nil? or questions.empty?
[]
else
questions.first.responses.collect { |response| response.nation.nation_id }.uniq
end
end
def count_responses
respondents.length
end
def respondent(nation_id)
Nation.find(nation_id)
end
def self.survey_columns
Nation.column_names.reject { |column| HIDDEN_COLUMNS.include?(column) }
end
end |
require 'spec_helper'
describe Types::Element do
include_context :types
before do
element.extend(Types::Element)
element_with_hooks.extend(Types::Element)
end
describe 'text' do
it 'can be read' do
element.browser_element.should_receive(:text).and_return('text')
element.text.should == 'text'
end
it 'can be read and hooks are called' do
element_with_hooks.browser_element.should_receive(:text).and_return('text')
element_with_hooks.text.should == 'text'
hooks_called.should == [:before, :after]
end
end
describe 'has_text?' do
it 'can check if text is present' do
element.browser_element.should_receive(:has_text?).with('text').and_return true
element.has_text?('text').should == true
end
it 'can check if text is present and call hooks' do
element_with_hooks.browser_element.should_receive(:has_text?).with('text').and_return true
element_with_hooks.has_text?('text').should == true
hooks_called.should == [:before, :after]
end
end
describe 'css_class' do
it 'can check if css class is present' do
element.browser_element.should_receive(:[]).with(:class).and_return 'classes'
element.css_class.should == 'classes'
end
it 'can check if css class is present and call hooks' do
element_with_hooks.browser_element.should_receive(:[]).with(:class).and_return 'classes'
element_with_hooks.css_class.should == 'classes'
hooks_called.should == [:before, :after]
end
end
describe 'attribute' do
it 'can retrieve attribute value' do
element.browser_element.should_receive(:[]).with(:href).and_return 'http://'
element.attribute(:href).should == 'http://'
end
it 'can retrieve attribute value and call hooks' do
element_with_hooks.browser_element.should_receive(:[]).with(:href).and_return 'http://'
element_with_hooks.attribute(:href).should == 'http://'
hooks_called.should == [:before, :after]
end
end
end |
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure("2") do |config|
config.vm.define "app" do |app|
app.vm.provision "shell", path: "provision-celery.sh"
app.vm.box = "ubuntu/xenial64"
app.vm.network "private_network", ip: "192.168.144.10", virtualbox__intnet: true
app.vm.hostname = "app"
end
config.vm.define "w1" do |box|
box.vm.provision "shell", path: "provision-celery.sh"
box.vm.box = "ubuntu/xenial64"
box.vm.network "private_network", ip: "192.168.144.21", virtualbox__intnet: true
box.vm.hostname = "w1"
end
config.vm.define "w2" do |box|
box.vm.provision "shell", path: "provision-celery.sh"
box.vm.box = "ubuntu/xenial64"
box.vm.network "private_network", ip: "192.168.144.22", virtualbox__intnet: true
box.vm.hostname = "w2"
end
config.vm.define "w3" do |box|
box.vm.provision "shell", path: "provision-celery.sh"
box.vm.box = "ubuntu/xenial64"
box.vm.network "private_network", ip: "192.168.144.23", virtualbox__intnet: true
box.vm.hostname = "w3"
end
config.vm.define "littlebunny" do |box|
config.vm.provider "docker" do |d|
#d.image = "rabbitmq"
d.build_dir = "docker-wabbit"
end
end
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ :name => 'Chicago' }, { :name => 'Copenhagen' }])
# Mayor.create(:name => 'Daley', :city => cities.first)
@logger = Logger.new $stderr
ActiveRecord::Base.logger = @logger
ActiveRecord::Base.colorize_logging = false
def process_volume(source, vol)
@logger.info "processing volume #{vol}"
count = 0
volume = Volume.where(:volume => vol).first
if (volume.nil?) then
volume = Volume.create!(:volume => vol)
end
dir = Dir.new(source + "/" + vol)
earliest_date = nil
dir.entries.each {|number|
if File.directory?(source + "/" + vol + "/" + number) and number != "." and number != ".."
count = count + 1
published_on = process_number(source, volume, number)
@logger.info "pub date #{published_on}"
end
}
end
def process_number(source, volume, number)
@logger.info "processing number #{number} of volume #{volume.volume}(#{volume.id})"
dir = Dir.new(source + "/" + volume.volume.to_s + "/" + number)
metadata = YAML::load(File.open("#{dir.path}/metadata.yaml"))
@logger.info "Metadata: #{metadata.to_s}"
issue = Issue.create(:volume => volume, :number => number, :page_count => metadata["page_count"], :published_on => metadata["published_on"])
issue.save!
dir.entries.each {|page_number|
page_dir = source + "/" + volume.volume.to_s + "/" + number + "/" + page_number
if File.directory?(page_dir) and page_number != "." and page_number != ".." and page_number != "work"
@logger.info "processing page #{page_number}"
page_text = ""
text_file = page_dir + "/full.txt"
if File.exists?(text_file)
IO.readlines(text_file, '\n').each {|line|
page_text += line
@logger.info "page text: " + page_text
}
end
page = Page.create(:issue => issue, :page_number => page_number, :text => page_text)
page.save!
@logger.info "page stored #{page.to_s}"
Dir.new(page_dir).entries.each {|file|
if file.end_with?(".png")
file_name = file[0..(file.index('.')-1)]
@logger.info "file_name: #{file_name}"
image = ImageRef.create(:page => page, :path => "volumes/#{volume.volume.to_s}/#{number}/#{page_number}/#{file}", :size => file_name)
image.save!
@logger.info "image stored #{image.to_s}"
end
}
end
}
return metadata["published_on"]
end
if ENV["source"] then
source = Dir.new(ENV["source"])
else
source = Dir.new("$HOME/volumes")
end
@logger.info "consuming ACs from #{source.path}"
source.entries.each {|dir|
if File.directory?(source.path + "/" + dir) and dir != "." and dir != ".." and dir != "work"
process_volume(source.path, dir)
end
}
|
module DeviseApiAuth
module TokenUtils
extend self
require 'openssl'
def generate_user_token(string, digester: Digest::SHA2)
return if !string.is_a?(String) || string.blank?
digester.hexdigest(string+DeviseApiAuth::Config.options[:user_salt])
end
class SecureCredentials
def initialize(headers: nil, params: nil)
@headers = headers
@params = params
end
def get_header_credentials
decrypt(encrypted_header_credentials, iv: header_iv).symbolize_keys
end
def get_param_credentials
decrypt(encrypted_param_credentials, iv: params_iv).symbolize_keys
end
def header_iv
@headers&.fetch(config_options[:header_iv],nil)
end
def params_iv
@params&.fetch(config_options[:param_iv],nil)
end
def encrypted_header_credentials
@headers&.fetch(config_options[:header_credentials],nil)
end
def encrypted_param_credentials
@params&.fetch(config_options[:param_credentials],nil)
end
protected
def decrypt(encrypted, iv:)
decrypted = DeviseApiAuth::TokenUtils::Decryptor.new(iv).decrypt(encrypted)
JSON.parse decrypted
rescue StandardError => e
{}
end
def config_options
DeviseApiAuth::Config.options
end
end
private
class Crypt
# Subclasses must provide block to initializer to set encrypt or decrypt on the cipher
# Accepts iv as hex string
def initialize(iv)
@failed = false
@cipher = OpenSSL::Cipher::Cipher.new('aes-256-cbc')
yield @cipher # setting encrypt or decrypt to the cipher
@cipher.key = DeviseApiAuth::Config.options[:encryption_key]
@cipher.iv = [iv].pack('H*')
rescue StandardError => e
@failed = true
end
private
def crypt(to_crypt)
return if @failed
crypted = @cipher.update(to_crypt)
crypted << @cipher.final
rescue StandardError => e
nil
end
end
public
class Decryptor < Crypt
def initialize(iv)
super {|cipher| cipher.decrypt}
end
# Accepts an encrypted hex string and returns plain text
def decrypt(encrypted)
return if encrypted.blank?
crypt([encrypted].pack('H*'))
end
end
class Encryptor < Crypt
def initialize(iv)
super{|cipher| cipher.encrypt}
end
# Accepts string and returns encrypted hex string
def encrypt(encrypted)
crypt(encrypted)&.unpack('H*')&.first
end
end
class SimpleTokenMatcher
def initialize(strings: nil, token: nil, digester: nil)
@digester = digester || Digest::SHA2
@string = strings
if @string.is_a?(Array)
@string = @string.include?(nil) ? nil : strings.join
end
@token = token
@_token = token_for @string
end
def match!
valid? && @_token == @token
end
def token_for(string)
return unless string.is_a?(String) && !string.blank?
@digester.hexdigest(string)
end
def valid?
!@_token.blank?
end
end
class DateTokenMatcher < SimpleTokenMatcher
# adds date and options hash that contains a verify_date bool and cutoff which is the amount of seconds to allow the date to be within
def initialize(strings: nil, token: nil, digester: nil, date: nil, **options)
@options = {verify_date: true, cutoff: 60 * 10}.merge(options)
self.date = date
super(strings: strings, token: token, digester: digester)
end
def match!
return false if verify_date? && !verify_date!
super
end
def valid?
return super if !verify_date?
verify_date! && super
end
private
def date=(d)
if d.is_a? String
@date = DateTime.parse(d)
elsif d.is_a? DateTime
@date = d
end
rescue ArgumentError
@date = nil
end
def verify_date!
return false if @date.nil?
a = cutoff.seconds.ago.to_datetime
b = cutoff.seconds.since.to_datetime
@date.between?(a,b)
end
def verify_date?
!!(@options[:verify_date])
end
def cutoff
[@options[:cutoff].to_i, 30].max
end
end
end
end |
class Social < ActiveRecord::Base
belongs_to :user
validates :facebook_link, format: { with: /facebook.com\//}
validates :linkedin_link, format: { with: /linkedin.com\//}
validates :youtube_link, format: { with: /youtube.com\//}
validates :instagram_link, format: { with: /instagram.com\//}
end
|
class User
attr_reader :id, :name
def initialize(id:, name:)
@id = id
@name = name
end
def to_json
return {
"id" => @id,
"name" => @name,
}
end
end
|
require "test_helper"
describe Rugged::Config do
before do
@path = temp_repo('testrepo.git')
@repo = Rugged::Repository.new(@path)
end
after do
destroy_temp_repo(@path)
end
it "can read the config file from repo" do
config = @repo.config
assert_equal 'false', config['core.bare']
assert_nil config['not.exist']
end
it "can read the config file from path" do
config = Rugged::Config.new(File.join(@repo.path, 'config'))
assert_equal 'false', config['core.bare']
end
it "can read the global config file" do
config = Rugged::Config.global
assert config['user.name'] != nil
assert_nil config['core.bare']
end
it "can write config values" do
config = @repo.config
config['custom.value'] = 'my value'
config2 = @repo.config
assert_equal 'my value', config2['custom.value']
content = File.read(File.join(@repo.path, 'config'))
assert_match(/value = my value/, content)
end
it "can delete config values" do
config = @repo.config
config.delete('core.bare')
config2 = @repo.config
assert_nil config2.get('core.bare')
end
end
|
module CronSpec
##
# Base class for the definition of CronSpecificationFactory classes.
#
class CronSpecificationFactory
WildcardPattern = /\A\*\z/
SingleValuePattern = /\A(\d+)\z/
RangePattern = /\A(\d+)-(\d+)\z/
StepPattern = /\A\*\/(\d+)\z/
##
# Constructs a new CronSpecificationFactory
#
def initialize
@single_value_pattern = SingleValuePattern
@range_pattern = RangePattern
@step_pattern = StepPattern
end
##
# Parses a unit of a cron specification.
# The supported patterns for parsing are one of:
#
# * Wildcard '*'
# * Single Scalar Value [0-9]+|(sun|mon|tue|wed|thu|fri|sat)|(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)
# * Range value (0-9, mon-fri, etc.)
# * Step value (*/[0-9]+)
#
def parse(value_spec)
case value_spec
when WildcardPattern
WildcardCronValue.new(@lower_limit, @upper_limit)
when @single_value_pattern
SingleValueCronValue.new(@lower_limit, @upper_limit, convert_value($1))
when @range_pattern
RangeCronValue.new(@lower_limit, @upper_limit, convert_value($1), convert_value($2))
when @step_pattern
StepCronValue.new(@lower_limit, @upper_limit, $1.to_i)
else
raise "Unrecognized cron specification pattern."
end
end
private
def convert_value(value)
value.to_i
end
end
end
|
module CopyPeste
class Core
# This class is used to store data between each execution of commands.
class CoreState
attr_accessor :analysis_module
attr_accessor :conf
attr_accessor :events_to_command
attr_accessor :graphic_mod
attr_accessor :module_mng
def initialize
@graphic_mod = nil
@analysis_module = nil
@conf = nil
@module_mng = nil
@events_to_command = {}
end
end
end
end
|
class PageRedirect < ActiveRecord::Migration
def up
add_column :pages, :redirect, :boolean
add_column :pages, :action_name, :string
add_column :pages, :controller_name, :string
end
def down
remove_column :pages, :redirect
remove_column :pages, :action_name
remove_column :pages, :controller_name
end
end
|
require 'factory_face'
require 'factory_face_rails/generator'
require 'rails'
module FactoryBot
class Railtie < Rails::Railtie
initializer "factory_face.set_fixture_replacement" do
FactoryBotRails::Generator.new(config).run
end
initializer "factory_face.set_factory_paths" do
FactoryBot.definition_file_paths = [
Rails.root.join('factories'),
Rails.root.join('test', 'factories'),
Rails.root.join('spec', 'factories')
]
end
config.after_initialize do
FactoryBot.find_definitions
if defined?(Spring)
Spring.after_fork { FactoryBot.reload }
end
end
end
end
|
=begin
#Swagger Petstore
#No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
The version of the OpenAPI document: 1.4.2
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 4.2.1-SNAPSHOT
=end
require 'cgi'
module BhalleExample
class PetsApi
attr_accessor :api_client
def initialize(api_client = ApiClient.default)
@api_client = api_client
end
# Create a pet
# @param [Hash] opts the optional parameters
# @return [nil]
def create_pets(opts = {})
create_pets_with_http_info(opts)
nil
end
# Create a pet
# @param [Hash] opts the optional parameters
# @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers
def create_pets_with_http_info(opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: PetsApi.create_pets ...'
end
# resource path
local_var_path = '/pets'
# query parameters
query_params = opts[:query_params] || {}
# header parameters
header_params = opts[:header_params] || {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/json'])
# form parameters
form_params = opts[:form_params] || {}
# http body (model)
post_body = opts[:body]
# return_type
return_type = opts[:return_type]
# auth_names
auth_names = opts[:auth_names] || []
new_options = opts.merge(
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => return_type
)
data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options)
if @api_client.config.debugging
@api_client.config.logger.debug "API called: PetsApi#create_pets\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
# List all pets
# @param [Hash] opts the optional parameters
# @option opts [Integer] :limit How many items to return at one time (max 100)
# @return [Array<Pet>]
def list_pets(opts = {})
data, _status_code, _headers = list_pets_with_http_info(opts)
data
end
# List all pets
# @param [Hash] opts the optional parameters
# @option opts [Integer] :limit How many items to return at one time (max 100)
# @return [Array<(Array<Pet>, Integer, Hash)>] Array<Pet> data, response status code and response headers
def list_pets_with_http_info(opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: PetsApi.list_pets ...'
end
# resource path
local_var_path = '/pets'
# query parameters
query_params = opts[:query_params] || {}
query_params[:'limit'] = opts[:'limit'] if !opts[:'limit'].nil?
# header parameters
header_params = opts[:header_params] || {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/json'])
# form parameters
form_params = opts[:form_params] || {}
# http body (model)
post_body = opts[:body]
# return_type
return_type = opts[:return_type] || 'Array<Pet>'
# auth_names
auth_names = opts[:auth_names] || []
new_options = opts.merge(
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => return_type
)
data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options)
if @api_client.config.debugging
@api_client.config.logger.debug "API called: PetsApi#list_pets\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
# Info for a specific pet
# @param pet_id [String] The id of the pet to retrieve
# @param [Hash] opts the optional parameters
# @return [Pet]
def show_pet_by_id(pet_id, opts = {})
data, _status_code, _headers = show_pet_by_id_with_http_info(pet_id, opts)
data
end
# Info for a specific pet
# @param pet_id [String] The id of the pet to retrieve
# @param [Hash] opts the optional parameters
# @return [Array<(Pet, Integer, Hash)>] Pet data, response status code and response headers
def show_pet_by_id_with_http_info(pet_id, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: PetsApi.show_pet_by_id ...'
end
# verify the required parameter 'pet_id' is set
if @api_client.config.client_side_validation && pet_id.nil?
fail ArgumentError, "Missing the required parameter 'pet_id' when calling PetsApi.show_pet_by_id"
end
# resource path
local_var_path = '/pets/{petId}'.sub('{' + 'petId' + '}', CGI.escape(pet_id.to_s))
# query parameters
query_params = opts[:query_params] || {}
# header parameters
header_params = opts[:header_params] || {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/json'])
# form parameters
form_params = opts[:form_params] || {}
# http body (model)
post_body = opts[:body]
# return_type
return_type = opts[:return_type] || 'Pet'
# auth_names
auth_names = opts[:auth_names] || []
new_options = opts.merge(
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => return_type
)
data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options)
if @api_client.config.debugging
@api_client.config.logger.debug "API called: PetsApi#show_pet_by_id\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
end
end
|
class Station
attr_accessor :station_name, :zone
def initialize(station_name, zone)
@station_name = station_name
@zone = zone
end
end
|
require_relative '../../lib/first/person'
RSpec.describe Person do
let(:person) { described_class.new(first_name, last_name, education_level) }
let(:first_name) { anything }
let(:last_name) { anything }
let(:education_level) { anything }
describe '#full_name' do
let(:full_name) { person.full_name }
let(:first_name) { 'John' }
let(:last_name) { 'Snow' }
let(:education_level) { anything }
it 'returns full name' do
expect(full_name).to eq 'John Snow'
end
end
describe '#educate!' do
let(:educate!) { person.educate! }
let(:first_name) { anything }
let(:last_name) { anything }
let(:education_level) { 2 }
it 'increments education_level by 1' do
expect { educate! }.to change { person.education_level }.by(1)
end
end
# or...
describe '#educate!' do
before { person.educate! }
let(:first_name) { anything }
let(:last_name) { anything }
let(:education_level) { 2 }
it 'increments education_level by 1' do
expect(person.education_level).to eq 3
end
end
end
|
require "rails_helper"
RSpec.describe ReportregsController, type: :routing do
describe "routing" do
it "routes to #index" do
expect(:get => "/reportregs").to route_to("reportregs#index")
end
it "routes to #new" do
expect(:get => "/reportregs/new").to route_to("reportregs#new")
end
it "routes to #show" do
expect(:get => "/reportregs/1").to route_to("reportregs#show", :id => "1")
end
it "routes to #edit" do
expect(:get => "/reportregs/1/edit").to route_to("reportregs#edit", :id => "1")
end
it "routes to #create" do
expect(:post => "/reportregs").to route_to("reportregs#create")
end
it "routes to #update via PUT" do
expect(:put => "/reportregs/1").to route_to("reportregs#update", :id => "1")
end
it "routes to #update via PATCH" do
expect(:patch => "/reportregs/1").to route_to("reportregs#update", :id => "1")
end
it "routes to #destroy" do
expect(:delete => "/reportregs/1").to route_to("reportregs#destroy", :id => "1")
end
end
end
|
class AddDeliverableIdToIssues < ActiveRecord::Migration[4.2]
def self.up
add_column :issues, :deliverable_id, :integer
end
def self.down
remove_column :issues, :deliverable_id
end
end
|
class Admins::CardApplyTemplatesController < Admins::BaseController
before_action :set_template, only: [:show, :edit, :update, :destroy, :add_item, :remove_item, :set_default]
def index
@templates = CardApplyTemplate.includes(items: :shop).order(id: :desc)
.page(params[:page])
.per(params[:per])
@template = CardApplyTemplate.new
end
def show
end
def new
end
def edit
end
def create
@template = CardApplyTemplate.new(template_params)
respond_to do |format|
if @template.save
format.js
format.html { redirect_to admins_card_apply_templates_path }
format.json { render json: @template }
else
format.html do
flash[:error] = @template.errors.full_messages.join(", ")
redirect_to new_admins_card_apply_template_path
end
format.json do
render json: {errors: @template.errors.full_messages.join(", ")}, status: :unprocessable_entity
end
format.js
end
end
end
def update
if @template.update(template_params)
redirect_to admins_card_apply_templates_path
else
flash[:error] = @template.errors.full_messages.join(', ')
render "edit"
end
end
def add_item
@card_template_item = @template.card_template_items.build(item_id: params[:item_id])
if @card_template_item.save
render json: @card_template_item.item.to_json(except: [:income_price], methods: [:shop_name, :shop_realname])
else
render json: {errors: @card_template_item.errors.full_messages}, status: :unprocessable_entity
end
end
def set_default
@template.set_default!
# render json: {}
end
def remove_item
@card_template_item = @template.card_template_items.find_by(item_id: params[:item_id])
@card_template_item.destroy if @card_template_item.present?
head :no_content
end
def destroy
@template.destroy
end
private
def set_template
@template = CardApplyTemplate.find(params[:id])
end
def template_params
params.require(:card_apply_template).permit(:title, :apply_items, card_template_items_attributes: [:item_id])
end
end
|
class ApiSessionsController < ApiController
def create
if authenticate
render json: { status: :success, email: current_user.email }
else
invalid_login_attempt
end
end
end
|
module Commonsense
module Core
class Tag < ActiveRecord::Base
has_many :incoming_tag_relations,
:class_name => "TagRelation",
:foreign_key => "destination_id",
:dependent => :destroy
has_many :outgoing_tag_relations,
:class_name => "TagRelation",
:foreign_key => "source_id",
:dependent => :destroy
has_many :sources, :through => :incoming_tag_relations
has_many :destinations, :through => :outgoing_tag_relations
has_many :tag_document_relations, :dependent => :destroy
has_many :documents, :through => :tag_document_relations
belongs_to :user
has_many :ratings, :as => :rateable, :dependent => :destroy
alias_method :relations, :destinations
end
end
end
|
require 'erb'
require 'ostruct'
require_relative 'utils'
module MagicServer
# This method takes a url like this: /erbtest?boo=hello
# and turns it into a map with :route and :arguments
# as keys. /erbtest would be :route, and boo => hello
# would be :arguments. The reason why this is done is
# so that the route and the parameters can be separated
def self.parse_heading(heading, method)
ret = {}
arguments = {}
parsed_heading = heading.gsub(/#{method}\ \//, '')
parsed_heading.gsub!(/\ HTTP.*/, '')
parsed_heading.chomp!
#Split up the heading between the routes and the arguments
split_heading = parsed_heading.split('?')
ret[:route] = split_heading[0]
#Parse the arguments into a map
if split_heading.size > 1
split_heading[1].split('&').each do |key_val|
key_and_val = key_val.split('=')
arguments[key_and_val[0]] = key_and_val[1]
end
end
ret[:arguments] = arguments
ret
end
# Fetch a file from the file system. the 'b' in open options
# stands for binary file mode. The reason this is used is
# because certain file types, like images, don't read properly
# unless you use it. I'm not exactly sure why this is the case,
# so it's definitely something to look into
def self.find_file(path)
open_options = 'rb'
if path.empty?
full_path = MagicServer::BASE_PATH + 'index.html'
else
full_path = MagicServer::BASE_PATH + path
end
found_file = ''
if File.exists? full_path
found_file = File.open(full_path, open_options).read
end
return found_file
end
# Generates the "Content-Type" heading based on the path
def self.get_content_type(path)
ext = File.extname(path).downcase
return MagicServer::HTML_TYPE if ext.include? ".html" or ext.include? ".htm"
return "text/plain" if ext.include? ".txt"
return "text/css" if ext.include? ".css"
return "image/jpeg" if ext.include? ".jpeg" or ext.include? ".jpg"
return "image/gif" if ext.include? ".gif"
return "image/bmp" if ext.include? ".bmp"
return "image/png" if ext.include? ".png"
return "text/plain" if ext.include? ".rb"
return "text/xml" if ext.include? ".xml"
return "text/xml" if ext.include? ".xsl"
return 'application/javascript' if ext.include?('.js')
return MagicServer::HTML_TYPE
end
# Takes a HTTP request and parses it into a map that's keyed
# by the title of the heading and the heading itself
def self.parse_http_request(request)
headers = {}
# Need to use readpartial instead of read because read will
# block due to the lack of a EOF
request_str = ''
until (line = request.gets) && (line.inspect.eql?('"\r\n"'))
request_str << line
end
arrayed_request = request_str.split(/\r?\n/)
headers['Request-Line'] = arrayed_request.shift
# For everything else, split on the first colon, and
# dump it all into the headers map
headers.update(arrayed_request.inject(headers) {|headers, line|
split = line.split(':')
headers[split.shift] = split.join(':').strip
headers
})
if headers.has_key? 'Content-Length'
headers['Body'] = request.readpartial(headers['Content-Length'].to_i)
LoggerUtil.info('Body is ' << headers['Body'])
end
headers
end
#takes the post body and makes it into a key/val map
def self.parse_post_body(post_body)
parsed_attr = {}
post_body.split('&').each do |key_val|
split_key_val = key_val.split('=')
parsed_attr[split_key_val[0]] = split_key_val[1]
end
return parsed_attr
end
#renders an erb template, taking in a hash for the variables
def self.render_erb(template, locals)
ERB.new(template).result(OpenStruct.new(locals).instance_eval { binding })
end
end
|
#!/usr/bin/env ruby
require_relative 'Emergency'
class Earthquake < Emergency
def initialize(epicenter=nil, magnitude=nil, radius=nil)
super()
@type = :earthquake
if epicenter.nil?
epicenter = "Place de la Bourse, 1000 Bruxelles"
end
if magnitude.nil?
magnitude = 3.2
end
if radius.nil?
radius = "25km"
end
@properties[:epicenter] = epicenter
@properties[:magnitude] = magnitude
@properties[:radius] = radius
end
end
|
require 'bundler/capistrano'
require "rvm/capistrano"
set :rvm_ruby_string, :local # use the same ruby as used locally for deployment
set :user, 'ubuntu'
set :domain, 'ec2-23-23-233-0.compute-1.amazonaws.com'
set :application, "dealStreet"
set :repository, "git@github.com:dalebiagio/DealStreetLinux.git"
#set :repository, "ssh:#{user}@#{domain}:/#{application}.git"
set :deploy_to, "/var/www"
set :normalize_asset_timestamps, false
ssh_options[:forward_agent] = true
ssh_options[:auth_methods] = ["publickey"]
ssh_options[:keys] = ["/home/dale/Dev/Whizz/whizz.pem"]
default_run_options[:pty] = true
role :web, domain # Your HTTP server, Apache/etc
role :app, domain # This may be the same as your `Web` serverrole :db, domain, :primary => true # This is where Rails migrations will run
default_run_options[:shell] = false
default_run_options[:pty] = true
# miscellaneous options
set :deploy_via, :remote_cache
set :scm, 'git'
set :branch, 'master'
set :scm_verbose, true
set :use_sudo, false
set :deploy_to, "/home/#{user}/apps/#{application}"
# Define all the tasks that need to be running manually after Capistrano is finished.
namespace :deploy do
task :bundle_install, :roles => :app do
run "cd #{release_path} && bundle install"
end
end
after "deploy:update_code", :bundle_install
desc "install the necessary prerequisites"
task :bundle_install, :roles => :app do
run "cd #{release_path} && bundle install"
run "cd #{release_path} && rake assets:precompile"end
|
class CreateClients < ActiveRecord::Migration
def change
create_table :clients do |t|
t.string :company_name
t.string :email
t.string :sector
t.string :size
t.boolean :can_contact
t.timestamps null: false
end
end
end
|
When(/^I go to events page$/) do
visit new_event_path
end
When(/^I submit the form for event$/) do
fill_in 'Location', with: 'something'
fill_in 'Starts at', with: Time.now
fill_in 'Ends at', with: Time.now
select first('MyString'), from: 'Hobby'
click_button 'Create Event'
end
Then(/^I should see a succes message$/) do
page.should have_content I18n.t!('events.created.success')
end
|
# frozen_string_literal: true
module Vedeu
# Produces ASCII character 27 which is ESC
ESCAPE_KEY_CODE = 27
module Input
# Captures input from the user terminal via 'getch' and
# translates special characters into symbols.
#
# @api private
#
class Capture
include Vedeu::Common
extend Forwardable
def_delegators Vedeu::Terminal::Mode,
:cooked_mode?,
:fake_mode?,
:raw_mode?
# Instantiate Vedeu::Input::Input and capture keypress(es).
#
# @return (see #read)
def self.read
new.read
end
# Returns a new instance of Vedeu::Input::Input.
#
# @return [Vedeu::Input::Input]
def initialize; end
# Triggers various events dependent on the terminal mode.
#
# - When in raw mode, the :_keypress_ event is triggered with
# the key(s) pressed.
# - When in fake mode, the keypress will be checked against the
# keymap relating to the interface/view currently in focus.
# - If registered, the :_keypress_ event is triggered with the
# key(s) pressed.
# - If the keypress is not registered, we check whether the
# interface in focus is editable, if so, the :_editor_
# event is triggered.
# - Otherwise, the :key event is triggered for the client
# application to handle.
# - When in cooked mode, the :_command_ event is triggered with
# the input given.
#
# @return [Array|String|Symbol]
def read
Vedeu.log(type: :input, message: "Waiting for user input...\n")
if raw_mode?
Vedeu.trigger(:_keypress_, keypress)
elsif fake_mode?
@key ||= keypress
if @key.nil?
nil
elsif click?(@key)
Vedeu.trigger(:_mouse_event_, @key)
elsif Vedeu::Input::Mapper.registered?(@key, name)
Vedeu.trigger(:_keypress_, @key, name)
elsif interface.editable?
Vedeu.trigger(:_editor_, @key)
else
Vedeu.trigger(:key, @key)
end
elsif cooked_mode?
Vedeu.trigger(:_command_, command)
end
end
private
# Returns the translated (when possible) keypress(es).
#
# @return [String|Symbol]
def keypress
Vedeu::Input::Translator.translate(input)
end
# Takes input from the user via the keyboard. Accepts special
# keys like the F-Keys etc, by capturing the entire sequence.
#
# @return [String]
def input
keys = Vedeu::Input::Raw.read
if click?(keys)
Vedeu::Input::Mouse.click(keys)
else
keys
end
end
# @macro interface_by_name
def interface
Vedeu.interfaces.by_name(name)
end
# Returns a boolean indicating whether a mouse click was
# received.
#
# @param keys [NilClass|String|Symbol|Vedeu::Cursors::Cursor]
# @return [Boolean]
def click?(keys)
return false if keys.nil? || symbol?(keys)
keys.is_a?(Vedeu::Cursors::Cursor) || keys.start_with?("\e[M")
end
# @return [IO]
def console
@console ||= Vedeu::Terminal.console
end
# Takes input from the user via the keyboard. Accepts special
# keys like the F-Keys etc, by capturing the entire sequence.
#
# @return [String]
def command
console.gets.chomp
end
# @macro return_name
def name
Vedeu.focus
end
end # Input
end # Input
end # Vedeu
|
# frozen_string_literal: true
require "kafka/statsd"
require "socket"
require "fake_statsd_agent"
describe "Reporting metrics to Statsd", functional: true do
example "reporting connection metrics" do
agent = FakeStatsdAgent.new
Kafka::Statsd.port = agent.port
agent.start
kafka.topics
agent.wait_for_metrics(count: 4)
expect(agent.metrics).to include(/ruby_kafka\.api\.\w+\.\w+\.[\w\.]+\.calls/)
expect(agent.metrics).to include(/ruby_kafka\.api\.\w+\.\w+\.[\w\.]+\.latency/)
expect(agent.metrics).to include(/ruby_kafka\.api\.\w+\.\w+\.[\w\.]+\.request_size/)
expect(agent.metrics).to include(/ruby_kafka\.api\.\w+\.\w+\.[\w\.]+\.response_size/)
end
end
|
json.array!(@site_settings) do |site_setting|
json.extract! site_setting, :id, :year_id
json.url site_setting_url(site_setting, format: :json)
end
|
require 'spec_helper'
module Boilerpipe::Filters
describe MinClauseWordsFilter do
describe '#process' do
let(:text_block) { Boilerpipe::Document::TextBlock }
let(:text_block1) { text_block.new('one two three four five, one two', 7) }
let(:text_block2) { text_block.new('one two', 2) }
let(:text_blocks) { [text_block1, text_block2] }
let!(:doc) { Boilerpipe::Document::TextDocument.new('', text_blocks) }
before do
text_block1.content = true
text_block2.content = true
end
it 'keeps blocks with one clause of at least 5 words' do
expect(text_block1.content).to be true
expect(text_block2.content).to be true
MinClauseWordsFilter.process doc
expect(text_block1.content).to be true
expect(text_block2.content).to be false
end
end
end
end
|
require_relative 'test_helper'
require './lib/sales_engine'
require 'csv'
class MerchantRepositoryTest < Minitest::Test
def setup
item_file_path = './test/fixtures/items_truncated.csv'
merchant_file_path = './test/fixtures/merchants_truncated.csv'
invoice_file_path = './test/fixtures/invoices_truncated.csv'
invoice_item_file_path = './test/fixtures/invoice_items_truncated.csv'
customer_file_path = './test/fixtures/customers_truncated.csv'
transaction_file_path = './test/fixtures/transactions_truncated.csv'
engine = SalesEngine.new(item_file_path, merchant_file_path,
invoice_file_path, invoice_item_file_path, customer_file_path,
transaction_file_path)
@repository = engine.merchants
end
def test_merchant_repository_class_exists
assert_instance_of MerchantRepository, @repository
end
def test_load_from_csv_returns_array_of_merchants
assert_instance_of Merchant, @repository.merchants[0]
end
def test_all_returns_array_of_all_merchants
all_merchants = @repository.all
assert_equal 4, all_merchants.count
end
def test_it_finds_merchant_by_id
merchant = @repository.find_by_id(12334113)
assert_equal "MiniatureBikez", merchant.name
merchant = @repository.find_by_id('12334113')
assert_equal "MiniatureBikez", merchant.name
end
def test_it_finds_merchants_by_name
merchant = @repository.find_by_name("LolaMarleys")
assert_equal 12334115, merchant.id
merchant = @repository.find_by_name("lolamarleys")
assert_equal 12334115, merchant.id
end
def test_it_returns_empty_array_if_no_name_foun
assert_empty(@repository.find_all_by_name("xyz"))
end
def test_it_finds_all_merchants_by_name_fragments
merchants = @repository.find_all_by_name("ar")
merchant1 = @repository.find_by_name("Candisart")
merchant2 = @repository.find_by_name("LolaMarleys")
assert merchants.include?(merchant1)
assert merchants.include?(merchant2)
end
end
|
# frozen_string_literal: true
# This is a porting of Thor::Shell::Basic
# rewritten as a module that can be included by
# plugins
# Thor is available under MIT license
# Copyright (c) 2008 Yehuda Katz, Eric Hodel, et al.
module Quicken
module Helpers
module Base
# Say (print) something to the user. If the sentence ends with a whitespace
# or tab character, a new line is not appended (print + flush). Otherwise
# are passed straight to puts (behavior got from Highline).
#
# ==== Example
# say("I know you knew that.")
#
def say message = '', color = nil, force_new_line = (message.to_s !~ /( |\t)\Z/)
buffer = prepare_message(message, *color)
buffer << "\n" if force_new_line && !message.to_s.end_with?("\n")
stdout.print(buffer)
stdout.flush
end
# Asks something to the user and receives a response.
#
# If a default value is specified it will be presented to the user
# and allows them to select that value with an empty response. This
# option is ignored when limited answers are supplied.
#
# If asked to limit the correct responses, you can pass in an
# array of acceptable answers. If one of those is not supplied,
# they will be shown a message stating that one of those answers
# must be given and re-asked the question.
#
# If asking for sensitive information, the :echo option can be set
# to false to mask user input from $stdin.
#
# If the required input is a path, then set the path option to
# true. This will enable tab completion for file paths relative
# to the current working directory on systems that support
# Readline.
#
# ==== Example
# ask("What is your name?")
#
# ask("What is the planet furthest from the sun?", :default => "Pluto")
#
# ask("What is your favorite Neopolitan flavor?", :limited_to => ["strawberry", "chocolate", "vanilla"])
#
# ask("What is your password?", :echo => false)
#
# ask("Where should the file be saved?", :path => true)
#
def ask statement, *args
options = args.last.is_a?(Hash) ? args.pop : {}
color = args.first
if options[:limited_to]
ask_filtered(statement, color, options)
else
ask_simply(statement, color, options)
end
end
# Say a status with the given color and appends the message. Since this
# method is used frequently by actions, it allows nil or false to be given
# in log_status, avoiding the message from being shown. If a Symbol is
# given in log_status, it's used as the color.
#
def say_status status, message, log_status = true
return if quiet? || log_status == false
spaces = ' ' * (padding + 1)
color = log_status.is_a?(Symbol) ? log_status : :green
status = status.to_s.rjust(12)
status = set_color status, color, true if color
buffer = "#{status}#{spaces}#{message}"
buffer = "#{buffer}\n" unless buffer.end_with?("\n")
stdout.print(buffer)
stdout.flush
end
# Make a question the to user and returns true if the user replies "y" or
# "yes".
#
def yes? statement, color = nil
(ask(statement, color, add_to_history: false) =~ is?(:yes))
end
# Make a question the to user and returns true if the user replies "n" or
# "no".
#
def no? statement, color = nil
(ask(statement, color, add_to_history: false) =~ is?(:no))
end
# Prints values in columns
#
# ==== Parameters
# Array[String, String, ...]
#
def print_in_columns array
return if array.empty?
colwidth = (array.map { |el| el.to_s.size }.max || 0) + 2
array.each_with_index do |value, index|
# Don't output trailing spaces when printing the last column
if ((((index + 1) % (terminal_width / colwidth))).zero? && !index.zero?) || index + 1 == array.length
stdout.puts value
else
stdout.printf("%-#{colwidth}s", value)
end
end
end
protected
def prepare_message message, *color
spaces = ' ' * padding
spaces + set_color(message.to_s, *color)
end
# Thor::Shell::Color is available under MIT license
# Copyright (c) 2008 Yehuda Katz, Eric Hodel, et al.
# Embed in a String to clear all previous ANSI sequences.
CLEAR = "\e[0m"
# The start of an ANSI bold sequence.
BOLD = "\e[1m"
# Set the terminal's foreground ANSI color to black.
BLACK = "\e[30m"
# Set the terminal's foreground ANSI color to red.
RED = "\e[31m"
# Set the terminal's foreground ANSI color to green.
GREEN = "\e[32m"
# Set the terminal's foreground ANSI color to yellow.
YELLOW = "\e[33m"
# Set the terminal's foreground ANSI color to blue.
BLUE = "\e[34m"
# Set the terminal's foreground ANSI color to magenta.
MAGENTA = "\e[35m"
# Set the terminal's foreground ANSI color to cyan.
CYAN = "\e[36m"
# Set the terminal's foreground ANSI color to white.
WHITE = "\e[37m"
# Set the terminal's background ANSI color to black.
ON_BLACK = "\e[40m"
# Set the terminal's background ANSI color to red.
ON_RED = "\e[41m"
# Set the terminal's background ANSI color to green.
ON_GREEN = "\e[42m"
# Set the terminal's background ANSI color to yellow.
ON_YELLOW = "\e[43m"
# Set the terminal's background ANSI color to blue.
ON_BLUE = "\e[44m"
# Set the terminal's background ANSI color to magenta.
ON_MAGENTA = "\e[45m"
# Set the terminal's background ANSI color to cyan.
ON_CYAN = "\e[46m"
# Set the terminal's background ANSI color to white.
ON_WHITE = "\e[47m"
# Set color by using a string or one of the defined constants. If a third
# option is set to true, it also adds bold to the string. This is based
# on Highline implementation and it automatically appends CLEAR to the end
# of the returned String.
#
# Pass foreground, background and bold options to this method as
# symbols.
#
# Example:
#
# set_color "Hi!", :red, :on_white, :bold
#
# The available colors are:
#
# :bold
# :black
# :red
# :green
# :yellow
# :blue
# :magenta
# :cyan
# :white
# :on_black
# :on_red
# :on_green
# :on_yellow
# :on_blue
# :on_magenta
# :on_cyan
# :on_white
def set_color string, *colors
if colors.compact.empty? || !can_display_colors?
string
elsif colors.all? { |color| color.is_a?(Symbol) || color.is_a?(String) }
ansi_colors = colors.map { |color| lookup_color(color) }
"#{ansi_colors.join}#{string}#{CLEAR}"
else
# The old API was `set_color(color, bold=boolean)`. We
# continue to support the old API because you should never
# break old APIs unnecessarily :P
foreground, bold = colors
foreground = self.class.const_get(foreground.to_s.upcase) if foreground.is_a?(Symbol)
bold = bold ? BOLD : ''
"#{bold}#{foreground}#{string}#{CLEAR}"
end
end
def lookup_color(color)
return color unless color.is_a?(Symbol)
self.class.const_get(color.to_s.upcase)
end
def can_display_colors?
stdout.tty?
end
# Overwrite show_diff to show diff with colors if Diff::LCS is
# available.
#
def show_diff destination, content
if diff_lcs_loaded? && ENV['THOR_DIFF'].nil? && ENV['RAILS_DIFF'].nil?
actual = File.binread(destination).to_s.split("\n")
content = content.to_s.split("\n")
Diff::LCS.sdiff(actual, content).each do |diff|
output_diff_line(diff)
end
else
diff_cmd = ENV["THOR_DIFF"] || ENV["RAILS_DIFF"] || "diff -u"
require "tempfile"
Tempfile.open(File.basename(destination), File.dirname(destination)) do |temp|
temp.write content
temp.rewind
system %(#{diff_cmd} "#{destination}" "#{temp.path}")
end
end
end
def output_diff_line diff
case diff.action
when '-'
say "- #{diff.old_element.chomp}", :red, true
when '+'
say "+ #{diff.new_element.chomp}", :green, true
when '!'
say "- #{diff.old_element.chomp}", :red, true
say "+ #{diff.new_element.chomp}", :green, true
else
say " #{diff.old_element.chomp}", nil, true
end
end
# Check if Diff::LCS is loaded. If it is, use it to create pretty output
# for diff.
#
def diff_lcs_loaded? #:nodoc:
return true if defined?(Diff::LCS)
return @diff_lcs_loaded unless @diff_lcs_loaded.nil?
@diff_lcs_loaded = begin
require 'diff/lcs'
true
rescue LoadError
false
end
end
def stdout
$stdout
end
def stderr
$stderr
end
def is? value #:nodoc:
value = value.to_s
if value.size == 1
/\A#{value}\z/i
else
/\A(#{value}|#{value[0, 1]})\z/i
end
end
def ask_simply statement, color, options
default = options[:default]
message = [statement, ("(#{default})" if default), nil].uniq.join(' ')
message = prepare_message(message, *color)
result = Thor::LineEditor.readline(message, options)
return unless result
result = result.strip
if default && result == ''
default
else
result
end
end
def ask_filtered statement, color, options
answer_set = options[:limited_to]
correct_answer = nil
until correct_answer
answers = answer_set.join(', ')
answer = ask_simply("#{statement} [#{answers}]", color, options)
correct_answer = answer_set.include?(answer) ? answer : nil
say("Your response must be one of: [#{answers}]. Please try again.") unless correct_answer
end
correct_answer
end
def die message
abort "ABORT: #{message}"
end
end
end
end
|
class CreateRuns < ActiveRecord::Migration
def change
create_table :runs do |t|
t.string :state
t.timestamp :started_at
t.timestamp :finished_at
t.references :workflow
t.timestamps
end
end
end
|
module Api
module V1
class CitiesController < BaseController
skip_before_action :set_resource
def index
@cities = @parser.get_cities
end
def show
city = @parser.get_city(params[:id])
unless city
@errors = {
city: 'City doesn\'t exists'
}
respond_to do |format|
format.json { render :error }
end
else
@city = city
end
end
private
def city_params
params.require(:city)
end
end
end
end |
class NoteRepository
include Curator::Repository
indexed_fields :user_id
end
|
class Dog
attr_accessor :breed, :name
def initialize(breed, name)
@breed = breed
@name = name
end
def wag_tail(emotion, frequency)
@emotion = emotion
@frequency = frequency
"The dog is #{emotion} and wags his tail #{frequency} "
end
def pant
puts "Is panting from heat"
end
def Snacks
puts "Gets snacks woof!"
end
end |
class CreateProductRebates < ActiveRecord::Migration[5.0]
def change
create_table :product_rebates do |t|
t.belongs_to :product, null: false, foreign_key: true
t.belongs_to :rebate, null: false, foreign_key: true
t.timestamps
end
end
end
|
module UsersHelper
def owner?(user)
if user.kind_of?(String)
user.eql?(current_user.user_name)
else
current_user.eql?(user)
end
end
end
|
# frozen-string-literal: true
module Down
VERSION = "4.6.0"
end
|
require 'rubygems'
require 'rake'
require 'rake/testtask'
require 'rake/rdoctask'
require 'rake/gempackagetask'
$LOAD_PATH.unshift 'lib'
require 'lolspeak/version'
$KCODE = "UTF-8"
task :default => [:test_units]
desc "Run basic tests"
Rake::TestTask.new("test_units") do |t|
t.pattern = 'test/*_test.rb'
t.verbose = false
t.warning = true
end
PKG_NAME = 'lolspeak'
PKG_VERSION = LOLspeak::VERSION
PKG_FILES = FileList[
'[A-Z]*',
'bin/**/*',
'lib/**/*.rb',
# Add this manually, because it's copied. If it doesn't exist at the time
# this is run, the wildcard won't pick it up, and it won't be included
# in the final package.
'lib/lolspeak/tranzlator.yml',
'test/**/*',
]
Rake::RDocTask.new(:rdoc) do |rdoc|
rdoc.rdoc_dir = 'rdoc'
rdoc.title = "#{PKG_NAME} -- A LOLspeak translator"
rdoc.rdoc_files.include('README')
rdoc.rdoc_files.include('lib/**/*.rb', 'bin/*')
end
spec = Gem::Specification.new do |s|
s.platform = Gem::Platform::RUBY
s.summary = "LOLspeak translator"
s.name = PKG_NAME
s.version = PKG_VERSION
s.requirements << 'none'
s.require_path = 'lib'
s.files = PKG_FILES
s.has_rdoc = true
s.bindir = 'bin'
s.executables = ['lolspeak']
s.description = <<-EOF
Translates English text into LOLspeak.
EOF
s.author = "Dave Dribin"
s.homepage = "http://www.dribin.org/dave/software/lolspeak/"
s.rubyforge_project = 'lolspeak'
end
Rake::GemPackageTask.new(spec) do |pkg|
pkg.need_zip = true
pkg.need_tar = true
end
SRC_TRANZ = "../tranzlator.yml"
DEST_TRANZ = "lib/lolspeak/tranzlator.yml"
if File.exists? SRC_TRANZ
file DEST_TRANZ => [SRC_TRANZ] do
safe_ln(SRC_TRANZ, DEST_TRANZ)
end
task :tranzlator => DEST_TRANZ
task :test_units => [:tranzlator]
task :package => [:tranzlator]
end
|
require 'Log4r'
#require 'log4r/formatter/patternformatter.rb'
class ILogger
def self.log
if @logger.nil?
@logger = Log4r::Logger.new('Metamask Application')
@logger.outputters << Log4r::Outputter.stdout
@logger.outputters << Log4r::FileOutputter.new(
'MetamaskTest',
:filename => 'results/Metamask.log',
:formatter => Log4r::PatternFormatter.new(:pattern => "%d %l %m \n" ),
:trunc => false)
end
@logger
end
def self.info(msg)
self.log.info(msg)
end
def self.error(msg)
self.log.error(msg)
end
end |
class Product < ApplicationRecord
has_many :reviews, dependent: :destroy
has_many :favorites, dependent: :destroy
belongs_to :category
belongs_to :user
validates :title, presence: true, uniqueness: {message: 'must be unique.'}
validates :description, presence: true, length: {minimum: 10}
validates :price, presence: true, numericality: {greater_than: 0}
validates :category_id, presence: true
after_initialize :set_price_default_to_1
before_validation :capitalize_title
def self.search(v)
where("title ILIKE ? OR description ILIKE ?", "%#{v}%", "%#{v}%")
end
def fav_for(user)
favorites.find_by_user_id user
end
private
def set_price_default_to_1
self.price ||= 1
end
def capitalize_title
self.title = title.titleize if title
end
end
|
require 'test_helper'
class VoteTest < ActiveSupport::TestCase
test "must have candidate_id" do
assert Vote.create!(candidate_id: 2, voter_id: 2)
assert_raise ActiveRecord::RecordInvalid do
Vote.create!(candidate_id: nil, voter_id: 2)
end
end
test "must have voter_id" do
assert Vote.create!(candidate_id: 2, voter_id: 2)
assert_raise ActiveRecord::RecordInvalid do
Vote.create!(candidate_id: 2, voter_id: nil)
end
end
test "row is created in table" do
test_candidate = Candidate.create!(name: "first tester", hometown: "home", district: "13", party: "indep")
test_voter = Voter.create!(name: "first test", party: "indep")
assert test_vote = Vote.create!(candidate_id: test_candidate.id, voter_id: test_voter.id)
assert_equal test_vote, Vote.last
end
end
|
class AddIndexToUserColumnOnIsGuest < ActiveRecord::Migration
def change
end
add_index :users, :is_guest
end
|
json.array!(@offices) do |office|
json.extract! office, :id, :company_id, :user_id, :nombre, :calle_numero, :colonia, :codigo_postal, :latitud, :longitud, :telefono
json.url office_url(office, format: :json)
end
|
require 'spec_helper'
describe TimeSlot do
let(:club_night) { ClubNight.create(FactoryGirl.attributes_for(:club_night)) }
let(:event) { club_night.events.create(FactoryGirl.attributes_for(:event)) }
let(:time_slot) { event.time_slots.create(FactoryGirl.attributes_for(:time_slot)) }
describe "#dj_ids=" do
context "for existing djs" do
let (:existing_djs) do
existing_dj1 = FactoryGirl.create(:dj)
existing_dj2 = FactoryGirl.create(:dj)
existing_dj3 = FactoryGirl.create(:dj)
[existing_dj1, existing_dj2, existing_dj3]
end
it "should add the correct number existing DJs to a time slot" do
expect { time_slot.dj_ids = [existing_djs.first.id, existing_djs.second.id, existing_djs.third.id]
}.to change{
time_slot.djs.count
}.to(3)
end
it "should include existing DJs as part of the time slot" do
time_slot.dj_ids = existing_djs.map(&:id)
time_slot.djs.should include(existing_djs.first, existing_djs.second, existing_djs.third)
end
end
context "for non-existing djs" do
let! (:djs) do
existing_dj1 = FactoryGirl.create(:dj, :club_night => club_night)
existing_dj2 = FactoryGirl.create(:dj, :club_night => club_night)
non_existing_dj = "Quadrant"
[existing_dj1, existing_dj2, non_existing_dj]
end
it "should add the correct number of DJs to a club night" do
expect { time_slot.dj_ids = [djs.first.id, djs.second.id, djs.third]
}.to change {
club_night.djs.count
}.to(3)
end
it "should create a new DJ" do
expect { time_slot.dj_ids = [djs.first.id, djs.second.id, djs.third] }.to change {
Dj.count
}.by(1)
end
it "should add DJ to time slot" do
expect { time_slot.dj_ids = [djs.first.id, djs.second.id, djs.third]
}.to change {
time_slot.djs.count
}.by(3)
# existing_djs.should be_in time_slot.djs
end
it "should add a DJ with the correct name" do
expect { time_slot.dj_ids = [djs.third] }.to change {
club_night.djs.where(:dj_name => djs.third).exists?
}.to(true)
end
end
end
describe "#dj_id_list" do
context "with a blank dj list" do
before { time_slot.stub(:dj_ids => []) }
it "should return an empty string" do
time_slot.dj_id_list.should == ''
end
end
context "with a non-blank dj list" do
before { time_slot.stub(:dj_ids => [1, 2, 3]) }
it "should return a comma separated list of ids" do
time_slot.dj_id_list.should == '1,2,3'
end
end
end
describe "#dj_id_list=" do
context "with a blank string" do
it "should set dj_ids= with an empty array" do
time_slot.should_receive(:dj_ids=).with([])
time_slot.dj_id_list = ''
end
end
context "with a non-blank string" do
it "should set dj_ids= with a populated array" do
time_slot.should_receive(:dj_ids=).with(['1', '2', '3'])
time_slot.dj_id_list = '1,2,3'
end
end
end
end
# look at ids and see if any aren't actually integers
# if they aren't, they're names. Try to find a dj for this club night w/ this name
# if the dj doesn't exist, then create one, using the genre for this night as the default, etc
# then take that dj name out of the ids array and replace it w/ the id of the newly created dj
# time_slot.dj_ids = [dj_1.id, dj_2.id, 'Johnny Monsoon'] |
# frozen_string_literal: true
class Update < Aid::Script
def self.description
'Updates your dev environment automatically'
end
def self.help
<<~HELP
aid update
This script is a way to update your development environment automatically.
It will:
- rebase origin/master onto this branch
- install any new dependencies
- run any migrations
- prune your logs
- restart your servers
HELP
end
def run
pull_git
install_dependencies
update_db
remove_old_logs
restart_servers
end
private
def pull_git
step 'Rebasing from origin/master' do
system! 'git fetch origin && git rebase origin/master'
end
end
def install_dependencies
step 'Installing dependencies' do
system! 'command -v bundler > /dev/null || '\
'gem install bundler --conservative'
system! 'bundle install'
system! 'yarn'
end
end
def update_db
step 'Updating database' do
system! 'rake db:migrate db:test:prepare'
end
end
def remove_old_logs
step 'Removing old logs and tempfiles' do
system! 'rake log:clear tmp:clear'
end
end
def restart_servers
restart_rails
end
def restart_rails
step 'Attempting to restart Rails' do
output = `bin/rails restart`
if $CHILD_STATUS.exitstatus.positive?
puts colorize(
:light_red,
'skipping restart, not supported in this version of '\
'Rails (needs >= 5)'
)
else
puts output
end
end
end
end
|
require 'simplecov'
SimpleCov.start
require './lib/cypher'
require './lib/code_breaker'
require './lib/encoder'
describe CodeBreaker do
before(:each) do
@message = 'hello world! end'
@key = '02715'
@date = '040895'
@breaker = CodeBreaker.new()
end
describe 'initialize' do
it 'exists' do
expect(@breaker).to be_a(CodeBreaker)
end
it 'has attributes' do
expect(@breaker.alphabet).to eq(["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", " "])
expect(@breaker.shifts).to eq([])
expect(@breaker.cypher).to be_a(Cypher)
end
end
describe 'methods' do
before(:each) do
@crackable_message = 'This is a crackable message end'
@crackable_message_2 = 'This is a crackable message! end'
@cypher = Cypher.new(@key, @date)
@encoder = Encoder.new(@cypher)
@breaker = CodeBreaker.new()
@cyphertext = @encoder.encrypt_message(@crackable_message)
@cyphertext_2 = @encoder.encrypt_message(@crackable_message_2)
end
describe ' #find_shifts' do
it 'returns an array from a message' do
expect(@breaker.find_shifts(@crackable_message)).to be_a(Array)
end
it 'returns an array of 4 values' do
expect(@breaker.find_shifts(@crackable_message).count).to eq(4)
end
it 'returns an array of integers' do
expect(@breaker.find_shifts(@crackable_message).all?{|v|v.class == Integer}).to eq(true)
end
it 'returns the expect shift in proper order' do
expected = @cypher.shifts
expect(@breaker.find_shifts(@cyphertext)).to eq(expected)
end
it 'returns the expect shift in proper order' do
expected = @cypher.shifts
expect(@breaker.find_shifts(@cyphertext_2)).to eq(expected)
end
it 'returns shifts that can decrypt entire message' do
@breaker.find_shifts(@cyphertext)
expect(@breaker.decrypt_message(@cyphertext)).to eq(@crackable_message)
end
end
describe ' #possible_shifts' do
before(:each) do
@shifts = [5 , 25, 26, 10]
@possible_shifts = [['05', '32', '59', '86'],
['25', '52', '79'],
['26', '53', '80'],
['10', '37', '64', '91']]
end
it 'returns an Array' do
expect(@breaker.possible_shifts(@shifts)).to be_a(Array)
end
it 'returns an Array of Arrays' do
expect(@breaker.possible_shifts(@shifts).all?{|v|v.class == Array}).to eq(true)
end
it 'returns 2-digit string values inside arrays' do
expect(@breaker.possible_shifts(@shifts).flatten.all?{|v|v.class == String && v.chars.count == 2}).to eq(true)
end
it 'returns correct values' do
expect(@breaker.possible_shifts(@shifts)).to eq(@possible_shifts)
end
end
describe ' #valid_shift?' do
before(:each) do
@shift_1 = '05'
@shift_2 = '51'
@shift_3 = '65'
end
it 'returns a boolean' do
expect(@breaker.valid_shift?(@shift_1, @shift_2)).to be_a(TrueClass || FalseClass)
end
it 'returns true if second index of first key matches first index of the secnd key' do
expect(@breaker.valid_shift?(@shift_1, @shift_2)).to eq(true)
end
it 'returns false if second index of first key does not match the first index of the secnd key' do
expect(@breaker.valid_shift?(@shift_1, @shift_3)).to eq(false)
end
end
describe ' #find_valid_shift' do
before(:each) do
@shift_1 = '05'
@viable_shifts = [['05', '32'], ['25', '52'], ['26', '53'], ['37', '64']]
end
it 'returns a String' do
expect(@breaker.find_valid_shift(@shift_1, @viable_shifts[1])).to be_a(String)
end
it 'returns the correct string' do
expect(@breaker.find_valid_shift(@shift_1, @viable_shifts[1])).to eq('52')
end
end
describe ' #viable_shifts' do
before(:each) do
@possible_shifts = [['05', '32', '59', '86'],
['25', '52', '79'],
['26', '53', '80'],
['10', '37', '64', '91']]
@viable_shifts = [['05', '32'],
['25', '52'],
['26', '53'],
['37', '64']]
end
it 'returns an Array' do
expect(@breaker.viable_shifts(@possible_shifts)).to be_a(Array)
end
it 'returns an Array of Arrays' do
expect(@breaker.viable_shifts(@possible_shifts).all?{|v|v.class == Array}).to eq(true)
end
it 'returns correct values' do
expect(@breaker.viable_shifts(@possible_shifts)).to eq(@viable_shifts)
end
end
describe ' #build_keys' do
before(:each) do
@viable_shifts = [['05', '32'], ['25', '52'], ['26', '53'], ['37', '64']]
end
it 'returns an array' do
expect(@breaker.build_keys(@viable_shifts)).to be_a(Array)
end
it 'returns an Array of 5 character Strings' do
expect(@breaker.build_keys(@viable_shifts).all?{|v|v.class == String && v.chars.count == 5}).to eq(true)
end
it 'returns the correct array of keys' do
expected = ['05264', '32537']
end
end
describe ' #crack_keys' do
it ' returns a string' do
expect(@breaker.crack_keys(@cyphertext, @date)).to be_a(String)
end
it 'returns the correct string' do
expect(@breaker.crack_keys(@cyphertext, @date)).to eq(@key)
end
end
describe ' #crack_easy' do
it 'updates the cypher shifts' do
expect(@breaker.cypher.shifts).to eq(nil)
@breaker.crack_easy(@cyphertext)
expect(@breaker.cypher.shifts).to eq([3, 0, 19, 20])
end
end
describe ' #crack_hard' do
# before(:each) do
# allow(@breaker).to receive(:generate_dates).and_return(['211095', @date])
# end
it 'returns a hash' do
expect(@breaker.crack_hard(@cyphertext)).to be_a(Hash)
end
it 'returns a hash with a date and a key' do
expect(@breaker.crack_hard(@cyphertext).keys).to eq([:date, :key])
end
it 'returns a hash with date and key string values' do
expect(@breaker.crack_hard(@cyphertext).values.all?{|v|v.class == String}).to eq(true)
end
it 'updates cypher with key and date values' do
expect(@breaker.cypher.date).to eq(nil)
expect(@breaker.cypher.key).to eq(nil)
@breaker.crack_hard(@cyphertext)
expect(@breaker.cypher.date).to eq('010105')
expect(@breaker.cypher.key).to eq('02715')
end
end
describe ' #generate_dates' do
before(:each) do
@months = %w(01 02 03 04 05 06 07 08 09 10 11 12)
@days = ('1'..'31').to_a.map{|num| '%02d' % num}
@years = ('0'..'99').to_a.map{|num| '%02d' % num}
end
it 'returns an array' do
expect(@breaker.generate_dates).to be_a(Array)
end
it 'does not return any invalid month values' do
expect(@breaker.generate_dates.all?{|date|@months.include?(date.chars[2..3].join(''))}).to eq(true)
end
it 'does not return any invalid day values' do
expect(@breaker.generate_dates.all?{|date|@days.include?(date.chars[0..1].join(''))}).to eq(true)
end
# it 'does not return any invalid year values' do
# expect(@breaker.generate_dates.all?{|date|@years.include?([date.chars[4..5].join(''))}).to eq(true)
# end
end
end
end
|
class PharmacyUser < ActiveRecord::Base
belongs_to :pharmacy
belongs_to :user
attr_accessible :pharmacy_id, :user_id
end
|
class RecipesController < ApplicationController
before_action :set_recipe, only: [:show, :edit, :update, :destroy]
def index
@recipes = Recipe.all.order("created_at DESC")
end
def show
end
def new
@recipe = Recipe.new
end
def edit
end
def create
@recipe = Recipe.new(recipe_params)
respond_to do |format|
if @recipe.save
format.html { redirect_to @recipe, notice: 'Recipe was successfully created.' }
format.json { render :show, status: :created, location: @recipe }
else
format.html { render :new }
format.json { render json: @recipe.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if @recipe.update(recipe_params)
format.html { redirect_to @recipe, notice: 'Recipe was successfully updated.' }
format.json { render :show, status: :created, location: @recipe }
else
format.html { render :new }
format.json { render json: @recipe.errors, status: :unprocessable_entity }
end
end
end
def destroy
@recipe.destroy
respond_to do |format|
format.html { redirect_to recipes_url, notice: 'Recipe was successfully destroyed.' }
format.json { head :no_content }
end
end
private
def set_recipe
@recipe = Recipe.find(params[:id])
end
def recipe_params
params.require(:recipe).permit(:title, :description, :image, ingredients_attributes: [:id, :name, :_destroy], directions_attributes: [:id, :step, :_destroy])
end
end
|
#
# Cookbook Name:: ktc-razor
# Recipe:: default
#
#
install_path = node['razor']['install_path']
directory ::File.join(install_path + "/lib/project_razor/model/ubuntu/", "precise_ktc") do
mode "0755"
end
%w[
precise_ktc/boot_install.erb
precise_ktc/boot_local.erb
precise_ktc/kernel_args.erb
precise_ktc/os_boot.erb
precise_ktc/os_complete.erb
precise_ktc/preseed.erb
].each do |model_file|
cookbook_file ::File.join(install_path + "/lib/project_razor/model/ubuntu/", model_file) do
source model_file
mode "0644"
end
end
cookbook_file ::File.join(install_path + "/lib/project_razor/model/", "ubuntu_precise_ktc.rb") do
source "ubuntu_precise_ktc.rb"
mode "0644"
end
directory ::File.join(install_path + "/lib/project_razor/model/ubuntu/", "precise_ktc_ip") do
mode "0755"
end
%w[
precise_ktc_ip/boot_install.erb
precise_ktc_ip/boot_local.erb
precise_ktc_ip/kernel_args.erb
precise_ktc_ip/os_boot.erb
precise_ktc_ip/os_complete.erb
precise_ktc_ip/preseed.erb
].each do |model_file|
cookbook_file ::File.join(install_path + "/lib/project_razor/model/ubuntu/", model_file) do
source model_file
mode "0644"
end
end
cookbook_file ::File.join(install_path + "/lib/project_razor/model/", "ubuntu_precise_ktc_ip.rb") do
source "ubuntu_precise_ktc_ip.rb"
mode "0644"
end
directory ::File.join(install_path + "/lib/project_razor/model/ubuntu/", "precise_lldp") do
mode "0755"
end
%w[
precise_lldp/boot_install.erb
precise_lldp/boot_local.erb
precise_lldp/kernel_args.erb
precise_lldp/os_boot.erb
precise_lldp/os_complete.erb
precise_lldp/preseed.erb
].each do |model_file|
cookbook_file ::File.join(install_path + "/lib/project_razor/model/ubuntu/", model_file) do
source model_file
mode "0644"
end
end
cookbook_file ::File.join(install_path + "/lib/project_razor/model/", "ubuntu_precise_lldp.rb") do
source "ubuntu_precise_lldp.rb"
mode "0644"
end
directory ::File.join(install_path + "/lib/project_razor/model/ubuntu/", "precise_lldp_mnode") do
mode "0755"
end
%w[
precise_lldp_mnode/boot_install.erb
precise_lldp_mnode/boot_local.erb
precise_lldp_mnode/kernel_args.erb
precise_lldp_mnode/os_boot.erb
precise_lldp_mnode/os_complete.erb
precise_lldp_mnode/preseed.erb
].each do |model_file|
cookbook_file ::File.join(install_path + "/lib/project_razor/model/ubuntu/", model_file) do
source model_file
mode "0644"
end
end
root_path = install_path + "/lib/project_razor/model/"
cookbook_file ::File.join(root_path, "ubuntu_precise_lldp_mnode.rb") do
source "ubuntu_precise_lldp_mnode.rb"
mode "0644"
end
|
class EntriesController < ApplicationController
def index
now = DateTime.now
@pr = Project.find(params[:project_id])
@entries = @pr.entries_for_month(2015, 7)
@month_hours = @pr.total_hours_in_month(now.year, now.month)
render ("index")
end
def new
@pr = Project.find params[:project_id]
@entr = @pr.entries.new
render("new")
end
def create
@pr = Project.find(params[:project_id])
@entr = @pr.entries.new(entry_params)
if @entr.save
redirect_to(project_entries_path)
else
render("new")
end
end
def edit
@pr = Project.find params[:project_id]
@entr = @pr.entries.find(params[:id])
render("edit")
end
def update
@pr = Project.find params[:project_id]
@entr = @pr.entries.find(params[:id])
if @entr.update_attributes(entry_params)
redirect_to(project_entries_path)
else
render("edit")
end
# @entr = @pr.entries.find(params[:id])
# if @entr.save
# redirect_to(project_entries_path)
# else
# render("edit")
# end
#retrieve the entry from the databases
#if input is valid, update
#redirect to list of entries for project
#otherwise show errors to user
#show the edit form again
end
private
def entry_params
return params.require(:entry).permit(:hours, :minutes, :date, :comment )
end
end
|
class FiguresController < ApplicationController
get '/figures' do
erb :'figures/index'
end
get '/figures/new' do
erb :'figures/new'
end
get '/figures/:id/edit' do
@figure = Figure.find(params[:id])
erb :'/figures/edit'
end
get '/figures/:id' do
@figure = Figure.find(params[:id])
erb :'/figures/show'
end
post '/figures/new' do
figure = Figure.new(name: params[:figure][:name])
if params[:figure][:title_ids]
figure.titles = params[:figure][:title_ids].map { |title_id| Title.find title_id }
end
if params[:title][:name].length > 0
figure.titles << Title.find_or_create_by(name: params[:title][:name])
end
if params[:figure][:landmark_ids]
figure.landmarks = params[:figure][:landmark_ids].map { |landmark_id| Landmark.find landmark_id }
end
if params[:landmark][:name].length > 0
figure.landmarks << Landmark.find_or_create_by(name: params[:landmark][:name])
end
figure.save
end
patch '/figures/:id' do
figure = Figure.find(params[:id])
figure.name = params[:figure][:name]
if params[:figure][:title_ids]
figure.titles = params[:figure][:title_ids].map { |title_id| Title.find title_id }
end
if params[:title][:name].length > 0
figure.titles << Title.find_or_create_by(name: params[:title][:name])
end
if params[:figure][:landmark_ids]
figure.landmarks = params[:figure][:landmark_ids].map { |landmark_id| Landmark.find landmark_id }
end
if params[:landmark][:name].length > 0
figure.landmarks << Landmark.find_or_create_by(name: params[:landmark][:name])
end
figure.save
# flash[:message] = 'Successfully updated song.'
redirect to "/figures/#{figure.id}"
end
end
|
# A binary search tree was created by traversing through an array from left to right
# and insterting each element. Given a binary search tree with distinct elements, print all possible
# array that could have led to this tree.
# given:
# 2
# 1 3
# return [2,1,3], [2,3,1]
require_relative 'node.rb'
# can do this recursively to build arrays based on lowest node.
def bst_sequence(node)
result = []
children_array = node.children.permutation.to_a
children_array.map do |array|
array.unshift(node)
end
end
# merge 2 arrays while maintaining order
# [0,1] [a,b]
# [0,1,a,b], [0,a,1,b], [0,a,b,1], [a,0,1,b], [a,b,0,1], [a,0,b,1]
def weave_array(array1, array2)
result = []
idx1 = 0
idx2 = 1
while #some condition
temp_array = []
while idx1 < array1.length && idx2 < array2.length
if
temp_array.push(array1[idx1])
idx1 += 1
end
if
temp_array.push(array2[idx2])
idx2 += 1
end
end
while idx1 < array1.length
temp_array.push(array1[idx1])
idx1 += 1
end
while idx2 < array2.length
temp_array.push(array1[idx2])
idx2 += 1
end
result.push(temp_array)
end
result
end
|
class VersionsController < ApplicationController
layout "application"
def show
@version = PaperTrail::Version.find(params[:id])
end
def index
@html_title = "Recent Activity"
@versions = PaperTrail::Version.order(:created_at => :desc).paginate(:page => params[:page],
:per_page => 50)
@title = "Recent Activity For Everything"
@linktomap = true
render :action => 'index'
end
def for_user
user_id = params[:id].to_i
@user = User.where(id: user_id).first
if @user
@html_title = "Activity for " + @user.login.capitalize
@title = "Recent Activity for User " +@user.login.capitalize
else
@html_title = "Activity for not found user #{params[:id]}"
@title = "Recent Activity for not found user #{params[:id]}"
end
order_options = "created_at DESC"
@versions = PaperTrail::Version.where(:whodunnit => user_id).order(order_options).paginate(:page => params[:page],
:per_page => 50)
render :action => 'index'
end
def for_map
@selected_tab = 5
@current_tab = "activity"
@map = Map.find(params[:id])
@html_title = "Activity for Map " + @map.id.to_s
order_options = "created_at DESC"
@versions = PaperTrail::Version.where("item_type = 'Map' AND item_id = ?", @map.id).order(order_options).paginate(:page => params[:page], :per_page => 20)
@title = "Recent Activity for Map "+params[:id].to_s
respond_to do | format |
if request.xhr?
@xhr_flag = "xhr"
format.html { render :layout => 'tab_container' }
else
format.html {render :layout => 'application' }
end
format.rss {render :action=> 'index'}
end
end
def for_map_model
@html_title = "Activity for All Maps"
order_options = "created_at DESC"
@versions = PaperTrail::Version.where(:item_type => 'Map').order(order_options).paginate(:page => params[:page], :per_page => 20)
@title = "Recent Activity for All Maps"
render :action => 'index'
end
def revert_map
@version = PaperTrail::Version.find(params[:id])
if @version.item_type != "Map"
flash[:error] = "Sorry this is not a map"
return redirect_to :activity_details
else
map = Map.find(@version.item_id)
reified_map = @version.reify(:has_many => true)
new_gcps = reified_map.gcps.to_a
map.gcps = new_gcps
flash[:notice] = "Map reverted!"
return redirect_to :activity_details
end
end
def revert_gcp
@version = PaperTrail::Version.find(params[:id])
if @version.item_type != "Gcp"
flash[:error] = "Sorry this is not a GCP"
return redirect_to :activity_details
else
if @version.event == "create"
if Gcp.exists?(@version.item_id.to_i)
gcp = Gcp.find(@version.item_id.to_i)
gcp.destroy
flash[:notice] = "GCP Reverted and Deleted!"
return redirect_to :activity_details
end
else
gcp = @version.reify
gcp.save
flash[:notice] = "GCP Reverted!"
return redirect_to :activity_details
end
end
end
end
|
require 'erector'
require 'omf-web/data_source_proxy'
module OMF::Web::Theme
class AbstractPage < Erector::Widget
depends_on :js, '/resource/vendor/stacktrace/stacktrace.js'
depends_on :js, '/resource/vendor/require/require.js'
depends_on :js, '/resource/vendor/underscore/underscore.js'
depends_on :js, '/resource/js/app.js'
depends_on :js, '/resource/vendor/jquery/jquery.js'
depends_on :js, '/resource/vendor/backbone/backbone.js'
depends_on :js, "/resource/theme/abstract/abstract.js"
#depends_on :js, 'http://echarts.baidu.com/build/dist/echarts.js'
depends_on :js, '/resource/vendor/echarts/echarts.js'
attr_reader :opts
def self.add_depends_on(type, url)
depends_on type.to_sym, url
end
def self.render_data_sources(widgets)
dss = Set.new
widgets.each do |w|
if w.respond_to? :collect_data_sources
w.collect_data_sources(dss)
end
end
return if dss.empty?
js = dss.map do |ds|
dspa = OMF::Web::DataSourceProxy.for_source(ds)
dspa.collect do |dsp|
dsp.reset()
dsp.to_javascript(ds)
end.join("\n")
end
# Calling 'javascript' doesn't seem to work here. No idea why, so let's do it by hand
%{
<script type="text/javascript">
// <![CDATA[
require(['omf/data_source_repo'], function(ds) {
#{js.join("\n")}
});
// ]]>
</script>
}
end
def initialize(widget, opts)
#puts "KEYS>>>>> #{opts.keys.inspect}"
super opts
@widget = widget
@opts = opts
end
def content
end
def render_flash
return unless @flash
if @flash[:notice]
div :class => 'flash_notice flash' do
text @flash[:notice]
end
end
if @flash[:alert]
div :class => 'flash_alert flash' do
a = @flash[:alert]
if a.kind_of? Array
ul do
a.each do |t| li t end
end
else
text a
end
end
end
end # render_flesh
# Return an array of widgets to collect data sources from
#
def data_source_widgets
[@widget]
end
def render_data_sources
return unless @widget
require 'omf_oml/table'
require 'set'
dss = Set.new
data_source_widgets.each do |w|
w.collect_data_sources(dss)
end
return if dss.empty?
js = dss.map do |ds|
render_data_source(ds)
end
# Calling 'javascript' doesn't seem to work here. No idea why, so let's do it by hand
%{
<script type="text/javascript">
// <![CDATA[
require(['omf/data_source_repo'], function(ds) {
#{js.join("\n")}
});
// ]]>
</script>
}
end
def render_data_source(ds)
dspa = OMF::Web::DataSourceProxy.for_source(ds)
dspa.collect do |dsp|
dsp.reset()
dsp.to_javascript(ds)
end.join("\n")
end
def render_additional_headers
#"\n\n<link href='/resource/css/incoming.css' media='all' rel='stylesheet' type='text/css' />\n"
end
def collect_data_sources(dsa)
dsa
end
def to_html(opts = {})
page_title = @page_title # context may get screwed up below, so put title into scope
b = super
if @opts[:request].params.key?('embedded')
b
else
e = render_externals << render_additional_headers << render_data_sources
r = Erector.inline do
#instruct
text! '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
html do
head do
title page_title || "OMF WEB"
meta 'http-equiv' => "content-type", :content => "text/html; charset=UTF8"
#<link rel="shortcut icon" href="/resource/theme/@theme/img/favicon.ico">
#<link rel="apple-touch-icon" href="/resource/theme/@theme/img/apple-touch-icon.png">
text! e.join("\n")
end
body do
text! b
end
end
end
r.to_html(opts)
end
end
end # class AbstractPage
end # OMF::Web::Theme
|
class CreateChildTasks < ActiveRecord::Migration[6.0]
def change
create_table :child_tasks do |t|
t.string :title
t.datetime :child_deadline
t.integer :possibility
t.integer :done
t.integer :result
t.integer :self_motivation
t.string :explanation
t.references :parent_task, null: false, foreign_key: true
t.timestamps
end
end
end
|
class Example < ActiveRecord::Base
validates :name, presence: true, length: {minimum: 3, maximum: 50}
validates :url, presence: true, length: {minimum: 10, maximum: 300}
validates :giturl, presence: true, length: {minimum: 10, maximum: 300}
validates :description, presence: true, length: {minimum: 10, maximum: 300}
end
|
##################################################################################
#
# config.rb
#
# [更新日]
# - 2014/01/15
#
# [解説]
# - Sass & Compass 設定ファイル
#
# [参考URL]
# - http://dev.classmethod.jp/ria/html5/web-desiner-corder-scss-config/
#
##################################################################################
##################################################################################
# プロジェクトのルート位置を指定。デフォルトは「/」。
# この設定は以下の指定を明記していない場合に影響を与えます。(各項目を明記している場合は使われません)
# http_stylesheets_dir
# http_images_dir
# http_javascripts_dir
# http_fonts_dir
##################################################################################
http_path = "../"
##################################################################################
# cssファイルのコンパイル先 ・・・ config.rbを置いた位置からの相対指定でCSSを置いているディレクトリを指定
##################################################################################
css_dir = "../lib/css"
##################################################################################
# sassファイルの配置先 ・・・ config.rbを置いた位置からの相対指定でsassを置いているディレクトリを指定
##################################################################################
sass_dir = "../lib/sass"
##################################################################################
# CSS内で利用する画像の配置先 ・・・ config.rbを置いた位置からの相対指定で画像を置いているディレクトリを指定
# scss内で、background: image-url(); を利用した際、ここで指定したディレクトリ位置が先頭に挿入されます。
##################################################################################
images_dir = "../lib/img"
##################################################################################
# compassによるsprite 実行時の、結合した画像保存先
##################################################################################
#generated_images_dir = "img"
##################################################################################
# scss内で background: image-url(); で画像を利用した際、デフォルトでは画像へのパスが相対パスになるが、
# http_images_pathを指定することで、パス記述を任意の場所に変更することが可能。
##################################################################################
#http_images_path = "img"
##################################################################################
# compassによるspriteで結合作成した画像へのパスは、デフォルトでは相対パスになるが、
# http_generated_images_pathを指定することで、パス記述を任意の場所に変更することが可能。
##################################################################################
#http_generated_images_path = "img"
##################################################################################
# JSの配置先 ・・・ プロジェクトルートからの相対指定でJavaScriptを置いているディレクトリを指定
##################################################################################
javascripts_dir = "../lib/js"
##################################################################################
# コンパイル時にデバッグ用のコメント行番号を挿入[true,false]
##################################################################################
line_comments = false
##################################################################################
# コンパイル時に .sass-cacheディレクトリを作るか?[true,false]
#
# [解説]
# Sassを利用すると.sass-cacheという名前のフォルダ名に
# キャッシュファイルが自動で生成されます
##################################################################################
cache = false
##################################################################################
# background: image-url(); をしたときに自動的にタイムスタンプを付加するか?
# デフォルトでは付加されます。付加したくない場合はコメントアウト
##################################################################################
asset_cache_buster :none
##################################################################################
# コンパイル後のCSSのスタイル指定
# [expanded,nested,compact,compressed]
##################################################################################
#
# expanded: 通常
# nested: デフォルトだとこの指定。Sassファイルのネストの深さが引き継がれます。
# compact: セレクタと属性を1行でまとめる
# compressed: 可能な限り圧縮
#
##################################################################################
output_style = :expanded
#output_style = :nested
#output_style = :compact
#output_style = :compressed
##################################################################################
# ブラウザでSassをデバッグするためのデバッグコメントを挿入
#
# [解説]
# 各ブラウザにアドオン・拡張機能 をインストールすることで、Sassファイルのデバッグが可能になります。
# FirefoxはアドオンからFirebugと FireSassをインストール
# ChromeはWeb StoreからSASS Inspectorをインストール
##################################################################################
#sass_options = {:debug_info => true}
|
# 1. The number of orphan planets (no star). TypeFlag = 3
# 2. The name (planet identifier) of the planet orbiting the hottest star.
# 3. A timeline of the number of planets discovered per year grouped by size. Use the following groups: “small� is less than 1 Jupiter radii, “medium� is less than 2 Jupiter radii, and anything bigger is considered “large�. For example, in 2004 we discovered 2 small planets, 5 medium planets, and 0 large planets.
require 'minitest/autorun'
require_relative "exoplanetsdetails"
#sample Json "json_test.txt" is required to execute this file
class ExoPlanetsTest < Minitest::Test
def setup
@uri = "json_test.txt"
@exoplanet_results = ExoPlanets.new
end
def test_response_values
response = @exoplanet_results.planets_details(@uri)
assert response != nil
end
def test_response_values_is_array
response = @exoplanet_results.planets_details(@uri)
assert_kind_of Array, response
end
def test_predefined_answers_is_not_empty
response = @exoplanet_results.planets_details(@uri)
refute_empty response
end
end
|
class User < ActiveRecord::Base
attr_accessor :remember_token
validates :name, presence: true,
length: { maximum: 25 }
VALID_EMAIL_REGEX = /\A\w+@\w+\.\w+\z/i
before_save { self.email = self.email.downcase }
validates :email, presence: true,
length: { maximum: 255 },
format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
has_secure_password
validates :password, length: { minimum: 6 }, allow_nil: true
has_many :croaks, dependent: :destroy
# hash digest for a string
def User.digest(string)
cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine.cost
BCrypt::Password.create(string, cost: cost)
end
# get a new token for creating a new remember_token on log in
def User.new_token
SecureRandom.urlsafe_base64
end
#generate the feed of croaks for a user
def feed
Croak.where("user_id = ?", self.id).includes(:user)
end
#set the remember_digest in the model until next log in
def remember
self.remember_token = User.new_token
self.update_attribute :remember_digest, User.digest(remember_token)
end
#clear remember_digest
def forget
self.update_attribute :remember_digest, nil
end
# returns whether the user is authenticated with a valid remember_token from the session cookie
def authenticated?(remember_token)
return false if self.remember_digest.nil?
BCrypt::Password.new(self.remember_digest).is_password?(remember_token)
end
end |
class RenameColumnTypeInMedicineSampleToTypemedicine < ActiveRecord::Migration[5.0]
def change
rename_column :medicine_samples, :type, :typemedicine
end
end
|
class CargoTrain < Train
TYPE = 'cargo'
private
def valid_car_type?(car)
car.class == CargoCar
end
end |
module CopyPeste
module Require
module Mixin
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
# @note
# - Only the first call of a namespace will require the
# associated file.
# - If there is not a file named as the folder, it is not working.
# @example
# Directory structure:
# |- a
# |- b
# | |- c
# | | |-d
# | | | `- e.rb
# | | `- d.rb
# | |- c.rb
# `- g.rb
#
# Code:
# module A
# include CopyPeste::Require::Mixin
# end
#
# A::B
# # will require the file /a/b.rb on the first call only
#
# A::B::C::D::E
# # will require the files /a/b/c.rb, /a/b/c/d.rb, /a/b/c/d/e.rb
#
def const_missing(constant)
constant_name = constant.to_s.underscore
constant_declaration_path = File.expand_path(
File.join namespace_path, constant_name
)
# If the file is available in the folder of the namespace,
# it means it belongs to it.
if File.exists? constant_declaration_path + '.rb'
require constant_declaration_path
if self.const_defined? constant
constant = self.const_get constant
constant.include Require::Mixin
constant
else super
end
# If there isn't a file matching, the constant might belong to
# one namespace over it.
elsif outer = Module.nesting.find { |n| name.include_different? n.name }
outer.const_get constant
# Otherwise, that's not our concern.
else
super
end
end
# Generate namespaces paths recursively over each outer namespace
#
# @return [String]
def namespace_path
local_namespace, outer_namespace =
self.name.reverse.split('::', 2).map(&:reverse)
outer_constant = Kernel.const_get outer_namespace
outer_path = outer_constant.namespace_path
local_path = '/' + local_namespace.underscore
outer_path + local_path
end
end # !ClassMethods
end # !Mixin
end
end
|
class ZhishiNotification
ZHISHI_EVENTS = /new\.(?<type>question|user|answer|comment)/
attr_reader :resource, :wrapper_type
def initialize(payload)
@wrapper_type = payload['notification']['type']
@resource = Hashie::Mash.new(payload['notification'])
end
def match_notification_type
@match ||= ZHISHI_EVENTS.match(wrapper_type)
end
def zhishi_notification?
match_notification_type
end
def resource_type
match_notification_type[:type].capitalize
end
def type
"ZhishiWrapper::#{resource_type}".constantize
end
def deserialized_notification
type.new(resource)
end
def presenter
"#{resource_type}Presenter".constantize
end
def presentable_resource
@presentable ||= presenter.new(deserialized_notification)
end
end
|
class ManagedRecordMailer < ApplicationMailer
default template_path: 'mail/managed_records'
layout 'mail/admin'
def created
setup
return unless @manager.notifications.new_managed_record?
subject = I18n.translate(@record.model_name.i18n_key, scope: 'mail.managed_record.created.subject', record: @record.label)
puts "[MAIL] Sending new managed record email to #{@manager.name} for #{@record}"
mail(to: @manager.email, subject: subject)
end
private
def setup
if params[:record]
@record = params[:record]
@manager = @record.manager
else
managed_record = params[:managed_record]
@manager = managed_record.manager
@record = managed_record.record
end
create_session!
end
end
|
class MembershipsController < ApplicationController
before_filter :authenticate_user!
def destroy
@membership = Membership.find(params[:id])
if @membership.present?
@membership.destroy
end
flash[:notice] = "Removed Membership."
redirect_to root_url
end
private
def membership_params
params.require(:membership).permit(:user_id, :project_id) if params[:membership]
end
end
|
require 'spec_helper'
describe StoryMerge do
let(:command) { StoryMerge.new }
before { command.stub(:story_branch).and_return('62831853-tau-manifesto') }
subject { command }
its(:cmd) { should match /git merge/ }
shared_examples "story-merge with known options" do
subject { command }
it "should not raise an error" do
expect { command.parse }.not_to raise_error(OptionParser::InvalidOption)
end
end
describe "with no options" do
its(:cmd) { should match /git checkout master/ }
its(:cmd) do
msg = Regexp.escape("[##{command.story_id}]")
branch = command.story_branch
should match /git merge --no-ff --log -m "#{msg}" #{branch}/
end
end
describe "with the finish option" do
let(:command) { StoryMerge.new(['-f']) }
its(:cmd) do
msg = Regexp.escape("[Finishes ##{command.story_id}]")
branch = command.story_branch
should match /git merge --no-ff --log -m "#{msg}" #{branch}/
end
end
describe "with the delivers option" do
let(:command) { StoryMerge.new(['-d']) }
its(:cmd) do
msg = Regexp.escape("[Delivers ##{command.story_id}]")
branch = command.story_branch
should match /git merge --no-ff --log -m "#{msg}" #{branch}/
end
end
describe "with a custom development branch" do
let(:command) { StoryMerge.new(['development']) }
its(:cmd) { should match /git checkout development/ }
end
describe "with some unknown options" do
let(:command) { StoryMerge.new(['development', '-o', '-a', '-z', '--foo']) }
it_should_behave_like "story-merge with known options"
its(:cmd) { should match /-a -z --foo/ }
end
describe "command-line command" do
subject { `bin/git-story-merge --debug development` }
it { should match /git checkout development/ }
it { should match /git merge --no-ff --log/ }
end
end |
require 'wikipedia'
require 'vocabularise/wikipedia_handler'
require 'vocabularise/mendeley_handler'
require 'vocabularise/request_handler'
module VocabulariSe
HANDLE_INTERNAL_RELATED_TAGS = "internal:related_tags"
HANDLE_INTERNAL_RELATED_TAGS_MENDELEY = "internal:related_tags:mendeley"
HANDLE_INTERNAL_RELATED_TAGS_WIKIPEDIA = "internal:related_tags:wikipedia"
HANDLE_INTERNAL_RELATED_DOCUMENTS = "internal:related_docs"
#
#
#
class InternalRelatedTags < RequestHandler
handles HANDLE_INTERNAL_RELATED_TAGS
cache_result DURATION_NORMAL
# @arg "tag" (mandatory)
# @arg "limit" (optional)
process do |handle, query, priority|
@debug = true
rdebug "handle = %s, query = %s, priority = %s " % \
[ handle, query.inspect, priority ]
raise ArgumentError, "no 'tag' found" unless query.include? 'tag'
intag = query['tag']
raise ArgumentError, "'tag' must not be nil" if intag.nil?
inlimit = query['limit'].to_i
inlimit ||= 0
tags = Hash.new 0
rdebug "try mendeley"
# try mendeley
if tags.empty? then
mendeley_related = @crawler.request \
HANDLE_INTERNAL_RELATED_TAGS_MENDELEY,
{ "tag" => intag, "limit" => inlimit }
tags.merge!( mendeley_related ) do |key,oldval,newval|
oldval + newval
end
end
rdebug tags.inspect
rdebug "try wikipedia"
# try wikipedia
if tags.empty? then
wikipedia_related = @crawler.request \
HANDLE_INTERNAL_RELATED_TAGS_WIKIPEDIA,
{ "tag" => intag, "limit" => inlimit }
# backup for broken cache
if wikipedia_related.kind_of? Array then
wikipedia_related = Hash[*wikipedia_related.collect { |t|
[t, 1]
}.flatten]
end
tags.merge!( wikipedia_related ) do |key,oldval,newval|
oldval + newval
end
end
# or fail
# FIXME: cleanup common tags
tags.delete(intag)
rdebug "result tags = %s" % tags.inspect
return tags
end
end
#
#
#
class InternalRelatedTagsMendeley < RequestHandler
handles HANDLE_INTERNAL_RELATED_TAGS_MENDELEY
cache_result DURATION_NORMAL
process do |handle, query, priority|
@debug = true
rdebug "handle = %s, query = %s, priority = %s " % \
[ handle, query.inspect, priority ]
raise ArgumentError, "no 'tag' found" unless query.include? 'tag'
intag = query['tag']
raise ArgumentError, "'tag' must not be nil" if intag.nil?
inlimit = query['limit'].to_i
inlimit ||= 0
tags = Hash.new 0
# may fail
documents = @crawler.request \
HANDLE_MENDELEY_DOCUMENT_SEARCH_TAGGED,
{ "tag" => intag, "limit" => inlimit }
documents.each do |doc|
document_tags = doc.tags
rdebug "Merge document tags"
rdebug "common tags : %s" % tags.inspect
rdebug " doc tags : %s" % document_tags.inspect
document_tags.each do |tag|
words = tag.split(/\s+/)
if words.length > 1 then
words.each { |w| tags[w] += 1 }
else
tags[tag] += 1
end
end
rdebug "merged tags : %s" % tags.inspect
end
# FIXME: cleanup mendeley-specific tags
# remove tags with non alpha characters
tags.keys.each do |tag|
tags.delete(tag) if tag.strip =~ /:/ ;
end
return tags
end
end
#
#
#
class InternalRelatedTagsWikipedia < RequestHandler
handles HANDLE_INTERNAL_RELATED_TAGS_WIKIPEDIA
cache_result DURATION_NORMAL
# @arg "tag" (mandatory)
# @arg "limit" (optional)
process do |handle, query, priority|
@debug = true
rdebug "handle = %s, query = %s, priority = %s " % \
[ handle, query.inspect, priority ]
raise ArgumentError, "no 'tag' found" unless query.include? 'tag'
intag = query['tag']
raise ArgumentError, "'tag' must not be nil" if intag.nil?
inlimit = query['limit'].to_i
inlimit ||= 0
# FIXME: do something with limit
rdebug "intag = %s" % intag
tags = Hash.new 0
page_json = @crawler.request \
HANDLE_WIKIPEDIA_REQUEST_PAGE,
{ "page" => intag }
page = Wikipedia::Page.new page_json
return tags if page.nil?
return tags if page.links.nil?
page.links.each do |tag|
# prevent modification on a frozen string
ftag = tag.dup
# cleanup wikipedia semantics for links categories
ftag.gsub!(/ \(.*\)$/,'')
tags[ftag] += 1
end
return tags
end
end
#
#
#
class InternalRelatedDocuments < RequestHandler
handles HANDLE_INTERNAL_RELATED_DOCUMENTS
cache_result DURATION_NORMAL
# @arg "tag" (mandatory)
# @arg "limit" (optional)
process do |handle, query, priority|
@debug = true
rdebug "handle = %s, query = %s, priority = %s " % \
[ handle, query.inspect, priority ]
raise ArgumentError, "no 'tag_list' found" unless query.include? 'tag_list'
tag_list = query['tag_list']
rdebug "tag_list = %s" % tag_list
documents = []
tag_list.each do |tag|
rdebug "current tag = %s" % tag_list
tag_docs = @crawler.request HANDLE_MENDELEY_DOCUMENT_SEARCH_TAGGED,
{ "tag" => tag }
if documents.empty? then
documents = tag_docs
else
documents = documents.select{ |doc| tag_docs.include? doc }
end
#rdebug "documents = %s" % documents.inspect
end
return documents
end
end
end
|
class UsersController < ApplicationController
def create
if user_exists
render json: user
else
new_user = User.create(user_params)
if new_user
render json: new_user
else
render json: new_user.errors
end
end
end
def update
respond_to do |format|
if user.update(user_params)
render json: user
else
render json: user.errors
end
end
end
private
def user_params
params.permit(:email, :username, :avatar, :user_id)
end
def user
@user ||= User.find_by(email: params[:email])
end
def user_exists
User.exists?(email: params[:email])
end
end
|
###Collections Practice
collection_array = ["blake", "ashley", "scott"]
#1. sort the following array in ascending order
collection_array.sort
#2. sort the following array in descending order
collection_array.sort.reverse
#3. put the following array in reverse order
collection_array.reverse
#4. grab the second element in the array
collection_array.at(1)
#5. print each element of the array to the console
collection_array.each do |element|
prints "#{element} "
end
#6. create a new array in the following order
# ["blake", "ashley", "scott"]
# should transform into
# ["blake", "scott", "ashley"]
collection_array_new = []
collection_array_new[0] = collection_array[0]
collection_array_new[1] = collection_array[2]
collection_array_new[2] = collection_array[1]
# 7. using the following array create a hash where the elements in the array are the keys and the values of the hash are those elements with the 3rd character changed to a dollar sign.
# ["blake", "ashley", "scott"]
collection_array_hash={}
collection_array.each do |element|
collection_array_hash [element] = element.gsub(element[2], "$")
end
# 8. create a hash with two keys, "greater_than_10", "less_than_10" and their values will be an array of any numbers greater than 10 or less than 10 in the following array
new_hash = {}
array_to_sort = [100, 1000, 5, 2, 3, 15, 1, 1, 100 ]
new_hash[:greater_than_10] = array_to_sort.collect(|x| x>10)
new_hash[:less_than_10] = array_to_sort.collect(|x| x<10)
# 9. find all the winners and put them in an array
outcome = {:blake => "winner", :ashley => "loser", :caroline => "loser", :carlos => "winner"}
winners = []
outcome.each do |competitor, win|
winners << competitor if win == "winner"
end
# 10. add the following arrays
# [1,2,3] and [5,9,4]
[1,2,3].concat([5,9,4])
#11. find all words that begin with "a" in the following array
array_to_sort = ["apple", "orange", "pear", "avis", "arlo", "ascot" ]
array_to_sort.each do |item|
sorted_array =[]
if item[0].downcase = "a"
sorted_array << item
end
end
# 11. sum all the numbers in the following array
to_sum = [11,4,7,8,9,100,134]
to_total.reduce(:+)
#12. Add an "s" to each word in the array except for the 2nd element in the array?
to_be_pluralized = ["hand","feet", "knee", "table"]
to_be_pluralized.each
# CHALLENGE
# word count
# "The summer of tenth grade was the best summer of my life. I went to the beach everyday and we had amazing weather. The weather didnt really vary much and was always pretty hot although sometimes at night it would rain. I didnt mind the rain because it would cool everything down and allow us to sleep peacefully. Its amazing how much the weather affects your mood. Who would have thought that I could write a whole essay just about the weather in tenth grade. Its kind of amazing right? Youd think for such an interesting person I might have more to say but you would be wrong"
# Count how many times each word appears in my story.
# Tip: You'll need to use Hash.new(0) to do this rather than creating a hash using literal syntax like {}.
# song library
# convert the following array of song titles
# ["dave matthews band - tripping billies", "dave matthews band - #41", "calvin harris - some techno song", "avicii - some other dance song", "oasis - wonderwall", "oasis - champagne supernova"]
# to a nested hash of the form
# {:artist1 => :songs => [], :artist2 => :songs => []}
[] |
module Api
class OrdersController < ApplicationController
before_filter :order_params
def create
#{:order => {:total, :email, :phone, :address, :name, :last_name, :code},:line_items_attributes => [{:product_id, :price, :count}]}
logger.debug params[:order][:toral]
logger.debug params["order"]["toral"]
begin
@order = Order.create(params["order"])
if @order
render :json => {:status => :ok, :order_code => @order.code}
else
render :json => {:errors => Order.errors.messages}
end
rescue => e
render :json => {:error => e}
end
params.require(:order).permit!
end
def show
@order = Order.find_by_code(params[:id])
render :json => @order.as_json(:only =>[:code, :email, :address, :name, :last_name, :phone, :total], :methods => [:line_items])
end
private
def order_params
params.permit!
end
end
end |
class User
include Mongoid::Document
include Mongoid::Timestamps
attr_accessible :name, :email, :password, :password_confirmation, :remember_me, :subscription_plan_id, :use_dropbox
attr_accessible :trial_expires_at, as: :admin
field :name
field :xero_auth, type: Hash
field :xero_auth_expires_at, type: DateTime
field :synchronizing, type: Boolean, default: false
field :dropbox_synchronizing, type: Boolean, default: false
field :storage_limit, type: Integer, default: 1_000_000_000
field :storage_utilization, type: Integer, default: 0
field :trial_expires_at, type: DateTime, default: lambda{ Time.now }
field :paypal_payment_token
field :paypal_customer_token
field :paypal_recurring_profile_token
field :paypal_billing_date, type: Date
field :use_dropbox, type: Boolean, default: false
field :dropbox_access_token, type: Hash
validates :name, presence: true
validates :subscription_plan_id, presence: true
validates :use_dropbox, presence: true
validates :trial_expires_at, presence: true
validate :check_plan_limit
def check_plan_limit
return if !subscription_plan_id
if subscription_plan.storage_limit < storage_utilization
errors.add(:subscription_plan_id, "You don't have enough space available to downgrade. Free up some space and try again.")
end
end
belongs_to :subscription_plan
has_many :documents, dependent: :destroy
has_many :contacts, dependent: :destroy
after_create :notify_owner
def notify_owner
if Rails.env == 'production'
MailWorker.perform_async('Notifier', 'notify_owner', id)
else
MailWorker.new.perform('Notifier', 'notify_owner', id)
end
end
before_destroy :cancel_payments
def cancel_payments
return if !paypal_customer_token
paypal = PaypalPayment.new(self)
paypal.cancel
rescue
nil
end
before_create :setup
def setup
self.trial_expires_at = Time.now + 7.days
end
before_save :setup_plan
def setup_plan
if subscription_plan_id_changed?
self.storage_limit = subscription_plan.storage_limit
if paypal_customer_token and paypal_recurring_profile_token
paypal = PaypalPayment.new(self)
paypal.cancel
end
self.paypal_recurring_profile_token = nil
self.paypal_customer_token = nil
self.paypal_payment_token = nil
end
end
def xero_authenticated?
if !xero_auth_expires_at.blank?
( xero_auth_expires_at - 10.minutes ) > Time.now
else
false
end
end
def dropbox_authenticated?
!!self.dropbox_access_token
end
def expire_xero_token!
self.xero_auth_expires_at = Time.now
save
end
def trial?
trial_expires_at >= Time.now
end
def available_storage
storage_limit - storage_utilization
end
def used_storage_percentile
( storage_utilization.to_f / storage_limit.to_f ).round(2)
end
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# :confirmable, :lockable
## Database authenticatable
field :email, :type => String, :default => ""
field :encrypted_password, :type => String, :default => ""
validates_presence_of :email
validates_presence_of :encrypted_password
## Recoverable
field :reset_password_token, :type => String
field :reset_password_sent_at, :type => Time
## Rememberable
field :remember_created_at, :type => Time
## Trackable
field :sign_in_count, :type => Integer, :default => 0
field :current_sign_in_at, :type => Time
field :last_sign_in_at, :type => Time
field :current_sign_in_ip, :type => String
field :last_sign_in_ip, :type => String
## Confirmable
field :confirmation_token, :type => String
field :confirmed_at, :type => Time
field :confirmation_sent_at, :type => Time
field :unconfirmed_email, :type => String # Only if using reconfirmable
## Lockable
field :failed_attempts, :type => Integer, :default => 0 # Only if lock strategy is :failed_attempts
field :unlock_token, :type => String # Only if unlock strategy is :email or :both
field :locked_at, :type => Time
## Token authenticatable
# field :authentication_token, :type => String
end
|
module RedPenTeacher
class DiffMarker < BaseMarker
def initialize(true_answer)
super(lambda do |answer|
answer == true_answer
end)
end
end
end
|
# frozen_string_literal: true
class RolesController < ApplicationController
def index
# Returns all tasks in order by id
@roles = Role.order(id: :asc)
end
def new
@roles = Role.new
end
def show
@roles = Role.find(params[:id])
end
def create
redirect_to '/roles' if current_user.role != 'admin' && current_user.role != 'moderator'
@roles = Role.new(role_params)
if @roles.save
redirect_to '/roles'
else
render :new
end
end
def destroy
@roles = Role.find(params[:id])
@roles.destroy
redirect_to @roles
end
def role_params
params.require(:role).permit(:role_name)
end
end
|
require 'spec_helper'
RSpec.describe 'log parser printer' do
it 'prints out a given data array with header and description sugar' do
data_array = [
[:b, 1],
[:a, 2],
]
description = 'LogParserPrinter test description'
follower_text = 'test count'
ordering_description = 'ascending order'
expected_output = [
"#{description} ordered in #{ordering_description}",
"#{data_array[0][0]} #{data_array[0][1]} #{follower_text}",
"#{data_array[1][0]} #{data_array[1][1]} #{follower_text}",
"#{SmartLogParser::LogParserPrinter::DELIMITER}"
].join("\n")
expect{ SmartLogParser::LogParserPrinter.print_visits(data_array, description, follower_text, ordering_description) }.to output(expected_output + "\n").to_stdout
end
end
|
module ApplicationHelper
def public_article_path(article)
issue = article.issue
year = issue.year
super year: year.year, issue: issue.number, article_slug: article.slug
end
def language_attributes
{lang: I18n.locale}
end
def page_title(page=nil)
title = "Stuyvesant Spectator"
slogan = "The Pulse of the Student Body"
sep = "|"
if page.nil?
"#{title} #{sep} #{slogan}"
else
"#{page} #{sep} #{title}"
end
end
def body_attrs
{ class: body_class }
end
private
def is_home
current_page?(root_url)
end
def is_dept
params[:controller] == "public/departments" and params[:action] == "show"
end
def is_search
false
end
def is_empty_search
false
end
def is_paged
false
end
def is_article
params[:controller] == "public/articles" and params[:action] == "show"
end
def is_author
params[:controller] == "public/authors" and params[:action] == "show"
end
def body_class
classes = [:desktop]
if is_home
classes << :home
classes << :blog
end
classes << :archive if is_dept
if is_search
classes << :search
classes << is_empty_search ? :'search-no-results' : :'search-results'
end
classes << :paged if is_paged
if is_article
classes << :single
classes << :'single-post'
classes << "postid-#{@article.id}"
end
if is_dept
classes << :archive
classes << :category
classes << "category-#{@department.name.downcase}"
classes << "category-#{@department.id}"
end
if is_author
classes << :archive
classes << :author
classes << "author-#{@author.first.downcase}#{@author.last.downcase}"
classes << "author-#{@author.id}"
end
if user_signed_in?
classes << :'logged-in'
end
return classes
end
end
|
#!/usr/bin/env ruby
require 'json'
require 'pry'
require_relative 'lib/run'
require_relative 'lib/git_helpers'
class MergeAndPush
SLEEP = 20
def initialize(branch)
@branch = branch
end
def checks_passed?(timeout:)
start_time = Time.now
repo_name = GitHelpers::repo_name
github_org = GitHelpers::github_org
commit = R::run("git rev-parse #{@branch}")[0].strip
while Time.now - start_time < timeout
output = R::run(%{curl --silent -H "Authorization: token #{ENV['GITHUB_OAUTH_TOKEN']}" https://api.github.com/repos/#{github_org}/#{repo_name}/commits/#{commit}/status})[0]
data = JSON.parse(output)
state = data['state']
if state == 'success'
return true
elsif state == 'pending'
builds = data['statuses'].select { |s| s['context'].start_with? "#{github_org}-#{repo_name}" }
build_statuses = builds.map { |s| s['state'] }
if !build_statuses.all? { |bs| bs=='success' }
puts "Got pending build status, sleeping for #{SLEEP} seconds and trying again"
sleep(SLEEP)
else
non_builds = data['statuses'] - builds
non_passing = non_builds.select { |s| s['state'] != 'success' }
$stderr.puts "*FAILURE*: Checks that need to pass: #{non_passing.map { |s| s['context'] }}"
return false
end
else
raise "Unknown state: #{state}"
end
end
$stderr.puts "*FAILURE* Checks didn't pass after #{timeout} second timeout!"
return false
end
private def check
if !ENV['GITHUB_OAUTH_TOKEN']
raise "Need GITHUB_OAUTH_TOKEN env var!"
end
end
def run
check
if R::run('git status -s')[0] != ''
raise "Can't run w/ local changes"
end
R::run_out 'git checkout master'
if !R::run('git status -uno')[0].include? 'up-to-date'
raise 'master is not up-to-date with origin, aborting!'
end
if !R::run('git branch')[0].split("\n").map { |f| f.strip }.any? { |f| f == @branch }
raise "No branch #{@branch} found"
end
timeout = 10*60
if checks_passed?(timeout: timeout)
R::run_out 'git pull'
R::run_out "git merge --no-ff #{@branch}"
R::run_out 'git push'
puts "Push successful, deleting branch #{@branch}"
R::run_out "git branch -d #{@branch}"
R::run_out "git push origin --delete #{@branch}"
R::run_out %{noti -t "Merge and push #{@branch}" -m "Merged and Pushed!"}
return true
else
R::run_out %{noti -t "Merge and push #{@branch}" -m "Checks didn't pass!"}
return false
end
end
end
if __FILE__== $0
success = MergeAndPush.new(ARGV[0]).run
exit(success ? 0 : 1)
end |
require 'socket'
namespace :data do
namespace :load do
desc "Cache data contained in the ECHO 10 format to return with granule results"
task :echo10 => ['environment'] do
puts "Starting data:load:echo10"
log_error('data:load:echo10') do
CollectionExtra.load_echo10
end
end
desc "Data about granules in collections to return with granule results"
task :granules => ['environment'] do
puts "Starting data:load:granules"
log_error('data:load:granules') do
CollectionExtra.load
end
end
desc "Sync tags for services"
task :tags => ['environment'] do
puts "Starting data:load:tags"
log_error('data:load:tags') do
CollectionExtra.sync_tags
end
end
def log_error(task, &block)
begin
yield
rescue
job = CronJobHistory.new(task_name: task, last_run: Time.now, status: 'failed', message: "#{error.present? ? error.inspect : 'Null'}", host: Socket.gethostname)
job.save!
exit 1
else
job = CronJobHistory.new(task_name: task, last_run: Time.now, status: 'succeeded', host: Socket.gethostname)
job.save!
end
end
end
desc "Load data from ECHO"
task :load
Rake::Task['data:load'].enhance(['data:load:echo10', 'data:load:granules', 'data:load:tags'])
namespace :dump do
# Only dump the CollectionExtra model
task :environment do
ENV['MODEL'] = 'CollectionExtra'
end
# Gets run after db:seed:dump to ensure that seeds.rb is only loaded as needed
task :headers do
original_file = 'db/seeds.rb'
new_file = original_file + '.new'
File.open(new_file, 'w') do |f|
lines = ["Cmep::Engine.load_seed if defined?(Cmep)",
"load_extra = CollectionExtra.maximum('updated_at').to_i < #{CollectionExtra.maximum('updated_at').to_i}",
"!load_extra && puts('CollectionExtra seeds are already up-to-date')",
"load_extra && puts('Loading CollectionExtra seeds')",
"load_extra && CollectionExtra.destroy_all",
"load_extra && "
]
f.print lines.join("\n")
File.foreach(original_file) { |line| f.puts(line) }
end
File.rename(new_file, original_file)
end
end
end
if Rake::Task.task_defined?("db:seed:dump")
Rake::Task["db:seed:dump"].enhance(['data:dump:environment']) do
Rake::Task['data:dump:headers'].invoke
end
end
|
# write a method that takes one argument, a string containing one
# or more words
# and returns the given string with words that contain five
# or more characters reversed
# each string will consists of only letters and spaces
# spaces should be included only when more than one word is present
# Examples:
#
# puts reverse_words('Professional') # => lanoisseforP
# puts reverse_words('Walk around the block') # => Walk dnuora the kcolb
# puts reverse_words('Launch School') # => hcnuaL loohcS
def reverse_words(string)
string.split.each do |word|
word.reverse! if word.length > 4
end.join(" ")
end
puts reverse_words('Professional')
puts reverse_words('Walk around the block')
puts reverse_words('Launch School') |
module Topographer
class Importer
module Strategy
class CreateOrUpdateRecord < Topographer::Importer::Strategy::Base
def import_record (source_data)
mapping_result = mapper.map_input(source_data)
search_params = mapping_result.data.slice(*mapper.key_fields)
model_instances = mapper.model_class.where(search_params)
if model_instances.any?
model_instance = model_instances.first
else
model_instance = mapper.model_class.new(search_params)
end
generate_messages(model_instance, search_params)
model_instance.attributes = mapping_result.data
model_instance.valid?
model_errors = model_instance.errors.full_messages
status = get_import_status(mapping_result, model_errors)
model_instance.save if should_persist_import?(status)
status
end
def success_message
@success_message
end
def failure_message
@failure_message
end
private
def generate_messages(model_instance, search_params)
if model_instance.new_record?
@success_message = 'Imported record'
@failure_message = 'Import failed'
else
params_string = search_params.map { |k, v| "#{k}: #{v}" }.join(', ')
@success_message = "Updated record matching `#{params_string}`"
@failure_message = "Update failed for record matching `#{params_string}`"
end
end
end
end
end
end
|
class GeojsonUploader < CarrierWave::Uploader::Base
FILENAME = 'meditation-venues.geojson'
# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounted:
def store_dir
'geojson'
end
def cache_dir
"#{Rails.root}/tmp/uploads"
end
# Replace all file names with a unique random string
def filename
FILENAME
end
end
|
# logicmonitor.rb
# Contains classes used by various providers in the LogicMonitor Puppet Module
# === Authors
#
# Sam Dacanay <sam.dacanay@logicmonitor.com>
# Ethan Culler-Mayeno <ethan.culler-mayeno@logicmonitor.com>
#
# Copyright 2016 LogicMonitor, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'net/http'
require 'net/https'
require 'uri'
require 'openssl'
require 'base64'
require 'json'
require 'date'
class Puppet::Provider::Logicmonitor < Puppet::Provider
# Supported HTTP Methods
HTTP_POST = 'POST'
HTTP_GET = 'GET'
HTTP_PUT = 'PUT'
HTTP_PATCH = 'PATCH'
HTTP_DELETE = 'DELETE'
# Supported Collector Architectures
LINUX_32 = 'linux32'
LINUX_64 = 'linux64'
# Device API endpoints
DEVICE_ENDPOINT = '/device/devices/%d'
DEVICES_ENDPOINT = '/device/devices'
DEVICE_PROPERTIES_ENDPOINT = '/device/devices/%d/properties'
# Device Group API endpoints
DEVICE_GROUP_ENDPOINT = '/device/groups/%d'
DEVICE_GROUPS_ENDPOINT = '/device/groups'
DEVICE_GROUP_PROPERTIES_ENDPOINT = '/device/groups/%d/properties'
# Collector API endpoints
COLLECTOR_ENDPOINT = '/setting/collectors/%d'
COLLECTORS_ENDPOINT = '/setting/collectors'
COLLECTOR_DOWNLOAD_ENDPOINT = '/setting/collectors/%d/installers/%s'
# Execute a RESTful request to LogicMonitor
# endpoint: RESTful endpoint to request
# http_method: HTTP Method to use for RESTful request
# query_params: Query Parameters to use in request (to modify results)
# data: JSON data to send in HTTP POST RESTful requests
# download_collector: If we are executing a download the URL will be santaba/do instead of santaba/rest
def rest(connection, endpoint, http_method, query_params={}, data=nil, download_collector=false)
# Sanity Check on Endpoint
endpoint.prepend('/') unless endpoint.start_with?'/'
http_method = http_method.upcase
# Build URI and add query Parameters
uri = URI.parse("https://#{resource[:account]}.logicmonitor.com/santaba/rest#{endpoint}")
# For PATCH requests, we want to use opType replace so that device/device group
# properties set outside of the module don't get deleted
if http_method == HTTP_PATCH
query_params['opType'] = 'replace'
end
# URL Encode Query Parameters
uri.query = URI.encode_www_form query_params unless nil_or_empty?(query_params)
# Build Request Object
request = nil
if http_method == HTTP_POST
raise ArgumentError, 'Invalid data for HTTP POST request' if nil_or_empty? data
request = Net::HTTP::Post.new uri.request_uri, {'Content-Type' => 'application/json'}
request.body = data
elsif http_method == HTTP_PUT
raise ArgumentError, 'Invalid data for HTTP PUT request' if nil_or_empty? data
request = Net::HTTP::Put.new uri.request_uri, {'Content-Type' => 'application/json'}
request.body = data
elsif http_method == HTTP_PATCH
raise ArgumentError, 'Invalid data for HTTP PATCH request' if nil_or_empty? data
request = Net::HTTP::Patch.new uri.request_uri, {'Content-Type' => 'application/json'}
request.body = data
elsif http_method == HTTP_GET
request = Net::HTTP::Get.new uri.request_uri, {'Accept' => 'application/json'}
elsif http_method == HTTP_DELETE
request = Net::HTTP::Delete.new uri.request_uri, {'Accept' => 'application/json'}
else
debug("Error: Invalid HTTP Method: #{http_method}")
end
# Add Authentication Information to Request
request['Authorization'] = generate_token(endpoint, http_method, data)
# Execute Request and Return Response
if connection.nil?
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.start
else
http = connection
end
rate_limited = false
begin
response = http.request(request)
if response.code == '429'
rate_limited = true
debug "Error: Request Rate Limited, sleep 1 second, retry"
sleep 1
raise 'Rate Limited'
end
unless response.kind_of? Net::HTTPSuccess
alert "Request failed: endpoint: #{endpoint}, method: #{http_method}, data: #{data}, query_param: #{uri.query}, response code: #{response.code}, response body: #{response.body}"
raise "Request Failed"
end
rescue Exception => e
if rate_limited
retry
end
alert "Request Failed. http_method: #{http_method}, scheme: #{uri.scheme}, host: #{uri.host}, path: #{uri.path}, query: #{uri.query}, data: #{data}"
raise e
end
download_collector ? response.body : JSON.parse(response.body)
end
# Builds a Hash containing LogicMonitor-supported RESTful query parameters
# filter: Filters the response according to the operator and value specified. Example: 'id>4'
# fields: Filters the response to only include the following fields for each object
# size: The number of results to display
# patch_ields: If we are preparing to perform an HTTP PATCH, we need to specify which fields we are updating
def build_query_params(filter=[], fields=[], size=-1, patch_fields=[])
query_params = Hash.new
unless nil_or_empty?(filter)
query_params['filter'] = filter
end
unless nil_or_empty?(fields)
if fields.is_a? Array
query_params['fields'] = fields.join(',')
elsif fields.is_a? String
query_params['fields'] = fields
else
raise ArgumentError, 'Invalid fields parameter, must be string (single element) or array'
end
end
unless size <= 0
query_params['size'] = size
end
unless nil_or_empty?(patch_fields)
query_params['patchFields'] = patch_fields.join(',')
end
query_params
end
# Helper method to generate a LMv1 API Token
def generate_token(endpoint, http_method, data='')
timestamp = DateTime.now.strftime('%Q')
unsigned_data = "#{http_method.upcase}#{timestamp}#{data.to_s}#{endpoint}"
signature = Base64.strict_encode64(
OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha256'), resource[:access_key], unsigned_data)
).strip
"LMv1 #{resource[:access_id]}:#{signature}:#{timestamp}"
end
# Helper method to determine if an object is nil or empty
def nil_or_empty?(obj)
if obj.nil? || obj.empty?
return true
end
false
end
# Helper method to determine if LogicMonitor RPC response is successful
# resp: Response from LogicMonitor API
# multi: If there could be multiple items, we should make sure items are not nil/empty
# delete: If we are deleting something we expect data to be nil, so just check status
def valid_api_response?(resp, multi=false, delete=false)
if delete
if resp['status'] == 200
return true
end
end
if resp['status'] == 200 && !nil_or_empty?(resp['data'])
if multi
unless nil_or_empty?(resp['data']['items'])
return true
end
return false
end
return true
end
false
end
# Retrieve Agent by it's description field
# connection: connection to use for executing API request
# description: description of collector (usually defaults to its hostname)
# fields: any fields that should be returned specifically (defaults to nil)
def get_agent_by_description(connection, description, fields=nil)
agents_json = rest(connection,
COLLECTORS_ENDPOINT,
HTTP_GET,
build_query_params("description:#{description}", fields, 1))
valid_api_response?(agents_json, true) ? agents_json['data']['items'][0] : nil
end
# Retrieve Group via fullPath
# connection: connection to use for executing API request
# full_path: full path of group location (similar to file path)
# fields: fields needed in request (to reduce overhead we can limit what LogicMonitor responds with)
def get_device_group(connection, full_path, fields=nil)
group_json = rest(connection,
'device/groups',
HTTP_GET,
build_query_params("fullPath:#{full_path.sub(/^\//,'')}", fields, 1))
valid_api_response?(group_json, true) ? group_json['data']['items'][0] : nil
end
# Builds JSON for creating or updating a LogicMonitor device group
# full_path: full path of group location (similar to file path)
# description: description of device group
# properties: Hash containing name/value pairs for properties
# disable_alerting: Enable / Disable alerting for devices in this group
# parent_id: device group ID of parent group (root level device group ID == 1)
def build_group_json(full_path, description, properties, disable_alerting, parent_id)
path = full_path.rpartition('/')
group_hash = {'name' => path[2]}
group_hash['parentId'] = parent_id
group_hash['disableAlerting'] = disable_alerting
unless description.nil?
group_hash['description'] = description
end
custom_properties = Array.new
unless nil_or_empty?(properties)
properties.each_pair do |key, value|
custom_properties << {'name' => key, 'value' => value}
end
group_hash['customProperties'] = custom_properties
end
group_hash
end
# Handles creation of all device groups
# connection: connection to use for executing API request
# full_path: full path of group location (similar to file path)
# description: description of device group
# properties: Hash containing name/value pairs for properties
# disable_alerting: Enable / Disable alerting for devices in this group
def recursive_group_create(connection, full_path, description, properties, disable_alerting)
path = full_path.rpartition('/')
parent_path = path[0]
debug "Checking for parent device group: #{path[0]}"
parent_id = 1
unless nil_or_empty?(parent_path)
parent = get_device_group(connection, parent_path, 'id')
if nil_or_empty?(parent)
parent_ret = recursive_group_create(connection, parent_path, nil, nil, true)
unless parent_ret.nil?
parent_id = parent_ret
end
else
debug 'parent group exists'
parent_id = parent['id']
end
end
debug 'Creating Group: %s' % full_path
add_device_group_json = rest(connection,
DEVICE_GROUPS_ENDPOINT,
HTTP_POST,
nil,
build_group_json(full_path, description, properties, disable_alerting, parent_id).to_json)
add_device_group_json['data']['id'] if valid_api_response?(add_device_group_json)
end
end
|
# encoding: utf-8
#
# © Copyright 2013 Hewlett-Packard Development Company, L.P.
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
RSpec.configure do |config|
# read file contents of a file in fixtures/files/<filename>
def read_file(filename)
read_fixture(:file, filename)
end
def read_fixture(type, filename)
dir_name = type.to_s + "s" # simple pluralize
File.read(File.dirname(__FILE__) + "/../fixtures/#{dir_name}/#{filename}")
end
end
|
class Carta
attr_reader :numero, :pinta
def initialize(numero, pinta)
pinta.upcase!
pintas =['C', 'D', 'E', 'T']
if (numero >= 1 && numero <=13) && pintas.include?(pinta)
@numero = numero
@pinta = pinta
else
raise ArgumentError.new(' No es un argumento valido')
end
end
end
pintas = ['C', 'D', 'E', 'T']
array_cartas=[]
5.times do |i|
carta =Carta.new(Random.rand(1..13), pintas.sample)
array_cartas +=[carta]
end
print array_cartas |
Node = Struct.new(:type) do
attr_accessor :batch_size
attr_reader :stock
def initialize(*args)
super(*args)
@stock = 0
end
def build(quantity)
@stock += batch_size * quantity
end
def take_stock(max)
if max >= stock
used_stock = stock
@stock = 0
else
used_stock = max
@stock -= max
end
used_stock
end
end
Edge = Struct.new(:from, :to, :weight)
class Graph
attr_accessor :nodes
def initialize
@nodes = {}
@edges = []
end
def attach(from_type, to_type, from_quantity, to_quantity)
node_from = get_or_create_node(from_type)
node_to = get_or_create_node(to_type, to_quantity)
@edges << Edge.new(from_type, to_type, from_quantity)
end
def build_type(type, quantity = 1)
return quantity if type == 'ORE'
node = @nodes[type]
stock_used = node.take_stock(quantity)
missing = quantity - stock_used
return 0 if missing == 0
batches_to_build = (missing / node.batch_size.to_f).ceil
ore_needed = edges_to(type).sum do |edge|
batches_to_build.times.sum { build_type(edge.from, edge.weight) }
end
node.build(batches_to_build)
node.take_stock(missing)
ore_needed
end
private
def get_or_create_node(type, batch_size = nil)
node = @nodes[type] || Node.new(type)
node.batch_size = batch_size unless batch_size.nil?
@nodes[type] = node
node
end
def edges_to(type)
@edges.select { |edge| edge.to == type }
end
end
graph = Graph.new
ARGF.each_line.map(&:chomp).map do |line|
from, to = line.split('=>').map(&:strip)
to_quantity, to_type = to.split
from
.split(',')
.map(&:strip)
.map(&:split)
.each do |(from_quantity, from_type)|
graph.attach(from_type, to_type, from_quantity.to_i, to_quantity.to_i)
end
end
puts graph.build_type('FUEL')
|
require 'spec_helper'
module Boilerpipe::SAX::TagActions
describe BlockTagLabel do
let(:subject) { BlockTagLabel.new(nil) }
let(:handler) { ::Boilerpipe::SAX::HTMLContentHandler.new }
describe '.new' do
it 'takes a label action'
end
describe '#start' do
it 'returns true' do
expect(subject.start(handler, nil, nil)).to be true
end
end
describe '#end_tag' do
it 'returns true' do
expect(subject.end_tag(handler, nil)).to be true
end
end
describe '#changes_tag_level?' do
it 'returns true' do
expect(subject.changes_tag_level?).to be true
end
end
end
end
|
#Author: John Kilfeather
require 'test/unit'
require 'MatrixStats.rb'
#create class that extends module just for testing
class TestMatrix
include MatrixStats
attr_accessor :size
def initialize size, values
@size = size
@numbers = Array.new(values)
end
end
class TC_MatrixStats < Test::Unit::TestCase
def setup
numbers = Array[[1,1],[5,5]]
@mtrx = TestMatrix.new 2, numbers
end
def test_initialize
#test mean
assert(@mtrx.mean == 3, 'mean not calculated correctly')
#test standard deviation
assert(@mtrx.std_dev == 2, 'standard deviation not calculated correctly')
end
end
|
module Vhost::FckeditorExtensions
module Controller
# Overwriting this method will tell all fckeditor instances exactly which
# site they should scope down to.
def current_directory_path
# @todo this needs to be turned into the current_site.hostname but protect against the * hostname
# or something else
site_dir = "#{FckeditorController::UPLOADED_ROOT}/#{current_site.id}"
Dir.mkdir(site_dir,0775) unless File.exists?(site_dir)
base_dir = "#{FckeditorController::UPLOADED_ROOT}/#{current_site.id}/#{params[:Type]}"
Dir.mkdir(base_dir,0775) unless File.exists?(base_dir)
check_path("#{base_dir}#{params[:CurrentFolder]}")
end
def upload_directory_path
uploaded = ActionController::Base.relative_url_root.to_s+"#{FckeditorController::UPLOADED}/#{current_site.id}/#{params[:Type]}"
"#{uploaded}#{params[:CurrentFolder]}"
end
end
end
|
# Double Doubles
# A double number is a number with an even number of digits whose left-side digits are exactly the same as its right-side digits. For example, 44, 3333, 103103, 7676 are all double numbers. 444, 334433, and 107 are not.
# Write a method that returns 2 times the number provided as an argument, unless the argument is a double number; double numbers should be returned as-is.
def twice(num)
# converts to string
str = num.to_s
# convert string to array
arr = str.split('')
# finds the number of the array length by 2
take_var = arr.length / 2
# gets the left half of the array
arr_left = arr.take(take_var)
# gets the right half of the array
arr_right = arr.slice(take_var..-1)
# combines the two array halves together
combined_num = arr_left.join + arr_right.join
# if two array halves are equal, return combined num. else num times 2
if arr_left == arr_right
return combined_num.to_i
else
num * 2
end
end
p twice(37) == 74
p twice(44) == 44
p twice(334433) == 668866
p twice(444) == 888
p twice(107) == 214
p twice(103103) == 103103
p twice(3333) == 3333
p twice(7676) == 7676
p twice(123_456_789_123_456_789) == 123_456_789_123_456_789
p twice(5) == 10 |
require 'test_helper'
class TaskTest < ActiveSupport::TestCase
setup :activate_authlogic
setup :valid_task
def valid_task
@session = login_as users(:guy)
@person = Person.make :user => @session.user
@company = Company.make :person => @person
@project = Project.make :company => @company
plan = Task.plan :project => @project
@task = Task.new :description => plan[:description],
:project => @project
assert @task.valid?
end
test "valid task" do
assert_difference('Task.count') do
assert @task.save
end
end
test "invalid task with missing description" do
@task.description = nil
assert !@task.valid?
assert @task.errors.invalid?(:description)
end
test "invalid task with same description for project" do
taken = Task.make :project => @project
@task.description = taken.description
assert !@task.valid?
assert @task.errors.invalid?(:description)
end
test "task acts as list for project" do
assert @task.save
@project.reload
assert @project.tasks[0].first?
assert @project.tasks[0].last?
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.