repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
railsrumble/r13-team-46
config/initializers/errbit.rb
<reponame>railsrumble/r13-team-46 Airbrake.configure do |config| config.api_key = '22b2740ec5056ec9a40d245b6d6be604' config.host = 'errbit.welaika.com' config.port = 80 config.secure = config.port == 443 end
railsrumble/r13-team-46
app/mailers/recurrence_mailer.rb
class RecurrenceMailer < ActionMailer::Base default from: "<EMAIL>" helper :tasks helper :recurrences helper :application def notify(user, task) @user = user @task = task mail(to: @user.email, subject: 'Evry.io notification') end end
railsrumble/r13-team-46
spec/repositories/create_repository_spec.rb
<filename>spec/repositories/create_repository_spec.rb<gh_stars>0 require 'unit_spec_helper' describe CreateRepository do let(:repository) { CreateRepository.new } let(:attributes) { stub } let(:klass) { stub } let(:buy) { stub(:persisted? => true) } before do repository.stubs(:klass).returns(klass) repository.stubs(:after_create_hooks).returns([]) end context "#create" do it 'sanitizes and delegates object creation' do repository.expects(:sanitize_attributes!).with(attributes) klass.expects(:create).with(attributes).returns(buy) repository.create(attributes) end context "#after_create_hooks" do class ExampleCallback cattr_accessor :count def initialize(model) @@count ||= 0 end def perform @@count += 1 end end context 'when object is created successfully' do before do repository.stubs(:after_create_hooks).returns([ ExampleCallback ]) klass.stubs(:create).with(attributes).returns(buy) end it 'runs callbacks' do repository.create(attributes) expect(ExampleCallback.count).to be(1) end end end end end
railsrumble/r13-team-46
db/migrate/20131019085603_create_recurrences.rb
<filename>db/migrate/20131019085603_create_recurrences.rb<gh_stars>0 class CreateRecurrences < ActiveRecord::Migration def change create_table :recurrences do |t| t.references :task, index: true t.boolean :auto_schedule t.datetime :next t.string :expression t.datetime :starting t.datetime :until t.timestamps end end end
railsrumble/r13-team-46
app/repositories/create_task.rb
class CreateTask < CreateRepository def after_create_hooks [ SyncTaskRecurrence ] end end
railsrumble/r13-team-46
spec/support/database_cleaner.rb
<gh_stars>0 require 'database_cleaner' RSpec.configure do |config| config.before(:suite) do DatabaseCleaner.clean_with(:deletion) end config.before(:each) do if defined?(Capybara) && Capybara.current_driver == :rack_test DatabaseCleaner.strategy = :transaction else DatabaseCleaner.strategy = :truncation end DatabaseCleaner.start end config.after(:each) do DatabaseCleaner.clean end end
railsrumble/r13-team-46
spec/unit_spec_helper.rb
RAILS_ROOT = File.expand_path('../../', __FILE__) $LOAD_PATH.unshift(RAILS_ROOT) unless $LOAD_PATH.include?(RAILS_ROOT) require 'fileutils' require 'active_support/dependencies' require 'active_support/concern' require 'active_support/core_ext' require 'active_model' require 'mocha/api' require 'timecop' require 'ostruct' require 'pry' require 'support/rspec_config' Dir[File.join(RAILS_ROOT, "spec/support/shared_examples/*.rb")].each { |f| require f } unless defined?(Rails) module Rails def self.root RAILS_ROOT end def self.env OpenStruct.new(test?: true) end end end autoload_paths = ActiveSupport::Dependencies.autoload_paths %w(lib app/services app/commands app/repositories).each do |path| autoload_paths.push(path) unless autoload_paths.include?(path) end
railsrumble/r13-team-46
db/migrate/20131019102652_add_fields_to_tasks.rb
<filename>db/migrate/20131019102652_add_fields_to_tasks.rb class AddFieldsToTasks < ActiveRecord::Migration def change rename_column :tasks, :title, :action add_column :tasks, :time_expression, :string end end
railsrumble/r13-team-46
app/controllers/tasks_controller.rb
class TasksController < ApplicationController before_filter :authenticate_user! load_and_authorize_resource inherit_resources respond_to :html respond_to :js, only: [ :create, :update, :destroy, :schedule ] def create @task = CreateTask.create(params[:task].merge(user_id: current_user.id)) if @task.errors.present? flash[:alert] = @task.errors.full_messages.first render 'new' else create! end end def update @task = Task.find(params[:id]) UpdateTask.new(@task).perform(params[:task]) update! end def index @tasks = @tasks.by_next_at.page(params[:page]) @task = Task.new end def duplicate task = Task.find(params[:id]) if task @task = Task.new(action: task.action, time_expression: task.time_expression) render "new" else flash[:alert] = "Can't duplicate not existing task" redirect_to tasks_url end end def mail_report @tasks = @tasks.by_next_at.includes(:recurrence) render '/recurrence_mailer/report', layout: false end def mail_notification render '/recurrence_mailer/notify', layout: false end def schedule @task = Task.find(params[:id]) SyncTaskRecurrence.new(@task).perform end end
railsrumble/r13-team-46
app/models/task.rb
<gh_stars>0 class Task < ActiveRecord::Base belongs_to :user has_one :recurrence, dependent: :destroy attr_accessible :time_expression, :action, :description, :user_id validates :time_expression, :action, :user_id, presence: true scope :by_next_at, -> { joins(:recurrence).order('next_at asc') } end
WolfMeister/homebrew-cask
Casks/boom-3d.rb
<reponame>WolfMeister/homebrew-cask<filename>Casks/boom-3d.rb<gh_stars>0 cask 'boom-3d' do version '1.1.2,1519729669' sha256 '14c645ab8b85a696052dc01ad810487cdc4a21fae3f702eee156dd9ec9af2895' # devmate.com/com.globaldelight.Boom3D was verified as official when first introduced to the cask url "https://dl.devmate.com/com.globaldelight.Boom3D/#{version.before_comma}/#{version.after_comma}/Boom3D-#{version.before_comma}.dmg" appcast 'https://updates.devmate.com/com.globaldelight.Boom3D.xml', checkpoint: '9ee92aee0087314310c20ce750c5763ecd8d0b7c061def98c361cd3c2deee7e4' name 'Boom 3D' homepage 'http://www.globaldelight.com/boom3d' depends_on macos: '>= :yosemite' app 'Boom 3D.app' uninstall launchctl: [ 'com.globaldelight.Boom3D', 'com.globaldelight.Boom3DHelper', ], quit: 'com.globaldelight.Boom3D' zap trash: [ '~/Library/Application Support/Boom3D', '~/Library/Application Support/com.globaldelight.Boom3D', '~/Library/Preferences/com.globaldelight.Boom3D.plist', '~/Library/Preferences/com.globaldelight.Boom3DHelper.plist', ] end
dannyflatiron/Rails-App
app/controllers/users_controller.rb
class UsersController < ApplicationController before_action :authenticate_user!, except: [:show, :index] def new end def create end def show @user = User.find(params[:id]) end private def user_params params.require(:user).permit(:name, :email, :uid, :encrypted_password, :provider ) end end
dannyflatiron/Rails-App
app/controllers/application_controller.rb
class ApplicationController < ActionController::Base before_action :configure_permitted_parameters, if: :devise_controller? protect_from_forgery with: :exception # before_action :authenticate_user! helper_method :morse_encode, :morse_encode_word MORSE_CODE = { "a" => ".-", "b" => "-...", "c" => "-.-.", "d" => "-..", "e" => ".", "f" => "..-.", "g" => "--.", "h" => "....", "i" => "..", "j" => ".---", "k" => "-.-", "l" => ".-..", "m" => "--", "n" => "-.", "o" => "---", "p" => ".--.", "q" => "--.-", "r" => ".-.", "s" => "...", "t" => "-", "u" => "..-", "v" => "...-", "w" => ".--", "x" => "-..-", "y" => "-.--", "z" => "--..", "0" => "-----", "1" => ".----", "2" => "..---", "3" => "...--", "4" => "....-", "5" => ".....", "6" => "-....", "7" => "--...", "8" => "---..", "9" => "----." } def morse_encode(str) str_downcase = str.downcase words = str_downcase.split(" ") encoded_words = words.map { |word| morse_encode_word(word) } encoded_words.join(" / ") end def morse_encode_word(word) letters = word.split("") codes = letters.map { |l| MORSE_CODE[l] } codes.join(" ") end def decodeMorse(string) words = string.split(" ") result = words.map do |word| phrase = "" letters = word.split(" ") letters.each do |letter| case letter when ".-" phrase << "a" when "-..." phrase << "b" when "-.-." phrase << "c" when "-.." phrase << "d" when "." phrase << "e" when "..-." phrase << "f" when "--." phrase << "g" when "...." phrase << "h" when ".." phrase << "i" when ".---" phrase << "j" when "-.-" phrase << "k" when ".-.." phrase << "l" when "--" phrase << "m" when "-." phrase << "n" when "---" phrase << "o" when ".--." phrase << "p" when "--.-" phrase << "q" when ".-." phrase << "r" when "..." phrase << "s" when "-" phrase << "t" when "..-" phrase << "u" when "...-" phrase << "v" when ".--" phrase << "w" when "-..-" phrase << "x" when "-.--" phrase << "y" when "--.." phrase << "z" when "-----" phrase << "0" when ".----" phrase << "1" when "..---" phrase << "2" when "...--" phrase << "3" when "....-" phrase << "4" when "-----" phrase << "5" when "-...." phrase << "6" when "--..." phrase << "7" when "---.." phrase << "8" when "----." phrase << "9" end end phrase end result.join(" ") end protected def configure_permitted_parameters devise_parameter_sanitizer.permit(:sign_up, keys: [:name]) devise_parameter_sanitizer.permit(:sign_in, keys: [:name]) end end
dannyflatiron/Rails-App
config/routes.rb
Rails.application.routes.draw do root to: "welcome#home" devise_for :users, controllers: { omniauth_callbacks: 'omniauth' } get '/signup' => 'users#new' post '/signup' => 'users#create' resources :messages # Nested Routes resources :users, only: [:show] do resources :missions, only: [:new, :create, :index, :show] resources :messages, shallow: true end resources :missions do resources :messages end resources :categories, only: [:index, :show] # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html end
dannyflatiron/Rails-App
app/models/category.rb
<filename>app/models/category.rb<gh_stars>0 class Category < ApplicationRecord has_many :missions validates :name, presence: true, format: { with: /\A[a-zA-Z]+\z/, message: "Only letters allowed" } end
dannyflatiron/Rails-App
app/models/mission.rb
class Mission < ApplicationRecord belongs_to :user #gives the reader and writer method belongs_to :category has_many :messages, dependent: :delete_all has_many :users, through: :messages #gives only the writer method for the plural validates :content, :title, presence: true scope :alphabetical_order, -> { order(:title)} scope :date_created, -> { order(created_at: :desc)} scope :last_updated, -> { order(updated_at: :desc)} scope :with_long_title, ->(length = 20) { where("LENGTH(title) > ?", length) } # delegate :name, to: :category # makes more sense to use find or create by instead of first or create # since first or create is typically used when paramaters are already present def category_attributes=(attr) self.category = Category.find_or_create_by(attr) if !attr[:name].blank? end def self.filter(params) where("category_id = ?", params) end def self.search(params) left_joins(:messages).where("LOWER(missions.title) LIKE :term OR LOWER(missions.content) LIKE :term OR LOWER(messages.content) LIKE :term", term: "%#{params}%") end end
dannyflatiron/Rails-App
app/controllers/missions_controller.rb
<reponame>dannyflatiron/Rails-App class MissionsController < ApplicationController before_action :authenticate_user! def index if params[:user_id] && @user = User.find_by_id(params[:user_id]) @missions = @user.missions.alphabetical_order else @error = "That user does not exist" if params[:user_id] @missions = Mission.last_updated.includes(:category, :user) end missions_search missions_filter end def show @mission = Mission.find_by_id(params[:id]) redirect_to missions_path if !@mission end def new if params[:user_id] && @user = User.find_by_id(params[:user_id]) @mission = @user.missions.build else @mission = Mission.new end @mission.build_category end def create @mission = current_user.missions.build(mission_params) if @mission.save redirect_to missions_path else render :new end end def edit set_mission if !@mission || @mission.user != current_user flash[:message] = "You do not have authorization to edit this mission" redirect_to missions_path end @mission.build_category if !@mission.category end def update set_mission redirect to missions_path if !@mission || @mission.user != current_user if @mission.update(mission_params) redirect_to mission_path(@mission) end end def destroy set_mission.destroy flash[:message] = "Mission was successfully deleted" redirect_to user_path(current_user) end private def mission_params params.require(:mission).permit(:title, :content, :category_id, category_attributes: [:name]) end def set_mission @mission = Mission.find_by(params[:id]) end def missions_search @missions = @missions.search(params[:q].downcase) if params[:q] && !params[:q].empty? end def missions_filter @missions = @missions.filter(params[:mission][:category_id]) if params.try(:mission) && params.try(:mission).try(:category_id) end end
dannyflatiron/Rails-App
app/models/user.rb
<reponame>dannyflatiron/Rails-App class User < ApplicationRecord has_many :missions, dependent: :delete_all has_many :categories, through: :missions, dependent: :delete_all has_many :messages, dependent: :delete_all has_many :messaged_missions, through: :messages, source: :mission, dependent: :delete_all # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable, :omniauthable, omniauth_providers: [:google_oauth2] def self.create_from_provider_data(provider_data) where(provider: provider_data.provider, uid: provider_data.uid).first_or_create do | user | user.provider = provider_data.provider user.name = provider_data.info.name user.uid = provider_data.uid user.email = provider_data.info.email user.password = <PASSWORD>ise.friendly_token[0, 20] end end end
dannyflatiron/Rails-App
app/helpers/messages_helper.rb
module MessagesHelper def index_display_header end end
dannyflatiron/Rails-App
app/controllers/messages_controller.rb
class MessagesController < ApplicationController before_action :authenticate_user! before_action :set_message, only: [:show] def index if params[:mission_id] && @mission = Mission.find_by_id(params[:mission_id]) @messages = @mission.messages else @error = "That mission does not exist" if params[:mission_id] @messages = Message.all end end def show end def new if params[:mission_id] && @mission = Mission.find_by_id(params[:mission_id]) @message = @mission.messages.build else @error = "That mission does not exist" if params[:mission_id] @message = Message.new end end def create @message = current_user.messages.build(message_params) if @message.save redirect_to messages_path else render :new end end def destroy end private def message_params params.require(:message).permit(:content, :mission_id, :user_id) end def set_message @message = Message.find_by(id: params[:id]) if !@message flash[:message] = "Message was not found" redirect_to messages_path end end end
opti/street-address
test/test_street_address.rb
<filename>test/test_street_address.rb require 'test/unit' require 'street_address' class StreetAddressUsTest < Test::Unit::TestCase def setup @addr1 = "2730 S Veitch St Apt 207, Arlington, VA 22206" @addr2 = "44 Canal Center Plaza Suite 500, Alexandria, VA 22314" @addr3 = "1600 Pennsylvania Ave Washington DC" @addr4 = "1005 Gravenstein Hwy N, Sebastopol CA 95472" @addr5 = "PO BOX 450, Chicago IL 60657" @addr6 = "2730 S Veitch St #207, Arlington, VA 22206" @addr7 = "#42 233 S Wacker Dr 60606" @addr8 = "Apt. 42, 233 S Wacker Dr 60606" @addr9 = "2730 S Veitch St #207" @int1 = "Hollywood & Vine, Los Angeles, CA" @int2 = "Hollywood Blvd and Vine St, Los Angeles, CA" @int3 = "Mission Street at Valencia Street, San Francisco, CA" end def test_zip_plus_4_with_dash addr = StreetAddress::US.parse("2730 S Veitch St, Arlington, VA 22206-3333") assert_equal "3333", addr.postal_code_ext end def test_zip_plus_4_without_dash addr = StreetAddress::US.parse("2730 S Veitch St, Arlington, VA 222064444") assert_equal "4444", addr.postal_code_ext end def test_informal_parse_normal_address a = StreetAddress::US.parse("2730 S Veitch St, Arlington, VA 222064444", :informal => true) assert_equal "2730", a.number assert_equal "S", a.prefix assert_equal "Veitch", a.street assert_equal "St", a.street_type assert_equal "Arlington", a.city assert_equal "VA", a.state assert_equal "22206", a.postal_code assert_equal "4444", a.postal_code_ext end def test_informal_parse_informal_address a = StreetAddress::US.parse("2730 S Veitch St", :informal => true) assert_equal "2730", a.number assert_equal "S", a.prefix assert_equal "Veitch", a.street assert_equal "St", a.street_type end def test_informal_parse_informal_address_trailing_words a = StreetAddress::US.parse("2730 S Veitch St in the south of arlington", :informal => true) assert_equal "2730", a.number assert_equal "S", a.prefix assert_equal "Veitch", a.street assert_equal "St", a.street_type end def test_parse assert_equal StreetAddress::US.parse("&"), nil assert_equal StreetAddress::US.parse(" and "), nil addr = StreetAddress::US.parse(@addr1) assert_equal addr.number, "2730" assert_equal addr.postal_code, "22206" assert_equal addr.prefix, "S" assert_equal addr.state, "VA" assert_equal addr.street, "Veitch" assert_equal addr.street_type, "St" assert_equal addr.unit, "207" assert_equal addr.unit_prefix, "Apt" assert_equal addr.city, "Arlington" assert_equal addr.prefix2, nil assert_equal addr.postal_code_ext, nil addr = StreetAddress::US.parse(@addr2) assert_equal addr.number, "44" assert_equal addr.postal_code, "22314" assert_equal addr.prefix, nil assert_equal addr.state, "VA" assert_equal addr.street, "Canal Center" assert_equal addr.street_type, "Plz" assert_equal addr.unit, "500" assert_equal addr.unit_prefix, "Suite" assert_equal addr.city, "Alexandria" assert_equal addr.street2, nil addr = StreetAddress::US.parse(@addr3) assert_equal addr.number, "1600" assert_equal addr.postal_code, nil assert_equal addr.prefix, nil assert_equal addr.state, "DC" assert_equal addr.street, "Pennsylvania" assert_equal addr.street_type, "Ave" assert_equal addr.unit, nil assert_equal addr.unit_prefix, nil assert_equal addr.city, "Washington" assert_equal addr.street2, nil addr = StreetAddress::US.parse(@addr4) assert_equal addr.number, "1005" assert_equal addr.postal_code, "95472" assert_equal addr.prefix, nil assert_equal addr.state, "CA" assert_equal addr.street, "Gravenstein" assert_equal addr.street_type, "Hwy" assert_equal addr.unit, nil assert_equal addr.unit_prefix, nil assert_equal addr.city, "Sebastopol" assert_equal addr.street2, nil assert_equal addr.suffix, "N" addr = StreetAddress::US.parse(@addr5) assert_equal addr, nil addr = StreetAddress::US.parse(@addr6) assert_equal("207", addr.unit) addr = StreetAddress::US.parse(@addr7, :informal => true) assert_equal addr.number, "233" assert_equal addr.postal_code, "60606" assert_equal addr.prefix, "S" assert_equal addr.state, nil assert_equal addr.street, "Wacker" assert_equal addr.street_type, "Dr" assert_equal addr.unit, "42" assert_equal addr.unit_prefix, "#" assert_equal addr.city, nil assert_equal addr.street2, nil assert_equal addr.suffix, nil addr = StreetAddress::US.parse(@addr8, :informal => true) assert_equal addr.number, "233" assert_equal addr.postal_code, "60606" assert_equal addr.prefix, "S" assert_equal addr.state, nil assert_equal addr.street, "Wacker" assert_equal addr.street_type, "Dr" assert_equal addr.unit, "42" assert_equal addr.unit_prefix, "Apt" assert_equal addr.city, nil assert_equal addr.street2, nil assert_equal addr.suffix, nil addr = StreetAddress::US.parse(@addr9, :informal => true) assert_equal("207", addr.unit) addr = StreetAddress::US.parse(@int1) assert_equal addr.city, "Los Angeles" assert_equal addr.state, "CA" assert_equal addr.street, "Hollywood" assert_equal addr.street2, "Vine" assert_equal addr.number, nil assert_equal addr.postal_code, nil assert_equal addr.intersection?, true addr = StreetAddress::US.parse(@int2) assert_equal addr.city, "Los Angeles" assert_equal addr.state, "CA" assert_equal addr.street, "Hollywood" assert_equal addr.street2, "Vine" assert_equal addr.number, nil assert_equal addr.postal_code, nil assert_equal addr.intersection?, true assert_equal addr.street_type, "Blvd" assert_equal addr.street_type2, "St" addr = StreetAddress::US.parse(@int3) assert_equal addr.city, "San Francisco" assert_equal addr.state, "CA" assert_equal addr.street, "Mission" assert_equal addr.street2, "Valencia" assert_equal addr.number, nil assert_equal addr.postal_code, nil assert_equal addr.intersection?, true assert_equal addr.street_type, "St" assert_equal addr.street_type2, "St" parseable = [ "1600 Pennsylvania Ave Washington DC 20006", "1600 Pennsylvania Ave #400, Washington, DC, 20006", "1600 Pennsylvania Ave Washington, DC", "1600 Pennsylvania Ave #400 Washington DC", "1600 Pennsylvania Ave, 20006", "1600 Pennsylvania Ave #400, 20006", "1600 Pennsylvania Ave 20006", "1600 Pennsylvania Ave #400 20006", "Hollywood & Vine, Los Angeles, CA", "Hollywood Blvd and Vine St, Los Angeles, CA", "Mission Street at Valencia Street, San Francisco, CA", "Hollywood & Vine, Los Angeles, CA, 90028", "Hollywood Blvd and Vine St, Los Angeles, CA, 90028", "Mission Street at Valencia Street, San Francisco, CA, 90028" ] parseable.each do |location| assert_not_nil(StreetAddress::US.parse(location), location + " was not parseable") end end end
idynkydnk/mastermind
lib/mastermind/computer.rb
module Mastermind class Computer @@password = [] @feedback = [] @guesses = 0 @possible_codes =*("0000".."5555") def self.password <PASSWORD> end def self.feedback @feedback end def self.choose_password colors (0..3).each do |i| @@password[i] = colors.sample end end def self.check_guess guess if guess == @@password return true else false end end def self.get_feedback guess black = 0 white = 0 player_guess = guess.clone x = player_guess code = @@password.clone 4.times.each do |i| if player_guess[i] == code[i] black += 1 code[i] = 0 player_guess[i] = 0 end end player_guess.delete(0) code.delete(0) player_guess.each do |i| if code.detect {|x| x == i} code.delete_at(code.find_index((code.detect {|x| x == i}))) end end white = player_guess.length - code.length blank_space = code.length @feedback = {black: black, white: white, blank: code.length} end def self.get_guess feedback, previous_guess guess = [] if previous_guess == [] guess << $colors[0] << $colors[0] << $colors[1] << $colors[1] return guess end not_possible = not_possible_codes(feedback, previous_guess) remove_impossible_codes(not_possible) number_guess = @possible_codes[0] guess = convert_numbers_to_colors(number_guess) @guesses += 1 guess end def self.convert_numbers_to_colors number_guess guess = [] (0..3).each do |x| case number_guess[x] when "0" guess << $colors[0] when "1" guess << $colors[1] when "2" guess << $colors[2] when "3" guess << $colors[3] when "4" guess << $colors[4] when "5" guess << $colors[5] end end guess end def self.not_possible_codes(feedback, guess) not_possible = {one: "", two: "", three: "", four: ""} case feedback[:black] when 0 not_possible[:one] << guess[0] not_possible[:two] << guess[1] not_possible[:three] << guess[2] not_possible[:four] << guess[3] end # go through available codes one by one and see if they reuturn the same feedback not_possible end def self.remove_impossible_codes not_possible impossible_numbers = colors_to_numbers(not_possible) @possible_codes.delete_if {|x| x[0].to_i == impossible_numbers[0] } @possible_codes.delete_if {|x| x[1].to_i == impossible_numbers[1] } @possible_codes.delete_if {|x| x[2].to_i == impossible_numbers[2] } @possible_codes.delete_if {|x| x[3].to_i == impossible_numbers[3] } end def self.colors_to_numbers impossible_colors impossible_numbers = [] i = [:one, :two, :three, :four] i.each do |x| case impossible_colors[x] when $colors[0] impossible_numbers << 0 when $colors[1] impossible_numbers << 1 when $colors[2] impossible_numbers << 2 when $colors[3] impossible_numbers << 3 when $colors[4] impossible_numbers << 4 when $colors[5] impossible_numbers << 5 end end impossible_numbers end end end
idynkydnk/mastermind
spec/feedback_cell_spec.rb
<filename>spec/feedback_cell_spec.rb<gh_stars>0 require_relative "spec_helper" module Mastermind describe FeedbackCell do context "#initialize" do it "is initialized with a value of '' by default" do cell = FeedbackCell.new expect(cell.color).to eq("") end it "can be initialized with a color" do cell = FeedbackCell.new("black") expect(cell.color).to eq("black") end end end end
idynkydnk/mastermind
lib/mastermind/test.rb
@possible_codes =*("0000".."5555") $colors = ["blue", "green", "purple", "red", "yellow", "Orange"] def not_possible_codes(feedback, guess) puts "We're in the method now" not_possible = {one: "", two: "", three: "", four: ""} new_possible_codes = [] guess = colors_to_numbers(guess) temp_code = guess puts "The prvious guess was " + temp_code @possible_codes.each do |possible_code| temp_black = 0 temp_white = 0 possible_code_minus_black = possible_code.dup temp_code_minus_black = temp_code.dup (0..3).each do |i| if possible_code[i] == temp_code[i] possible_code_minus_black.sub!(possible_code[i], "") temp_code_minus_black.sub!(temp_code[i], "") temp_black += 1 end end possible_code_minus_black.length.times do |i| if temp_code_minus_black.include? possible_code_minus_black[i] temp_code_minus_black.sub!(possible_code_minus_black[i], "") temp_white += 1 end end if feedback[:black] == temp_black && feedback[:white] == temp_white new_possible_codes << possible_code puts new_possible_codes end puts "the code of " + possible_code.to_s + " compared to the previous guess of " + temp_code.to_s + " gives the feedback of blacks: " + temp_black.to_s + " and whites: " + temp_white.to_s end end def colors_to_numbers colors numbers = [] colors.each do |x| case x when $colors[0] numbers << "0" when $colors[1] numbers << "1" when $colors[2] numbers << "2" when $colors[3] numbers << "3" when $colors[4] numbers << "4" when $colors[5] numbers << "5" end end numbers.join end actual_code = ["blue", "green", "blue", "purple"] feedback = {black: 1, white: 2, blank: 1} previous_guess = ["blue", "blue", "green", "green"] # 0011 # example of of same feedback 0102 puts "The actual code is " + actual_code.to_s puts "The feedback sent to the method is " + feedback.to_s puts "The previous guess was " + previous_guess.to_s not_possible_codes(feedback, previous_guess)
idynkydnk/mastermind
lib/mastermind/player.rb
module Mastermind class Player @guess = [] @code = [] def self.guess @guess end def self.code @code end def self.code=(code) @code end def self.get_guess colors puts "Available colors: " + colors.join(", ") print "Guess the code: " @guess = gets.chomp.split(", ") end def set_code UI.get_code end def self.get_feedback puts "How many black pegs?" black = gets.chomp puts "How many white pegs?" white = gets.chomp puts "How many blank spaces?" blank = gets.chomp feedback = {black: black.to_i, white: white.to_i, blank: blank.to_i} end end end
idynkydnk/mastermind
lib/mastermind/play.rb
<reponame>idynkydnk/mastermind require_relative 'board' module Mastermind my_board = Board.new my_board.play end
idynkydnk/mastermind
lib/mastermind/ui.rb
module Mastermind class UI def self.draw_board(cells, feedback_cells) i = 0 cells.each_slice(4) do |main_row| main_row.each do |cell| if cell.color != "" print " " + cell.color + " " else print " _ " end end print " " 4.times do print feedback_cells[i].value i += 1 end print "\n" end end def self.who_is_the_creator puts "Would you like to be the guesser or creator?" puts "1. Guesser" puts "2. Creator" choice = gets.chomp if choice == "1" return "computer" elsif choice == "2" return "player" else puts "All you had to do was pick 1 or 2." end end def self.winner puts "We have a winner! Congrats!" exit end def self.get_code colors puts "Available colors: " + colors.join(", ") puts "What's your code?" code = gets.chomp end def self.code_is_set code puts "The code has been set to " + code.join(", ") end def self.computer_guess guess puts "The computer has guessed " + guess.join(", ") end end end
idynkydnk/mastermind
spec/cell_spec.rb
<reponame>idynkydnk/mastermind require_relative "spec_helper" module Mastermind describe Cell do context "#initialize" do it "is initialized with a value of '' by default" do cell = Cell.new expect(cell.color).to eq("") end it "can be initialized with a color" do cell = Cell.new("Purple") expect(cell.color).to eq("Purple") end end end end
idynkydnk/mastermind
lib/mastermind/board.rb
<filename>lib/mastermind/board.rb require_relative 'cell' require_relative 'ui' require_relative 'feedback_cell' require_relative 'computer' require_relative 'player' module Mastermind $colors = ["blue", "green", "purple", "red", "yellow", "Orange"] class Board def initialize @cells = [] @feedback_cells = [] @colors = ["blue", "green", "purple", "red", "yellow", "Orange"] set_new_board end def play if UI.who_is_the_creator == "computer" computer_is_creator_play else player_is_creator_play end end def player_is_creator_play feedback = {black: 0, white: 0, blank: 4} code = UI.get_code(@colors) code = code.split(", ") guess = [] UI.code_is_set(code) 2.times do |guess_count| UI.draw_board(@cells, @feedback_cells) guess = Computer.get_guess(feedback, guess) UI.computer_guess(guess) feedback = Player.get_feedback if feedback[:black] == 4 UI.winner end update_board(feedback, guess, guess_count) end end def computer_is_creator_play Computer.choose_password(@colors) 12.times do |guess_count| UI.draw_board(@cells, @feedback_cells) Player.get_guess(@colors) if Computer.check_guess(Player.guess) UI.winner else update_board(Computer.get_feedback(Player.guess), Player.guess, guess_count) end end puts "You lose!" end def set_new_board (1..48).each { |n| @cells << Cell.new("")} (1..48).each { |n| @feedback_cells << FeedbackCell.new("_")} end def update_board feedback, guess, guess_count feedback_to_display = randomize_feedback(feedback) guess_to_display = shorten_colors(guess) x = guess_count * 4 4.times do |i| @cells[i+x].color = guess_to_display[i] @feedback_cells[i+x].value = feedback_to_display[i] end end def randomize_feedback feedback converted_feedback = [] converted_feedback << "B" * feedback[:black] converted_feedback << "W" * feedback[:white] converted_feedback << "_" * feedback[:blank] converted_feedback = converted_feedback.join converted_feedback = converted_feedback.split("") converted_feedback.shuffle! end def shorten_colors guess short_guess = [] i = 0 guess.each do |x| short_guess[i] = x[0].upcase i += 1 end short_guess end end end
idynkydnk/mastermind
lib/mastermind.rb
require "mastermind/version" module Mastermind end require_relative "./mastermind/cell.rb" require_relative "./mastermind/feedback_cell.rb" require_relative "./mastermind/board.rb" require_relative "./mastermind/computer.rb" require_relative "./mastermind/player.rb"
idynkydnk/mastermind
spec/board_spec.rb
<filename>spec/board_spec.rb require_relative "spec_helper" module Mastermind describe Board do context "#initialize" do it "is initializes a board with 40 cells" do board = Board.new expect(board.cells.size).to eq 40 end end context "#update_board" do it "updates the board with new cells and feedback" do board = Board.new end end end end
idynkydnk/mastermind
lib/mastermind/string.rb
<filename>lib/mastermind/string.rb class String def bg_black; "\e[40m#{self}\e[0m" end def bg_red; "\e[41m#{self}\e[0m" end def bg_green; "\e[42m#{self}\e[0m" end def bg_blue; "\e[44m#{self}\e[0m" end def bg_purple; "\e[45m#{self}\e[0m" end def bg_gray; "\e[47m#{self}\e[0m" end def bg_yellow; "\e[43m#{self}\e[0m" end end
panterch/railsmplayer
vendor/rails/railties/lib/rails/rack/metal.rb
require 'active_support/ordered_hash' module Rails module Rack class Metal NotFoundResponse = [404, {}, []].freeze NotFound = lambda { NotFoundResponse } cattr_accessor :metal_paths self.metal_paths = ["#{Rails.root}/app/metal"] cattr_accessor :requested_metals def self.metals matcher = /#{Regexp.escape('/app/metal/')}(.*)\.rb\Z/ metal_glob = metal_paths.map{ |base| "#{base}/**/*.rb" } all_metals = {} metal_glob.each do |glob| Dir[glob].sort.map do |file| file = file.match(matcher)[1] all_metals[file.classify] = file end end load_list = requested_metals || all_metals.keys load_list.map do |requested_metal| if metal = all_metals[requested_metal] require metal requested_metal.constantize end end.compact end def initialize(app) @app = app @metals = ActiveSupport::OrderedHash.new self.class.metals.each { |app| @metals[app] = true } freeze end def call(env) @metals.keys.each do |app| result = app.call(env) return result unless result[0].to_i == 404 end @app.call(env) end end end end
panterch/railsmplayer
vendor/rails/railties/guides/rails_guides.rb
pwd = File.dirname(__FILE__) $: << pwd $: << File.join(pwd, "../../activesupport/lib") $: << File.join(pwd, "../../actionpack/lib") require "action_controller" require "action_view" # Require rubygems after loading Action View require 'rubygems' begin gem 'RedCloth', '>= 4.1.1'# Need exactly 4.1.1 rescue Gem::LoadError $stderr.puts %(Missing the RedCloth 4.1.1 gem.\nPlease `gem install -v=4.1.1 RedCloth` to generate the guides.) exit 1 end require 'redcloth' module RailsGuides autoload :Generator, "rails_guides/generator" autoload :Indexer, "rails_guides/indexer" autoload :Helpers, "rails_guides/helpers" autoload :TextileExtensions, "rails_guides/textile_extensions" end RedCloth.send(:include, RailsGuides::TextileExtensions) if $0 == __FILE__ RailsGuides::Generator.new.generate end
panterch/railsmplayer
lib/mplayer.rb
<filename>lib/mplayer.rb require 'thread' require 'singleton' class Mplayer include Singleton attr_accessor :recent, :log def initialize( opts = '' ) @recent = [ DEFAULT_URL ] @log = [ ] debug 'initializing mplayer singleton' ObjectSpace.define_finalizer self, Mplayer.create_finalizer(self) end def close execute 'quit' @io.try(:close) @io_thread.join(0.5) unless @io_thread.nil? sleep 1 `pkill -9 #{MPLAYER_BIN}` # leave no witnesses behind end def play( path ) close unless (path =~ /^http/ || path =~ /^mms/) return debug('sorry, only http & mms supported...') end path.gsub! /[^\w\.\:\-\=\/\?\&\ ]/, '' cmd = "#{MPLAYER_BIN} #{MPLAYER_OPT} '#{path}' 2>&1" debug(cmd) @io = IO.popen(cmd, 'r+') @recent.insert(0, path) @recent.uniq! @io_thread = Thread.new(self) { |p| p.read_thread } end def pause execute "pause" end def volume_up execute 'volume 20' end def volume_down execute 'volume -20' end def seek_left execute 'seek -60 0' end def seek_right execute 'seek +60 0' end protected def read_thread buff = '' begin until @io.eof? buff += @io.read 1 next unless (i = buff.index(/[\r\n]/)) debug buff.slice!(0, i+1).strip end rescue return end end def Mplayer.create_finalizer( player ) proc { player.close } end def execute(cmd) debug cmd @io.puts cmd rescue => error RAILS_DEFAULT_LOGGER.error(error) debug error end def debug(msg) RAILS_DEFAULT_LOGGER.info(msg) @log.insert(0, msg) @log.pop while @log.length > 100 end end
panterch/railsmplayer
config/deploy.rb
set :application, "project_zero" role :app, "mieze.panter.local" role :web, "mieze.panter.local" role :db, "mieze.panter.local" set :rails_env, 'production' set :deploy_via, :remote_cache set :git_enable_submodules, 1 set :scm, :git set :default_run_options, { :pty => true } set :repository, "<EMAIL>:panter/railsmplayer.git" set :ssh_options, {:forward_agent => true} set :deploy_to, "/home/rails/app" set :user, "rails" set :use_sudo, false task :update_config_links, :roles => [:app] do run "ln -sf #{shared_path}/config/* #{release_path}/config/" end after "deploy:update_code", :update_config_links namespace :deploy do desc "Restart Application" task :restart, :roles => :app do run "touch #{current_path}/tmp/restart.txt" end end after "deploy", "deploy:cleanup"
panterch/railsmplayer
vendor/rails/railties/guides/rails_guides/indexer.rb
<filename>vendor/rails/railties/guides/rails_guides/indexer.rb module RailsGuides class Indexer attr_reader :body, :result, :level_hash def initialize(body) @body = body @result = @body.dup end def index @level_hash = process(body) end private def process(string, current_level= 3, counters = [1]) s = StringScanner.new(string) level_hash = ActiveSupport::OrderedHash.new while !s.eos? s.match?(/\h[0-9]\..*$/) if matched = s.matched matched =~ /\h([0-9])\.(.*)$/ level, title = $1.to_i, $2 if level < current_level # This is needed. Go figure. return level_hash elsif level == current_level index = counters.join(".") bookmark = '#' + title.gsub(/[^a-z0-9\-_]+/i, '').underscore.dasherize raise "Parsing Fail" unless @result.sub!(matched, "h#{level}(#{bookmark}). #{index}#{title}") key = { :title => title, :id => bookmark } # Recurse counters << 1 level_hash[key] = process(s.post_match, current_level + 1, counters) counters.pop # Increment the current level last = counters.pop counters << last + 1 end end s.getch end level_hash end end end
panterch/railsmplayer
app/controllers/commands_controller.rb
<filename>app/controllers/commands_controller.rb class CommandsController < ApplicationController Mplayer.instance.public_methods(false).grep(/[^=]$/).each do |method| class_eval %{ def #{method} Mplayer.instance.#{method} render_nothing end } end def play url = params[:url] Mplayer.instance.play(url) render :partial => 'info' end def info render :partial => 'info' end protected def render_nothing render :nothing => true end end
nezhyborets/AsyncNinja
AsyncNinja.podspec
<reponame>nezhyborets/AsyncNinja Pod::Spec.new do |s| s.name = 'AsyncNinja' s.version = '1.4.0' s.summary = 'A complete set of primitives for concurrency and reactive programming on Swift' s.homepage = 'https://async.ninja' s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { '<NAME>' => '<EMAIL>' } s.social_media_url = 'https://twitter.com/AntonMironov' s.ios.frameworks = 'WebKit', 'CoreData', 'SystemConfiguration', 'UIKit' s.ios.deployment_target = '8.0' s.osx.frameworks = 'WebKit', 'CoreData', 'SystemConfiguration', 'AppKit' s.osx.deployment_target = '10.10' s.watchos.frameworks = 'CoreData', 'WatchKit' s.watchos.deployment_target = '2.0' s.tvos.frameworks = 'CoreData', 'SystemConfiguration', 'UIKit' s.tvos.deployment_target = '9.0' s.source_files = 'Sources/*.swift' s.source = { :git => 'https://github.com/AsyncNinja/AsyncNinja.git', :tag => s.version } s.requires_arc = true s.documentation_url = 'http://docs.async.ninja' end
denislaliberte/sobriquet
lib/sobriquet/command.rb
module Sobriquet # Command hold value of the command class Command attr_reader :value, :alias, :description, :type def initialize(data) @value = data[0] @alias = data[1] @description = data[2] @type = data[3] end end end
denislaliberte/sobriquet
spec/command_collection_spec.rb
<gh_stars>0 require 'sobriquet' include Sobriquet RSpec.describe CommandCollection do let(:command_data) do ['git status', 'gs', 'get the status of the git directory'] end let(:persistance) do instance_double('Persistance', 'workspace/path') end it 'add and get a new command' do allow(persistance).to receive(:save) commands = described_class.new(persistance) commands.add(command_data) expect(commands.get).to include(command_data) end it 'add and persist a new command' do expect(persistance).to receive(:save).with([command_data], any_args) commands = described_class.new(persistance) commands.add(command_data) end it 'compile command to script file' do allow(persistance).to receive(:get).and_return([Command.new(command_data)]) commands = described_class.new(persistance) expect(commands.compile).to include('alias gs="git status"') end it 'script comain descrtion of commands' do allow(persistance).to receive(:get).and_return([Command.new(command_data)]) commands = described_class.new(persistance) expect(commands.compile).to include( '# description : get the status of the git directory' ) end end
denislaliberte/sobriquet
sobriquet.gemspec
require File.join([File.dirname(__FILE__), 'lib', 'sobriquet', 'version.rb']) spec = Gem::Specification.new do |s| s.name = 'sobriquet' s.description = 'sobiquet is a command line tool that help you to save quickly new shell alias variables' s.version = Sobriquet::VERSION s.author = '<NAME>' s.email = '<EMAIL>' s.license = 'mit' s.homepage = 'http://laliberte.io' s.platform = Gem::Platform::RUBY s.summary = 'Sobriquet manage your alias' s.files = `git ls-files`.split(" ") s.require_paths << 'lib' s.has_rdoc = true s.extra_rdoc_files = ['README.rdoc', 'sobriquet.rdoc'] s.rdoc_options << '--title' << 'sobriquet' << '--main' << 'README.rdoc' << '-ri' s.bindir = 'bin' s.executables << 'sobriquet' s.add_development_dependency('rake') s.add_development_dependency('rdoc') s.add_development_dependency('aruba') s.add_development_dependency('rubocop') s.add_development_dependency('rspec') s.add_development_dependency('rubocop-rspec') s.add_runtime_dependency('gli', '2.14.0') s.add_runtime_dependency("mustache", "~> 1.0") end
denislaliberte/sobriquet
lib/sobriquet/persistance.rb
require 'CSV' module Sobriquet # Persistance handle interaction with the file system class Persistance def initialize(workspace) @workspace = workspace end def get(type) _title, *data = CSV.read(@workspace, 'rb', col_sep: ' | ') data.map { |a| Command.new(a) }.select { |a| a.type == type } end def save(commands, title) csv_string = CSV.generate(col_sep: ' | ') do |csv| csv.add_row(title) commands.map do |line| csv.add_row(line) end end File.open(@workspace, 'w') do |file| file.write(csv_string) end end end end
denislaliberte/sobriquet
lib/sobriquet.rb
<filename>lib/sobriquet.rb require 'sobriquet/version.rb' require 'sobriquet/persistance.rb' require 'sobriquet/command.rb' require 'sobriquet/command_collection.rb'
denislaliberte/sobriquet
lib/sobriquet/command_collection.rb
require 'mustache' require 'yaml' module Sobriquet # Contain a collection of commands class CommandCollection def initialize(persistance) @persistance = persistance @commands = [] @title = %w(command alias description type) end def get @commands end def add(data) @commands.push(data) @persistance.save(@commands, @title) end def compile Mustache.render( '{{#commands}} # description : {{description}} alias {{alias}}="{{value}}" {{/commands}} {{#variables}} # description : {{description}} export {{alias}}="{{value}}" {{/variables}}', commands: @persistance.get('command'), variables: @persistance.get('variable') ) end end end
denislaliberte/sobriquet
spec/persistance_spec.rb
require 'sobriquet' include Sobriquet RSpec.describe Persistance do let(:title) do %w(command alias description type) end let(:csv) do 'command | alias | description | type "git status" | gs | "get the status of the git directory" | command "origin master" | om | "no description" | variable ' end let(:data) do [ ['git status', 'gs', 'get the status of the git directory', 'command'], ['origin master', 'om', 'no description', 'variable'] ] end context 'Reading csv with data' do before do expect(File).to receive(:open).with(any_args) { StringIO.new(csv) } end it 'retrive the command csv from csv and contain value' do persistance = described_class.new('workspace.csv') first_command = persistance.get('command').first expect(first_command.value).to eq('git status') end it 'return only the commands' do persistance = described_class.new('workspace.csv') expect(persistance.get('command').count).to eq(1) end it 'retrive the command csv from csv and contain alias' do persistance = described_class.new('workspace.csv') first_command = persistance.get('command').first expect(first_command.alias).to eq('gs') end it 'retrive the command csv from csv and contain description' do persistance = described_class.new('workspace.csv') first_command = persistance.get('command').first expect(first_command.description).to eq( 'get the status of the git directory' ) end end it 'save the commands data to the csv' do file = instance_double('file') expect(File).to receive(:open).with(any_args).and_yield(file) expect(file).to receive(:write).with(csv) persistance = described_class.new('workspace.csv') persistance.save(data, title) end end
ph/logstash-input-kafka
spec/inputs/kafka_spec.rb
# encoding: utf-8 require 'spec_helper' describe 'inputs/kafka' do let (:kafka_config) {{'topic_id' => 'test'}} it "should register" do input = LogStash::Plugin.lookup("input", "kafka").new(kafka_config) expect {input.register}.to_not raise_error end it 'should populate kafka config with default values' do kafka = LogStash::Inputs::Kafka.new(kafka_config) insist {kafka.zk_connect} == 'localhost:2181' insist {kafka.topic_id} == 'test' insist {kafka.group_id} == 'logstash' !insist { kafka.reset_beginning } end it 'should retrieve event from kafka' do # Extend class to control behavior class LogStash::Inputs::TestKafka < LogStash::Inputs::Kafka milestone 1 private def queue_event(msg, output_queue) super(msg, output_queue) # need to raise exception here to stop the infinite loop raise LogStash::ShutdownSignal end end kafka = LogStash::Inputs::TestKafka.new(kafka_config) kafka.register class Kafka::Group public def run(a_num_threads, a_queue) a_queue << 'Kafka message' end end logstash_queue = Queue.new kafka.run logstash_queue e = logstash_queue.pop insist { e['message'] } == 'Kafka message' # no metadata by default insist { e['kafka'] } == nil end end
POSpulse/harmonizer_redis
lib/harmonizer_redis/idf_scorer.rb
module HarmonizerRedis module IdfScorer # class self class << self def add_document(phrase_id) self.incr_doc_count text = HarmonizerRedis::Phrase.get_content(phrase_id) word_set = Set.new text.split.each do |word| unless word_set.include? word word_set.add(word) Redis.current.incr(word_doc_freq_key(word)) end Redis.current.incr(word_count_key(word)) end end def get_score(word) doc_freq = self.get_doc_freq(word) + 0.1 doc_count = self.doc_count + 0.1 Math.log(0.1+(doc_count / doc_freq)) end # first char is length of phrase (capped at 255 words). Each word(key) is separated # by a comma and the keys and values are separated by a vertical bar def serialize_matrix(matrix) serialized = "#{matrix.length.chr}#{matrix.keys.join(',')},#{matrix.values.join(',')}" serialized end # Used for soft cosine similarity def calc_soft_matrix(phrase_content) matrix = Hash.new(0.0) phrase_content.split.each do |word| matrix[word] += 1.0 end matrix.each do |word, count| updated = (1.0 + Math::log10(count)) * self.get_score(word) matrix[word] = updated end #calculate normalization factor norm_factor_sqrd = 0.0 matrix.each do |word_a, value_a| matrix.each do |word_b, value_b| similarity = WhiteSimilarity.score(word_a, word_b) norm_factor_sqrd += (similarity * value_a * value_b) end end #normalize factor = Math::sqrt(norm_factor_sqrd) matrix.each do |word, value| matrix[word] = value / factor end matrix end def cos_similarity(matrix_a, matrix_b) similarity = 0.0 matrix_a.each do |word, value| similarity += (value * matrix_b[word]) end similarity end def soft_cos_similarity(matrix_a, matrix_b) similarity = 0.0 matrix_a.each do |word_a, value_a| matrix_b.each do |word_b, value_b| if word_a != word_b white_similarity = WhiteSimilarity.score(word_a, word_b) else white_similarity = 1.0 end similarity += (white_similarity * value_a * value_b) end end similarity end def get_doc_freq(word) Redis.current.get(word_doc_freq_key(word)).to_f end def get_count(word) Redis.current.get(word_count_key(word)).to_f end def decr_doc_freq(word) Redis.current.decr(word_doc_freq_key(word)) Redis.current.decr("#{self}:doc_count") end def doc_count Redis.current.get("#{self}:doc_count").to_f end def incr_doc_count Redis.current.incr("#{self}:doc_count") end def word_doc_freq_key(word) "Word:[#{word}]:doc_freq" end def word_count_key(word) "Word:[#{word}]:count" end end end end
POSpulse/harmonizer_redis
lib/harmonizer_redis/base_object.rb
<reponame>POSpulse/harmonizer_redis<filename>lib/harmonizer_redis/base_object.rb module HarmonizerRedis class BaseObject attr_accessor :id def generate_id Redis.current.incr("#{self.class}").to_i - 1 end def save #creates a new id only when object is being saved klass = "#{self.class}" new_id = @id || self.generate_id self.instance_variables.each do |variable| var_name = variable.to_s[1..-1] Redis.current.set("#{klass}:#{new_id}:#{var_name}", instance_variable_get(variable)) end @id = new_id #add id to HarmonizerRedis::ClassName:set Redis.current.sadd("#{klass}:set", @id) end end end
POSpulse/harmonizer_redis
lib/harmonizer_redis/phrase.rb
module HarmonizerRedis class Phrase < BaseObject attr_accessor :content def initialize(content) @content = content end def save super() HarmonizerRedis::IdfScorer.add_document(@id) Redis.current.set("#{self.class}:[#{@content}]", "#{@id}") end class << self def find_by_content(content) Redis.current.get("#{self}:[#{content}]") end def get_content(phrase_id) Redis.current.get("#{self}:#{phrase_id}:content") end # Setup def add_linkage(phrase_id, linkage_id, category_id) add_linkage_id(phrase_id, linkage_id) add_category_id(phrase_id, category_id) end # Linkages def add_linkage_id(phrase_id, linkage_id) Redis.current.zincrby(linkage_set_key(phrase_id), 1, Linkage.get_content(linkage_id)) end def get_linkage_count(phrase_id) Redis.current.zcard(linkage_set_key(phrase_id)) end def get_popular_linkages(phrase_id, number = 5) if number <= 0 raise "number must be >= 0" end Redis.current.zrevrange(linkage_set_key(phrase_id), 0, number-1, with_scores: true) end # Categories def add_category_id(phrase_id, category_id) Redis.current.sadd(category_set_key(phrase_id), category_id) end def get_categories(phrase_id) Redis.current.smembers(category_set_key(phrase_id)) end #get a serialized version of the matrix. def get_matrix(phrase_id) serialized = Redis.current.get("#{self}:#{phrase_id}:matrix") if serialized serialized else nil end end def calc_pair_similarity(phrase_a, phrase_b, phrase_a_matrix, phrase_b_matrix) idf_similarity = IdfScorer.cos_similarity(phrase_a_matrix, phrase_b_matrix) white_similarity = WhiteSimilarity.score(phrase_a, phrase_b) (idf_similarity + white_similarity) * -0.5 end def calc_soft_pair_similarity(phrase_a_matrix, phrase_b_matrix) WhiteSimilarity.soft_cos_similarity(phrase_a_matrix, phrase_b_matrix) end ### Helpers ### (consider refactoring with metaprogramming) def linkage_set_key(phrase_id) "#{self}:#{phrase_id}:linkage_set" end def category_set_key(phrase_id) "#{self}:#{phrase_id}:category_set" end end private_class_method :linkage_set_key, :category_set_key end end
POSpulse/harmonizer_redis
spec/tfidf_table_spec.rb
<reponame>POSpulse/harmonizer_redis<filename>spec/tfidf_table_spec.rb require 'spec_helper' describe HarmonizerRedis::IdfScorer do before :all do Redis.current = Redis.new end before :each do Redis.current.flushall phrases = ['this this is test', 'test is this', 'this is testing'] phrases.each_with_index do |phrase, index| new_linkage = HarmonizerRedis::Linkage.new(id:index, content:phrase, category_id: 1) new_linkage.save end end it 'should add documents' do expect(HarmonizerRedis::IdfScorer.get_count('this')).to eq(4) expect(HarmonizerRedis::IdfScorer.get_doc_freq('this')).to eq(3) end it 'should calculate the tfidf for a word' do expect(HarmonizerRedis::IdfScorer.get_score('testing')).to be_within(0.01).of(1.071) end end
POSpulse/harmonizer_redis
spec/benchmark_spec.rb
require 'spec_helper' require 'benchmark' describe 'Benchmarking' do before :all do Redis.current = Redis.new(:driver => :hiredis) end before :each do Redis.current.flushall @to_add = [] file = File.open('/Users/tianwang/Documents/POSpulse/shopscout_data/douglas/all.txt', 'r') file.each_line do |line| @to_add << line end file.close end it 'should add 200 linkages quickly', :benchmark do (0...@to_add.length-200).each do |index| new_linkage = HarmonizerRedis::Linkage.new(content: @to_add[index], category_id: 1) new_linkage.save end time = Benchmark.realtime do (@to_add.length-200...@to_add.length).each do |index| new_linkage = HarmonizerRedis::Linkage.new(content: @to_add[index], category_id: 2) new_linkage.save end end expect(time).to be < 0.5 end it 'should calculate similarities quickly', :benchmark do @to_add.each_with_index do |task_answer, index| new_linkage = HarmonizerRedis::Linkage.new(content: task_answer, category_id: 1) new_linkage.save end time = Benchmark.realtime do HarmonizerRedis.calculate_similarities(1) end expect(time).to be < 3.0 end it 'should add 200 similarities quickly', :benchmark do (0...@to_add.length-200).each do |index| new_linkage = HarmonizerRedis::Linkage.new(content: @to_add[index], category_id: 1) new_linkage.save end (@to_add.length-200...@to_add.length).each do |index| new_linkage = HarmonizerRedis::Linkage.new(content: @to_add[index], category_id: 2) new_linkage.save end time = Benchmark.realtime do HarmonizerRedis.calculate_similarities(2) end expect(time).to be < 0.3 end it 'should calculate/retrieve similarities for 1 quickly', :benchmark do linkage_ids = [] (@to_add.length-200...@to_add.length).each do |index| new_linkage = HarmonizerRedis::Linkage.new(content: @to_add[index], category_id: 1) new_linkage.save linkage_ids << new_linkage.id end time = Benchmark.realtime do linkage_ids.each do |linkage_id| my_linkage = HarmonizerRedis::Linkage.find(linkage_id) my_linkage.get_similarities(20) end end expect(time / linkage_ids.length.to_f).to be < 0.1 end end
POSpulse/harmonizer_redis
lib/harmonizer_redis/category.rb
module HarmonizerRedis class Category < BaseObject attr_reader :id def initialize(id) @id = id end def save super() end class << self # Add linkage to category group def add_linkage(linkage) category_id = linkage.category_id linkage_id = linkage.id phrase_id = linkage.phrase_id unless self.valid?(category_id) new_category = self.new(category_id) new_category.save end self.add_to_linkage_set(category_id, linkage_id) self.add_to_phrase_set(category_id, phrase_id) set_changed(category_id, 1) set_calculated(category_id, 0) set_phrase_calculated(category_id, phrase_id, 0) # Creating/adding to a group add_group(category_id, phrase_id) # Adding linkage to the phrase Phrase.add_linkage(phrase_id, linkage_id, category_id) end # Gets list of linkages included in category group def get_linkage_list(category_id) Redis.current.smembers("#{self}:#{category_id}:linkage_set") end def get_phrase_list(category_id) Redis.current.smembers("#{self}:#{category_id}:phrase_set") end def get_matrices(category_id, phrase_id_list) matrices_list = [] if !matrices_calculated?(category_id) || changed?(category_id) phrase_id_list.each do |id| content = Phrase.get_content(id) new_matrix = IdfScorer.serialize_matrix(IdfScorer.calc_soft_matrix(content)) Redis.current.set("HarmonizerRedis::Phrase:#{id}:matrix", new_matrix) matrices_list << new_matrix end set_calculated(category_id, 1) else phrase_id_list.each do |phrase_id| matrices_list << Phrase.get_matrix(phrase_id) end end matrices_list end # Set the category as "unchanged". Should be called after Category similarities # have been calculated def reset_changed(category_id) set_changed(category_id, 0) end # Check to see if id is valid def valid?(category_id) Redis.current.sismember("#{self}:set", "#{category_id}") end def changed?(category_id) !Redis.current.getbit("#{self}:changed", category_id).zero? end def matrices_calculated?(category_id) !Redis.current.getbit("#{self}:calculated", category_id).zero? end def is_phrase_calculated?(category_id, phrase_id) !Redis.current.getbit("#{self}:#{category_id}:calculated", phrase_id).zero? end # Merge 2 phrases' groups def merge_phrase_groups(category_id, phrase_a_id, phrase_b_id) group_a = get_group_key(category_id, phrase_a_id) group_b = get_group_key(category_id, phrase_b_id) # Error either group does not exist if group_a.nil? || group_b.nil? raise 'Invalid Phrase ID(s) given!' end # Do nothing if both are already in the same group if group_a == group_b return end label_a = get_group_label(category_id, phrase_a_id) label_b = get_group_label(category_id, phrase_b_id) # if label_a and label_b both exist unless label_a.nil? ^ label_b.nil? # if label_a and label_b are not the same label if label_a != label_b # delete both labels due to conflict Redis.current.del(label_a, label_b) else # both labels are the same # delete only the label that belongs to the group getting destroyed Redis.current.del(label_b) end end # if only label_b exists if label_a.nil? && !label_b.nil? merge_phrase_group_helper(category_id, group_a, group_b) Redis.current.del(group_a) else # if only label_a exists merge_phrase_group_helper(category_id, group_b, group_a) Redis.current.del(group_b) end end ### Getting popular linkages and generating possible labels def get_group_popular_linkages(category_id, phrase_id, number = 5) phrases = get_group(category_id, phrase_id) linkages = [] phrases.each do |id| linkages += Phrase.get_popular_linkages(id) end linkages.sort_by! { |entry| -1 * entry[-1] } linkages.first(number) end def get_all_group_labels(category_id, phrase_id) phrases_in_group = get_group(category_id, phrase_id) categories = [] phrases_in_group.each do |phrase_id| categories += Phrase.get_categories(phrase_id) end labels = Hash.new { |hash, key| hash[key] = 0.0 } categories.each do |category_id| phrases_in_group.each do |phrase_id| group_label = get_group_label(category_id, phrase_id) unless group_label.nil? labels[group_label] += Phrase.get_linkage_count(phrase_id) end end end labels.to_a.sort_by { |x| x[-1] } end def set_group_label(category_id, phrase_id, label) Redis.current.set("#{get_group_key(category_id, phrase_id)}:label", label) end def get_group_label(category_id, phrase_id) Redis.current.get("#{get_group_key(category_id, phrase_id)}:label") end def get_group_count(category_id, phrase_id) Redis.current.scard(get_group_key(category_id, phrase_id)) end def get_group(category_id, phrase_id) Redis.current.smembers(get_group_key(category_id, phrase_id)) end def in_same_group?(category_id, phrase_a_id, phrase_b_id) get_group_key(category_id, phrase_a_id) == get_group_key(category_id, phrase_b_id) end ### Helpers #### def add_to_linkage_set(category_id, linkage_id) Redis.current.sadd("#{self}:#{category_id}:linkage_set", linkage_id) end def add_to_phrase_set(category_id, phrase_id) Redis.current.sadd("#{self}:#{category_id}:phrase_set", phrase_id) end def set_changed(category_id, value) Redis.current.setbit("#{self}:changed", category_id, value) end def set_calculated(category_id, value) Redis.current.setbit("#{self}:calculated", category_id, value) end def set_phrase_calculated(category_id, phrase_id, value) Redis.current.setbit("#{self}:#{category_id}:calculated", phrase_id, value) end def add_group(category_id, phrase_id) group_key = get_group_key(category_id, phrase_id) if group_key.nil? group_key = create_group(category_id, phrase_id) Redis.current.sadd(group_key, phrase_id) end end def create_group(category_id, phrase_id) new_group_id = Redis.current.incr("#{self}:#{category_id}:group_count") - 1 new_group_key = "#{self}:#{category_id}:group:#{new_group_id}" set_phrase_group(category_id, phrase_id, new_group_key) new_group_key end def get_group_key(category_id, phrase_id) Redis.current.get("#{self}:#{category_id}:#{phrase_id}:group") end def change_phrases_group(category_id, old_group_key, new_group_key) phrase_list = Redis.current.smembers(old_group_key) phrase_list.each do |phrase_id| set_phrase_group(category_id, phrase_id, new_group_key) end end def merge_phrase_group_helper(category_id, source_group, dest_group) Redis.current.sunionstore(dest_group, source_group, dest_group) change_phrases_group(category_id, source_group, dest_group) Redis.current.del(source_group) end def set_phrase_group(category_id, phrase_id, group_key) Redis.current.set("#{self}:#{category_id}:#{phrase_id}:group", group_key) end end private_class_method :set_changed, :create_group, :get_group_key, :set_phrase_group, :change_phrases_group end end
POSpulse/harmonizer_redis
ext/white_similarity/extconf.rb
require 'mkmf' $CFLAGS = '--std=c99 -O' create_makefile('harmonizer_redis/white_similarity')
POSpulse/harmonizer_redis
spec/linkage_spec.rb
require 'spec_helper' describe HarmonizerRedis::Linkage do before :all do Redis.current = Redis.new end before :each do Redis.current.flushall @linkage = HarmonizerRedis::Linkage.new(content: 'testing', category_id: 3) end it '#new' do expect(@linkage).to be_instance_of(HarmonizerRedis::Linkage) expect(@linkage.content).to eq('testing') expect(@linkage.category_id).to eq(3) end it '#save' do @linkage.save expect(Redis.current.sismember("#{@linkage.class}:set", @linkage.id)).to be true expect(Redis.current.get("#{@linkage.class}:#{@linkage.id}:content")).to eq('testing') expect(Redis.current.get("#{@linkage.class}:#{@linkage.id}:category_id")).to eq('3') expect(Redis.current.smembers("HarmonizerRedis::Category:3:linkage_set").length).to eq(1) end it 'should set old phrase if matches content' do @old_phrase = HarmonizerRedis::Linkage.new(id: 1, content: ' tEsTiNg ', category_id: 2) @old_phrase.save @linkage.save expect(Redis.current.get("#{@linkage.class}:#{@linkage.id}:phrase")).to eq('0') expect(Redis.current.get('HarmonizerRedis::Phrase:0:content')).to eq('testing') end it 'should create new phrase if content is new' do @old_phrase = HarmonizerRedis::Linkage.new(id: 1, content: 'different', category_id: 2) @old_phrase.save @linkage.save expect(Redis.current.get("#{@linkage.class}:#{@linkage.id}:phrase")).to eq('1') expect(Redis.current.get('HarmonizerRedis::Phrase:0:content')).to eq('different') expect(Redis.current.get('HarmonizerRedis::Phrase:1:content')).to eq('testing') end end
POSpulse/harmonizer_redis
lib/harmonizer_redis.rb
require 'harmonizer_redis/version' require 'harmonizer_redis/base_object' require 'harmonizer_redis/linkage' require 'harmonizer_redis/phrase' require 'harmonizer_redis/idf_scorer' require 'harmonizer_redis/white_similarity' require 'harmonizer_redis/category' require 'active_support/all' require 'redis/connection/hiredis' require 'redis' include WhiteSimilarity module HarmonizerRedis ### Calculate Similarities. Store them with the category class << self def calculate_similarities(category_id) unless Category.valid?(category_id) raise "Category ID: #{category_id} is invalid" end phrase_id_list = Category.get_phrase_list(category_id) matrix_list = Category.get_matrices(category_id, phrase_id_list) Redis.current.pipelined do (0...phrase_id_list.length).each do |i| (i + 1...phrase_id_list.length).each do |j| id_x = phrase_id_list[i] id_y = phrase_id_list[j] score = Phrase.calc_soft_pair_similarity(matrix_list[i], matrix_list[j]) unless score < 0.2 add_similarity_entry(id_x, id_y, score, category_id) end end end end Category.reset_changed(category_id) end ### String PreProcessing def normalize_string(string) ActiveSupport::Inflector.transliterate(string.strip.downcase). split(/[^\p{L}0-9]/).delete_if { |x| x.length == 0 }.join(' ') end ### Helper def add_similarity_entry(id_x, id_y, score, category_id) Redis.current.zadd("HarmonizerRedis::Category:#{category_id}:#{id_x}:sims", score, id_y) Redis.current.zadd("HarmonizerRedis::Category:#{category_id}:#{id_y}:sims", score, id_x) end private :add_similarity_entry end end
POSpulse/harmonizer_redis
lib/harmonizer_redis/linkage.rb
<gh_stars>0 module HarmonizerRedis class Linkage < BaseObject attr_reader :id def generate_id SecureRandom.uuid end def initialize(params={}) @content = params[:content] @category_id = params[:category_id] end def save # make sure that new phrase is saved # if phrase already exists : set to that phrase # otherwise : create a new phrase and set linkage:phrase to that phrase # linkage is also added to the category with certain id (can be used to divide tasks) # Assert: all required fields have been set @id = generate_id unless @id && @content && @category_id raise "id, content, and category_id are not all set" end @content_normalized = HarmonizerRedis.normalize_string(@content) existing_phrase_id = HarmonizerRedis::Phrase.find_by_content(@content_normalized) if existing_phrase_id @phrase = existing_phrase_id else new_phrase = HarmonizerRedis::Phrase.new(@content_normalized) new_phrase.save @phrase = new_phrase.id end super() Category.add_linkage(self) end # Readers def content @content ||= self.class.get_content(@id) end def content_normalized @content_normalized ||= self.class.get_content_normalized(@id) end def category_id @category_id ||= self.class.get_category_id(@id) end def corrected label = Category.get_group_label(category_id, phrase_id) if label.nil? if Category.get_group_count(category_id, phrase_id) return content else '(LABEL NOT SET)' end else label end end def phrase_id @phrase ||= self.class.get_phrase_id(@id) end # Writers def content=(value) if self.is_saved? raise "Saved linkage content cannot be edited" else @content = value end end def category_id=(value) if self.is_saved? raise "Saved linkage category_id cannot be edited" else @category_id = value end end ### Functionality def calculate_similarities own_phrase_id = phrase_id own_cat_id = category_id phrase_list = Category.get_phrase_list(own_cat_id) matrix_list = Category.get_matrices(category_id, phrase_list) own_matrix = Phrase.get_matrix(own_phrase_id) Redis.current.pipelined do phrase_list.each_with_index do |other_id, index| score = Phrase.calc_soft_pair_similarity(own_matrix, matrix_list[index]) if score > 0.2 Redis.current.zadd("HarmonizerRedis::Category:#{own_cat_id}:#{own_phrase_id}:sims", score, other_id) end end end Category.set_phrase_calculated(own_cat_id, own_phrase_id, 1) Category.reset_changed(own_cat_id) end def get_similarities(num_phrases = 20) self_phrase_id = phrase_id unless is_calculated? calculate_similarities end phrase_id_list = Redis.current.zrevrange("HarmonizerRedis::Category:#{self.category_id}:#{self_phrase_id}:sims", 0, num_phrases, :with_scores => true) results = [] phrase_id_list.each do |phrase, score| unless Category.in_same_group?(category_id, self_phrase_id, phrase) results << [Phrase.get_content(phrase), Category.get_group_label(category_id, phrase), score, phrase] end end results end # Recommend possible labels for a linkage def recommend_labels existing_labels = Category.get_all_group_labels(category_id, phrase_id) other_linkages = Category.get_group_popular_linkages(category_id, phrase_id) existing_labels + other_linkages end def merge_with_phrase(phrase_id) Category.merge_phrase_groups(category_id, self.phrase_id, phrase_id) end def set_corrected_label(label) Category.set_group_label(category_id, phrase_id, label) end ### Helpers def is_category_changed? unless is_saved? raise "Linkage must be saved first" end Category.changed?(self.category_id) end def is_saved? self.class.is_linkage_saved?(@id) end def is_calculated? if is_category_changed? || !is_saved? false else Category.is_phrase_calculated?(category_id, phrase_id) end end class << self def find(linkage_id) unless is_linkage_saved?(linkage_id) return nil end linkage = self.new linkage.instance_variable_set('@id', linkage_id) linkage end def is_linkage_saved?(linkage_id) Redis.current.sismember("#{self}:set", "#{linkage_id}") end def get_category_id(linkage_id) Redis.current.get("#{self}:#{linkage_id}:category_id") end def get_phrase_id(linkage_id) Redis.current.get("#{self}:#{linkage_id}:phrase") end def get_content(linkage_id) Redis.current.get("#{self}:#{linkage_id}:content") end def get_content_normalized(linkage_id) Redis.current.get("#{self}:#{linkage_id}:content_normalized") end end end end
POSpulse/harmonizer_redis
spec/integration_spec.rb
<reponame>POSpulse/harmonizer_redis require 'spec_helper' describe 'Integration Tests' do before :all do Redis.current = Redis.new(driver: :hiredis) end before :each do Redis.current.flushall data = [['Abcd.zzz', 1], ['abcDzzz', 1], ['abcdefg', 1], ['hijk lmnop', 1], ['abcd zzz', 2], ['zzzefg', 2]] @id_map = {} data.each_with_index do |entry, index| text, category_id = entry new_linkage = HarmonizerRedis::Linkage.new(id: index, content: text, category_id: category_id) new_linkage.save @id_map[index] = new_linkage.id end end it "should load a linkage" do my_linkage = HarmonizerRedis::Linkage.find(@id_map[0]) expect(my_linkage.content).to eq('Abcd.zzz') expect(my_linkage.corrected).to eq('Abcd.zzz') end it "should return whether more linkages have been added to same category" do my_linkage = HarmonizerRedis::Linkage.find(@id_map[0]) expect(my_linkage.is_category_changed?).to be_truthy end it "should allow separate calculations" do # Batch calculate similarities HarmonizerRedis.calculate_similarities(2) my_linkage = HarmonizerRedis::Linkage.find(@id_map[0]) phrase_id_list = Redis.current. zrevrange("HarmonizerRedis::Category:#{my_linkage.category_id}:#{my_linkage.phrase_id}:sims", 0, 20, :with_scores => true) expect(phrase_id_list).to eq([]) end it "should retrieve similarities for a linkage" do HarmonizerRedis.calculate_similarities(1) my_linkage = HarmonizerRedis::Linkage.find(@id_map[0]) similar_phrases = my_linkage.get_similarities(20) expect(similar_phrases.length).to eq(2) expect(similar_phrases[0][-1]).to eq("1") expect(similar_phrases[1][-1]).to eq("2") end it "should calc individual linkage similarities if no calculation has been made or data changes" do my_linkage = HarmonizerRedis::Linkage.find(@id_map[0]) similar_phrases = my_linkage.get_similarities(20) expect(similar_phrases.length).to eq(2) expect(similar_phrases[0][-1]).to eq("1") expect(similar_phrases[1][-1]).to eq("2") end it "should keep track if new calculations need to be made" do my_linkage = HarmonizerRedis::Linkage.find(@id_map[0]) expect(my_linkage.is_calculated?).to be_falsey my_linkage.calculate_similarities expect(my_linkage.is_calculated?).to be_truthy HarmonizerRedis::Linkage.new(content: 'new linkage', category_id: 1).save expect(my_linkage.is_calculated?).to be_falsey end it "should combine linkage's phrase with another phrase" do HarmonizerRedis.calculate_similarities(1) my_linkage = HarmonizerRedis::Linkage.find(@id_map[0]) other_linkage = HarmonizerRedis::Linkage.find(@id_map[1]) my_linkage.merge_with_phrase(1) my_linkage_group = Redis.current.get("HarmonizerRedis::Category:#{my_linkage.category_id}:#{my_linkage.phrase_id}:group") other_linkage_group = Redis.current.get("HarmonizerRedis::Category:#{other_linkage.category_id}:#{other_linkage.phrase_id}:group") expect(my_linkage_group).to eq(other_linkage_group) end it "should prevent linkage combos for phrases that are in different categories" do HarmonizerRedis.calculate_similarities(1) my_linkage = HarmonizerRedis::Linkage.find(@id_map[0]) other_linkage = HarmonizerRedis::Linkage.find(@id_map[5]) expect{my_linkage.merge_with_phrase(other_linkage.phrase_id)}.to raise_error("Invalid Phrase ID(s) given!") end it "should do nothing if linkage tries to combine with it's own phrase/another phrase in group" do HarmonizerRedis.calculate_similarities(1) my_linkage = HarmonizerRedis::Linkage.find(@id_map[0]) other_linkage = HarmonizerRedis::Linkage.find(@id_map[1]) my_linkage.merge_with_phrase(other_linkage.phrase_id) my_linkage.merge_with_phrase(other_linkage.phrase_id) my_linkage_group = Redis.current.get("HarmonizerRedis::Category:#{my_linkage.category_id}:#{my_linkage.phrase_id}:group") other_linkage_group = Redis.current.get("HarmonizerRedis::Category:#{other_linkage.category_id}:#{other_linkage.phrase_id}:group") expect(Redis.current.smembers(my_linkage_group)).to eq(Redis.current.smembers(other_linkage_group)) end it "similarities do not show phrases in the same group" do HarmonizerRedis.calculate_similarities(1) linkage_a = HarmonizerRedis::Linkage.find(@id_map[0]) linkage_b = HarmonizerRedis::Linkage.find(@id_map[1]) linkage_a.merge_with_phrase(linkage_b.phrase_id) simplified_a = linkage_a.get_similarities(20).map { |x| x[-1] } simplified_b = linkage_b.get_similarities(20).map { |x| x[-1] } expect(simplified_a.to_set.include?(linkage_b.phrase_id)).to be_falsey expect(simplified_b.to_set.include?(linkage_a.phrase_id)).to be_falsey end it "should let the label that is already set persist" do linkage_a = HarmonizerRedis::Linkage.find(@id_map[0]) linkage_b = HarmonizerRedis::Linkage.find(@id_map[1]) linkage_c = HarmonizerRedis::Linkage.find(@id_map[2]) linkage_b.set_corrected_label('ABCD') linkage_a.merge_with_phrase(linkage_b.phrase_id) expect(linkage_a.corrected).to eq('ABCD') linkage_c.merge_with_phrase(linkage_a.phrase_id) expect(linkage_c.corrected).to eq('ABCD') expect(linkage_b.corrected).to eq('ABCD') end it "should get probable labels for a linkage" do HarmonizerRedis.calculate_similarities(1) HarmonizerRedis.calculate_similarities(2) linkage_a = HarmonizerRedis::Linkage.find(@id_map[0]) linkage_b = HarmonizerRedis::Linkage.find(@id_map[1]) linkage_c = HarmonizerRedis::Linkage.find(@id_map[4]) linkage_a.merge_with_phrase(linkage_b.phrase_id) linkage_c.set_corrected_label('ABCD') suggested = linkage_a.recommend_labels expect(suggested[0][0]).to eq('ABCD') end end
POSpulse/harmonizer_redis
test/manual.rb
<gh_stars>0 require 'harmonizer_redis' Redis.current = Redis.new(:driver => :hiredis) Redis.current.flushall douglas_path = '/Users/tianwang/Documents/POSpulse/shopscout_data/douglas/all.txt' ey_path = '/Users/tianwang/Documents/POSpulse/shopscout_data/ey/raw_store_name_input.txt' to_add = [] file = File.open(ey_path, 'r') file.each_line do |line| to_add << line end file.close file = File.open(douglas_path, 'r') file.each_line do |line| to_add << line end to_add.each_with_index do |text, index| new_linkage = HarmonizerRedis::Linkage.new(id: index, content: text, category_id: 1) new_linkage.save end time = Benchmark.realtime do HarmonizerRedis.calculate_similarities(1) end ### Functions def print_list(list) list.each do |entry| entry.each do |item| print "#{item}\t" end print "\n" end end puts "Time: #{time}" puts 'Done. Now enter tests.' linkage_list = Redis.current.smembers("HarmonizerRedis::Linkage:set") input = 'ha' current_index = 0 while input[0] != 'quit' curr = HarmonizerRedis::Linkage.find(linkage_list[current_index]) puts "#{curr.content}" input = gets.chomp.downcase.split(',') if input[0] == 'similar' print_list(curr.get_similarities(10)) elsif input[0] == 'merge' phrase_id = input[1].to_i curr.merge_with_phrase(phrase_id) puts 'Merged!' elsif input[0] == 'recommend' print_list(curr.recommend_labels) elsif input[0] == 'set' unless input.length >= 2 raise 'Input too short' end curr.set_corrected_label(input[1]) else current_index += 1 end end linkage_list.each do |linkage_id| linkage = HarmonizerRedis.Linkage.find(linkage_id) puts "#{linkage.content}\t#{linkage.corrected}" end
rollbar/resque-rollbar
spec/spec_helper.rb
require "rubygems" require "bundler/setup" require "resque" require "resque-rollbar"
rollbar/resque-rollbar
lib/resque-rollbar.rb
require "resque-rollbar/version" require "resque/failure/rollbar" require "resque/rollbar"
rollbar/resque-rollbar
lib/resque/failure/rollbar.rb
<gh_stars>0 module Resque module Failure class Rollbar < Base def save ::Rollbar.report_exception(exception, payload) end end end end
rollbar/resque-rollbar
lib/resque/rollbar.rb
module Resque class Worker alias_method :initialize_original, :initialize def initialize(queues = [], options = {}) # Force synchronous reporting ::Rollbar.configure do |config| config.use_async = false end initialize_original queues, options end end end
rollbar/resque-rollbar
lib/resque-rollbar/version.rb
<reponame>rollbar/resque-rollbar<gh_stars>0 module Resque module Rollbar VERSION = "0.0.1" end end
rollbar/resque-rollbar
spec/resque/failure/rollbar_spec.rb
<reponame>rollbar/resque-rollbar describe Resque::Failure::Rollbar do it "notifies" do exception = StandardError.new("BOOM") worker = Resque::Worker.new(:test) queue = "test" payload = {'class' => Object, 'args' => 66} ::Rollbar = mock("rollbar") ::Rollbar.should_receive(:report_exception).with(exception, payload) backend = Resque::Failure::Rollbar.new(exception, worker, queue, payload) backend.save end end
yusayusa/HighlightTextView
HighlightTextView.podspec
Pod::Spec.new do |spec| spec.name = "HighlightTextView" spec.version = "0.6.0" spec.summary = "Highlight TextView." spec.homepage = "https://github.com/yusayusa/HighlightTextView" spec.license = "MIT" spec.author = { "yusayusa" => "<EMAIL>" } spec.swift_version = "5.0" spec.platform = :ios, "8.0" spec.source = { :git => "https://github.com/yusayusa/HighlightTextView.git", :tag => "#{spec.version}" } spec.source_files = ['HighlightTextView/**/*.{swift,h}'] end
grokify/glip-sdk-ruby
glip_sdk.gemspec
lib = 'glip_sdk' lib_file = File.expand_path("../lib/#{lib}.rb", __FILE__) File.read(lib_file) =~ /\bVERSION\s*=\s*["'](.+?)["']/ version = $1 #require File.expand_path('../lib/ringcentral_sdk/version', __FILE__) Gem::Specification.new do |s| s.name = lib s.version = version s.date = '2017-03-14' s.summary = 'Glip SDK client for Ruby' s.description = 'A Ruby SDK for the Glip collaboration solution (https://glip.com)' s.authors = ['<NAME>'] s.email = '<EMAIL>' s.homepage = 'https://github.com/grokify/' s.licenses = ['MIT'] s.files = Dir['lib/**/**/*'] s.files += Dir['[A-Z]*'] + Dir['test/**/*'] # s.files.reject! { |fn| fn.include? "CVS" } s.required_ruby_version = '>= 2.2.2' s.add_dependency 'ringcentral_sdk', '~> 2', '>= 2.0.0' s.add_development_dependency 'bundler', '~> 1' s.add_development_dependency 'coveralls', '~> 0' s.add_development_dependency 'mocha', '~> 1' s.add_development_dependency 'rake', '~> 12' s.add_development_dependency 'simplecov', '~> 0' s.add_development_dependency 'test-unit', '~> 3' end
grokify/glip-sdk-ruby
lib/glip_sdk/rest/client.rb
<filename>lib/glip_sdk/rest/client.rb require 'multi_json' require 'glip_sdk/rest/cache/groups' module GlipSdk module REST class Client attr_accessor :api attr_accessor :logger attr_accessor :groups attr_accessor :groups_cache attr_accessor :persons attr_accessor :posts def initialize(rc_sdk) @api = rc_sdk @logger = @api.config.logger puts ">>>\nGLIP_SCK_LOGGER_NAME [#{@api.config.logger.class.name}]\n<<<\n" @groups_cache = GlipSdk::REST::Cache::Groups.new @groups = GlipSdk::REST::Groups.new @api @persons = GlipSdk::REST::Persons.new @api @posts = GlipSdk::REST::Posts.new @api end def load_groups_cache(filepath = nil) if !filepath.nil? && File.exist?(filepath) groups_json = IO.read filepath all_groups = MultiJson.decode groups_json @groups_cache.load_groups all_groups else @groups_cache.load_groups @groups.all_groups end @posts.groups_cache = @groups_cache end end end end
grokify/glip-sdk-ruby
lib/glip_sdk/rest/cache.rb
<gh_stars>0 module GlipSdk module REST module Cache autoload :Groups, 'glip_sdk/rest/cache/groups' end end end
grokify/glip-sdk-ruby
lib/glip_sdk.rb
module GlipSdk VERSION = '0.0.5'.freeze autoload :REST, 'glip_sdk/rest' class << self def new(client, opts = {}) GlipSdk::REST::Client.new client, opts end end end
grokify/glip-sdk-ruby
lib/glip_sdk/rest/persons.rb
<reponame>grokify/glip-sdk-ruby module GlipSdk module REST class Persons def initialize(rc_sdk) @api = rc_sdk end def get(opts = {}) if opts.key? :personId return @api.http.get "glip/persons/#{opts[:personId]}" end nil end end end end
grokify/glip-sdk-ruby
lib/glip_sdk/rest/cache/groups.rb
module GlipSdk::REST::Cache class Groups attr_accessor :groups attr_accessor :groups_name2id attr_accessor :teams attr_accessor :teams_name2id def initialize @groups = {} @teams = {} @teams_name2id = {} @groups_name2id = {} end def load_groups(groups) if groups.is_a? Array groups.each { |g| load_group g } elsif groups.is_a? Hash groups.each { |_, g| load_group g} end end def load_group(group) if group.key? 'id' id = group['id'] type = group['type'] if type.to_s.downcase == 'team' @teams[id.to_s] = group @teams_name2id[group['name']] = id.to_s else @groups[id.to_s] = group @groups_name2id[group['name']] = id.to_s end end end def id_by_name(name) group = by_name name group.nil? ? nil : group['id'] end def by_name(name) team = team_by_name name return team unless team.nil? group_by_name name end def team_by_name(name) team_id = @teams_name2id[name.to_s] team_id ? @teams[team_id] : nil end def group_by_name(name) group_id = @groups_name2id[name.to_s] group_id ? @groups[group_id] : nil end end end
grokify/glip-sdk-ruby
lib/glip_sdk/rest/groups.rb
<filename>lib/glip_sdk/rest/groups.rb module GlipSdk module REST class Groups attr_accessor :cache attr_accessor :subscription def initialize(rc_sdk) @api = rc_sdk end def get(opts = {}) if opts.key? :groupId return @api.http.get "glip/groups/#{opts[:groupId]}" end @api.http.get 'glip/groups', opts end def observe(observer) @subscription = @api.create_subscription @subscription.subscribe ['/restapi/v1.0/account/~/extension/~/glip/groups'] @subscription.add_observer observer end def all_groups(params = {}) groups = [] get_next = true while get_next res = get params groups.concat(res.body['records']) if res.body['records'].length > 0 if res.body.key?('navigation') && res.body['navigation'].key?('prevPageToken') params['pageToken'] = res.body['navigation']['prevPageToken'] @api.config.logger.info "PrevPageToken [#{res.body['navigation']['prevPageToken']}]" else get_next = false end end groups end end end end
grokify/glip-sdk-ruby
lib/glip_sdk/rest/posts.rb
require 'multi_json' module GlipSdk module REST class Posts attr_accessor :groups_cache def initialize(rc_sdk) @api = rc_sdk @logger_prefix = " -- #{self.class.name}: " end def post(opts = {}) unless opts.key? :text raise ArgumentError, "Text must be provided to post message" end unless opts.key?(:groupId) || opts.key?(:groupName) raise ArgumentError, "Group Id or Group Name must be provided" end group_id = opts[:groupId] if group_id.nil? && @groups_cache && opts.key?(:groupName) group_id = @groups_cache.id_by_name(opts[:groupName]) end params = { groupId: group_id, text: opts[:text] } res = @api.http.post do |req| req.url 'glip/posts' req.headers['Content-Type'] = 'application/json' req.body = { groupId: group_id, text: opts[:text] } end if res.status >= 400 @api.config.logger.warn("#{@logger_prefix}Glip API Response Status #{res.status}") @api.config.logger.warn("#{@logger_prefix}Response Body: #{MultiJson.encode(res.body)}") else @api.config.logger.info("#{@logger_prefix}Glip API Response Status #{res.status}") end res end def get(opts = {}) if opts.key? :postId return @api.http.get "glip/posts/#{opts[:postId]}" end @api.http.get do |req| req.url "glip/posts" req.headers['Content-Type'] = 'application/json' req.body = opts end end def observe(observer) @subscription = @api.create_subscription() @subscription.subscribe(['/restapi/v1.0/account/~/extension/~/glip/posts']) @subscription.add_observer observer end end end end
grokify/glip-sdk-ruby
scripts/groups.rb
#!ruby require 'dotenv' require 'logger' require 'multi_json' require 'ringcentral_sdk' require 'glip_sdk' Dotenv.load rc = RingCentralSdk::REST::Client.new do |config| config.server_url = ENV['RC_SERVER_URL'] config.app_key = ENV['RC_APP_KEY'] config.app_secret = ENV['RC_APP_SECRET'] config.username = ENV['RC_USER_USERNAME'] config.extension = ENV['RC_USER_EXTENSION'] config.password = ENV['<PASSWORD>'] config.logger = Logger.new STDOUT config.logger.level = Logger::INFO end glip = GlipSdk::REST::Client.new rc # Get all groups and teams groups = glip.groups.all_groups glip.logger.info "#{groups.length} groups/teams were found." # Get all groups groups = glip.groups.all_groups type: 'Group' glip.logger.info "#{groups.length} groups were found." # Get all teams teams = glip.groups.all_groups type: 'Team' glip.logger.info "#{teams.length} teams were found." # Get one team if teams.length team = glip.groups.get groupId: teams[0]['id'] glip.logger.info MultiJson.encode(team.body) else glip.logger.info 'No teams to retrieve' end # Subscribe to group events including: GroupAdded, GroupChanged and GroupRemoved class MyObserverGroups def initialize(logger) @logger = logger end def update(message) @logger.info 'Subscription Group Message Received' @logger.info MultiJson.encode(message) end end glip.groups.observe MyObserverGroups.new(glip.logger) glip.logger.info("Hit any key to end") gets glip.groups.subscription.destroy
grokify/glip-sdk-ruby
lib/glip_sdk/rest.rb
module GlipSdk # REST is the namespace for the RingCentral REST API class in the # RingCentral Ruby SDK module REST autoload :Cache, 'glip_sdk/rest/cache' autoload :Client, 'glip_sdk/rest/client' autoload :Groups, 'glip_sdk/rest/groups' autoload :Persons, 'glip_sdk/rest/persons' autoload :Posts, 'glip_sdk/rest/posts' end end
ffknob/logstash-output-rocketchat
lib/logstash/outputs/rocketchat.rb
<gh_stars>0 # encoding: utf-8 require "logstash/outputs/base" require "logstash/namespace" # Rocket.Chat is free, unlimited and open source. Replace email, HipChat & Slack with the ultimate team chat software solution. # # This Logstash output plugin allows to send events as messages to channels and groups of a Rocketchat server. # # ==== Example # # [source,ruby] # ---------------------------------- # input { # stdin { } # } # output { # rocketchat { # host => "chat.deathstar.sw" # port => "3000" # username => "rc_integrations" # password => "<PASSWORD>" # channels => ["management", "operations", "rh"] # content => "My message: %{message}" # } # } # ---------------------------------- # # An rocketchat output that does nothing. class LogStash::Outputs::Rocketchat < LogStash::Outputs::Base config_name "rocketchat" # Host address of the Rocketchat server config :host, :validate => :string, :required => true # Port in which the Rocketchat server is listening config :port, :validate => :string,:default => 3000 # Http or https config :scheme, :validate => :string, :default => "http" # API route config :api, :validate => :string, :default => "/api/v1" # Username to use for the integration config :username, :validate => :string, :required => true # Password of the user config :password, :validate => :string, :required => true # A list of channels/groups to which the messages will be posted config :channels, :validate => :string, :required => true, :list => true # Message's content to be sent config :content, :validate => :string, :default => "%{message}" concurrency :single public def register m = __method__.to_s require 'rest-client' require 'cgi' require 'json' # Rocketchat's API # More information in https://rocket.chat/docs/developer-guides/rest-api/ raw_url = "#{@scheme}://#{@host}:#{@port}#{@api}" @url = ::LogStash::Util::SafeURI.new(raw_url) # We'll keep the rooms' ids so we don't need to ask again for each event @room_ids = Hash.new @logger.info("[#{m}] URL #{@url}, Username: #{@username}, Channel: #{@channels}") # We need to grab a token from Rocketchat auth() end # def register public def receive(event) return unless output?(event) m = __method__.to_s # The message itself message = event.sprintf(@content) # To which channels/groups should the message be sent @channels.map {|channel| if send_message(channel, message) @logger.debug("[#{m}] Message sent to room #{channel}") else @logger.error("[#{m}] An error occurred trying to send a message to room #{channel}.") end } end # def event public def auth() m = __method__.to_s @logger.debug("[#{m}] Trying to authenticate") # https://rocket.chat/docs/developer-guides/rest-api/authentication/login/ endpoint = "#{@url}/login" # We have to send a valid username/password in order to get a token payload = Hash.new payload['username'] = @username payload['password'] = <PASSWORD> @logger.debug("[#{m}] Endpoint: #{endpoint}, payload: #{payload}") # Go get this token... body = make_request('POST', endpoint, nil, payload) if body.nil? @logger.error("[#{m}] An error occurred trying to authenticate to the Rocketchat server") return false else status = body['status'] if status == 'success' # If it succeds, then we'll have an user id. and an authentication token @userId = body['data']['userId'] @authToken = body['data']['authToken'] return true end end end # def auth public def get_room_id(room_name) m = __method__.to_s @logger.debug("[#{m}] Trying to get the room's id for room #{room_name}") # Have we got the room's id already? if @room_ids.key?(room_name) @logger.debug("[#{m}] Already got the id for room #{room_name}, no need to ask Rocketchat server") return @room_ids[room_name] end # https://rocket.chat/docs/developer-guides/rest-api/channels/info/ endpoint = "#{@url}/channels.info" body = make_request('GET', endpoint, {:roomName => room_name}, nil) if body.nil? @logger.error("[#{m}] An error occurred trying to get the room id (channels endpoint) for room #{room_name}") else success = body['success'] if success # It's a channel... return the room's id @logger.debug("[#{m}] Room #{room_name} is a channel, saving its id so we don't need to ask for it anymore") @room_ids[:room_name] = body['channel']['_id'] @logger.debug("[#{m}] Rooms' ids: #{@room_ids}") return body['channel']['_id'] else @logger.info("[#{m}] Couldn't get the room id for room #{room_name} through the channels endpoint, trying with the groups endpoint") # https://rocket.chat/docs/developer-guides/rest-api/groups/info/ endpoint = "#{@url}/groups.info" body = make_request('GET', endpoint, {:roomName => room_name}, nil) if body.nil? @logger.error("[#{m}] An error occurred trying to get the room id (groups endpoint) for room #{room_name}") else success = body['success'] if success # It's a group... return the room's id @logger.debug("[#{m}] Room #{room_name} is a group, saving its id so we don't need to ask for it anymore") @room_ids[:room_name] = body['group']['_id'] @logger.debug("[#{m}] Rooms' ids: #{@room_ids}") return body['group']['_id'] else return nil end end end end return nil end # def get_room_id public def send_message(room_name, message) m = __method__.to_s @logger.debug("[#{m}] Trying to a send message to room #{room_name}") # https://rocket.chat/docs/developer-guides/rest-api/chat/sendmessage/ endpoint = "#{@url}/chat.sendMessage" # Go get the room's id room_id = get_room_id(room_name) if room_id payload = Hash.new payload['message'] = Hash.new payload['message']['rid'] = room_id payload['message']['msg'] = message body = make_request('POST', endpoint, nil, payload) if body.nil? @logger.error("[#{m}] An error occurred trying to send message to the Rocketchat server, room #{room_name}") return false else success = body['success'] if success # Message sent return true else # Something went wrong return false end end else @logger.warn("[#{m}] An error occurred trying to get the room id for room #{room_name}. Are you sure the user #{@user} is subscribed to this room?") end return false end # def send_message public def make_request(method, endpoint, params = nil, payload = nil) m = __method__.to_s @logger.debug("[#{m}] Making a #{method} request to #{endpoint}") @logger.debug("[#{m}] Auth token: #{@authToken}") @logger.debug("[#{m}] User id: #{@userId}") @logger.debug("[#{m}] Params: #{params}") @logger.debug("[#{m}] Payload: #{payload}") begin if method == 'POST' RestClient.post( endpoint, JSON.dump(payload), { :'X-Auth-Token' => @authToken || '', :'X-User-Id' => @userId || '' , :accept => "application/json", :'User-Agent' => "logstash-output-rocketchat", :content_type => @content_type }) { |response, request, result, &block| if response.code != 200 @logger.error("[#{m}] An error occurred trying to request from the Rocketchat's server API: #{response.code}") @logger.debug("[#{m}] Got a #{response.code} response: #{response}") return response.body ? JSON.parse(response.body) : nil else @logger.debug("[#{m}] Got a #{response.code} response: #{response}") return response.body ? JSON.parse(response.body) : nil end } elsif method == 'GET' RestClient.get( endpoint, { :params => params, :'X-Auth-Token' => @authToken || '', :'X-User-Id' => @userId || '' , :accept => "application/json", :'User-Agent' => "logstash-output-rocketchat", :content_type => @content_type }) { |response, request, result, &block| if response.code != 200 @logger.error("[#{m}] An error occurred trying to request from the Rocketchat's server API: #{response.code}") @logger.debug("[#{m}] Got a #{response.code} response: #{response}") return response.body ? JSON.parse(response.body) : nil else @logger.debug("[#{m}] Got a #{response.code} response: #{response}") return response.body ? JSON.parse(response.body) : nil end } end rescue Exception => e @logger.error("[#{m}] Unhandled exception", :exception => e, :stacktrace => e.backtrace) end end # def make_request end # class LogStash::Outputs::Rocketchat
ffknob/logstash-output-rocketchat
logstash-output-rocketchat.gemspec
Gem::Specification.new do |s| s.name = 'logstash-output-rocketchat' s.version = '0.1.3' s.licenses = ['Apache-2.0'] s.summary = 'Sends messages to a Rocketchat server with information from the events.' s.description = 'Rocket.Chat is the leading open source team chat software solution. Free, unlimited and completely customizable with on-premises and SaaS cloud hosting. This Logstash plugin allows to send events to Rocketchat channels and groups.' s.homepage = 'https://github.com/ffknob/logstash-output-rocketchat' s.authors = ['ffknob'] s.email = '<EMAIL>' s.require_paths = ['lib'] # Files s.files = Dir['lib/**/*','spec/**/*','vendor/**/*','*.gemspec','*.md','CONTRIBUTORS','Gemfile','LICENSE','NOTICE.TXT'] # Tests s.test_files = s.files.grep(%r{^(test|spec|features)/}) # Special flag to let us know this is actually a logstash plugin s.metadata = { "logstash_plugin" => "true", "logstash_group" => "output" } # Gem dependencies s.add_runtime_dependency "logstash-core-plugin-api", ">= 1.60", "<= 2.99" s.add_runtime_dependency "logstash-codec-plain" s.add_runtime_dependency "rest-client", '~> 1.8', ">= 1.8.0" s.add_development_dependency "logstash-devutils" s.add_development_dependency "logstash-filter-json" end
indirect/rails-footnotes
spec/controllers/log_note_controller_spec.rb
<filename>spec/controllers/log_note_controller_spec.rb<gh_stars>10-100 require 'spec_helper' require 'stringio' describe 'log note', type: :controller do class ApplicationController < ActionController::Base end controller do def index Rails.logger.error 'foo' Rails.logger.warn 'bar' render inline: '<html><head></head><body></body></html>', content_type: 'text/html' end end before :all do Footnotes.enabled = true end after :all do Footnotes.enabled = false end it 'Includes the log in the response' do get :index log_debug = first('fieldset#log_debug_info div', :visible => false) expect(log_debug).to have_content('foo') expect(log_debug).to have_content('bar') end end
indirect/rails-footnotes
lib/rails-footnotes/filter.rb
<gh_stars>10-100 module Footnotes class Filter @@no_style = false @@multiple_notes = false @@klasses = [] @@lock_top_right = false @@font_size = '11px' # Default link prefix is textmate @@prefix = 'txmt://open?url=file://%s&amp;line=%d&amp;column=%d' # Edit notes @@notes = [ :controller, :view, :layout, :partials, :stylesheets, :javascripts ] # Show notes @@notes += [ :assigns, :session, :cookies, :params, :filters, :routes, :env, :queries, :log] # :no_style => If you don't want the style to be appended to your pages # :notes => Class variable that holds the notes to be processed # :prefix => Prefix appended to FootnotesLinks # :multiple_notes => Set to true if you want to open several notes at the same time # :lock_top_right => Lock a btn to toggle notes to the top right of the browser # :font_size => CSS font-size property cattr_accessor :no_style, :notes, :prefix, :multiple_notes, :lock_top_right, :font_size class << self include Footnotes::EachWithRescue # Calls the class method start! in each note # Sometimes notes need to set variables or clean the environment to work properly # This method allows this kind of setup # def start!(controller) self.each_with_rescue(Footnotes.before_hooks) {|hook| hook.call(controller, self)} @@klasses = [] self.each_with_rescue(@@notes.flatten) do |note| klass = "Footnotes::Notes::#{note.to_s.camelize}Note".constantize klass.start!(controller) if klass.respond_to?(:start!) @@klasses << klass end end # If none argument is sent, simply return the prefix. # Otherwise, replace the args in the prefix. # def prefix(*args) if args.empty? @@prefix else args.map! { |arg| arg.to_s.split("/").map{|s| ERB::Util.url_encode(s) }.join("/") } if @@prefix.respond_to? :call @@prefix.call *args else format(@@prefix, *args) end end end end def initialize(controller) @controller = controller @template = controller.instance_variable_get(:@template) @notes = [] revert_pos(controller.response_body) do @body = controller.response.body end end def add_footnotes! add_footnotes_without_validation! if valid? rescue Exception => e # Discard footnotes if there are any problems self.class.log_error("Footnotes Exception", e) end # Calls the class method close! in each note # Sometimes notes need to finish their work even after being read # This method allows this kind of work # def close!(controller) self.each_with_rescue(@@klasses) {|klass| klass.close!(controller)} self.each_with_rescue(Footnotes.after_hooks) {|hook| hook.call(controller, self)} end protected def valid? @body.is_a?(String) && performed_render? && valid_format? && valid_content_type? && !component_request? && !xhr? && !footnotes_disabled? && !attached_file? end def add_footnotes_without_validation! initialize_notes! insert_styles unless @@no_style insert_footnotes end def initialize_notes! each_with_rescue(@@klasses) do |klass| note = klass.new(@controller) @notes << note if note.valid? end end def revert_pos(file) return yield unless file.respond_to?(:pos) && file.respond_to?(:pos=) original = file.pos yield file.pos = original end def performed_render? @controller.respond_to?(:performed?) && @controller.performed? end def valid_format? format = @controller.response.content_type format.nil? || format.include?("text/html") end def valid_content_type? c = @controller.response.headers['Content-Type'].to_s (c.empty? || c =~ /html/) end def component_request? @controller.instance_variable_get(:@parent_controller) end def xhr? @controller.request.xhr? end def footnotes_disabled? @controller.params[:footnotes] == "false" end def attached_file? !!(@controller.headers['Content-Disposition'] =~ /attachment/) end # # Insertion methods # def insert_styles #TODO More customizable(reset.css, from file etc.) if @@lock_top_right extra_styles = <<-STYLES #footnotes_debug {position: fixed; top: 0px; right: 0px; width: 100%; z-index: 10000; margin-top: 0;} #footnotes_debug #toggle_footnotes {position: absolute; right: 0; top: 0; background: #fff; border: 1px solid #ccc; color: #9b1b1b; font-size: 20px; text-align: center; padding: 8px; opacity: 0.9;} #footnotes_debug #toggle_footnotes:hover {opacity: 1;} #footnotes_debug #all_footnotes {display: none; padding: 15px; background: #fff; box-shadow: 0 0 5px rgba(0,0,0,0.4);} #footnotes_debug fieldset > div {max-height: 500px; overflow: scroll;} STYLES else extra_styles = <<-STYLES #footnotes_debug #toggle_footnotes {display: none;} STYLES end insert_text :before, /<\/head>/i, <<-HTML <!-- Footnotes Style --> <style type="text/css"> #footnotes_debug {font-size: #{@@font_size}; font-family: Consolas, monaco, monospace; font-weight: normal; margin: 2em 0 1em 0; text-align: center; color: #444; line-height: 16px; background: #fff;} #footnotes_debug th, #footnotes_debug td {color: #444; line-height: 18px;} #footnotes_debug a {color: #9b1b1b; font-weight: inherit; text-decoration: none; line-height: 18px;} #footnotes_debug table {text-align: left; width: 100%;} #footnotes_debug table td {padding: 5px; border-bottom: 1px solid #ccc;} #footnotes_debug table td strong {color: #9b1b1b;} #footnotes_debug table th {padding: 5px; border-bottom: 1px solid #ccc;} #footnotes_debug table tr:nth-child(2n) td {background: #f5f5f5;} #footnotes_debug table tr:nth-child(2n + 1) td {background: #fff;} #footnotes_debug tbody {text-align: left;} #footnotes_debug .name_values td {vertical-align: top;} #footnotes_debug legend {background-color: #fff;} #footnotes_debug fieldset {text-align: left; border: 1px dashed #aaa; padding: 0.5em 1em 1em 1em; margin: 1em 2em; color: #444; background-color: #FFF;} #{extra_styles} /* Aditional Stylesheets */ #{@notes.map(&:stylesheet).compact.join("\n")} </style> <!-- End Footnotes Style --> HTML end def insert_footnotes # Fieldsets method should be called first content = fieldsets element_style = '' if @@lock_top_right element_style = 'style="display: none;"' end footnotes_html = <<-HTML <!-- Footnotes --> <div style="clear:both"></div> <div id="footnotes_debug"> <a id="toggle_footnotes" href="#" onclick="Footnotes.toggle('all_footnotes'); return false;">fn</a> <div id="all_footnotes" #{element_style}> #{links} #{content} </div> <script type="text/javascript"> var Footnotes = function() { function hideAll(){ #{close unless @@multiple_notes} } function hideAllAndToggle(id) { var n = note(id); var display = n.style.display; hideAll(); // Restore original display to allow toggling n.style.display = display; toggle(id) location.href = '#footnotes_debug'; } function note(id) { return (document.getElementById(id)); } function toggle(id){ var el = note(id); if (el.style.display == 'none') { Footnotes.show(el); } else { Footnotes.hide(el); } } function show(element) { element.style.display = 'block' } function hide(element) { element.style.display = 'none' } return { show: show, hide: hide, toggle: toggle, hideAllAndToggle: hideAllAndToggle } }(); /* Additional Javascript */ #{@notes.map(&:javascript).compact.join("\n")} </script> </div> <!-- End Footnotes --> HTML placeholder = /<div[^>]+id=['"]footnotes_holder['"][^>]*>/i if @controller.response.body =~ placeholder insert_text :after, placeholder, footnotes_html else insert_text :before, /<\/body>/i, footnotes_html end end # Process notes to gets their links in their equivalent row # def links links = Hash.new([]) order = [] each_with_rescue(@notes) do |note| order << note.row links[note.row] += [link_helper(note)] end html = '' order.uniq! order.each do |row| html << "#{row.is_a?(String) ? row : row.to_s.camelize}: #{links[row].join(" | \n")}<br />" end html end # Process notes to get their content # def fieldsets content = '' each_with_rescue(@notes) do |note| next unless note.has_fieldset? content << <<-HTML <fieldset id="#{note.to_sym}_debug_info" style="display: none"> <legend>#{note.legend}</legend> <div>#{note.content}</div> </fieldset> HTML end content end # Process notes to get javascript code to close them. # This method is only used when multiple_notes is false. # def close javascript = '' each_with_rescue(@notes) do |note| next unless note.has_fieldset? javascript << close_helper(note) end javascript end # # Helpers # # Helper that creates the javascript code to close the note # def close_helper(note) "Footnotes.hide(document.getElementById('#{note.to_sym}_debug_info'));\n" end # Helper that creates the link and javascript code when note is clicked # def link_helper(note) onclick = note.onclick unless href = note.link href = '#' onclick ||= "Footnotes.hideAllAndToggle('#{note.to_sym}_debug_info');return false;" if note.has_fieldset? end "<a href=\"#{href}\" onclick=\"#{onclick}\">#{note.title}</a>" end # Inserts text in to the body of the document # +pattern+ is a Regular expression which, when matched, will cause +new_text+ # to be inserted before or after the match. If no match is found, +new_text+ is appended # to the body instead. +position+ may be either :before or :after # def insert_text(position, pattern, new_text) index = case pattern when Regexp if match = @controller.response.body.match(pattern) match.offset(0)[position == :before ? 0 : 1] else @controller.response.body.size end else pattern end newbody = @controller.response.body newbody.insert index, new_text @controller.response.body = newbody end # Instance each_with_rescue method # def each_with_rescue(*args, &block) self.class.each_with_rescue(*args, &block) end end end
indirect/rails-footnotes
lib/rails-footnotes/notes/view_note.rb
module Footnotes module Notes class ViewNote < AbstractNote cattr_accessor :template def self.start!(controller) @subscriber ||= ActiveSupport::Notifications.subscribe('render_template.action_view') do |*args| event = ActiveSupport::Notifications::Event.new *args self.template = {:file => event.payload[:identifier], :duration => event.duration} end end def initialize(controller) @controller = controller end def row :edit end def title "View (#{"%.3f" % self.template[:duration]}ms)" end def link escape(Footnotes::Filter.prefix(filename, 1, 1)) end def valid? prefix? && filename && File.exists?(filename) end protected def filename return @filename if defined?(@filename) @filename = self.class.template.try(:[], :file) end end end end
indirect/rails-footnotes
lib/rails-footnotes/notes/files_note.rb
module Footnotes module Notes class FilesNote < AbstractNote def initialize(controller) @files = scan_text(controller.response.body) parse_files! end def row :edit end def content if @files.empty? "" else "<ul><li>%s</li></ul>" % @files.join("</li><li>") end end def valid? prefix? end protected def scan_text(text) raise NotImplementedError, "implement this in your subclass" end def parse_files! asset_paths = Rails.application.config.try(:assets).try(:paths) || [] linked_files = [] @files.collect do |file| file.gsub!(/-[a-f0-9]{64}\./, '.') base_name = File.basename(file) asset_paths.each do |asset_path| results = Dir[File.expand_path(base_name, asset_path) + '*'] results.each do |r| linked_files << %[<a href="#{Footnotes::Filter.prefix(r, 1, 1)}">#{File.basename(r)}</a>] end break if results.present? end end @files = linked_files end end end end
indirect/rails-footnotes
spec/notes/assigns_note_spec.rb
require "spec_helper" require 'action_controller' require "rails-footnotes/notes/assigns_note" describe Footnotes::Notes::AssignsNote do let(:note) do @controller = double allow(@controller).to receive(:instance_variables).and_return([:@action_has_layout, :@status]) @controller.instance_variable_set(:@action_has_layout, true) @controller.instance_variable_set(:@status, 200) Footnotes::Notes::AssignsNote.new(@controller) end subject {note} before(:each) {Footnotes::Notes::AssignsNote.ignored_assigns = []} it {should be_valid} describe '#title' do subject { super().title } it {should eql 'Assigns (2)'} end specify {expect(note.send(:assigns)).to eql [:@action_has_layout, :@status]} specify {expect(note.send(:to_table)).to eql [ ["Name", "Value"], ["<strong>@action_has_layout</strong><br /><em>TrueClass</em>", "true"], ["<strong>@status</strong><br /><em>Integer</em>", "200"] ]} describe "Ignored Assigns" do before(:each) {Footnotes::Notes::AssignsNote.ignored_assigns = [:@status]} it {expect(note.send(:assigns)).not_to include :@status} end describe "Ignored Assigns by regexp" do before(:each) {Footnotes::Notes::AssignsNote.ignored_assigns_pattern = /^@status$/} it {expect(note.send(:assigns)).not_to include :@status} end it "should call #mount_table method with correct params" do expect(note).to receive(:mount_table).with( [ ["Name", "Value"], ["<strong>@action_has_layout</strong><br /><em>TrueClass</em>", "true"], ["<strong>@status</strong><br /><em>Integer</em>", "200"] ], {:summary=>"Debug information for Assigns (2)"}) note.content end end
indirect/rails-footnotes
lib/rails-footnotes.rb
<filename>lib/rails-footnotes.rb require 'rails' require 'action_controller' require 'rails-footnotes/abstract_note' require 'rails-footnotes/each_with_rescue' require 'rails-footnotes/filter' require 'rails-footnotes/notes/all' require 'rails-footnotes/extension' module Footnotes mattr_accessor :before_hooks @@before_hooks = [] mattr_accessor :after_hooks @@after_hooks = [] mattr_accessor :enabled @@enabled = false class << self delegate :notes, :to => Filter delegate :notes=, :to => Filter delegate :prefix, :to => Filter delegate :prefix=, :to => Filter delegate :no_style, :to => Filter delegate :no_style=, :to => Filter delegate :multiple_notes, :to => Filter delegate :multiple_notes=, :to => Filter delegate :lock_top_right, :to => Filter delegate :lock_top_right=, :to => Filter delegate :font_size, :to => Filter delegate :font_size=, :to => Filter end def self.before(&block) @@before_hooks << block end def self.after(&block) @@after_hooks << block end def self.enabled?(controller) if @@enabled.is_a? Proc if @@enabled.arity == 1 @@enabled.call(controller) else @@enabled.call end else !!@@enabled end end def self.setup yield self end end ActiveSupport.on_load(:action_controller) do ActionController::Base.send(:include, Footnotes::RailsFootnotesExtension) end load Rails.root.join('.rails_footnotes') if Rails.root && Rails.root.join('.rails_footnotes').exist?
indirect/rails-footnotes
spec/notes/view_note_spec.rb
<reponame>indirect/rails-footnotes<filename>spec/notes/view_note_spec.rb require "spec_helper" require "rails-footnotes/notes/view_note" describe Footnotes::Notes::ViewNote do it "should not be valid if view file not exist" do note = Footnotes::Notes::ViewNote.new(double) allow(note).to receive(:filename).and_return(nil) expect(note).not_to be_valid end it "should not explode if template is nil" do Footnotes::Notes::ViewNote.template = nil note = Footnotes::Notes::ViewNote.new(double) expect(note).to_not be_valid end end
indirect/rails-footnotes
lib/rails6-footnotes.rb
require_relative "./rails-footnotes"
indirect/rails-footnotes
lib/rails-footnotes/extension.rb
require 'active_support/concern' module Footnotes module RailsFootnotesExtension extend ActiveSupport::Concern included do prepend_before_action :rails_footnotes_before_filter after_action :rails_footnotes_after_filter end def rails_footnotes_before_filter Footnotes::Filter.start!(self) if Footnotes.enabled?(self) end def rails_footnotes_after_filter return unless Footnotes.enabled?(self) filter = Footnotes::Filter.new(self) filter.add_footnotes! filter.close!(self) end end end
indirect/rails-footnotes
rails-footnotes.gemspec
# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) require "rails-footnotes/version" Gem::Specification.new do |s| s.name = "rails-footnotes" s.version = Footnotes::VERSION s.platform = Gem::Platform::RUBY s.authors = ["<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>"] s.email = ["<EMAIL>"] s.homepage = "http://github.com/indirect/rails-footnotes" s.summary = %q{Every Rails page has footnotes that gives information about your application and links back to your editor.} s.description = %q{Every Rails page has footnotes that gives information about your application and links back to your editor.} s.add_dependency "rails", "~> 6.0" s.required_ruby_version = "~> 3.0" s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.require_paths = ["lib"] end
dpep/ruby_gem_template
spec/spec_helper.rb
<reponame>dpep/ruby_gem_template require "byebug" require "rspec" require "simplecov" SimpleCov.start do add_filter /spec/ end if ENV["CI"] == "true" || ENV["CODECOV_TOKEN"] require "codecov" SimpleCov.formatter = SimpleCov::Formatter::Codecov end # load this gem gem_name = Dir.glob("*.gemspec")[0].split(".")[0] require gem_name RSpec.configure do |config| # allow "fit" examples config.filter_run_when_matching :focus config.mock_with :rspec do |mocks| # verify existence of stubbed methods mocks.verify_partial_doubles = true end end # Dir["./spec/support/**/*.rb"].sort.each { |f| require f }
dpep/ruby_gem_template
lib/MY_NEW_GEM.rb
<filename>lib/MY_NEW_GEM.rb require "MY_NEW_GEM/version" module MY_NEW_GEM end
shjang7/Enumerable
lib/enumerable.rb
# frozen_string_literal: true module Enumerable def my_each return (is_a? Enumerator) ? self : to_enum(:my_each) unless block_given? for x in self yield(x) end end def my_each_with_index return to_enum(:my_each_with_index) unless block_given? i = 0 my_each do |x| yield(x, i) i += 1 end end def my_select return (is_a? Enumerator) ? self : to_enum(:my_select) unless block_given? arr = [] my_each { |p| arr << p if yield(p) } arr end def my_all?(pattern = nil) if block_given? my_each { |p| return false unless yield(p) } elsif !pattern.nil? if pattern.is_a? Regexp my_each { |p| return false unless pattern =~ p } else # sort my_each { |p| return false unless p.is_a?(pattern) } end else my_each { |p| return false unless p } end true end def my_any?(pattern = nil) if block_given? my_each { |p| return true if yield(p) } elsif !pattern.nil? if pattern.is_a? Regexp my_each { |p| return true if pattern =~ p } else # sort my_each { |p| return true if p.is_a?(pattern) } end else my_each { |p| return true if p } end false end def my_none?(pattern = nil) if block_given? my_each { |p| return false if yield(p) } elsif !pattern.nil? if pattern.is_a? Regexp my_each { |p| return false if pattern =~ p } else # sort my_each { |p| return false if p.is_a?(pattern) } end else my_each { |p| return false if p } end true end def my_count(item = nil) cnt = 0 if item.nil? my_each do |p| next if block_given? && !yield(p) cnt += 1 end else my_each { |p| cnt += 1 if p == item } end cnt end def my_map(proc = nil) return to_enum(:my_map) unless block_given? new_arr = [] my_each do |p| new_arr << if !proc.nil? proc.call(p) else yield(p) end end new_arr end def my_inject(acc = nil) my_each_with_index do |p, i| if i == 0 && acc.nil? acc = p next end acc = yield(acc, p) end acc end end def multiply_else(arr) result = arr.my_inject do |memo, curr| memo * curr end result end
heaptracetechnology/yaml
app.rb
#!/usr/bin/env ruby require 'json' require 'sinatra' require "sinatra/namespace" require 'yaml' set :port, 8080 set :bind, '0.0.0.0' set :show_exceptions, false post '/format' do data = JSON.parse request.body.read YAML.dump(data['data']) end namespace '/parse' do before do content_type :json end post do data = JSON.parse request.body.read YAML.load(data['data']) end after do response.body = JSON.dump(response.body) end end error do {'message': env['sinatra.error'].message} end
michaelvobrien/furigana
lib/furigana/formatter/html.rb
module Furigana module Formatter class HTML < Formatter::Base def replacement(surface_form, reading) "<ruby><rb>%s</rb><rp>【</rp><rt>%s</rt><rp>】</rp></ruby>" % [surface_form, reading] end end end end
michaelvobrien/furigana
lib/furigana/formatter/json.rb
require 'json' module Furigana module Formatter class JSON < Formatter::Base def render @kanji_tokens.to_json end end end end
michaelvobrien/furigana
lib/furigana/formatters.rb
require_relative 'formatter/base' require_relative 'formatter/text' require_relative 'formatter/yomikata' require_relative 'formatter/html' require_relative 'formatter/json'
michaelvobrien/furigana
lib/furigana/formatter/text.rb
module Furigana module Formatter class Text < Formatter::Base def replacement(surface_form, reading) "%s【%s】" % [surface_form, reading] end end end end
michaelvobrien/furigana
test/reader_test.rb
<filename>test/reader_test.rb # -*- coding: utf-8 -*- require 'test_helper' class ReaderTest < Test::Unit::TestCase test "食べる" do text = "食べる" expected = [['食', 'た']] assert_equal expected, Furigana::Reader.new.reading(text) end test "勉強" do text = "勉強" expected = [['勉強', 'べんきょう']] assert_equal expected, Furigana::Reader.new.reading(text) end test "細かいお金" do text = "細かいお金" expected = [["細", "こま"], ["金", "かね"]] assert_equal expected, Furigana::Reader.new.reading(text) end test "コーヒーを飲んだ" do text = "コーヒーを飲んだ" expected = [["飲", "の"]] assert_equal expected, Furigana::Reader.new.reading(text) end test "日本語を勉強する。" do text = "日本語を勉強する。" expected = [['日本語', 'にほんご'], ['勉強', 'べんきょう']] assert_equal expected, Furigana::Reader.new.reading(text) end test "バルト海の新しい読み物。" do text = "バルト海の新しい読み物。" expected = [["海", "かい"], ["新", "あたら"], ["読", "よ"], ["物", "もの"]] assert_equal expected, Furigana::Reader.new.reading(text) end test "国営通信は20日" do text = "国営通信は20日" expected = [["国営", "こくえい"], ["通信", "つうしん"], ["日", "にち"]] assert_equal expected, Furigana::Reader.new.reading(text) end end
michaelvobrien/furigana
test/html_formatter_test.rb
<gh_stars>10-100 # -*- coding: utf-8 -*- require 'test_helper' class HTMLFormatterTest < Test::Unit::TestCase test "食べる" do text = "食べる" expected = "<ruby><rb>食</rb><rp>【</rp><rt>た</rt><rp>】</rp></ruby>べる" assert_equal expected, Furigana::Formatter::HTML.new(text, Furigana::Reader.new.reading(text)).render end test "勉強" do text = "勉強" expected = "<ruby><rb>勉強</rb><rp>【</rp><rt>べんきょう</rt><rp>】</rp></ruby>" assert_equal expected, Furigana::Formatter::HTML.new(text, Furigana::Reader.new.reading(text)).render end test "細かいお金" do text = "細かいお金" expected = "<ruby><rb>細</rb><rp>【</rp><rt>こま</rt><rp>】</rp></ruby>かいお<ruby><rb>金</rb><rp>【</rp><rt>かね</rt><rp>】</rp></ruby>" assert_equal expected, Furigana::Formatter::HTML.new(text, Furigana::Reader.new.reading(text)).render end test "日本語を勉強する。" do text = "日本語を勉強する。" expected = "<ruby><rb>日本語</rb><rp>【</rp><rt>にほんご</rt><rp>】</rp></ruby>を<ruby><rb>勉強</rb><rp>【</rp><rt>べんきょう</rt><rp>】</rp></ruby>する。" assert_equal expected, Furigana::Formatter::HTML.new(text, Furigana::Reader.new.reading(text)).render end end
michaelvobrien/furigana
lib/furigana/formatter/base.rb
module Furigana module Formatter class Base SURFACE_FORM, READING = 0, 1 def initialize(text, kanji_tokens) @text = text @kanji_tokens = kanji_tokens end def render reset @text.each_char do |char| if no_more_kanji_tokens? @new_text += char next end @substring += char if not_a_kanji_group_match? char @new_text += @substring reset_substring next end if kanji_group_match? # replace kanji group with formatting @new_text += replacement(@current_token[SURFACE_FORM], @current_token[READING]) @current_token = next_token reset_substring else # kanji token pos advances with char pos increment_kanji_char_pos end end @new_text end private def reset @new_text = "" reset_substring @kanji_tokens_enum = @kanji_tokens.to_enum @current_token = next_token end def reset_substring @substring = "" @kanji_char_pos = 0 end def increment_kanji_char_pos @kanji_char_pos += 1 end def no_more_kanji_tokens? @current_token.nil? end def not_a_kanji_group_match?(char) current_kanji_char = @current_token[SURFACE_FORM][@kanji_char_pos] char != current_kanji_char end def kanji_group_match? @kanji_char_pos == (@current_token[SURFACE_FORM].length - 1) end def next_token @kanji_tokens_enum.next rescue StopIteration nil end def replacement(surface_form, reading) fail NotImplementedError, "#{self.class} must implement `#{__method__}`" end end end end
michaelvobrien/furigana
lib/furigana/reader.rb
require 'diff/lcs' require 'nkf' module Furigana class Reader def reading(text) Mecab.tokenize(text).reduce([]) do |list, token| with_reading = add_reading(token) list += with_reading if with_reading list end end private def k2h(k) return nil if k.nil? NKF.nkf("-h1 -w", k) end def diff_token_surface_form_and_reading(token) Diff::LCS.sdiff(k2h(token[:surface_form]), k2h(token[:reading])) end def add_reading(token) states = { kanji_and_yomi: '!', yomi: '+', kana: '=' } kanji, yomi = 0, 1 list = [] if /\p{Han}/.match(token[:surface_form]) on_kanji = false diff_token_surface_form_and_reading(token).each do |part| case part.action when states[:kanji_and_yomi] list.push ['',''] unless on_kanji list.last[kanji] += part.old_element list.last[yomi] += part.new_element on_kanji = true when states[:yomi] list.last[yomi] += part.new_element when states[:kana] on_kanji = false end end end list end end end