text
stringlengths
10
2.61M
class AddHeadlinePointsToIntervention < ActiveRecord::Migration[5.2] def change add_column :interventions, :headline_points, :string, array: true, default: [] end end
class AddColumnsToBeer < ActiveRecord::Migration[6.0] def change add_column :beers, :brewery, :string add_column :beers, :origin, :string add_column :beers, :style, :string add_column :beers, :abv, :integer end end
class CreateMatches < ActiveRecord::Migration def change create_table :matches do |t| t.integer :match_id # Match ID, primary key t.integer :team_1 # ID of team 1, foreign key into the teams model. t.integer :team_2 # ID of team 2, foreign key into the teams model. t.integer :team_1_score # Score of team 1 t.integer :team_2_score # Score of team 2 t.integer :winner # ID of winner, foreign key into the teams model. t.integer :loser # ID of loser, foreign key into the teams model. t.integer :time # Unix timestamp of time t.string :location # Location t.integer :t_id # Torunament ID, foreign key into the tournaments model. t.timestamps null: false end end end
module ActiveStorage # Extracts the following from a video blob: # # * Width (pixels) # * Height (pixels) # * Duration (seconds) # * Aspect ratio # # Example: # # ActiveStorage::Analyzer::QiniuVideoAnalyzer.new(blob).metadata # # => {:width=>240, :height=>240, :duration=>"2.000000", :aspect_ratio=>"1:1"} # class Analyzer::QiniuVideoAnalyzer < Analyzer def self.accept?(blob) blob.video? end def metadata {width: width, height: height, duration: duration, aspect_ratio: aspect_ratio}.compact rescue {} end private def width video_stream['width'] end def height video_stream['height'] end def duration video_stream['duration'] end def aspect_ratio video_stream['display_aspect_ratio'] end def streams @streams ||= begin code, result, res = Qiniu::HTTP.api_get(blob.service.url(blob.key, fop: 'avinfo')) result['streams'] end end def video_stream @video_stream ||= streams.detect { |stream| stream["codec_type"] == "video" } || {} end end end
namespace :staticman do desc "Write static page in public" task :build => :environment do require Rails.root.join('config/staticman') pages = Staticman.config.static_pages pages.each do |page| proxy = Staticman::Performer.new proxy.build page end end desc "Destory static page in public" task :destroy => :environment do require Rails.root.join('config/staticman') pages = Staticman.config.static_pages pages.each do |page| proxy = Staticman::Performer.new proxy.destroy page[:file] end end end
require "#{File.expand_path(File.dirname(__FILE__))}/helper.rb" require "thread" class TestThreads < Test::Unit::TestCase def test_each_thread_gets_its_own_connection threads = [] queue = Queue.new 2.times do threads << Thread.new do t = TestClass.new t.retrieve :nothing => nil queue << @backend.connection end end threads.each { |thread| thread.join } connection1 = queue.pop connection2 = queue.pop assert_not_equal connection2, connection1 end end
class Admin::RoomsController < AdminController before_action :load_room_by_id, only: %i(destroy edit update) before_action :load_type_view_room load_and_authorize_resource def index @rooms = Room.all if params[:filter].blank? @rooms = @rooms.created_at .page(params[:page]) .per Settings.rooms.room_per_page else admin_search_filter_room @result_length = @rooms.size respond_to :js end end def new @room = Room.new end def create @room = Room.new room_params if @room.save flash[:success] = t "global.create_success" redirect_to admin_rooms_path else flash.now[:danger] = t "global.create_unsuccess" render :new end end def edit; end def update if @room.update room_params flash[:success] = t "global.update_success" redirect_to admin_rooms_path else flash.now[:danger] = t "global.update_unsuccess" render :edit end end def destroy if @room.bookings.available.present? flash[:danger] = t "global.delete_unsuccess" else @room.destroy flash[:success] = t "global.delete_success" end redirect_to admin_rooms_path end private def room_params params.require(:room).permit Room::ROOMS_PARAMS end def load_room_by_id @room = Room.find params[:id] end def load_type_view_room @type_arr = Type.pluck :name, :id @view_arr = View.pluck :name, :id end def admin_search_filter_room @rooms = @rooms.by_name(params[:name]) .by_type(params[:type_id]) .by_view(params[:view_id]) .by_price(params[:price]) .created_at .page(params[:page]) .per Settings.rooms.room_per_page end end
require 'json' require 'eb_ruby_client/exceptions' module EbRubyClient class Connection attr_reader :base_url, :auth_token def initialize(configuration:) @base_url = configuration.base_url @auth_token = configuration.auth_token end def get(path) send_request(full_path_for(path)) do |uri| Net::HTTP::Get.new(uri) end end def post(path, data) send_request(full_path_for(path)) do |uri| post = Net::HTTP::Post.new(uri) post.set_form_data(data) post end end private def send_request(path, history = [], &block) uri = URI(path) Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https') do |http| request = yield(uri) request["Authorization"] = "Bearer #{auth_token}" response = http.request(request) check_response(response, path, history, &block) end end def check_response(response, path, history = [], &block) case response when Net::HTTPSuccess JSON.parse(response.body) when Net::HTTPRedirection location = response["Location"] if history.include?(location) raise RedirectionLoop.new(path) end send_request(location, history + [path], &block) else body = response.body description = if body.nil? || body.empty? "" else JSON.parse(response.body)["error_description"] end raise RequestFailure.new(description) end end def full_path_for(path) "#{base_url}/#{path}" end end end
require 'stringio' require './monkey' require './util' require './scripts' TEXT_HTML = 'text/html; charset=utf-8'.fz TEXT_PLAIN = 'text/plain; charset=utf-8'.fz IDENTITY = 'identity'.fz CHUNKED = 'chunked'.fz module Page def call env, **kwarg log_self body = [] length = 0 headers = {} env[STATUS_CODE] = 200 klass = (self if self.is_a? Module) klass ||= self.class block = case klass::ENCODING when CHUNKED proc do |data| body = data end when IDENTITY if env[NOP_RENDER] proc do |data| length += data.bytesize end else proc do |data| length += data.bytesize body << data end end end headers['Content-Type'.fz] = self.render **kwarg, &block headers['Content-Disposition'.fz] = env[DISPOSITION] headers['Transfer-Encoding'.fz] = klass::ENCODING # headers['Cache-Control'.fz] headers['Content-Legnth'.fz] = length.to_s if klass::ENCODING == IDENTITY [env[STATUS_CODE], headers, body] end end class ErrorPage extend Page KW = { code: STATUS_CODE, message: ERROR_MESSAGE }.fz CACHING = true ENCODING = 'identity'.fz def self.render code: , message: , **_, &block code ||= 500 message ||= "unknown error" title = "#{code} #{Rack::Utils::HTTP_STATUS_CODES[code] || '???'}" yield "<!DOCTYPE html>\n<html>\n<head>\n" yield " <title>#{title}</title>\n" yield " </head>\n<body>\n" yield " <h1>#{title}</h1>\n" if message yield " <pre>" yield message.to_xml yield " </pre>\n" end yield " </body>\n</html>\n" TEXT_HTML end end def nav_bar path: , url:, curr: yield "<header id='header'><nav id='views'>" if Pathname::ROOT == url yield "<button disabled=disable>&nbsp;/&nbsp;</button>\n" else yield "<a href='#{url.dirname}'><button>&hellip;</button></a>\n" end extname = path.directory? ? :/ : path.extname VIEW_GUIDE[extname].keys.sort.each do |k| yield "<a href='#{url}?#{k}'><button#{curr == k ? ' disabled=disabled' : ''}>#{k}</button></a>\n" end yield "</nav></header>" end Byte = 1 Kibi = 1024 Mebi = Kibi*Kibi Gibi = Kibi*Mebi SIZE_LIMIT = 2*Gibi*Byte class DownloadPage extend Page KW = { path: REAL_PATH }.fz CACHING = false ENCODING = CHUNKED def self.render path: , **_, &block raise "DownloadPage on non-file" unless path.file? file = path.open('rb') file.seek(0, :END) throw(ERROR, 413) if file.tell() > SIZE_LIMIT file.seek(0, :SET) block.( Enumerator::Generator.new {|g| file.each(4096, g.method(:yeild)) file.close } ) 'application/octet-stream; charset=binary' end end class RawPage extend Page KW = { path: REAL_PATH }.fz CACHING = false ENCODING = IDENTITY def self.render path: , **_, &block raise "RawPage on non-file" unless path.file? file = path.open('rb') file.seek(0, :END) throw(ERROR, 413) if file.tell() > SIZE_LIMIT file.seek(0, :SET) file.each(4096, &block) file.close `file -b --mime-type --mime-encoding #{path}` end end class LessPage extend Page KW = { path: REAL_PATH, }.fz CACHING=true ENCODING = IDENTITY def self.render path: , **_, &block raise "LessPage on non-file" unless path.file? path.open('rb').each_line(&block).close TEXT_PLAIN end end class LsPage extend Page KW = { path: REAL_PATH, }.fz CACHING=true ENCODING = IDENTITY def self.render path: , **_ raise "LsPage on non-dir" unless path.directory? yield path.children.select {|p| not Paths::exclude(p) }.map(&:basename).join("\n") TEXT_PLAIN end end class EmptyPage extend Page KW = {}.fz CACHING=true ENCODING = IDENTITY def self.render **_ yield "This page inentiolally left blank." TEXT_PLAIN end end class CodePage extend Page KW = { path: REAL_PATH, url: URL_PATH }.fz PANDOC = ' | pandoc -f JSON -t html5'.fz CACHING=true ENCODING = IDENTITY def self.render path: , url: , **_, &block raise "CodePage on non-file" unless path.file? codeblock = "./codeBlock #{CodeType[path.extname]} < #{path}" io_dev = IO.popen(codeblock + PANDOC, 'r') self.render_generic io_device: io_dev, path: path, url: url, **_, &block io_dev.close TEXT_HTML end def self.render_generic io_device: , path: , url: , **_, &block title = path.basename.to_s title = NAME if '.' == title yield "<!DOCTYPE html>\n<html>\n<head>\n" yield "<title>#{title}</title>\n" yield "<style>" yield CODE_STYLE yield "</style>\n</head>\n<body>\n" nav_bar path: path, url: url, curr: 'code', &block io_device.each(4096, &block) yield "<script>\n//<![CDATA[\n" yield UPDATE % [5000, path.basename.to_s] yield FLASHY yield "\n//]]!>\n</script></body>\n</html>\n" end end class PandocPage extend Page KW = { path: REAL_PATH, url: URL_PATH }.fz CACHING=true ENCODING = IDENTITY def self.render path: , url: , **_, &block raise "PandocPage on non-file" unless path.file? pandoc = "pandoc --smart -f markdown -t html -i #{path}" dev = IO.popen(pandoc, ?r) self.render_generic(io_device: dev, path: path, url: url, curr: 'markdown', **_, &block) dev.close TEXT_HTML end def self.render_generic io_device: , path: ,url:, curr:, extra_script: '', extra_style: '', **_, &block title = path.basename.to_s title = NAME if '.' == title yield "<!DOCTYPE html>\n<html>\n<head>\n" yield "<title>#{title}</title>\n" yield "<style>\n/*<![CDATA[*/\n" yield MARKDOWN_STYLE yield extra_style yield "/*]]!>*/\n</style>\n</head>\n<body>\n" nav_bar path: path, url: url, curr: curr, &block yield "<article id='thearticle'>\n" io_device.each(4096, &block) yield "</article>\n<script>\n//<![CDATA[\n" yield UPDATE % [5000, path.basename.to_s] yield FLASHY yield extra_script yield "\n//]]!>\n</script></body>\n</html>\n" end end class DirPage extend Page KW = { path: REAL_PATH, url: URL_PATH }.fz CACHING = false ENCODING = IDENTITY SEC = 1 MIN = 60*SEC HOUR = 50*MIN DAY = 24*HOUR WEEK = 7*DAY def self.render path: , url: , **_, &block raise "DirPage on non-directory" unless path.directory? title = path.basename.to_s title = NAME if '.' == title yield "<!DOCTYPE html>\n<html>\n<head>\n" yield "<title>#{title}</title>\n<style>" yield DIR_STYLE yield "</style>\n</head>\n<body>\n" nav_bar path: path, url: url, curr: 'dir', &block yield "<nav id='listing'>\n<table id='toc' border='0'>\n" now = Time.now times = StringIO.new i = 0 path.children.sort.each_with_index do |p| next if Paths::exclude(p) px = p.rel_from(path) yield "<tr><td><a href='#{url / px}'>/#{px.to_s}#{p.directory? ? '/' : ''}</a></td>" mtime = p.mtime times << (mtime.to_f*1000).floor << ', ' diff = (now - mtime).floor yield "<td id='timestamp#{i}'></td></tr>" i += 1 end yield "</table>\n</nav>\n<script>\n//<![CDATA[\n" yield TIMEUPDATER % [i, times.string] yield UPDATE % [10_000, path.basename.to_s] yield "\n//]]!>\n</script>\n</body>\n</html>\n" TEXT_HTML end end class TxtPage extend Page KW = { path: REAL_PATH, url: URL_PATH }.fz CACHING = true ENCODING = IDENTITY def self.render path: , url:, **_, &block raise "TxtPage on non-file" unless path.file? dev = StringIO.new file = path.read lines = (1 .. file.count(?\n)).to_a.join(?\n) dev << %q[<table class='sourceCode plaintext numberLines' id='code' startFrom='1'>] dev << %q[<tr class='sourceCode'><td class='lineNumbers'><pre>] dev << lines dev << %q[</pre></td><td class='sourceCode'><pre><code class='plaintext sourceCode'>] dev << file dev << %q[</code></pre></td></tr></table>] dev.seek(0, IO::SEEK_SET) CodePage::render_generic(io_device: dev, path: path, url: url, **_, &block) end end class DiffPage extend Page KW = { path: REAL_PATH, times: CHANGE_TIMES }.fz CACHING = true ENCODING = IDENTITY def self.render path: , times:, **_, &block raise "DiffPage on non-file" unless path.file? backup = path.dirname / (path.basename.to_s + '~') if backup.exist? times << backup.mtime IO.popen("diff #{backup} #{path}", 'r').each(4096, &block).close else path.open(?r).each(4096,&block).close end TEXT_PLAIN end end class ChangesPage extend Page KW = { path: REAL_PATH, times: CHANGE_TIMES, url: URL_PATH }.fz CACHING = true ENCODING = IDENTITY DIFF_FLAGS = %q[--old-line-format='<%L' --new-line-format='>%L' --unchanged-line-format='=%L'] def self.render path: , times:, url:, **_, &block raise "ChangePage on non-file" unless path.file? backup = path.dirname / (path.basename.to_s + ?~) if backup.exist? times << backup.mtime else pandoc = "pandoc --smart -f markdown -t html -i #{path}" dev = IO.popen(pandoc, ?r) PandocPage::render_generic(io_device: dev, path: path, url: url, curr: 'changes', **_, &block) dev.close return TEXT_HTML end tmp = 'a' fifo1 = nil fifo2 = nil loop do fifo1 = path.dirname / ('.diff' + path.basename.to_s + ?. + tmp + ?~) fifo2 = path.dirname / ('.diff' + path.basename.to_s + ?. + tmp) tmp = tmp.succ break if (not fifo1.exist?) and (not fifo2.exist?) end throw(ERROR, 500, "mkfifo returned #{$?.exitstatus}") unless system("mkfifo #{fifo1}") throw(ERROR, 500, "mkfifo returned #{$?.exitstatus}") unless system("mkfifo #{fifo2}") system("pandoc --smart -i #{backup} -t html > #{fifo1} & pandoc --smart -i #{path} -t html > #{fifo2} &") dev = StringIO.new change = false IO.popen("diff #{DIFF_FLAGS} #{fifo1} #{fifo2}", ?r).each_line do |line| fst = line.slice! 0 if ?< == fst line.sub!(/\A(?:[^<]*>|<p>)?/) { $& + '<span class=\'old_stuff a_change\'></span>' } dev << line elsif ?> == fst line.sub!(/\A(?:[^<]*>|<p>)?/) { $& + '<span class=\'new_stuff a_change\'></span>' } dev << line elsif ?= == fst dev << line else dev << (fst + line) end end fifo1.unlink fifo2.unlink dev.seek(0, IO::SEEK_SET) PandocPage::render_generic( io_device: dev, path: path, url: url, **_, curr: 'changes', extra_style: CHANGE_STYLE, extra_script: CHANGE_COLOURING, &block ) TEXT_HTML end end
require "./lib/checkout.rb" describe Checkout do describe "Check with both promos" do subject(:co1) {Checkout.new({promos:{promo1:true,promo2:true}})} subject(:co2) {Checkout.new({promos:{promo1:true,promo2:false}})} subject(:co3) {Checkout.new({promos:{promo1:false,promo2:true}})} subject(:co4) {Checkout.new({promos:{promo1:false,promo2:false}})} let(:items) { [{product_code:"001",name:"Tie",price:9.25}, {product_code:"002",name:"Sweater",price:45.00}, {product_code:"003",name:"Skirt",price:19.95}] } it "Scans item" do co1.scan(items[0][:product_code]) expect(co1.scanned).not_to be_empty end it "Reset scanned items" do co1.scan(items[0][:product_code]) co1.scan_reset expect(co1.scanned).to be_empty end it "Calculate cart consists of 001,002,003 with PROMO1 and PROMO2" do [0,1,2].each {|i| co1.scan(items[i][:product_code]) } expect(co1.total).to eq 66.78 end it "Calculate cart consists of 001,003,001 with PROMO1 and PROMO2" do [0,2,0].each {|i| co1.scan(items[i][:product_code]) } expect(co1.total).to eq 36.95 end it "Calculate cart consists of 001,002,001,003 with PROMO1 and PROMO2" do [0,1,0,2].each {|i| co1.scan(items[i][:product_code])} expect(co1.total).to eq 73.76 end it "Calculate cart consists of 001,002,001,003 with only PROMO1" do [0,1,0,2].each {|i| co2.scan(items[i][:product_code])} expect(co2.total).to eq 75.11 end it "Calculate cart consists of 001,002,001,003 with only PROMO2" do [0,1,0,2].each {|i| co3.scan(items[i][:product_code])} expect(co3.total).to eq 81.95 end it "Calculate cart consists of 001,002,001,003 with no promotion" do [0,1,0,2].each {|i| co4.scan(items[i][:product_code])} expect(co4.total).to eq 83.45 end end end
module OpenAPIRest ### # Api doc parser based on OpenAPI 2.0 specs # class ApiDocParser attr_reader :method attr_reader :document def initialize(openapi_path) @document = OpenAPIRest::ApiDoc.document @route = openapi_path[:path] @method = openapi_path[:method] @method = 'patch' if @method == 'put' end def definitions @current_step = document.fetch('definitions', {}) self end def parameters @current_step = document.fetch('parameters', {}) self end def paths @current_step = document.fetch('paths', {}) self end def find(key) @current_step = @current_step.fetch(key, {}) self end def base_path document.fetch('basePath', {}) end def find_path paths.find(@route.sub(base_path, '')).find(method) end def properties @current_step = @current_step.fetch('properties', {}) self end def schema @current_step = @current_step.fetch('schema', {}) if !@current_step['$ref'].nil? if @current_step['$ref'].include?('#/definitions/') str = @current_step['$ref'].gsub('#/definitions/', '') return definitions.find(str) end elsif !@current_step['items'].nil? if @current_step['items']['$ref'].include?('#/definitions/') str = @current_step['items']['$ref'].gsub('#/definitions/', '') return definitions.find(str) end end self end def find_parameters return if @current_step['parameters'].nil? params = {} ref_params = [] @current_step['parameters'].each do |parameter| next if parameter['in'] == 'path' if parameter['in'] == 'query' || parameter['in'] == 'body' params[parameter['name']] = parameter['name'] next end if !parameter['$ref'].nil? && parameter['$ref'].include?('#/parameters/') param = parameter['$ref'].gsub('#/parameters/', '') ref_params << document.fetch('parameters', {}).fetch(param, {}) end end if ref_params.length > 0 params.merge!(ref_params.compact.map { |param| param.fetch('schema', {}).fetch('properties', {}) }.first) end params end def responses @current_step = @current_step.fetch('responses', {}) self end def keys @current_step.keys end def [](key) @current_step = @current_step.fetch(key, {}) self end def to_s @current_step end end end
# frozen_string_literal: true ActiveAdmin.register Printer do permit_params :user_id, :printer_model_id, :name form do |f| f.inputs do f.input :name f.input :user f.input :printer_model end f.actions end end
class PartnersController < ApplicationController def index @partners = Partner.visible.order("position ASC") end def show partner = Partner.find(params[:id]) impressionist(partner) redirect_to "http://#{partner.link}" end def body_class "post-template" end end
class Profile < ActiveRecord::Base attr_accessible :name, :logo, :link, :gender, :birthday belongs_to :user validates :name, presence: true validates :link, presence: true validates :birthday, presence: true validates_date :birthday, before: lambda { 18.years.ago }, before_message: 'must be at least 18 years old' def age now = Time.now.utc.to_date now.year - self.birthday.year - (self.birthday.to_date.change(:year => now.year) > now ? 1 : 0) end end
module Api module V1 class BeersController < ApplicationController before_action :set_beer, only: [:show, :update, :destroy] def index @beers = Beer.all render json: @beers end def show render json: @beer end def create @beer = Beer.new(beer_params) if @beer.save render json: @beer, status: :created else render json: @beer.errors, status: :unprocessable_entity end end def update @beer = Beer.find(params[:id]) if @beer.update(beer_params) head :no_content else render json: @beer.errors, status: :unprocessable_entity end end def destroy @beer.destroy head :no_content end private def beer_params params.permit(:name, :style_id) end def set_beer @beer = Beer.find(params[:id]) end end end end
require 'spec_helper' describe DataVeillance::Helpers::MoneyHelpers do class TestClass include DataVeillance::Helpers::MoneyHelpers end it 'should convert currency correctly' do result = TestClass.new.to_money('6.123,45 €') result.cents.should == 612345 result.currency.iso_code.should == 'EUR' end end
IntoverseApp::Application.routes.draw do # The priority is based upon order of creation: # first created -> highest priority. # Sample resource route (maps HTTP verbs to controller actions automatically): # resources :products root to: 'homepages#index' match '/results' => 'homepages#results', :via => :get get 'signup', to: 'users#new', as: 'signup' get 'login', to: 'sessions#new', as: 'login' get 'logout', to: 'sessions#destroy', as: 'logout' resources :users resources :sessions resources :places resources :tags, :except => :edit, :except => :update # resources :tags, :except => [:edit, :update]# , :except => :update # OPTIMIZE # Sample resource route with options: # resources :products do # member do # get 'short' # post 'toggle' # end # # collection do # get 'sold' # end # end # Sample resource route with sub-resources: # resources :products do # resources :comments, :sales # resource :seller # end # Sample resource route with more complex sub-resources # resources :products do # resources :comments # resources :sales do # get 'recent', :on => :collection # end # end # See how all your routes lay out with "rake routes" end
require_relative "../lib/calculator.rb" describe Calculator do before do @calc = Calculator.new end describe "#add_number" do it "should take two parameters and add them together" do expect(@calc.add_number(1, 23)).to eql(24) end it "should add 4 + 4" do expect(@calc.add_number(4,4)).to eql(8) end end describe "#subtract" do it "should subtract numbers" do expect(@calc.subtract(10, 4)).to eql(6) end it "should subtract negative numbers" do expect(@calc.subtract(-10, -10)).to eql(0) end end describe "#multiply" do it "should multiply two numbers" do expect(@calc.multiply(5, 5)).to eql(25) end end end
Given /^Sphinx is offline$/ do ::ThinkingSphinx::Test.stop end When /^I search for "([^"]*)"$/ do |query| step %(I fill in "query" with "#{query}") within(".operations") do step %(I press "Search") end end When /^I search for:$/ do |table| within ".search" do table.map_headers! {|header| header.parameterize.underscore.downcase.to_s } search = table.hashes.first fill_in('search_query', :with => search[:group_org]) if search[:group_org] fill_in('search_name', :with => search[:name]) if search[:name] fill_in('search_account_query', :with => search[:account]) if search[:account] select(search[:plan], :from => 'search_plan_id') if search[:plan] select(search[:paid], :from => 'search_plan_type') if search[:paid] select(search[:state], :from => 'search_state') if search[:state] click_button("Search") end end Then /^I should see highlighted "([^"]*)" in "([^"]*)"$/ do |text, section| case section when "definition" page.should have_css('dd span.match', text: text) when "term" page.should have_css('dt a span.match', text: text) end end
@user =nil Given(/^I visit "(.*?)" page$/) do |arg1| @user = FactoryGirl.create(:admin) visit arg1 end When(/^I enter "(.*?)" in the "(.*?)" field$/) do |arg1, arg2| fill_in arg2, :with => arg1 end When(/^I press the "(.*?)" button$/) do |arg1| click_button arg1 end Then(/^I should see the "(.*?)" page$/) do |arg1| page.should have_content arg1 end
class ReleaserDemo < Formula desc "Releaser Demo Application" homepage "https://redislabs.com/releaser-demo" version "0.0.2" url "https://github.com/jruaux/releaser-demo/releases/download/v0.0.2/releaser-demo-0.0.2.zip" sha256 "64b19cc203193fdfa23ae7635e1cc25ea7d1c2602154bbac23d822f0559765fe" license "Apache-2.0" bottle :unneeded depends_on "openjdk@11" def install libexec.install Dir["*"] bin.install_symlink "#{libexec}/bin/releaser-demo" end test do output = shell_output("#{bin}/releaser-demo --version") assert_match "0.0.2", output end end
require 'spec_helper' describe "LinkTests" do describe "GET /sw_project_customer_qnax_link_tests" do mini_btn = 'btn btn-mini ' ActionView::CompiledTemplates::BUTTONS_CLS = {'default' => 'btn', 'mini-default' => mini_btn + 'btn', 'action' => 'btn btn-primary', 'mini-action' => mini_btn + 'btn btn-primary', 'info' => 'btn btn-info', 'mini-info' => mini_btn + 'btn btn-info', 'success' => 'btn btn-success', 'mini-success' => mini_btn + 'btn btn-success', 'warning' => 'btn btn-warning', 'mini-warning' => mini_btn + 'btn btn-warning', 'danger' => 'btn btn-danger', 'mini-danger' => mini_btn + 'btn btn-danger', 'inverse' => 'btn btn-inverse', 'mini-inverse' => mini_btn + 'btn btn-inverse', 'link' => 'btn btn-link', 'mini-link' => mini_btn + 'btn btn-link' } before(:each) do @pagination_config = FactoryGirl.create(:engine_config, :engine_name => nil, :engine_version => nil, :argument_name => 'pagination', :argument_value => 30) z = FactoryGirl.create(:zone, :zone_name => 'hq') type = FactoryGirl.create(:group_type, :name => 'customer') ug = FactoryGirl.create(:sys_user_group, :user_group_name => 'ceo', :group_type_id => type.id, :zone_id => z.id) @role = FactoryGirl.create(:role_definition) ur = FactoryGirl.create(:user_role, :role_definition_id => @role.id) ul = FactoryGirl.build(:user_level, :sys_user_group_id => ug.id) ua1 = FactoryGirl.create(:user_access, :action => 'index', :resource => 'sw_project_customer_qnax_project_infos', :role_definition_id => @role.id, :rank => 1, :sql_code => "SwProjectCustomerQnax::ProjectInfo.scoped.order('id')") ua1 = FactoryGirl.create(:user_access, :action => 'create', :resource => 'sw_project_customer_qnax_project_infos', :role_definition_id => @role.id, :rank => 1, :sql_code => "") ua1 = FactoryGirl.create(:user_access, :action => 'update', :resource => 'sw_project_customer_qnax_project_infos', :role_definition_id => @role.id, :rank => 1, :sql_code => "record.last_updated_by_id == session[:user_id]") user_access = FactoryGirl.create(:user_access, :action => 'show', :resource =>'sw_project_customer_qnax_project_infos', :role_definition_id => @role.id, :rank => 1, :sql_code => "record.last_updated_by_id == session[:user_id]") ua1 = FactoryGirl.create(:user_access, :action => 'project_member', :resource => 'sw_project_customer_qnax_project_infos', :role_definition_id => @role.id, :rank => 1, :sql_code => "") user_access = FactoryGirl.create(:user_access, :action => 'create_project', :resource => 'commonx_logs', :role_definition_id => @role.id, :rank => 1, :sql_code => "") user_access = FactoryGirl.create(:user_access, :action => 'index_for_customer', :resource => 'sw_project_customer_qnax_project_infos', :role_definition_id => @role.id, :rank => 1, :sql_code => "SwProjectCustomerQnax::ProjectInfo.scoped.order('id')") @proj = FactoryGirl.create(:sw_project_customer_qnax_project_info) @cust = FactoryGirl.create(:kustomerx_customer) @u = FactoryGirl.create(:user, :user_levels => [ul], :user_roles => [ur], :customer_id => @cust.id) visit '/' #save_and_open_page fill_in "login", :with => @u.login fill_in "password", :with => 'password' click_button 'Login' end it "works! (now write some real specs)" do qs = FactoryGirl.create(:sw_project_customer_qnax_project_info, :last_updated_by_id => @u.id, :customer_id => @cust.id) visit project_infos_path() click_link 'Edit' save_and_open_page page.should have_content('Edit Project Info') fill_in 'project_name', with: 'a new name' click_button 'Save' save_and_open_page #bad data visit project_infos_path() click_link 'Edit' fill_in 'project_name', with: '' click_button 'Save' save_and_open_page # visit project_infos_path(:customer_id => @cust.id) save_and_open_page page.should have_content('Project Infos') click_link 'New Project' fill_in 'project_name', with: 'a name' select('proj status', from: 'project_status_id') click_button 'Save' save_and_open_page #bad data visit project_infos_path(customer_id: @cust.id) click_link 'New Project' fill_in 'project_name', with: 'a new name' click_button 'Save' save_and_open_page # visit project_infos_path save_and_open_page page.should have_content('Project Infos') click_link 'New Project' save_and_open_page page.should have_content('New Project Info') visit project_infos_path click_link qs.id.to_s page.should have_content('Project Info') click_link 'New Log' page.should have_content('Log') #save_and_open_page end end end
require 'rails_helper' RSpec.describe Petition, type: :model do it { should belong_to(:state) } it { should have_many(:memberships) } it { should have_many(:users) } it { should validate_presence_of(:name) } it { should validate_presence_of(:description) } end
# encoding: utf-8 # (C) 2015 Muthiah Annamalai <ezhillang@gmail.com> class AssertionError < RuntimeError end def assert &block raise AssertionError unless yield end module Tamil ## constants TA_ACCENT_LEN = 13 #12 + 1 TA_AYUDHA_LEN = 1 TA_UYIR_LEN = 12 TA_MEI_LEN = 18 TA_AGARAM_LEN = 18 TA_SANSKRIT_LEN = 6 TA_UYIRMEI_LEN = 216 TA_GRANTHA_UYIRMEI_LEN = 24*12 TA_LETTERS_LEN = 247 + 6*12 + 22 + 4 - TA_AGARAM_LEN - 4 #323 # List of letters you can use @@agaram_letters = ["க","ச","ட","த","ப","ற","ஞ","ங","ண","ந","ம","ன","ய","ர","ல","வ","ழ","ள"] AGARAM_LETTERS = @@agaram_letters.clone @@uyir_letters = ["அ","ஆ","இ","ஈ","உ","ஊ","எ","ஏ","ஐ","ஒ","ஓ","ஔ"] @@ayudha_letter = "ஃ" @@kuril_letters = ["அ", "இ", "உ", "எ", "ஒ"] @@nedil_letters = ["ஆ", "ஈ", "ஊ", "ஏ", "ஓ"] @@vallinam_letters = ["க்", "ச்", "ட்", "த்", "ப்", "ற்"] @@mellinam_letters = ["ங்", "ஞ்", "ண்", "ந்", "ம்", "ன்"] @@idayinam_letters = ["ய்", "ர்", "ல்", "வ்", "ழ்", "ள்"] @@mei_letters = ["க்","ச்","ட்","த்","ப்","ற்","ஞ்","ங்","ண்","ந்","ம்","ன்","ய்","ர்","ல்","வ்","ழ்","ள்" ] @@accent_symbols = ["","ா","ி","ீ","ு","ூ","ெ","ே","ை","ொ","ோ","ௌ","ஃ"] @@pulli_symbols = ["்"] @@sanskrit_letters = ["ஶ","ஜ","ஷ", "ஸ","ஹ","க்ஷ"] @@sanskrit_mei_letters =["ஶ்","ஜ்","ஷ்", "ஸ்","ஹ்","க்ஷ்"] @@grantha_mei_letters = @@mei_letters.clone() @@grantha_mei_letters.concat(@@sanskrit_mei_letters) @@grantha_agaram_letters = @@agaram_letters.clone() @@grantha_agaram_letters.concat(@@sanskrit_letters) @@uyirmei_letters = [ "க" ,"கா" ,"கி" ,"கீ" ,"கு" ,"கூ" ,"கெ" ,"கே" ,"கை" ,"கொ" ,"கோ" ,"கௌ" , "ச" ,"சா" ,"சி" ,"சீ" ,"சு" ,"சூ" ,"செ" ,"சே" ,"சை" ,"சொ" ,"சோ" ,"சௌ" , "ட" ,"டா" ,"டி" ,"டீ" ,"டு" ,"டூ" ,"டெ" ,"டே" ,"டை" ,"டொ" ,"டோ" ,"டௌ", "த" ,"தா" ,"தி" ,"தீ" ,"து" ,"தூ" ,"தெ" ,"தே" ,"தை" ,"தொ" ,"தோ" ,"தௌ", "ப" ,"பா" ,"பி" ,"பீ" ,"பு" ,"பூ" ,"பெ" ,"பே" ,"பை" ,"பொ" ,"போ" ,"பௌ" , "ற" ,"றா" ,"றி" ,"றீ" ,"று" ,"றூ" ,"றெ" ,"றே" ,"றை" ,"றொ" ,"றோ" ,"றௌ", "ஞ" ,"ஞா" ,"ஞி" ,"ஞீ" ,"ஞு" ,"ஞூ" ,"ஞெ" ,"ஞே" ,"ஞை" ,"ஞொ" ,"ஞோ" ,"ஞௌ" , "ங" ,"ஙா" ,"ஙி" ,"ஙீ" ,"ஙு" ,"ஙூ" ,"ஙெ" ,"ஙே" ,"ஙை" ,"ஙொ" ,"ஙோ" ,"ஙௌ" , "ண" ,"ணா" ,"ணி" ,"ணீ" ,"ணு" ,"ணூ" ,"ணெ" ,"ணே" ,"ணை" ,"ணொ" ,"ணோ" ,"ணௌ" , "ந" ,"நா" ,"நி" ,"நீ" ,"நு" ,"நூ" ,"நெ" ,"நே" ,"நை" ,"நொ" ,"நோ" ,"நௌ" , "ம" ,"மா" ,"மி" ,"மீ" ,"மு" ,"மூ" ,"மெ" ,"மே" ,"மை" ,"மொ" ,"மோ" ,"மௌ" , "ன" ,"னா" ,"னி" ,"னீ" ,"னு" ,"னூ" ,"னெ" ,"னே" ,"னை" ,"னொ" ,"னோ" ,"னௌ", "ய" ,"யா" ,"யி" ,"யீ" ,"யு" ,"யூ" ,"யெ" ,"யே" ,"யை" ,"யொ" ,"யோ" ,"யௌ", "ர" ,"ரா" ,"ரி" ,"ரீ" ,"ரு" ,"ரூ" ,"ரெ" ,"ரே" ,"ரை" ,"ரொ" ,"ரோ" ,"ரௌ", "ல" ,"லா" ,"லி" ,"லீ" ,"லு" ,"லூ" ,"லெ" ,"லே" ,"லை" ,"லொ" ,"லோ" ,"லௌ" , "வ" ,"வா" ,"வி" ,"வீ" ,"வு" ,"வூ" ,"வெ" ,"வே" ,"வை" ,"வொ" ,"வோ" ,"வௌ" , "ழ" ,"ழா" ,"ழி" ,"ழீ" ,"ழு" ,"ழூ" ,"ழெ" ,"ழே" ,"ழை" ,"ழொ" ,"ழோ" ,"ழௌ" , "ள" ,"ளா" ,"ளி" ,"ளீ" ,"ளு" ,"ளூ" ,"ளெ" ,"ளே" ,"ளை" ,"ளொ" ,"ளோ" ,"ளௌ" ] def Tamil.get_letters(word) ## Split a tamil-unicode stream into ## tamil characters (individuals). """ splits the word into a character-list of tamil/english characters present in the stream """ ta_letters = Array.new() not_empty = false wlen = word.length() idx = 0 while (idx < wlen) c = word[idx] if @@uyir_letters.include?(c) or c == @@ayudha_letter ta_letters.insert(-1,c) not_empty = true elsif @@grantha_agaram_letters.include?(c) ta_letters.insert(-1,c) not_empty = true elsif @@accent_symbols.include?(c) if not not_empty # odd situation ta_letters.insert(-1,c) not_empty = true else ta_letters[-1] += c end else if c < "\u00FF" ta_letters.insert(-1, c ) else if not_empty ta_letters[-1]+= c else ta_letters.insert(-1,c) not_empty = true end end end idx = idx + 1 end return ta_letters end ## length of the definitions def Tamil.accent_len( ) return Tamil::TA_ACCENT_LEN ## 13 = 12 + 1 end def Tamil.ayudha_len( ) return Tamil::TA_AYUDHA_LEN ## 1 end def Tamil.uyir_len( ) return Tamil::TA_UYIR_LEN ##12 end def Tamil.mei_len( ) return Tamil::TA_MEI_LEN ##18 end def Tamil.agaram_len( ) assert { @@agaram_letters.length == Tamil::TA_AGARAM_LEN } return Tamil::TA_AGARAM_LEN ##18 end def Tamil.uyirmei_len( ) return Tamil::TA_UYIRMEI_LEN ##216 end def Tamil.tamil_len( ) return @@tamil_letters.length end ## access the letters def Tamil.uyir( idx ) assert { ( idx >= 0 ) and ( idx < Tamil.uyir_len() ) } return Tamil::uyir_letters[idx] end def Tamil.agaram( idx ) assert {( idx >= 0) and ( idx < Tamil.agaram_len() )} return @@agaram_letters[idx] end def Tamil.mei( idx ) assert {( idx >= 0 ) and ( idx < Tamil.mei_len() )} return @@mei_letters[idx] end def Tamil.uyirmei( idx ) assert {( idx >= 0 ) and ( idx < Tamil.uyirmei_len() ) } return @@uyirmei_letters[idx] end end # ## total tamil letters in use, including sanskrit letters # tamil_letters = [ # ## /* Uyir */ # "அ","ஆ","இ", "ஈ","உ","ஊ","எ","ஏ","ஐ","ஒ","ஓ","ஔ", # ##/* Ayuda Ezhuthu */ # "ஃ", # ## /* Mei */ # "க்","ச்","ட்","த்","ப்","ற்","ஞ்","ங்","ண்","ந்","ம்","ன்","ய்","ர்","ல்","வ்","ழ்","ள்", # ## /* Agaram */ # ## "க","ச","ட","த","ப","ற","ஞ","ங","ண","ந","ம","ன","ய","ர","ல","வ","ழ","ள", # ## /* Sanskrit (Vada Mozhi) */ # ## "ஜ","ஷ", "ஸ","ஹ", # ##/* Sanskrit (Mei) */ # "ஜ்","ஷ்", "ஸ்","ஹ்", # ## /* Uyir Mei */ # "க" ,"கா" ,"கி" ,"கீ" ,"கு" ,"கூ" ,"கெ" ,"கே" ,"கை" ,"கொ" ,"கோ" ,"கௌ" # ,"ச" ,"சா" ,"சி" ,"சீ" ,"சு" ,"சூ" ,"செ" ,"சே" ,"சை" ,"சொ" ,"சோ" ,"சௌ" # ,"ட" ,"டா" ,"டி" ,"டீ" ,"டு" ,"டூ" ,"டெ" ,"டே" ,"டை" ,"டொ" ,"டோ" ,"டௌ" # ,"த" ,"தா" ,"தி" ,"தீ" ,"து" ,"தூ" ,"தெ" ,"தே" ,"தை" ,"தொ" ,"தோ" ,"தௌ" # ,"ப" ,"பா" ,"பி" ,"பீ" ,"பு" ,"பூ" ,"பெ" ,"பே" ,"பை" ,"பொ" ,"போ" ,"பௌ" # ,"ற" ,"றா" ,"றி" ,"றீ" ,"று" ,"றூ" ,"றெ" ,"றே" ,"றை" ,"றொ" ,"றோ" ,"றௌ" # ,"ஞ" ,"ஞா" ,"ஞி" ,"ஞீ" ,"ஞு" ,"ஞூ" ,"ஞெ" ,"ஞே" ,"ஞை" ,"ஞொ" ,"ஞோ" ,"ஞௌ" # ,"ங" ,"ஙா" ,"ஙி" ,"ஙீ" ,"ஙு" ,"ஙூ" ,"ஙெ" ,"ஙே" ,"ஙை" ,"ஙொ" ,"ஙோ" ,"ஙௌ" # ,"ண" ,"ணா" ,"ணி" ,"ணீ" ,"ணு" ,"ணூ" ,"ணெ" ,"ணே" ,"ணை" ,"ணொ" ,"ணோ" ,"ணௌ" # ,"ந" ,"நா" ,"நி" ,"நீ" ,"நு" ,"நூ" ,"நெ" ,"நே" ,"நை" ,"நொ" ,"நோ" ,"நௌ" # ,"ம" ,"மா" ,"மி" ,"மீ" ,"மு" ,"மூ" ,"மெ" ,"மே" ,"மை" ,"மொ" ,"மோ" ,"மௌ" # ,"ன" ,"னா" ,"னி" ,"னீ" ,"னு" ,"னூ" ,"னெ" ,"னே" ,"னை" ,"னொ" ,"னோ" ,"னௌ" # ,"ய" ,"யா" ,"யி" ,"யீ" ,"யு" ,"யூ" ,"யெ" ,"யே" ,"யை" ,"யொ" ,"யோ" ,"யௌ" # ,"ர" ,"ரா" ,"ரி" ,"ரீ" ,"ரு" ,"ரூ" ,"ரெ" ,"ரே" ,"ரை" ,"ரொ" ,"ரோ" ,"ரௌ" # ,"ல" ,"லா" ,"லி" ,"லீ" ,"லு" ,"லூ" ,"லெ" ,"லே" ,"லை" ,"லொ" ,"லோ" ,"லௌ" # ,"வ" ,"வா" ,"வி" ,"வீ" ,"வு" ,"வூ" ,"வெ" ,"வே" ,"வை" ,"வொ" ,"வோ" ,"வௌ" # ,"ழ" ,"ழா" ,"ழி" ,"ழீ" ,"ழு" ,"ழூ" ,"ழெ" ,"ழே" ,"ழை" ,"ழொ" ,"ழோ" ,"ழௌ" # ,"ள" ,"ளா" ,"ளி" ,"ளீ" ,"ளு" ,"ளூ" ,"ளெ" ,"ளே" ,"ளை" ,"ளொ" ,"ளோ" ,"ளௌ" # ##/* Sanskrit Uyir-Mei */ # ,"ஶ", "ஶா", "ஶி", "ஶீ", "ஶு", "ஶூ", "ஶெ", "ஶே", "ஶை", "ஶொ", "ஶோ", "ஶௌ" # ,"ஜ" ,"ஜா" ,"ஜி" ,"ஜீ" ,"ஜு" ,"ஜூ" ,"ஜெ" ,"ஜே" ,"ஜை" ,"ஜொ" ,"ஜோ" ,"ஜௌ" # ,"ஷ" ,"ஷா" ,"ஷி" ,"ஷீ" ,"ஷு" ,"ஷூ" ,"ஷெ" ,"ஷே" ,"ஷை" ,"ஷொ" ,"ஷோ" ,"ஷௌ" # ,"ஸ" ,"ஸா" ,"ஸி" ,"ஸீ" ,"ஸு" ,"ஸூ" ,"ஸெ" ,"ஸே" ,"ஸை" ,"ஸொ" ,"ஸோ" ,"ஸௌ" # ,"ஹ" ,"ஹா" ,"ஹி" ,"ஹீ" ,"ஹு" ,"ஹூ" ,"ஹெ" ,"ஹே" ,"ஹை" ,"ஹொ" ,"ஹோ" ,"ஹௌ" # ,"க்ஷ" ,"க்ஷா" ,"க்ஷி" ,"க்ஷீ" ,"க்ஷு" ,"க்ஷூ" ,"க்ஷெ" ,"க்ஷே" ,"க்ஷை" ,"க்ஷொ" ,"க்ஷோ" ,"க்ஷௌ" ] # grantha_uyirmei_letters = tamil_letters[tamil_letters.index("கா")-1:].clone() # def uyirmei_constructed( mei_idx, uyir_idx): # """ construct uyirmei letter give mei index and uyir index """ # idx,idy = mei_idx,uyir_idx # assert ( idy >= 0 and idy < uyir_len() ) # assert ( idx >= 0 and idx < mei_len() ) # return agaram_letters[mei_idx]+accent_symbols[uyir_idx] # def tamil( idx ): # """ retrieve Tamil letter at canonical index from array utf8.tamil_letters """ # assert ( idx >= 0 and idx < tamil_len() ) # return tamil_letters[idx] # # companion function to @tamil() # def getidx(letter): # for itr in range(0,tamil_len()): # if tamil_letters[itr] == letter: # return itr # raise Exception("Cannot find letter in Tamil arichuvadi") # ## useful part of the API: # def istamil_prefix( word ): # """ check if the given word has a tamil prefix. Returns # either a True/False flag """ # for letter in tamil_letters: # if ( word.find(letter) == 0 ): # return True # return False # if not PYTHON3: # is_tamil_unicode_predicate = lambda x: x >= unichr(2946) and x <= unichr(3066) # else: # is_tamil_unicode_predicate = lambda x: x >= chr(2946) and x <= chr(3066) # def is_tamil_unicode( sequence ): # # Ref: languagetool-office-extension/src/main/java/org/languagetool/openoffice/TamilDetector.java # if type(sequence) is list: # return list(map( is_tamil_unicode_predicate, sequence )) # if len(sequence) > 1: # return list(map( is_tamil_unicode_predicate, get_letters(sequence) )) # return is_tamil_unicode_predicate( sequence ) # def all_tamil( word_in ): # """ predicate checks if all letters of the input word are Tamil letters """ # if isinstance(word_in,list): # word = word_in # else: # word = get_letters( word_in ) # return all( [(letter in tamil_letters) for letter in word] ) # def has_tamil( word ): # """check if the word has any occurance of any tamil letter """ # # list comprehension is not necessary - we bail at earliest # for letters in tamil_letters: # if ( word.find(letters) >= 0 ): # return True # return False # def istamil( tchar ): # """ check if the letter tchar is prefix of # any of tamil-letter. It suggests we have a tamil identifier""" # if (tchar in tamil_letters): # return True # return False # def istamil_alnum( tchar ): # """ check if the character is alphanumeric, or tamil. # This saves time from running through istamil() check. """ # return ( tchar.isalnum( ) or istamil( tchar ) ) # def reverse_word( word ): # """ reverse a Tamil word according to letters not unicode-points """ # op = get_letters( word ) # op.reverse() # return "".join(op) # ## find out if the letters like, "பொ" are written in canonical "ப + ொ"" graphemes then # ## return True. If they are written like "ப + ெ + ா" then return False on first occurrence # def is_normalized( text ): # TLEN,idx = len(text),1 # kaal = "ா" # sinna_kombu, periya_kombu = "ெ", "ே" # kombugal = [sinna_kombu, periya_kombu] # def predicate( last_letter, prev_letter): # if ((last_letter == kaal) and (prev_letter in kombugal)): # return True # return False # if TLEN < 2: # return True # elif TLEN == 2: # if predicate( text[-1], text[-2] ): # return False # return True # a = text[0] # b = text[1] # assert idx == 1 # while (idx < TLEN): # if predicate(b,a): # return False # a=b # idx = idx + 1 # if idx < TLEN: # b=text[idx] # # reached end and nothing tripped us # return True # def _make_set(args): # if PYTHON3: # return frozenset(args) # return set(args) # grantha_agaram_set = _make_set(grantha_agaram_letters) # accent_symbol_set = _make_set(accent_symbols) # uyir_letter_set = _make_set(uyir_letters) # _all_symbols = copy( accent_symbols ) # _all_symbols.extend( pulli_symbols ) # all_symbol_set = _make_set(_all_symbols) # # same as get_letters but use as iterable # def get_letters_iterable( word ): # """ splits the word into a character-list of tamil/english # characters present in the stream """ # WLEN,idx = len(word),0 # while (idx < WLEN): # c = word[idx] # #print(idx,hex(ord(c)),len(ta_letters)) # if c in uyir_letter_set or c == ayudha_letter: # idx = idx + 1 # yield c # elif c in grantha_agaram_set: # if idx + 1 < WLEN and word[idx+1] in all_symbol_set: # c2 = word[idx+1] # idx = idx + 2 # yield (c + c2) # else: # idx = idx + 1 # yield c # else: # idx = idx + 1 # yield c # raise StopIteration # def get_words(letters,tamil_only=False): # return [ word for word in get_words_iterable(letters,tamil_only) ] # def get_words_iterable( letters, tamil_only=False ): # """ given a list of UTF-8 letters section them into words, grouping them at spaces """ # # correct algorithm for get-tamil-words # buf = [] # for idx,let in enumerate(letters): # if not let.isspace(): # if istamil(let) or (not tamil_only): # buf.append( let ) # else: # if len(buf) > 0: # yield "".join( buf ) # buf = [] # if len(buf) > 0: # yield "".join(buf) # def get_tamil_words( letters ): # """ reverse a Tamil word according to letters, not unicode-points """ # return [word for word in get_words_iterable( letters, tamil_only = True )] # if PYTHON3: # def cmp( x, y): # if x == y: # return 0 # if x > y: # return 1 # return -1 # # answer if word_a ranks ahead of, or at same level, as word_b in a Tamil dictionary order... # # for use with Python : if a > 0 # def compare_words_lexicographic( word_a, word_b ): # """ compare words in Tamil lexicographic order """ # # sanity check for words to be all Tamil # if ( not all_tamil(word_a) ) or (not all_tamil(word_b)) : # print("## ") # print(word_a) # print(word_b) # print("Both operands need to be Tamil words") # La = len(word_a) # Lb = len(word_b) # all_TA_letters = "".join(tamil_letters) # for itr in range(0,min(La,Lb)): # pos1 = all_TA_letters.find( word_a[itr] ) # pos2 = all_TA_letters.find( word_b[itr] ) # if pos1 != pos2 : # #print not( pos1 > pos2), pos1, pos2 # return cmp(pos1, pos2) # # result depends on if La is shorter than Lb, or 0 if La == Lb i.e. cmp # return cmp(La,Lb) # # return a list of ordered-pairs containing positions # # that are common in word_a, and word_b; e.g. # # தேடுக x தடங்கல் -> one common letter க [(2,3)] # # சொல் x தேடுக -> no common letters [] # def word_intersection( word_a, word_b ): # """ return a list of tuples where word_a, word_b intersect """ # positions = [] # word_a_letters = get_letters( word_a ) # word_b_letters = get_letters( word_b ) # for idx,wa in enumerate(word_a_letters): # for idy,wb in enumerate(word_b_letters): # if ( wa == wb ): # positions.append( (idx, idy) ) # return positions # def splitMeiUyir(uyirmei_char): # """ # This function split uyirmei compound character into mei + uyir characters # and returns in tuple. # Input : It must be unicode tamil char. # Written By : Arulalan.T # Date : 22.09.2014 # """ # if not isinstance(uyirmei_char, PYTHON3 and str or unicode): # raise ValueError("Passed input letter '%s' must be unicode, \ # not just string" % uyirmei_char) # if uyirmei_char in mei_letters: # return uyirmei_char # if uyirmei_char in uyir_letters: # return uyirmei_char # if uyirmei_char not in grantha_uyirmei_letters: # raise ValueError("Passed input letter '%s' is not tamil letter" % uyirmei_char) # idx = grantha_uyirmei_letters.index(uyirmei_char) # uyiridx = idx % 12 # meiidx = int((idx - uyiridx)/ 12) # return (grantha_mei_letters[meiidx], uyir_letters[uyiridx]) # # end of def splitMeiUyir(uyirmei_char): # def joinMeiUyir(mei_char, uyir_char): # """ # This function join mei character and uyir character, and retuns as # compound uyirmei unicode character. # Inputs: # mei_char : It must be unicode tamil mei char. # uyir_char : It must be unicode tamil uyir char. # Written By : Arulalan.T # Date : 22.09.2014 # """ # if not isinstance(mei_char, PYTHON3 and str or unicode): # raise ValueError("Passed input mei character '%s' must be unicode, \ # not just string" % mei_char) # if not isinstance(uyir_char, PYTHON3 and str or unicode): # raise ValueError("Passed input uyir character '%s' must be unicode, \ # not just string" % uyir_char) # if mei_char not in grantha_mei_letters: # raise ValueError("Passed input character '%s' is not a" # "tamil mei character" % mei_char) # if uyir_char not in uyir_letters: # raise ValueError("Passed input character '%s' is not a" # "tamil uyir character" % uyir_char) # uyiridx = uyir_letters.index(uyir_char) # meiidx = grantha_mei_letters.index(mei_char) # # calculate uyirmei index # uyirmeiidx = meiidx*12 + uyiridx # return grantha_uyirmei_letters[uyirmeiidx] # Tamil Letters # அ ஆ இ ஈ உ ஊ எ ஏ ஐ ஒ ஓ ஔ ஃ # க் ச் ட் த் ப் ற் ஞ் ங் ண் ந் ம் ன் ய் ர் ல் வ் ழ் ள் ஜ் ஷ் ஸ் ஹ் # க ச ட த ப ற ஞ ங ண ந ம ன ய ர ல வ ழ ள ஜ ஷ ஸ ஹ # க கா கி கீ கு கூ கெ கே கை கௌ # ச சா சி சீ சு சூ செ சே சை சொ சோ சௌ # ட டா டி டீ டு டூ டெ டே டை டொ டோ டௌ # த தா தி தீ து தூ தெ தே தை தொ தோ தௌ # ப பா பி பீ பு பூ பெ பே பை பொ போ பௌ # ற றா றி றீ று றூ றெ றே றை றொ றோ றௌ # ஞ ஞா ஞி ஞீ ஞு ஞூ ஞெ ஞே ஞை ஞொ ஞோ ஞௌ # ங ஙா ஙி ஙீ ஙு ஙூ ஙெ ஙே ஙை ஙொ ஙோ ஙௌ # ண ணா ணி ணீ ணு ணூ ணெ ணே ணை ணொ ணோ ணௌ # ந நா நி நீ நு நூ நெ நே நை நொ நோ நௌ # ம மா மி மீ மு மூ மெ மே மை மொ மோ மௌ # ன னா னி னீ னு னூ னெ னே னை னொ னோ னௌ # ய யா யி யீ யு யூ யெ யே யை யொ யோ யௌ # ர ரா ரி ரீ ரு ரூ ரெ ரே ரை ரொ ரோ ரௌ # ல லா லி லீ லு லூ லெ லே லை லொ லோ லௌ # வ வா வி வீ வு வூ வெ வே வை வொ வோ வௌ # ழ ழா ழி ழீ ழு ழூ ழெ ழே ழை ழொ ழோ ழௌ # ள ளா ளி ளீ ளு ளூ ளெ ளே ளை ளொ ளோ ளௌ # ஶ ஶா ஶி ஶீ ஶு ஶூ ஶெ ஶே ஶை ஶொ ஶோ ஶௌ # ஜ ஜா ஜி ஜீ ஜு ஜூ ஜெ ஜே ஜை ஜொ ஜோ ஜௌ # ஷ ஷா ஷி ஷீ ஷு ஷூ ஷெ ஷே ஷை ஷொ ஷோ ஷௌ # ஸ ஸா ஸி ஸீ ஸு ஸூ ஸெ ஸே ஸை ஸொ ஸோ ஸௌ # ஹ ஹா ஹி ஹீ ஹு ஹூ ஹெ ஹே ஹை ஹொ ஹோ ஹௌ # க்ஷ க்ஷா க்ஷி க்ஷீ க்ஷு க்ஷூ க்ஷெ க்ஷே க்ஷை க்ஷொ க்ஷோ க்ஷௌ
class AddDriverLocation < ActiveRecord::Migration[5.1] def change add_reference :fleets, :driver, foreign: true add_column :drivers, :location, :string end end
Rails.application.routes.draw do resources :comments devise_for :users root 'posts#index' get 'unauthorized' => 'posts#unauthorized' resources :posts resources :users end
class AddPaidAtToProducts < ActiveRecord::Migration def change add_column :products, :paid_at, :datetime end end
require File.expand_path(File.join(File.dirname(__FILE__), *%w[.. .. spec_helper])) describe '/services/index' do before :each do assigns[:services] = @services = Array.new(3) { Service.generate! } end def do_render render '/services/index' end it 'should show a summary for each service' do @services.each do |service| template.expects(:summarize).with(service) end do_render end it 'should include a link to add a new service' do do_render response.should have_tag('a[href=?]', new_service_path) end it 'should include a link to edit each service' do do_render @services.each do |service| response.should have_tag('a[href=?]', edit_service_path(service)) end end it 'should include a link to delete each service if it is safe to delete the service' do @services.each { |service| service.stubs(:safe_to_delete?).returns(true) } do_render @services.each do |service| response.should have_tag('a[href=?]', service_path(service), :text => /[Dd]elete/) end end it 'should not include a link to delete each service if it is not safe to delete the service' do @services.each { |service| service.stubs(:safe_to_delete?).returns(false) } do_render @services.each do |service| response.should_not have_tag('a[href=?]', service_path(service), :text => /[Dd]elete/) end end end
class Order < ActiveRecord::Base belongs_to :user has_many :order_items has_many :items, through: :order_items before_create :create_from_cart enum status: %w(ordered paid cancelled completed) attr_accessor :cart_data def total order_items.inject(0) do |subtotal, order_item| subtotal + (order_item.item.final_price * order_item.quantity) end end private def create_from_cart if cart_data cart_data.each do |item_id, quantity| order_items.build(quantity: quantity, item_id: item_id.to_i, order_id: id) end end end end
class UsersController < ApplicationController before_filter :authenticate_user!, :search def index @users = User.order("email ASC") end def new @user = User.new end def create @user = User.new(params[:user]) if @user.save redirect_to(users_path, notice: 'User was successfully created.') else render action: :new end end def edit @user = User.find(params[:id]) end def update if params[:user][:password].blank? params[:user].delete(:password) params[:user].delete(:password_confirmation) end @user = User.find(params[:id]) if @user.update_attributes(params[:user]) sign_in(@user, bypass: true) redirect_to(users_path, notice: 'User was successfully updated.') else render action: :edit end end def destroy @current_user = current_user @user = User.find(params[:id]) @user.destroy sign_in(@current_user, bypass: true) redirect_to users_path end end
helpers do def username session[ :identity ] ? 'Hello ' + session[ :identity ] : 'Hello stranger' end def simstate '<a href="/simulation">' + simstate_text + '</a>' end def can_configure? @snapshot.state.nil? || @snapshot.aborted? end def can_simulate? @snapshot.created? end def can_simulate_pause? @snapshot.running? end def can_simulate_resume? @snapshot.paused? end def can_simulate_abort? @snapshot.running? end def simstate_text if @snapshot.created? return 'waiting to start' elsif @snapshot.paused? return 'paused' elsif @snapshot.running? return 'running' elsif @snapshot.aborted? return 'stopped' end return 'non existant' end def try_adding_player( params ) return false if params[ :crew ].nil? or not params[ :crew ].length begin $runner.join( Crews.const_get( params[ :crew ] ) ) return true end end def try_setting_simulation( params ) return false unless params[ :simulate ] action = params[ :simulate ].keys.first method = ( 'try_' + action + '_simulation' ).to_sym return false unless respond_to?( method ) send( method, params ) return true end def try_generate_simulation( params ) $runner.with( { :universe => { :size => params[ :universe ][ :size ].to_i } } ) $runner.create end def try_start_simulation( params ) $runner.simulate end def try_pause_simulation( params ) $runner.pause end def try_resume_simulation( params ) $runner.resume end def try_abort_simulation( params ) $runner.abort end def get_crews Crews.constants.map do |crew| Crews.const_get crew end end def menu_li( route, text ) link = '<a href="' + route + '">' + text + '</a>' if route == request.path_info return '<li class="active">' + link + '</li>' end return '<li>' + link + '</li>' end def prettify_time( t ) ms = t * 1000 return "#{ ms.round() } ms" if ms < 1000 "#{ t.round 2 } s" end end
require "rspec/autorun" TracePoint.new(:end) do |tp| klass = tp.self if defined?(Minitest) && defined?(Minitest::Test) && klass != Minitest::Test && klass.ancestors.include?(Minitest::Test) klass.generate_rspec_tests end end.enable module Assertions def assert_equal(a, b) expect(a).to eq b end def refute_equal(a, b) expect(a).to_not eq b end def assert(a) expect(a).to be_truthy end def refute(a) expect(a).to be_falsy end attr_accessor :rspec def method_missing(name, *args, &block) if rspec.respond_to?(name) rspec.send(name, *args, &block) else super end end def respond_to_missing?(name, _) rspec.respond_to?(name) || super end end module Minitest class Test include Assertions def self.generate_rspec_tests test_methods = instance_methods(false).map(&:to_s).grep(/test_/) klass = self RSpec.describe self do if klass.new.respond_to?(:setup) before(:each) do instance = klass.new # instance variables set in `setup` need to be visible in the test # methods. So wee need to store the instance so we can get at it # later instance_variable_set(:"@__trust_me_instance", instance) instance.rspec = self instance.send(:setup) end end if klass.new.respond_to?(:teardown) after(:each) do instance = instance_variable_get(:"@__trust_me_instance") || raise("`@__trust_me_instance` never set") instance.rspec = self instance.send(:teardown) end end test_methods.each do |name| spec_doc = name.to_s.sub("test_", "") it spec_doc do instance = instance_variable_get(:"@__trust_me_instance") || begin instance = klass.new # we again need to store the instance, this time so `teardown` # can access it instance_variable_set(:"@__trust_me_instance", instance) instance end instance.rspec = self instance.send(name) end end end end end end
class Candy attr_reader :candy, :sugar_level def initialize(candy, sugar_level = 0) @candy = candy @sugar_level = sugar_level end def type candy end end
class Chapter require 'redcarpet/render_strip' attr_accessor :bid, :pid, :sid, :suid, :cid include Mongoid::Document include Mongoid::Slug field :chap, as: :chapter field :t, as: :title field :alt, as: :alt_title field :subt, as: :subtitle field :desc, as: :description field :no, type: Integer field :ordr, as: :order, type: Integer field :dt, as: :date field :dto, as: :date_obj, type: Date field :yr, as: :year, type: Integer field :mo, as: :month, type: Integer field :dts, as: :date_start, type: Integer field :dte, as: :date_end, type: Integer field :mts, as: :month_start, type: Integer field :mte, as: :month_end, type: Integer field :yrs, as: :year_start, type: Integer field :yre, as: :year_end, type: Integer field :loc, as: :location field :mot, as: :motto, type: String # for Life Divine field :txt field :exc, as: :excerpt field :type field :path, type: Array field :url slug :t field :prvt field :prvu field :nxtt field :nxtu field :conc, as: :concordance, type: Hash embedded_in :readable, polymorphic: true embeds_many :segments, cascade_callbacks: true embeds_many :items, as: :itemised, cascade_callbacks: true def text(*args) if args.length == 0 raw = false else raw = args[0] end text = '' if txt text = txt elsif items.length > 0 text = get_items(items, false, raw) elsif segments.length > 0 text = get_segments(segments, raw) end text end def get_concordance parser = Redcarpet::Markdown.new(Redcarpet::Render::StripDown) words = parser.render(self.text(true)).gsub(/\[\^\d\]|\[\^\d\]:|\(|\)/, '').gsub(/\n|—/, ' '). gsub(/[^0-9 A-Z\'’a-z\-À-ü]/, '').downcase.split(' ').reject { |w| /\d|^\d+.\d+$/.match(w) } frequency = Hash.new(0) # words.each { |word| frequency[word] += 1 } words.each do |word| if (!%w('twas ’twas 'tis ’tis).include?(word)) # matchSingleQuoted = /^['|’](.*)['|’]?$|(.*)['|’]?$/.match(word) # word = matchSingleQuoted.nil? ? word : matchSingleQuoted.captures[0] # word = word.gsub(/'|’/, '').strip word = word.start_with?("'", "’") ? word[1, word.length - 1] : word word = word.end_with?("'", "’") ? word[0, word.length - 1] : word end frequency[word] += 1 end # Hash[frequency.sort] frequency end private def get_segments(segments, raw) segment_txt = '' new_para = "\n\n" segments.each_with_index do |segment, i| segment_txt += new_para + '---' if i > 0 && !raw segment_txt += new_para + '## ' + segment.t if segment.t && !raw segment_txt += new_para + '### ' + segment.subt if segment.subt && !raw segment_txt += get_items(segment.items, true, raw) end segment_txt end def get_items(items, hasSegments, raw) item_txt = '' new_para = "\n\n" items.each_with_index do |item, i| item_txt += new_para + '---' if i > 0 && !raw if item.t && !raw item_txt += new_para if i > 0 if hasSegments item_txt += new_para + '#### ' + item.t else item_txt += '## ' + item.t end end if item.subt && !raw item_txt += new_para if i > 0 || item.t if hasSegments && !raw item_txt += new_para + '##### ' + item.subt else item_txt += '### ' + item.subt end end item_txt += !raw ? new_para + item.txt : item.txt end item_txt end end
require 'spec_helper' describe "/notifiers/index.html.erb" do include NotifiersHelper before(:each) do assigns[:notifiers] = [ stub_model(Notifier, :url => "value for url" ), stub_model(Notifier, :url => "value for url" ) ] end it "renders a list of notifiers" do render response.should have_tag("ul li", "value for url".to_s, 2) end end
class MicrocosmsController < ApplicationController before_action :set_microcosm, only: [:show, :show_editors, :show_changesets, :show_organizers, :show_members, :edit, :update, :destroy, :welcome_editor, :welcome_editor_form] before_action :set_microcosm_by_key, only: [:show_by_key] before_action :authenticate, :except => [:index, :show, :show_by_key] # TODO inherit helper_method :recent_first_editors helper_method :current_changesets helper_method :organizer_names # GET /microcosms # GET /microcosms.json def index @microcosms = Microcosm.order(:name) end # GET /microcosms/1 # GET /microcosms/1.json def show end # GET /microcosms/mycity # GET /microcosms/mycity.json def show_by_key render action: "show" end def show_editors end def show_changesets end def show_organizers end def show_members end # GET /microcosms/new def new @microcosm = Microcosm.new end # GET /microcosms/1/edit def edit end # POST /microcosms # POST /microcosms.json def create @microcosm = Microcosm.new(microcosm_params) respond_to do |format| if @microcosm.save format.html { redirect_to @microcosm, notice: 'Microcosm was successfully created.' } format.json { render :show, status: :created, location: @microcosm } else format.html { render :new } format.json { render json: @microcosm.errors, status: :unprocessable_entity } end end end # PATCH/PUT /microcosms/1 # PATCH/PUT /microcosms/1.json def update respond_to do |format| if @microcosm.update(microcosm_params) format.html { redirect_to @microcosm, notice: 'Microcosm was successfully updated.' } format.json { render :show, status: :ok, location: @microcosm } else format.html { render :edit } format.json { render json: @microcosm.errors, status: :unprocessable_entity } end end end # DELETE /microcosms/1 # DELETE /microcosms/1.json def destroy @microcosm.destroy respond_to do |format| format.html { redirect_to microcosms_url, notice: 'Microcosm was successfully destroyed.' } format.json { head :no_content } end end def recent_first_editors @rfe = User.includes(:first_edit).order('uid::int desc').first(40) end def current_changesets MicrocosmChangeset.includes(:user).where(microcosm_id: @microcosm.id).where(review_num: 0).last(10) end def organizer_names @microcosm.organizers.map { |organizer| # names = organizer.user.name.split(' ') # names.first + ' ' + names.last.first organizer.user.name }.join(', ') end def discover_changesets @microcosm = Microcosm.find(params[:microcosm_id]) # Get the greatest known changeset_id for this microcosm. max_id = MicrocosmChangeset.where(microcosm_id: @microcosm.id).maximum('changeset_id') || 0 count_default = 10; count_max = 10000 limit = [params.fetch(:count, count_default).to_i, count_max].min Osm::Changeset.where("? < max_lon and min_lon < ? and ? < max_lat and min_lat < ?", @microcosm.min_lon, @microcosm.max_lon, @microcosm.min_lat, @microcosm.max_lat).where("? < id", max_id).order(:id).limit(limit).each do |changeset| # Copy the user osm_user = Osm::User.find(changeset.user_id) u = User.find_or_create_by(uid: changeset.user_id) do |u| u.uid = changeset.user_id u.name = osm_user.display_name u.created_at = osm_user.creation_time u.updated_at = osm_user.creation_time end # TODO: Use default value for review_num. mc = MicrocosmChangeset.new(microcosm_id: @microcosm.id, changeset_id: changeset.id, user_id: u.id, review_num: 0) mc.save(validate: false) end render action: "show" end def welcome_editor editor = User.find(params[:editor_id]) editor.welcomed = true editor.save redirect_to @microcosm end def welcome_editor_form @editor = User.find(params[:editor_id]) @subject = 'Welcome to OpenStreetMap' @welcome_message = @microcosm.welcome_message.sub! '{{name}}', @editor.name @qs = URI.encode_www_form([['message[title]', @subject], ['message[body]', @welcome_message]]) render 'welcome_editor_form' end private # Use callbacks to share common setup or constraints between actions. def set_microcosm @microcosm = Microcosm.find(params[:id]) end def set_microcosm_by_key @microcosm = Microcosm.find_by(key: params[:key]) end # Never trust parameters from the scary internet, only allow the white list through. def microcosm_params params.require(:microcosm).permit(:name, :key, :facebook, :twitter, :lat, :lon, :min_lat, :max_lat, :min_lon, :max_lon, :description, :welcome_message) end end
require 'zlib' # @private Implements the +write+ method for strings, used with zlib to # use GZStrings as the target for compression. class GZString < String alias write << end
require 'spec_helper' class TestPageWithElement extend SPV::Mixins::Element class << self def element(*); end end def test_el1; end def test_el2 'original element' end link_vcr_with_element :test_el2 end describe SPV::Mixins::Element do describe '.element_with_vcr' do subject do TestPageWithElement.instance_eval do element_with_vcr :test_el1, '#test_selector', visible: false end end it 'calls the original element method with given arguments' do expect(TestPageWithElement).to receive(:element).with( :test_el1, '#test_selector', visible: false ) subject end it 'links vcr with an element' do expect(TestPageWithElement).to receive(:link_vcr_with_element).with( :test_el1 ) subject end end describe '.link_vcr_with_element' do context 'when a method for getting an element is called' do let(:page) { TestPageWithElement.new } let(:vcr_el) { 'vcr element' } subject { page.test_el2 } it 'initializes a new instance of an element' do expect(SPV::Element).to receive(:new).with( 'original element', page ).and_return(vcr_el) expect(subject).to eq(vcr_el) end end end end
class Comment < ApplicationRecord belongs_to :gossip belongs_to :user validates :content, length: { minimum: 3 } end
module Spider class Proxy < Struct.new(:host, :port, :user, :password) DEFAULT_PORT = 8080 def initialize(attributes={}) super( attributes[:host], attributes.fetch(:port,DEFAULT_PORT), attributes[:user], attributes[:password] ) end def enabled? !host.nil? end def disabled? host.nil? end end end
Types::VTDomainType = GraphQL::ObjectType.define do name "VTDomain" field :hostname, types.String, hash_key: 'hostname' field :last_resolved, types.String, hash_key: 'last_resolved' field :whois, types.String, hash_key: 'whois' field :whois_timestamp, types.String, hash_key: 'whois_timestamp' field :categories, types[types.String], hash_key: 'categories' field :subdomains, types[types.String], hash_key: 'subdomains' field :samples, types[Types::VTFileType] do argument :pivot, types.Boolean, default_value: false description "Pivotable file samples" resolve ->(obj, args, ctx) { obj.select{|key| key.match(/.*_samples/) }.values.flatten.map do |res| if args['pivot'] res.merge! Uirusu::VTFile.query_report(VTAPI, res['sha256'], allinfo: 1) end res end } end field :resolutions, types[Types::VTAddressType] do description "Pivotable IP Resolutions" argument :pivot, types.Boolean, default_value: false resolve ->(obj, args, ctx) { obj['resolutions'].map do |res| if args['pivot'] res.merge! Uirusu::VTIPAddr.query_report(VTAPI, res['ip_address']) end res end } end field :raw, types.String do description "Response as raw JSON" resolve ->(obj, args, ctx) { obj.to_json } end end
require 'benchmark' namespace :benchmark do task :setup do ENV['ITERATIONS'] ||= '100000' end desc 'Benchmark Yeah::Vector' task :vector => :setup do |task| require 'yeah/vector' Benchmark.bm(10) do |bm| iterations = ENV['ITERATIONS'].to_i a = Yeah::Vector.new(10, 20, 30) b = Yeah::Vector.new(-5, -5, -5) bm.report('+') do iterations.times { |i| a + b } end bm.report('-') do iterations.times { |i| a - b } end bm.report('*') do iterations.times { |i| a * 5 } end bm.report('/') do iterations.times { |i| a / 5 } end bm.report('+@') do iterations.times { |i| +a } end bm.report('-@') do iterations.times { |i| -a } end bm.report('length') do iterations.times { |i| a.length } end bm.report('distance_to') do iterations.times { |i| a.distance_to(b) } end bm.report('angle_to') do iterations.times { |i| a.angle_to(b) } end radian = Math::PI * 45 / 180 bm.report('along') do iterations.times { |i| a.along(radian, 10) } end bm.report('along!') do iterations.times { |i| a.along!(radian, 10) } end end end end
require 'spec_helper' describe Subscription do let(:plan) { FactoryGirl.create :volume_plan } subject { Subscription.create account_id:10, plan_id: plan.id } describe '#use' do it 'updates the usage' do # TODO: Not sure why the following is throwing an error # expect { subject.use 10 }.to change(subject.usage).by(10) # Failure/Error: expect { subject.use 10 }.to change(subject.usage).by(10) # TypeError: # nil is not a symbol subject.usage.should == 0 subject.use 10 subject.usage.should == 10 end end describe '#remaining' do it 'is the remaining quota' do subject.use 15 subject.remaining.should == (subject.plan.quota-15) end end describe '#enough_quota?' do it 'is always true if subscribed to unlimited plan' do plan = FactoryGirl.create :time_plan subject = Subscription.create account_id:10, plan_id: plan.id subject.should be_enough_quota(10) end it 'is true if we have enough' do subject.should be_enough_quota(subject.remaining/2) end it 'is false if plan is expired' do subject.stub :expired? => true subject.should_not be_enough_quota(1) end end describe '#auto_renew?' do it 'is true if plan is also auto renew' do free_plan = FactoryGirl.create :free_plan subject = Subscription.create account_id:10, plan_id:free_plan.id subject.should be_auto_renew end end describe '#renew' do it 'reset expired_at' do subject.expired_at.should_not be_nil end it 'resets usage' do subject.use 100 expect { subject.renew }. to change { subject.usage }.from(100).to(0) end end describe '#expired?' do it 'is false if it has not been expired' do plan = FactoryGirl.create :quota_plan subscripton = Subscription.create account_id:10, plan_id: plan.id subscripton.should_not be_expired end it 'is true if plan has expired' do DateTime.should_receive(:now).and_return(1.years.from_now) subject.should be_expired end end describe '#notify' do it 'emails users about usage close to subscribed plan' it 'does nothing if we have previously notified user' end describe '#subscribe' do # ensure we have a payment object let(:payment) { FactoryGirl.create :payment } before { subject.payment = payment } it 'creates payment object from given token' it 'updates card of existing customer' it 'subscribes to given plan' let(:exception) { mock } it 'returns false if payment was not successful' do subject.payment.should_receive(:subscribe).and_raise (subject.subscribe mock).should be_false end end end
require 'test_helper' class InvigilatorsControllerTest < ActionDispatch::IntegrationTest setup do @invigilator = invigilators(:one) end test "should get index" do get invigilators_url assert_response :success end test "should get new" do get new_invigilator_url assert_response :success end test "should create invigilator" do assert_difference('Invigilator.count') do post invigilators_url, params: { invigilator: { name: @invigilator.name } } end assert_redirected_to invigilator_url(Invigilator.last) end test "should show invigilator" do get invigilator_url(@invigilator) assert_response :success end test "should get edit" do get edit_invigilator_url(@invigilator) assert_response :success end test "should update invigilator" do patch invigilator_url(@invigilator), params: { invigilator: { name: @invigilator.name } } assert_redirected_to invigilator_url(@invigilator) end test "should destroy invigilator" do assert_difference('Invigilator.count', -1) do delete invigilator_url(@invigilator) end assert_redirected_to invigilators_url end end
class PharmItemsController < ApplicationController before_action :set_pharm_item, only: [:show, :edit, :update, :destroy] def index @pharm_items = PharmItem.all new respond_to do |format| format.html format.xlsx end end def new @pharm_item = PharmItem.new @pharm_item.pharm_item_sub_classes.build @subclasses = SubClass.all @marketers = Marketer.all @unit_doses = UnitDose.all @pharm_item.brands.build end def edit @itemclasses = ItemClass.all @pharm_item.pharm_item_sub_classes.build @marketers = Marketer.all @unit_doses = UnitDose.all @pharm_item.brands.build end def create @pharm_item = PharmItem.new(pharm_item_params) begin #authorize @pharm_item @pharm_item.pharm_item_sub_classes.build(params[:sub_class_ids])if (params[:sub_class_ids]).present? @pharm_item.critical_levels @pharm_item.save! #unless @pharm_item.has_brand? == true rescue ActiveRecord::RecordInvalid => invalid @error = invalid.record.errors.full_messages.first end end def update @pharm_item.attributes = pharm_item_params #authorize @pharm_item @pharm_item.critical_levels #if @pharm_item.has_brand? == true @pharm_item.save! end def destroy #authorize @pharm_item @error = @pharm_item.errors.full_messages.to_sentence unless @pharm_item.destroy! end private def set_pharm_item @pharm_item = PharmItem.find(params[:id]) end def pharm_item_params params.require(:pharm_item).permit(:name,{:sub_class_ids=>[]},:central_restock_level,:central_critical_level,:main_restock_level, :main_critical_level,:dispensary_restock_level,:dispensary_critical_level,:ward_restock_level,:ward_critical_level, brands_attributes: [:id, :name,:pack_bundle, :marketer_id, :unit_dose_id, :concentration, :item_concentration_unit_id, :pack_size,:pharm_item_id,:min_dispensable]) end end
# frozen_string_literal: true # == Schema Information # # Table name: events # # attendance_limit :bigint(8) # city :string(255) not null # country :string(255) not null # created_at :timestamptz not null # days_to_charge :bigint(8) default(7) # end_date :timestamptz # event_image :string(255) # event_nickname :string # event_remote :boolean default(FALSE) # event_remote_manual_link :string # event_remote_platform_mail :string # event_remote_platform_name :string # event_schedule_link :string # full_price :decimal(10, ) # id :bigint(8) not null, primary key # link :string(255) # main_email_contact :string(255) not null # name :string(255) # privacy_policy :string # start_date :timestamptz # state :string(255) not null # updated_at :timestamptz not null # class Event < ApplicationRecord mount_uploader :event_image, RegistrationsImageUploader has_many :attendances, dependent: :restrict_with_exception has_many :registration_periods, dependent: :destroy has_many :registration_quotas, dependent: :destroy has_many :registration_groups, dependent: :destroy has_many :slack_configurations, dependent: :destroy, class_name: 'Slack::SlackConfiguration' has_and_belongs_to_many :organizers, class_name: 'User' validates :start_date, :end_date, :full_price, :name, :main_email_contact, :attendance_limit, :country, :state, :city, presence: true validate :period_valid? scope :active_for, ->(date) { where('end_date > ?', date) } scope :not_started, -> { where('start_date > ?', Time.zone.today) } scope :ended, -> { where('end_date < ?', Time.zone.today) } scope :events_to_welcome_attendances, -> { where('date(start_date) <= :limit_date AND date(end_date) >= :end_limit_date', limit_date: 4.days.from_now.to_date, end_limit_date: Time.zone.today) } def full? places_sold = reserved_count + attendances.active.size attendance_limit.present? && attendance_limit.positive? && (attendance_limit <= places_sold) end def registration_price_for(attendance, payment_type) group = attendance.registration_group return group.amount if group.present? && group.amount.present? && group.amount.positive? extract_value(attendance, payment_type) end def period_for(now = Time.zone.now) registration_periods.for(now).first if registration_periods.present? end def find_quota registration_quotas.order(order: :asc).select(&:vacancy?) end def started Time.zone.today >= start_date end def add_organizer(user) organizers << user unless organizers.include?(user) save end def remove_organizer(user) organizers.delete(user) save end def contains?(user) attendances.active.where(user: user).present? end def attendances_in_the_queue? !attendances.waiting.empty? end def queue_average_time attendances_passed_by_queue = attendances.active.with_time_in_queue return 0 if attendances_passed_by_queue.empty? attendances_passed_by_queue.sum(:queue_time) / attendances_passed_by_queue.count end def agile_alliance_discount_group? agile_alliance_discount_group.present? end def agile_alliance_discount_group registration_groups.find_by(name: 'Membros da Agile Alliance') end def capacity_left attendance_limit - (attendances.active.size + reserved_count) end def attendances_count attendances.active.count + reserved_count end def reserved_count RegistrationGroupRepository.instance.reserved_for_event(self) end def average_ticket attendances_confirmed = attendances.committed_to return 0 if attendances_confirmed.empty? attendances_confirmed.sum(:registration_value) / attendances_confirmed.count end def ended? end_date < Time.zone.now end def event_image_valid? return false if event_image.blank? NetServices.instance.url_found?(event_image.url) end private # TODO: bad logic here - fixing needed def extract_value(attendance, payment_type) quota = find_quota if payment_type == 'statement_agreement' full_price elsif attendance.price_band? attendance.band_value * attendance.discount elsif period_for.present? period_for.price * attendance.discount elsif quota.first.present? quota.first.price * attendance.discount else (full_price || 0) * attendance.discount end end def period_valid? return unless start_date.present? && end_date.present? errors.add(:end_date, I18n.t('activerecord.errors.models.event.attributes.end_date.invalid_period')) if start_date > end_date end end
class LatexResumeController < ApplicationController @@source_tex_file = "config/resume.tex" def index end def source root_dir = 'public/tmp/src' public_file = File.join( root_dir, 'resume_source' ) FileUtils.mkdir_p( root_dir ) FileUtils.cp( @@source_tex_file, public_file ) # dont need the 'public' in the redirect path redirect_path = public_file.gsub( /public/, '' ) redirect_to redirect_path end def generate root_dir = 'public/tmp/pdf' command = "pdflatex -output-dir=public/tmp/pdf #{@@source_tex_file}" output_file = File.join( root_dir, File.basename( @@source_tex_file, ".*" ) + ".pdf" ) raise "Error running: #{command}" unless system( command ) raise "Missing output file: #{output_file}" unless File.file? output_file # dont need the 'public' in the redirect path redirect_path = output_file.gsub( /public/, '' ) redirect_to redirect_path end end
class RefreshStripeCacheJob < ApplicationJob queue_as :default def perform(user_id) user = User.find_by(id: user_id) if user StripeCache.new(user).refresh end end end
class Bear attr_reader :name, :type def initialize(name, type) @name = name @type = type @stomach = [] end def bear_name() return @bear.name() end def bear_type() return @bear.type() end def food_count() @stomach.length() end def put_fish(fish_name) @stomach.push(fish_name) end def bear_roar() return "ROAAAAR" end end
require 'rails_helper' RSpec.describe Job, type: :model do it {should belong_to :user} it "creates a new job" do user = FactoryGirl.create(:user) job = FactoryGirl.create(:job) expect(Job.all).to include job end end
require 'rails_helper' describe Role do describe 'associations' do describe 'has_many association' do it { should have_and_belong_to_many(:users) } end describe 'belongs_to' do it { should belong_to(:resource) } end end end
# encoding: UTF-8 # Plugin Definition file # The purpose of this file is to declare to InSpec what plugin_types (capabilities) # are included in this plugin, and provide hooks that will load them as needed. # It is important that this file load successfully and *quickly*. # Your plugin's functionality may never be used on this InSpec run; so we keep things # fast and light by only loading heavy things when they are needed. # Presumably this is light require 'inspec-resource-pack/version' # The InspecPlugins namespace is where all plugins should declare themselves. # The 'Inspec' capitalization is used throughout the InSpec source code; yes, it's # strange. module InspecPlugins # Pick a reasonable namespace here for your plugin. A reasonable choice # would be the CamelCase version of your plugin gem name. # inspec-resource-pack => ResourcePack module ResourcePack # This simple class handles the plugin definition, so calling it simply Plugin is OK. # Inspec.plugin returns various Classes, intended to be superclasses for various # plugin components. Here, the one-arg form gives you the Plugin Definition superclass, # which mainly gives you access to the hook / plugin_type DSL. # The number '2' says you are asking for version 2 of the plugin API. If there are # future versions, InSpec promises plugin API v2 will work for at least two more InSpec # major versions. class Plugin < ::Inspec.plugin(2) plugin_name :'inspec-resource-pack' cli_command :generate do require 'inspec-resource-pack/cli_command' InspecPlugins::ResourcePack::GenerateCLI end end end end
class DashboardController < ApplicationController def index @filters = Rails.cache.fetch("/current_user/#{current_user.role.name}/filters", expires_in: 1.day) do current_user.filters('dashboard') end end end
class AddAssociationBetweenReportAndPlannedDisbursements < ActiveRecord::Migration[6.0] def change add_reference :planned_disbursements, :report, type: :uuid end end
class VarsController < ApplicationController # GET /vars # GET /vars.json def index @vars = Var.all respond_to do |format| format.html # index.html.erb format.json { render json: @vars } end end # GET /vars/1 # GET /vars/1.json def show @var = Var.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @var } end end # GET /vars/new # GET /vars/new.json def new @var = Var.new respond_to do |format| format.html # new.html.erb format.json { render json: @var } end end # GET /vars/1/edit def edit @var = Var.find(params[:id]) end # POST /vars # POST /vars.json def create params[:var][:value] = params[:var][:value].gsub(',','.') @var = Var.new(params[:var]) respond_to do |format| if @var.save format.html { redirect_to vars_url } format.json { render json: @var, status: :created, location: @var } else format.html { render action: "new" } format.json { render json: @var.errors, status: :unprocessable_entity } end end end # PUT /vars/1 # PUT /vars/1.json def update @var = Var.find(params[:id]) respond_to do |format| if @var.update_attributes(params[:var]) format.html { redirect_to vars_url } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @var.errors, status: :unprocessable_entity } end end end # DELETE /vars/1 # DELETE /vars/1.json def destroy @var = Var.find(params[:id]) @var.destroy respond_to do |format| format.html { redirect_to vars_url } format.json { head :no_content } end end end
require 'rails_helper' RSpec.describe CreateGameRoomService do describe '.create_new_game_room_with_player' do context 'if there was an error in the creation of the game room' do it 'returns the appropriate error hash' do GameRoom.create_game_room('house') h = CreateGameRoomService.new_game_room_and_player('house', 'khoj') expect(h).to include(:errors) expect(h[:success]).to be false end end context 'there was no error in creation of game room and player' do it 'returns the appropriate success hash' do h = CreateGameRoomService.new_game_room_and_player('house', 'khoj') expect(h).to_not include(:errors) expect(h[:success]).to be true expect(GameRoom.last.name).to eq('house') expect(GameRoom.last.players.first.name).to eq('khoj') expect(GameRoom.last.players.first.is_game_master).to be true end end end end
# frozen_string_literal: true require 'rails_helper' require 'date' RSpec.describe Pressure, type: :model do describe 'Associations' do it { should belong_to :profile } end describe 'Validations' do before do @existing_profile = FactoryBot.create :profile, email: 'joao@example.org' end it "Is valid with valid attributes" do pressure = Pressure.new(systolic: 1, diastolic: 60, date: DateTime.now, profile: @existing_profile) expect(pressure).to be_valid end it "Should have a profile associated" do pressure = Pressure.new(systolic: 1, diastolic: 60, date: DateTime.now, profile: nil) expect(pressure).to_not be_valid end it "Is not valid without a value" do pressure = Pressure.new(systolic: nil, diastolic: 60, date: DateTime.now, profile: @existing_profile) expect(pressure).to_not be_valid end it "Value should not lesser than 0" do pressure = Pressure.new(systolic: -1, diastolic: 60, date: DateTime.now, profile: @existing_profile) expect(pressure).to_not be_valid end end end
class AnnotationsController < ApplicationController respond_to :json def create a = Annotation.create(annotation_params) respond_with a, status: :ok end private def annotation_params params.require(:annotation).permit(:name, :canonical_name, :role, :role_translation, :role_language, :comment, :note_id, :approved ) end end
#!/usr/bin/env ruby # frozen_string_literal: true # Created by Paul A. Gureghian in May 2020. # # This Ruby script demos control flow in Ruby. # # Start of script. # # Prompt for input. # print "Integer please: \n" user_num = Integer(gets.chomp) if user_num < 0 puts 'Negative integer was inputed' elsif user_num > 0 puts 'Positive integer was inputed' else puts 'Zero was inputed' end # End of script. #
class AddCreatorIdToHats < ActiveRecord::Migration[5.2] def change add_column :hats, :creator_id, :integer end end
require 'drb' module RestAssured module Utils module DrbSniffer def running_in_spork? defined?(Spork) && Spork.using_spork? end end end end
class RegistrationVC < UITableViewController POSTMARK_API_KEY = "7d4a30d7-4ed1-4130-9b2b-8caa14831987" Fields = [ [t("name_field"), t("name_placeholder"), :name], [t("city_field"), t("city_placeholder"), :location], [t("zip_field"), t("zip_placeholder"), :zipcode], [t("email_field"), t("email_placeholder"), :email] ] attr_accessor :delegate ERROR_EMPTY_FIELD = 0 ERROR_INVALID_EMAIL = 1 # Initialization def viewDidLoad @values ||= Array.new(Fields.length, "") # Make a header view headerView = UIView.alloc.initWithFrame([[0, 0], [0, 60]]) descView = UITextView.alloc.initWithFrame([[10, 0], [300, 60]]) descView.editable = false descView.backgroundColor = nil descView.font = UIFont.boldSystemFontOfSize(16.0) descView.textColor = UIColor.colorWithRed(0.22, green:0.33, blue:0.5, alpha:1.0) descView.text = t("registration_description") headerView.addSubview(descView) footerView = UIView.alloc.initWithFrame([[0, 0], [0, 160]]) registerButton = UIButton.buttonWithType(UIButtonTypeRoundedRect) registerButton.frame = [[10, 10], [300, 45]] registerButton.setTitle(t("register_title"), forState:UIControlStateNormal) registerButton.addTarget(self, action:'register', forControlEvents:UIControlEventTouchUpInside) footerView.addSubview(registerButton) closeButton = UIButton.buttonWithType(UIButtonTypeRoundedRect) closeButton.frame = [[10, 60], [300, 45]] closeButton.setTitle(t("hide_title"), forState:UIControlStateNormal) closeButton.addTarget(self, action:'close', forControlEvents:UIControlEventTouchUpInside) footerView.addSubview(closeButton) vCardButton = UIButton.buttonWithType(UIButtonTypeRoundedRect) vCardButton.frame = [[10, 110], [300, 45]] vCardButton.setTitle("Jan Smit (Moose F\u00E4rg)", forState:UIControlStateNormal) vCardButton.setTitleColor(UIColor.grayColor, forState:UIControlStateDisabled) vCardButton.addTarget(self, action:'addVCard:', forControlEvents:UIControlEventTouchUpInside) footerView.addSubview(vCardButton) @iconButton = UIButton.buttonWithType(UIButtonTypeContactAdd) @iconButton.frame = [[20, 110], [45, 45]] @iconButton.setUserInteractionEnabled false footerView.addSubview(@iconButton) tableView.tableHeaderView = headerView tableView.tableFooterView = footerView end def addVCard(sender) addressBook = ABAddressBookCreate() person = ABPersonCreate() ABRecordSetValue(person, KABPersonFirstNameProperty, "Jan", nil) ABRecordSetValue(person, KABPersonLastNameProperty, "Smit", nil) ABRecordSetValue(person, KABPersonOrganizationProperty, "Moose F\u00E4rg", nil) phoneNumberMultiValue = ABMultiValueCreateMutable(KABPersonPhoneProperty); ABMultiValueAddValueAndLabel(phoneNumberMultiValue, "(+31) 06 55333165", KABPersonPhoneMobileLabel, nil); ABMultiValueAddValueAndLabel(phoneNumberMultiValue, "(+31) 0224 217071", KABPersonPhoneMainLabel, nil); ABRecordSetValue(person, KABPersonPhoneProperty, phoneNumberMultiValue, nil); emailMultiValue = ABMultiValueCreateMutable(KABPersonEmailProperty); ABMultiValueAddValueAndLabel(emailMultiValue, "jan@moosefarg.com", KABWorkLabel, nil); ABRecordSetValue(person, KABPersonEmailProperty, emailMultiValue, nil); addressMultiValue = ABMultiValueCreateMutable(KABMultiDictionaryPropertyType); dict = { KABPersonAddressStreetKey => "De Dreef 32", KABPersonAddressZIPKey => "1741 MH", KABPersonAddressCityKey => "Schagen", KABPersonAddressStateKey => "Noord-Holland", KABPersonAddressCountryKey =>"The Netherlands", KABPersonAddressCountryCodeKey => "nl" } ABMultiValueAddValueAndLabel(addressMultiValue, dict, KABWorkLabel, nil); ABRecordSetValue(person, KABPersonAddressProperty, addressMultiValue, nil); ABAddressBookAddRecord(addressBook, person, nil) ABAddressBookSave(addressBook, nil) sender.enabled = false @iconButton.enabled = false end # Data-source def numberOfSectionsInTableView(tableView) 1 end def tableView(tableView, numberOfRowsInSection:section) Fields.count end def tableView(tableView, cellForRowAtIndexPath:indexPath) field = Fields[indexPath.row] cell = UITableViewCell.alloc.initWithStyle(UITableViewCellStyleDefault, reuseIdentifier:nil) cell.selectionStyle = UITableViewCellSelectionStyleNone; cell.textLabel.text = field[0]; tf = self.textFieldWithPlaceholder(field[1]) tf.frame = [[120, 12], [170, 30]] tf.addTarget(self, action:"textFieldFinished:", forControlEvents:UIControlEventEditingDidEndOnExit) tf.delegate = self cell.addSubview(tf) cell end # Custom Textfields def textFieldWithPlaceholder(placeholder) tf = UITextField.alloc.init tf.placeholder = placeholder tf.adjustsFontSizeToFitWidth = true tf.textColor = UIColor.colorWithRed(0.22, green:0.33, blue:0.5, alpha:1.0) tf end # UITextField delegate def textFieldDidEndEditing(textField) self.textFieldFinished(textField) end def textFieldFinished(textField) # select by placeholder field = Fields.find_index { |(title, placeholder, symbol)| placeholder === textField.placeholder } @values[field] = textField.text end def error(type) text = "" case type when ERROR_EMPTY_FIELD text = t("error_empty_field") when ERROR_INVALID_EMAIL text = t("error_invalid_email") end alert = UIAlertView.alloc.init alert.title = "Error" alert.message = text alert.addButtonWithTitle(t("cancel_title")) alert.setCancelButtonIndex(0) alert.show end def register @values.each do |value| if value === "" self.error ERROR_EMPTY_FIELD return end end if not (@values[3] =~ /@/) self.error ERROR_INVALID_EMAIL return end self.send_postmark end def form_body form_body = "De volgende persoon heeft zich zojuist aangemeld voor de nieuwsbrief (via iOS) <br /> <br />" Fields.each_with_index do |(titel, placeholder, symbol), i| form_body += "<b>#{titel}</b>: #{@values[i]} <br />" end form_body += "<br /> Groet, <br /><br /> De Moose Farg iPhone app" form_body end def send_postmark apiURL = NSURL.URLWithString "http://api.postmarkapp.com/email" body = '{ "From" : "jwbuurlage@me.com", "To" : "jan@moosefarg.com", "Subject" : "Nieuwe Registratie Moose Farg Nieuwsbrief // iPhone", "Tag" : "Registratie, iPhone", "HtmlBody" : "' + form_body + '", "TextBody" : "' + form_body + '", "ReplyTo" : "jwbuurlage@me.com" }' data = body.dataUsingEncoding NSUTF8StringEncoding length = data.length.to_s request = NSMutableURLRequest.alloc.initWithURL apiURL request.HTTPMethod = "POST" request.HTTPBody = data request.setValue(length, forHTTPHeaderField:"Content-Length") request.setValue("application/json" , forHTTPHeaderField:"Content-Type") request.setValue("application/json" , forHTTPHeaderField:"Accept") request.setValue(POSTMARK_API_KEY, forHTTPHeaderField:"X-Postmark-Server-Token") completionLambda = lambda do |response, responseData, error| response = NSString.alloc.initWithData(responseData, encoding: NSUTF8StringEncoding) puts response end NSURLConnection.sendAsynchronousRequest(request, queue:NSOperationQueue.mainQueue, completionHandler: completionLambda) close end def close delegate.dismissViewControllerAnimated(true, completion:lambda {}) end end
require_relative "piece.rb" require_relative 'starting_pieces' require 'colorize' class Board attr_reader :grid def self.create_default_board grid = Array.new(8) { Array.new(8) } (0..7).each do |row| (0..7).each do |col| if BLACK_PIECES.key?([row, col]) current_piece = Piece.new(BLACK_PIECES[[row, col]], "black") current_piece.current_pos = [row, col] grid[row][col] = current_piece elsif WHITE_PIECES.key?([row, col]) current_piece = Piece.new(WHITE_PIECES[[row, col]], "white") current_piece.current_pos = [row, col] grid[row][col] = current_piece else empty_piece = Piece.new empty_piece.current_pos = [row, col] grid[row][col] = empty_piece end end end grid end def initialize(grid= Board.create_default_board) @grid = grid end def render (0..7).each do |row| (0..7).each do |col| piece = @grid[row][col] if col.even? && row.even? || col.odd? && row.odd? piece.set_square_color(:yellow) unless piece.square_color == :red || piece.square_color == :blue else piece.set_square_color(:green) unless piece.square_color == :red || piece.square_color == :blue end display_piece = @grid[row][col].display string = " #{display_piece} " # puts "PIECE" # puts string # puts "LENGTH" # puts string.length length = string.length string = string + ("" * (18 - string.length) ) # string += " " if piece == "e" print string.colorize(background: piece.square_color) end print "\n" end end def move_piece(start_pos, end_pos) row, col = pos @grid[row][col] end # def [](pos) # row,column = pos # @board[row][col] # end def is_start_position_valid?(start_pos) row, col = start_pos raise Exception.new if !row.between?(0, 7) || !col.between?(0, 7) raise Exception.new if @grid[row][col].nil? end def is_end_pos_valid?(start_pos,end_pos) row, col = end_pos start_row, start_col = start_pos raise Exception.new if !row.between?(0, 7) || !col.between?(0, 7) # raise Exception.new if !@board[row][col].nil? piece = @grid[start_row][start_col] a = piece.moves.any? do |move| piece.send(move,start_pos,end_pos) end p a end end # board.is_end_pos_valid?([1,0],[2,0])
require 'rails_helper' RSpec.describe ArticlePresenter do describe '#title' do context 'when article is sticky' do let(:article) { FactoryBot.build(:article, is_sticky: true).presenter } it 'includes "Sticky" in the beginning of title' do expect(article.title).to match(/Sticky: /) end end context 'when article is not sticky' do let(:article) { FactoryBot.build(:article, is_sticky: false).presenter } it 'includes "Sticky" in the beginning of title' do expect(article.title).not_to match(/Sticky: /) end end end describe '#host' do let(:article) do FactoryBot.build(:article, url: 'https://xkcd.com/314').presenter end it 'returns the hostname from url' do expect(article.host).to eq('xkcd.com') end end describe '#description_only?' do context 'when there is only a description' do let(:article) do FactoryBot.build(:article, description: 'description', url: '').presenter end it 'returns true' do expect(article).to be_description_only end end context 'when there is a description + url' do let(:article) do FactoryBot.build(:article, description: 'description', url: 'https://xkcd.com/314').presenter end it 'returns true' do expect(article).not_to be_description_only end end context 'when there is a no description' do let(:article) do FactoryBot.build(:article, description: '', url: 'https://xkcd.com/314').presenter end it 'returns true' do expect(article).not_to be_description_only end end end end
class DocumentParanoid include Mongoid::Document # slug, then paranoia include Mongoid::Slug include Paranoid.new field :title slug :title end
#!/usr/bin/env ruby # Copyright (c) 2006-2007, The RubyCocoa Project. # All Rights Reserved. # # RubyCocoa is free software, covered under either the Ruby's license or the # LGPL. See the COPYRIGHT file for more information. require 'rbconfig' def show_options puts "Usage:" puts " #{__FILE__} build [options] <output dir>" puts "" puts " build Create the RDoc documentation for the supported frameworks" puts '' puts "Options:" puts " The extra options only apply to 'build' option and are options passed" puts " to the actual rdocify_framework.rb script." puts " These are:" puts " -v Verbose output." puts " -f Force the output files to be written even if there were errors during parsing." puts '' puts "Output Dir:" puts " If a optional output dir is specified," puts " the documentation will be generated in that location." puts "" puts "Examples:" puts " #{__FILE__} build ~/documentation" puts " #{__FILE__} build -v -f" puts '' end def command( str ) $stderr.puts str system str or raise RuntimeError, "'system #{str}' failed" end def ruby( str ) command "#{Config::CONFIG["bindir"]}/ruby #{str}" end def rdoc( str ) command "#{Config::CONFIG["bindir"]}/rdoc #{str}" end unless ARGV[0].nil? case ARGV[0] when 'build' options = [] output_dir = '' # Check if there are any other args if ARGV.length > 1 ARGV[1..-1].each do |arg| case arg when '-v' options.push '-v' when '-f' options.push '-f' else output_dir = arg end end end # Get a reference to the output dir and create it if necessary unless output_dir.empty? output_dir = File.expand_path(output_dir) unless File.exist?(output_dir) command "mkdir -p #{output_dir}" end else output_dir = File.join(File.dirname(File.expand_path(__FILE__)), 'doc/') end DOCUMENTATION_PATH = if `sw_vers -productVersion`.strip =~ /^10\.5/ '/Developer/Documentation/DocSets/com.apple.ADC_Reference_Library.CoreReference.docset/Contents/Resources/Documents/documentation' else '/Developer/ADC Reference Library/documentation' end SUPPORTED_FRAMEWORKS = ["#{DOCUMENTATION_PATH}/Cocoa/Reference/ApplicationKit/", "#{DOCUMENTATION_PATH}/Cocoa/Reference/Foundation/", "#{DOCUMENTATION_PATH}/Cocoa/Reference/WebKit/", "#{DOCUMENTATION_PATH}/Cocoa/Reference/CoreDataFramework/", "#{DOCUMENTATION_PATH}/QuickTime/Reference/QTKitFramework/", "#{DOCUMENTATION_PATH}/UserExperience/Reference/AddressBook/", "#{DOCUMENTATION_PATH}/AppleApplications/Reference/InstantMessageFrameworkRef/", "#{DOCUMENTATION_PATH}/GraphicsImaging/Reference/QuartzFramework/"] start_time = Time.now # Setup the env ENV['DYLD_FRAMEWORK_PATH'] = File.expand_path('../build/Default') ENV['BRIDGE_SUPPORT_PATH'] = File.expand_path('../bridge-support') # Parse the rdoc for each supported framework SUPPORTED_FRAMEWORKS.each do |f| ruby "-I../../ext/rubycocoa -I../../lib gen_bridge_doc/rdocify_framework.rb #{options.join(' ')} '#{f}' #{output_dir}/ruby" end osx_additions = %w{oc_attachments.rb oc_attachments_appkit.rb oc_types.rb oc_types_appkit.rb ruby_addition.rb}.map do |file| File.expand_path(file, '../src/ruby/osx/objc/') end.join(' ') # Create the rdoc files #system "rdoc --line-numbers --inline-source --template gen_bridge_doc/allison/allison.rb gen_bridge_doc/output -o doc/html" Dir.chdir "#{output_dir}/ruby" do rdoc ". -o #{output_dir}/html #{osx_additions}" rdoc "--ri . -o #{output_dir}/ri #{osx_additions}" end puts "" puts "Total Cocoa Reference to RDoc processing time: #{Time.now - start_time} seconds" else show_options exit 1 end else show_options exit 1 end
class CreateSoliderQueues < ActiveRecord::Migration def change create_table :solider_queues do |t| t.integer :city_id t.integer :solider_num t.integer :solider_kind t.integer :status, :default => 0 t.timestamps end end end
# TODO: single, multi -> 引数で切り替え 、default value # TODO: jws! # TODO: sample web app making # String extensions module StringExtension refine String do # Combine strings by dot(.). # # @example # "sample".dot("is_test") => "sample.is_test" def dot(str) self + "." + str end def removeLastRET self.chomp end def inDoubleQuot(insert) if insert.is_a?(String) self + insert.modifyDoubleQuo end end def inSingleQuo(insert) if insert.is_a?(String) self + $SINGLE_QUO + insert + $SINGLE_QUO end end def inParenth(insert) if insert.is_a?(String) self + "(" + $SINGLE_QUO + insert + $SINGLE_QUO + ")" end end # "xxx".plus "aaa" # => "xxx" + "aaa" def plus(item) self + " + " + item end # "xxx".dQuo # => "xxx" def modifyDoubleQuo $DOUBLE_QUO + self + $DOUBLE_QUO end # "xxx".sQuo # => 'xxx' def modifySingleQuo $SINGLE_QUO + self + $SINGLE_QUO end alias_method :dQuo, :modifyDoubleQuo alias_method :sQuo, :modifySingleQuo def variable $LABEL_INSERT_START + self + $LABEL_INSERT_END end <<-VAL_Usage a = "a".dataIs "dddd"# => {:label=>"a", :data=>"dddd"} p a p a[:label] p a[:data] # >> {:label=>"a", :data=>"dddd"} # >> "a" # >> "dddd" VAL_Usage def varIs(val) {:label => self, :data => val} end def rowSpan(val) self + $ROW_SPAN + "#{val}" end def colSpan(val) self + $COL_SPAN + "#{val}" end end end # ## Symbol extension ############ module SymbolExtension refine Symbol do # To make string as variable # @example # :abc.variable => "$LABEL_INSERT_STARTabc$LABEL_INSERT_END" def variable $LABEL_INSERT_START + self.to_s + $LABEL_INSERT_END end # to meke array # @example # :id__test.varIs "sample" => {:label => "id__test", :data => "sample"} def varIs(val) {:label => self.to_s, :data => val} end # @return [string] divid by "__" # @example # :id__test.divid => "test" def divid sim = self.to_s elem = sim.split "__" elem end # :id__test => true # :id_test => false def hasDoubleUnderBar? ans = self.to_s return true if ans.include? "__" false end end end # ## Array extension ############ module ArrayExtension refine Array do # @example # a = [1,2,3] # b = [4,5,6] # a.append b # => [1, 2, 3, 4, 5, 6] def append(element) self << element self.flatten! end # @example # a = [1,2,3] # b = [4,5,6] # a.appends [11,22], [33,55] # => [1, 2, 3, [4, 5, 6]] # p a # => [1, 2, 3, 11, 22, 33, 55] def appends (*element) element.each do |a| self.append a end end end end module Jabverwock using StringExtension using ArrayExtension using SymbolExtension # global constant ############ $SINGLE = "need single mode" $MULTI = "need multi mode" $MT = $MULTI $SL = $SINGLE $RET = "\n" $TAB = "\t" $SPC = " " $COMMA = "," $COLON = ":" $SEMI_COLON = ";" $JS_CMD_END = $SEMI_COLON $DOUBLE_QUO = "\"" $SINGLE_QUO = "'" $EQUAL = "=" $INSERTSTRING = "%%" $STYLE_CONTENT = "##STYLE##" $LABEL_INSERT_START = "##LABELSTART##" $LABEL_INSERT_END = "##LABELEND##" $JS_UNITS_PREFIX = "js" ## struct ########## $CHILD = "_c_" $MEMBER = "_m_" $ENDMARK = "_e_" ## Table #################### $BR = "<br>" $ROW_SPAN = "%rowSpan=" $COL_SPAN = "%colSpan=" ## Css #################### $ID_ELEM_ID = "id::" $ID_ELEM_CLS = "cls::" # CSS border style list # # none, hidden, dotted, dashed, solid, double, groove, ridge, inset, outset # # @return [String] border style # @example css.border_style = STYLE.NONE # "css {\nborder-style: none;\n}" module STYLE class << self styles = %w(none hidden dotted dashed solid double groove ridge inset outset) styles.each do |s| define_method s.upcase do "#{s}" end end end end # CSS origin property list # # border, padding, content # @return [String] property style # @example # css.background_origin = ORIGIN.BORDER # => "{\nbackground-origin: border-box;\n}" module ORIGIN class << self origin = %w(border padding content) origin.each do |o| define_method o.upcase do "#{o}-box" end end end end # CSS attachment property list # # scroll, fixed, local # @return [String] attachment property module ATTATCHMENT class << self atta = %w(scroll fixed local) atta.each do |a| define_method a.upcase do "#{a}" end end end end # CSS repeat property list module REPEAT class << self def repeatTemp(r) @result ||= "" @result << r + $SPC self end # @return [String] def Yes() repeatTemp "repeat" end # @return [String] def No() repeatTemp "no-repeat" end # @return [String] def X() repeatTemp "repeat-x" end # @return [String] def Y() repeatTemp "repeat-y" end # @return [String] def SPC() repeatTemp "space" end # @return [String] def ROUND() repeatTemp "round" end # @return [String] def val() @result ||= "" ans = @result.rstrip @result = "" ans end end end # express url property module URL class << self # @return [String] # @example css.background_image = URL.url 'paper.gif'.dQuo # "css {\nbackground-image: url(\"paper.gif\");\n}" def url(str) "url(#{str})" end end end # express color property module Color class << self # rgb color # @param [String] red value # @param [String] green value # @param [String] blue value # @return [String] def rgb(red, green, blue) "rgb(#{red}, #{green}, #{blue})" end end end #This is utilities for css.rb module CssUtil class << self # koko now # def nameWithDividStr(sel, divi) # sel.inject("") do |name, s| # next name << s if name == "" # name << divi << s # end # end # def useCore(sel, arr) # ans = [] # se # l.each do |s| # next ans << idElm(arr) if includeID s,arr # next ans << clsElm(arr) if includeCls s,arr # next ans.unshift useCoreWithName(arr) if s == :name # end # ans # end # def useCoreWithName(arr) # ans = [] # arr.each do |v| # ans.unshift v unless include_ID_ELEM_ID(v) || include_ID_ELEM_CLS(v) # end # ans # end # def include_ID_ELEM_ID(val) # val.include?($ID_ELEM_ID) ? true : false # end # def include_ID_ELEM_CLS(val) # val.include?($ID_ELEM_CLS) ? true : false # end # def includeID(elm, arr) # KSUtil.isID(elm.to_s) && symbolInclude(:id,arr) ? true:false # end # def includeCls(elm,arr) # KSUtil.isCls(elm.to_s) && symbolInclude(:cls, arr) ? true : false # end # def dividBySpace(str) # str.split # end # def idElm(arr) # index = findIDIndex arr # removeIDIndex arr[index] # end # def clsElm(arr) # index = findClsIndex arr # removeClsIndex arr[index] # end # def symbolInclude(sym, arr) # arr.each do |a| # return true if a.include? sym.to_s # end # false # end # def hasSymbolArrTargetSymbol(sym,symArr) # symArr.each do |s| # return true if s == sym # end # false # end # def findIDIndex(arr) # arr.index{ |f| f =~ /^#{$ID_ELEM_ID}/ } # end # def findClsIndex(arr) # arr.index{ |f| f =~ /^#{$ID_ELEM_CLS}/ } # end # def removeIDIndex(str) # str.split($ID_ELEM_ID).last # end # def removeClsIndex(str) # str.split($ID_ELEM_CLS).last # end end end # This module provide utility for hash # Hash needs made by seqHash function in jabverwock # make hash with js keyword module KSHash # FIRST_KEY is keyword and symbol eqal to ":js1" FIRST_KEY = "#{$JS_UNITS_PREFIX}1".to_sym class << self # # @param [String] val hash value # @param [Int] step make symbol like js1: # @return [Hash] # @example # seqHash "test", 1 => {:js1 => "test"} def seqHash(val,step) sym = "#{$JS_UNITS_PREFIX}#{step}".to_sym {sym => val} end # @param [Hash] hash target hash # @return [String] value of hash[0] def firstHashValue(hash) hash[FIRST_KEY] end # @param [Hash] hash target hash # @return [String] value of last hash def lastHashValue(hash) lk = lastHashKey hash ans = hash[lk] ans ||= '' end # @param [Hash] hash target hash # @return [String] key of last hash def lastHashKey(hash) lastKey = FIRST_KEY #:a1 hash.each_key do |k| lastKey = k if compareKeys(k, lastKey) end lastKey end # @param [Symbol] a symbol made by seqHash function # @param [Symbol] b symbol made by seqHash function # @return [Bool] whether a is bigger key # @example hash key used by seqHash function is like :js1 # compareKeys :js2, :js1 => true def compareKeys(a,b) return true if removePrefix(a) > removePrefix(b) false end # @param [Symbol] k symbol # @return [Int] # @example remove string = $JS_UNITS_PREFIX # $JS_UNITS_PREFIX + "1" => 1 def removePrefix(k) k.to_s.gsub($JS_UNITS_PREFIX,"").to_i end def hashValues(hash) hash.values end def removeLastHashValue(hash) lk = lastHashKey hash hash.delete lk end end end # This module is utility, not depend on class instance module KSUtil class << self # For debugging, can remove? def pathForTest(currentFilePath) File.dirname(currentFilePath) + "/" end # For debugging, can remove? # def myPATH # pathForTest "test" # end # For Test # diff form index.html and indexPressed.html # index.html and indexPressed.html should be same folder # @param [String] currentFilePath path of files # @return diff result def myDiff(currentFilePath) path = currentFilePath dif = `diff -b "#{path}index.html" "#{path}indexPressed.html"` if dif != "" p dif return end p 'no difference!' end # file reading, array make from each line # @param [String] txt # @param [Array] arr # @return [Array] def fileReadingToArr (txt, arr) begin File.open(txt) do |file| file.each_line do |labmen| arr << labmen end end # 例外は小さい単位で捕捉する rescue SystemCallError => e puts %Q(class=[#{e.class}] message=[#{e.message}]) rescue IOError => e puts %Q(class=[#{e.class}] message=[#{e.message}]) end end # @param [Anything] v value # @return [Bool] def isBool(v) !!v === v end # @param [String] s # @return [Symbol] def strinrgConvertSymbole(s) if s.is_a? String s = s.to_sym end s end # @param [Symbol] sym # @param [String] str # @example # attr(:id, "test") => attr(:id__test) def combineSym(sym, str) ans = sym.to_s << "__" << str ans.to_sym end # @param [Anything] sym # @return [Bool] whether symbol has "__" double underbar # @example # :id__test => true def isDoubleUnderBarSymbol(sym) return nil unless sym.is_a? Symbol sym.hasDoubleUnderBar? end # @param [Anything] data # @return [Bool] whether array def isDoubleArray (data) data[0].is_a?(Array) end # @return [Bool] def isBase (i,s) s.to_s.include?(i) ? true : false end # @param [Anything] s # @return [Bool] whether inclued "id" as string def isID(s) isBase "id", s end # @param [Anything] s # @return [Bool] whether inclued "cls" as string def isCls(s) isBase "cls", s end # @param [Anything] s # @return [Bool] whether inclued "name" as string def isName(s) isBase "name", s end # define multi line tag # @return [Array] array of multi tags # @example # <HTML> \n </HTML> def multiTags m = %w(HEAD ) m += %w(ADDRESS ARTICLE ASIDE AREA AUDIO) m += %w(BODY BLOCKQUOTE CANVAS) m += %w(DATALIST DETAILS DIALOG DIV DL DEL) m += %w(FORM FOOTER FIGURE FIELDSET) m += %w(HTML HEADER HGGROUP INS) m += %w(MAIN MAP NAV NOSCRIPT OL OPTGROUP PRE ) m += %w(SCRIPT STYLE SECTION SELECT SMALL SPAN) m += %w(TEXTAREA TEMPLATE UL ) # m += %w(LI_multi ) m += %w(VIDEO ) end # define table tag # @return [Array] array of table tags # @example # <Table> \n </Table> def tableTags %w(TABLE TROW THEAD TDATA) end # define single tag # @return [Array] array of single tags # @example # <P> </P> def singleTags s = %w( LIST_ITEM TD) s += %w(A ABBR) s += %w(B BDI BDO BR BUTTON ) s += %w(CITE CODE ) s += %w(DT DD DATA DFN) s += %w(EM ) s += %w(FIGCAPTION HR) s += %w(I KBD ) s += %w(LI LABEL LEGEND MARK METER) s += %w(OPTION OUTPUT P PROGRESS Q) s += %w(RP RT RTC RUBY) s += %w(S SAMP STRONG SUB SUP SUMMARY) s += %w(TITLE TIME TT U) s += %w(VAR WBR) end def headingList %w(HEADING) end def commentTag %w(COMMENT) end # define one tag # @return [Array] array of one tags # @example # <DOCTYPE> def oneTags o = %w(DOCTYPE IMG INPUT EMBED PARAM SOURCE) o += %w(LINK META TRACK) end def allTags a = [] a += singleTags a += multiTags a += tableTags a += headingList a += commentTag a += oneTags end # string insert to style tags # @param [String] str # @return [String] # @example # intoStyleTag "test" # => "<style>\n test\n </style>\n" def intoStyleTag (str) "<style>\n" << "#{str}\n" << "</style>\n" end # @param [String] tag # @return [Bool] whether tag is "<" def isOpenTag(tag) tag.match(/^(\t)*<(\w+)/) do |d| return true end false end # @param [String] tag # @return [Bool] whether tag is ">" def isCloseTag(tag) tag.match(/<\/(\w+)/) do return true end false end # @param [String] tag # @return [Bool] whether tag is "{" def isOpenPara(tag) tag.include? "{" end # @param [String] tag # @return [Bool] whether tag is "}" def isClosePara(tag) tag.include? "}" end end end # this class is HTML arrange, especialy treat with RET and TAB. module KString # 型チェック class << self def testPrint p "test done" end # cls reName to class # @example # renameCls "cls" => "class" # renameCls "name" => "name" def renameCls (str) if str == "cls" return "class" end str end # "_" convert to "-" # @example # renameUnderBar "cls_height" => "cls-height" def renameUnderBar (str) if str.include?("_") return str.gsub(/_/, "-") end str end # text line to Array # @param [String] str # @return [Array] def reader(str) # sentence -> arr str.lines end # insert string to array # @param [Array] arr # @param [String] txt # @return [Array] # @example # a = ["a", "b", "<\/body>"] # KString.insertText a, "!!" # => "a\nb\n!!\n<\/body>\n" def insertText(arr,txt) index = insertBodyEndTag arr tArr = removeAllRET arr tArr.insert index, txt insertReturnEachLine tArr end # @param [Array] arr String Array # return [Array] def insertReturnEachLine (arr) ans = arr.inject("")do |a,t| a << t << $RET end end # @param [Array] arr String Array # @return [Array] def insertBodyEndTag (arr) arr.index { |i| i =~ /<\/body>/ } end # @param [Any] type type of instance # @param [Any] instance # @return [Bool] def check_type(type, instance) # pass check -> true # fail check -> ArgumentError unless instance.kind_of?(type) raise ArgumentError::new("type mismatch: #{instance.class} for #{type}") end true end # whether instance type is string # @param [String] instance # @return [Bool] def isString? (instance) check_type(String, instance) end # whether instance type is Int # @param [Int] instance # @return [Bool] def isInt?(instance) check_type(Integer,instance) end # last Return remove from text line # @param [String] text line of text # @return [String] def removeLastRET(text) isString? text text.chomp end # remove Return from all of text lines # @param [Array<String>] arr String Array # @return [Array] def removeAllRET(arr) arr.map { |s| s.chomp } end # remove ";$" characters from text # @param [String] text # @return [String] def remove_Js_Cmd_End(text) isString? text text.gsub(/;$/, "") end # add space to top of string # @param [String] str # @return [String] # @example # addSpace "test" => " test" def addSpace(str) isString? str unless str.empty? str = $SPC + str end str end # whether Array include string # @param [Array] arr # @return [Bool] def isStringInArray(arr) arr.each do |a| isString? a end end # @param [Array] arr # @return [String] # @example # [a,b,c] => "a\nb\nc\n" def stringArrayConectRET (arr) return if arr.empty? return unless isStringInArray arr arr.inject("") do |ans, d| ans << d << $RET end end # replace word "of" to "with" in strings # @param [String] str target string # @param [String] of target word # @param [String] with replace word # @return [String] def reprace(str:, of:, with:) isString? str isString? of isString? with str.gsub(of,with) end # @param [element] element css element # @param [Array] elementArray css array # @return [Array] css element array def makeElementArray (element, elementArray) tempArray = [] if element != nil tempArray << element end if elementArray.count > 0 tempArray += elementArray end return tempArray end # check including css string, such as {} # @param [String] str # @return [Bool] true if css string include def isExistCssString(str) return false if str.empty? if !str.include?("{") || !str.include?("}") return false end removeFront = str.gsub(/.*{/, "").gsub(/}/, "").gsub(/\n/, "") return false if removeFront == "" true end # add tab each line # @param [Array] arr array<String> # @param [Int] number express how many tab adding in front of line # @return [Array] def addTabEachArray(arr, number) return "" if arr.empty? arr.map{ |a| "\t" * number << a }.join.sub!("\t" * number, "") end # whether range has Int # @param [Int] range # @return [Bool] whether range is Int def isIntegerIndex(range) return false unless range.first.is_a? Integer return false unless range.last.is_a? Integer true end # @param [Array] range # @return [Range] def sliceRange(range) (range.first + 1)..(range.last + 1) end end end end
describe "a position" do class ::Object def in?(collection) collection.include? self end end def next_state(opts) if(opts[:neighbours].in? 2..3) :alive elsif(opts[:neighbours] == 1) :dead end end context "with 2 live neighbours" do it "is alive in the next iteration" do next_state(:neighbours => 2).should == :alive end end context "with 3 live neighbours" do it "is alive in the next iteration" do next_state(:neighbours => 3).should == :alive end end context "with one live neighbour" do it "is dead in the next iteration" do next_state(:neighbours => 1).should == :dead end end end
module Ruboty module Handlers class Gekiron < Base on( /topic|gekiron|激論/, name: 'topic', description: '激論しそうな話題を返します', ) on( /gekiron/, name: 'topic', description: '激論しそうな話題を返します', all: true ) def topic(message) Ruboty::Gekiron::Actions::Topic.new(message).call end end end end
# https://www.codewars.com/kata/541c8630095125aba6000c00 def digital_root(n) loop do n = n.to_s.chars.map(&:to_i).reduce(:+) break n if n < 10 end end
require 'spec_helper' describe 'log in' do before { visit root_path } subject { page } describe 'should be able to login' do before do user = FactoryGirl.create (:user) fill_in 'username', with: user.username fill_in 'password', with: user.password click_on 'Login' end it { should have_link 'Log out'} end describe 'should not be able to login' do before do user = FactoryGirl.create (:user) fill_in 'username', with: user.username fill_in 'password', with: "killbill" click_on 'Login' end it { should have_content('Unknown user. Please check your username and password.')} end end
class Api::V1::RoadtripsController < ApplicationController def new if !params[:api_key] || User.find_by(api_key: params[:api_key]) == nil render status: :unauthorized, body: 'Unauthorized' else facade = RoadtripFacade.new(params[:origin], params[:destination]) serialized = RoadtripSerializer.new(facade) render json: serialized end end end
require 'spec_helper' describe Pacer::YamlEncoder do let(:original) do { :string => ' bob ', :symbol => :abba, :empty => '', :integer => 121, :float => 100.001, :time => Time.utc(1999, 11, 9, 9, 9, 1), :object => { :a => 1, 1 => :a }, :set => Set[1, 2, 3], :nested_array => [1, 'a', [2]], :ok_string => 'string value' } end describe '#encode_property' do subject do pairs = original.map do |name, value| [name, Pacer::YamlEncoder.encode_property(value)] end Hash[pairs] end it { should_not equal(original) } specify 'string should be stripped' do subject[:string].should == 'bob' end specify 'empty string becomes nil' do subject[:empty].should be_nil end specify 'numbers should be javafied' do subject[:integer].should == 121.to_java(:long) subject[:float].should == 100.001 end specify 'dates are custom to enable range queries' do subject[:time].should =~ /^ utcT \d/ end specify 'everything else should be yaml' do subject[:nested_array].should == ' ' + YAML.dump(original[:nested_array]) end end describe '#decode_property' do it 'should round-trip cleanly' do # remove values that get cleaned up when encoded original.delete :string original.delete :empty original.values.each do |value| encoded = Pacer::YamlEncoder.encode_property(value) decoded = Pacer::YamlEncoder.decode_property(encoded) decoded.should == value end end it 'should strip strings' do encoded = Pacer::YamlEncoder.encode_property(' a b c ') decoded = Pacer::YamlEncoder.decode_property(encoded) decoded.should == 'a b c' end it 'empty strings -> nil' do encoded = Pacer::YamlEncoder.encode_property(' ') decoded = Pacer::YamlEncoder.decode_property(encoded) decoded.should be_nil end end end
# # Cookbook Name:: wal-e # Recipe:: default include_recipe 'apt' # install packages unless node[:wal_e][:packages].nil? node[:wal_e][:packages].each do |pkg| package pkg end end # install python modules with pip unless overriden unless node[:wal_e][:pips].nil? include_recipe "python::pip" node[:wal_e][:pips].each do |pp| python_pip pp do user node[:wal_e][:pip_user] end end end # Install from source or pip pacakge case node[:wal_e][:install_method] when 'source' code_path = "#{Chef::Config[:file_cache_path]}/wal-e" bash "install_wal_e" do cwd code_path code <<-EOH /usr/bin/python ./setup.py install EOH action :nothing end git code_path do repository node[:wal_e][:repository_url] revision node[:wal_e][:git_version] notifies :run, "bash[install_wal_e]" end when 'pip' python_pip 'wal-e' do version node[:wal_e][:version] if node[:wal_e][:version] user node[:wal_e][:pip_user] end end directory node[:wal_e][:env_dir] do user node[:wal_e][:user] group node[:wal_e][:group] mode "0550" end vars = {'WALE_S3_PREFIX' => node[:wal_e][:s3_prefix] } if node[:wal_e][:aws_access_key] vars['AWS_ACCESS_KEY_ID'] = node[:wal_e][:aws_access_key] vars['AWS_SECRET_ACCESS_KEY'] = node[:wal_e][:aws_secret_key] end if node[:wal_e][:s3_use_sigv4] vars['S3_USE_SIGV4'] = node[:wal_e][:s3_use_sigv4] end if node[:wal_e][:wale_s3_endpoint] vars['WALE_S3_ENDPOINT'] = node[:wal_e][:wale_s3_endpoint] end if node[:wal_e][:ssl_cert_file] vars['SSL_CERT_FILE'] = node[:wal_e][:ssl_cert_file] end vars.each do |key, value| file "#{node[:wal_e][:env_dir]}/#{key}" do content value user node[:wal_e][:user] group node[:wal_e][:group] mode "0440" end end cron "wal_e_base_backup" do user node[:wal_e][:user] command "/usr/bin/envdir #{node[:wal_e][:env_dir]} /usr/local/bin/wal-e backup-push #{node[:wal_e][:base_backup][:options]} #{node[:wal_e][:pgdata_dir]}" not_if { node[:wal_e][:base_backup][:disabled] } minute node[:wal_e][:base_backup][:minute] hour node[:wal_e][:base_backup][:hour] day node[:wal_e][:base_backup][:day] month node[:wal_e][:base_backup][:month] weekday node[:wal_e][:base_backup][:weekday] end
class DeckSerializer < ActiveModel::Serializer attributes :id, :name,:description, :card_ids, :collection_id end
class Show < ActiveRecord::Base require 'figaro' has_many :trackings has_many :users, through: :trackings attr_accessible :title, :last_episode, :last_title, :last_airdate, :next_episode, :next_title, :next_airdate, :status, :airtime, :banner scope :active? def ended_statuses ["Ended", "Canceled/Ended"] end def ended? ended_statuses.include?(status) end # Called by #batch_update_next_airdate! def update_inactive_data! show_data = Show.check_for_show_data(title) latest_episode = next_episode = status = airtime = nil show_data.split("\n").each do |data| latest_episode = data if data[/^Latest Episode/] next_episode = data if data[/^Next Episode/] status = data if data[/^Status/] airtime = data if data[/^Airtime/] end self.update_attributes({ last_episode: latest_episode && latest_episode[/(\d+x\d+)/], last_title: latest_episode && latest_episode.match(/\^(.+)\^/).captures.first, last_airdate: latest_episode && latest_episode.match(/\^(\D{3}\/\d{2}\/\d{4})$/).captures.first, next_episode: next_episode && next_episode[/(\d+x\d+)/], next_title: next_episode && next_episode.match(/\^(.+)\^/).captures.first, next_airdate: next_episode && valid_date_format?(next_episode) && next_episode.match(/\^(\D{3}\/\d{2}\/\d{4})$/).captures.first, status: status.match(/@(.+)$/).captures.first, airtime: airtime && airtime.match(/@(.+)$/).captures.first, }) end def valid_date_format?(string) string.match(/\^(\D{3}\/\d{2}\/\d{4})$/) end # Sometimes a show may be canceled but then brought back. Users can manually resurrect those shows here, # because cron will not in its current form. def resurrect show_data = Show.check_for_show_data(title) new_show_status = nil show_data.split("\n").each {|data| new_show_status = data.match(/@(.+)$/).captures.first if data[/^Status/] } return false if self.status == new_show_status self.update_inactive_data! end class << self def active? where("status IN(?)", active_statuses) end def active_statuses ["Returning Series", "Final Season", "In Development", "TBD/On The Bubble", "New Series"] end def show_available?(query) canonical_title = check_for_show_data(query) canonical_title.present? ? canonical_title.match(/Show Name@(.+)\nShow URL{1}/).captures.first : false end def create_show_data(query, canonical_title, show_id) show_data = check_for_show_data(canonical_title) return false unless show_data latest_episode = next_episode = status = airtime = nil show_data.split("\n").each do |data| latest_episode = data if data[/^Latest Episode/] next_episode = data if data[/^Next Episode/] status = data if data[/^Status/] airtime = data if data[/^Airtime/] end Show.find(show_id).update_attributes({ title: canonical_title, last_episode: latest_episode && latest_episode[/(\d+x\d+)/], last_title: latest_episode && latest_episode.match(/\^(.+)\^/).captures.first, last_airdate: latest_episode && latest_episode.match(/\^(\D{3}\/\d{2}\/\d{4})$/).captures.first, next_episode: next_episode && next_episode[/(\d+x\d+)/], next_title: next_episode && next_episode.match(/\^(.+)\^/).captures.first, next_airdate: next_episode && next_episode.match(/\^(\D{3}\/\d{2}\/\d{4})$/).captures.first, status: status.match(/@(.+)$/).captures.first, airtime: airtime && airtime.match(/@(.+)$/).captures.first, banner: fetch_show_banner(query, canonical_title) }) end # To be called by a cron job to systematically update all recurring shows' next airdates def batch_update_next_airdate! Show.active?.where('next_airdate < ? OR next_airdate IS NULL', DateTime.now).each{ |show| show.update_inactive_data!} end def check_for_show_data(query) response = HTTParty.get('http://services.tvrage.com/tools/quickinfo.php', :query => {:show => query}, :format => :html) Crack::XML.parse(response)["pre"] end def fetch_show_banner(query, canonical_title) tvdb = TvdbParty::Search.new(Figaro.env.tvdb_api_key) begin show = tvdb.get_series_by_id(tvdb.search(canonical_title).first["seriesid"]) rescue NoMethodError show = tvdb.get_series_by_id(tvdb.search(query).first["seriesid"]) rescue NoMethodError banner = "#{Rails.root.join('app', 'assets', 'images', '404banner.jpg')}" end show ? show.series_banners('en').first.url : banner end end end
module Jshint module Cli def self.run(reporter_name = :Default, result_file = nil, config_path = nil) linter = Jshint::Lint.new(config_path) linter.lint reporter = Jshint::Reporters.const_get(reporter_name).new(linter.errors) printer = lambda do |stream| stream.puts reporter.report end if result_file Dir.mkdir(File.dirname(result_file)) File.open(result_file, 'w') do |stream| printer.call(stream) end else printer.call($stdout) end linter end end end
require "spec_helper" describe "vim for cython" do before(:all) { vim.command "new" vim.command "set ft=cython" vim.command("set indentexpr?").should include "GetPythonPEPIndent(" } before(:each) { # clear buffer vim.normal 'gg"_dG' # Insert two blank lines. # The first line is a corner case in this plugin that would shadow the # correct behaviour of other tests. Thus we explicitly jump to the first # line when we require so. vim.feedkeys 'i\<CR>\<CR>\<ESC>' } after(:all) { vim.command "bwipe!" } describe "when using a cdef function definition" do it "indents shiftwidth spaces" do vim.feedkeys 'icdef long_function_name(\<CR>arg' indent.should == shiftwidth end end describe "when using a cpdef function definition" do it "indents shiftwidth spaces" do vim.feedkeys 'icpdef long_function_name(\<CR>arg' indent.should == shiftwidth end end end
class BlocksController < ApplicationController before_action :set_block, only: [ :update, :destroy] # POST /blocks def create @block = Block.new(block_params) if @block.save render json: @block, status: :created, location: @block else render json: @block.errors, status: :unprocessable_entity end end # DELETE /blocks/1 def destroy @block.destroy render json: {status: "success"}, status: 200 end private # Use callbacks to share common setup or constraints between actions. def set_block @block = Block.find(params[:id]) end # Only allow a trusted parameter "white list" through. def block_params p = JSON.parse(request.raw_post) params[:block] = p params.require(:block).permit([:pad, :period, :goalie_id, :game_id]) end end
class CreateWebpages < ActiveRecord::Migration def change create_table :webpages do |t| t.string :unid t.string :url t.string :content t.timestamps end end end
# frozen_string_literal: true describe RegistrationPeriodsController, type: :controller do context 'unauthenticated' do describe 'GET #new' do before { get :new, params: { event_id: 'foo' } } it { expect(response).to redirect_to new_user_session_path } end describe 'POST #create' do before { post :create, params: { event_id: 'foo' } } it { expect(response).to redirect_to new_user_session_path } end describe 'DELETE #destroy' do before { delete :destroy, params: { event_id: 'foo', id: 'bar' } } it { expect(response).to redirect_to new_user_session_path } end end context 'logged as normal user' do let(:user) { Fabricate(:user) } let(:event) { Fabricate(:event) } before { sign_in user } describe 'GET #new' do before { get :new, params: { event_id: event } } it { expect(response).to have_http_status :not_found } end describe 'POST #create' do before { post :create, params: { event_id: event, registration_period: { title: 'foo', start_at: Time.zone.today, end_at: Time.zone.tomorrow, price: 100 } } } it { expect(response).to have_http_status :not_found } end end context 'logged as admin user' do let(:admin) { Fabricate(:user, role: :admin) } before { sign_in admin } describe 'GET #new' do context 'with a valid event' do let!(:event) { Fabricate :event } it 'assigns the variables and render the template' do get :new, params: { event_id: event } expect(assigns(:event)).to eq event expect(assigns(:period)).to be_a_new RegistrationPeriod expect(response).to render_template :new end end context 'with an invalid event' do it 'renders 404' do get :new, params: { event_id: 'foo' } expect(response).to have_http_status :not_found end end end describe 'POST #create' do let(:event) { Fabricate :event } context 'with valid parameters' do it 'creates the period and redirects to event' do start_date = Time.zone.now end_date = 1.week.from_now post :create, params: { event_id: event, registration_period: { title: 'foo', start_at: start_date, end_at: end_date, price: 100 } } period_persisted = RegistrationPeriod.last expect(period_persisted.title).to eq 'foo' expect(period_persisted.start_at.utc.to_i).to eq start_date.to_i expect(period_persisted.end_at.utc.to_i).to eq end_date.to_i expect(period_persisted.price.to_d).to eq 100 expect(response).to redirect_to event_path(event) end end context 'with invalid parameters' do context 'and invalid period params' do it 'renders form with the errors' do post :create, params: { event_id: event, registration_period: { title: '' } } period = assigns(:period) expect(period).to be_a RegistrationPeriod expect(period.errors.full_messages).to eq ['Título: não pode ficar em branco', 'Começa em: não pode ficar em branco', 'Termina em: não pode ficar em branco', 'Preço: não pode ficar em branco'] expect(response).to render_template :new end end context 'and invalid event' do it 'renders 404' do post :create, params: { event_id: 'foo', registration_period: { title: '' } } expect(response).to have_http_status :not_found end end end end describe 'DELETE #destroy' do let(:event) { Fabricate :event } let!(:period) { Fabricate :registration_period, event: event } context 'with valid parameters' do context 'and responding to HTML' do it 'deletes the period and redirects to event show' do delete :destroy, params: { event_id: event.id, id: period } expect(response).to redirect_to event_path(event) expect(RegistrationPeriod.count).to eq 0 end end end context 'with invalid parameters' do context 'and a valid event' do it 'responds 404' do delete :destroy, params: { event_id: event, id: 'foo' } expect(response).to have_http_status :not_found end end context 'and a invalid event' do it 'responds 404' do delete :destroy, params: { event_id: 'foo', id: period } expect(response).to have_http_status :not_found end end end end describe 'GET #edit' do let(:event) { Fabricate :event } let(:period) { Fabricate :registration_period, event: event } context 'with valid IDs' do it 'assigns the instance variable and renders the template' do get :edit, params: { event_id: event, id: period } expect(assigns(:period)).to eq period expect(response).to render_template :edit end end context 'with invalid IDs' do context 'and no valid event and period' do it 'does not assign the instance variable responds 404' do get :edit, params: { event_id: 'foo', id: 'bar' } expect(assigns(:period)).to be_nil expect(response).to have_http_status :not_found end end context 'and an invalid event' do it 'responds 404' do get :edit, params: { event_id: 'foo', id: period } expect(response).to have_http_status :not_found end end context 'and a period for other event' do let(:other_event) { Fabricate :event } let(:period) { Fabricate :registration_period, event: other_event } it 'does not assign the instance variable responds 404' do get :edit, params: { event_id: event, id: period } expect(assigns(:period)).to be_nil expect(response).to have_http_status :not_found end end end end describe 'PUT #update' do let(:event) { Fabricate :event } let(:period) { Fabricate :registration_period, event: event } let(:start_date) { Time.zone.now } let(:end_date) { 1.week.from_now } let(:valid_parameters) { { title: 'foo', start_at: start_date, end_at: end_date, price: 100 } } context 'with valid parameters' do it 'updates and redirects to event show' do put :update, params: { event_id: event, id: period, registration_period: valid_parameters } updated_period = RegistrationPeriod.last expect(updated_period.title).to eq 'foo' expect(updated_period.start_at.utc.to_i).to eq start_date.to_i expect(updated_period.end_at.utc.to_i).to eq end_date.to_i expect(updated_period.price.to_d).to eq 100 expect(response).to redirect_to event end end context 'with invalid parameters' do context 'and valid event and period, but invalid update parameters' do it 'does not update and render form with errors' do put :update, params: { event_id: event, id: period, registration_period: { title: '', start_at: '', end_at: '' } } updated_period = assigns(:period) expect(updated_period.errors.full_messages).to eq ['Título: não pode ficar em branco', 'Começa em: não pode ficar em branco', 'Termina em: não pode ficar em branco'] expect(response).to render_template :edit end end context 'with invalid IDs' do context 'and no valid event and period' do it 'does not assign the instance variable responds 404' do put :update, params: { event_id: 'bar', id: 'foo', registration_period: valid_parameters } expect(assigns(:registration_period)).to be_nil expect(response).to have_http_status :not_found end end context 'and an invalid event' do it 'responds 404' do put :update, params: { event_id: 'bar', id: period, registration_period: valid_parameters } expect(response).to have_http_status :not_found end end context 'and a period for other event' do let(:other_event) { Fabricate :event } let(:period) { Fabricate :registration_period, event: other_event } it 'does not assign the instance variable responds 404' do put :update, params: { event_id: event, id: period, registration_period: valid_parameters } expect(assigns(:period)).to be_nil expect(response).to have_http_status :not_found end end end end end end end
class MicropostsController < ApplicationController def index_food @food = Micropost.new @foods = Micropost.where(category: "食事").order(id: :desc).page(params[:page]).per(5) end def index_live @live = Micropost.new @lives = Micropost.where(category: "棲み家").order(id: :desc).page(params[:page]).per(5) end def index_play @play = Micropost.new @plays = Micropost.where(category: "遊び").order(id: :desc).page(params[:page]).per(5) end def show @micropost = Micropost.find(params[:id]) @comment = @micropost.comments.build @comments = @micropost.comments.order(id: :desc).page(params[:page]).per(5) end def create @micropost = current_user.microposts.build(micropost_params) if @micropost.save flash[:success] = '質問を投稿しました。' if (@micropost.category == "食事") @foods = Micropost.where(category: "食事").order(id: :desc).page(params[:page]).per(5) redirect_to food_url elsif (@micropost.category == "棲み家") @lives = Micropost.where(category: "棲み家").order(id: :desc).page(params[:page]).per(5) redirect_to live_url else (@micropost.category == "遊び") @plays = Micropost.where(category: "遊び").order(id: :desc).page(params[:page]).per(5) redirect_to play_url end else @microposts = Micropost.order(id: :desc).page(params[:page]) flash.now[:danger] = '質問の投稿に失敗しました。' if (@micropost.category == "食事") @food = @micropost @foods = Micropost.where(category: "食事").order(id: :desc).page(params[:page]).per(5) render "index_food" elsif (@micropost.category == "棲み家") @live = @micropost @lives = Micropost.where(category: "棲み家").order(id: :desc).page(params[:page]).per(5) render "index_live" else (@micropost.category == "遊び") @play = @micropost @plays = Micropost.where(category: "遊び").order(id: :desc).page(params[:page]).per(5) render "index_play" end end end def destroy @micropost = current_user.microposts.find_by(id: params[:id]) @micropost.destroy flash[:success] = '質問が削除されました' redirect_to root_url end private def micropost_params params.require(:micropost).permit(:category, :contents, :comments, :user_id) end end
ActiveAdmin.register ApiKey do # See permitted parameters documentation: # https://github.com/activeadmin/activeadmin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters # # permit_params :list, :of, :attributes, :on, :model # # or # # permit_params do # permitted = [:permitted, :attributes] # permitted << :other if resource.something? # permitted # end index do column 'Key ID', :id column 'Owner', :user_id do |api_key| api_key.user.username end column 'Owner ID', :user_id column 'Updated', :updated_at column 'Expires', :expires_at column :status actions end end
class ResourceCompletionController < ApplicationController before_action :private_access def create @resource = Resource.friendly.find(params[:resource_id]) @subject = @resource.subject if @resource.resource_completions.where(user: current_user).blank? @resource.resource_completions.create(user_id: current_user.id) end respond_to do |format| format.html { redirect_to next_path(@resource) } format.js end end def destroy @resource = Resource.friendly.find(params[:resource_id]) @subject = @resource.subject ResourceCompletion.where(resource_id: @resource.id, user_id: current_user.id).delete_all end private def next_path(resource) subject = resource.subject if current_user.finished?(subject) && resource.last? next_subject = subject.next if next_subject if current_user.stats.progress_by_subject(next_subject) == 0 flash[:notice] = "<strong>¡Felicitaciones!</strong> Has terminado #{subject.name}. Esta aventura continúa con #{next_subject.name}" end subject.next else subject end else next_resource = resource.next next_resource ? [subject, next_resource] : subject end end end
# method to check for equality def assert_equal(expected, actual) raise "Expected #{expected} to match #{actual}" unless expected == actual end # Write a program that prints the numbers from 1 to 100. # But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. # For numbers which are multiples of both three and five print “FizzBuzz”. # # Your code here def fizzbuzz(num) result = "#{"Fizz" if num%3==0} #{"Buzz" if num%5==0}" result.empty? ? num : result end # Tests assert_equal fizzbuzz(1), 1 assert_equal fizzbuzz(3), "Fizz" assert_equal fizzbuzz(4), 4 assert_equal fizzbuzz(50), "Buzz" assert_equal fizzbuzz(15), "FizzBuzz" assert_equal fizzbuzz(5175), "FizzBuzz" # uncomment this code when your tests pass 1.upto(100) do |number| puts fizzbuzz(number) end ##### test 1 def fizzbuzz i = 0 for i in 1..100 if i%3 && i%5 ==0 puts "FizzBuzz" elsif i%3 ==0 puts "Fizz" elsif i%5 ==0 puts "Buzz" else print"#{i} \n" end end end ##### test 2 def fizzbuzz(num) result = num if i%3 && i%5 ==0 result= "FizzBuzz" elsif i%3 ==0 result= "Fizz" elsif i%5 ==0 result = "Buzz" end result end ##### test 3 --- works def fizzbuzz(num) #result = num result = "#{"Fizz" if num%3==0} #{"Buzz" if num%5==0}" if result.empty? num else result end if (num%3==0 && num%5==0) #result = "Fizzbuzz" "Fizzbuzz" elsif(num%3==0) #result = "Fizz" "Fizz" elsif(num%5==0) #result = "Buzz" "Buzz" else num end #result end
require 'objectively/message' require 'objectively/edge' module Objectively class Diagram def self.draw(output:, &block) new .trace(&block) .draw(output: output) end def trace(&_block) require 'binding_of_caller' trace = TracePoint.trace(:call) do |tp| messages << Message.new( source: object_name(tp.binding.of_caller(2).eval('self')), target: object_name(tp.binding.eval('self')), method: tp.callee_id.to_s, args: tp.parameters.map do |(_, arg_name)| tp.binding.eval(arg_name.to_s) end ) rescue StandardError => error puts "Error in tracepoint handler: #{$!}" puts "Backtrace:\n\t#{error.backtrace.join("\n\t")}" end yield self ensure trace.disable end def draw(output:) require 'graphviz' GraphViz.new(:G, type: :digraph) do |g| added_nodes = {} objects.each do |object_name| added_nodes[object_name] = g.add_nodes(object_name) end edges.values.each do |edge| g.add_edges( added_nodes[edge.source], added_nodes[edge.target], label: edge.label ) end end.output(output) end private def object_name(obj) object_names[object_key obj] ||= if obj.respond_to? :__name_in_diagram__ obj.__name_in_diagram__ else default_object_name(obj) end end def default_object_name(obj) class_name = obj.class.name object_name = object_names[object_key obj] return object_name if object_name id = (classes[class_name] || 0) + 1 classes[class_name] = id "#{class_name}:#{id}" end def object_key(obj) "#{obj.class.name}:#{obj.object_id}" end def classes @classes ||= {} end def object_names @object_names ||= {} end def edges @edges ||= begin edges = {} messages.each_with_index do |message, index| key = [message.source, message.target].freeze existing_edge = edges[key] message_line = "#{index + 1}. #{message}" if existing_edge existing_edge.calls << message_line else edges[key] = Edge.new( source: message.source, target: message.target, calls: [message_line] ) end end edges end end def messages @messages ||= [] end def objects object_names.values end end end
#!/usr/bin/env ruby require 'rexml/document' class String def uncapitalize self[0, 1].downcase + self[1..-1] end end class QualityGenerator def initialize(doc) @doc = doc @qif = doc.elements['//QIFDocument'] @devices = {} @product = nil end Device = Struct.new(:accuracy, :description, :id, :manufacturer, :name, :resolution, :serialNumber, :type) def parse_devices @qif.each_element("MeasurementResources/MeasurementDevices/*") do |device| attrs = {type: device.name, id: device.attributes['id']} device.each_element_with_text do |f| text = f.text.strip f.each_element_with_text { |t| text << t.text } attrs[f.name.uncapitalize.to_sym] = text end device = Device.new(*attrs.keys.sort.map { |k| attrs[k] }) @devices[device.id] = device end end class Product attr_reader :root, :parts Part = Struct.new(:id, :name) def initialize(root, parts) @root = root @parts = parts end end def parse_product root = nil parts = [] @qif.each_element('Product/*') do |e| case e.name when 'PartSet' e.each_element('Part') do |part| parts << Product::Part.new(part.attributes['id'], part.elements['Name'].text) end when 'RootPart' root = e.elements['Id'].text end @product = Product.new(root, parts) end end module Characteristic Definition = Struct.new(:id, :name, :min, :max, :limit) Nominal = Struct.new(:id, :definition, :target, :mode) Item = Struct.new(:id, :description, :name, :devices, :nominal) end def parse_characteristics # definitions @definitions = {} @qif.each_element('Characteristics/CharacteristicDefinitions/*') do |c| id = c.attributes['id'] name = c.elements['Name'].text min = c.elements['Tolerance/MinValue'].text max = c.elements['Tolerance/MaxValue'].text limit = c.elements['Tolerance/DefinedAsLimit'].text @definitions[id] = Characteristic::Definition.new(id, name, min, max, limit) end @nominals = {} @qif.each_element('Characteristics/CharacteristicNominals/*') do |c| id = c.attributes['id'] def_id = c.elements['CharacteristicDefinitionId'].text target = c.elements['TargetValue'].text mode = c.elements['AnalysisMode'].text definition = @definitions[def_id] if definition @nominals[id] = Characteristic::Nominal.new(id, definition, target, mode) else puts "Cannot find characteristic definition for: #{def_id}" end end @items = {} @qif.each_element('Characteristics/CharacteristicItems/*') do |c| id = c.attributes['id'] description = c.elements['Description'].text name = c.elements['Name'].text devices = c.get_elements('MeasurementDeviceIds/*').map { |d| d.text } nom_id = c.elements['CharacteristicNominalId'].text nominal = @nominals[nom_id] if nominal @items[id] = Characteristic::Item.new(id, description, name, devices, nominal) else puts "Cannot find characteristic nominal for: #{nom_id}" end end end class MeasurementResult attr_reader :id, :actuals, :status CharacteristicActual = Struct.new(:id, :item, :status, :value) def initialize(id, actuals, status) @id, @actuals, @status = id, actuals, status end end def parse_results @results = {} @actuals = {} @qif.each_element('MeasurementsResults/MeasurementResults') do |r| actuals = r.get_elements('MeasuredCharacteristics/CharacteristicActuals/*').map do |act| id = act.attributes['id'] status = act.elements['Status/CharacteristicStatusEnum'].text item_id = act.elements['CharacteristicItemId'].text value = act.elements['Value'].text @actuals[id] = MeasurementResult::CharacteristicActual.new(id, @items[item_id], status, value) end id = r.attributes['id'] status = r.elements['InspectionStatus/InspectionStatusEnum'].text @results[id] = MeasurementResult.new(id, actuals, status) end end class StudyResult attr_reader :item, :groups, :status, :stats Group = Struct.new(:id, :actuals) def initialize(item, groups, status, stats) @item, @groups, @status, @stats = item, groups, status, stats end end def parse_statistics @studies = [] @qif.each_element('Statistics/StatisticalStudiesResults/' + 'CapabilityStudyResults/CharacteristicsStats/' + 'DistanceBetweenCharacteristicStats') do |s| results = s.get_elements('Subgroup').map do |e| StudyResult::Group.new(e.attributes['id'], e.get_elements('ActualIds/Ids/Id').map { |i| @actuals[i.text] }) end item = results.first.actuals.first.item status = s.elements['Status/StatsEvalStatusEnum'].text stats = Hash[*s.get_elements('ValueStats/*').map { |e| [e.name, e.text] }.flatten] @studies << StudyResult.new(item, results, status, stats) end end def generate_table(file) doc = REXML::Document.new # Header html = doc.add_element('html') head = html.add_element('head') head.add_element('link', 'rel' => 'stylesheet', 'type' => 'text/css', 'href' => '/qif.css') body = html.add_element('body') #body table = body.add_element 'table' header = ['Characteristic ID', 'LTL', 'Target', 'UTL'] columns = [] stat_headings = [] measures = [] measures_header = [] first = true @studies.each do |study| column = [] item = study.item column << item.description column << item.nominal.definition.min column << item.nominal.target column << item.nominal.definition.max header << 'Statistical Summary' if first column << '' if first stat_headings = study.stats.keys.sort header.concat stat_headings end stat_headings.each do |h| column << study.stats[h] end columns << column header << 'Part Measurements' if first column << '' column = [] study.groups.each do |group| measures_header << group.id if first column << group.actuals.first.value end measures << column first = false end columns.unshift header rows = columns.first.zip(*columns[1..-1]) thead = table.add_element('thead') row = thead.add_element 'tr' row.add_element('th').add_text('Part ID') row.add_element('th').add_text(@product.parts.first.name) (columns.size - 2).times { row.add_element('th') } row = rows.shift tr = thead.add_element 'tr' row.each do |e| tr.add_element('th').add_text(e) end tbody = table.add_element('tbody') rows.each do |row| tr = tbody.add_element 'tr' cls = { 'class' => 'bold' } row.each do |e| tr.add_element('td', cls).add_text(e) cls = nil end end measures.unshift measures_header rows = measures.first.zip(*measures[1..-1]) rows.each do |row| tr = tbody.add_element 'tr' cls = { 'class' => 'bold' } row.each do |e| tr.add_element('td', cls).add_text(e) cls = { 'class' => 'measurement'} end end File.open(file, 'w') { |f| f.write html.to_s } end def parse parse_devices parse_product parse_characteristics parse_results parse_statistics end end
#!/usr/bin/env ruby # # Vertically aligns multiple columns, which are # delimited by a user-defined regular expression, # that are present in the input given on STDIN. # # For example, the following input: # # short text = foo = hello # really long text = bar = world # wide operator <=> moz <=> again # # yields the following output: # # short text = foo # really long text = bar # wide operator <=> moz # #-- # Written in 2007 by Suraj N. Kurapati def align_table lines, delimiter, selector, rejector, justifier delim_regexp = /#{delimiter}/ # determine columns widths widths = Hash.new(0) rows = lines.map do |line| line.chomp! if line =~ selector and line !~ rejector and line =~ delim_regexp fields = line.split(delim_regexp) fields.each {|f| f.strip! } fields.unshift line[/\A[ \t]*/] # whitespace margin delims = line.scan(delim_regexp) delims[0..-2].each {|d| d << ' ' } delims[1..-1].each {|d| d.insert(0, ' ') } #delims.each {|d| d.insert(0, ' ') << ' ' } delims.unshift nil cols = fields.zip(delims).flatten.compact cols.each_with_index do |c, i| widths[i] = [c.length, widths[i]].max end else line end end # equalize column widths rows.map! do |row| if row.is_a? Array cols = [] row.each_with_index do |col, i| cols[i] = col.send(justifier, widths[i]) end cols.join.rstrip else row end end rows.join("\n") end if $0 == __FILE__ require 'optparse' parser = OptionParser.new parser.on '-h', '--help', 'show this help message' do puts File.read(__FILE__).split(/^$/).first, nil, parser exit end parser.on '-d', '--delimiter REGEXP', 'input column delimiter', "(default: #{(delimiter = /[[:punct:]]*=[[:punct:]]*/).inspect})\n", String do |arg| delimiter = arg end parser.on '-j', '--justify METHOD', 'justify text inside columns', '(choices: ljust, rjust, or center)', "(default: #{justifier = 'center'})", String do |arg| justifier = arg end parser.on '-m', '--select REGEXP', 'only wrap lines that match REGEXP', "(default: #{(selector = //).inspect})", Regexp do |arg| selector = arg end parser.on '-M', '--reject REGEXP', 'do not wrap lines that match REGEXP', "(default: #{(rejector = nil).inspect})", Regexp do |arg| rejector = arg end parser.parse ARGV puts align_table(STDIN.readlines, delimiter, selector, rejector, justifier) end
module Yt module Associations # @private # Provides methods to access the analytics reports of a resource. module HasReports # @!macro [new] reports # Returns the reports for the given metrics grouped by the given dimension. # @!method reports(options = {}) # @param [Hash] options the metrics, time-range and dimensions for the reports. # @option options [Array<Symbol>] :only The metrics to generate reports # for. # @option options [Symbol] :by (:day) The dimension to collect metrics # by. Accepted values are: +:day+, +:week+, +:month+. # @option options [#to_date] :since The first day of the time-range. # Also aliased as +:from+. # @option options [#to_date] :until The last day of the time-range. # Also aliased as +:to+. # @return [Hash<Symbol, Hash>] the reports for each metric specified. # @example Get the views and estimated minutes watched by day for last week: # resource.reports only: [:views, :estimated_minutes_watched] since: 1.week.ago, by: :day # # => {views: {Wed, 8 May 2014 => 12, Thu, 9 May 2014 => 34, …}, estimated_minutes_watched: {Wed, 8 May 2014 => 9, Thu, 9 May 2014 => 6, …}} # @!macro [new] report # Returns the $1 grouped by the given dimension. # @!method $1(options = {}) # @param [Hash] options the time-range and dimensions for the $1. # @option options [#to_date] :since The first day of the time-range. # Also aliased as +:from+. # @option options [#to_date] :until The last day of the time-range. # Also aliased as +:to+. # @!macro [new] report_with_day # @return [Hash<Date, $2>] if grouped by day, the $1 # for each day in the time-range. # @example Get the $1 for each day of last week: # resource.$1 since: 2.weeks.ago, until: 1.week.ago, by: :day # # => {Wed, 8 May 2014 => 12.0, Thu, 9 May 2014 => 34.0, …} # @return [Hash<Range<Date, Date>, $2>] if grouped by month, the $1 # for each month in the time-range. # @example Get the $1 for this and last month: # resource.$1 since: 1.month.ago, by: :month # # => {Wed, 01 Apr 2014..Thu, 30 Apr 2014 => 12.0, Fri, 01 May 2014..Sun, 31 May 2014 => 34.0, …} # @return [Hash<Range<Date, Date>, $2>] if grouped by week, the $1 # for each week in the time-range. # @example Get the $1 for this and last week: # resource.$1 since: 1.week.ago, by: :week # # => {Wed, 01 Apr 2014..Tue, 07 Apr 2014 => 20.0, Wed, 08 Apr 2014..Tue, 14 Apr 2014 => 13.0, …} # @macro report # @!macro [new] report_with_range # @return [Hash<Symbol, $2>] if grouped by range, the $1 # for the entire time-range (under the key +:total+). # @example Get the $1 for the whole last week: # resource.$1 since: 2.weeks.ago, until: 1.week.ago, by: :range # # => {total: 564.0} # @!macro [new] report_with_country # @option options [<String, Hash>] :in The country to limit the $1 # to. Can either be the two-letter ISO-3166-1 code of a country, such # as +"US"+, or a Hash with the code in the +:country+ key, such # as +{country: "US"}+. # @example Get the $1 for the whole last week in France only: # resource.$1 since: 2.weeks.ago, until: 1.week.ago, by: :range, in: 'FR' # # => {total: 44.0} # @!macro [new] report_with_country_and_state # @option options [<String, Hash>] :in The location to limit the $1 # to. Can either be the two-letter ISO-3166-1 code of a country, such # as +"US"+, or a Hash that either contains the +:country+ key, such # as +{country: "US"}+ or the +:state+ key, such as +{state: "TX"}+. # Note that YouTube API only provides data for US states. # @example Get the $1 for the whole last week in Texas only: # resource.$1 since: 2.weeks.ago, until: 1.week.ago, by: :range, in: {state: 'TX'} # # => {total: 19.0} # @!macro [new] report_by_day # @option options [Symbol] :by (:day) The dimension to collect $1 by. # Accepted values are: +:day+, +:week+, +:month+. # @macro report_with_day # @!macro [new] report_by_day_and_country # @option options [Symbol] :by (:day) The dimension to collect $1 by. # Accepted values are: +:day+, +:week+, +:month+, :+range+. # @macro report_with_day # @macro report_with_range # @macro report_with_country # @!macro [new] report_by_day_and_state # @option options [Symbol] :by (:day) The dimension to collect $1 by. # Accepted values are: +:day+, +:week+, +:month+, :+range+. # @macro report_with_day # @macro report_with_range # @macro report_with_country_and_state # @!macro [new] report_with_video_dimensions # @return [Hash<Symbol, $2>] if grouped by playback location, the # $1 for each traffic playback location. # @example Get yesterday’s $1 grouped by playback location: # resource.$1 since: 1.day.ago, until: 1.day.ago, by: :playback_location # # => {embedded: 53.0, watch: 467.0, …} # @return [Hash<Yt::Video, $2>] if grouped by related video, the # $1 for each related video. # @example Get yesterday’s $1 by related video, eager-loading the snippet of each video:: # resource.$1 since: 1.day.ago, until: 1.day.ago, by: :related_video, includes: [:snippet] # # => {#<Yt::Video @id=…> => 33.0, #<Yt::Video @id=…> => 12.0, …} # @return [Hash<Symbol, $2>] if grouped by device type, the # $1 for each device type. # @example Get yesterday’s $1 by search term: # resource.$1 since: 1.day.ago, until: 1.day.ago, by: :search_term # # => {"fullscreen" => 33.0, "good music" => 12.0, …} # @return [Hash<String, $2>] if grouped by search term, the # $1 for each search term that led viewers to the content. # @example Get yesterday’s $1 by URL that referred to the resource: # resource.$1 since: 1.day.ago, until: 1.day.ago, by: :referrer # # => {"Google Search" => 33.0, "ytimg.com" => 12.0, …} # @return [Hash<String, $2>] if grouped by search term, the # $1 for each search term that led viewers to the content. # @example Get yesterday’s $1 by device type: # resource.$1 since: 1.day.ago, until: 1.day.ago, by: :device_type # # => {mobile: 133.0, tv: 412.0, …} # @return [Hash<Symbol, $2>] if grouped by traffic source, the # $1 for each traffic source. # @example Get yesterday’s $1 by traffic source: # resource.$1 since: 1.day.ago, until: 1.day.ago, by: :traffic_source # # => {advertising: 543.0, playlist: 92.0, …} # @macro report_with_day # @macro report_with_range # @!macro [new] report_by_video_dimensions # @option options [Symbol] :by (:day) The dimension to collect $1 by. # Accepted values are: +:day+, +:week+, +:month+, +:range+, # +:traffic_source+,+:search_term+, +:playback_location+, # +:related_video+, +:embedded_player_location+. # @option options [Array<Symbol>] :includes ([:id]) if grouped by # related video, the parts of each video to eager-load. Accepted # values are: +:id+, +:snippet+, +:status+, +:statistics+, # +:content_details+. # @return [Hash<Symbol, $2>] if grouped by embedded player location, # the $1 for each embedded player location. # @example Get yesterday’s $1 by embedded player location: # resource.$1 since: 1.day.ago, until: 1.day.ago, by: :embedded_player_location # # => {"fullscreen.net" => 92.0, "yahoo.com" => 14.0, …} # @macro report_with_video_dimensions # @macro report_with_country_and_state # @!macro [new] report_with_channel_dimensions # @option options [Array<Symbol>] :includes ([:id]) if grouped by # video, related video, or playlist, the parts of each video or # playlist to eager-load. Accepted values are: +:id+, +:snippet+, # +:status+, +:statistics+, +:content_details+. # @return [Hash<Yt::Video, $2>] if grouped by video, the # $1 for each video. # @example Get yesterday’s $1 by video, eager-loading the status and statistics of each video: # resource.$1 since: 1.day.ago, until: 1.day.ago, by: :video, includes: [:status, :statistics] # # => {#<Yt::Video @id=…> => 33.0, #<Yt::Video @id=…> => 12.0, …} # @return [Hash<Yt::Playlist, $2>] if grouped by playlist, the # $1 for each playlist. # @example Get yesterday’s $1 by playlist: # resource.$1 since: 1.day.ago, until: 1.day.ago, by: :playlist # # => {#<Yt::Playlist @id=…> => 33.0, #<Yt::Playlist @id=…> => 12.0, …} # @macro report_with_video_dimensions # @!macro [new] report_by_channel_dimensions # @option options [Symbol] :by (:day) The dimension to collect $1 by. # Accepted values are: +:day+, +:week+, +:month+, +:range+, # +:traffic_source+, +:search_term+, +:playback_location+, +:video+, # +:related_video+, +:playlist+, +:embedded_player_location+. # @return [Hash<Symbol, $2>] if grouped by embedded player location, # the $1 for each embedded player location. # @example Get yesterday’s $1 by embedded player location: # resource.$1 since: 1.day.ago, until: 1.day.ago, by: :embedded_player_location # # => {"fullscreen.net" => 92.0, "yahoo.com" => 14.0, …} # @macro report_with_channel_dimensions # @macro report_with_country_and_state # @!macro [new] report_by_playlist_dimensions # @option options [Symbol] :by (:day) The dimension to collect $1 by. # Accepted values are: +:day+, +:week+, +:month+, +:range+, # +:traffic_source+, +:playback_location+, +:related_video+, +:video+, # +:playlist+. # @macro report_with_channel_dimensions # @macro report_with_country_and_state # @!macro [new] report_by_gender_and_age_group # @option options [Symbol] :by (:gender_age_group) The dimension to # show viewer percentage by. # Accepted values are: +:gender+, +:age_group+, +:gender_age_group+. # @return [Hash<Symbol, $2>] if grouped by gender, the # viewer percentage by gender. # @example Get yesterday’s viewer percentage by gender: # resource.$1 since: 1.day.ago, until: 1.day.ago, by: :gender # # => {female: 53.0, male: 47.0} # @return [Hash<String, $2>] if grouped by age group, the # viewer percentage by age group. # @example Get yesterday’s $1 grouped by age group: # resource.$1 since: 1.day.ago, until: 1.day.ago, by: :age_group # # => {"18-24" => 4.54, "35-24" => 12.31, "45-34" => 8.92, …} # @return [Hash<Symbol, [Hash<String, $2>]>] if grouped by gender # and age group, the viewer percentage by gender/age group. # @example Get yesterday’s $1 by gender and age group: # resource.$1 since: 1.day.ago, until: 1.day.ago # # => {female: {"18-24" => 12.12, "25-34" => 16.16, …}, male:…} # @example Get yesterday’s $1 by gender and age group in France only: # resource.$1 since: 1.day.ago, until: 1.day.ago, in: 'FR' # # => {female: {"18-24" => 16.12, "25-34" => 13.16, …}, male:…} # @macro report # @macro report_with_country_and_state # Defines a public instance methods to access the reports of a # resource for a specific metric. # @param [Symbol] metric the metric to access the reports of. # @param [Class] type The class to cast the returned values to. # @example Adds +comments+ on a Channel resource. # class Channel < Resource # has_report :comments, Integer # end def has_report(metric, type) require 'yt/collections/reports' define_metric_method metric define_reports_method metric, type define_range_metric_method metric define_all_metric_method metric, type end private def define_reports_method(metric, type) (@metrics ||= {})[metric] = type define_method :reports do |options = {}| from = options[:since] || options[:from] || ([:day, :week, :month].include?(options[:by]) ? 5.days.ago : '2005-02-01') to = options[:until] || options[:to] || Date.today location = options[:in] country = location.is_a?(Hash) ? location[:country] : location state = location[:state] if location.is_a?(Hash) dimension = options[:by] || (metric == :viewer_percentage ? :gender_age_group : :range) videos = options[:videos] if dimension == :month from = from.to_date.beginning_of_month to = to.to_date.beginning_of_month end date_range = Range.new *[from, to].map(&:to_date) only = options.fetch :only, [] reports = Collections::Reports.of(self).tap do |reports| reports.metrics = self.class.instance_variable_get(:@metrics).select{|k, v| only.include?(k)} end reports.within date_range, country, state, dimension, videos end unless defined?(reports) end def define_metric_method(metric) define_method metric do |options = {}| from = options[:since] || options[:from] || ([:day, :week, :month].include?(options[:by]) ? 5.days.ago : '2005-02-01') to = options[:until] || options[:to] || Date.today location = options[:in] country = location.is_a?(Hash) ? location[:country] : location state = location[:state] if location.is_a?(Hash) dimension = options[:by] || (metric == :viewer_percentage ? :gender_age_group : :range) videos = options[:videos] if dimension == :month from = from.to_date.beginning_of_month to = to.to_date.beginning_of_month end range = Range.new *[from, to].map(&:to_date) ivar = instance_variable_get "@#{metric}_#{dimension}_#{country}_#{state}" instance_variable_set "@#{metric}_#{dimension}_#{country}_#{state}", ivar || {} results = case dimension when :day Hash[*range.flat_map do |date| [date, instance_variable_get("@#{metric}_#{dimension}_#{country}_#{state}")[date] ||= send("range_#{metric}", range, dimension, country, state, videos)[date]] end] else instance_variable_get("@#{metric}_#{dimension}_#{country}_#{state}")[range] ||= send("range_#{metric}", range, dimension, country, state, videos) end lookup_class = case options[:by] when :video, :related_video then Yt::Collections::Videos when :playlist then Yt::Collections::Playlists end if lookup_class includes = options.fetch(:includes, [:id]).join(',').camelize(:lower) items = lookup_class.new(auth: auth).where(part: includes, id: results.keys.join(',')) results.transform_keys{|id| items.find{|item| item.id == id}}.reject{|k, _| k.nil?} else results end end end def define_range_metric_method(metric) define_method "range_#{metric}" do |date_range, dimension, country, state, videos| ivar = instance_variable_get "@range_#{metric}_#{dimension}_#{country}_#{state}" instance_variable_set "@range_#{metric}_#{dimension}_#{country}_#{state}", ivar || {} instance_variable_get("@range_#{metric}_#{dimension}_#{country}_#{state}")[date_range] ||= send("all_#{metric}").within date_range, country, state, dimension, videos end private "range_#{metric}" end def define_all_metric_method(metric, type) define_method "all_#{metric}" do # @note Asking for the "estimated_revenue" metric of a day in which a channel # made 0 USD returns the wrong "nil". But adding to the request the # "estimatedMinutesWatched" metric returns the correct value 0. metrics = {metric => type} metrics[:estimated_minutes_watched] = Integer if metric == :estimated_revenue Collections::Reports.of(self).tap{|reports| reports.metrics = metrics} end private "all_#{metric}" end end end end
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :invitable, :database_authenticatable, :registerable, :confirmable, :recoverable, :rememberable, :trackable, :validatable enum role: [:user, :worship_leader, :admin] enum instrument: %w(voice violin trombone trumpet piano acoustic_bass acoustic_guitar electric_guitar electric_bass_guitar drums bongos flute saxophone oboe) belongs_to :church after_initialize :set_default_role, :if => :new_record? after_initialize :set_default_church_role has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "100x100#", :med_tiny => "75x75#", :tiny => "50x50#", :mini => "39x39#" }, :default_url => "/images/:style/user.png" validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/ has_many :user_song_preferences has_many :instrument_preferences has_many :meeting_users, :dependent => :destroy has_one :church_role accepts_nested_attributes_for :church_role accepts_nested_attributes_for :instrument_preferences, :reject_if => :all_blank, :allow_destroy => true validates :first_name, :last_name, :email, :presence => true validates :password, :presence => true, :on => :create scope :leaders, -> { where('users.role IN (?) ', [:worship_leader,:admin].map{|r| User.roles[r]}) } acts_as_liker def set_default_role self.role ||= :user end def set_default_church_role if church.present? and !self.church_role self.build_church_role(:role => :member, :user_id => self.id, :church_id => self.church.id) end end def full_name full_name = "" if name.present? full_name = name else full_name = "#{self.first_name ? self.first_name.downcase.capitalize : ""} #{self.last_name ? self.last_name.downcase.capitalize : ""}" end full_name end def name at_name = read_attribute(:name) if at_name.present? at_name = at_name.capitalize end at_name end def self.current Thread.current[:user] end def self.current=(user) Thread.current[:user] = user end def has_role?(role) self.role == role.to_s end def is_admin? has_role?(:admin) end def is_up_to_worship_leader? is_admin? or has_role?(:worship_leader) end def has_church_role?(church_role) self.church and self.church_role and self.church_role.church == self.church and self.church_role.role == church_role end def instruments if self.instrument_preferences.present? return self.instrument_preferences.map{|ip| ip.instrument} else return InstrumentPreference.instruments.keys end end end
module HelperMethods def titleize(str) strArr = str.downcase.split(" ") # split the string into an array containing each word. Now loop through array and Capitalize as necesary arr = [] strArr.each do |word| if ((word == "in") || (word == "the") || (word == "of") || (word == "and") || (word == "or") || (word == "from")) && (strArr.index(word) != 0) arr << word else arr << word.capitalize end end return arr.join(" "); end end
class A2200 attr_reader :options, :name, :field_type, :node def initialize @name = "Previous Assessment Reference Date for Significant Correction (format = yyyymmdd) (A2200)" @field_type = TEXT @node = "A2200" @options = [] @options << FieldOption.new("") end def set_values_for_type(klass) date1 = Date.today - 20.days date2 = Date.today - 19.days date3 = Date.today - 18.days date4 = Date.today - 17.days date5 = Date.today - 28.days date6 = Date.today - 16.days date7 = Date.today - 15.days case klass when "CorrectionOfAdmission" then return date1.strftime("%Y%m%d") when "CorrectionOfQuarterly" then return date2.strftime("%Y%m%d") when "CorrectionOfAnnual" then return date3.strftime("%Y%m%d") when "CorrectionOfSignificantChange" then return date4.strftime("%Y%m%d") when "CorrectionOfPps5Day" then return date5.strftime("%Y%m%d") when "CorrectionOfInterimPayment" then return date6.strftime("%Y%m%d") when "CorrectionOfPpsDischarge" then return date7.strftime("%Y%m%d") else return date2.strftime("%Y%m%d") end end end
class CreateDeals < ActiveRecord::Migration[5.2] def change create_table :deals do |t| t.date :deal_date t.integer :deal_quantity t.boolean :confirmation t.references :brewery, foreign_key: true t.references :client, foreign_key: true t.timestamps end end end
class FinancialStatementsAnalyzer def initialize filedir fs_directory = Dir.new(filedir) financial_statements = fs_directory.entries.select { |e| e =~ /.*_[A-Z][A-Z]\.txt$/} payments = fs_directory.entries.select { |e| e =~ /.*_PYMT\.txt$/} @region = Hash.new @apps = Hash.new financial_statements.each do |fs| analyze_financial_statement(Dir.getwd + "/" + filedir + "/" + fs) end payments.each do |p| analyze_payment(Dir.getwd + "/" + filedir + "/" + p) end financial_status end private def analyze_financial_statement filepath lines = IO.readlines(filepath) region = filepath[-6,2] # region region_earned = lines.last.chomp.split(":").last.to_f # total earned for file currency = lines[1].chomp.split(/\t/)[8] add_region_data(region, region_earned, 0.0, currency) lines[1..-2].each do |line| splitted = line.chomp.split(/\t/) app_name = splitted[4] # number_sold = splitted[5] # individual_price = splitted[6] earned = splitted[7].to_f # currency = splitted[8] if @apps.key?(app_name) if @apps[app_name].key?(region) @apps[app_name][region] = @apps[app_name][region] + earned else @apps[app_name][region] = earned end else @apps[app_name] = Hash.new @apps[app_name][region] = earned end end end def analyze_payment filepath lines = IO.readlines(filepath) region = filepath[-11, 2] # region payment = lines.last.chomp.split(/ +/)[1].to_f currency = lines[3].chomp.split(/: /)[1] add_region_data(region, 0.0, payment, currency) end def add_region_data region, earned, payment, currency if @region.key?(region) @region[region]["Payments"] = @region[region]["Payments"] + payment @region[region]["Earned"] = @region[region]["Earned"] + earned else @region[region] = Hash.new @region[region]["Payments"] = payment @region[region]["Earned"] = earned @region[region]["Currency"] = currency end end def financial_status puts puts "#######################################################" puts "REGIONS" puts "#######################################################" puts @region.each do | key, region | puts "=====================================================" puts "For region #{key}" puts puts "You earned #{region['Earned']} #{region['Currency']}" puts "You received #{region['Payments']} #{region['Currency']}" end puts puts "#######################################################" puts "APPLICATIONS" puts "#######################################################" puts @apps.each do |key, app| puts "=====================================================" puts "For #{key}" app.each do |region, earned| puts "#{region} => #{earned} #{@region[region]['Currency']}" end end end end if __FILE__ == $0 FinancialStatementsAnalyzer.new("fs") end
Given /^the following couch time is in the database:$/ do |table| table.hashes.each do |hash| hash[:user] = User.find_by_name hash["user"] couch_time = CouchTime.create!(hash) end end When /^I fill in the creation form correctly with duration "([^"]*)"$/ do |duration| fill_in("Duration", :with => duration) fill_in("Comment", :with => "Some placeholder comment!") end When /^I fill in the creation form correctly with occurred at "([^"]*)"$/ do |occurred_at| fill_in("Duration", :with => 23) fill_in("Comment", :with => "The same place holder comment as before. Ehrm.. wait a minute. This is a totally different comment!") fill_in("Occurred at", :with => occurred_at) end Then /^I should have a couch time in database with:$/ do |table| search_params = Hash.new table.rows_hash.each { |property, value| search_params[property] = value } couch_time = CouchTime.find(:first, :conditions => search_params) couch_time.should_not be_nil end Then /^I should have a couch time in database with duration (\d+)$/ do |expected_duration| couch_time = CouchTime.find(:first) couch_time.duration.should == expected_duration.to_i end Then /^I should have a couch time in database with occurred at (.+)$/ do |expected_occurred_at| couch_time = CouchTime.find(:first) couch_time.occurred_at.should == expected_occurred_at end
require 'onesky' module OneSky class Client attr_accessor :client, :project, :base_locale, :onesky_locales, :config def initialize(config_hash) unless valid_config?(config_hash) fail ArgumentError, 'Invalid config. Please check if `api_key`, `api_secret` and `project_id` exist.' end @config = config_hash @client = ::Onesky::Client.new(@config['api_key'], @config['api_secret']) @project = @client.project(@config['project_id'].to_i) @base_locale = config_hash.fetch('base_locale', I18n.default_locale).to_s @onesky_locales = [] end def verify_languages! languages = languages_from_onesky languages.each do |language| locale = language['custom_locale'] || language['code'] if language['is_base_language'] verify_base_locale!(locale) elsif language['is_ready_to_publish'] @onesky_locales << locale end end end private def valid_config?(config) config['api_key'].present? && config['api_secret'].present? && config['project_id'].present? end def languages_from_onesky JSON.parse(@project.list_language)['data'] end def verify_base_locale!(locale) if locale != @base_locale fail BaseLanguageNotMatchError, "The default locale (#{@base_locale}) of " \ "your Rails app doesn't match the base language (#{locale}) of the OneSky project" end end end class BaseLanguageNotMatchError < StandardError; end end
ActiveAdmin.register_page "Dashboard" do menu priority: 1, label: proc{ I18n.t("active_admin.dashboard") } content title: proc{ I18n.t("active_admin.dashboard") } do columns do column do panel "Users" do table_for User.order("created_at desc").limit(10) do column :full_name do |user| link_to user.full_name, [:admin, user] end column :email column :approved end strong { link_to "View All Users", admin_users_path } end end column do panel "Logins" do table_for Login.order("logged_in_at desc").limit(10) do column :full_name do |login| link_to login.user.full_name, [:admin, login] end column :logged_in_at do |login| login.logged_in_at.in_time_zone('Eastern Time (US & Canada)') end end strong { link_to "View All Logins", admin_logins_path } end end end end end
name 'ssh-auth' maintainer 'phaninder [phaninder.com]' maintainer_email 'pasupulaphani.gmail.com' license 'Apache 2.0' description 'Configures ssh' long_description 'Configures ssh and provides some utils for auth keys' version '0.1.4' unless defined?(Chef::Cookbook::Metadata) source_url 'https://bitbucket.org/ppasupula/chef-ssh-auth' issues_url 'https://bitbucket.org/ppasupula/chef-ssh-auth/issues' end supports 'ubuntu' supports 'RHEL' supports 'CentOs' provides "ssh-auth::sshd" provides "here(:ssh_key)" recipe "ssh-auth::sshd", "Configures ssh server"
class Creation < ActiveRecord::Base belongs_to :user validates_presence_of :author, :title, :work validates_length_of :author, in: 1..100 validates_length_of :title, in: 1..100 validates_length_of :work, minimum: 1 end