text
stringlengths
10
2.61M
FactoryBot.define do factory :book do name { Faker::Book.title } isbn { Faker::Code.isbn } authors { Faker::Book.author } info { Faker::Lorem.paragraph } cover_image do Rack::Test::UploadedFile.new( Rails.root.join('spec', 'support', 'books', 'calculus.jpg'), 'image/jpeg' ) end preview_url { Faker::Internet.url } user { create(:user) } price { Faker::Number.between(0, 3000) } status { Faker::Number.between(0, 3) } view_count { 0 } end end
# frozen_string_literal: true # rubocop:todo all # Copyright (C) 2015-2020 MongoDB Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Mongo module Options # Class for wrapping options that could be sensitive. # When printed, the sensitive values will be redacted. # # @since 2.1.0 class Redacted < BSON::Document # The options whose values will be redacted. # # @since 2.1.0 SENSITIVE_OPTIONS = [ :password, :pwd ].freeze # The replacement string used in place of the value for sensitive keys. # # @since 2.1.0 STRING_REPLACEMENT = '<REDACTED>'.freeze # Get a string representation of the options. # # @return [ String ] The string representation of the options. # # @since 2.1.0 def inspect redacted_string(:inspect) end # Get a string representation of the options. # # @return [ String ] The string representation of the options. # # @since 2.1.0 def to_s redacted_string(:to_s) end # Whether these options contain a given key. # # @example Determine if the options contain a given key. # options.has_key?(:name) # # @param [ String, Symbol ] key The key to check for existence. # # @return [ true, false ] If the options contain the given key. # # @since 2.1.0 def has_key?(key) super(convert_key(key)) end alias_method :key?, :has_key? # Returns a new options object consisting of pairs for which the block returns false. # # @example Get a new options object with pairs for which the block returns false. # new_options = options.reject { |k, v| k == 'database' } # # @yieldparam [ String, Object ] The key as a string and its value. # # @return [ Options::Redacted ] A new options object. # # @since 2.1.0 def reject(&block) new_options = dup new_options.reject!(&block) || new_options end # Only keeps pairs for which the block returns false. # # @example Remove pairs from this object for which the block returns true. # options.reject! { |k, v| k == 'database' } # # @yieldparam [ String, Object ] The key as a string and its value. # # @return [ Options::Redacted, nil ] This object or nil if no changes were made. # # @since 2.1.0 def reject! if block_given? n_keys = keys.size keys.each do |key| delete(key) if yield(key, self[key]) end n_keys == keys.size ? nil : self else to_enum end end # Returns a new options object consisting of pairs for which the block returns true. # # @example Get a new options object with pairs for which the block returns true. # ssl_options = options.select { |k, v| k =~ /ssl/ } # # @yieldparam [ String, Object ] The key as a string and its value. # # @return [ Options::Redacted ] A new options object. # # @since 2.1.0 def select(&block) new_options = dup new_options.select!(&block) || new_options end # Only keeps pairs for which the block returns true. # # @example Remove pairs from this object for which the block does not return true. # options.select! { |k, v| k =~ /ssl/ } # # @yieldparam [ String, Object ] The key as a string and its value. # # @return [ Options::Redacted, nil ] This object or nil if no changes were made. # # @since 2.1.0 def select! if block_given? n_keys = keys.size keys.each do |key| delete(key) unless yield(key, self[key]) end n_keys == keys.size ? nil : self else to_enum end end private def redacted_string(method) '{' + reduce([]) do |list, (k, v)| list << "#{k.send(method)}=>#{redact(k, v, method)}" end.join(', ') + '}' end def redact(k, v, method) return STRING_REPLACEMENT if SENSITIVE_OPTIONS.include?(k.to_sym) v.send(method) end end end end
# ============================================================================== # SETUP # ============================================================================== cmd_prefix = "GEM_HOME=#{status.gem_home} RAILS_ENV=#{node.environment.framework_env}" pid_dir = '/data/ahwaa/shared/tmp/pids' pid_file = 'tmp/pids/resque_worker_QUEUE.pid' # ============================================================================== # CREATE PIDS DIR ONLY IF IT DOES NOT EXIST # ============================================================================== directory pid_dir do owner app[:user] group app[:user] mode 0777 always_run true end execute "Generate babilu js files" do always_run true owner app[:user] path release_path command "#{cmd_prefix} rake babilu:generate" end execute "Copy generated I18n files" do always_run true owner app[:user] path release_path command "cp /data/ahwaa/shared/javascripts/locales.js public/javascripts/locales.js" end execute 'Installing cron jobs' do always_run true owner app[:user] path release_path command "#{cmd_prefix} whenever --load-file cron/schedule.rb -w" end execute "Remove all.js file" do always_run true owner app[:user] path release_path command "rm -f public/javascripts/all.js" end execute 'Generate foreman environment file' do always_run true owner app[:user] path current_path command "/bin/sh -l -c 'echo \"#{cmd_prefix.split(' ').join('\n')}\" > .env'" end execute 'Run foreman to generate upstart services' do always_run true owner app[:user] path current_path command "/bin/sh -l -c 'sudo foreman export upstart /etc/init -a ahwaa -l /data/ahwaa/current/log -u deploy'" end execute 'Stop resque jobs' do always_run true owner app[:user] path current_path command "/bin/sh -l -c 'sudo stop ahwaa'" end execute 'Start resque jobs' do always_run true owner app[:user] path current_path command "/bin/sh -l -c 'sudo start ahwaa'" end # Node server, left in two steps to commit start command # execute 'stop node server' do # always_run true # owner app[:user] # path current_path # command "daemon -n node_server --stop" # end # execute 'start node server' do # always_run true # owner app[:user] # path current_path # command "daemon -n node_server -e 'NODE_ENV=#{node.environment.framework_env}' -- node #{current_path}/chat_server.js" # end # Delayed job is used to send emails in background for subscribers # execute "Start delayed jobs." do # always_run true # owner app[:user] # path release_path # command "#{cmd_prefix} script/delayed_job start" # end
class RemoveUserIdFromEntities < ActiveRecord::Migration def change remove_columns :entities, :user_id end end
class RemoveUnusedFieldsFromStep < ActiveRecord::Migration[5.0] def change remove_columns(:steps, :yaml_template, :operates_on_artifact) end end
Gem::Specification.new do |s| s.name = "golia" s.rubyforge_project = "golia" s.authors = ["DAddYE"] s.email = "d.dagostino@lipsiasoft.com" s.summary = "Dead Links Checker and Speed Analyzer" s.homepage = "http://www.padrinorb.com" s.description = "Golia is an website performance analyzer. Check speed and dead links." s.default_executable = "golia" s.version = "1.3.2" s.date = Time.now.strftime("%Y-%m-%d") s.extra_rdoc_files = Dir["*.rdoc"] s.files = `git ls-files`.split("\n") s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.require_paths = %w(lib) end
require 'date' module Types class OrderType < Types::BaseObject field :id, ID, null: false field :user, Types::UserType, null: false field :pickup_location, Types::PickupLocationType, null: false field :items, [Types::OrderItemType], null: false def items OrderItem.where('order_id = ?', object.id) end field :total_amount, Integer, null: false field :orderedAt, GraphQL::Types::ISO8601DateTime, null: true def orderedAt object.created_at end field :deliveryDate, GraphQL::Types::ISO8601DateTime, null: true def deliveryDate delivery_date = object.created_at delivery_date += 1.days DateTime.parse(delivery_date.strftime("%Y-%m-%d 12:00:00 +0900")) end end end
# frozen_string_literal: true require 'stannum/constraints/types' module Stannum::Constraints::Types # A Nil type constraint asserts that the object is nil. class NilType < Stannum::Constraints::Type # The :type of the error generated for a matching object. NEGATED_TYPE = 'stannum.constraints.types.is_nil' # The :type of the error generated for a non-matching object. TYPE = 'stannum.constraints.types.is_not_nil' # @param options [Hash<Symbol, Object>] Configuration options for the # constraint. Defaults to an empty Hash. def initialize(**options) super(::NilClass, **options) end end end
class ResultsAddDescJson < ActiveRecord::Migration[7.0] def change add_column(:results, :desc_json, :string) add_column(:results, :core_link, :string) end end
module JanusGateway::Plugin class Audioroom < JanusGateway::Resource::Plugin # @param [JanusGateway::Client] client # @param [JanusGateway::Resource::Session] session def initialize(client, session) super(client, session, 'janus.plugin.cm.audioroom') end # @return [Concurrent::Promise] def list promise = Concurrent::Promise.new client.send_transaction( janus: 'message', session_id: session.id, handle_id: id, body: { request: 'list' } ).then do |data| plugindata = data['plugindata']['data'] if plugindata['error_code'].nil? _on_success(data) promise.set(data).execute else error = JanusGateway::Error.new(plugindata['error_code'], plugindata['error']) _on_error(error) promise.fail(error).execute end end.rescue do |error| promise.fail(error).execute end promise end private def _on_success(data) @data = data['plugindata'] emit :success end def _on_error(error) emit :error, error end end end
class EasyVersionQuery < EasyQuery include ProjectsHelper def available_filters return @available_filters unless @available_filters.blank? group = l("label_filter_group_#{self.class.name.underscore}") @available_filters = { 'status' => { :type => :list, :values => Version::VERSION_STATUSES.collect {|s| [l("version_status_#{s}"), s]}, :order => 1, :group => group}, 'name' => { :type => :text, :order => 2, :group => group}, 'effective_date' => { :type => :date_period, :order => 3, :group => group}, 'role_id' => { :type => :list, :order => 5, :values => Proc.new{Role.all.collect{|r| [r.name, r.id.to_s]}} , :group => group}, 'created_on' => { :type => :date_period, :order => 6, :group => group}, 'updated_on' => { :type => :date_period, :order => 7, :group => group}, 'sharing' => { :type => :list, :values => Version::VERSION_SHARINGS.collect {|s| [format_version_sharing(s), s]}, :order => 8, :group => group}, 'easy_version_category_id' => {:type => :list, :values => Proc.new{EasyVersionCategory.active.all.collect{|v| [v.name, v.id]}}, :order => 10, :group => group} } @available_filters['member_id'] = { :type => :list, :order => 4, :values => Proc.new do user_values = [] user_values << ["<< #{l(:label_me)} >>", 'me'] if User.current.logged? user_values += User.active.non_system_flag.sorted.collect{|s| [s.name, s.id.to_s] } # if User.current.admin? # user_values += User.active.sort_by(&:name).collect{|s| [s.name, s.id.to_s] } # else # user_values += User.current.projects.collect(&:users).flatten.uniq.sort_by(&:name).collect{|s| [s.name, s.id.to_s] } # end user_values end, :group => group } if self.project @available_filters['xproject_id'] = {:type => :list, :values => Proc.new{projects_for_select(self.project.self_and_ancestors.visible.non_templates.order(:lft))}, :order => 13, :group => group} else @available_filters['project_id'] = {:type => :list, :values => Proc.new{projects_for_select(Project.visible.non_templates.order(:lft))}, :order => 13, :group => group} end add_custom_fields_filters(VersionCustomField) @available_filters end def easy_query_entity_controller self.project ? 'versions' : 'easy_versions' end def available_columns unless @available_columns_added @available_columns = [ EasyQueryColumn.new(:project, :sortable => "#{Project.table_name}.name", :groupable => true), EasyQueryColumn.new(:status, :sortable => "#{Version.table_name}.status", :groupable => true), EasyQueryColumn.new(:name, :sortable => "#{Version.table_name}.name", :groupable => true), EasyQueryColumn.new(:effective_date, :sortable => "#{Version.table_name}.effective_date", :groupable => true), EasyQueryColumn.new(:description), EasyQueryColumn.new(:easy_version_category, :groupable => true, :sortable => "#{EasyVersionCategory.table_name}.name"), EasyQueryColumn.new(:sharing, :sortable => "#{Version.table_name}.sharing", :groupable => true), EasyQueryColumn.new(:created_on, :sortable => "#{Version.table_name}.created_on", :groupable => true), EasyQueryColumn.new(:updated_on, :sortable => "#{Version.table_name}.updated_on", :groupable => true), EasyQueryColumn.new(:completed_percent, :caption => :field_completed_percent) ] @available_columns += VersionCustomField.all.collect {|cf| EasyQueryCustomFieldColumn.new(cf)} @available_columns_added = true end @available_columns end def default_find_include [:project, :easy_version_category] end def default_sort_criteria ['project', 'name'] end def entity Version end def entity_scope self.project.nil? ? Version.visible : self.project.shared_versions end def extended_period_options { :extended_options => [:to_today, :is_null, :is_not_null], :option_limit => { :after_due_date => ['effective_date'], :next_week => ['effective_date'], :tomorrow => ['effective_date'], :next_5_days => ['effective_date'], :next_7_days => ['effective_date'], :next_10_days => ['effective_date'], :next_30_days => ['effective_date'], :next_90_days => ['effective_date'], :next_month => ['effective_date'], :next_year => ['effective_date'] } } end protected def statement_skip_fields ['member_id', 'role_id'] end def add_statement_sql_before_filters my_fields = ['member_id', 'role_id'] & filters.keys unless my_fields.blank? if my_fields.include?('member_id') mv = values_for('member_id').dup mv.push(User.current.logged? ? User.current.id.to_s : '0') if mv.delete('me') sql_member_id = "#{Project.table_name}.id #{operator_for('member_id') == '=' ? 'IN' : 'NOT IN'} (SELECT DISTINCT pm1.project_id FROM #{Member.table_name} pm1 WHERE " sql_member_id << sql_for_field('member_id', '=', mv, 'pm1', 'user_id', true) sql_member_id << ')' if my_fields.include?('role_id') sql_member_id << " AND #{Project.table_name}.id #{operator_for('role_id') == '=' ? 'IN' : 'NOT IN'} (SELECT DISTINCT pm1.project_id FROM #{Member.table_name} pm1 INNER JOIN #{MemberRole.table_name} pmr1 ON pmr1.member_id = pm1.id WHERE " sql_member_id << sql_for_field('member_id', '=', mv, 'pm1', 'user_id', true) sql_member_id << (' AND ' + sql_for_field('role_id', '=', values_for('role_id').dup, 'pmr1', 'role_id', true)) sql_member_id << ')' end elsif my_fields.include?('role_id') sql_role_id = "#{Project.table_name}.id #{operator_for('role_id') == '=' ? 'IN' : 'NOT IN'} (SELECT DISTINCT pm1.project_id FROM #{Member.table_name} pm1 INNER JOIN #{MemberRole.table_name} pmr1 ON pmr1.member_id = pm1.id WHERE " sql_role_id << sql_for_field('role_id', '=', values_for('role_id').dup, 'pmr1', 'role_id', true) sql_role_id << ')' end sql = [sql_member_id, sql_role_id].compact.join(' AND ') return sql end end def sql_for_xproject_id_field(field, operator, v) db_table = self.entity.table_name db_field = 'project_id' returned_sql_for_field = self.sql_for_field(db_field, operator, v, db_table, db_field) return ('(' + returned_sql_for_field + ')') unless returned_sql_for_field.blank? end end
namespace :react_meetup do desc 'Expire accreditations over 90 days' task :generate => :environment do tmp = [] tables = ActiveRecord::Base.connection.tables tables.each do |table| next if ['tmp_investment_term', 'version', 'msd_profile'].include?(table.singularize.to_s) tmp_result = [table.singularize.to_s] table_class = table.singularize.camelize.constantize rescue next # WIP tmp_required_columns = [] table_class.validators.each do |validator| next unless validator.is_a?(ActiveRecord::Validations::PresenceValidator) validator.attributes.each do |column| tmp_required_columns << column end tmp_required_columns.uniq.compact end # binding.pry table_columns = table_class.columns.map(&:name) tmp_table_columns = table_columns.reject{|asdf| true if (asdf =~ /audit_/ || asdf.eql?('account_id')) } tmp_result << tmp_table_columns.compact.join(' ') # Put column name w/ class type tmp_form_columns = table_class.columns.collect{|x| if !(x.name =~ /audit_/ || x.name.eql?('id')) tmp_final_column = '' if x.sql_type.eql?('timestamp without time zone') tmp_final_column = tmp_final_column + x.name + ':timestamp' elsif x.sql_type.include?('character varying') tmp_final_column = tmp_final_column + x.name + ':character' elsif x.sql_type.include?('double precision') tmp_final_column = tmp_final_column + x.name + ':character' else tmp_final_column = tmp_final_column + x.name + ':' + x.sql_type end if tmp_required_columns.include?(x.name.to_sym) tmp_final_column = tmp_final_column + ':required' end tmp_final_column end } # binding.pry if table.eql?('postal_addresses') tmp_result << tmp_form_columns.compact.join(' ') tmp_reflections = table.classify.constantize.reflections.keys if (['email_address', 'phone_number', 'postal_address'] & tmp_reflections).any? tmp_params = '' tmp_params << '-' tmp_params << 'e' if tmp_reflections.include?('email_address') tmp_params << 'p' if tmp_reflections.include?('phone_number') tmp_params << 'a' if tmp_reflections.include?('postal_address') tmp_params << 'b' if tmp_reflections.include?('bank_account') tmp_result << tmp_params end puts tmp_result tmp << tmp_result end File.open('generator_arguments.txt', 'w') do |file| tmp.each do |class_generator| # file.write('```' + "\r\n" + class_generator[0].strip + ' "' + class_generator[1].strip + '" "' + class_generator[2].strip + '"' + "\r\n" + '```' + "\r\n") tmp_output = "\r\nyo ims-v-5 " + class_generator[0].strip + ' "' + class_generator[1].strip + '" "' + class_generator[2].strip + '" ' tmp_output << class_generator[3].strip if class_generator[3].present? file.write(tmp_output) end end end end
class CreateTopLists < ActiveRecord::Migration def change create_table :top_lists do |t| t.integer :top_list_id t.string :name t.timestamps end end end
module Api class PropertiesController < ApplicationController def index @properties = Property.order(created_at: :desc).page(params[:page]).per(6) return render json: { error: 'not_found' }, status: :not_found if !@properties render 'api/properties/index', status: :ok end def show @property = Property.find_by(id: params[:id]) return render json: { error: 'not_found' }, status: :not_found if !@property render 'api/properties/show', status: :ok end def create token = cookies.signed[:airbnb_session_token] session = Session.find_by(token: token) user = session.user property = user.properties.new(property_params) if property.save render 'api/properties/create', status: :ok else render json: { success: false }, status: :bad_request end end def update @property = Property.find_by(id: params[:id]) if property.update_attributes(property_params) render json: { success: true }, status: :ok else render json: { success: false }, status: :bad_request end end def destroy token = cookies.signed[:airbnb_session_token] session = Session.find_by(token: token) return render json: { success: false } unless session user = session.user property = Property.find_by(id: params[:id]) if property and property.user == user and property.destroy render json: { success: true } else render json: { success: false } end end def index_by_user user = User.find_by(username: params[:username]) if user @properties = user.properties render 'api/properties/index' end end private def property_params params.require(:property).permit(:title, :description, :city, :country, :property_type, :price_per_night, :max_guests, :bedrooms, :beds, :baths) end end end
require 'ankusa' require 'ankusa/memory_storage' class Cschat::MessageClassifier def initialize data @storage = Ankusa::MemoryStorage.new @classifier = Ankusa::NaiveBayesClassifier.new @storage @listeners = {} data.each { |action, text| @classifier.train action.to_sym, text } if data end def classify text if text category = @classifier.classify text notify_all :process_message, category, text end end def listener(listener, category = nil) if listener category_sym = category && category.to_sym @listeners[category_sym] ||= [] @listeners[category_sym] << listener end self end private def notify_all(method, category, text) listeners(category, include_defaults: true).each { |o| o.send method, category, text } end def listeners(category, include_defaults: false) category_listeners = @listeners[category] || [] default_listeners = (include_defaults && @listeners[nil]) || [] (category_listeners + default_listeners).uniq end end
module SeedMigrator # Machinery to load the actual data update classes module UpdateClassLoader # Loads the class corresponding to the given update name from the given # file system path. # # @param [String|Pathname|Symbol] root_path # @param [String|Symbol] update_name # # @return [::Class] def get_update_class(root_path, update_name) update = strip_seq_prefix(update_name.to_s) file_name = find_file(root_path, update) if file_name file_name = File.basename(file_name, '.rb') if root_path.to_s.ends_with?('/') require "#{root_path}#{file_name}" else require "#{root_path}/#{file_name}" end update.camelize.constantize else raise LoadError, "Unable to find file for update #{update_name} in #{root_path}" end end # Determines what's the actual filename for the given update name def find_file(root_path, update) update_file = "#{update}.rb" Dir.entries(root_path).find{|entry| strip_seq_prefix(entry) == update_file } end private :find_file # Takes the given file name and strips out the sequence prefix if any. If # the file name starts with a digit, all characters up to the first '_' are # considered part of the prefix. For example, for '00234ab_foo_bar' the # prefix would be '00234ab' and 'foo_bar' would be returned. # # @param [String] update_name # # @return [String] def strip_seq_prefix(update_name) index = update_name =~ /_/ if index start = update_name[0,1] # If the first letter of the prefix is a digit, we assume the prefix is # for sequence ordering purposes. if %w(0 1 2 3 4 5 6 7 8 9).include?(start) update_name = update_name[index + 1, update_name.size - index] end end update_name end private :strip_seq_prefix end end
require 'github/markup' class PostsController < ApplicationController before_action :login_check before_action :set_post, only: [:show, :edit, :update, :destroy] # GET /posts # GET /posts.json def index @posts = Post.where(user_id: session[:user_id]).order(:updated_at) end # GET /posts/1 # GET /posts/1.json def show end # GET /posts/new def new @post = Post.new end # GET /posts/1/edit def edit end # POST /posts # POST /posts.json def create @post = Post.new(post_params) respond_to do |format| if @post.save format.html { redirect_to @post, notice: 'Post was successfully created.' } format.json { render :show, status: :created, location: @post } else format.html { render :new } format.json { render json: @post.errors, status: :unprocessable_entity } end end end # PATCH/PUT /posts/1 # PATCH/PUT /posts/1.json def update respond_to do |format| if @post.update(post_params) format.html { redirect_to @post, notice: 'Post was successfully updated.' } format.json { render :show, status: :ok, location: @post } else format.html { render :edit } format.json { render json: @post.errors, status: :unprocessable_entity } end end end # DELETE /posts/1 # DELETE /posts/1.json def destroy @post.destroy respond_to do |format| format.html { redirect_to posts_url, notice: 'Post was successfully destroyed.' } format.json { head :no_content } end end def markdown(str) GitHub::Markup.render('README.markdown',str) end helper_method :markdown private # Use callbacks to share common setup or constraints between actions. def set_post @post = Post.find_by(id: params[:id],user_id: session['user_id']) if @post.nil? redirect_to posts_path, notice: "That page is not your's " end end # Never trust parameters from the scary internet, only allow the white list through. def post_params params[:post][:user_id] = session[:user_id] params.require(:post).permit(:user_id, :content) end end
require 'rails_helper' feature "user deletes account" do before(:each) do @bob = FactoryBot.create(:user, name: "bob", email: "bob@example.com") @frank = FactoryBot.create(:user, name: "frank", email: "frank@example.com") sign_in @bob visit root_path click_on "edit account" click_on "Cancel my account" end scenario "they see a flash message" do expect(page).to have_content("Your account has been successfully cancelled") end scenario "other users no longer see them in the users index" do sign_out @bob sign_in @frank visit root_path click_on "users" expect(page).not_to have_content("bob") end end
class AddDirectorRatingWriterStudioGenreToMovies < ActiveRecord::Migration[5.0] def change add_column :movies, :director_id, :integer add_column :movies, :writer, :string add_column :movies, :studio, :string add_column :movies, :genre_id, :integer add_column :movies, :rating, :string end end
require "rubygems" require "gosu" class Rect attr_accessor :x, :y, :width, :height, :color, :z_order def initialize(params = Hash.new) @x = params[:x] || 0 @y = params[:y] || 0 @width = params[:width] || 0 @height = params[:height] || 0 @color = params[:color] || 0xff000000 @z_order = params[:z_order] || 0 end def top @y end def bottom @y + @height end def left @x end def right @x + @width end def draw(window) window.draw_quad(left, top, @color, right, top, @color, right, bottom, @color, left, bottom, @color, @z_order) end end
require 'fileutils' namespace :caching_funtime do #good to overwrite this in order to load the correct fragment_trackerfiles task :cache_environment => :environment do require 'action_controller' begin require 'caching_config' rescue LoadError => le end CachingFuntime::TheCacher.perform_caching = true end namespace :assets do desc 'remove cached assets' task :sweep => :cache_environment do CachingFuntime::TheCacher.sweep_assets :all, :verbose => true end task :remove => :sweep end namespace :fragments do desc 'remove cached fragments (and actions)' task :sweep => [ :cache_environment ] do CachingFuntime::TheCacher.sweep_fragments( :all, :verbose => true ) end desc 'sweep specified fragment rake caching_funtime:fragments:sweep_by_name NAME=_browse' task :sweep_by_name => [:cache_environment] do CachingFuntime::TheCacher.sweep_fragments( ENV['NAME'], :verbose => true ) end end namespace :page do desc 'Clear the page cache' task :sweep => :cache_environment do CachingFuntime::TheCacher.sweep_pages :all, :verbose => true end end namespace :public do desc 'Remove all page caches and assets' task :sweep => ["page:sweep", "assets:sweep"] end end
require "spec_helper" describe Paperclip::Validators::AttachmentContentTypeValidator do before do rebuild_model @dummy = Dummy.new end def build_validator(options) @validator = Paperclip::Validators::AttachmentContentTypeValidator.new(options.merge( attributes: :avatar )) end context "with a nil content type" do before do build_validator content_type: "image/jpg" allow(@dummy).to receive_messages(avatar_content_type: nil) @validator.validate(@dummy) end it "does not set an error message" do assert @dummy.errors[:avatar_content_type].blank? end end context "with :allow_nil option" do context "as true" do before do build_validator content_type: "image/png", allow_nil: true allow(@dummy).to receive_messages(avatar_content_type: nil) @validator.validate(@dummy) end it "allows avatar_content_type as nil" do assert @dummy.errors[:avatar_content_type].blank? end end context "as false" do before do build_validator content_type: "image/png", allow_nil: false allow(@dummy).to receive_messages(avatar_content_type: nil) @validator.validate(@dummy) end it "does not allow avatar_content_type as nil" do assert @dummy.errors[:avatar_content_type].present? end end end context "with a failing validation" do before do build_validator content_type: "image/png", allow_nil: false allow(@dummy).to receive_messages(avatar_content_type: nil) @validator.validate(@dummy) end it "adds error to the base object" do assert @dummy.errors[:avatar].present?, "Error not added to base attribute" end it "adds error to base object as a string" do expect(@dummy.errors[:avatar].first).to be_a String end end context "with add_validation_errors_to not set (implicitly :both)" do it "adds error to both attribute and base" do build_validator content_type: "image/png", allow_nil: false allow(@dummy).to receive_messages(avatar_content_type: nil) @validator.validate(@dummy) assert @dummy.errors[:avatar_content_type].present?, "Error not added to attribute" assert @dummy.errors[:avatar].present?, "Error not added to base attribute" end end context "with add_validation_errors_to set to :attribute globally" do before do Paperclip.options[:add_validation_errors_to] = :attribute end after do Paperclip.options[:add_validation_errors_to] = :both end it "only adds error to attribute not base" do build_validator content_type: "image/png", allow_nil: false allow(@dummy).to receive_messages(avatar_content_type: nil) @validator.validate(@dummy) assert @dummy.errors[:avatar_content_type].present?, "Error not added to attribute" assert @dummy.errors[:avatar].blank?, "Error added to base attribute" end end context "with add_validation_errors_to set to :base globally" do before do Paperclip.options[:add_validation_errors_to] = :base end after do Paperclip.options[:add_validation_errors_to] = :both end it "only adds error to base not attribute" do build_validator content_type: "image/png", allow_nil: false allow(@dummy).to receive_messages(avatar_content_type: nil) @validator.validate(@dummy) assert @dummy.errors[:avatar].present?, "Error not added to base attribute" assert @dummy.errors[:avatar_content_type].blank?, "Error added to attribute" end end context "with add_validation_errors_to set to :attribute" do it "only adds error to attribute not base" do build_validator content_type: "image/png", allow_nil: false, add_validation_errors_to: :attribute allow(@dummy).to receive_messages(avatar_content_type: nil) @validator.validate(@dummy) assert @dummy.errors[:avatar_content_type].present?, "Error not added to attribute" assert @dummy.errors[:avatar].blank?, "Error added to base attribute" end end context "with add_validation_errors_to set to :base" do it "only adds error to base not attribute" do build_validator content_type: "image/png", allow_nil: false, add_validation_errors_to: :base allow(@dummy).to receive_messages(avatar_content_type: nil) @validator.validate(@dummy) assert @dummy.errors[:avatar].present?, "Error not added to base attribute" assert @dummy.errors[:avatar_content_type].blank?, "Error added to attribute" end end context "with a successful validation" do before do build_validator content_type: "image/png", allow_nil: false allow(@dummy).to receive_messages(avatar_content_type: "image/png") @validator.validate(@dummy) end it "does not add error to the base object" do assert @dummy.errors[:avatar].blank?, "Error was added to base attribute" end end context "with :allow_blank option" do context "as true" do before do build_validator content_type: "image/png", allow_blank: true allow(@dummy).to receive_messages(avatar_content_type: "") @validator.validate(@dummy) end it "allows avatar_content_type as blank" do assert @dummy.errors[:avatar_content_type].blank? end end context "as false" do before do build_validator content_type: "image/png", allow_blank: false allow(@dummy).to receive_messages(avatar_content_type: "") @validator.validate(@dummy) end it "does not allow avatar_content_type as blank" do assert @dummy.errors[:avatar_content_type].present? end end end context "whitelist format" do context "with an allowed type" do context "as a string" do before do build_validator content_type: "image/jpg" allow(@dummy).to receive_messages(avatar_content_type: "image/jpg") @validator.validate(@dummy) end it "does not set an error message" do assert @dummy.errors[:avatar_content_type].blank? end end context "as an regexp" do before do build_validator content_type: /^image\/.*/ allow(@dummy).to receive_messages(avatar_content_type: "image/jpg") @validator.validate(@dummy) end it "does not set an error message" do assert @dummy.errors[:avatar_content_type].blank? end end context "as a list" do before do build_validator content_type: ["image/png", "image/jpg", "image/jpeg"] allow(@dummy).to receive_messages(avatar_content_type: "image/jpg") @validator.validate(@dummy) end it "does not set an error message" do assert @dummy.errors[:avatar_content_type].blank? end end end context "with a disallowed type" do context "as a string" do before do build_validator content_type: "image/png" allow(@dummy).to receive_messages(avatar_content_type: "image/jpg") @validator.validate(@dummy) end it "sets a correct default error message" do assert @dummy.errors[:avatar_content_type].present? expect(@dummy.errors[:avatar_content_type]).to include "is invalid" end end context "as a regexp" do before do build_validator content_type: /^text\/.*/ allow(@dummy).to receive_messages(avatar_content_type: "image/jpg") @validator.validate(@dummy) end it "sets a correct default error message" do assert @dummy.errors[:avatar_content_type].present? expect(@dummy.errors[:avatar_content_type]).to include "is invalid" end end context "with :message option" do context "without interpolation" do before do build_validator content_type: "image/png", message: "should be a PNG image" allow(@dummy).to receive_messages(avatar_content_type: "image/jpg") @validator.validate(@dummy) end it "sets a correct error message" do expect(@dummy.errors[:avatar_content_type]).to include "should be a PNG image" end end context "with interpolation" do before do build_validator content_type: "image/png", message: "should have content type %{types}" allow(@dummy).to receive_messages(avatar_content_type: "image/jpg") @validator.validate(@dummy) end it "sets a correct error message" do expect(@dummy.errors[:avatar_content_type]).to include "should have content type image/png" end end end end end context "blacklist format" do context "with an allowed type" do context "as a string" do before do build_validator not: "image/gif" allow(@dummy).to receive_messages(avatar_content_type: "image/jpg") @validator.validate(@dummy) end it "does not set an error message" do assert @dummy.errors[:avatar_content_type].blank? end end context "as an regexp" do before do build_validator not: /^text\/.*/ allow(@dummy).to receive_messages(avatar_content_type: "image/jpg") @validator.validate(@dummy) end it "does not set an error message" do assert @dummy.errors[:avatar_content_type].blank? end end context "as a list" do before do build_validator not: ["image/png", "image/jpg", "image/jpeg"] allow(@dummy).to receive_messages(avatar_content_type: "image/gif") @validator.validate(@dummy) end it "does not set an error message" do assert @dummy.errors[:avatar_content_type].blank? end end end context "with a disallowed type" do context "as a string" do before do build_validator not: "image/png" allow(@dummy).to receive_messages(avatar_content_type: "image/png") @validator.validate(@dummy) end it "sets a correct default error message" do assert @dummy.errors[:avatar_content_type].present? expect(@dummy.errors[:avatar_content_type]).to include "is invalid" end end context "as a regexp" do before do build_validator not: /^text\/.*/ allow(@dummy).to receive_messages(avatar_content_type: "text/plain") @validator.validate(@dummy) end it "sets a correct default error message" do assert @dummy.errors[:avatar_content_type].present? expect(@dummy.errors[:avatar_content_type]).to include "is invalid" end end context "with :message option" do context "without interpolation" do before do build_validator not: "image/png", message: "should not be a PNG image" allow(@dummy).to receive_messages(avatar_content_type: "image/png") @validator.validate(@dummy) end it "sets a correct error message" do expect(@dummy.errors[:avatar_content_type]).to include "should not be a PNG image" end end context "with interpolation" do before do build_validator not: "image/png", message: "should not have content type %{types}" allow(@dummy).to receive_messages(avatar_content_type: "image/png") @validator.validate(@dummy) end it "sets a correct error message" do expect(@dummy.errors[:avatar_content_type]).to include "should not have content type image/png" end end end end end context "using the helper" do before do Dummy.validates_attachment_content_type :avatar, content_type: "image/jpg" end it "adds the validator to the class" do assert Dummy.validators_on(:avatar).any? { |validator| validator.kind == :attachment_content_type } end end context "given options" do it "raises argument error if no required argument was given" do assert_raises(ArgumentError) do build_validator message: "Some message" end end it "does not raise argument error if :content_type was given" do build_validator content_type: "image/jpg" end it "does not raise argument error if :not was given" do build_validator not: "image/jpg" end end end
require 'pry' class Triangle attr_accessor :side_a, :side_b, :side_c, :triangle @@triangle = [] def initialize(side_a ,side_b ,side_c) @side_a = side_a @side_b = side_b @side_c = side_c @triangle = [side_a, side_b, side_c] end def kind sum = 0 triangle = [] triangle= @triangle.sort sum = (triangle[0] + triangle[1]) > triangle[2] if @triangle.detect {|side| side <=0} || !sum raise TriangleError else find_kind end end def find_kind equality = 0 @triangle.each_with_index do |side, index| @triangle.each_with_index do |side_2, place| if !(place == index) if side == side_2 equality +=1 end end end end if equality == 0 :scalene elsif equality == 2 :isosceles else equality == 3 :equilateral end end end class TriangleError < StandardError end
require 'rails/generators/active_record' module Merit module Generators::ActiveRecord class MeritGenerator < ::ActiveRecord::Generators::Base include Rails::Generators::Migration source_root File.expand_path('../templates', __FILE__) desc 'add active_record merit migrations' def self.next_migration_number(path) ActiveRecord::Generators::Base.next_migration_number(path) end def copy_migrations_and_model migration_template 'add_merit_fields_to_model.erb', "db/migrate/add_merit_fields_to_#{table_name}.rb" end def migration_version "[#{Rails::VERSION::MAJOR}.#{Rails::VERSION::MINOR}]" end end end end
module GithubTwitterServer # these modules extend Feed instances for custom parsing module Events module GenericEvent def project end def content @content ||= parsed_content end end module IssuesEvent include GenericEvent def issue_number @issue_number end def issue_action @issue_action end def project @project ||= \ if title =~ /\w+ (\w+) issue (\d+) on (.*)$/ @issue_action = $1 @issue_number = $2 $3 end end def content @content ||= begin project "#{issue_action} ##{issue_number} #{parsed_content}" end end end module WatchEvent include GenericEvent def content @content ||= begin txt = title.dup txt.gsub! /^\w+ started/, 'Started' txt.gsub!(/watching (\w+\/)/) { |s| "watching @#{$1}" } txt end end end module CommitCommentEvent def project @project ||= \ if title =~ /\w+ commented on (.*)$/ $1 end end # Comment in a18f575: this mess is gonna get raw, like sushi => # @c_a18f575 this mess is gonna get raw, like sushi def content @content ||= begin # pull out commit hash and comment if parsed_content =~ /(\w+)\: (.+)$/ "@c_#{$1} #{$2}" else parsed_content end end end end module PushEvent def project @project ||= \ if title =~ /\w+ pushed to \w+ at (.*)$/ $1 end end # put each commit on a line # @link users # @link commits def content @content ||= begin parsed_content.dup.tap do |text| # parse out "HEAD IS (sha)" text.gsub! /^HEAD is \w+ /, '' # [['technoweenie', 'sha1'], ['technoweenie', 'sha2']] commits = text.scan(/(\w+) committed (\w+):/) msgs = text.split(/\w+ committed \w+: /) msgs.shift s = [] commits.each_with_index do |(user, sha), idx| s << "#{"@#{user} " if user != author}#{sha} #{msgs[idx]}".strip end s = s * "\n" text.replace \ case commits.size when 1 then s when 0 then '' else "#{commits.size} commits: #{s}" end end end end end end end
class UserItemsController < ApplicationController def cart cartItem = UserItem.find{|userItem| userItem.item_id === params[:item_id] && userItem.user_id === params[:user_id]} if(cartItem) if(params[:step] == "add") cartItem.update(quantity: cartItem.quantity += 1) elsif(params[:step] == "subtract") cartItem.update(quantity: cartItem.quantity -= 1) end render json: cartItem else @user_item = UserItem.create(user_item_params) render json: @user_item end end # def update # @user_item = UserItem.find(params[:id]) # @user_item.update(user_item_params) # render json: @user_item # end def show @user_items = @user.user_items render json: @user_items end def index @user_item = UserItem.find(params[:id]) render json: @user_item end def destroy @user_item = UserItem.find(params[:id]) @user_item.destroy end private def user_item_params params.permit(:user_id, :item_id, :quantity).merge(quantity: 1) end end
class CreateQueryHistories < ActiveRecord::Migration def change create_table :query_histories do |t| t.references :custom, index: true t.string :company_code t.string :company_name t.string :num t.datetime :queried_at t.timestamps end end end
# frozen_string_literal: true require_relative 'display' # require_relative 'player' # require 'colorize' class Board attr_accessor :board def initialize @board = Array.new(7) { Array.new(6) } end # push disc into first nil slot on a given column def push_disc(column, player) board[column].each_index do |row| if board[column][row].nil? board[column][row] = player return [[column], [row]].flatten end end end def column_not_full?(column) return false unless board[column].include?(nil) true end def display_board print_board end def check_winner(arr) return true if check_horizontal_left(arr[0], arr[1]) return true if check_horizontal_right(arr[0], arr[1]) return true if check_vertical_up(arr[0], arr[1]) return true if check_vertical_down(arr[0], arr[1]) return true if check_diagonal_left_up(arr[0], arr[1]) return true if check_diagonal_left_down(arr[0], arr[1]) return true if check_diagonal_right_up(arr[0], arr[1]) return true if check_diagonal_right_down(arr[0], arr[1]) false end def tie? return true if board.flatten.count(&:nil?).zero? false end private def print_board print Display::TOP_LINE 5.downto(0) do |i| print Display::VERTICAL_LINE 0.upto(6) do |n| if board[n][i].nil? print " #{Display::EMPTY_CELL} #{Display::VERTICAL_LINE}" else # print " #{Display::FILLED_CELL.colorize(board[n][i].color.to_sym)} #{Display::VERTICAL_LINE}" print " \e#{board[n][i].color}#{Display::FILLED_CELL}\e[m #{Display::VERTICAL_LINE}" end end puts "\n" end print Display::BOTTOM_LINE print "#{Display::COLUMN_NUMBERS}\n" end def check_horizontal_right(column, row) return false if column + 3 > 6 if board[column][row] == board[column + 1][row] && board[column + 1][row] == board[column + 2][row] && board[column + 2][row] == board[column + 3][row] return true end false end def check_horizontal_left(column, row) return false if (column - 3).negative? if board[column][row] == board[column - 1][row] && board[column - 1][row] == board[column - 2][row] && board[column - 2][row] == board[column - 3][row] return true end false end def check_vertical_up(column, row) return false if row + 3 > 5 if board[column][row] == board[column][row + 1] && board[column][row + 1] == board[column][row + 2] && board[column][row + 2] == board[column][row + 3] return true end false end def check_vertical_down(column, row) return false if (row - 3).negative? if board[column][row] == board[column][row - 1] && board[column][row - 1] == board[column][row - 2] && board[column][row - 2] == board[column][row - 3] return true end false end def check_diagonal_right_up(column, row) return false if column + 3 > 6 return false if row + 3 > 5 if board[column][row] == board[column + 1][row + 1] && board[column + 1][row + 1] == board[column + 2][row + 2] && board[column + 2][row + 2] == board[column + 3][row + 3] return true end false end def check_diagonal_right_down(column, row) return false if column + 3 > 6 return false if (row - 3).negative? if board[column][row] == board[column + 1][row - 1] && board[column + 1][row - 1] == board[column + 2][row - 2] && board[column + 2][row - 2] == board[column + 3][row - 3] return true end false end def check_diagonal_left_up(column, row) return false if (column - 3).negative? return false if row + 3 > 5 if board[column][row] == board[column - 1][row + 1] && board[column - 1][row + 1] == board[column - 2][row + 2] && board[column - 2][row + 2] == board[column - 3][row + 3] return true end false end def check_diagonal_left_down(column, row) return false if (column - 3).negative? return false if (row - 3).negative? if board[column][row] == board[column - 1][row - 1] && board[column - 1][row - 1] == board[column - 2][row - 2] && board[column - 2][row - 2] == board[column - 3][row - 3] return true end false end end
# GOOGLE_CHROME_SHIM is an environment variable set within the Heroku CI pipeline environment. # GOOGLE_CHROME_SHIM contains the path to chrome-related assets on the Heroku CI ephemeral VM. chrome_bin = ENV.fetch('GOOGLE_CHROME_SHIM', nil) binary_options = chrome_bin ? {binary: chrome_bin} : {} headless_options = {args: %w(headless disable-gpu)} Capybara.register_driver :chrome do |app| chrome_options = {chromeOptions: binary_options} capabilities = Selenium::WebDriver::Remote::Capabilities.chrome(chrome_options) # noinspection RubyArgCount Capybara::Selenium::Driver.new(app, browser: :chrome, desired_capabilities: capabilities) end Capybara.register_driver :headless_chrome do |app| chrome_options = {chromeOptions: binary_options.merge(headless_options)} capabilities = Selenium::WebDriver::Remote::Capabilities.chrome(chrome_options) # noinspection RubyArgCount Capybara::Selenium::Driver.new(app, browser: :chrome, desired_capabilities: capabilities) end
require 'rake' require 'rake/gempackagetask' require 'plugems_deploy/manifest' require 'fileutils' module PlugemsDeployBuild include FileUtils def gem_version version_specified? ? plugem_version : get_gem_version end def version_specified? ! (plugem_version.empty? || (plugem_version == '> 0.0')) end def get_gem_version micro = gem_micro_revision || @manifest.version[2] || 0 ver = (@manifest.version + [0,0])[0..1].join('.') "#{ ver }.#{ micro }" end def gem_homepage nil end def gem_author @manifest.author end def gem_requirements [ 'none' ] end def gem_require_path 'lib' end def add_gem_dependencies(s) @manifest.dependencies.each do |name,version| s.add_dependency(name, version || '>= 0.0.0') unless package_ignored_gems.include?(name) end end def gem_files Dir["**/*"].reject { |f| f == 'test' } end def gem_test_files Dir['test/**/*_test.rb'] end def add_auto_require(s) s.autorequire = plugem_name if File.exist?("lib/#{plugem_name}.rb") end def plugem_name @manifest.name end def gem_spec @manifest = PlugemsDeploy::Manifest.new spec = Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.summary = @manifest.description s.name = plugem_name s.version = gem_version s.homepage = gem_homepage if gem_homepage s.author = gem_author s.requirements = gem_requirements s.require_path = gem_require_path s.files = gem_files s.test_files = gem_test_files s.description = @manifest.description s.executables = @manifest.executables add_auto_require(s) add_gem_dependencies(s) finalize_gem_spec(s) end end def finalize_gem_spec(s) # Use this method to add/overwrite any spec attributes end end # Allows to have some gem depdencies used at the run time only but not at the packaging time set :package_ignored_gems, [] # Allows to define the micro revision from the external recipe file set :gem_micro_revision, nil desc 'Builds a gem package locally' task :plugem_build do self.class.send(:include, PlugemsDeployBuild) rm_rf('pkg') Rake::GemPackageTask.new(gem_spec) do |pkg| additional_gem_packaging_tasks(pkg) if self.class.method_defined?(:additional_gem_packaging_tasks) end Rake::Task['package'].invoke end
module Environment def environment ENV["RACK_ENV"] || ENV["RAILS_ENV"] end def development? environment == "development" end def production? environment == "production" end def staging? environment == "staging" end def test? environment == "test" end module ClassMethods def environment ENV["RACK_ENV"] || ENV["RAILS_ENV"] end def development? environment == "development" end def production? environment == "production" end def staging? environment == "staging" end def test? environment == "test" end end end
class MessagingErrorMailer < ApplicationMailer def ranking_error_message(object, error_messsage) @object = object @error_messsage = error_messsage mail(subject: "Error processing ranking object") end end
require_relative 'feature_spec_helper' describe 'an order', type: :feature do let(:current_order) { Order.create! } let(:user) { FactoryGirl.create :user } let(:item) { FactoryGirl.create :item, user_id: user.id } def book_an_item item.availabilities.create(date: "10/04/2014") item.availabilities.create(date: "11/04/2014") item.item_images.create! visit "/items" visit item_path(item) fill_in "from", with: "04/10/2014" fill_in "to", with: "04/11/2014" click_link_or_button "Book it!" end it "starts with zero items" do visit items_path visit order_path(current_order) expect(page).to have_content("You don't have any items in your cart!") end it "can add an item" do book_an_item expect(page).to have_css ".table", text: "MyTitle" end it "can remove an item" do book_an_item click_link_or_button "Remove" expect(page).not_to have_content("MyTitle") expect(page).not_to have_content("Remove") end it "reflects the correct number of nights" do book_an_item expect(page).to have_content "Nights" within(".nights") do expect(page).to have_content "1" end end it "displays the correct check-in and check-out dates" do book_an_item within(".check-in") { expect(page).to have_content "Apr 10, 2014" } within(".check-out") { expect(page).to have_content "Apr 11, 2014" } end it "subtotals the price of each item in order" do book_an_item expect(page).to have_content('$0.32') end it "can return to an empty state" do book_an_item click_link_or_button("Remove") expect(page).to have_content("You don't have any items in your cart!") end end
require 'rails_helper' describe 'User auth on request' do let(:request_path) { '/tasks' } context 'no token provided' do it 'gets 401' do get request_path, {}, {} expect(response.code).to eq('401') end end context 'when invalid token provided' do it 'gets 401' do get request_path, {}, { 'Authorization' => 'some_random_string' } expect(response.code).to eq('401') end end context 'when valid token provided' do let(:token) { JsonWebToken.encode(user_email: create(:user).email) } it 'gets 200' do get request_path, {}, { 'Authorization' => token } expect(response.code).to eq('200') end end end
# frozen_string_literal: true RSpec.configure do |config| config.before(:each) do Uploadcare.config.public_key = 'demopublickey' Uploadcare.config.secret_key = 'demoprivatekey' Uploadcare.config.auth_type = 'Uploadcare' Uploadcare.config.multipart_size_threshold = 100 * 1024 * 1024 end end
module ActiveRecord class Base def self.to_qry(*args) DirectiveRecord::Query.new(self, extract_connection(args)).to_sql(*args) end def self.qry(*args) extract_connection(args).select_rows to_qry(*args) end def self.qry_value(*args) extract_connection(args).select_value to_qry(*args) end def self.qry_values(*args) extract_connection(args).select_values to_qry(*args) end def self.to_trend_qry(q1, q2, join_column_count, options) DirectiveRecord::Query.new(self).to_trend_sql(q1, q2, join_column_count, options) end private def self.extract_connection(args) (args[-1][:connection] if args[-1].is_a?(Hash)) || connection end end end
class Person def initialize(name, surname) @name = name @surname = surname end end
class AddDataModuleIdToTreatmentModules < ActiveRecord::Migration def change add_column :treatment_modules, :data_module_id, :integer end end
require_relative '../test_helper' class ProjectMedia2Test < ActiveSupport::TestCase def setup require 'sidekiq/testing' Sidekiq::Testing.fake! super create_team_bot login: 'keep', name: 'Keep' create_verification_status_stuff end test "should cache number of linked items" do RequestStore.store[:skip_cached_field_update] = false Sidekiq::Testing.inline! do t = create_team pm = create_project_media team: t assert_queries(0, '=') { assert_equal(1, pm.linked_items_count) } pm2 = create_project_media team: t assert_queries(0, '=') { assert_equal(1, pm2.linked_items_count) } create_relationship source_id: pm.id, target_id: pm2.id, relationship_type: Relationship.confirmed_type assert_queries(0, '=') { assert_equal(2, pm.linked_items_count) } assert_queries(0, '=') { assert_equal(1, pm2.linked_items_count) } pm3 = create_project_media team: t assert_queries(0, '=') { assert_equal(1, pm3.linked_items_count) } r = create_relationship source_id: pm.id, target_id: pm3.id, relationship_type: Relationship.confirmed_type assert_queries(0, '=') { assert_equal(3, pm.linked_items_count) } assert_queries(0, '=') { assert_equal(1, pm2.linked_items_count) } assert_queries(0, '=') { assert_equal(1, pm3.linked_items_count) } r.destroy! assert_queries(0, '=') { assert_equal(2, pm.linked_items_count) } assert_queries(0, '=') { assert_equal(1, pm2.linked_items_count) } assert_queries(0, '=') { assert_equal(1, pm3.linked_items_count) } assert_queries(0, '>') { assert_equal(2, pm.linked_items_count(true)) } end end test "should cache show warning cover" do RequestStore.store[:skip_cached_field_update] = false Sidekiq::Testing.inline! do team = create_team pm = create_project_media team: team assert_not pm.show_warning_cover flag = create_flag annotated: pm flag.set_fields = { show_cover: true }.to_json flag.save! assert pm.show_warning_cover puts "Data :: #{pm.show_warning_cover}" assert_queries(0, '=') { assert_equal(true, pm.show_warning_cover) } assert_queries(0, '>') { assert_equal(true, pm.show_warning_cover(true)) } end end test "should cache status" do RequestStore.store[:skip_cached_field_update] = false Sidekiq::Testing.inline! do pm = create_project_media assert pm.respond_to?(:status) assert_queries 0, '=' do assert_equal 'undetermined', pm.status end s = pm.last_verification_status_obj s.status = 'verified' s.save! assert_queries 0, '=' do assert_equal 'verified', pm.status end assert_queries(0, '>') do assert_equal 'verified', pm.status(true) end end end test "should cache title" do RequestStore.store[:skip_cached_field_update] = false Sidekiq::Testing.inline! do pm = create_project_media quote: 'Title 0' assert_equal 'Title 0', pm.title cd = create_claim_description project_media: pm, description: 'Title 1' assert_queries 0, '=' do assert_equal 'Title 1', pm.title end create_fact_check claim_description: cd, title: 'Title 2' assert_queries 0, '=' do assert_equal 'Title 1', pm.title end assert_queries(0, '>') do assert_equal 'Title 1', pm.reload.title(true) end end end test "should cache title for imported items" do RequestStore.store[:skip_cached_field_update] = false Sidekiq::Testing.inline! do t = create_team u = create_user create_team_user team: t, user: u, role: 'admin' with_current_user_and_team(u, t) do pm = ProjectMedia.create!( media: Blank.create!, team: t, user: u, channel: { main: CheckChannels::ChannelCodes::FETCH } ) cd = ClaimDescription.new cd.skip_check_ability = true cd.project_media = pm cd.description = '-' cd.user = u cd.save! fc_summary = 'fc_summary' fc_title = 'fc_title' fc = FactCheck.new fc.claim_description = cd fc.title = fc_title fc.summary = fc_summary fc.user = u fc.skip_report_update = true fc.save! assert_equal fc_title, pm.title assert_equal fc_summary, pm.description end end end test "should cache description" do RequestStore.store[:skip_cached_field_update] = false Sidekiq::Testing.inline! do pm = create_project_media quote: 'Description 0' assert_equal 'Description 0', pm.description cd = create_claim_description description: 'Description 1', project_media: pm assert_queries 0, '=' do assert_equal 'Description 1', pm.description end create_fact_check claim_description: cd, summary: 'Description 2' assert_queries 0, '=' do assert_equal 'Description 1', pm.description end assert_queries(0, '>') do assert_equal 'Description 1', pm.reload.description(true) end end end test "should index sortable fields" do RequestStore.store[:skip_cached_field_update] = false # sortable fields are [linked_items_count, last_seen and share_count] setup_elasticsearch create_annotation_type_and_fields('Smooch', { 'Data' => ['JSON', false] }) Rails.stubs(:env).returns('development'.inquiry) team = create_team p = create_project team: team pm = create_project_media team: team, project_id: p.id, disable_es_callbacks: false result = $repository.find(get_es_id(pm)) assert_equal 1, result['linked_items_count'] assert_equal pm.created_at.to_i, result['last_seen'] assert_equal pm.reload.last_seen, pm.read_attribute(:last_seen) t = t0 = create_dynamic_annotation(annotation_type: 'smooch', annotated: pm).created_at.to_i result = $repository.find(get_es_id(pm)) assert_equal t, result['last_seen'] assert_equal pm.reload.last_seen, pm.read_attribute(:last_seen) pm2 = create_project_media team: team, project_id: p.id, disable_es_callbacks: false r = create_relationship source_id: pm.id, target_id: pm2.id, relationship_type: Relationship.confirmed_type t = pm2.created_at.to_i result = $repository.find(get_es_id(pm)) result2 = $repository.find(get_es_id(pm2)) assert_equal 2, result['linked_items_count'] assert_equal 1, result2['linked_items_count'] assert_equal t, result['last_seen'] assert_equal pm.reload.last_seen, pm.read_attribute(:last_seen) t = create_dynamic_annotation(annotation_type: 'smooch', annotated: pm2).created_at.to_i result = $repository.find(get_es_id(pm)) assert_equal t, result['last_seen'] assert_equal pm.reload.last_seen, pm.read_attribute(:last_seen) r.destroy! result = $repository.find(get_es_id(pm)) assert_equal t0, result['last_seen'] assert_equal pm.reload.last_seen, pm.read_attribute(:last_seen) result = $repository.find(get_es_id(pm)) result2 = $repository.find(get_es_id(pm2)) assert_equal 1, result['linked_items_count'] assert_equal 1, result2['linked_items_count'] end test "should get team" do t = create_team pm = create_project_media team: t assert_equal t, pm.reload.team t2 = create_team pm.team = t2 assert_equal t2, pm.team assert_equal t, ProjectMedia.find(pm.id).team end test "should cache last_seen value" do RequestStore.store[:skip_cached_field_update] = false Sidekiq::Testing.inline! do team = create_team pm = create_project_media team: team t0 = pm.created_at.to_i # pm.last_seen should equal pm.created_at if no tipline request (aka 'smooch' annotation) assert_queries(0, '=') { assert_equal(t0, pm.last_seen) } t1 = create_dynamic_annotation(annotation_type: 'smooch', annotated: pm).created_at.to_i # pm.last_seen should equal pm smooch annotation created_at if item is not related assert_queries(0, '=') { assert_equal(t1, pm.last_seen) } pm2 = create_project_media team: team t2 = pm2.created_at.to_i # pm2.last_seen should equal pm2.created_at if no tipline request (aka 'smooch' annotation) assert_queries(0, '=') { assert_equal(t2, pm2.last_seen) } r1 = create_relationship source_id: pm.id, target_id: pm2.id, relationship_type: Relationship.confirmed_type # pm is now a parent and pm2 its child with no smooch annotation, so pm.last_seen should match pm2.created_at assert_queries(0, '=') { assert_equal(t2, pm.last_seen) } # adding a smooch annotation to pm2 should update parent last_seen t3 = create_dynamic_annotation(annotation_type: 'smooch', annotated: pm2).created_at.to_i assert_queries(0, '=') { assert_equal(t3, pm.last_seen) } # now let's add a second child pm3... pm3 = create_project_media team: team t4 = create_dynamic_annotation(annotation_type: 'smooch', annotated: pm3).created_at.to_i r2 = create_relationship source_id: pm.id, target_id: pm3.id, relationship_type: Relationship.confirmed_type # pm3.last_seen should equal pm3 smooch annotation created_at assert_queries(0, '=') { assert_equal(t4, pm3.last_seen) } assert_queries(0, '>') { assert_equal(t4, pm3.last_seen(true)) } # last_seen for each child item should be smooch annotation created_at of that single item assert_queries(0, '=') { assert_equal(t3, pm2.last_seen) } assert_queries(0, '>') { assert_equal(t3, pm2.last_seen(true)) } r1.destroy! r2.destroy! # last_seen of former parent should be restored to smooch annotation created_at after relationship is destroyed assert_queries(0, '=') { assert_equal(t1, pm.last_seen) } assert_queries(0, '>') { assert_equal(t1, pm.last_seen(true)) } # last_seen of former child should be unchanged after relationship is destroyed assert_queries(0, '=') { assert_equal(t3, pm2.last_seen) } assert_queries(0, '>') { assert_equal(t3, pm2.last_seen(true)) } end end end
# encoding: utf-8 require "rails_helper" describe RestaurantsAPI, :type => :request do # ============================================================================ context "Get restaurant reviews" do before :each do @user = create(:user) @restaurant_1 = create(:restaurant) @user.ensure_authentication_token! @request_headers = { 'HTTP_ACCEPT' => 'application/json', 'HTTP_CONTENT_TYPE' => 'application/json', 'HTTP_APIKEY' => API_KEY_ANDROID, 'HTTP_USERTOKEN' => @user.reload.authentication_token } end it "fail with wrong api key" do @request_headers["HTTP_APIKEY"] = Faker::Name.name get "/v1.2/restaurants/#{@restaurant_1.id}/reviews/list.json", nil, @request_headers output = JSON.parse(response.body) expect(output["success"]).to eq false expect(output["message"]).to eq I18n.t("service_api.errors.invalid_api_key") expect(output["error"]).to eq 401 end it "fail with wrong user token" do @request_headers["HTTP_USERTOKEN"] = Faker::Name.name get "/v1.2/restaurants/#{@restaurant_1.id}/reviews/list.json", nil, @request_headers output = JSON.parse(response.body) expect(output["success"]).to eq false expect(output["message"]).to eq I18n.t("service_api.errors.wrong_authentication_token") expect(output["error"]).to eq 600 end it "success with no reviews" do get "/v1.2/restaurants/#{@restaurant_1.id}/reviews/list.json", nil, @request_headers output = JSON.parse(response.body) expect(output["success"]).to eq true expect(output["message"]).to eq I18n.t("service_api.success.none_reviews") expect(output["data"]).to be_empty end it "success with list reviews" do request_params = { restaurant_id: @restaurant_1.id, service: 1, quality: 1, value: 1, content: 1, month: Time.now.month, year: Time.now.year, } review_ids = [] post "/v1.2/restaurants/#{@restaurant_1.id}/reviews/create.json", request_params, @request_headers output = JSON.parse(response.body) review = Review.last review.update_attributes(status: true) review_ids.push(review) post "/v1.2/restaurants/#{@restaurant_1.id}/reviews/create.json", request_params, @request_headers output = JSON.parse(response.body) review = Review.last review.update_attributes(status: true) review_ids.push(review) post "/v1.2/restaurants/#{@restaurant_1.id}/reviews/create.json", request_params, @request_headers output = JSON.parse(response.body) review = Review.last review.update_attributes(status: true) review_ids.push(review) post "/v1.2/restaurants/#{@restaurant_1.id}/reviews/create.json", request_params, @request_headers output = JSON.parse(response.body) review = Review.last review.update_attributes(status: true) review_ids.push(review) get "/v1.2/restaurants/#{@restaurant_1.id}/reviews/list.json", nil, @request_headers output = JSON.parse(response.body) expect(output["success"]).to eq true expect(output["message"]).to eq I18n.t("service_api.success.get_list_reviews") expect(output["data"]).not_to be_empty output["data"].each do |review| expect(review["id"]).not_to be_nil expect(review_ids).not_to include(review["id"].to_i) expect(review["content"]).not_to be_nil expect(review["service"]).not_to be_nil expect(review["quality"]).not_to be_nil expect(review["value"]).not_to be_nil expect(review["status"]).not_to be_nil expect(review["rating"]).not_to be_nil expect(review["user"]).not_to be_nil end end end end
require 'will_paginate/array' class Api::V1::PostsController < ApplicationController def index local_posts = Post.all.order(created_at: :desc).paginate(page: params[:page], per_page: 2) posts = local_posts.to_a posts << ::Gnews::GetPosts.new.call(query: 'watches').to_a.flatten.paginate(page: params[:page], per_page: 2) render json: posts.flatten end def create post = Post.create(post_params) if post render json: post else render json: post.errors end end def update if post.update(post_params) render json: post else render json: post.errors end end def show if post render json: post else render json: post.errors end end def destroy post&.destroy render json: { message: 'Post destroyed!' } end private def post_params params.permit(:title, :content, :description, :image) end def post local_post || remote_post end def local_post @local_post ||= Post.find_by(slug: params[:slug]) end def remote_post @remote_post ||= ::Gnews::GetPosts.new.call(query: 'watches').select do |post| post.slug == params[:slug] end.first end end
# frozen_string_literal: true # rubocop:todo all # Copyright (C) 2019-2020 MongoDB Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Mongo class Error < StandardError # A module encapsulating functionality to manage data attached to # exceptions in the driver, since the driver does not currently have a # single exception hierarchy root. # # @since 2.11.0 # @api private module Notable # Returns an array of strings with additional information about the # exception. # # @return [ Array<String> ] Additional information strings. # # @since 2.11.0 # @api public def notes if @notes @notes.dup else [] end end # @api private def add_note(note) unless @notes @notes = [] end if Lint.enabled? if @notes.include?(note) # The driver makes an effort to not add duplicated notes, by # keeping track of *when* a particular exception should have the # particular notes attached to it throughout the call stack. raise Error::LintError, "Adding a note which already exists in exception #{self}: #{note}" end end @notes << note end # Allows multiple notes to be added in a single call, for convenience. # # @api private def add_notes(*notes) notes.each { |note| add_note(note) } end # Returns connection pool generation for the connection on which the # error occurred. # # @return [ Integer | nil ] Connection pool generation. attr_accessor :generation # Returns service id for the connection on which the error occurred. # # @return [ Object | nil ] Service id. # # @api experimental attr_accessor :service_id # Returns global id of the connection on which the error occurred. # # @return [ Integer | nil ] Connection global id. # # @api private attr_accessor :connection_global_id # @api public def to_s super + notes_tail end private # @api private def notes_tail msg = '' unless notes.empty? msg += " (#{notes.join(', ')})" end msg end end end end
# encoding: BINARY require 'rubygems' require 'hexdump' require 'zlib' require 'digest' Encoding.default_external = 'BINARY' STATIC_HEADER = "gpak\x00\x0d\x0a\xa5" VERSION_NUMBER = "\x00\x00\x00\x01" EMPTY_TIMESTAMP = "\xff" * 8 EMPTY_CHECKSUM = "\x00" * 32 TYPE_DELTA = 0x08 TYPE_COMPRESSED = 0x10 TYPE_INVALID_MASK = 0xff ^ TYPE_COMPRESSED ^ TYPE_DELTA ^ 0x07 if ARGV.length < 1 || ARGV.length > 2 puts "Usage: read.rb globpack [hash to output]" exit end pack = File.open(ARGV[0]) globpack_name = File.basename(ARGV[0]) marked_object = [ARGV[1]].pack('H40') print "Reading scanned keys... " expected = [] scanned_file = File.new('scanned_keys.txt') scanned_file.each do |line| if match = line.match(/Expecting ([0-9a-f]{40}) at (\d+):(\d+)$/) expected << [match[3].to_i, [match[1]].pack('H40')] end end scanned_file.close print "Sorting... " expected.sort_by!(&:first) expected_index = 0 puts "Done." # Read and verify header (sans checksum, we'll do that later) header = pack.read(52) if header.length != 52 raise 'Unexpectedly short globpack/header' end if header[0..7] != STATIC_HEADER raise 'Bad globpack static header.' end if header[8..11] != VERSION_NUMBER raise 'Unknown globpack version.' end expected_length = header[12..19].unpack('Q>').first if File.size(pack) != expected_length # raise "Incorrect globpack length. (File said #{expected_length}, really was "+ # "#{File.size(pack)})" end expected_checksum = header[20..51] pos = 52 # Initialize checksum. Note that the checksum is computed with itself and the # size being masked (each in a different way) checksum_header = header.dup checksum_header[12..19] = EMPTY_TIMESTAMP checksum_header[20..51] = EMPTY_CHECKSUM checksum_digest = Digest::SHA256.new checksum_digest.update checksum_header deltas = 0 compressed = 0 objects = {} while not pack.eof? objpos = pos hash_data = pack.read(20) expected_obj = expected[expected_index] if expected_obj[1] != hash_data raise "Unexpected object at position #{pos}. Expected #{expected_obj[1].unpack('H40')[0]}, got #{hash_data.unpack('H40')[0]}." end if expected_obj[0] != pos raise "Unexpected position for object #{hash_data.unpack('H40')[0]}! Expected #{expected_obj[0]}, got #{pos}." end checksum_digest.update hash_data type = pack.read(1) checksum_digest.update type type = type.unpack('C').first pos += 21 if type & TYPE_INVALID_MASK > 0 raise "Unexpected type: #{type}" end if type & TYPE_DELTA > 0 # This is a delta, read a base object too. base = pack.read(20) checksum_digest.update(base) pos += 20 deltas += 1 end if type & TYPE_COMPRESSED > 0 compressed += 1 end # if type & 0x07 == 0x01 # puts "Commit: #{hash}" # end # Now read the stored data length continue = true offset = 0 length = 0 while continue byte = pack.read(1) checksum_digest.update(byte) byte = byte.unpack('C').first continue = byte & 0x80 == 0x80 length += (byte & 0x7f) << offset offset += 7 pos += 1 end objects[hash_data] = objpos compressed_data = pack.read(length) checksum_digest.update(compressed_data) pos += length if hash_data == marked_object puts "Marked object (#{hash_data.unpack('H40')[0]}):" puts " Position: #{objpos} (#{[objpos].pack('Q<').inspect})" puts " Type: 0x#{type.chr.unpack('H2')[0]}" if type & TYPE_COMPRESSED puts "Compressed data:" compressed_data.hexdump decompressed_data = Zlib::Inflate.new(-15).inflate(compressed_data) else decompressed_data = compressed_data end puts "Decompressed data:" decompressed_data.hexdump end end pack.close computed_checksum = checksum_digest.digest if expected_checksum != computed_checksum raise 'Checksum mismatch' else puts "Checksums match (#{computed_checksum} = #{expected_checksum})" end puts "#{objects.length} objects, #{deltas} deltas, #{compressed} compressed" to_insert = objects.map{|hash, loc| { id: r.binary(hash), loc: loc, file: globpack_name }}
# frozen_string_literal: true require 'rails_helper' RSpec.describe 'Workers - SQL Injection Report Producer', type: :feature do subject(:archive_api) { Departments::Archive::Api.instance } let(:legal_name) { 'Demo_1' } let(:legal_ip_address) { '79.181.31.4' } let(:friendly_resource) { archive_api.new_friendly_resource(legal_name, legal_ip_address) } let(:cyber_report_type) { Departments::Shared::AnalysisType::SQL_INJECTION_CYBER_REPORT } let(:sql_injection_positive_intelligence) { [ { 'uris' => ['DROP DATABASE test;', '/DROP DATABASE test;/'] }, { 'uris' => ['DROP DATABASE test;'] } ] } let(:sql_injection_negative_intelligence) { [ { 'uris' => ['name=one;', '/1/'] }, { 'uris' => ['DROP DATASE test;'] } ] } it 'Identifies SQL Injection when it is present' do archive_api.persist_friendly_resource(friendly_resource) sql_injection_positive_intelligence.each do |intelligence| Workers::Analysis::CodeInjection::Sql::CyberReportProducer.new.perform( friendly_resource.ip_address, cyber_report_type, intelligence ) end expect( archive_api.cyber_reports_by_friendly_resource_ip_and_type( friendly_resource.ip_address, cyber_report_type, 1, 2 ).size ).to eql(2) end it 'Does not identify SQL Injection when it is not present' do archive_api.persist_friendly_resource(friendly_resource) sql_injection_negative_intelligence.each do |intelligence| Workers::Analysis::CodeInjection::Sql::CyberReportProducer.new.perform( friendly_resource.ip_address, cyber_report_type, intelligence ) expect( archive_api.cyber_reports_by_friendly_resource_ip_and_type( friendly_resource.ip_address, cyber_report_type, 1, 2 ).size ).to eql(0) end end end
require 'spec_helper' describe Configuration do context "with all environment variables present" do before :each do ENV.stub(:[]).with("WEBEX_SITE_NAME").and_return("bakeryevents") ENV.stub(:[]).with("WEBEX_USERNAME").and_return("bakery") ENV.stub(:[]).with("WEBEX_PASSWORD").and_return("secret") ENV.stub(:[]).with("WEBEX_SITE_ID").and_return("358562") ENV.stub(:[]).with("WEBEX_PARTNER_ID").and_return("123ab") end it { Configuration.site_name.should == "bakeryevents" } it { Configuration.username.should == "bakery" } it { Configuration.password.should == "secret" } it { Configuration.site_id.should == "358562" } it { Configuration.partner_id.should == "123ab" } it { Configuration.xml_service_url.should == "https://bakeryevents.webex.com/WBXService/XMLService" } end end
ReleaseNotes::Engine.routes.draw do get '/' => 'release_notes#index' get '/:version' => 'release_notes#show', as: 'version' end
Factory.define :note do |note| note.sequence(:content) {|i| "Content #{i}"} end
class SnakesField def initialize(n) @number_of_snakes = n @snakes = [] (0..n).each do |i| pos_y = ((i*20)+i*20) s = SnakeSquare.new(x:0,y:pos_y,size:20,color:'red', dir:'right') @snakes << SnakeController.new([s]) end end def moveSnakes(key) @snakes.each {|s| s.nextMove(key)} end def moveSnakesWithTick(t) @snakes.each {|s| s.nextMoveWithTick(t)} end end
class ConditionsController < ApplicationController #->Prelang (scaffolding:rails/scope_to_user) before_filter :require_user_signed_in, only: [:new, :edit, :create, :update, :destroy] before_action :set_condition, only: [:show, :edit, :update, :destroy, :vote] # GET /conditions # GET /conditions.json def index @conditions = Condition.all end # GET /conditions/1 # GET /conditions/1.json def show end # GET /conditions/new def new @condition = Condition.new end # GET /conditions/1/edit def edit end # POST /conditions # POST /conditions.json def create @condition = Condition.new(condition_params) @condition.user = current_user respond_to do |format| if @condition.save format.html { redirect_to @condition, notice: 'Condition was successfully created.' } format.json { render :show, status: :created, location: @condition } else format.html { render :new } format.json { render json: @condition.errors, status: :unprocessable_entity } end end end # PATCH/PUT /conditions/1 # PATCH/PUT /conditions/1.json def update respond_to do |format| if @condition.update(condition_params) format.html { redirect_to @condition, notice: 'Condition was successfully updated.' } format.json { render :show, status: :ok, location: @condition } else format.html { render :edit } format.json { render json: @condition.errors, status: :unprocessable_entity } end end end # DELETE /conditions/1 # DELETE /conditions/1.json def destroy @condition.destroy respond_to do |format| format.html { redirect_to conditions_url, notice: 'Condition was successfully destroyed.' } format.json { head :no_content } end end #->Prelang (voting/acts_as_votable) def vote direction = params[:direction] # Make sure we've specified a direction raise "No direction parameter specified to #vote action." unless direction # Make sure the direction is valid unless ["like", "bad"].member? direction raise "Direction '#{direction}' is not a valid direction for vote method." end @condition.vote_by voter: current_user, vote: direction redirect_to action: :index end private # Use callbacks to share common setup or constraints between actions. def set_condition @condition = Condition.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def condition_params params.require(:condition).permit(:name, :item, :key, :order_count, :cur_count, :user_id) end end
require 'rspec' require './lib/invoice_repository' require './lib/sales_engine' require 'simplecov' SimpleCov.start RSpec.describe InvoiceRepository do before(:each) do @se = SalesEngine.from_csv({ :items => './spec/fixtures/item_mock.csv', :merchants => './spec/fixtures/merchant_mock.csv', :invoices => './spec/fixtures/invoices_mock.csv', :invoice_items => './spec/fixtures/invoice_items_mock.csv', :customers => './spec/fixtures/customers_mock.csv', :transactions => './spec/fixtures/transactions_mock.csv'}) @ir = InvoiceRepository.new('./spec/fixtures/invoices_mock.csv', @se) end describe 'instantiation' do it 'exists' do expect(@ir).to be_an_instance_of(InvoiceRepository) end it 'has readable attributes' do expect(@ir.invoices.count).to eq(0) expect(@ir.invoices).to eq([]) @ir.create_repo expect(@ir.invoices.count).to eq(30) expect(@ir.invoices[0].id).to eq(1) end end describe 'has a method that can' do it 'can create a repo' do expect(@ir.invoices.count).to eq(0) expect(@ir.invoices).to eq([]) @ir.create_repo expect(@ir.invoices.count).to eq(30) expect(@ir.invoices[20].id).to eq(21) end it 'can return all invoices' do @ir.create_repo expect(@ir.all.count).to eq(30) end it 'can find invoices by invoice id' do @ir.create_repo expect(@ir.find_by_id(20)).to be_an_instance_of(Invoice) expect(@ir.find_by_id(20).merchant_id).to eq(12334994) end it 'can find all invoices by customer by their id number' do @ir.create_repo expect(@ir.find_all_by_customer_id(15).count).to eq(3) expect(@ir.find_all_by_customer_id(11).count).to eq(6) end it 'can find all invoices by merchant by their id number' do @ir.create_repo expect(@ir.find_all_by_merchant_id(12334986).count).to eq(10) expect(@ir.find_all_by_merchant_id(12334159).count).to eq(2) end it 'can find all invoices by status' do @ir.create_repo expect(@ir.find_all_by_status('pending').count).to eq(11) expect(@ir.find_all_by_status('shipped').count).to eq(18) end it 'can create new invoices with readable attributes' do @ir.create_repo expect(@ir.all.count).to eq(30) @ir.create({ id: 31, created_at: Time.now.strftime("%Y-%m-%d"), updated_at: Time.now.strftime("%Y-%m-%d") }) expect(@ir.all.count).to eq(31) expect(@ir.all.last.id).to eq(31) end it 'can update existing invoices' do @ir.create_repo expect(@ir.find_by_id(15).status).to eq('shipped') @ir.update(15, {status: 'not shipped'}) expect(@ir.find_by_id(15).status).to eq('not shipped') end it 'can delete by id' do @ir.create_repo expect(@ir.all.count).to eq(30) expect(@ir.all.last.id).to eq(30) @ir.delete(30) expect(@ir.all.count).to eq(29) expect(@ir.all.last.id).to eq(29) end end end
# frozen_string_literal: true class AddRegionToPokemons < ActiveRecord::Migration[5.2] def change add_reference :pokemons, :region, foreign_key: true end end
class Topic < ApplicationRecord # # => Validation # => Column Value Validation # validates_presence_of :title # => Entity relationship has_many :blogs end
class SophityMailer < ApplicationMailer default from: "info@sophity.com" def sample_email(user) @user = user mail(to: @user.email, subject: 'Sophity HealthCheck Report') end end
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe CoberturasController do def mock_cobertura(stubs={}) @mock_cobertura ||= mock_model(Cobertura, stubs) end describe "GET index" do it "assigns all coberturas as @coberturas" do Cobertura.stub!(:find).with(:all).and_return([mock_cobertura]) get :index assigns[:coberturas].should == [mock_cobertura] end end describe "GET show" do it "assigns the requested cobertura as @cobertura" do Cobertura.stub!(:find).with("37").and_return(mock_cobertura) get :show, :id => "37" assigns[:cobertura].should equal(mock_cobertura) end end describe "GET new" do it "assigns a new cobertura as @cobertura" do Cobertura.stub!(:new).and_return(mock_cobertura) get :new assigns[:cobertura].should equal(mock_cobertura) end end describe "GET edit" do it "assigns the requested cobertura as @cobertura" do Cobertura.stub!(:find).with("37").and_return(mock_cobertura) get :edit, :id => "37" assigns[:cobertura].should equal(mock_cobertura) end end describe "POST create" do describe "with valid params" do it "assigns a newly created cobertura as @cobertura" do Cobertura.stub!(:new).with({'these' => 'params'}).and_return(mock_cobertura(:save => true)) post :create, :cobertura => {:these => 'params'} assigns[:cobertura].should equal(mock_cobertura) end it "redirects to the created cobertura" do Cobertura.stub!(:new).and_return(mock_cobertura(:save => true)) post :create, :cobertura => {} response.should redirect_to(cobertura_url(mock_cobertura)) end end describe "with invalid params" do it "assigns a newly created but unsaved cobertura as @cobertura" do Cobertura.stub!(:new).with({'these' => 'params'}).and_return(mock_cobertura(:save => false)) post :create, :cobertura => {:these => 'params'} assigns[:cobertura].should equal(mock_cobertura) end it "re-renders the 'new' template" do Cobertura.stub!(:new).and_return(mock_cobertura(:save => false)) post :create, :cobertura => {} response.should render_template('new') end end end describe "PUT update" do describe "with valid params" do it "updates the requested cobertura" do Cobertura.should_receive(:find).with("37").and_return(mock_cobertura) mock_cobertura.should_receive(:update_attributes).with({'these' => 'params'}) put :update, :id => "37", :cobertura => {:these => 'params'} end it "assigns the requested cobertura as @cobertura" do Cobertura.stub!(:find).and_return(mock_cobertura(:update_attributes => true)) put :update, :id => "1" assigns[:cobertura].should equal(mock_cobertura) end it "redirects to the cobertura" do Cobertura.stub!(:find).and_return(mock_cobertura(:update_attributes => true)) put :update, :id => "1" response.should redirect_to(cobertura_url(mock_cobertura)) end end describe "with invalid params" do it "updates the requested cobertura" do Cobertura.should_receive(:find).with("37").and_return(mock_cobertura) mock_cobertura.should_receive(:update_attributes).with({'these' => 'params'}) put :update, :id => "37", :cobertura => {:these => 'params'} end it "assigns the cobertura as @cobertura" do Cobertura.stub!(:find).and_return(mock_cobertura(:update_attributes => false)) put :update, :id => "1" assigns[:cobertura].should equal(mock_cobertura) end it "re-renders the 'edit' template" do Cobertura.stub!(:find).and_return(mock_cobertura(:update_attributes => false)) put :update, :id => "1" response.should render_template('edit') end end end describe "DELETE destroy" do it "destroys the requested cobertura" do Cobertura.should_receive(:find).with("37").and_return(mock_cobertura) mock_cobertura.should_receive(:destroy) delete :destroy, :id => "37" end it "redirects to the coberturas list" do Cobertura.stub!(:find).and_return(mock_cobertura(:destroy => true)) delete :destroy, :id => "1" response.should redirect_to(coberturas_url) end end end
a = (1930...1951).to_a puts a[rand(a.size)] *The numbers that will not be displayed are 1951 and 1952. They will not be displayed because (1930...1951) is an exclusive range, meaning the top end number that defines the range is not included in the range. The low end number is. In this case, 1930 - 1950 are the range's boundries.* (1930...1951) *Once that has been set, then you: <br>- expand the range out with the .to_a method <br>- determine the size of the array with a.size, which is 21 <br>- put forward a random number between 0 and 21 (not including 21) <br>- put the number that is in the array at the random numbers index*
module ApplicationHelper #here we'll have our master-list of answers, and the user's guess will be checked against that list. def check_answer(answer, quiztype) citylist = ["Atlanta","Asheville","Charlotte","Raleigh"] statelist = ["Alaska", "Hawaii", "Washington", "Oregon", "California", "Arizona", "Nevada", "Idaho", "Montana", "Utah", "New Mexico", "Colorado", "Wyoming", "North Dakota", "South Dakota", "Nebraska", "Kansas", "Oklahoma", "Texas", "Louisiana", "Arkansas", "Missouri", "Iowa", "Minnesota", "Wisconsin", "Illinois", "Indiana", "Ohio", "Michigan", "Kentucky", "Tennessee", "Mississippi", "Alabama", "Georgia", "Florida", "South Carolina", "North Carolina", "Virginia", "West Virginia", "Maryland", "Delaware", "Pennsylvania", "New Jersey", "New York", "Connecticut", "Rhode Island", "Massachusetts", "New Hampshire", "Vermont", "Maine"] #additional master-lists could be placed here. correct = false if quiztype == 'city' citylist.each do |c| if answer == c correct = true end end elsif quiztype == 'state' statelist.each do |s| if answer == s correct = true end end else correct = false #not great error handling for the case where the quiztype is wrong... but ok for now end return correct end #check to see if the answer, while although correct, may have already been guessed and put into the database of answers. def check_for_dup(answer,database) is_dup = false database.each do |d| if answer == d.name is_dup = true end end return is_dup end end
require_relative "lib/caesar_cipher" describe CaesarCipher do # ~> NoMethodError: undefined method `describe' for main:Object describe '#total_shift' do # a = 97, z = 122, A = 65, Z = 90 it 'shifts "a" correctly with a small shift factor' do caesar = CaesarCipher.new test = caesar.total_shift(97, 1) expect(test).to eq(1) # => end it 'shifts "A" correctly with a small shift factor' do caesar = CaesarCipher.new test = caesar.total_shift(65, 1) expect(test).to eq(1) end it 'shifts "z" correctly with a small shift factor' do caesar = CaesarCipher.new test = caesar.total_shift(122, 1) expect(test).to eq(-25) end it 'shifts "Z" correctly with a small shift factor' do caesar = CaesarCipher.new test = caesar.total_shift(90, 1) expect(test).to eq(-25) end it 'shifts "a" correctly with a large shift factor' do caesar = CaesarCipher.new test = caesar.total_shift(97, 53) expect(test).to eq(1) # => end it 'shifts "A" correctly with a large shift factor' do caesar = CaesarCipher.new test = caesar.total_shift(65, 53) expect(test).to eq(1) end it 'shifts "z" correctly with a large shift factor' do caesar = CaesarCipher.new test = caesar.total_shift(122, 53) expect(test).to eq(-25) end it 'shifts "Z" correctly with a large shift factor' do caesar = CaesarCipher.new test = caesar.total_shift(90, 53) expect(test).to eq(-25) end end describe '#encrypt' do it 'encrypts with small shift' do caesar = CaesarCipher.new test = caesar.encrypt("Hello",1) expect(test).to eq("Ifmmp") end it 'encrypts with large shift' do caesar = CaesarCipher.new test = caesar.encrypt("Hello",100) expect(test).to eq("Dahhk") end end end # >> "azAZ" # >> "zyZY" # ~> NoMethodError # ~> undefined method `describe' for main:Object # ~> # ~> caesar_cipher_spec.rb:3:in `<main>'
require 'digest/sha1' # Clase encargada de llevar un control de integridad sobre # el último archivo de copia de seguridad generado. class Backup < ActiveRecord::Base # Método que genera un nuevo Digest para una cadena, # que en éste caso corresponde al archivo de copia de # seguridad más reciente. def self.actualiza_hash(objeto) first = find(:first) digest = Digest::SHA1.hexdigest(objeto) if first.nil? create(:security_hash => digest) else first.update_attribute(:security_hash, digest) end end # Método que analiza si el archivo de copia de seguridad # que se va a incorporar a la base de datos actual # es consistente. def self.hash_es_el_mismo(objeto) first = find(:first) return true if first.nil? digest = Digest::SHA1.hexdigest(objeto) digest.eql? first.security_hash end end
class Snapshot < ActiveRecord::Base attr_accessible :category, :count, :item, :snapshot_date validates_presence_of :category, :count, :item, :snapshot_date def self.take_snapshot Member::MEMBER_TYPES.collect do |member_type| Snapshot.create(:category => "member type", :item => member_type, :count => Member.where(:member_type => member_type).count, :snapshot_date => Date.today) end Member::BILLING_PLANS.collect do |billing_plan| Snapshot.create(:category => "billing plan", :item => billing_plan, :count => Member.where(:billing_plan => billing_plan).count, :snapshot_date => Date.today) end end end
class AddStateFieldToTask < ActiveRecord::Migration def change add_column :tasks, :state, :string, null: false, default: 'inactive' end end
class Ability include Scholar::Ability::CollectionAbility include Hydra::Ability include Hyrax::Ability self.ability_logic += [:everyone_can_create_curation_concerns, :collection_abilities] self.admin_group_name = 'admin' def custom_permissions if admin? can [:destroy], ActiveFedora::Base can [:create, :show, :add_user, :remove_user, :index, :edit, :update, :destroy], Role can :manage, Zizia::CsvImport can :manage, Zizia::CsvImportDetail end if collection_manager? can :manage, ::Collection can :manage_any, ::Collection can :create_any, ::Collection can :view_admin_show_any, ::Collection end cannot :manage, ::Collection unless collection_manager? can :update, ContentBlock end def admin? user_groups.include? admin_group_name end def collection_manager? user_groups.any? { |x| ["collection_manager", "admin"].include?(x) } end end
class User < ApplicationRecord has_many :offers has_secure_password end
PlanSource::Application.routes.draw do get "signup_links/edit" authenticated :user do root :to => 'home#index' end root :to => "home#index" devise_for :users, skip: [:registrations] # We have to add the edit and update actions directly devise_scope :user do get '/users/edit' => 'devise/registrations#edit', as: :edit_user_registration put '/users' => 'devise/registrations#update', as: :update_user_registration end namespace :api do resources :jobs, except: ["new", "edit"], :as => :job post '/jobs/share_link' => 'jobs#sub_share_link' get '/jobs/:id/eligible_project_managers' => 'users#eligible_project_managers' get '/jobs/:id/eligible_shop_drawing_managers' => 'users#eligible_shop_drawing_managers' get '/jobs/:id/eligible_rfi_assignees' => 'users#eligible_rfi_assignees' get '/jobs/:id/eligible_shops_assignees' => 'users#eligible_shops_assignees' post '/jobs/:id/project_manager' => 'jobs#project_manager' post '/jobs/:id/shop_drawing_manager' => 'jobs#shop_drawing_manager' resources :plans, except: ["new", "edit", "index"] get '/plans/embedded/:id' => 'plans#show_embedded' get '/plans/records/:id' => 'plans#plan_records' post '/plans/records' => 'plan_records#batch_update' get '/user/contacts' => 'users#contacts' post '/user/contacts' => 'users#add_contacts' resources :shares, only: ["create", "destroy", "update"] post "/shares/batch" => "shares#batch" resource :token, only: ["create"] #only retrieve token match "/download/:id" => "downloads#download" match "/embed/:id" => "downloads#embed" post '/uploads/presign' => 'uploads#presign' post '/message' => 'messages#group' post '/message' => 'messages#group' post '/shops/:id/assign' => 'shops#assign' get '/submittals/:plan_id' => 'submittals#index' post '/submittals' => 'submittals#create' get '/submittals/download_attachment/:id' => 'submittals#download_attachment', as: :submittal_download_attachment post '/submittals/:id/destroy' => 'submittals#destroy' post '/submittals/:id' => 'submittals#update' post '/rfis' => 'rfis#create' put '/rfis/:id' => 'rfis#update' delete '/rfis/:id' => 'rfis#destroy' post '/rfis/:id/assign' => 'rfis#assign' get '/rfis/download_attachment/:id' => 'rfis#download_attachment', as: :rfi_download_attachment post '/asis' => 'asis#create' put '/asis/:id' => 'asis#update' delete '/asis/:id' => 'asis#destroy' post '/asis/:id/assign' => 'asis#assign' get '/asis/download_attachment/:id' => 'asis#download_attachment', as: :asi_download_attachment post '/photos/submit' => 'photos#submit_photos' get '/photos/download/:id' => 'photos#download_photo' post '/photos/:id/destroy' => 'photos#destroy' get '/jobs/:job_id/photos' => 'photos#show' get '/jobs/:job_id/renderings' => 'renderings#show' post '/photos/:id' => 'photos#update' #post '/troubleshoot' => 'troubleshoot#create' end get '/view' => 'pdf#index', as: "view_pdf" get '/photos/:id/gallery' => 'api/photos#gallery' get '/notifications/unsubscribe/:id' => 'notification#unsubscribe', as: :unsubscribe get '/app#/jobs/:id' => 'home#index', as: :jobs_link get '/jobs/:id/share' => 'api/jobs#show_sub_share_link' get '/share_link/company_name' => 'api/jobs#share_link_company_name' post '/share_link/company_name' => 'api/jobs#set_share_link_company_name', as: "set_share_link_company_name" # Download share link get '/d/:token' => 'api/plans#download_share_link', as: "download_share_link" resources :users, only: ["index", "edit", "update", "destroy"] do member do post :batch_shares end end get "/users/:id/demote" => "users#demote", as: "demote" get "/users/signup_link/:key", to: "signup_links#edit", as: "signup_link" put "/users/signup_link/:key", to: "signup_links#update" get "/print/asi/:id" => "print#asi", as: :print_asi get "/reports" => "reports#index", as: :reports post "/reports/shop_drawings" => "reports#shop_drawings", as: :shop_drawings_report get "/reports/shop_drawings/jobs" => "reports#shop_drawing_jobs", as: :shop_drawings_report_jobs get "/reports/rfi_asis/jobs" => "reports#rfi_asi_jobs", as: :rfi_asis_report_jobs post "/reports/rfi_asis" => "reports#rfi_asis", as: :rfi_asis_report get "/admin/sub_logins" => "admin#sub_logins" delete "/admin/sub_logins/:id" => "admin#delete_sub_login", as: "delete_sub_login" resources :emails, only: [:index, :create] get "emails/download" => "emails#download" match "/mobile" => "mobile#index" match "/app" => "app#index" end
class PostsController < ApplicationController before_action :require_user_logged_in before_action :correct_user, only: [:destroy] def create @post = Post.new(post_params) if @post.save flash[:success] = '書き込み成功しました。' #@post.order(@post.topic) redirect_to topic_path(@post.topic_id) else flash[:danger] = '書き込みに失敗しました。' redirect_to topic_path(@post.topic_id) end end def destroy Post.find(params[:id]).destroy flash[:success] = 'メッセージを削除しました。' redirect_back(fallback_location: root_path) end private def post_params params.require(:post).permit(:topic_id, :name, :content, :user_id) end def correct_user @posts = current_user.posts.find_by(id: params[:id]) unless @posts redirect_to root_url end end end
class AddBackgroundColumnsToUspages < ActiveRecord::Migration def self.up add_column :us_pages, :us_background_file_name, :string add_column :us_pages, :us_background_content_type, :string add_column :us_pages, :us_background_file_size, :integer add_column :us_pages, :us_background_updated_at, :datetime end def self.down remove_column :us_pages, :us_background_file_name remove_column :us_pages, :us_background_content_type remove_column :us_pages, :us_background_file_size remove_column :us_pages, :us_background_updated_at end end
module ChatGPT module_function def last_ask = @last_ask def last_response = @last_response def last_chat_data = @last_chat_data def client @client ||= OpenAI::Client.new end def ask(str) @last_ask = str response = client.chat( parameters: { model: "gpt-3.5-turbo", # Required. messages: [{ role: "user", content: str }], # Required. } ) @last_chat_data = response @last_response = response.dig("choices", 0, "message", "content") end def short_name_from_order(order_title) prompt = "In one or two words but less than 20 characters, summarize the following:" ask("#{prompt} #{order_title}") end def order_with_timestamp(email_text) now = Time.current.in_time_zone(User.timezone) res = ask( "Assuming today is #{now}, respond with nothing but the order id and the" \ " expected delivery timestamp formatted in iso8601 from the following email: #{email_text}" ) # "Order ID: 111-3842886-2135464\nExpected Delivery Timestamp: 2023-07-25T22:00:00-0600" [ res.match(/Order ID: ([\d\-]+)/).to_a[1], res.match(/Expected Delivery Timestamp: (\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}-\d{4})/).to_a[1], ] # ["111-3842886-2135464", "2023-07-25T22:00:00-0600"] end end
class ShoppingCart #attr_accessor :products def initialize @products = [] @my_items = { "apple" => 10, "orange" => 5, "grape" => 15, "banana" => 20, "watermelon" => 50 } end def add (item) @products << item end def getprice(item) @my_items[item] puts @my_items[item] end def cost price=0 @products.each do |element| price= price + getprice(element) end return price end def discount end end cart = ShoppingCart.new cart.add("apple") cart.add("banana") puts cart.cost()
#! /usr/bin/env ruby -S rspec require 'spec_helper' describe 'the dns_lookup function' do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it 'should exist' do expect(Puppet::Parser::Functions.function('dns_lookup')).to eq('function_dns_lookup') end it 'should raise a ArgumentError if there is less than 1 arguments' do expect { scope.function_dns_lookup([]) }.to raise_error(ArgumentError) end it 'should return a list of addresses when doing a lookup for a single record' do results = scope.function_dns_lookup(['google.com']) expect(results).to be_a Array results.each do |res| # Horrible regex that matches both IPv4 and v6 addresses expect(res).to match(/^([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}|([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/) end end it 'should return a list of addresses when doing a lookup for multiple records' do results = scope.function_dns_lookup(['google.com']) expect(results).to be_a Array results.each do |res| expect(res).to match(/^([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}|([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/) end end it 'should raise an error on empty reply' do expect { scope.function_dns_lookup(['foo.example.com']) }.to raise_error(Resolv::ResolvError) end end
class CreateCourseInvites < ActiveRecord::Migration def change create_table :course_invites do |t| t.string :token, null: false t.references :course t.timestamps null: false end add_index :course_invites, :token, unique: true end end
# This lecture covers having a zoo (an array of all our animals) class Animal attr_accessor :color, :name def initialize( name, color ) @color = color @name = name end def identify return "I am a #{self.class}" end def speak return "hello my name is #{@name}" end end class Tiger < Animal # We can use super to add on/inhereit from the class above def speak return super + " grrrr" end end class Zebra < Animal attr_reader :stripes def initialize( name, color, stripes ) @stripes = stripes super(name, color) end end class Hyena < Animal end # Main Program zoo = [] 10.times do | num | zoo << Zebra.new( "Zebra#{num}", "black and white", rand(20..100) ) end zoo.each do | animal | puts "#{animal.speak} #{animal.color} #{animal.stripes}" end zoo.select! do | zebra | zebra.stripes > 50 end puts zoo.count
# -*- coding: utf-8 -*- # # EpisoDASデータをもとに単一HTMLを生成 # # % ruby expand.rb Amazon_masui {seed} > Amazon.html # require 'erb' require 'uri' require "base64" def get_file(file) File.read "/home/masui/EpisoPass/public#{file}" end def expand_js(js) '<script type="text/javascript">' + js + '</script>' end def expand name = @name seed = if @seed then "'#{@seed}'" else 'null' end # Data URI schemeで背景画像を作成 bg_image = get_file('/images/exclusive_paper.gif') bg_encoded = Base64.encode64(bg_image).gsub("\n",'') fav_image = get_file('/images/favicon.png') fav_encoded = Base64.encode64(fav_image).gsub("\n",'') data_json = readdata(@name) jquery_js = get_file('/javascripts/jquery.js') episodas_js = get_file('/javascripts/episodas.js') md5_js = get_file('/javascripts/md5.js') crypt_js = get_file('/javascripts/crypt.js') ERB.new(<<EOF).result(binding) <!-- name: <%= name %> seed: <%= seed %> data: <%= data_json %> --> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"> <meta name="full-screen" content="yes"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-title" content="EpisoPass"> <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent"> <link rel="icon" type="image/png" href="data:image/png;base64,<%= fav_encoded %>"> <title><%= @name %></title> <style type="text/css"> body { background-image: url("data:image/gif;base64,<%= bg_encoded %>"); } div { font-family: sans-serif } span { font-family: sans-serif } </style> <script type="text/javascript"> const data = <%= data_json %>; const name = '<%= name %>'; const seed = <%= seed %> ? <%= seed %> : data['seed']; </script> <%= expand_js(jquery_js) %> <%= expand_js(episodas_js) %> <%= expand_js(md5_js) %> <%= expand_js(crypt_js) %> </head> <body> </body> </html> EOF end
module Super module Codecs class TimeCodec def decode(value) return unless value value.is_a?(Time) ? value : Time.iso8601(value) rescue ArgumentError raise Super::Errors::DecodeError, "#{value} as #{value.class}" end def encode(entity) return unless entity raise Super::Errors::EncodeError, entity unless entity.is_a?(Time) entity.iso8601 end end end end
class RpgsController < ApplicationController def index set_session_defaults end def gamble building = params[:building] gold = calculate_gold building activity = build_activity building, gold update_session gold, activity redirect_to :back end private def calculate_gold building amounts = { farm: [10, 20], cave: [5, 10], house: [2, 5], casino: [-50, 50] } values = amounts[building.to_sym] rand(values[0]..values[1]) end def build_activity building, gold activity = {} time = Time.now.in_time_zone('Central Time (US & Canada)').strftime('%b %d, %Y, %l:%M') if gold >= 0 activity[:color] = 'green' activity[:message] = "Earned #{gold} golds from the #{building} #{time}" else activity[:color] = 'red' activity[:message] = "Entered a casino and lost #{gold} golds... Ouch... #{time}" end return activity end def set_session_defaults session[:gold] ||= 0 session[:activities] ||= [] end def update_session gold, activity session[:gold] += gold session[:activities].unshift activity return end end
# Add your own tasks in files placed in lib/tasks ending in .rake, # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. require File.expand_path('../config/application', __FILE__) Rails.application.load_tasks def variant ENV['RAILS_ENV'] || 'development' end desc "prepares db and assets" task :prepare do Rake::Task["db:setup"].invoke Rake::Task["db:migrate"].invoke Rake::Task["db:seed"].invoke Rake::Task["assets:clean"].invoke Rake::Task["assets:precompile"].invoke end desc "runs rails server" task :serve do sh "rails s -b 0.0.0.0 -e #{variant}" end desc "runs all tests in spec folder" task :test do sh "rspec" end
module Steppable extend ActiveSupport::Concern included do has_many :steps, -> {where(:deleted => false).order(step_no: :asc)}, :as => :steppable, :inverse_of => 'steppable' accepts_nested_attributes_for :steps end def step_at(step_no) steps.find{|s| s.step_no.to_i == step_no.to_i} end end
# Application template recipe for the rails_apps_composer. Change the recipe here: # https://github.com/RailsApps/rails_apps_composer/blob/master/recipes/tests4.rb after_bundler do say_wizard "recipe running after 'bundle install'" ### RSPEC ### if prefer :tests, 'rspec' say_wizard "recipe installing RSpec" run 'rm -rf test/' # Removing test folder (not needed for RSpec) generate 'rspec:install' inject_into_file '.rspec', "--format documentation\n", :after => "--color\n" gsub_file 'spec/spec_helper.rb', /ActiveRecord::Migration.check_pending! if defined?(ActiveRecord::Migration)/, "ActiveRecord::Migration.maintain_test_schema!" inject_into_file 'config/application.rb', :after => "Rails::Application\n" do <<-RUBY config.generators do |g| g.test_framework :rspec, fixtures: true, view_specs: false, helper_specs: false, routing_specs: false, controller_specs: false, request_specs: false g.fixture_replacement :factory_girl, dir: "spec/factories" end RUBY end ### Configure Launchy to display CSS and JavaScript create_file 'spec/support/capybara.rb', "Capybara.asset_host = 'http://localhost:3000'\n" ### Configure Database Cleaner to test JavaScript gsub_file 'spec/spec_helper.rb', /config.use_transactional_fixtures = true/, "config.use_transactional_fixtures = false" create_file 'spec/support/database_cleaner.rb' do <<-RUBY RSpec.configure do |config| config.before(:suite) do DatabaseCleaner.clean_with(:truncation) end config.before(:each) do DatabaseCleaner.strategy = :transaction end config.before(:each, :js => true) do DatabaseCleaner.strategy = :truncation end config.before(:each) do DatabaseCleaner.start end config.append_after(:each) do DatabaseCleaner.clean end end RUBY end ### Configure FactoryGirl for shortcuts create_file 'spec/support/factory_girl.rb' do <<-RUBY RSpec.configure do |config| config.include FactoryGirl::Syntax::Methods end RUBY end ## RSPEC AND DEVISE if prefer :authentication, 'devise' # add Devise test helpers create_file 'spec/support/devise.rb' do <<-RUBY RSpec.configure do |config| config.include Devise::TestHelpers, :type => :controller end RUBY end end end ### GUARD if prefer :continuous_testing, 'guard' say_wizard "recipe initializing Guard" run 'bundle exec guard init' end ### GIT ### git :add => '-A' if prefer :git, true git :commit => '-qm "rails_apps_composer: testing framework"' if prefer :git, true end # after_bundler after_everything do say_wizard "recipe running after everything" # copy tests from repos here end # after_everything __END__ name: tests4 description: "Add testing framework." author: RailsApps requires: [setup, gems] run_after: [setup, gems] category: testing
class ChangeTypeNameToKind < ActiveRecord::Migration def change rename_column :marks, :type, :kind end end
class AddOptionsToOrders < ActiveRecord::Migration def change remove_column :orders, :options add_column :orders, :options, :hstore end end
class Product attr_reader :title, :price, :barcode, :manufacturer, :code, :generate_control attr_writer :barcode, :code def initialize(hash) self.title = hash["title"].to_s if(hash["price"].nil?) fail SimpleStore::Error, "O preço do produto deve ser >= 0.0" else self.price = hash["price"].to_f end @barcode = hash["barcode"] @manufacturer_code = hash["manufacturer_code"] c = SimpleStore::AUTHORIZED_MANUFACTURERS self.manufacturer = c.key(@manufacturer_code) c2 = SimpleStore::PRODUCT_TYPES self.generate_control = c2[self.class.name.to_sym] @code = generate_control_code end def title=(new_title) if(new_title != "" && !new_title.nil?) @title = new_title else fail SimpleStore::Error, "O título do produto não pode ser vazio" end end def price=(new_price) if(new_price >= 0) @price = new_price else fail SimpleStore::Error, "O preço do produto deve ser >= 0.0" end end def manufacturer=(new_manufacturer) if(new_manufacturer != nil) @manufacturer = new_manufacturer else fail SimpleStore::Error, "O fabricante não está autorizado" end end def generate_control=(new_generate_control) #if(new_generate_control != nil) @generate_control = new_generate_control #else #fail SimpleStore::Error, "O produto não está autorizado" #end end private def generate_control_code "#{@generate_control}--#{@manufacturer_code}--#{@barcode}" end end class SimpleStore PRODUCT_TYPES = { :Product => 0, :DigitalProduct => 1, :FreshProduct => 2, :PhysicalProduct => 3 } AUTHORIZED_MANUFACTURERS = { # Digital products :OReillyMedia => 0, :Microsoft => 1, # Physical products :Sony => 2, :Apple => 3, :Unilever => 4, # Fresh products :ProdutosMaeTerra => 5, :PlanetaOrganico => 6, :SaborNatural => 7 } class Error < RuntimeError; end end class A def initialize(hash) puts hash[self.class.name] end end
class HighScore < ActiveRecord::Base validates :user, presence: true validates :game, presence: true validates :score, presence: true, numericality: {greater_than_or_equal_to: 0} end
class HangpersonGame # add the necessary class methods, attributes, etc. here # to make the tests in spec/hangperson_game_spec.rb pass. # Get a word from remote "random word" service # def initialize() # end attr_accessor :word attr_accessor :guesses attr_accessor :wrong_guesses def initialize(word) @word = word @guesses = "" @wrong_guesses = "" @@number_of_guesses=0 end def self.get_random_word require 'uri' require 'net/http' uri = URI('http://watchout4snakes.com/wo4snakes/Random/RandomWord') Net::HTTP.post_form(uri ,{}).body end def guess(letter) @@number_of_guesses+=1 raise ArgumentError, "Entered nil" if letter.nil? i=0 correct=false letter=letter.downcase raise ArgumentError, 'Nothing inserted' if letter.length==0 raise ArgumentError, 'Not a valid letter' unless letter =~ /[[:alpha:]]/ if letter==@guesses return false end if letter == @wrong_guesses return false end while i<word.length if word[i].match(letter) correct=true @guesses = @guesses+letter end i+=1 end if correct==false @wrong_guesses = letter end return true end def word_with_guesses() i=0 display_word="" puts self.guesses @word.length.times { display_word=display_word+"-" } while i<@guesses.length j=0 while j<@word.length if @word[j]==@guesses[i] display_word[j]=@guesses[i] end j+=1 end i+=1 end return display_word end def check_win_or_lose() puts self.guesses current_word = self.word_with_guesses() if current_word==@word return :win elsif @@number_of_guesses>6 return :lose else return :play end end end
class ApplicationController < ActionController::Base include PagesHelper protect_from_forgery with: :exception # def render_404 # render file: "#{Rails.root}/public/404", layout: false, status: 404 # end unless Rails.application.config.consider_all_requests_local rescue_from Exception, with: -> (exception) { render_500 exception } rescue_from ActionController::RoutingError, ActionController::UnknownController, ::AbstractController::ActionNotFound, ActiveRecord::RecordNotFound, with: -> (exception) { render_error 404, exception } end private def render_500(exception) ExceptionNotifier::Notifier.exception_notification(request.env, exception).deliver render_error 500, exception end def render_error(status, _exception) respond_to do |format| format.html do render file: "#{Rails.root}/public/#{status}", layout: false, status: status end format.all { render nothing: true, status: status } end end end
require_relative 'game' require_relative 'piece' require_relative 'cursor' require_relative 'chars_array' require_relative 'plane_like' require_relative 'chess_clock' require_relative 'checkers_errors' require_relative 'symbol' require 'colorize' class Board include PlaneLike include CheckersErrors COLORS = [:red, :black] attr_reader :cursor, :prev_pos, :clock, :upgrade_cursor attr_accessor :end_of_turn, :takens def initialize @rows = Array.new(8) { Array.new(8) } place_pieces @cursor = Cursor.new @prev_pos = nil @end_of_turn = false @clock = ChessClock.new @takens = [[],[]] end def click(turn) pos = cursor.pos if self.prev_pos.nil? self.prev_pos = pos unless self[pos].nil? || self[pos].color != turn else begin move(self.prev_pos, pos, turn) rescue CheckersError self.prev_pos = nil # clicked in a bad spot so resets end end end def select_only_legal_piece(turn) selectables = self.pieces(turn).reject { |piece| piece.jump_moves.empty? } if selectables.count == 1 self.prev_pos = selectables[0].pos cursor.pos = prev_pos end end def selected_piece self[self.prev_pos] unless self.prev_pos.nil? end def opposite(color) color == COLORS[0] ? COLORS[1] : COLORS[0] end def take(start, end_pos) taken_piece_pos = middle(start, end_pos) taken_piece = self[taken_piece_pos] self[taken_piece_pos] = nil taken_box = ( taken_piece.color == :red ? takens[0] : takens[1] ) taken_box << taken_piece end def jump(start, end_pos, color) self.take(start, end_pos) if self[end_pos].jump_moves.empty? self.end_of_turn = true self.prev_pos = nil else # For double-jumps self.end_of_turn = false self.prev_pos = end_pos end end def slide(start, end_pos, color) self.end_of_turn = true self.prev_pos = nil #deselects cursor #probably should rename end def move(start, end_pos, color) raise_move_errors(start, end_pos, color) moved_piece = self[start] moved_piece.move(end_pos) unless moved_piece.is_a?(King) || !moved_piece.at_end? moved_piece = King.new(self, moved_piece.color, moved_piece.pos) end if jump?(start, end_pos) jump(start, end_pos, color) else slide(start, end_pos, color) end end def jump?(pos1, pos2) (pos1[0] - pos2[0]).abs == 2 && (pos1[1] - pos2[1]).abs == 2 end def cursor_move(sym,turn) if sym == :" " self.click(turn) elsif sym == :o return :title_mode else cursor.scroll(sym) end :board_mode end def dup duped = Board.new 8.times do |y| rows[y].each_with_index do |piece, x| duped[[y,x]] = nil # Have to do this bc place_pieces unless self[[y,x]].nil? duped[[y,x]] = piece.class.new(duped,piece.color,[y, x]) end end end duped end def pieces(color) self.rows.flatten.compact.select { |piece| piece.color == color } end def display(turn) puts render(turn) end def middle(pos1, pos2) [(pos1[0] + pos2[0]) / 2, (pos1[1] + pos2[1]) / 2] end protected attr_writer :prev_pos private attr_accessor :mode def taken_pieces(color) color == :red ? takens[0] : takens[1] end def place_pieces # kinda illegible 8.times do |col| rows[col % 2][col] = Piece.new(self, :black, [col % 2, col]) rows[2][(2 * col) % 8] = Piece.new(self, :black, [2, (2 * col) % 8]) rows[6 + (col % 2)][col] = Piece.new(self, :red, [6 + (col % 2), col]) rows[5][(2 * col +1) % 8] = Piece.new(self, :red, [5, (2 * col + 1) % 8]) end end def render(turn) characters_array = CharsArray.new(self, turn).rows.map white_chars = takens[0].render.sort black_chars = takens[1].render.sort str = '' str << white_chars.drop(8).join << "\n" str << white_chars.take(8).join << "\n" characters_array.each do |row| row.each { |char| str << char } str << "\n" end str << black_chars.take(8).join << "\n" str << black_chars.drop(8).join << "\n" str << "Red Current Time: #{clock.convert_times[0]} \t" << "Red Total Time: #{clock.convert_times[1]}\n" << "Black Current Time: #{clock.convert_times[2]} \t" << "Black Total Time: #{clock.convert_times[3]}" str end end
class BlogsTagsController < ApplicationController # GET /blogs_tags # GET /blogs_tags.xml before_filter :check_login_status def index @blogs_tags = BlogsTag.all respond_to do |format| format.html # index.html.erb format.xml { render :xml => @blogs_tags } end end # GET /blogs_tags/1 # GET /blogs_tags/1.xml def show @blogs_tag = BlogsTag.find(params[:id]) respond_to do |format| format.html # show.html.erb format.xml { render :xml => @blogs_tag } end end # GET /blogs_tags/new # GET /blogs_tags/new.xml def new @blogs_tag = BlogsTag.new respond_to do |format| format.html # new.html.erb format.xml { render :xml => @blogs_tag } end end # GET /blogs_tags/1/edit def edit @blogs_tag = BlogsTag.find(params[:id]) end # POST /blogs_tags # POST /blogs_tags.xml def create @blogs_tag = BlogsTag.new(params[:blogs_tag]) respond_to do |format| if @blogs_tag.save format.html { redirect_to(@blogs_tag, :notice => 'Blogs tag was successfully created.') } format.xml { render :xml => @blogs_tag, :status => :created, :location => @blogs_tag } else format.html { render :action => "new" } format.xml { render :xml => @blogs_tag.errors, :status => :unprocessable_entity } end end end # PUT /blogs_tags/1 # PUT /blogs_tags/1.xml def update @blogs_tag = BlogsTag.find(params[:id]) respond_to do |format| if @blogs_tag.update_attributes(params[:blogs_tag]) format.html { redirect_to(@blogs_tag, :notice => 'Blogs tag was successfully updated.') } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @blogs_tag.errors, :status => :unprocessable_entity } end end end # DELETE /blogs_tags/1 # DELETE /blogs_tags/1.xml def destroy @blogs_tag = BlogsTag.find(params[:id]) @blogs_tag.destroy respond_to do |format| format.html { redirect_to(blogs_tags_url) } format.xml { head :ok } end end end
class CreateFeeds < ActiveRecord::Migration def change create_table :feeds do |t| t.string :provider t.datetime :date t.boolean :unread, :default => true t.string :image t.string :title t.string :url t.text :description t.integer :subscription_id t.timestamps end add_index :feeds, :subscription_id end end
require 'test_helper' class PlaceTest < ActiveSupport::TestCase fixtures :users test 'each place can return the weather' do place = Place.new( favorite_memory: 'going to the beach', image_url: 'http://www.example.com/res.png', location: 'philly', visit_length: '1 week', user_id: users(:one).id ) place.save weather = place.get_weather assert weather[:description], 'weather description exists.' assert weather[:temperature], 'temperature exists.' assert weather[:icon_url], 'icon url exists.' assert_equal weather[:status], 200, 'a valid location returns status code 200.' end test 'an invalid location returns status 0' do place = Place.new( favorite_memory: 'going to the beach', image_url: 'http://www.example.com/res.png', location: '', visit_length: '1 week', user_id: users(:one).id ) place.save weather = place.get_weather assert_not_equal weather[:status], 200, 'an invalid location returns default status' end test 'an image url returns an error' do place = Place.new( favorite_memory: 'going to the beach', image_url: 'http://www.example.com', location: 'California', visit_length: '1 week', user_id: users(:one).id ) place.save assert place.invalid?, 'url must end in image extension.' assert_equal ["Image must be a URL for GIF, JPG or PNG image. For example: http://cruiseweb.com/admin/Images/image-gallery/rainbow-falls-hawaii.jpg"], place.errors[:image_url] end end
require_relative "Board.rb" class Game attr_accessor :board def initialize @board = Board.new turn end def turn @board.view_current_grid while !won? get_guesses end end def get_guesses count = 0 guess1 = [] guess2 = [] while count < 2 print "Please enter the position of the card you'd like to flip (e.g. '2 3')" pos = gets.chomp guess = pos.split(" ") if valid?(guess) x,y = guess[0].to_i, guess[1].to_i if count == 0 guess1 = [x,y] @board.working[x][y] = @board.grid[x][y] @board.view_current_grid count +=1 elsif count == 1 guess2 = [x,y] @board.working[x][y] = @board.grid[x][y] @board.view_current_grid count +=1 end end end if !match?(guess1,guess2) @board.working[guess1[0]][guess1[1]] = '_' @board.working[guess2[0]][guess2[1]] = '_' sleep 2.0 system("clear") @board.view_current_grid end guess1 = [] guess2 = [] count = 0 end def valid?(guess) values = [0,1,2,3] if values.include?(guess[0].to_i) && values.include?(guess[1].to_i) true else false print "This is not a valid guess. Please try again." end end def match?(guess1,guess2) if @board.working[guess1[0]][guess1[1]] == @board.working[guess2[0]][guess2[1]] print("It's a match! \n") true else print("Not a match \n") false end end def won? @board.grid.flatten.include?('_') end end g = Game.new
module TrackingNumberValidator class Service VALIDATORS = [ DHLValidator, FedExGroundValidator ] def self.detect(tracking_number) tracking_number ||= "" tracking_number = sanitize(tracking_number) VALIDATORS.each do |validator| validator = validator.new(tracking_number) return validator.name if validator.valid? end nil end private def self.sanitize(tracking_number) tracking_number[/\d+/] || "" end end end
class JobOrder < ActiveRecord::Base belongs_to :company has_and_belongs_to_many :employees, :join_table => "employee_job_orders" validates :name, presence: true, length: {in: 1..25} end
module Api class WorkingSetController < ApplicationApiController def create @working_set = WorkingSet.new working_set_params if @working_set.valid? @working_set.save! end end def working_set_params params.require(:working_set).permit(:real_reps, :predicted_reps, :real_weight, :predicted_weight) end end end
class HiringCompany < ActiveRecord::Base has_many :job_listings accepts_nested_attributes_for :job_listings, :allow_destroy => true acts_as_list has_attached_file :logo, :styles => {:thumb => '200x200'} validates_attachment_content_type :logo, :content_type => /image/ default_scope { order('position ASC') } end
class Cpufetch < Formula desc "CPU architecture fetching tool" homepage "https://github.com/Dr-Noob/cpufetch" url "https://github.com/Dr-Noob/cpufetch/archive/v1.00.tar.gz" sha256 "2254c2578435cc35c4d325b25fdff4c4b681de92cbce9a7a36e58ad58a3d9173" license "MIT" head "https://github.com/Dr-Noob/cpufetch.git", branch: "master" bottle do sha256 cellar: :any_skip_relocation, arm64_big_sur: "a9261597d5753e1946399243d1a678ad734d04583769a7c44471f7ce9618cc82" sha256 cellar: :any_skip_relocation, big_sur: "79a1430cf484b5af27898f13a6cbfa50c45c704b114dc1422f033f540b9c9fdf" sha256 cellar: :any_skip_relocation, catalina: "38e7cd730de97b753d3c1cbf342d132c62dbc914e9ec17f775e55c2e8d78ad1a" sha256 cellar: :any_skip_relocation, mojave: "790d979cab962161c6b4e372f67f11c756f9f2f1404f39f61997d64a5dd1215e" sha256 cellar: :any_skip_relocation, x86_64_linux: "88d4ed1abfb99807493c94f56ed01f1274763c3db9e747c4cdc2bf383e5c40a1" end def install system "make" bin.install "cpufetch" man1.install "cpufetch.1" end test do actual = shell_output("#{bin}/cpufetch -d").each_line.first.strip expected = if OS.linux? "cpufetch v#{version} (Linux #{Hardware::CPU.arch} build)" elsif Hardware::CPU.arm? "cpufetch v#{version} (macOS ARM build)" else "cpufetch is computing APIC IDs, please wait..." end assert_equal expected, actual end end
# encoding: utf-8 # copyright: 2016, you # license: All rights reserved # date: 2016-09-16 # description: The Microsoft Internet Explorer 11 Security Technical Implementation Guide (STIG) is published as a tool to improve the security of Department of Defense (DoD) information systems. Comments or proposed revisions to this document should be sent via e-mail to the following address: disa.stig_spt@mail.mil # impacts title 'V-46807 - AutoComplete feature for forms must be disallowed.' control 'V-46807' do impact 0.5 title 'AutoComplete feature for forms must be disallowed.' desc 'This AutoComplete feature suggests possible matches when users are filling in forms. It is possible that this feature will cache sensitive data and store it in the users profile, where it might not be protected as rigorously as required by organizational policy. If you enable this setting, the user is not presented with suggested matches when filling in forms. If you disable this setting, the user is presented with suggested possible matches when filling forms. If you do not configure this setting, the user has the freedom to turn on the auto-complete feature for forms. To display this option, the user opens the Internet Options dialog box, clicks the "Contents" tab, and clicks the "Settings" button.' tag 'stig', 'V-46807' tag severity: 'medium' tag checkid: 'C-49899r2_chk' tag fixid: 'F-50557r1_fix' tag version: 'DTBI690-IE11' tag ruleid: 'SV-59673r1_rule' tag fixtext: 'Set the policy value for User Configuration -> Administrative Templates -> Windows Components -> Internet Explorer -> Disable AutoComplete for forms to Enabled.' tag checktext: 'The policy value for User Configuration -> Administrative Templates -> Windows Components -> Internet Explorer -> Disable AutoComplete for forms must be Enabled. Procedure: Use the Windows Registry Editor to navigate to the following key: HKCU\Software\Policies\Microsoft\Internet Explorer\Main Criteria: If the value "Use FormSuggest" is REG_SZ = no, this is not a finding.' # START_DESCRIBE V-46807 describe registry_key('HKCU\Software\Policies\Microsoft\Internet Explorer\Main') do its('Use FormSuggest') { should eq 'no' } end # STOP_DESCRIBE V-46807 end
class Item < ActiveRecord::Base scope :with_tag, ->(tag){ Item.all.select{|i| i.tags.include?(tag)}} end
class ChangeCommentToRestaurants < ActiveRecord::Migration def up change_column :Restaurants, :comment, :text end #変更前の型 def down change_column :Restaurants, :comment, :string end end
class AddFinishedToResolutions < ActiveRecord::Migration def change add_column :resolutions, :finished, :boolean end end
# # 1. Use the "each" method of Array to iterate over [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], and print out each value. # arr = [1,2,3,4,5,6,7,8,9,10] arr.each do |element| puts element end # Convention for Rubyist (does the same as above) arr.each { |element| puts element } # Alternative way [1,2,3,4,5,6,7,8,9,10].each { |element| puts element } arr2 = [1,2,3,4,5,6,7,8,9,10] # # 2. Same as above, but only print out values greater than 5. # arr2.each do |element| if element > 5 puts element end end # # 3. Now, using the same array from #2, use the "select" method to extract all odd numbers into a new array. # arr3 = [1,2,3,4,5,6,7,8,9,10] new_arr3 = arr3.select do |e| e % 2 != 0 # e.odd? is another option end puts new_arr3 # # 4. Append "11" to the end of the array. Prepend "0" to the beginning. # and # 5. Get rid of "11". And append a "3". # arr4 = [1,2,3,4,5,6,7,8,9,10] gets rid of 11 arr4 << 11 arr4.unshift(0) appends 199 arr4.pop arr4 << 199 puts arr4 # 6. Get rid of duplicates without specifically removing any one value. puts arr6.uniq puts arr6 # 7. What's the major difference between an Array and a Hash? # => Hash does not guarantee order; array is. # => Hash has key values # 8. Create a Hash using both Ruby 1.8 and 1.9 syntax. # => Suppose you have a h = {a:1, b:2, c:3, d:4} # 9. Get the value of key "b". h[:b] # 10. Add to this hash the key:value pair {e:5} h[:e] = 5 # 13. Remove all key:value pairs whose value is less than 3.5 h.delete_if{|k, v| v < 3.5} # 14. Can hash values be arrays? Can you have an array of hashes? (give examples) # yes, hash values can be arrays; yes # => [{a: 1, b: 2, etc}, {}, {}] # 15. Look at several Rails/Ruby online API sources and say which one your like best and why. # => For Ruby API's I prefer http://www.ruby-doc.org/ because it is very easy to navigate # => It also gives you a brief explaination of a method and an example, so you can easily understand. # # => As for Rails, http://api.rubyonrails.org/ and http://railsapi.com/ look pretty good, but # => since we won;t get to it until next course, i won't know yet.
module Sluggable extend ActiveSupport::Concern included do before_create :set_slug validates :slug, uniqueness: { case_sensitive: false } scope :from_param, -> param { find_by(slug: param) } end def to_param self.slug end private def set_slug number = 1 begin self.slug = self.name.parameterize self.slug += "-#{number}" if number > 1 number += 1 end while self.class.where(slug: self.slug).exists? end end
require 'rails_helper' include SessionTimeoutWarningHelper include ActionView::Helpers::DateHelper feature 'Sign in' do scenario 'user cannot sign in if not registered' do signin('test@example.com', 'Please123!') expect(page).to have_content t('devise.failure.not_found_in_database') end scenario 'user cannot sign in with wrong email' do user = create(:user) signin('invalid@email.com', user.password) expect(page).to have_content t('devise.failure.not_found_in_database') end scenario 'user cannot sign in with empty email' do signin('', 'foo') expect(page).to have_content t('devise.failure.invalid') end scenario 'user cannot sign in with empty password' do signin('test@example.com', '') expect(page).to have_content t('devise.failure.invalid') end scenario 'user cannot sign in with wrong password' do user = create(:user) signin(user.email, 'invalidpass') expect(page).to have_content t('devise.failure.invalid') end scenario 'user can see and use password visibility toggle', js: true do visit new_user_session_path find('#pw-toggle-0', visible: false).trigger('click') expect(page).to have_css('input.password[type="text"]') end scenario 'user session expires in amount of time specified by Devise config' do sign_in_and_2fa_user visit account_path expect(current_path).to eq account_path Timecop.travel(Devise.timeout_in + 1.minute) visit account_path expect(current_path).to eq root_path Timecop.return end scenario 'user session cookie has no explicit expiration time (dies with browser exit)' do sign_in_and_2fa_user expect(session_cookie.expires).to be_nil end context 'session approaches timeout', js: true do before :each do allow(Figaro.env).to receive(:session_check_frequency).and_return('1') allow(Figaro.env).to receive(:session_check_delay).and_return('2') allow(Figaro.env).to receive(:session_timeout_warning_seconds). and_return(Devise.timeout_in.to_s) sign_in_and_2fa_user visit root_path end scenario 'user sees warning before session times out' do expect(page).to have_css('#session-timeout-msg') request_headers = page.driver.network_traffic.flat_map(&:headers).uniq ajax_headers = { 'name' => 'X-Requested-With', 'value' => 'XMLHttpRequest' } expect(request_headers).to include ajax_headers expect(page).to have_content('7:59') expect(page).to have_content('7:58') end scenario 'user can continue browsing' do find_link(t('notices.timeout_warning.signed_in.continue')).trigger('click') expect(current_path).to eq account_path end scenario 'user has option to sign out' do click_link(t('notices.timeout_warning.signed_in.sign_out')) expect(page).to have_content t('devise.sessions.signed_out') expect(current_path).to eq new_user_session_path end end context 'user only signs in via email and password', js: true do it 'displays the session timeout warning with partially signed in copy' do allow(Figaro.env).to receive(:session_check_frequency).and_return('1') allow(Figaro.env).to receive(:session_check_delay).and_return('2') allow(Figaro.env).to receive(:session_timeout_warning_seconds). and_return(Devise.timeout_in.to_s) user = create(:user, :signed_up) sign_in_user(user) visit user_two_factor_authentication_path expect(page).to have_css('#session-timeout-msg') expect(page).to have_content(t('notices.timeout_warning.partially_signed_in.continue')) expect(page).to have_content(t('notices.timeout_warning.partially_signed_in.sign_out')) end end context 'signed out' do it 'refreshes the current page after session expires', js: true do allow(Devise).to receive(:timeout_in).and_return(1) visit sign_up_email_path(request_id: '123abc') fill_in 'Email', with: 'test@example.com' expect(page).to have_content( t('notices.session_cleared', minutes: Figaro.env.session_timeout_in_minutes) ) expect(page).to have_field('Email', with: '') expect(current_url).to match Regexp.escape(sign_up_email_path(request_id: '123abc')) end it 'does not refresh the page after the session expires', js: true do allow(Devise).to receive(:timeout_in).and_return(60) visit root_path expect(page).to_not have_content( t('notices.session_cleared', minutes: Figaro.env.session_timeout_in_minutes) ) end end context 'signing back in after session timeout length' do before do ActionController::Base.allow_forgery_protection = true end after do ActionController::Base.allow_forgery_protection = false end it 'fails to sign in the user, with CSRF error' do user = sign_in_and_2fa_user click_link(t('links.sign_out'), match: :first) Timecop.travel(Devise.timeout_in + 1.minute) do expect(page).to_not have_content(t('forms.buttons.continue')) # Redis doesn't respect Timecop so expire session manually. session_store.send(:destroy_session_from_sid, session_cookie.value) fill_in_credentials_and_submit(user.email, user.password) expect(page).to have_content t('errors.invalid_authenticity_token') fill_in_credentials_and_submit(user.email, user.password) expect(current_path).to eq login_two_factor_path(otp_delivery_preference: 'sms') end end it 'refreshes the page (which clears the form) and notifies the user', js: true do allow(Devise).to receive(:timeout_in).and_return(1) user = create(:user) visit root_path fill_in 'Email', with: user.email fill_in 'Password', with: user.password expect(page).to have_content( t('notices.session_cleared', minutes: Figaro.env.session_timeout_in_minutes) ) expect(find_field('Email').value).to be_blank expect(find_field('Password').value).to be_blank end end describe 'session timeout configuration' do it 'uses delay and warning settings whose sum is a multiple of 60' do expect((start + warning) % 60).to eq 0 end it 'uses frequency and warning settings whose sum is a multiple of 60' do expect((frequency + warning) % 60).to eq 0 end end context 'user attempts too many concurrent sessions' do scenario 'redirects to home page with error' do user = user_with_2fa perform_in_browser(:one) do sign_in_live_with_2fa(user) expect(current_path).to eq account_path end perform_in_browser(:two) do sign_in_live_with_2fa(user) expect(current_path).to eq account_path end perform_in_browser(:one) do visit account_path expect(current_path).to eq new_user_session_path expect(page).to have_content(t('devise.failure.session_limited')) end end end context 'attribute_encryption_key is changed but queue does not contain any previous keys' do it 'throws an exception and does not overwrite User email' do email = 'test@example.com' password = 'salty pickles' create(:user, :signed_up, email: email, password: password) user = User.find_with_email(email) encrypted_email = user.encrypted_email rotate_attribute_encryption_key_with_invalid_queue expect { signin(email, password) }. to raise_error Pii::EncryptionError, 'unable to decrypt attribute with any key' user = User.find_with_email(email) expect(user.encrypted_email).to eq encrypted_email end end context 'KMS is on and user enters incorrect password' do it 'redirects to root_path with user-friendly error message, not a 500 error' do allow(FeatureManagement).to receive(:use_kms?).and_return(true) stub_aws_kms_client_invalid_ciphertext allow(SessionEncryptorErrorHandler).to receive(:call) user = create(:user) signin(user.email, 'invalid') expect(current_path).to eq root_path expect(page).to have_content t('devise.failure.invalid') end end context 'invalid request_id' do it 'allows the user to sign in and does not try to redirect to any SP' do allow(FeatureManagement).to receive(:prefill_otp_codes?).and_return(true) user = create(:user, :signed_up) visit new_user_session_path(request_id: 'invalid') fill_in_credentials_and_submit(user.email, user.password) click_submit_default expect(current_path).to eq account_path end end end
require 'digest/md5' class User < ActiveRecord::Base # Validation for the password has_secure_password before_validation :prep_email #prepara el correo antes de validarlo before_save :create_avatar_url #crea el hash md5 antes de guardarlo ya que se puede dar el caso de que actualizan algun dato del correo. #validates :email, presence: true, uniqueness: true, format: { with: /^[\w\.+-]+@([\w]+\.)+\A[a-zA-Z]*\z+$/} validates :email, presence: true, uniqueness: true, format: { with: /@/ } validates :username, presence: true, uniqueness: true validates :name, presence: true validates :last_name, presence: true private # Toma el correo que se ha introducido y lo prepara. self.email, luego con el .strip le quita los espacios # en blanco que tenga por delante y por detras y luego lo pone en minuscula con el .downcase def prep_email self.email = self.email.strip.downcase if self.email end # Crea un avatar utilizando el correo y el servicio en el sitio que se antecede. def create_avatar_url self.avatar_url = "http://www.gravatar.com/avatar/#{Digest::MD5.hexdigest(self.email)}?s=50" end end