text
stringlengths
10
2.61M
# module Rdf::Owl # class Restriction # include SS::Document # # attr_accessor :in_vocab, :in_class # attr_accessor :in_property_namespace, :in_property_prefix, :in_property_name # # field :_id, type: String, default: ->{ property.try(:name) } # field :property, type: Rdf::Extensions::Reference::Prop # field :datatype, type: Rdf::Extensions::Reference::Class # field :cardinality, type: String # field :comments, type: Rdf::Extensions::LangHash # embedded_in :rdf_class, class_name: "Rdf::Class", inverse_of: :property # # permit_params :in_property_namespace, :in_property_prefix, :in_property_name # permit_params :property, :datatype, :cardinality, :comments # permit_params comments: Rdf::Extensions::LangHash::LANGS # # before_validation :set_property # before_validation :set_id # before_validation :set_datatype # # validates :_id, presence: true, uniqueness: true # validates :property, presence: true # validates :datatype, presence: true # validate :validate_property_and_datatype # # before_save :ensure_prop_exist # # class << self # def search(params) # # criteria = self.where({}) # # return criteria if params.blank? # # # # if params[:name].present? # # # criteria = criteria.search_text params[:name] # # words = params[:name] # # words = words.split(/[\s ]+/).uniq.compact.map { |w| /\Q#{Regexp.escape(w)}\E/i } if words.is_a?(String) # # criteria = criteria.all_in(:name => words) # # end # # # # criteria # self.where({}) # end # end # # def comment # comment = nil # if comments.present? # comment = comments.preferred_value # end # if comment.blank? && (prop = property.prop).present? # comment = prop.comments.preferred_value # end # comment # end # # private # def set_property # return if in_property_name.blank? # self.property ||= "#{in_vocab.uri}#{in_property_name}" # end # # def set_id # set_property # name = property.try(:name) # return if name.blank? # self._id ||= name # end # # def set_datatype # return if datatype.present? # # prop = property.try(:prop) # self.datatype ||= prop.ranges.first if prop.present? && prop.ranges.present? # end # # def validate_property_and_datatype # return if property.blank? # return if datatype.blank? # # prop = property.prop # if prop.present? && prop.ranges.present? # unless prop.ranges.include?(datatype) # errors.add(:property, :already_exists_as, range: prop.ranges.first.uri) # end # end # end # # def ensure_prop_exist # prop_id = self.property.prop_id # return if prop_id.present? # # # create rdf prop if rdf prop is not existed. # prop = Rdf::Prop.vocab(in_vocab).where(name: in_property_name).first # if prop.blank? # prop = Rdf::Prop.create({vocab_id: in_vocab.id, # name: in_property_name, # labels: { ja: in_property_name }, # comments: self.comments}) # end # # copy = {} # self.property.each do |k, v| # copy[k] = v # end # copy[Rdf::Extensions::Reference::Prop::PROP_ID_KEY] = prop.id # self.property = copy # end # end # end
class TimerSerializer < ActiveModel::Serializer attributes :id, :time, :is_on, :start end
require ('minitest/autorun') require ('minitest/rg') require_relative('../guest') require_relative('../library') require_relative('../bar') class TestGuest < Minitest::Test def setup @library = Library.new @library.add_song("ABBA", "Waterloo", "pop", "abba_waterloo.mp3") @library.add_song("Queen", "Bohemian Rhapsody", "rock", "queen_bohemian-rhapsody.mp3") @bar = Bar.new @bar.add_drink("vodka", "Grey Goose", 5.0) @bar.add_drink("vodka", "Smirnoff", 5.0) @guest = Guest.new("Reg Wailer", 5.0, {type: "vodka", brand: "Grey Goose"}) end def test_choose_drink assert_equal(@bar.drinks_menu()[0], @guest.choose_drink(@bar)) end def test_can_afford_drink assert_equal(true, @guest.can_afford_drink?(@bar.drinks_menu()[0])) end def test_buy_drink @guest.buy_drink(@bar.drinks_menu()[0]) assert_equal(1, @guest.bar_tab.length) assert_equal(@bar.drinks_menu()[0], @guest.bar_tab[0]) end def test_tab_total @guest.buy_drink(@bar.drinks_menu()[0]) assert(5.0, @guest.tab_total) end def test_cannot_afford_drink @guest.buy_drink(@bar.drinks_menu()[0]) assert_equal(false, @guest.can_afford_drink?(@bar.drinks_menu()[0])) end def test_library search_result = @library.song_search("genre", "pop") assert_equal(1, search_result.count) assert_equal("ABBA", search_result[0].artist) assert_equal("Waterloo", search_result[0].title) end def test_choose_song song = @guest.choose_song(@library) assert_equal("Waterloo", song.title) @guest.favourite_music[:genre] << "rock" @guest.favourite_music[:artist] << "Queen" @guest.favourite_music[:title] << "Bohemian Rhapsody" song = @guest.choose_song(@library) assert_equal("Bohemian Rhapsody", song.title) end end
require "json" require "csv" def parse_data a = JSON.parse(File.read("a.json")) levels = {} fields = {} a.each do |record| recursion_level = record["recursionLevel"] levels[recursion_level] ||= {} record["result"].each do |result| key = result.keys.first.gsub(/ for \d+/, "") levels[recursion_level][key] = result.values.first[/\d+/].to_i fields[key] = true end end ordered_fields = fields.keys CSV.generate do |csv| csv << ["Run Number", *ordered_fields] levels.each do |level, results| csv << [level, *ordered_fields.map { |field| results[field] }] end end end puts parse_data
require 'keen/version' require 'keen/http' module Keen class Client attr_accessor :project_id, :api_key CONFIG = { :api_host => "api.keen.io", :api_port => 443, :api_sync_http_options => { :use_ssl => true, :verify_mode => OpenSSL::SSL::VERIFY_PEER, :verify_depth => 5, :ca_file => File.expand_path("../../../config/cacert.pem", __FILE__) }, :api_async_http_options => {}, :api_headers => { "Content-Type" => "application/json", "User-Agent" => "keen-gem v#{Keen::VERSION}" } } def initialize(*args) options = args[0] unless options.is_a?(Hash) # deprecated, pass a hash of options instead options = { :project_id => args[0], :api_key => args[1], }.merge(args[2] || {}) end @project_id, @api_key = options.values_at( :project_id, :api_key) end def publish(event_name, properties) check_configuration! begin response = Keen::HTTP::Sync.new( api_host, api_port, api_sync_http_options).post( :path => api_path(event_name), :headers => api_headers_with_auth, :body => MultiJson.encode(properties)) rescue Exception => http_error raise HttpError.new("Couldn't connect to Keen IO: #{http_error.message}", http_error) end process_response(response.code, response.body.chomp) end def publish_async(event_name, properties) check_configuration! deferrable = EventMachine::DefaultDeferrable.new http_client = Keen::HTTP::Async.new(api_host, api_port, api_async_http_options) http = http_client.post({ :path => api_path(event_name), :headers => api_headers_with_auth, :body => MultiJson.encode(properties) }) http.callback { begin response = process_response(http.response_header.status, http.response.chomp) deferrable.succeed(response) rescue Exception => e deferrable.fail(e) end } http.errback { Keen.logger.warn("Couldn't connect to Keen IO: #{http.error}") deferrable.fail(Error.new("Couldn't connect to Keen IO: #{http.error}")) } deferrable end # deprecated def add_event(event_name, properties, options={}) self.publish(event_name, properties, options) end private def process_response(status_code, response_body) body = MultiJson.decode(response_body) case status_code.to_i when 200..201 return body when 400 raise BadRequestError.new(body) when 401 raise AuthenticationError.new(body) when 404 raise NotFoundError.new(body) else raise HttpError.new(body) end end def api_path(collection) "/3.0/projects/#{project_id}/events/#{collection}" end def api_headers_with_auth api_headers.merge("Authorization" => api_key) end def check_configuration! raise ConfigurationError, "Project ID must be set" unless project_id raise ConfigurationError, "API Key must be set" unless api_key end def method_missing(_method, *args, &block) CONFIG[_method.to_sym] || super end end end
class Payrolls::AfpDetailsController < ApplicationController before_filter :authenticate_user!, :only => [:index, :new, :create, :edit, :update ] protect_from_forgery with: :null_session, :only => [:destroy, :delete] def index @afp = Afp.where("status = 1") render layout: false end def show @afp = Afp.find(params[:id]) render layout: false end def new @afp = Afp.new @today = Time.now render layout: false end def create render :new, layout: false end def edit @afp = AfpDetail.find(params[:id]) @today = Time.now @action = 'edit' render layout: false end def update afp = AfpDetail.find(params[:id]) if afp.update_attributes(afp_parameters) flash[:notice] = "Se ha actualizado correctamente los datos." redirect_to :action => :show, :controller => :afps, :id=>afp.afp_id else afp.errors.messages.each do |attribute, error| flash[:error] = attribute " " + flash[:error].to_s + error.to_s + " " end # Load new() @afp = afp render :edit, layout: false end end def destroy afp = Afp.find(params[:id]) render :json => afp end private def afp_parameters params.require(:afp_detail).permit(:contribution_fp, :insurance_premium, :top, :c_variable, :mixed) end end
require 'rails_helper' RSpec.describe 'Invoicing#index', type: :system do before do log_in admin_attributes end it 'basic' do property_create human_ref: 2, account: account_new invoicing_create property_range: '1-200', period: '2013-6-30'..'2013-8-30' visit '/invoicings/' expect(page.title).to eq 'Letting - Invoicings' expect(page).to have_text '1-200' expect(page).to have_text '30/Jun/13' end it 'deletes' do property_create human_ref: 2, account: account_new invoicing_create property_range: '1-200', period: "#{Time.zone.now.year}-6-30".. "#{Time.zone.now.year}-8-30" visit '/invoicings/' expect { click_on 'Delete' }.to change(Invoicing, :count) expect(page.title).to eq 'Letting - Invoicings' expect(page).to \ have_text 'Range 1-200, Period 30/Jun - 30/Aug, deleted!' end end
class UpdateCompanies < ActiveRecord::Migration def change remove_column :companies, :location, :string add_column :companies, :state, :string add_column :companies, :city, :string add_column :companies, :address, :string end end
require "spec_helper" describe Lita::Handlers::CreateTeam, lita_handler: true do describe "create team" do it "creates a new team" do send_command "create testing team" expect(replies.last).to eq("testing team created, add some people to it") end context "team already exists" do it "does not create a new team" do send_command "create testing team" send_command "create testing team" expect(replies.last).to eq("testing team already exists") end end end end
# frozen_string_literal: true class User def initialize(surname:, name:, patronymic: '') @name = name @surname = surname @patronymic = patronymic *@full_name = surname, name, patronymic end def full_name @full_name.join(' ') end attr_reader :name, :surname, :patronymic end
unless Object.const_defined?("ExitError") class ExitError < StandardError; end end class DebuggerOverTCP def self.instance(renew = false) @instance = nil if renew @instance ||= new end def initialize(verbose = false) @verbose = verbose @empty_messages = 0 end def print(str, retries = 1) STDOUT.print(str) if @verbose client.write(str + "\n") str rescue SimpleTCP::UnexpectedWriteError return if retries == 0 puts(str, retries - 1) end def puts(str, retries = 1) STDOUT.puts(str) if @verbose client.write(str + "[_EOL]\n") str rescue SimpleTCP::UnexpectedWriteError return if retries == 0 puts(str, retries - 1) end def gets(retries = 1) # Read from TCP and add any messages to the queue messages = client.read # If would block when blocking, ignore return if messages.nil? # If getting empty messages, send an empty message back - essentially like a # ping just to force the client to sure the connection is connected still. if messages == "" print("") return end messages.split("\n").each do |message| gets_buffer << message if messages.length > 0 end # Pop (FIFO) only one message at a time message = gets_buffer.shift STDOUT.puts(message) if message && @verbose message rescue SimpleTCP::UnexpectedReadError return if retries == 0 gets(retries - 1) end protected def client @client ||= SimpleTCP::Client.new @client.connect("127.0.0.1", 3465) unless @client.connected? @client rescue SimpleTCP::FailedToConnectError STDOUT.puts("Failed to connect to debugger (run `bundle exec mrb-debugger`)") sleep(3) client end private def gets_buffer @gets_buffer ||= [] end end
class LocateUsers < ActiveRecord::Migration def change add_column :users, :county_id, :integer add_column :users, :parish_id, :integer add_column :users, :town_id, :integer end end
class CreateTaggings < ActiveRecord::Migration def up create_table :taggings do |t| t.integer :taggable_id t.string :taggable_type t.integer :tag_id t.timestamps null: false end add_index :taggings, :taggable_id end def down drop_table :taggings end end
class RecipeReport < ApplicationRecord belongs_to :recipe belongs_to :report end
require 'wsdl_mapper/runtime/backend_base' require 'concurrent' require 'faraday' require 'wsdl_mapper/runtime/middlewares/async_message_factory' require 'wsdl_mapper/runtime/middlewares/async_request_factory' require 'wsdl_mapper/runtime/middlewares/async_dispatcher' require 'wsdl_mapper/runtime/middlewares/async_response_factory' require 'wsdl_mapper/runtime/middlewares/async_request_logger' require 'wsdl_mapper/runtime/middlewares/async_response_logger' module WsdlMapper module Runtime # ## Middleware Stack # ### Default Configuration # The default stack is composed of the following middlewares: # ![Diagram](/docs/file/doc/diag/async_backend.png) # 1. `message.factory`: {WsdlMapper::Runtime::Middlewares::AsyncMessageFactory} # 2. `request.factory`: {WsdlMapper::Runtime::Middlewares::AsyncRequestFactory} # 3. `dispatcher`: {WsdlMapper::Runtime::Middlewares::AsyncDispatcher} # 4. `response.factory`: {WsdlMapper::Runtime::Middlewares::AsyncResponseFactory} class AsyncHttpBackend < BackendBase include WsdlMapper::Runtime::Middlewares def initialize(connection: Faraday.new, executor: nil) super() @executor = executor stack.add 'message.factory', AsyncMessageFactory.new stack.add 'request.factory', AsyncRequestFactory.new stack.add 'dispatcher', AsyncDispatcher.new(connection) stack.add 'response.factory', AsyncResponseFactory.new end # Enables request and response logging. Returns self. # @param [Logger] logger Logger instance to use. # @param [Logger::DEBUG, Logger::INFO, Logger::FATAL, Logger::ERROR, Logger::WARN] log_level # @return [AsyncHttpBackend] def enable_logging(logger = Logger.new(STDOUT), log_level: Logger::DEBUG) stack.after 'request.factory', 'request.logger', AsyncRequestLogger.new(logger, log_level: log_level) stack.before 'response.factory', 'response.logger', AsyncResponseLogger.new(logger, log_level: log_level) self end # Disables logging by removing the logging middlewares from the stack. Returns self. # @return [AsyncHttpBackend] def disable_logging stack.remove 'request.logger' stack.remove 'response.logger' self end # Takes an `operation` and arguments, wraps them in a new {Concurrent::Promise}, # passes them to the {#stack} and returns the response promise. # @param [WsdlMapper::Runtime::Operation] operation # @param [Array] args # @return [Concurrent::Promise] The unscheduled response promise. def dispatch(operation, *args) promise = Concurrent::Promise.new(executor: @executor) { args } dispatch_async operation, promise end # Passes a promise to the stack and returns the response promise. # @param [WsdlMapper::Runtime::Operation] operation # @param [Concurrent::Promise] promise A promise for the request arguments. # @return [Concurrent::Promise] The unscheduled response promise. def dispatch_async(operation, promise) stack.execute([operation, promise]).last end end end end
require 'spec_helper' describe 'popular location' do let(:pop_location) {create(:post, :location => "popular location")} context "when there is already 5 posts at a location" do before do 5.times { Post.create(:onid => "testonid", :title => "title", :description => "desc", :location => "popular location", :meeting_time => Time.current, :end_time => (Time.current + 2.hours)) } end it "should have that many posts in the database" do expect(Post.all.count).to eq 5 end context "when creating a new group with the same location", :js => true do before do RubyCAS::Filter.fake("onid1") visit signin_path visit new_post_path fill_in "Title", :with => "post title" fill_in "Description", :with => "post description" fill_in "Location", :with => "popular location" fill_in "Meeting time", :with => Time.now.strftime(I18n.t('time.formats.form')) fill_in "End time", :with => (Time.now + 2.hours).strftime(I18n.t('time.formats.form')) page.execute_script("window.popular_location_manager.location_busy = function(){$('body').addClass('locationbusy')}") end it "should be marked as busy" do click_button "Create Post" expect(page).to have_selector("body.locationbusy") end end end end
module Csv require 'csv' def export(data) CSV.open("#{data.values.first}.csv", 'w') do |csv| csv << data.keys csv << data.values end end def self.provide_info_of_module "CSV test" end end
class WikiReference < ActiveRecord::Base LINKED_PAGE = 'L' WANTED_PAGE = 'W' REDIRECTED_PAGE = 'R' INCLUDED_PAGE = 'I' CATEGORY = 'C' AUTHOR = 'A' FILE = 'F' WANTED_FILE = 'E' belongs_to :page validates_inclusion_of :link_type, :in => [LINKED_PAGE, WANTED_PAGE, REDIRECTED_PAGE, INCLUDED_PAGE, CATEGORY, AUTHOR, FILE, WANTED_FILE] def referenced_name read_attribute(:referenced_name).as_utf8 end def self.link_type(web, page_name) if web.has_page?(page_name) || self.page_that_redirects_for(web, page_name) LINKED_PAGE else WANTED_PAGE end end def self.pages_that_reference(web, page_name) query = 'SELECT name FROM pages JOIN wiki_references ' + 'ON pages.id = wiki_references.page_id ' + 'WHERE wiki_references.referenced_name = ? ' + "AND wiki_references.link_type in ('#{LINKED_PAGE}', '#{WANTED_PAGE}', '#{INCLUDED_PAGE}') " + "AND pages.web_id = '#{web.id}'" names = connection.select_all(sanitize_sql([query, page_name])).map { |row| row['name'] } end def self.pages_that_link_to(web, page_name) query = 'SELECT name FROM pages JOIN wiki_references ' + 'ON pages.id = wiki_references.page_id ' + 'WHERE wiki_references.referenced_name = ? ' + "AND wiki_references.link_type in ('#{LINKED_PAGE}','#{WANTED_PAGE}') " + "AND pages.web_id = '#{web.id}'" names = connection.select_all(sanitize_sql([query, page_name])).map { |row| row['name'] } end def self.pages_that_link_to_file(web, file_name) query = 'SELECT name FROM pages JOIN wiki_references ' + 'ON pages.id = wiki_references.page_id ' + 'WHERE wiki_references.referenced_name = ? ' + "AND wiki_references.link_type in ('#{FILE}','#{WANTED_FILE}') " + "AND pages.web_id = '#{web.id}'" names = connection.select_all(sanitize_sql([query, file_name])).map { |row| row['name'] } end def self.pages_that_include(web, page_name) query = 'SELECT name FROM pages JOIN wiki_references ' + 'ON pages.id = wiki_references.page_id ' + 'WHERE wiki_references.referenced_name = ? ' + "AND wiki_references.link_type = '#{INCLUDED_PAGE}' " + "AND pages.web_id = '#{web.id}'" names = connection.select_all(sanitize_sql([query, page_name])).map { |row| row['name'] } end def self.pages_redirected_to(web, page_name) names = [] redirected_pages = [] page = web.page(page_name) return [] unless page redirected_pages.concat page.redirects redirected_pages.concat Thread.current[:page_redirects][page] if Thread.current[:page_redirects] && Thread.current[:page_redirects][page] redirected_pages.uniq.each { |name| names.concat self.pages_that_reference(web, name) } names.uniq end def self.pages_that_redirect_for(web, page_name) query = 'SELECT name FROM pages JOIN wiki_references ' + 'ON pages.id = wiki_references.page_id ' + 'WHERE wiki_references.referenced_name = ? ' + "AND wiki_references.link_type = '#{REDIRECTED_PAGE}' " + "AND pages.web_id = '#{web.id}'" rows = connection.select_all(sanitize_sql([query, page_name])) rows.collect {|r| r['name'].as_utf8} end def self.page_that_redirects_for(web, page_name) self.pages_that_redirect_for(web, page_name).last end def self.pages_in_category(web, category) query = "SELECT name FROM pages JOIN wiki_references " + "ON pages.id = wiki_references.page_id " + "WHERE wiki_references.referenced_name = ? " + "AND wiki_references.link_type = '#{CATEGORY}' " + "AND pages.web_id = '#{web.id}'" names = connection.select_all(sanitize_sql([query, category])).map { |row| row['name'].as_utf8 } end def self.list_categories(web) query = "SELECT DISTINCT wiki_references.referenced_name " + "FROM wiki_references LEFT OUTER JOIN pages " + "ON wiki_references.page_id = pages.id " + "WHERE wiki_references.link_type = '#{CATEGORY}' " + "AND pages.web_id = '#{web.id}'" connection.select_all(query).map { |row| row['referenced_name'].as_utf8 } end def wiki_word? linked_page? or wanted_page? end def wiki_link? linked_page? or wanted_page? or file? or wanted_file? end def linked_page? link_type == LINKED_PAGE end def redirected_page? link_type == REDIRECTED_PAGE end def wanted_page? link_type == WANTED_PAGE end def included_page? link_type == INCLUDED_PAGE end def file? link_type == FILE end def wanted_file? link_type == WANTED_FILE end def category? link_type == CATEGORY end end
require 'minitest/autorun' require_relative 'test_helper' require_relative '../csv_parser' require_relative '../csv_formatter' class CSVFormatterTest < MiniTest::Unit::TestCase def parsed_data CSVParser.new('./test/test_data/test_transcripts_class1.csv').parse end def test_it_can_return_all_words_in_a_specified_class_dataset assert_equal ["this","is","a","test","some","data","another","test","one","last","one","for", "good","measure"], CSVFormatter.new(parsed_data).all_words end end
class School < ActiveRecord::Base has_many :students end
# Write a method that takes an Array, and returns a new Array with the elements of the original list in reverse order. # Do not modify the original list. # You may not use Array#reverse or Array#reverse!, nor may you use the method you wrote in the previous exercise. # Examples: # reverse([1,2,3,4]) == [4,3,2,1] # => true # reverse(%w(a b e d c)) == %w(c d e b a) # => true # reverse(['abc']) == ['abc'] # => true # reverse([]) == [] # => true # list = [1, 3, 2] # => [1, 3, 2] # new_list = reverse(list) # => [2, 3, 1] # list.object_id != new_list.object_id # => true # list == [1, 3, 2] # => true # new_list == [2, 3, 1] # => true # Question: # Write a method that takes an array and returns a new array with elements of the list in reverse order. dont modify original list # Input vs Output: # Input: array # Output: array reversed (new array) # Explicit vs Implicit Rules: # Explicit: # 1) Do not modify original array # Implicit: # N/A # Algorithm: # reverse method # 1) initialize empty array called 'result' # 2) iterate through 'array' by calling each method # 3) within do..end, invoke prepend method on 'result' # 4) return 'result' def reverse(array) result = [] array.each do |item| result.prepend(item) end result end
module Liquider::MarkupHelper def tokenize(source, mode: :text) Liquider::Scanner.new(Liquider::TextStream.new(source), mode: mode).to_enum end def split_on_keyword(keyword, tokens) keyword = keyword.to_s chunks = tokens.slice_before { |token| token == [:IDENT, keyword] }.to_a [chunks[0]] + chunks[1..-1].map { |chunk| chunk[1..-1] } end def parse_expression(source) Liquider::Parser.new({}, [[:GOTOEXPRESSION, ''], *tokenize(source, mode: :liquid)]).parse end def parse_arguments(source) Liquider::Parser.new({}, [[:GOTOARGLIST, ''], *tokenize(source, mode: :liquid)]).parse end end
class OptionsController < ApplicationController respond_to :json before_action :set_detail before_action :set_option, only:[:destroy] def index @options = @detail.options end def create @option = Option.new(option_params) @detail.options << @option render json: @option end def update if @option.update(detail_params) render :show else render json: @option.errors, status: :unprocessable_entity end end def destroy @option.destroy render json: @option end private def set_detail @detail = Detail.find(params[:detail_id]) end def set_option @option = Option.find(params[:id]) end def option_params params.require(:option).permit(:val) end end
class Ballot < ActiveRecord::Base belongs_to :voter has_many :ticks, dependent: :destroy has_many :vote_options, through: :ticks validates :voter, presence: true validates :phone_number, presence: true attr_accessible :legacy_voter_id, :legacy_tick_ids, :phone_number, :voter_id end
require 'test_helper' class FriendshipTest < ActiveSupport::TestCase # Replace this with your real tests. test "the truth" do assert true end test "should be invalid" do friendship = Friendship.new assert !friendship.valid?, "Friendship shoudn't be created" end test "shouldn't allow nil user" do friendship = new(user:nil) assert !friendship.valid?, ":user shoudn't be nil" end test "shouldn't allow nil friend" do friendship = new(friend:nil) assert !friendship.valid?, ":friend shoudn't be nil" end test "shouldn't allow be friend of himself" do user = User.find_or_create_by_email(:email => "hboaventura@gmail.com", :password => "123456") friendship = user.friendships.new(friend:user) assert !friendship.valid?, "User shoudn't be friend of himself" end test "should create a friendship waiting for authorizing" do user = User.find_or_create_by_email(:email => "hboaventura@gmail.com", :password => "123456") friend = User.find_or_create_by_email(:email => "friendships@gmail.com", :password => "123456") friendship = user.friendships.new(friend:friend) assert friendship.valid?, "friendship should be valid" assert friendship.status == "pending", "friendship should be waiting for acception" end test "should create a friendship and authorize it" do user = User.find_or_create_by_email(:email => "hboaventura@gmail.com", :password => "123456") friend = User.find_or_create_by_email(:email => "friendships@gmail.com", :password => "123456") friendship = user.friendships.new(friend:friend) friendship.status = "accepted" assert friendship.valid?, "friendship should be valid" assert friendship.status == "accepted", "friendship should be accepted" end test "should create a friendship and deny it" do user = User.find_or_create_by_email(:email => "hboaventura@gmail.com", :password => "123456") friend = User.find_or_create_by_email(:email => "friendships@gmail.com", :password => "123456") friendship = user.friendships.new(friend:friend) friendship.status = "denied" assert friendship.valid?, "friendship should be valid" assert friendship.status == "denied", "friendship shouldn't' be accepted" end def new(options={}) Friendship.new({ :user => User.new, :friend => User.new }.merge(options)) end end
require 'rails_helper' require 'spec_helper' RSpec.describe User, type: :model do let(:user){create(:create_user)} describe "Model valid object" do context "Fail" do it "has a invalid factory" do expect(build(:create_user,email: nil).valid?).to eq(false) end it "has a invalid factory" do expect(build(:create_user,first_name: nil).valid?).to eq(false) end it "has a invalid factory" do expect(build(:create_user,last_name: nil).valid?).to eq(false) end it "has a invalid factory" do expect(build(:create_user,email: "r@").valid?).to eq(false) end end context "Success" do it "has a valid factory" do expect(build(:create_user)).to be_valid end end end end
class InitialSchemaForIdeas < ActiveRecord::Migration def self.up create_table :ideas do |t| t.string :title t.text :description t.integer :idea_category_id t.integer :user_id t.integer :points, :default => 0 t.string :stage t.boolean :voting_enabled, :default => true t.timestamps end create_table :idea_categories do |t| t.integer :parent_category_id t.string :display_text, :title t.text :intro, :meta_keywords, :meta_description t.timestamps end create_table :idea_votes do |t| t.belongs_to :idea, :user t.integer :points t.timestamps end create_table :fulltext_rows, :options => 'ENGINE=MyISAM' do |t| t.column :fulltextable_type, :string, :null => false, :limit => 50 t.column :fulltextable_id, :integer, :null => false t.column :value, :text, :null => false, :default => '' t.column :parent_id, :integer end execute "CREATE FULLTEXT INDEX fulltext_index ON fulltext_rows (value)" add_index :fulltext_rows, :parent_id add_index :fulltext_rows, [:fulltextable_type, :fulltextable_id], :unique => true end def self.down drop_table :ideas drop_table :idea_categories drop_table :idea_votes drop_table :fulltext_rows end end
# @param {Integer[]} nums # @return {Integer[]} def single_number(nums) result = [] return result if nums == nil nums.each do |num| result << num if nums.index(num) == nums.rindex(num) end return result end
class CreateJianghuRecorders < ActiveRecord::Migration def change create_table :jianghu_recorders, options: 'ENGINE=INNODB, CHARSET=UTF8' do |t| t.integer :user_id, default: -1 t.integer :scene_id, default: -1 t.integer :item_id, default: -1 t.integer :star, default: 0 t.boolean :is_finish, default: false t.integer :failed_time, default: 0 t.timestamps end end end
require 'mongoid' require_relative 'feed' require_relative 'entry' Mongoid.load!(File.expand_path '../../config/mongoid.yml', __FILE__) class FeedPersistenceService class MongoFeed include Mongoid::Document field :username embeds_many :mongo_entries validates_uniqueness_of :username end class MongoEntry include Mongoid::Document field :author field :link field :pub_date field :content field :title embedded_in :mongo_feed end def create feed mongo_entries = feed.entries.map do |e| MongoEntry.new e.to_hash end MongoFeed.create username: feed.username, mongo_entries: mongo_entries feed end def update feed mongo_entries = feed.entries.map do |e| MongoEntry.new e.to_hash end mf = MongoFeed.find_by username: feed.username mf.mongo_entries = mongo_entries feed end def find feed_id mongo_feed = MongoFeed.find_by username: feed_id Feed.new username: mongo_feed.username, entries: get_entries(mongo_feed) rescue Mongoid::Errors::DocumentNotFound nil end def all MongoFeed.all.map do |mongo_feed| Feed.new username: mongo_feed.username, entries: get_entries(mongo_feed) end end def find_or_create feed_id find(feed_id) or create(Feed.new username: feed_id) end private def get_entries mongo_feed mongo_feed.mongo_entries.map do |me| Entry.new me.as_document.except("_id").symbolize_keys end end end
Then(/^I should be see a "(.*?)" link$/) do |link| page.should have_link(link) end Then(/^I will follow the forum$/) do wait_for_ajax @user.followed_forums.include?(@forum).should eq(true) end Then(/^I will see the forums I follow on my profile$/) do visit user_path(@user) @user.followed_forums.each do |forum| page.should have_link(forum.name, href: forum_path(forum)) end end Then(/^I will see the lastest posts on my profile$/) do @forum.posts.recent do |post| page.should have_content(post.title) end end Given(/^there are (\d+) followers of the "(.*?)" forum$/) do |x, name| @forum = Forum.find_by_name(name) @forum.followers << create_list(:user, x.to_i) end Then(/^I will see the recent followers on the forum$/) do @forum.followers.recent.each do |follower| page.should have_content(follower.full_name) end end
require "stringer/version" require "stringer/strings_file" require "stringer/processor" module Stringer def self.run(locale, options = {}) Stringer::Processor.new(locale, options).run end end
class HappeningsForClubDatatable < TrkDatatables::ActiveRecord def columns { 'happenings.id': { hide: true }, 'happenings.name': {}, 'happenings.start_date': {}, 'venues.name': { title: Venue.model_name.human }, } end def all_items @club = Club.find @view.params[:id] if @club.happenings.present? @club.happenings.includes(:venue).references(:venue).order(:start_date) else @club.secondary_happenings.includes(:venue).references(:venue).order(:start_date) end end def rows(filtered) filtered.map do |happening| link = if @view.request.controller_class.module_parent_name == 'Admin' @view.link_to(happening.name, @view.admin_happening_path(happening)) else @view.link_to(happening.name, @view.happening_path(happening)) end [ happening.id, link, I18n.l(happening.start_date, format: :long_with_week), happening.venue.name, ] end end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) modules_to_load = [ Authlogic::ActsAsAuthentic::SingleAccessToken::Methods::InstanceMethods, Authlogic::ActsAsAuthentic::SingleAccessToken::Methods, Authlogic::ActsAsAuthentic::SessionMaintenance::Methods, Authlogic::ActsAsAuthentic::PersistenceToken::Methods::InstanceMethods, Authlogic::ActsAsAuthentic::PersistenceToken::Methods, Authlogic::ActsAsAuthentic::PerishableToken::Methods::InstanceMethods, Authlogic::ActsAsAuthentic::PerishableToken::Methods, Authlogic::ActsAsAuthentic::Password::Methods::InstanceMethods, Authlogic::ActsAsAuthentic::Password::Methods, Authlogic::ActsAsAuthentic::Password::Callbacks, Authlogic::ActsAsAuthentic::MagicColumns::Methods, Authlogic::ActsAsAuthentic::Login::Methods, Authlogic::ActsAsAuthentic::LoggedInStatus::Methods::InstanceMethods, Authlogic::ActsAsAuthentic::LoggedInStatus::Methods, Authlogic::ActsAsAuthentic::Email::Methods ].reject{ |m| User.included_modules.include? m } User.send :include, *modules_to_load
class CollectionsController < ApplicationController load_and_authorize_resource :through => :current_user, :only => [:index, :new, :edit, :create, :update, :destroy] load_and_authorize_resource :id_param => :collection_id, :through => :current_user, :only => [:append_photos, :remove_photos, :reorder_photo] load_and_authorize_resource :only => [:show] respond_to :html, :json def index respond_with(@collections) end def show respond_to do |format| format.html { @collection } format.json { render json: @collection } end end def create if @collection.save redirect_to collection_url(@collection), :notice => 'Collection was successfully created.' else render :action => "new" end end def update if @collection.update_attributes(params[:collection]) redirect_to @collection, :notice => 'Collection was successfully updated.' else render :action => "edit" end end def destroy @collection.destroy redirect_to collections_url end def append_photos photos = Photo.where(:photostream_id => current_photostream).find(params[:photo_ids]) photos.each do |photo| if not @collection.photos.include?(photo) @collection.photos << photo end end @collection.save respond_to do |format| format.html { redirect_to @collection } format.json { render json: @collection } end end def remove_photos photo_in_collections = PhotoInCollection.find(params[:photo_ids]) photo_in_collections.each do |pc| if @collection.photo_in_collections.include?(pc) @collection.photo_in_collections.delete(pc) end end @collection.save respond_to do |format| format.html { redirect_to @collection } format.json { render json: @collection } end end def reorder_photo photo_in_collection = PhotoInCollection.find(params[:uuid]) photo_in_collection.position = params[:position] photo_in_collection.save! @collection.photo_in_collections.reload @collection.photos.reload respond_to do |format| format.html { redirect_to @collection } format.json { render json: @collection } end end rescue_from CanCan::AccessDenied do |exception| if exception.action == :show and current_user and exception.subject.user != current_user redirect_to root_url, :alert => 'You cannot access this collection' else redirect_to new_user_session_url, :alert => 'You must sign in to access collections' end end end
module SOAP class XSD class Element < Hash def initialize( type ) type.attributes.each { |name, value| self[name.to_sym] = value } type.find_all{ |e| e.class == REXML::Element }.each { |content| case content.name when "simpleType" raise SOAP::LCElementError, "Malformated element `#{type.attributes['name']}'" unless self[:type].nil? self[:type] = :simpleType ############################################################################### warn "xsd:simpleType in xsd:element is not yet supported!" ############################################################################### when "complexType" raise SOAP::LCElementError, "Malformated element `#{type.attributes['name']}'" unless self[:type].nil? self[:type] = :complexType self[:complexType] = SOAP::XSD::ComplexType.new( content ) when "unique" raise SOAP::LCElementError, "Malformated element `#{type.attributes['name']}'" unless self[:key].nil? self[:key] = :unique ############################################################################### warn "xsd:unique in xsd:element is not yet supported!" ############################################################################### when "key" raise SOAP::LCElementError, "Malformated element `#{type.attributes['name']}'" unless self[:key].nil? self[:key] = :key ############################################################################### warn "xsd:unique in xsd:element is not yet supported!" ############################################################################### when "keyref" raise SOAP::LCElementError, "Malformated element `#{type.attributes['name']}'" unless self[:key].nil? self[:key] = :keyref ############################################################################### warn "xsd:unique in xsd:element is not yet supported!" ############################################################################### when "annotation" ############################################################################### warn "xsd:annotation in xsd:complexType (global definition) (global definition) is not yet supported!" ############################################################################### else raise SOAP::LCElementError, "Invalid element `#{content.name}' in xsd:element `#{type.attributes['name']}'" end } end def display( types, args ) r = "" min, max = getOccures( args ) if self[:type].is_a?(String) && SOAP::XSD::ANY_SIMPLE_TYPE.include?( self[:type].nns ) r << SOAP::XSD.displayBuiltinType( self[:name], args, min, max ) else case types[self[:type].nns][:type] when :simpleType if args.keys.include?( self[:name].to_sym ) args[self[:name].to_sym] = [args[self[:name].to_sym]] unless args[self[:name].to_sym].class == Array if args[self[:name].to_sym].size < min or args[self[:name].to_sym].size > max raise SOAP::LCArgumentError, "Wrong number or values for parameter `#{name}'" end args[self[:name].to_sym].each { |v| r << "<#{self[:name]}>" r << "#{v}" ############ CHECK !!! r << "</#{self[:name]}>\n" } elsif min > 0 raise SOAP::LCArgumentError, "Missing parameter `#{name}'" if min > 0 end when :complexType if args.keys.include?( self[:name].to_sym ) if args.keys.include?( self[:name].to_sym ) args[self[:name].to_sym] = [args[self[:name].to_sym]] unless args[self[:name].to_sym].class == Array if args[self[:name].to_sym].size < min or args[self[:name].to_sym].size > max raise SOAP::LCArgumentError, "Wrong number or values for parameter `#{name}'" end args[self[:name].to_sym].each { |v| r << "<#{self[:name]}>" r << types[self[:type].nns][:value].display( types, v ) r << "</#{self[:name]}>\n" } elsif min > 0 raise SOAP::LCArgumentError, "Missing parameter `#{name}'" if min > 0 end else r << "<#{self[:name]}>\n" r << types[self[:type].nns][:value].display( types, args ) r << "</#{self[:name]}>\n" end else raise SOAL::LCWSDLError, "Malformated element `#{self[:name]}'" end end return r end def getOccures( args ) element_min = self[:minOccurs].to_i || 1 element_max = self[:maxOccurs] || "1" if element_max == "unbounded" if args.keys.include?(self[:name].to_sym) if args[self[:name].to_sym].class == Array element_max = args[self[:name].to_sym].size else element_max = 1 end else element_max = 1 end else element_max = element_max.to_i end return( [element_min, element_max] ) end def responseToHash( xml, types ) r = {} if SOAP::XSD::ANY_SIMPLE_TYPE.include?( self[:type].to_s.nns ) xml.each { |e| if e.name == self[:name] r[self[:name]] = SOAP::XSD::Convert.to_ruby( self[:type].to_s, e.text ) end } else case self[:type] when :simpleType # **************************** TODO ************************************ when :complexType # **************************** NEED TO BE VERIFIED ************************************ r = self[:complexType].responseToHash( xml, types ) else xml.each { |e| if e.name == self[:name] case types[self[:type].to_s.nns][:type] when :simpleType if r.keys.include?(self[:name]) unless r[self[:name]].class == Array r[self[:name]] = [r[self[:name]]] end r[self[:name]] << types[self[:type].to_s.nns][:value].responseToHash( e.text, types ) else r[self[:name]] = types[self[:type].to_s.nns][:value].responseToHash( e.text, types ) end else if r.keys.include?(self[:name]) unless r[self[:name]].class == Array r[self[:name]] = [r[self[:name]]] end r[self[:name]] << types[self[:type].to_s.nns][:value].responseToHash( e, types ) else r[self[:name]] = types[self[:type].to_s.nns][:value].responseToHash( e, types ) end end end } end end return r end end end end
require 'test_helper' class ReisControllerTest < ActionDispatch::IntegrationTest setup do @rei = reis(:one) end test "should get index" do get reis_url assert_response :success end test "should get new" do get new_rei_url assert_response :success end test "should create rei" do assert_difference('Rei.count') do post reis_url, params: { rei: { content: @rei.content } } end assert_redirected_to rei_url(Rei.last) end test "should show rei" do get rei_url(@rei) assert_response :success end test "should get edit" do get edit_rei_url(@rei) assert_response :success end test "should update rei" do patch rei_url(@rei), params: { rei: { content: @rei.content } } assert_redirected_to rei_url(@rei) end test "should destroy rei" do assert_difference('Rei.count', -1) do delete rei_url(@rei) end assert_redirected_to reis_url end end
require_relative 'exceptions' require_relative 'validation' class Module attr_accessor :before_validations, :after_validations, :included_mixin, :was_redefined def befores self.before_validations ||= [] end def afters self.after_validations ||= [] end # El included nos avisa cuando un mixin es incluido en la clase (que se pasa por parametro) # Entonces, lo que hacemos es agregarle otro mixin a la clase, con los mismos metodos que el mixin original pero tuneados con los invariants de la clase def included(class_including_me) # Este unless es para que solo redefina los mixins de clases que tienen un after (al menos un invariant) unless class_including_me.afters.empty? mixin_clone = self.clone # Este unless es para que no entrar en un loop: aca adentro estamos incluyendo un mixin, send(:include, mixin_clone) unless class_including_me.included_mixin mixin_clone.define_method_added # Como el mixin original va a seguir estando en la clase, este puede hacer super en cada metodo self.instance_methods.each do |mixin_method| mixin_clone.define_method(mixin_method) do |*args, &block| super(*args, &block) end end # Esto es lo que se usa en el if para evitar el loop class_including_me.included_mixin = true # Aca incluyo el mixin tuneado class_including_me.send(:include, mixin_clone) class_including_me.included_mixin = false end end end def define_method_added # TODO este if no lo esta tomando. de todas formas: podemos evitar redefinir un metodo al pedo, sin este if? # if !self.methods.include?(:method_added) def self.method_added(method_name) unless self.was_redefined #Para evitar un loop self.was_redefined = true #Obtiene el unbound method original_method = instance_method(method_name) redefine_method(original_method) #Para poder seguir agregando metodos luego self.was_redefined = false end end end def redefine_method(method) #Seteo las nuevas validaciones para el ultimo metodo que se agrego set_validations_for_defined_method(self.befores, method.name) set_validations_for_defined_method(self.afters, method.name) self.define_method(method.name) { |*args, &block| #Clono el objeto para no tener el problema que conllevaba poner y sacar los metodos (pudiendo sacar metodos que no queremos) self_clone = self.clone #Seteo los parametros como metodos para que las validaciones puedan usarlos self.class.add_method_args_as_methods(self_clone, method, args) #Ejecuta los befores self_clone.class.validate(self_clone, self_clone.class.befores, method.name) #Ejecuta el metodo en el clone porque podria tener efecto result = method.bind(self_clone).call(*args, &block) #Ejecuta los afters self_clone.class.validate(self_clone, self_clone.class.afters, method.name, result) #Si llego hasta aca es porque paso todas las validaciones => ejecuta el metodo (solo el cachito original) sobre la instancia original method.bind(self).call(*args, &block) } end def set_validations_for_defined_method(validations, method_name) validations.each {|validation| validation.for_method(method_name) } end def add_method_args_as_methods(instance, method, args) #Agrego los parametros del metodo como metodos al objeto method.parameters.map { |(_, param_name)| param_name } .zip(args).each { |(param_name, arg_value)| instance.define_singleton_method(param_name) { arg_value } } end def validate(instance, validations, method_name, method_result = nil) validations.each { |validation| validation.execute_over(instance, method_name, method_result) } end def define_initialize self.define_method(:initialize) do end end def add_validation(validation, where) where.push(validation) define_method_added end def before_and_after_each_call(_before, _after) add_validation(BeforeAfterMethod.new(_before), self.befores) add_validation(BeforeAfterMethod.new(_after), self.afters) end def invariant(&condition) add_validation(InvariantValidation.new(condition), self.afters) define_initialize end def pre(&condition) add_validation(PrePostValidation.new(condition, PreConditionError), self.befores) end def post(&condition) add_validation(PrePostValidation.new(condition, PostConditionError), self.afters) end end
RSpec.describe DX::Api::Project::Source do subject { described_class } describe '#has_folders?' do subject { described_class.new(id: 'project-1234') } context 'when folder is root path: "/"' do it { is_expected.to_not have_folders } end end describe '#has_object_ids?' do subject { described_class.new(id: 'project-1234') } context 'when object ids are not present'do it { is_expected.to_not have_object_ids } end end end
require_relative 'planet' require_relative 'solar_system' # Wave 3 Driver Code def main solar_system = SolarSystem.new('Sun') earth = Planet.new('Earth', 'blue-green', 5.972e24, '149.6 mil', 'Only planet known to support life') solar_system.add_planet(earth) mars = Planet.new('Mars', 'red', 6.39e23, '227.9 mil', 'Second smallest planet in the solar system') solar_system.add_planet(mars) venus = Planet.new('Venus', 'red-brown', 4.867e24, '108.2 mil', 'Second brightest object in the night sky') solar_system.add_planet(venus) options = ["add planet", "planet details", "list planets", "exit"] puts "What would you like to do?" puts "Please choose from the following options:" puts options command = gets.chomp.downcase while options.include? command case command when "add planet" puts solar_system.new_planet when "planet details" puts solar_system.planet_details.summary when "list planets" puts solar_system.list_planets when "exit" exit end puts "What would you like to do next?" command = gets.chomp.downcase end end main # Wave 1 & 2 Driver Code # def main # earth = Planet.new('Earth', 'blue-green', 5.972e24, 1.496e8, 'Only planet known to support life') # puts earth.name # puts earth.color # puts earth.summary # # mars = Planet.new('Mars', 'red', 6.39e23, 227.9, 'Fun fact about Mars') # puts mars.name # puts mars.color # puts mars.summary # # solar_system = SolarSystem.new('Sun') # solar_system.add_planet(earth) # solar_system.add_planet(mars) # list = solar_system.list_planets # puts list # # found_planet = solar_system.find_planet_by_name("Earth") # puts found_planet.summary # # end # # main
require 'scripts/models/base' module Models class Tileset < Base field :filename, type: String, default: '' array :passages, type: Integer array :tile_properties, type: Integer field :cell_w, type: Integer, default: 32 field :cell_h, type: Integer, default: 32 field :columns, type: Integer, default: 16 # Used by the SpritesheetCache # # @return [Array<Object>] [filename, cell_w, cell_h] def spritesheet_id return filename, cell_w, cell_h end end end
class Admin::AuthenticationsController < ApplicationController skip_before_filter :logined, :only => [:index, :login] layout 'admin_application' def index check_session end def login check_session @wrong_data = false @wrong_recaptcha = false until params_empty? params render 'index' return end @user_exist = Admin.where(:name => params[:name], :password => params[:password] ) user_exist? params[:name], @user_exist[0] end def logout reset_session redirect_to :action => :index end def new @admin = Admin.new end def add @admin = Admin.new(params[:admin]) if @admin.save render 'add' else render 'new' end end private def check_session if session[:status] redirect_to '/admin/feeds/' return end if session[:counter_wrong_login] == nil session[:counter_wrong_login] = 0 end end def params_empty? params if params[:name] == nil or params[:name] == "" or params[:password] == "" if params[:name] != nil @wrong_data = true session[:counter_wrong_login]+=1 end return false end return true end def login_user! name session[:counter_wrong_login] = 0 session[:status] = true session[:name] = name redirect_to '/admin/feeds/' end def user_exist? name, user_exist if session[:counter_wrong_login] > 3 and user_exist != nil if verify_recaptcha() login_user! name else @wrong_recaptcha = true @wrong_data = true session[:counter_wrong_login]+=1 render 'index' end else if user_exist != nil login_user! name else @wrong_data = true session[:counter_wrong_login]+=1 render 'index' end end end end
module Leftovers class Users attr_reader :username, :organization, :user_id, :password def initialize(username,organization,user_id = nil, password = nil) @username = username @organization = organization @user_id = user_id @password = password end def create @user_id = Leftovers.orm.create_user(@username,@organization) self end def save Leftovers.orm.update_user(@user_id,@password) self end def has_password?(password) @password == Digest::SHA1.hexdigest(password) end def update_password(password) @password = Digest::SHA1.hexdigest(password) end def create_session Leftovers.orm.create_user_session(@user_id) end end end
require_relative 'google_play/version.rb' require_relative 'google_play/gmail_service.rb' require_relative 'google_play/play_scraper.rb' require_relative 'google_play/log.rb' require 'yaml' module GooglePlay class << self include GooglePlay::Log LOG_FILE = File.expand_path('../../recommendations.log', __FILE__) def run account1, account2, account3 = YAML.load_file('assets/accounts.yml') emails = YAML.load_file(EMAIL_CONFIG_PATH) action_movie_emails = emails['action'] family_movie_emails = emails['family'] # for holding the recommendations data = Hash.new data['recommendations'] = [[],[]] next_round = last_round_in_log(LOG_FILE) + 1 action_movie_emails.zip(family_movie_emails).cycle do |email_pair| email1 = email_pair.first email2 = email_pair.last logger.info 'Fetching new recommendations' play1 = GooglePlay::PlayScraper.new(account1) play2 = GooglePlay::PlayScraper.new(account2) new_recommendations1 = play1.get_movie_recommendations new_recommendations2 = play2.get_movie_recommendations last_recommendations = data['recommendations'] File.open(LOG_FILE, 'a') do |file| file.puts "Round # #{next_round}" file.puts "#{Time.now}" logger.info "Checking variance for account #{account1['login']} against last round" file.puts "Account: #{account1['login']}" acc1_equal_last = collections_equal? last_recommendations.first, new_recommendations1 if acc1_equal_last str = ' Compared to last round: SAME' logger.info str file.puts str else str = ' Compared to last round: DIFFERENT' logger.info str file.puts str end file.puts " Will now send email about #{email1['subject']}" logger.info "Checking variance for account #{account2['login']} against last round" file.puts "Account: #{account2['login']}" acc2_equal_last = collections_equal? last_recommendations.last, new_recommendations2 if acc2_equal_last str = ' Compared to last round: SAME' logger.info str file.puts str else str = ' Compared to last round: DIFFERENT' logger.info str file.puts str end file.puts " Will now send email about #{email2['subject']}" logger.info 'Checking variance across the two accounts in this round' cross_acc_equal_current = collections_equal? new_recommendations1, new_recommendations2 if cross_acc_equal_current str = "#{account1['login']} compared to #{account2['login']} in this round: SAME" logger.info str file.puts str else str = "#{account1['login']} compared to #{account2['login']} in this round: DIFFERENT" logger.info str file.puts str end unless acc1_equal_last && acc2_equal_last && cross_acc_equal_current r1 = "#{account1['login']}: #{new_recommendations1.join(', ')}" r2 = "#{account2['login']}: #{new_recommendations2.join(', ')}" logger.info r1 file.puts r1 logger.info r2 file.puts r2 end logger.info '*' * 81 file.puts '*' * 81 end data['recommendations'] = [new_recommendations1, new_recommendations2] logger.info 'Sending emails' simulate_emails(account1, email1, account2, email2, account3) minutes = 30 logger.info "Sleeping #{minutes} minutes" sleep(60 * minutes) next_round += 1 end end def simulate_emails(account1, email1, account2, email2, account3) action_movie_fan = GmailService.new(account1) family_movie_fan = GmailService.new(account2) supportive_friend = GmailService.new(account3) logger.info 'Sending action emails' action_movie_fan.read_emails action_movie_fan.send(account3['login'], email1['subject'], email1['content']) action_movie_fan.logout logger.info 'Sending family emails' family_movie_fan.read_emails family_movie_fan.send(account3['login'], email2['subject'], email2['content']) family_movie_fan.logout logger.info 'Support friend reads emails' supportive_friend.read_emails logger.info 'Replying action emails' supportive_friend.send(account1['login'], email1['subject'], email1['reply']) logger.info 'Replying family emails' supportive_friend.send(account2['login'], email2['subject'], email2['reply']) supportive_friend.logout end EMAIL_CONFIG_PATH = 'assets/emails.yml' def dry_emails account1, account2, account3 = YAML.load_file('assets/accounts.yml') emails = YAML.load_file(EMAIL_CONFIG_PATH) action_movie_emails = emails['test'] family_movie_emails = emails['test'] action_movie_fan = GmailService.new(account1) family_movie_fan = GmailService.new(account2) supportive_friend = GmailService.new(account2) logger.info 'Sending action emails' action_movie_emails.each do |email| action_movie_fan.send(account3['login'], email['subject'], email['content']) end logger.info 'Sending family emails' family_movie_emails.each do |email| family_movie_fan.send(account3['login'], email['subject'], email['content']) end logger.info 'Support friend reads emails' supportive_friend.read_emails logger.info 'Replying action emails' action_movie_emails.each do |email| supportive_friend.send(account1['login'], email['subject'], email['reply']) end logger.info 'Replying family emails' family_movie_emails.each do |email| supportive_friend.send(account2['login'], email['subject'], email['reply']) end end private def collections_equal?(c1, c2) c1.size == c2.size && c1.lazy.zip(c2).all? { |x, y| x == y } end def last_round_in_log file `tail -n 20 #{file} | grep 'Round #'`.strip.scan(/[0-9]+$/).last.to_i end end end
class Resource < ApplicationRecord has_many :resource_sightings has_many :users, through: :resource_sightings has_many :parks, through: :resource_sightings end
#!/usr/bin/env rspec require 'spec_helper' require 'project_razor/utility' describe ProjectRazor::SliceUtil::Common do class TestClass end before :each do @test = TestClass.new @test.extend(ProjectRazor::SliceUtil::Common) # TODO: Review external dependencies here: @test.extend(ProjectRazor::Utility) end describe "get_web_args" do it "should return value for matching key" do @test.stub(:command_shift){'{"@k1":"v1","@k2":"v2","@k3":"v3"}'} @test.get_web_vars(['k1', 'k2']).should == ['v1','v2'] end it "should return nil element for nonmatching key" do @test.stub(:command_shift){'{"@k1":"v1","@k2":"v2","@k3":"v3"}'} @test.get_web_vars(['k1', 'k4']).should == ['v1', nil] end it "should return nil for invalid JSON" do @test.stub(:command_shift){'\3"}'} @test.get_web_vars(['k1', 'k2']).should == nil end end describe "get_cli_args" do it "should return value for matching key" do @test.stub(:command_array){["template=debian_wheezy", "label=debian", "image_uuid=3RpS0x2KWmITuAsHALa3Ni"]} @test.get_cli_vars(['template', 'label']).should == ['debian_wheezy','debian'] end it "should return nil element for nonmatching key" do @test.stub(:command_array){["template=debian_wheezy", "label=debian", "image_uuid=3RpS0x2KWmITuAsHALa3Ni"]} @test.get_cli_vars(['template', 'foo']).should == ['debian_wheezy', nil] end end describe "validate_arg" do it "should return false for empty values" do [ nil, {}, '', '{}', '{1}', ['', 1], [nil, 1], ['{}', 1] ].each do |val| @test.validate_arg(*[val].flatten).should == false end end it "should return valid value" do @test.validate_arg('foo','bar').should == ['foo', 'bar'] end end end
require 'rails_helper' describe Forums::Post do before(:all) { create(:forums_post) } it { should belong_to(:thread).inverse_of(:posts).counter_cache(true) } it { should belong_to(:created_by).class_name('User') } it { should validate_presence_of(:content) } it { should validate_length_of(:content).is_at_least(10).is_at_most(10_000) } end
class GarbagesController < ApplicationController before_action :set_garbage, only: [:show, :edit, :update_cleaned, :update_reviewed] before_action :index_filter, only: [:index] include EkoChekor::Import[ web_client: 'web_client' ] # GET /garbages def index respond_to do |format| format.html format.json { render json: @garbages.as_json } end end # GET /garbages/1 def show end # GET /garbages/new def new @garbage = Garbage.new end # GET /garbages/1/edit def edit end # POST /garbages def create @garbage = Garbage.new(garbage_params.merge(user_id: current_user.id, status: Garbage::STATUSES[:not_cleaned])) if @garbage.save body = { image_url: @garbage.image.url }.to_json response = JSON.parse(web_client.post(ENV['IMAGE_PROCESSOR_HOST'], :body => body).body) @garbage.points = response["result"] @garbage.save redirect_back(fallback_location: map_path) else render :new end end def update_cleaned @garbage.status = 1 @garbage.cleaner = current_user @garbage.image_cleaned = params[:garbage][:image] @garbage.save! redirect_to :map end def update_reviewed @garbage.status = 2 @garbage.reviewer = current_user @garbage.save! redirect_to :map end # DELETE /garbages/1 def destroy @garbage.destroy redirect_to garbages_url end def map @garbage = Garbage.new render :index end private # Use callbacks to share common setup or constraints between actions. def set_garbage @garbage = Garbage.find(params[:id]) end # Only allow a trusted parameter "white list" through. def garbage_params params.require(:garbage).permit(:description, :image, :status, :points, location_attributes: [:longitude, :latitude]) end def index_filter if params.to_unsafe_h[:filters] @garbages = Garbage.none filters = params.to_unsafe_h[:filters].reduce({}, :merge) if current_user.present? user_id = current_user.id @garbages = @garbages.or(Garbage.filter_reported_by_me(user_id)) if filters['reported_by_me'] @garbages = @garbages.or(Garbage.filter_cleaned_by_me(user_id)) if filters['cleaned_by_me'] @garbages = @garbages.or(Garbage.filter_reviewed_by_me(user_id)) if filters['reviewed_by_me'] end @garbages = @garbages.or(Garbage.filter_for_cleaning) if filters['for_cleaning'] @garbages = @garbages.or(Garbage.filter_for_reviewing) if filters['for_reviewing'] @garbages = @garbages.or(Garbage.filter_finished) if filters['filter_finished'] else @garbages = Garbage.all end end end
require File.dirname(__FILE__) + '/../../test_helper' class Qa::HomeControllerTest < ActionController::TestCase test "index should get answers home" do get :index assert_template 'qa/home/index' assert_equal [], assigns(:featured_questions) end test "should use the qa_home layout" do get :index assert_equal "layouts/qa_home", @response.layout end test "should set title" do get :index assert_equal "Answers", assigns(:title) end test "should set breadcrumbs for index" do get :index assert_select '#bread_crumb span', :text => 'Answers Home' end test "should set breadcrumbs for new questions" do get :new_questions assert_select '#bread_crumb span', :text => 'New Questions' end test "should set breadcrumbs for unanswered questions" do get :unanswered_questions assert_select '#bread_crumb span', :text => 'Open Questions' end test "should set breadcrumbs for answered questions" do get :answered_questions assert_select '#bread_crumb span', :text => 'Answered Questions' end test "index should set the featured questions" do questions = [] 3.times do |index| questions << Factory(:qa_question, :title => "Question #{index}") end cobrand = Cobrand.find_by_short_name('viewpoints') cobrand_params = cobrand.params.find_or_create_by_key('featured_questions') cobrand_params.update_attributes! :value => questions.collect(&:id) * ',' CobrandParamCache.instance.reload_cache get :index assert_equal questions, assigns(:featured_questions) cobrand_params.delete CobrandParamCache.instance.reload_cache end test "index should set uniq featured questions" do question_one = Factory(:qa_question, :title => "Question one") question_two = Factory(:qa_question, :title => "Question two") cobrand = Cobrand.find_by_short_name('viewpoints') cobrand_params = cobrand.params.find_or_create_by_key('featured_questions') cobrand_params.update_attributes! :value => [question_one.id, question_one.id, question_two.id] * ',' CobrandParamCache.instance.reload_cache get :index assert_equal [question_one, question_two], assigns(:featured_questions) cobrand_params.delete CobrandParamCache.instance.reload_cache end test "should load popular categories and assign it" do popular_categories = Category.all(:limit => 2) CategoryStat.expects(:most_popular_categories).returns(popular_categories) get :index assert_equal popular_categories, assigns(:popular_categories) end test "should set the owner of the page to root category" do get :index assert_equal Category.find_root, assigns(:owner) end test "should set the owner of the page to root category for new_questions" do get :new_questions assert_equal Category.find_root, assigns(:owner) end test "should set the owner of the page to root category for unanswered_questions" do get :unanswered_questions assert_equal Category.find_root, assigns(:owner) end test "should set the owner of the page to root category for answered_questions" do get :answered_questions assert_equal Category.find_root, assigns(:owner) end test "should create a question object for the home page for new_questions" do get :new_questions assert_not_nil assigns(:question) end test "should create a question object for the home page for unanswered_questions" do get :unanswered_questions assert_not_nil assigns(:question) end test "should create a question object for the home page for answered_questions" do get :answered_questions assert_not_nil assigns(:question) end test "pagination" do (1..5).each do |i| question = Factory(:activated_qa_question, :title => "question #{i}", :created_at => (10 - i).days.ago); 2.times {Factory(:activated_qa_answer, :question => question)} end get :answered_questions, :per_page => 2, :page => 2, :order => 'most_recent' assert_equal 5, assigns(:questions).total_entries assert_equal ['question 3', 'question 2'], assigns(:questions).map(&:title) end test "routes" do assert_routing({:method => :get, :path => '/ask'}, {:controller => 'qa/home', :action => 'index'}) assert_routing({:method => :get, :path => '/new-questions'}, {:controller => 'qa/home', :action => 'new_questions'}) assert_routing({:method => :get, :path => '/unanswered-questions'}, {:controller => 'qa/home', :action => 'unanswered_questions'}) assert_routing({:method => :get, :path => '/answered-questions'}, {:controller => 'qa/home', :action => 'answered_questions'}) end test "should set most popular questions" do popular_question_period = 30 App.stub!(:answers_module).returns({"homepage" => {"popular_questions_count" => 4, "popular_question_period" => popular_question_period}}) questions = (1..5).map {|i| Factory(:qa_question, :visits => i)} Factory(:qa_question, :created_at => (popular_question_period + 1).days.ago, :visits => 3) questions_based_on_visit = questions.reverse get :index assert_equal questions_based_on_visit[0..3], assigns(:popular_questions) end test "should set right rail content for all actions" do filter_methods = @controller.class.filter_chain.map {|filter| filter.method} assert filter_methods.include?(:load_right_rail_content) end test "right rails should have popular categories and featured contributers" do @controller.send(:load_right_rail_content) assert @controller.instance_variable_get(:@popular_categories) assert @controller.instance_variable_get(:@featured_contributors) end context "google analytics" do before do @controller = Qa::HomeController.new end test "should be set for Answers home" do get :index assert_equal '/pt-Q-and-A/logged-out/Answers/Questions-Home/Answers-Home',assigns(:web_analytics).google_analytics_url end test "should be set for New questions" do get :new_questions assert_equal '/pt-Q-and-A/logged-out/Answers/Questions-Home/New-Questions',assigns(:web_analytics).google_analytics_url end test "should be set for Open questions" do get :unanswered_questions assert_equal '/pt-Q-and-A/logged-out/Answers/Questions-Home/Open-Questions',assigns(:web_analytics).google_analytics_url end test "should be set for Answered questions" do get :answered_questions assert_equal '/pt-Q-and-A/logged-out/Answers/Questions-Home/Answered-Questions',assigns(:web_analytics).google_analytics_url end test "should include page numbers" do 10.times {Factory(:qa_question)} get :new_questions, :page => 5, :per_page => 2 assert_equal '/pt-Q-and-A/logged-out/Answers/Questions-Home/New-Questions/Page-5',assigns(:web_analytics).google_analytics_url get :unanswered_questions, :page => 5, :per_page => 2 assert_equal '/pt-Q-and-A/logged-out/Answers/Questions-Home/Open-Questions/Page-5',assigns(:web_analytics).google_analytics_url Qa::Question.all.each {|question| Factory(:qa_answer, :question => question)} get :answered_questions, :page => 5, :per_page => 2 assert_equal '/pt-Q-and-A/logged-out/Answers/Questions-Home/Answered-Questions/Page-5',assigns(:web_analytics).google_analytics_url end end end
require File.dirname(__FILE__)+'/spec_helper' describe Cosy::Pitch do it 'should generate text representations from numeric values' do Pitch.new(60).to_s.should == 'C4' Pitch.new(61).to_s.should == 'C#4' end it 'should have equivalent midi and pitchclass/accidental/octave represenations' do Pitch.new(63).should == Pitch.new(PITCH_CLASS['D'], 1, 4) end end describe Cosy::Interval do it 'should be equivalent to the number of semitones in the interval' do %w{p1 m2 M2 m3 M3 P4 aug4 P5 m6 M6 m7 M7}.each_with_index do |str,semitones| semitones.should == Interval.new(str) end end it 'should support alternate names for the intervals' do %w{dim2 aug1 dim3 aug2 dim4 aug3 dim5 dim6 aug5 dim7 aug6 dim8}.each_with_index do |str,semitones| semitones.should == Interval.new(str) end end it 'should support negative (descending) intervals' do %w{-p1 -m2 -M2 -m3 -M3 -P4 -aug4 -P5 -m6 -M6 -m7 -M7}.each_with_index do |str,index| semitones = -index semitones.should == Interval.new(str) end end it 'should support intervals over an octave' do %w{p8 m9 M9 m10 M10 P11 aug11 P12 m13 M13 m14 M14}.each_with_index do |str,semitones| semitones.should == Interval.new(str) end end it 'should result in a pitch when added to a pitch' do Pitch.new(63).should == Pitch.new(PITCH_CLASS['C'], 0, 4) + Interval.new('m3') end end
class FixReadToBook < ActiveRecord::Migration def up remove_column :books, :read end end
require 'rails_helper' describe 'users/index' do let(:users) { build_stubbed_list(:user, 3) } before do users.first.badge_name = 'Admin' end it 'shows all users' do assign(:users, users.paginate(page: 1)) render users.each do |user| expect(rendered).to include(user.name) end end end
class SharesController < ApplicationController before_filter :authorize_user, only: [:create] def create @share = Share.where("note_id = '#{params[:note_id]}'").first if @share redirect_to "/s/#{@share.uuid}" else @note = Note.find(params[:note_id]) @share = Share.new(note: @note) if @share.save redirect_to "/s/#{@share.uuid}" else redirect_to @note, error: 'There was an error sharing your note' end end end def show @share = Share.where("uuid = '#{params[:uuid]}'").first @note = @share.note render 'notes/plain', :layout => false end end
require 'forwardable' require 'socket' require 'openssl' require 'json' require 'adck/version' require 'multi_json' module ADCK @host = 'gateway.sandbox.push.apple.com' @port = 2195 # openssl pkcs12 -in mycert.p12 -out client-cert.pem -nodes -clcerts @pem = nil # this should be the path of the pem file not the contentes @pass = nil class << self attr_accessor :host, :pem, :port, :pass def send_notification token, message=nil if token.is_a?(Notification) n = token else n = Notification.new(token,message) end send_notifications([n]) end def send_notifications(notifications) Connection.new.open do |sock,ssl| notifications.each do |n| ssl.write(n.packaged_notification) end end end def feedback apns_feedback = [] Connection.feedback.open do |sock, ssl| while line = sock.gets # Read lines from the socket line.strip! f = line.unpack('N1n1H140') apns_feedback << [Time.at(f[0]), f[2]] end end apns_feedback end end end def ADCK val, msg=nil if val.is_a?(Array) ADCK.send_notifications(val) elsif val.is_a?(ADCK::Notification) ADCK.send_notifications([val]) else ADCK.send_notification(val,msg) end end require 'adck/notification' require 'adck/message' require 'adck/connection'
class CreateDomainNames < ActiveRecord::Migration def up create_table :domain_names do |t| t.string :value, null: false t.integer :organization_id end add_index(:domain_names, :organization_id) end def down drop_table :domain_names end end
class AddMediaToNoot < ActiveRecord::Migration[5.1] def create add_column :noots, :media, :float end end
class UserMailer < ActionMailer::Base default from: "ironshop@no-reply.com" def price_watch_email(user, watches) @user = user @watches = watches mail(to: @user.email, subject: 'Price Watch') end end
$:.push File.expand_path("../lib", __FILE__) # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "spree_blogging_spree" s.version = '0.2.1' s.authors = ["Antipin Konstantin", "Jay Mendoza", "Alexander Balashov"] s.email = ["nick@entropi.co"] s.homepage = "http://github.com/nwwatson/prosely" s.summary = 'BloggingSpree: A Spree blogging solution (Updated to Spree 0.30 and Rails 3)' s.description = "Small Rails 3.1 blogging mountable engine." s.files = Dir["{app,config,db,lib}/**/*"] + ["LICENSE", "Rakefile", "README.markdown"] s.add_dependency('spree_core', '>= 0.30.0') s.add_dependency('is_taggable') end
require 'spec_helper' describe WebhookService do before do @account = FactoryGirl.create(:account) end context "initialize" do it "should set the @request instance variable" do request = ActionController::TestRequest.new webhook_service = WebhookService.new(request, @account) webhook_service.request.should eq(request) webhook_service.account.should eq(@account) end end context "verify_webhook" do it "should return true if test header is set correctly" do request = ActionController::TestRequest.new request.env["HTTP_X_SHOPIFY_TEST"] = true webhook_service = WebhookService.new(request, @account) webhook_service.verify_webhook.should be_true request = ActionController::TestRequest.new request.env["HTTP_X_SHOPIFY_TEST"] = "true" webhook_service = WebhookService.new(request, @account) webhook_service.verify_webhook.should be_true end it "should NOT return true if test header is set incorrectly" do request = ActionController::TestRequest.new request.env["HTTP_X_SHOPIFY_TEST"] = "foo" webhook_service = WebhookService.new(request, @account) webhook_service.verify_webhook.should_not be_true end it "should return false if the hmac header isn't present" do request = ActionController::TestRequest.new request.env["HTTP_X_SHOPIFY_HMAC_SHA512"] = "1234" webhook_service = WebhookService.new(request, @account) webhook_service.verify_webhook.should be_false end it "should return true if the data verifies" do # Create a new digest digest = OpenSSL::Digest::Digest.new('sha256') # Encode our test data test_hmac = Base64.encode64(OpenSSL::HMAC.digest(digest, SHOPIFY_SHARED_SECRET, "this is test data {'order':'1234'}")).strip request = ActionController::TestRequest.new request.env["HTTP_X_SHOPIFY_HMAC_SHA256"] = test_hmac request.env["RAW_POST_DATA"] = "this is test data {'order':'1234'}" webhook_service = WebhookService.new(request, @account) webhook_service.verify_webhook.should be_true end it "should return false if the data does NOT verify" do # Create a new digest digest = OpenSSL::Digest::Digest.new('sha256') # Encode our test data test_hmac = Base64.encode64(OpenSSL::HMAC.digest(digest, SHOPIFY_SHARED_SECRET, "this is NOT test data {'order':'1234'}")).strip request = ActionController::TestRequest.new request.env["HTTP_X_SHOPIFY_HMAC_SHA256"] = test_hmac request.env["RAW_POST_DATA"] = "this is test data {'order':'1234'}" webhook_service = WebhookService.new(request, @account) webhook_service.verify_webhook.should be_false end end end
lib = File.expand_path("../lib", __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require "deathnote/version" Gem::Specification.new do |spec| spec.name = "deathnote" spec.version = Deathnote::VERSION spec.authors = ["Shia"] spec.email = ["rise.shia@gmail.com"] spec.summary = %q{logging unused methods in execution.} spec.description = %q{Deathnote will log all methods in the project, which methods wasn't called in exection.} spec.homepage = "https://github.com/riseshia/deathnote" spec.license = "MIT" # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host' # to allow pushing to a single host or delete this section to allow pushing to any host. if spec.respond_to?(:metadata) spec.metadata["allowed_push_host"] = "TODO: Set to 'http://mygemserver.com'" else raise "RubyGems 2.0 or newer is required to protect against " \ "public gem pushes." end spec.files = `git ls-files -z`.split("\x0").reject do |f| f.match(%r{^(test|spec|features)/}) end spec.bindir = "exe" spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.16" spec.add_development_dependency "rake", "~> 10.0" spec.add_development_dependency "rspec", "~> 3.0" spec.add_development_dependency "benchmark-ips", "~> 2.7.2" spec.add_development_dependency "okuribito", "~> 0.2.3" spec.add_dependency "activesupport", ">= 4.0" spec.add_dependency "ruby_parser", "~> 3.11.0" spec.add_dependency "sexp_processor", "~> 4.10.1" end
# # Copyright 2016-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'spec_helper' describe PoiseArchive::Resources::PoiseArchive do context 'an absolute path' do context 'an implicit destination' do recipe do poise_archive '/tmp/myapp.tar' end it { is_expected.to unpack_poise_archive('/tmp/myapp.tar').with(absolute_path: '/tmp/myapp.tar', destination: '/tmp/myapp') } end # /context an implicit destination context 'an explicit destination' do recipe do poise_archive '/tmp/myapp.tar' do destination '/opt/myapp' end end it { is_expected.to unpack_poise_archive('/tmp/myapp.tar').with(absolute_path: '/tmp/myapp.tar', destination: '/opt/myapp') } end # /context an explicit destination end # /context an absolute path context 'a relative path' do # Backup and restore the cache path. around do |ex| begin old_cache_path = Chef::Config[:file_cache_path] ex.run ensure Chef::Config[:file_cache_path] = old_cache_path end end context 'an implicit destination' do recipe do Chef::Config[:file_cache_path] = '/var/chef/cache' poise_archive 'myapp.tar' end it { is_expected.to unpack_poise_archive('myapp.tar').with(absolute_path: '/var/chef/cache/myapp.tar', destination: '/var/chef/cache/myapp') } end # /context an implicit destination context 'an explicit destination' do recipe do Chef::Config[:file_cache_path] = '/var/chef/cache' poise_archive 'myapp.tar' do destination '/opt/myapp' end end it { is_expected.to unpack_poise_archive('myapp.tar').with(absolute_path: '/var/chef/cache/myapp.tar', destination: '/opt/myapp') } end # /context an explicit destination end # /context a relative path context 'with .tar.gz' do recipe do poise_archive '/tmp/myapp.tar.gz' end it { is_expected.to unpack_poise_archive('/tmp/myapp.tar.gz').with(absolute_path: '/tmp/myapp.tar.gz', destination: '/tmp/myapp') } end # /context with .tar.gz context 'with .tgz' do recipe do poise_archive '/tmp/myapp.tgz' end it { is_expected.to unpack_poise_archive('/tmp/myapp.tgz').with(absolute_path: '/tmp/myapp.tgz', destination: '/tmp/myapp') } end # /context with .tgz context 'with .tar.bz2' do recipe do poise_archive '/tmp/myapp.tar.bz2' end it { is_expected.to unpack_poise_archive('/tmp/myapp.tar.bz2').with(absolute_path: '/tmp/myapp.tar.bz2', destination: '/tmp/myapp') } end # /context with .tar.bz2 context 'with .tbz2' do recipe do poise_archive '/tmp/myapp.tbz2' end it { is_expected.to unpack_poise_archive('/tmp/myapp.tbz2').with(absolute_path: '/tmp/myapp.tbz2', destination: '/tmp/myapp') } end # /context with .tbz2 context 'with .tar.xz' do recipe do poise_archive '/tmp/myapp.tar.xz' end it { is_expected.to unpack_poise_archive('/tmp/myapp.tar.xz').with(absolute_path: '/tmp/myapp.tar.xz', destination: '/tmp/myapp') } end # /context with .tar.xz context 'with .txz' do recipe do poise_archive '/tmp/myapp.txz' end it { is_expected.to unpack_poise_archive('/tmp/myapp.txz').with(absolute_path: '/tmp/myapp.txz', destination: '/tmp/myapp') } end # /context with .txz context 'with .zip' do recipe do poise_archive '/tmp/myapp.zip' end it { is_expected.to unpack_poise_archive('/tmp/myapp.zip').with(absolute_path: '/tmp/myapp.zip', destination: '/tmp/myapp') } end # /context with .zip context 'with a hidden file' do recipe do poise_archive '/tmp/.myapp.tar' end it { is_expected.to unpack_poise_archive('/tmp/.myapp.tar').with(absolute_path: '/tmp/.myapp.tar', destination: '/tmp/.myapp') } end # /context with a hidden file context 'with a version number' do recipe do poise_archive '/tmp/myapp-1.0.0.tar' end it { is_expected.to unpack_poise_archive('/tmp/myapp-1.0.0.tar').with(absolute_path: '/tmp/myapp-1.0.0.tar', destination: '/tmp/myapp-1.0.0') } end # /context with a version number context 'with a version number and .tar.gz' do recipe do poise_archive '/tmp/myapp-1.0.0.tar.gz' end it { is_expected.to unpack_poise_archive('/tmp/myapp-1.0.0.tar.gz').with(absolute_path: '/tmp/myapp-1.0.0.tar.gz', destination: '/tmp/myapp-1.0.0') } end # /context with a version number and .tar.gz context 'with a URL' do recipe do Chef::Config[:file_cache_path] = '/var/chef/cache' poise_archive 'http://example.com/myapp-1.0.0.zip' do destination '/tmp/myapp' end end it { is_expected.to unpack_poise_archive('http://example.com/myapp-1.0.0.zip').with(path: 'http://example.com/myapp-1.0.0.zip', absolute_path: '/var/chef/cache/aHR0cDovL2V4YW1wbGUuY29tL215YXBwLTEuMC4wLnppcA_myapp-1.0.0.zip', destination: '/tmp/myapp', merged_source_properties: {}) } end # /context with a URL context 'with a URL and name properties' do recipe do Chef::Config[:file_cache_path] = '/var/chef/cache' poise_archive ['http://example.com/myapp-1.0.0.zip', {retries: 0}] do destination '/tmp/myapp' end end it { is_expected.to unpack_poise_archive('http://example.com/myapp-1.0.0.zip, {:retries=>0}').with(path: 'http://example.com/myapp-1.0.0.zip', absolute_path: '/var/chef/cache/aHR0cDovL2V4YW1wbGUuY29tL215YXBwLTEuMC4wLnppcCwgezpyZXRyaWVzPT4wfQ_myapp-1.0.0.zip', destination: '/tmp/myapp', merged_source_properties: {'retries' => 0}) } end # /context with a URL and name properties context 'with a URL and source properties' do recipe do Chef::Config[:file_cache_path] = '/var/chef/cache' poise_archive 'http://example.com/myapp-1.0.0.zip' do destination '/tmp/myapp' source_properties do retries 0 end end end it { is_expected.to unpack_poise_archive('http://example.com/myapp-1.0.0.zip').with(path: 'http://example.com/myapp-1.0.0.zip', absolute_path: '/var/chef/cache/aHR0cDovL2V4YW1wbGUuY29tL215YXBwLTEuMC4wLnppcA_myapp-1.0.0.zip', destination: '/tmp/myapp', merged_source_properties: {'retries' => 0}) } end # /context with a URL and source properties context 'with a URL and both properties' do recipe do Chef::Config[:file_cache_path] = '/var/chef/cache' poise_archive ['http://example.com/myapp-1.0.0.zip', {retries: 100}] do destination '/tmp/myapp' source_properties do retries 0 end end end it { is_expected.to unpack_poise_archive('http://example.com/myapp-1.0.0.zip, {:retries=>100}').with(path: 'http://example.com/myapp-1.0.0.zip', absolute_path: '/var/chef/cache/aHR0cDovL2V4YW1wbGUuY29tL215YXBwLTEuMC4wLnppcCwgezpyZXRyaWVzPT4xMDB9_myapp-1.0.0.zip', destination: '/tmp/myapp', merged_source_properties: {'retries' => 100}) } end # /context with a URL and both properties end
module UploadHelper def file_name(file) if file.present? File.basename(file.url) end end def file_name_with_link(file, path, options = {}) name = file_name(file) if name link_to(name, path, options) end end end
module Fog module Storage class GoogleJSON class Files < Fog::Collection model Fog::Storage::GoogleJSON::File extend Fog::Deprecation deprecate :get_url, :get_https_url attribute :common_prefixes, :aliases => "CommonPrefixes" attribute :delimiter, :aliases => "Delimiter" attribute :directory attribute :page_token, :aliases => %w(pageToken page_token) attribute :max_results, :aliases => ["MaxKeys", "max-keys"] attribute :prefix, :aliases => "Prefix" attribute :next_page_token def all(options = {}) requires :directory parent = service.list_objects(directory.key, attributes.merge(options)) attributes[:next_page_token] = parent.next_page_token data = parent.to_h[:items] || [] load(data) end alias_method :each_file_this_page, :each def each if block_given? subset = dup.all subset.each_file_this_page { |f| yield f } while subset.next_page_token subset = subset.all(:page_token => subset.next_page_token) subset.each_file_this_page { |f| yield f } end end self end def get(key, options = {}, &block) requires :directory data = service.get_object(directory.key, key, **options, &block).to_h new(data) rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 nil end def get_https_url(key, expires, options = {}) requires :directory service.get_object_https_url(directory.key, key, expires, **options) end def metadata(key, options = {}) requires :directory data = service.get_object_metadata(directory.key, key, **options).to_h new(data) rescue ::Google::Apis::ClientError nil end alias_method :head, :metadata def new(opts = {}) requires :directory super({ :directory => directory }.merge(opts)) end end end end end
class Jarvis::Nest < Jarvis::Action def self.reserved_words [:house, :home] end def attempt return unless valid_words? raise Jarvis::Error.not_allowed unless @user&.admin? response = NestCommand.command(parse_cmd) if Rails.env.production? NestCommandWorker.perform_in(10.seconds, :update.to_s) # to_s because Sidekiq complains end return response.presence || "Sent to Nest" end def valid_words? return false if @rx.match_any_words?(@msg, Jarvis.reserved_words - self.class.reserved_words) @rx.match_any_words?(@msg, *home_commands) end def home_commands [ :home, :house, :ac, :heat, :cool, :up, :rooms, :upstairs, :main, :entry, :entryway, ] end def parse_cmd words = @msg.downcase if words.match?(/#{@rx.words(:the, :my)} (\w+)$/) end_word = words[/\w+$/i] words[/#{@rx.words(:the, :my)} (\w+)$/] = "" words = "#{end_word} #{words}" end words = words.gsub(@rx.words(:home, :house), "") words = words.gsub(@rx.words(:ac), "cool") words = words.gsub(@rx.words(:the, :set, :to, :is, :my), "") words.squish end end
class YellingString def initialize(string) @string = string.upcase end def <<(other) @string << other.upcase end def to_s @string end def reverse @string.reverse end end mason = YellingString.new("Mason") mason << " Matthews" puts mason.reverse
#!/usr/bin/env ruby require 'set' module Day06 module Part1 # In the map data, this orbital relationship is written AAA)BBB, which means "BBB is in orbit around AAA". # create a dictionary where the key is a planet # and the value is what it orbits # so it would be BBB => AAA ORBITS = File.readlines("06.txt").map { |l| l.strip.split(")") } .map { |arr| [arr[1], arr[0]]}.to_h @memoize = {} def self.count_orbits(orbits, planet) unless orbits.has_key?(planet) return 0 end if @memoize.has_key?(planet) return @memoize[planet] end return 1 + self.count_orbits(orbits, orbits[planet]) end puts ORBITS.keys.map{ |planet| self.count_orbits(ORBITS, planet) }.reduce(0, :+) end module Part2 def self.min_orbital_transfers(planets, planet, destination, visited) if planet == destination return 0 end if visited.include?(planet) return Float::INFINITY end visited.add(planet) results = [] # At this point we can try to move to any planet we are orbiting # or are being orbited #1. orbiting if planets.has_key?(planet) results << self.min_orbital_transfers(planets, planets[planet], destination, visited) end # 2. find everyone who is orbiting this planet planets.find_all{|_,v|v == planet}.each do |p, _| results << self.min_orbital_transfers(planets, p, destination, visited) end if results.empty? return Float::INFINITY end return results.min + 1 end puts self.min_orbital_transfers(Part1::ORBITS, Part1::ORBITS["YOU"], Part1::ORBITS["SAN"], Set.new) end end
class FelicasController < ApplicationController before_action :set_felica, only: [:show, :edit, :update, :destroy] # GET /felicas # GET /felicas.json def index @mode = params[:mode].presence || "all" @active = params[:activation] @felicas = case @mode when "all" Felica.all.page(params[:page]) when "registered" Felica.active.page(params[:page]) when "unregistered" Felica.not_active.page(params[:page]) end end # GET /felicas/1 # GET /felicas/1.json def show end # POST /felicas # POST /felicas.json def create @felica = Felica.new(felica_params) respond_to do |format| if @felica.save format.html { redirect_to @felica, notice: 'Felica was successfully created.' } format.json { render :show, status: :created, location: @felica } else format.html { render :new } format.json { render json: @felica.errors, status: :unprocessable_entity } end end end # PATCH/PUT /felicas/1 # PATCH/PUT /felicas/1.json def update respond_to do |format| if @felica.update(felica_params) format.html { redirect_to @felica, notice: 'Felica was successfully updated.' } format.json { render :show, status: :ok, location: @felica } else format.html { render :edit } format.json { render json: @felica.errors, status: :unprocessable_entity } end end end # DELETE /felicas/1 # DELETE /felicas/1.json def destroy @felica.destroy respond_to do |format| format.html { redirect_to felicas_url, notice: 'Felica was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_felica @felica = Felica.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def felica_params params.require(:felica).permit(:idm, :activation, :activated_at) end def search_params params.permit(:activation).select { |k, v| v.present? } end end
class EditedSchema < ActiveRecord::Migration[5.2] def change remove_column :users, :commute_area_center add_column :users, :commute_area_address, :string add_column :users, :commute_area_latitude, :float add_column :users, :commute_area_longitude, :float end end
class Transaction include Mongoid::Document field :date, type: Date field :position_taken, type: BigDecimal field :underlying_currency field :exchanged_currency belongs_to :position validates :date, presence: true validates :underlying_currency, length: { minimum: 3, maximum: 5 } validates :exchanged_currency, length: { minimum: 3, maximum: 5 } validates_inclusion_of :exchanged_currency, in: Currency::ACCEPTED_CURRENCIES validates_inclusion_of :underlying_currency, in: Currency::ACCEPTED_CURRENCIES end
Rails.application.routes.draw do root to: 'pairings#new' resources :pairings do resources :foods end resources :wines end
# # Author: Martin Magr <mmagr@redhat.com> # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # # Forked from https://github.com/puppetlabs/puppetlabs-inifile . module Puppet module Util class OpenStackConfig class Section @@SETTING_REGEX = /^(\s*)([^#;\s]|[^#;\s].*?[^\s=])(\s*=[ \t]*)(.*)\s*$/ @@COMMENTED_SETTING_REGEX = /^(\s*)[#;]+(\s*)(.*?[^\s=])(\s*=[ \t]*)(.*)\s*$/ def initialize(name, lines=nil) @name = name @lines = lines.nil? ? [] : lines # parse lines @indentation = nil @settings = {} @lines.each do |line| if match = @@SETTING_REGEX.match(line) indent = match[1].length @indentation = [indent, @indentation || indent].min if @settings.include?(match[2]) if not @settings[match[2]].kind_of?(Array) @settings[match[2]] = [@settings[match[2]]] end @settings[match[2]].push(match[4]) else @settings[match[2]] = match[4] end end end end attr_reader :name, :indentation def settings Marshal.load(Marshal.dump(@settings)) end def lines @lines.clone end def is_global? @name == '' end def is_new_section? @lines.empty? end def setting_names @settings.keys end def add_setting(setting_name, value) @settings[setting_name] = value add_lines(setting_name, value) end def update_setting(setting_name, value) old_value = @settings[setting_name] @settings[setting_name] = value if value.kind_of?(Array) or old_value.kind_of?(Array) # ---- update lines for multi setting ---- old_value = old_value.kind_of?(Array) ? old_value : [old_value] new_value = value.kind_of?(Array) ? value : [value] if useless = old_value - new_value remove_lines(setting_name, useless) end if missing = new_value - old_value add_lines(setting_name, missing) end else # ---- update lines for single setting ---- @lines.each_with_index do |line, index| if match = @@SETTING_REGEX.match(line) if (match[2] == setting_name) @lines[index] = "#{match[1]}#{match[2]}#{match[3]}#{value}\n" end end end end end def remove_setting(setting_name, value=nil) if value.nil? or @settings[setting_name] == value @settings.delete(setting_name) else value.each do |val| @settings[setting_name].delete(val) end end remove_lines(setting_name, value) end private def find_commented_setting(setting_name) @lines.each_with_index do |line, index| if match = @@COMMENTED_SETTING_REGEX.match(line) if match[3] == setting_name return index end end end nil end def find_last_setting(setting_name) result = nil @lines.each_with_index do |line, index| if match = @@SETTING_REGEX.match(line) if match[2] == setting_name result = index end end end result end def remove_lines(setting_name, value=nil) if value.kind_of?(Array) val_arr = value else val_arr = [value] end val_arr.each do |val| @lines.each_with_index do |line, index| if (match = @@SETTING_REGEX.match(line)) if match[2] == setting_name if val.nil? or val_arr.include?(match[4]) @lines.delete_at(index) break end end end end end end def add_lines(setting_name, value) indent_str = ' ' * (indentation || 0) if current = find_last_setting(setting_name) offset = current elsif comment = find_commented_setting(setting_name) offset = comment + 1 else offset = @lines.length end if value.kind_of?(Array) value.each do |val| @lines.insert(offset, "#{indent_str}#{setting_name}=#{val}\n") offset += 1 end else @lines.insert(offset, "#{indent_str}#{setting_name}=#{value}\n") end end end end end end
# prereqs: iterators, hashes, conditional logic # Given a hash with numeric values, return the key for the smallest value def key_for_min_value(name_hash) # code goes here if (name_hash.length == 0) min_value_key = nil else min_value_key = name_hash.first[0] min_value = name_hash.first[1] name_hash.each { |key, value| min_value_key = key if value < min_value } end min_value_key end
require "rails_helper" describe "User logging in" do it "creates a session and loads the catalog", :js do catalog = create(:catalog) user = catalog.user visit root_path first(:link, t("devise.sessions.sign_in")).click fill_in "Email", with: user.email fill_in "Password", with: user.password within "form" do click_on t("devise.sessions.sign_in") end expect(page).to have_link_to_catalog(catalog) expect(page).to have_catalog_date(catalog) expect(page).to have_add_gift_link(catalog) end end
class ArtworksController < ApplicationController skip_before_action :authenticate_user!, only: [:index, :show] def index @catalogue = Catalogue.new if user_signed_in? @catalogue_default = Catalogue.where(user_id:current_user.id, kind: "default_user").first @catalogues_artworks = CatalogueArtwork.where(catalogue_id:@catalogue_default.id) end if artworks_search_params.length != 0 @artworks = Artwork.where(artworks_search_params) else if params[:type] == "selection" @artworks = Artwork.all.sample(8) elsif params[:type] == "trending" @artworks = Artwork.all.sample(8) else @artworks = Artwork.all end end end def new @user = current_user @artwork = @user.artworks.build end def show @catalogues_artworks = CatalogueArtwork.where(artwork_id:params[:id]) @catalogues_artworks.each do |catalogue_artwork| if user_signed_in? if catalogue_artwork.catalogue.user_id == current_user.id @current_user_catalogue_artworks = catalogue_artwork end end end @catalogue = Catalogue.new @artwork = Artwork.find(params[:id]) @user = current_user @review = Review.new end def create @user = current_user @artwork = @user.artworks.new(artwork_params) create_default_artist_profile if @artwork.save @catalogue = Catalogue.where( user: @user , kind: "default_artist" )[0] @catalogue_artwork = CatalogueArtwork.new(artwork_id: @artwork.id,catalogue_id:@catalogue.id ) @catalogue_artwork.save! redirect_to catalogues_path else render :new end end def edit @user = current_user @artwork = Artwork.find(params[:id]) end def update @user = current_user @artwork = Artwork.find(params[:id]) @artwork.update_attributes(artwork_params) redirect_to profile_path(@user) end def destroy @artwork = Artwork.find(params[:id]) @artwork.destroy flash[:notice] = "Artwork deleted! ( Artwork Destroy 1 )" redirect_to catalogues_path end private def create_default_artist_profile if Artist.where( user:current_user).length == 0 artist_name = current_user.first_name + " , " + current_user.last_name @artist = Artist.new(artist_name:artist_name, user_id:current_user.id, presentation:"Write few words to introduce you as an artist.") @artist.save! else @artist = Artist.where(user_id:current_user.id)[0] end return @artist end def artworks_search_params params.permit(:title, :date_of_work, :artwork_picture, :category, :style, :subject, :medium, :dimensions, :place_of_work, :owner , :current_location, :exhibition_history, :condition_of_work, :signature, :bibliography, :reproduction, :public_display , :description ) end def artwork_params params.require(:artwork).permit(:title, :date_of_work, :artwork_picture, :artwork_picture_cache, :category, :style, :subject, :medium, :dimensions, :place_of_work, :owner , :current_location, :exhibition_history, :condition_of_work, :signature, :bibliography, :reproduction, :public_display, :description ) end end
# frozen_string_literal: true module SC::Billing::Stripe class SyncSubscriptionsService def call ::Stripe::Subscription.all.auto_paging_each.each(&method(:create_or_actualize_subscription)) end private def create_or_actualize_subscription(subscription_data) if subscription_exists?(subscription_data.id) actualize_subscription(subscription_data) else create_subscription(subscription_data) end end def subscription_exists?(stripe_id) !::SC::Billing::Stripe::Subscription.where(stripe_id: stripe_id).empty? end def create_subscription(data) ::SC::Billing::Stripe::Webhooks::Customers::Subscriptions::CreateOperation.new.call(data) end def actualize_subscription(data) ::SC::Billing::Stripe::Webhooks::Customers::Subscriptions::UpdateOperation.new.call(data) end end end
require 'rails_helper' RSpec.describe Consumer, type: :model do subject { build :consumer } it 'has a valid factory' do expect(build :consumer).to be_valid end describe 'validations' do it { is_expected.to validate_presence_of(:first_name) } it { is_expected.to validate_presence_of(:last_name) } end describe 'associations' do it { is_expected.to have_one(:user) } end end
# pry(main)> require './lib/player' # # => true # pry(main)> player = Player.new({name: "Luka Modric", position: "midfielder"}) # # => #<Player:0x00007fd8273d21e0...> # pry(main)> player.name # # => "Luka Modric" # pry(main)> player.position # # => "midfielder" require 'minitest/autorun' require 'minitest/pride' require_relative '../lib/player' class PlayerTest < Minitest::Test def test_it_exists player = Player.new({name: "Luka Modric", position: "midfielder"}) assert_instance_of Player, player end def test_it_has_attributes player = Player.new({name: "Luka Modric", position: "midfielder"}) assert_equal "Luka Modric", player.name assert_equal "midfielder", player.position end end
class CreateBillEntries < ActiveRecord::Migration def change create_table :bill_entries, :id => false do |t| t.integer :amount t.integer :bill_id t.integer :article_id t.timestamps end execute "ALTER TABLE bill_entries ADD PRIMARY KEY (bill_id, article_id);" end end
class UserBadge < ActiveRecord::Base validates_presence_of :user_id, :client_id, :badge_id validates_uniqueness_of :user_id, :scope => [:client_id, :badge_id] belongs_to :user belongs_to :client belongs_to :badge def as_json(options={}) # include timestamp? { :badge_id => self.badge_id, :client_id => self.client_id } end def self.top_badges(client_id, start_date, end_date) # gotta be a better way to do this, but oh well ... start_time = Time.zone.parse(start_date.to_s) end_time = Time.zone.parse(end_date.to_s).end_of_day # this comes back as an OrderedHash - a little weird badges = UserBadge.count( :conditions => ["user_badges.client_id = ? AND user_badges.created_at BETWEEN ? AND ?", client_id, start_time, end_time], :group => :badge_id, :order => "count(*) desc") results = [] for badge in badges results << {:badge_id => badge[0], :badge_name => Badge.find(badge[0]).name, :badges => badge[1]} end return results end end
# input: string # output: new string where every uppercase letter is replaced by its lowercase version and lowercase replaced with uppercase (other chars should be unchanged) # cannot use swapcase method # non-alphabetic chars should be unchanged (including spaces) # data structure: array # algo: # set two constants, both should be ranges of capital letters and lowercase letters # separate words into separate chars in an array # validate if the char is included in either of the constants and change case accordingly # use join method to join chars into words UPPERCASE = ('A'..'Z').to_a LOWERCASE = ('a'..'z').to_a def swapcase(string) char_array = string.chars.map do |char| if UPPERCASE.include?(char) char.downcase elsif LOWERCASE.include?(char) char.upcase else char end end char_array.join end # or def swapcase(string) characters = string.chars.map do |char| if char =~ /[a-z]/ char.upcase elsif char =~ /[A-Z]/ char.downcase else char end end characters.join end
# Break Statement =begin Pattern 1: 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 Pattern 2 by modifying PATTERN 1 & using BREAK: 1 2 1 2 1 2 1 2 1 2 =end for r in 1..5 for c in 1..5 print "#{c}" break if c==2 #whenever value of c = 2, then it breaks out of this loop and prints the statment below end print"\n" end
# frozen_string_literal: true require 'rails_helper' RSpec.describe Position, type: :model do it {should have_many(:employment_terms)} it {should have_one(:position_history)} end
class GrantUpdatesController < ApplicationController def new @grant_application = GrantApplication.find(params[:grant_application_id]) @grant_update = GrantUpdate.new end def create @grant_application = GrantApplication.find(params[:grant_application_id]) @user = User.find(@grant_application.user_id) @grant_update = @grant_application.grant_updates.create!(grant_update_params) if @grant_update.save flash[:success] = "Grant Update Submitted" redirect_to @user else flash[:danger] = "Grant Update Failed" redirect_to @user end end private def grant_update_params params.require(:grant_update).permit(:grant_update) end end
# frozen_string_literal: true require 'globalize' require 'globalize-accessors' require 'after_commit_action' module Globalize::Automatic mattr_accessor :asynchronously, :translator module TranslatedExtension extend ActiveSupport::Concern included do class_attribute :automatic_translation_attribute_names, :automatic_translation_field_locales, :automatic_translated_field_locales self.automatic_translation_attribute_names = [] self.automatic_translation_field_locales = Hash.new { [] } self.automatic_translated_field_locales = Hash.new { [] } after_update :update_automatic_translations end class_methods do def automatic_translation_class return @automatic_translation_class if defined?(@automatic_translation_class) if self.const_defined?(:AutomaticTranslation, false) klass = self.const_get(AutomaticTranslation, false) else klass = Class.new(Globalize::Automatic::Translation) self.const_set(:AutomaticTranslation, klass) end foreign_key = name.foreign_key klass.belongs_to :automatic_translated_model, class_name: name, foreign_key: foreign_key, inverse_of: :automatic_translations klass.define_singleton_method(:automatic_translated_model_foreign_key) do foreign_key end @automatic_translation_class = klass end # 翻訳元フィールドと言語 def add_automatic_translation_field_locales!(fields, locales) fields.each do |field| automatic_translation_field_locales[field] = locales end end # 翻訳先フィールドと言語 def add_automatic_translated_field_locales!(fields, locales) fields.each do |field| automatic_translated_field_locales[field] = locales end end # field が locale で自動翻訳元指定されているか def translate_field_automatically?(field, locale) automatic_translation_field_locales[field].include?(locale) end # field が locale で自動翻訳先指定されているか def translated_field_automatically?(field, locale) automatic_translated_field_locales[field].include?(locale) end # 自動翻訳ON/OFF属性名 def automatic_translation_attribute_name_for(attr_name, locale) "#{attr_name}_#{locale.to_s.underscore}_automatically" end public def create_automatic_translation_table!(*fields) automatic_translation_class.create_table!(*fields) end def drop_automatic_translation_table! automatic_translation_class.drop_table! end def add_automatic_translation_fields!(*fields) automatic_translation_class.add_fields!(*fields) end end def automatic_translation_for(locale) automatic_translation_caches[locale] ||= automatic_translations.where(locale: locale). first_or_initialize(default_translation_automatically(locale)) end # from_locale から attribute_names を自動翻訳 # 自動翻訳が対象でない場合なにもしない def run_automatic_translation(from_locale: , attribute_names:) attribute_names.each do |attr_name| # 自動翻訳対象以外 next unless automatic_translation_field_locales[attr_name].include?(from_locale) # 自動翻訳先としては無効化されている next if automatic_translation_for(from_locale)[:"#{attr_name}_automatically"] automatic_translated_field_locales[attr_name].each do |to_locale| next if to_locale == from_locale automatic_translation_for(to_locale).translate(attr_name) end end true end # 自動翻訳元言語 # attr_nameの自動変換が有効なとき # 現在翻訳元として設定されていてかつ自動変換が無効なものの中で # 一番優先度の高い翻訳元localeを返す。 # どの言語も設定されてない場合は一番優先度の高いもの # 自動翻訳元でない場合nil def automatic_translation_locale(attr_name) locales = automatic_translation_field_locales[attr_name] locales.each do |locale| next if send(self.class.automatic_translation_attribute_name_for(attr_name, locale)) return locale unless translation_for(locale)[attr_name].blank? end locales.first end def reload(options = nil) automatic_translation_caches.clear automatic_translation_attribute_names.each { |attr_name| @attributes.reset(attr_name.to_s) } super(options) end def initialize_dup(other) @automatic_translation_caches = nil super(other) other.automatic_translation_attribute_names.each do |attr_name| self.attributes = { attr_name => other.send(attr_name) } end end private def default_translation_automatically(locale) # 自動翻訳元指定されていなくて、 # 自動翻訳先指定されているものを # デフォルトで自動翻訳ONにする # # 自動翻訳元指定されていて # 自動翻訳先指定されているものは # デフォルトで自動翻訳OFFにする  # # 自動翻訳先指定されていないものは対象外 translated_attribute_names.inject({}) do |defaults, attr_name| if self.class.translated_field_automatically?(attr_name, locale) defaults[:"#{attr_name}_automatically"] = !self.class.translate_field_automatically?(attr_name, locale) end defaults end end def automatic_translation_caches @automatic_translation_caches ||= {} end def update_automatic_translations automatic_translation_caches.values.flatten.each(&:save) end end module TranslationExtension extend ActiveSupport::Concern included do include AfterCommitAction unless include?(AfterCommitAction) after_save :after_save end private def after_save if globalized_model changed_attr_names = globalized_model.translated_attribute_names & changes.keys.map(&:to_sym) execute_after_commit do globalized_model.run_automatic_translation(from_locale: locale, attribute_names: changed_attr_names) true end end true end end module_function def setup_automatic_translation!(klass, attr_names, options) automatic_options = validate_options(parse_options(options)) locales = (automatic_options[:from] + automatic_options[:to]).uniq klass.globalize_accessors locales: locales, attributes: attr_names unless klass.include?(Globalize::Automatic::TranslatedExtension) klass.include Globalize::Automatic::TranslatedExtension klass.has_many :automatic_translations, dependent: :destroy, autosave: true, class_name: klass.automatic_translation_class.name, foreign_key: klass.name.foreign_key, inverse_of: :automatic_translated_model automatic_table_name = "#{klass.table_name.singularize}_automatic_translations" klass.automatic_translation_class.table_name = automatic_table_name klass.automatic_translation_class.define_singleton_method(:table_name) { automatic_table_name } end klass.add_automatic_translation_field_locales!(attr_names, automatic_options[:from]) klass.add_automatic_translated_field_locales!(attr_names, automatic_options[:to]) attr_names.each do |attr_name| locales.each do |locale| klass.class_eval(<<"EVAL") def #{klass.automatic_translation_attribute_name_for(attr_name, locale)} automatic_translation_for(#{locale.inspect}).#{attr_name}_automatically end def #{klass.automatic_translation_attribute_name_for(attr_name, locale)}=(automatically) automatic_translation_for(#{locale.inspect}).#{attr_name}_automatically = automatically end self.automatic_translation_attribute_names.push(:#{klass.automatic_translation_attribute_name_for(attr_name, locale)}) EVAL end end unless klass.translation_class.include?(Globalize::Automatic::TranslationExtension) klass.translation_class.include Globalize::Automatic::TranslationExtension end end def parse_options(options) case options when Hash from_locales = normalize_locales(options[:from]) to_locales = normalize_locales(options[:to]) else from_locales = normalize_locales(options) to_locales = I18n.available_locales end {from: from_locales, to: to_locales} end def normalize_locales(locales) [locales].flatten.compact.map(&:to_sym) end def validate_options(options) if options[:from].empty? raise ArgumentError.new('missing :from option') elsif options[:to].empty? raise ArgumentError.new('missing :to option') else options end end end require 'globalize/automatic/translation' require 'globalize/automatic/translation_job' require 'globalize/automatic/translator/easy_translate' Globalize::Automatic.asynchronously = false Globalize::Automatic.translator = Globalize::Automatic::Translator::EasyTranslate.new Globalize::ActiveRecord::ActMacro.module_eval do def translates_with_automatic(*attr_names) translates_without_automatic(*attr_names).tap do options = attr_names.extract_options! automatic_options = options.delete(:automatic) if automatic_options.present? Globalize::Automatic.setup_automatic_translation!(self, attr_names, automatic_options) end end end alias_method_chain :translates, :automatic end
require 'rails_helper' feature "Page Styles" do scenario "'Click To Hide Me' link has error CSS class" do visit '/' expect(page).to have_css("a.error", text: "Click To Hide Me") end scenario "body tag has cool-background CSS class" do visit '/' expect(page).to have_css("body.cool-background") end end
#elfmaker require "sqlite3" require_relative "elfnamer" include Elfnamer #create the database full of elves $db = SQLite3::Database.new("elves.db") #With that database, allow users to modify it. Give them the chance to view elves, add x amount of elves, and remove certain ones create_table_cmd = <<-SQL CREATE TABLE IF NOT EXISTS elves( id INTEGER PRIMARY KEY, name VARCHAR(255), age INT, clan VARCHAR(255), lvl INT ) SQL #Create the table full of elves $db.execute(create_table_cmd) def create_elf(db, age, lvl) name = name_creator puts "I did not break on #{name}" clan = tribe_assigner puts "I did not break on #{clan}" #IF this works I will be sad $db.execute("INSERT INTO elves (name, age, clan, lvl) VALUES ('#{name}', #{age},'#{clan}',#{lvl});") end def remove_elf (name) $db.execute("DELETE FROM elves WHERE name='#{name}';") end def view_elves view = $db.execute("SELECT * FROM elves;") view.each do |id,name, age, clan, lvl| puts "I am #{name} of Clan #{clan}. I am #{age} years of age and #{lvl} level" end end def view_elf(id) db.execute("SELECT * FROM elves WHERE id=#{id};") end start = true until start == false puts "Hello! Welcome to the Elf generator." input = 0 puts "What would you like to do today? Enter 1 to view elves, 2 to remove elves, and 3 to generate more. 9 quits" input = gets.chomp input = input.to_i if input == 1 output = view_elves puts output elsif input == 2 puts "Enter the name of the elf you would like to remove. Warning, will remove all elves of that name." input = gets.chomp remove_elf(input) elsif input == 3 puts "How many elves would you like to add?" input = gets.chomp input = input.to_i counter = 0 while counter != input create_elf($db, 20, 1) counter += 1 end elsif input == 9 start = false else puts "Huh?" end end
module StringSanitize def self.included(klass) klass.extend ClassMethods end module ClassMethods def sanitize_text(args = {}) sanitize_options = {:except => [], :allow_links => [], :basic => [], :strict => false} sanitize_options.update(args) Rails.logger.debug("Santize options for #{self.to_s} : #{sanitize_options}") before_save :sanitize_input class_eval <<-EOV def options #{sanitize_options} end EOV include StringSanitize::InstanceMethods end end module InstanceMethods def sanitize_input allowed_tags = { :basic => Sanitize::Config::BASIC, :restricted => Sanitize::Config::RESTRICTED, :allow_links => { :elements => ['a'], :attributes => { 'a' => ['href'] }, :protocols => { 'a' => { 'href' => ['ftp', 'http', 'https', 'mailto', :relative] } } } } self.changes.each do |change, value| unless options[:except].include?(change.to_sym) if self.column_for_attribute(change).type == :text if options[:allow_links].include?(change.to_sym) self.send("#{change}=", Sanitize.clean(value.last, allowed_tags[:allow_links])) elsif options[:basic].include?(change.to_sym) self.send("#{change}=", Sanitize.clean(value.last, allowed_tags[:basic])) else self.send("#{change}=", Sanitize.clean(value.last, options[:strict] ? {} : allowed_tags[:restricted])) end elsif self.column_for_attribute(change).type == :string self.send("#{change}=", Sanitize.clean(value.last)) end end end end end end ActionDispatch::Callbacks.to_prepare do ActiveRecord::Base.send(:include, StringSanitize) end
# frozen_string_literal: true class SurveyQuestion < ApplicationRecord acts_as_list belongs_to :survey has_many :survey_answers, dependent: :destroy end
class StocksController < ApplicationController def index @q = Stock.ransack(params[:q]) @stocks = @q.result(:distinct => true).includes(:follows, :comments).page(params[:page]).per(10) render("stock_templates/index.html.erb") end def show @comment = Comment.new @follow = Follow.new @stock = Stock.find(params.fetch("id_to_display")) render("stock_templates/show.html.erb") end def new_form @stock = Stock.new render("stock_templates/new_form.html.erb") end def create_row @stock = Stock.new @stock.ticker = params.fetch("ticker") if @stock.valid? @stock.save redirect_back(:fallback_location => "/stocks", :notice => "Stock created successfully.") else render("stock_templates/new_form_with_errors.html.erb") end end def edit_form @stock = Stock.find(params.fetch("prefill_with_id")) render("stock_templates/edit_form.html.erb") end def update_row @stock = Stock.find(params.fetch("id_to_modify")) @stock.ticker = params.fetch("ticker") if @stock.valid? @stock.save redirect_to("/stocks/#{@stock.id}", :notice => "Stock updated successfully.") else render("stock_templates/edit_form_with_errors.html.erb") end end def destroy_row @stock = Stock.find(params.fetch("id_to_remove")) @stock.destroy redirect_to("/stocks", :notice => "Stock deleted successfully.") end end
require 'windows/error' require 'windows/eventlog' require 'windows/security' require 'windows/registry' require 'windows/system_info' require 'windows/library' require 'windows/synchronize' require 'windows/handle' class String # Return the portion of the string up to the first NULL character. This # was added for both speed and convenience. def nstrip self[ /^[^\0]*/ ] end end module Win32 class EventLogError < StandardError; end class EventLog include Windows::Error include Windows::EventLog include Windows::Security include Windows::Registry include Windows::SystemInfo include Windows::Library include Windows::Synchronize include Windows::Handle extend Windows::Error extend Windows::Registry VERSION = '0.4.3' # Aliased read flags FORWARDS_READ = EVENTLOG_FORWARDS_READ BACKWARDS_READ = EVENTLOG_BACKWARDS_READ SEEK_READ = EVENTLOG_SEEK_READ SEQUENTIAL_READ = EVENTLOG_SEQUENTIAL_READ # Aliased event types SUCCESS = EVENTLOG_SUCCESS ERROR = EVENTLOG_ERROR_TYPE WARN = EVENTLOG_WARNING_TYPE INFO = EVENTLOG_INFORMATION_TYPE AUDIT_SUCCESS = EVENTLOG_AUDIT_SUCCESS AUDIT_FAILURE = EVENTLOG_AUDIT_FAILURE # These are not meant for public use BUFFER_SIZE = 1024 * 64 MAX_SIZE = 256 MAX_STRINGS = 16 BASE_KEY = "SYSTEM\\CurrentControlSet\\Services\\EventLog\\" EventLogStruct = Struct.new('EventLogStruct', :record_number, :time_generated, :time_written, :event_id, :event_type, :category, :source, :computer, :user, :string_inserts, :description ) # The name of the event log source. This will typically be # 'Application', 'System' or 'Security', but could also refer to # a custom event log source. # attr_reader :source # The name of the server which the event log is reading from. # attr_reader :server # The name of the file used in the EventLog.open_backup method. This is # set to nil if the file was not opened using the EventLog.open_backup # method. # attr_reader :file # Opens a handle to the new EventLog +source+ on +server+, or the local # machine if no host is specified. Typically, your source will be # 'Application, 'Security' or 'System', although you can specify a # custom log file as well. # # If a custom, registered log file name cannot be found, the event # logging service opens the 'Application' log file. This is the # behavior of the underlying Windows function, not my own doing. # def initialize(source = 'Application', server = nil, file = nil) @source = source || 'Application' # In case of explicit nil @server = server @file = file # Avoid Win32API segfaults raise TypeError unless @source.is_a?(String) raise TypeError unless @server.is_a?(String) if @server function = 'OpenEventLog()' if @file.nil? @handle = OpenEventLog(@server, @source) else @handle = OpenBackupEventLog(@server, @file) function = 'OpenBackupEventLog()' end if @handle == 0 error = "#{function} failed: " + get_last_error raise EventLogError, error end # Ensure the handle is closed at the end of a block if block_given? begin yield self ensure close end end end # Class method aliases class << self alias :open :new end # Nearly identical to EventLog.open, except that the source is a backup # file and not an event source (and there is no default). # def self.open_backup(file, source = 'Application', server = nil) @file = file @source = source @server = server # Avoid Win32API segfaults raise TypeError unless @file.is_a?(String) raise TypeError unless @source.is_a?(String) raise TypeError unless @server.is_a?(String) if @server self.new(source, server, file) end # Adds an event source to the registry. The following are valid keys: # # * source - Source name. Set to "Application" by default # * key_name - Name stored as the registry key # * category_count - Number of supported (custom) categories # * event_message_file - File (dll) that defines events # * category_message_file - File (dll) that defines categories # * supported_types - See the 'event types' constants # # Of these keys, only +key_name+ is mandatory. An ArgumentError is # raised if you attempt to use an invalid key. If +supported_types+ # is not specified then the following value is used: # # EventLog::ERROR | EventLog::WARN | EventLog::INFO # # The +event_message_file+ and +category_message_file+ are typically, # though not necessarily, the same file. See the documentation on .mc files # for more details. # def self.add_event_source(args) raise TypeError unless args.is_a?(Hash) hkey = [0].pack('L') valid_keys = %w/source key_name category_count event_message_file category_message_file supported_types/ key_base = "SYSTEM\\CurrentControlSet\\Services\\EventLog\\" # Default values hash = { 'source' => 'Application', 'supported_types' => ERROR | WARN | INFO } # Validate the keys, and convert symbols and case to lowercase strings. args.each{ |key, val| key = key.to_s.downcase unless valid_keys.include?(key) raise ArgumentError, "invalid key '#{key}'" end hash[key] = val } # The key_name must be specified unless hash['key_name'] raise EventLogError, 'no event_type specified' end key = key_base << hash['source'] << "\\" << hash['key_name'] if RegCreateKey(HKEY_LOCAL_MACHINE, key, hkey) != ERROR_SUCCESS error = 'RegCreateKey() failed: ' + get_last_error raise EventLogError, error end hkey = hkey.unpack('L').first if hash['category_count'] data = [hash['category_count']].pack('L') rv = RegSetValueEx( hkey, 'CategoryCount', 0, REG_DWORD, data, data.size ) if rv != ERROR_SUCCESS error = 'RegSetValueEx() failed: ', get_last_error RegCloseKey(hkey) raise EventLogError, error end end if hash['category_message_file'] data = File.expand_path(hash['category_message_file']) rv = RegSetValueEx( hkey, 'CategoryMessageFile', 0, REG_EXPAND_SZ, data, data.size ) if rv != ERROR_SUCCESS error = 'RegSetValueEx() failed: ', get_last_error RegCloseKey(hkey) raise EventLogError, error end end if hash['event_message_file'] data = File.expand_path(hash['event_message_file']) rv = RegSetValueEx( hkey, 'EventMessageFile', 0, REG_EXPAND_SZ, data, data.size ) if rv != ERROR_SUCCESS error = 'RegSetValueEx() failed: ', get_last_error RegCloseKey(hkey) raise EventLogError, error end end data = [hash['supported_types']].pack('L') rv = RegSetValueEx( hkey, 'TypesSupported', 0, REG_DWORD, data, data.size ) if rv != ERROR_SUCCESS error = 'RegSetValueEx() failed: ', get_last_error RegCloseKey(hkey) raise EventLogError, error end RegCloseKey(hkey) self end # Backs up the event log to +file+. Note that you cannot backup to # a file that already exists or a EventLogError will be raised. # def backup(file) raise TypeError unless file.is_a?(String) unless BackupEventLog(@handle, file) error = 'BackupEventLog() failed: ' + get_last_error raise EventLogError, error end self end # Clears the EventLog. If +backup_file+ is provided, it backs up the # event log to that file first. # def clear(backup_file = nil) raise TypeError unless backup_file.is_a?(String) if backup_file backup_file = 0 unless backup_file unless ClearEventLog(@handle, backup_file) error = 'ClearEventLog() failed: ' + get_last_error raise EventLogError end self end # Closes the EventLog handle. Automatically closed for you if you use # the block form of EventLog.new. # def close CloseEventLog(@handle) end # Indicates whether or not the event log is full. # def full? buf = [0].pack('L') # dwFull needed = [0].pack('L') unless GetEventLogInformation(@handle, 0, buf, buf.size, needed) raise 'GetEventLogInformation() failed: ' + get_last_error end buf[0,4].unpack('L').first != 0 end # Returns the absolute record number of the oldest record. Note that # this is not guaranteed to be 1 because event log records can be # overwritten. # def oldest_record_number rec = [0].pack('L') unless GetOldestEventLogRecord(@handle, rec) error = 'GetOldestEventLogRecord() failed: ' + get_last_error raise EventLogError, error end rec.unpack('L').first end # Returns the total number of records for the given event log. # def total_records total = [0].pack('L') unless GetNumberOfEventLogRecords(@handle, total) error = 'GetNumberOfEventLogRecords() failed: ' error += get_last_error raise EventLogError, error end total.unpack('L').first end # Yields an EventLogStruct every time a record is written to the event # log. Unlike EventLog#tail, this method breaks out of the block after # the event. # # Raises an EventLogError if no block is provided. # def notify_change(&block) unless block_given? raise EventLogError, 'block missing for notify_change()' end # Reopen the handle because the NotifyChangeEventLog() function will # choke after five or six reads otherwise. @handle = OpenEventLog(@server, @source) if @handle == 0 error = "OpenEventLog() failed: " + get_last_error raise EventLogError, error end event = CreateEvent(0, 0, 0, 0) unless NotifyChangeEventLog(@handle, event) error = 'NotifyChangeEventLog() failed: ' + get_last_error raise EventLogError, error end wait_result = WaitForSingleObject(event, INFINITE) if wait_result == WAIT_FAILED error = 'WaitForSingleObject() failed: ' + get_last_error CloseHandle(event) raise EventLogError, error else last = read_last_event block.call(last) end CloseHandle(event) self end # Yields an EventLogStruct every time a record is written to the event # log, once every +frequency+ seconds. Unlike EventLog#notify_change, # this method does not break out of the block after the event. The read # +frequency+ is set to 5 seconds by default. # # Raises an EventLogError if no block is provided. # # The delay between reads is due to the nature of the Windows event log. # It is not really designed to be tailed in the manner of a Unix syslog, # for example, in that not nearly as many events are typically recorded. # It's just not designed to be polled that heavily. # def tail(frequency = 5) unless block_given? raise EventLogError, 'block missing for tail()' end old_total = total_records() flags = FORWARDS_READ | SEEK_READ rec_num = read_last_event.record_number while true new_total = total_records() if new_total != old_total rec_num = oldest_record_number() if full? read(flags, rec_num).each{ |log| yield log } old_total = new_total rec_num = read_last_event.record_number + 1 end sleep frequency end end # EventLog#read(flags=nil, offset=0) # EventLog#read(flags=nil, offset=0){ |log| ... } # # Iterates over each record in the event log, yielding a EventLogStruct # for each record. The offset value is only used when used in # conjunction with the EventLog::SEEK_READ flag. Otherwise, it is # ignored. If no flags are specified, then the default flags are: # # EventLog::SEQUENTIAL_READ | EventLog::FORWARDS_READ # # Note that, if you're performing a SEEK_READ, then the offset must # refer to a record number that actually exists. The default of 0 # may or may not work for your particular event log. # # The EventLogStruct struct contains the following members: # # record_number # Fixnum # time_generated # Time # time_written # Time # event_id # Fixnum # event_type # String # category # String # source # String # computer # String # user # String or nil # description # String or nil # string_inserts # An array of Strings or nil # # If no block is given the method returns an array of EventLogStruct's. # def read(flags = nil, offset = 0) buf = 0.chr * BUFFER_SIZE # 64k buffer size = buf.size read = [0].pack('L') needed = [0].pack('L') array = [] unless flags flags = FORWARDS_READ | SEQUENTIAL_READ end while ReadEventLog(@handle, flags, offset, buf, size, read, needed) || GetLastError() == ERROR_INSUFFICIENT_BUFFER if GetLastError() == ERROR_INSUFFICIENT_BUFFER buf += 0.chr * needed.unpack('L').first ReadEventLog(@handle, flags, offset, buf, size, read, needed) end dwread = read.unpack('L').first while dwread > 0 struct = EventLogStruct.new event_source = buf[56..-1].nstrip computer = buf[56 + event_source.length + 1..-1].nstrip user = get_user(buf) strings, desc = get_description(buf, event_source) struct.source = event_source struct.computer = computer struct.record_number = buf[8,4].unpack('L').first struct.time_generated = Time.at(buf[12,4].unpack('L').first) struct.time_written = Time.at(buf[16,4].unpack('L').first) struct.event_id = buf[20,4].unpack('L').first & 0x0000FFFF struct.event_type = get_event_type(buf[24,2].unpack('S').first) struct.user = user struct.category = buf[28,2].unpack('S').first struct.string_inserts = strings struct.description = desc if block_given? yield struct else array.push(struct) end if flags & EVENTLOG_BACKWARDS_READ > 0 offset = buf[8,4].unpack('L').first - 1 else offset = buf[8,4].unpack('L').first + 1 end length = buf[0,4].unpack('L').first # Length dwread -= length buf = buf[length..-1] end buf = 0.chr * BUFFER_SIZE read = [0].pack('L') end block_given? ? nil : array end # This class method is nearly identical to the EventLog#read instance # method, except that it takes a +source+ and +server+ as the first two # arguments. # def self.read(source='Application', server=nil, flags=nil, offset=0) self.new(source, server){ |log| if block_given? log.read(flags, offset){ |els| yield els } else return log.read(flags, offset) end } end # EventLog#report_event(key => value, ...) # # Writes an event to the event log. The following are valid keys: # # source # Event log source name. Defaults to "Application" # event_id # Event ID (defined in event message file) # category # Event category (defined in category message file) # data # String that is written to the log # event_type # Type of event, e.g. EventLog::ERROR, etc. # # The +event_type+ keyword is the only mandatory keyword. The others are # optional. Although the +source+ defaults to "Application", I # recommend that you create an application specific event source and use # that instead. See the 'EventLog.add_event_source' method for more # details. # # The +event_id+ and +category+ values are defined in the message # file(s) that you created for your application. See the tutorial.txt # file for more details on how to create a message file. # # An ArgumentError is raised if you attempt to use an invalid key. # def report_event(args) raise TypeError unless args.is_a?(Hash) valid_keys = %w/source event_id category data event_type/ num_strings = 0 # Default values hash = { 'source' => @source, 'event_id' => 0, 'category' => 0, 'data' => 0 } # Validate the keys, and convert symbols and case to lowercase strings. args.each{ |key, val| key = key.to_s.downcase unless valid_keys.include?(key) raise ArgumentError, "invalid key '#{key}'" end hash[key] = val } # The event_type must be specified unless hash['event_type'] raise EventLogError, 'no event_type specified' end handle = RegisterEventSource(@server, hash['source']) if handle == 0 error = 'RegisterEventSource() failed: ' + get_last_error raise EventLogError, error end if hash['data'].is_a?(String) data = hash['data'] << 0.chr data = [data].pack('p*') num_strings = 1 else data = 0 num_strings = 0 end bool = ReportEvent( handle, hash['event_type'], hash['category'], hash['event_id'], 0, num_strings, 0, data, 0 ) unless bool error = 'ReportEvent() failed: ' + get_last_error raise EventLogError, error end self end alias :write :report_event private # A private method that reads the last event log record. # def read_last_event(handle=@handle, source=@source, server=@server) buf = 0.chr * BUFFER_SIZE # 64k buffer read = [0].pack('L') needed = [0].pack('L') flags = EVENTLOG_BACKWARDS_READ | EVENTLOG_SEQUENTIAL_READ ReadEventLog(@handle, flags, 0, buf, buf.size, read, needed) event_source = buf[56..-1].nstrip computer = buf[56 + event_source.length + 1..-1].nstrip event_type = get_event_type(buf[24,2].unpack('S').first) user = get_user(buf) desc = get_description(buf, event_source) struct = EventLogStruct.new struct.source = event_source struct.computer = computer struct.record_number = buf[8,4].unpack('L').first struct.time_generated = Time.at(buf[12,4].unpack('L').first) struct.time_written = Time.at(buf[16,4].unpack('L').first) struct.event_id = buf[20,4].unpack('L').first & 0x0000FFFF struct.event_type = event_type struct.user = user struct.category = buf[28,2].unpack('S').first struct.description = desc struct end # Private method that gets the string inserts (Array) and the full # event description (String) based on data from the EVENTLOGRECORD # buffer. # def get_description(rec, event_source) str = rec[rec[36,4].unpack('L').first .. -1] num = rec[26,2].unpack('S').first # NumStrings hkey = [0].pack('L') key = BASE_KEY + "#{@source}\\#{event_source}" buf = 0.chr * 1024 va_list = nil if num == 0 va_list_ptr = 0.chr * 4 else va_list = str.split(0.chr)[0...num] va_list_ptr = va_list.map{ |x| [x + 0.chr].pack('P').unpack('L').first }.pack('L*') end if RegOpenKeyEx(HKEY_LOCAL_MACHINE, key, 0, KEY_READ, hkey) == 0 value = 'EventMessageFile' file = 0.chr * MAX_SIZE hkey = hkey.unpack('L').first size = [file.length].pack('L') if RegQueryValueEx(hkey, value, 0, 0, file, size) == 0 file = file.nstrip exe = 0.chr * MAX_SIZE ExpandEnvironmentStrings(file, exe, exe.size) exe = exe.nstrip exe.split(';').each{ |file| hmodule = LoadLibraryEx(file, 0, LOAD_LIBRARY_AS_DATAFILE) event_id = rec[20,4].unpack('L').first if hmodule != 0 FormatMessage( FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_ARGUMENT_ARRAY, hmodule, event_id, 0, buf, buf.size, va_list_ptr ) FreeLibrary(hmodule) end } end RegCloseKey(hkey) end [va_list, buf.strip] end # Private method that retrieves the user name based on data in the # EVENTLOGRECORD buffer. # def get_user(buf) return nil if buf[40,4].unpack('L').first <= 0 # UserSidLength name = 0.chr * MAX_SIZE name_size = [name.size].pack('L') domain = 0.chr * MAX_SIZE domain_size = [domain.size].pack('L') snu = 0.chr * 4 offset = buf[44,4].unpack('L').first # UserSidOffset val = LookupAccountSid( @server, [buf].pack('P').unpack('L').first + offset, name, name_size, domain, domain_size, snu ) # Return nil if the lookup failed return val ? name.nstrip : nil end # Private method that converts a numeric event type into a human # readable string. # def get_event_type(event) case event when EVENTLOG_ERROR_TYPE 'error' when EVENTLOG_WARNING_TYPE 'warning' when EVENTLOG_INFORMATION_TYPE 'information' when EVENTLOG_AUDIT_SUCCESS 'audit_success' when EVENTLOG_AUDIT_FAILURE 'audit_failure' else nil end end end end
require('minitest/autorun') require_relative('../bus.rb') require_relative('../person.rb') require_relative('../bus_stop.rb') class TestStudents < MiniTest::Test def setup @passenger1 = Person.new("Ivy", 35) @passenger2 = Person.new("Cletus", 47) @passenger3 = Person.new("Little Jimmy", 4) @all_passengers = [@passenger1, @passenger2, @passenger3] @bus_stop = BusStop.new("The Moon", @all_passengers) @bus = Bus.new(1000, "Mars") end def test_bus_stop_getter assert_equal("The Moon", @bus_stop.name) assert_equal([@passenger1, @passenger2, @passenger3], @bus_stop.queue) end end
require 'tmpdir' require 'stringio' module Duct class Runner def initialize(config) @config = config @script, @data = File.read(@config.filename).split(/^__END__$/, 2) @preamble = @data.split(/^@@\s*(.*\S)\s*$/, 2).first end def run copy_embedded_files system "BUNDLE_GEMFILE=#{tempdir}/Gemfile bundle #{@config.command}" update_embedded_files exec "BUNDLE_GEMFILE=#{tempdir}/Gemfile bundle exec ruby #{@config.filename} #{@config.params.join(' ')}; rm -rf #{tempdir}" unless @config.command end private def copy_embedded_files embedded_files.each do |file, contents| IO.write("#{tempdir}/#{file}", contents) end end def update_embedded_files contents = @script.dup contents << "__END__" contents << @preamble Dir.glob("#{tempdir}/*") do |filename| contents << "@@ #{File.basename(filename)}\n" contents << File.read(filename) end IO.write(@config.filename, contents) end def embedded_files @embedded_files ||= {}.tap do |files| file = nil @data.each_line do |line| if line =~ /^@@\s*(.*\S)\s*$/ file = '' files[$1.to_sym] = file elsif file file << line end end end end def tempdir @tempdir ||= Dir.mktmpdir end end end
class AddIndexToStuffsTags < ActiveRecord::Migration def change add_index :stuffs_tags, [:stuff_id, :tag_id], unique: true end end
class Wound < ApplicationRecord belongs_to :person has_many :treatments end
class CompraDetalle < ActiveRecord::Base attr_accessible :compra_id, :producto_proveedor_id, :producto_id, :proveedor_id, :cantidad_solicitada, :precio_compra, :precio_venta, :cantidad_aprobada, :cantidad_proveida scope :ordenado_id, -> {order('id')} belongs_to :compra belongs_to :producto_proveedor belongs_to :proveedor belongs_to :producto has_many :productos_movimientos end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) AdminUser.create!(email: 'admin@example.com', password: 'password', password_confirmation: 'password') categories = [ {name: 'clothing'}, {name: 'hygiene'}, {name: 'essentials'} ] categories.each do |c| Category.create!(c) end items = [ {name: 'shirt', category_id: 1}, {name: 'hat', category_id: 1}, {name: 'pants', category_id: 1}, {name: 'soap', category_id: 2}, {name: 'toothpaste', category_id: 2}, {name: 'toothbrush', category_id: 2}, {name: 'mouthwash', category_id: 2}, {name: 'feminine hygiene', category_id: 2}, {name: 'blanket', category_id: 3}, {name: 'sleeping bags', category_id: 3}, {name: 'cat food', category_id: 3}, {name: 'dog food', category_id: 3} ] items.each do |i| Item.create!(i) end User.create!(name: "Eye Need", email: "test@email.com", phone: "555-1212")
# Basic interface for writing to the guest s3 bucket. # Right now only used for medication pages. # Use ImageUploader.write_image(key, local_filename), where key includes # a folder and identifier (ex. 'medications/1') class ImageUploader @s3_client = nil def self.client if @s3_client.nil? consul_settings = App.settings.consul access_key_id = consul_settings[:aws][:access_key_id] secret_access_key = consul_settings[:aws][:secret_access_key] @s3_client = ::Aws::S3::Client.new(region: 'us-west-1', access_key_id: access_key_id, secret_access_key: secret_access_key) end @s3_client end # Opens a file and writes it to the guest s3 bucket def self.write_image(key, filename) File.open(filename, 'rb') do |file| client.put_object(bucket: App.settings.s3[:bucket], key: key, body: file, acl: 'public-read') end end end
json.array!(@users) do |user| json.extract! user, :id, :name, :email, :cellphone, :english_speaker?, :teacher?, :admin?, :student? json.url user_url(user, format: :json) end
class ApplicationController < ActionController::Base before_action :role_authenticate rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found rescue_from ActiveRecord::RecordInvalid, :with => :record_invalid # SUPER_CONTROLLERS = %w[admin/users admin/products api/v1/products].freeze def role_authenticate if admin_action && !current_user&.admin? if params['controller'].include? 'admin' redirect_to new_user_session_path else render json: {success: false, error: 'You do not have role to do this action'}, status: :unauthorized end end end def admin_action controller = params['controller'].to_s action = params['action'].to_s ((controller.include?('users') || controller.include?('products'))&& !%w[index login].include?(action)) && !(controller == "api/v1/users" && action == 'create') end def order params[:order] || 'created_at' end def limit params[:limit] || 20 end def page params[:page] || 1 end def offset (page - 1) * limit end private def record_not_found render json: {success: false, error: 'Cannot find record'}, status: :bad_request end def record_invalid render json: {success: false, error: 'Bad params'}, status: :bad_request end end
Instaviewer::Application.routes.draw do # The priority is based upon order of creation: # first created -> highest priority. match "auth/callback" => "auths#create" match "auth" => "auths#new", :as => :login resources :photos, :only => [:index, :show] end