text
stringlengths
10
2.61M
class AdditionalFile < ActiveRecord::Base def uploaded_file=(data_file_field) self.additional_file_name = File.basename(data_file_field.original_filename) self.additional_data_file = data_file_field.read end end
require_relative 'foreman' build "Array" do craft "#assoc" do nails = ["common", "duplex", "drywall", "spikes"] screws = ["wood", "metal", "masonry", "timber"] anchors = "flat" fasteners = [nails, screws, anchors] assert_equal fasteners.assoc("wood"), __ assert_equal fasteners.assoc("flat"), __ end craft "#at" do tools = ["saw", "hammer", "gripper"] assert_equal tools.at(1), __ assert_equal tools.at(-1), __ end craft "#clear" do materials = ["cement", "pebble", "tar"] assert_equal materials.clear, __ end craft "#compact" do roofs = ["pitched roof", nil, "sheed roof", nil] assert_equal roofs.compact, __ end craft "#concat and #+" do nails = ["common", "duplex"] screws = ["wood", "metal"] assert_equal nails.concat(["drywall", "spikes"]), __ assert_equal screws + ["masonry"], __ end craft "#delete" do workers = [ "allen", "sam", "hans", "davis"] assert_equal workers.delete("allen"), __ assert_equal workers, __ assert_equal workers.delete("jimmy"), __ assert_equal workers.delete("harris") { "is not here!" }, __ assert_equal workers.delete("tom") { |name| "#{name} is not here!" }, __ end craft "#delete_at" do lunches = ["sandwich", "burger", "pasta"] assert_equal lunches.delete_at(1), __ assert_equal lunches.delete_at(5), __ end craft "#delete_if" do truck = ["full", "blank"] assert_equal truck.delete_if {|s| s == "full" }, __ assert_equal truck, __ end craft "#drop" do bricks = [1, 2, 3, 4, 5, 6, 7] assert_equal bricks.drop(2), __ end craft "#drop_while" do sizes = [1, 2, 3, 4, 5, 6, 17, 18, 19] assert_equal sizes.drop_while {|s| s > 6 }, __ end craft "#empty?" do boiler = [] hole = [nil, nil] assert_equal boiler.empty?, __ assert_equal hole.empty?, __ end craft "#eql?" do tools = ["hammer", "axt"] toolbox = ["chisel", "screwdriver"] more_tools = ["hammer", "axt"] assert_equal tools.eql?(toolbox), __ assert_equal tools.eql?(more_tools), __ end craft "#fetch" do dimensions = [11, 22, 33, 44] assert_equal dimensions.fetch(0), __ assert_equal dimensions.fetch(-2), __ assert_equal dimensions.fetch(5, 'hello?'), __ assert_equal dimensions.fetch(5) {|d| "#{d} index not exist!" }, __ assert_raises __ do dimensions.fetch(18) end end craft "#fill" do screws = ["wood", "metal", "masonry", "timber"] assert_equal screws.fill("gone"), __ assert_equal screws.fill("gone", 1, 2), __ assert_equal screws.fill("gone", 0..2), __ assert_equal screws.fill {|x| x * 2 }, __ assert_equal screws.fill(-2) {|x| x * 2 }, __ end craft "#index #find_index" do tools = ["borer", "grinder"] assert_equal tools.index("borer"), __ assert_equal tools.index("sawing"), __ assert_equal tools.index {|x| x == "grinder" }, __ end craft "#first" do cars = ["digger", "crane", "truck", "van"] assert_equal cars.first, __ assert_equal cars.first(2), __ end craft "#flatten" do layers = [1, 2, 3, [1, 2, 3, [1, 2, 3]]] assert_equal layers.flatten, __ assert_equal layers.flatten(1), __ end craft "#include?" do colors = ["red", "blue", "green"] assert_equal a.include?("blue"), __ assert_equal a.include?("yellow"), __ end craft "#replace" do numbers = [1, 2, 3, 4, 5] assert_equal numbers.replace([77, 88, 99]), __ assert_equal numbers, __ end craft "#insert" do screws = ["wood", "metal", "masonry"] assert_equal screws.insert(1, "stone"), __ assert_equal screws.insert(-3, "timber", "stainless"), __ end craft "#join" do tools = ["to", "ol", "s"] assert_equal tools.join, __ assert_equal tools.join("*"), __ end craft "#keep_if" do lunches = ["sandwich", "burger", "pasta"] assert_equal lunches.keep_if {|l| l =~ /(urg)/ }, __ end craft "#last" do cars = ["digger", "crane", "truck", "van"] assert_equal cars.last, __ assert_equal cars.last(2), __ end craft "#pop" do nails = ["common", "duplex", "drywall", "spikes"] assert_equal nails.pop, __ assert_equal nails.pop(2), __ assert_equal nails, __ end craft "#push" do nails = ["common", "duplex"] assert_equal nails.push("drywall", "spikes"), __ end craft "#rassoc" do workers = [[31, "allen"], [30, "sam"], [40, "hans"], [51, "davis"]] assert_equal workers.rassoc("sam"), __ assert_equal workers.rassoc("tom"), __ end craft "#reverse" do screws = ["wood", "metal", "masonry"] assert_equal screws.reverse, __ end craft "#rotate" do numbers = [1, 2, 3, 4, 5, 6] assert_equal numbers.rotate, __ assert_equal numbers.rotate(2), __ assert_equal numbers.rotate(-1), __ end craft "#select" do cars = ["digger", 22, "truck", "van", 33, 49] assert_equal cars.select {|c| c =~ /[aeiou]/}, __ end craft "#shift" do materials = ["cement", "pebble", "tar", "wood"] assert_equal materials.shift, __ assert_equal materials.shift(2), __ end craft "#sort" do workers = ["tom", "cleve", "andrew", "billy"] assert_equal workers.sort, __ assert_equal workers.sort { |x, y| x <=> y }, __ end craft "#uniq" do screws = ["wood", "wood", "masonry", "masonry", "timber", "timber"] cars = ["1:truck", "1:digger", "2:van"] assert_equal screws.uniq, __ assert_equal cars.uniq { |c| c[/^\d+/] }, __ end craft "#unshift" do materials = ["cement", "pebble", "tar", "wood"] assert_equal materials.unshift("tar"), __ assert_equal materials.unshift("77","grass"), __ end craft "#values_at" do colors = ["red", "blue", "yellow", "gray", "cyan"] assert_equal colors.values_at(0, 2, 3), __ assert_equal colors.values_at(-1, 3), __ assert_equal colors.values_at(2..3, 0...7), __ assert_equal colors.values_at(3), __ end end
# frozen_string_literal: true require_relative './ast_base.rb' class FunctionCallNode < ASTBase def debug_print(level) identifier = children_of_type(IdentifierToken).first arguments = @children - [identifier] arguments_string = arguments.map { |a| a.debug_print(level + 1) }.join("\n") pad = ("\t" * level) "#{pad}FunctionCall\n#{identifier.debug_print(level+1)}\n#{arguments_string}" end def to_s "FunctionCall(#{@children}, args: [#{children}])" end def execute(context) identifier = children_of_type(IdentifierToken).first arguments = @children - [identifier] function = context.find_function(identifier.value) raise "Unknown function `#{identifier.value}` called - aw heck" unless function raise "We don't have wholesomelang functions yet" unless function.respond_to?(:call) function.call(context, arguments.map(&:value)) end end
require 'spec_helper' require_relative '../../lib/image_comparator' describe ImageComparator do let(:comparator) {ImageComparator.new} context 'when images are the same' do it 'should find no differences' do file_path = File.join(Dir.pwd, 'spec', 'images', 'doge.png') expect(comparator.match?(file_path, file_path)).to be_truthy end end context 'when images differs' do let(:doge_path) {File.join(Dir.pwd, 'spec', 'images', 'doge.png')} let(:doge_text_path) {File.join(Dir.pwd, 'spec', 'images', 'doge_text.png')} let(:result_path) {File.join(Dir.pwd, 'spec', 'images', 'diff-doge-doge_text.png')} after do FileUtils.rm(result_path) end it 'should find some diffences' do expect(comparator.match?(doge_path, doge_text_path)).to be_falsey end it 'should save a diff image' do comparator.match?(doge_path, doge_text_path) expect(File.file?(result_path)).to be_truthy end end end
class HomepageController < ApplicationController def show @top_rated = TopItem.highest_rated(3) @most_visited_conversations = Conversation.get_top_visited(3) @conversations = Conversation.order("created_at DESC").paginate(:page => params[:page], :per_page => 12) @main_article = Article.homepage_main_article.first @sub_articles = Article.homepage_sub_articles.limit(3) @regions = Region.all @recent_items = TopItem.newest_items(3).with_items_and_associations.collect(&:item) end end
require 'rails_helper' RSpec.feature 'signs in flow' do before do @user = create(:user) @profile = create(:profile, user_id: @user.id ) end scenario 'User signs in with correct credentials' do given_the_login_page_is_open when_user_fills_in_login_form and_click_on_log_in then_user_is_redirected_to_home_page end scenario 'User signs in with incorrect credentials' do given_the_login_page_is_open when_user_fills_in_incorectly_login_form and_click_on_log_in then_user_is_redirected_to_signin_page end def given_the_login_page_is_open visit new_user_session_path end def when_user_fills_in_login_form fill_in "Email", with: @user.email fill_in "Password", with: @user.password end def when_user_fills_in_incorectly_login_form fill_in "Email", with: 'philippe' fill_in "Password", with: @user.password end def and_click_on_log_in click_button 'Log in' end def then_user_is_redirected_to_home_page expect(page.current_path).to eq root_path end def then_user_is_redirected_to_signin_page expect(page.current_path).to eq "/users/sign_in" end end
module Dota module API class Entity include Utilities::Inspectable attr_reader :raw def initialize(raw) @raw = raw end end end end
class FriendsSerializer < ActiveModel::Serializer type 'friends' link(:next) { api_v1_friends_url(object.next_page_params) } has_many :users, :serializer => FriendUserSerializer def id scope.uid end def users object.users end end
class AddIndexToTables < ActiveRecord::Migration def change # admin_users add_index :admin_users, :login_name, :unique => true # countries add_index :countries, :name_ja, :unique => true add_index :countries, :name_en, :unique => true # flavors add_index :flavors, :name, :unique => true # product_categories add_index :product_categories, :name, :unique => true # product_contents add_index :product_contents, :name add_index :product_contents, :product_id # product_images add_index :product_images, :product_id add_index :product_images, :product_image_uid, :unique => true # product_types add_index :product_types, :name, :unique => true # products add_index :products, :name # providers add_index :providers, :name add_index :providers, :url, :unique => true # review_contents add_index :review_contents, :review_id, :unique => true # review_images add_index :review_images, :review_id add_index :review_images, :product_id add_index :review_images, :user_id add_index :review_images, :review_image_uid, :unique => true # reviews add_index :reviews, :product_id add_index :reviews, :user_id # shop_images add_index :shop_images, :shop_id add_index :shop_images, :shop_image_uid, :unique => true # shop_reviews add_index :shop_reviews, :shop_id add_index :shop_reviews, :user_id # shops add_index :shops, :country_id add_index :shops, :state_id add_index :shops, :name, :unique => true # state add_index :states, :name, :unique => true add_index :states, :code, :unique => true # user add_index :users, :nickname, :unique => true add_index :users, :facebook_uid, :unique => true add_index :users, :email, :unique => true end end
class AlterPetsChangeColumn < ActiveRecord::Migration[5.0] def change remove_column :pets, :animal_id, :integer remove_column :pets, :longitue, :float add_column :pets, :longitude, :float add_column :pets, :race_id, :integer add_column :pets, :situation_id, :integer end end
# typed: false # frozen_string_literal: true # This file was generated by GoReleaser. DO NOT EDIT. class Nv < Formula desc "Lightweight utility to load context specific environment variables" homepage "https://github.com/jcouture/nv" version "2.1.1" on_macos do if Hardware::CPU.arm? url "https://github.com/jcouture/nv/releases/download/2.1.1/nv_2.1.1_darwin_arm64.tar.gz" sha256 "edb88d8f9077b5c2fb304a2226b27a3422664f211e3403342ba3079d75055664" def install bin.install "nv" end end if Hardware::CPU.intel? url "https://github.com/jcouture/nv/releases/download/2.1.1/nv_2.1.1_darwin_amd64.tar.gz" sha256 "3ce370bfc4910f44a78661fec232c3bc64b60eee673ce511a54fb068be7482cd" def install bin.install "nv" end end end on_linux do if Hardware::CPU.arm? && !Hardware::CPU.is_64_bit? url "https://github.com/jcouture/nv/releases/download/2.1.1/nv_2.1.1_linux_armv6.tar.gz" sha256 "f726df8eb7e080a4667bef0311e0f95d923078978a9ff44ca19077eee269b721" def install bin.install "nv" end end if Hardware::CPU.intel? url "https://github.com/jcouture/nv/releases/download/2.1.1/nv_2.1.1_linux_amd64.tar.gz" sha256 "f22a4863bd4163097fef15fbe78ab42cd0eaa6677874710bb34e5dc6d559a6fe" def install bin.install "nv" end end if Hardware::CPU.arm? && Hardware::CPU.is_64_bit? url "https://github.com/jcouture/nv/releases/download/2.1.1/nv_2.1.1_linux_arm64.tar.gz" sha256 "f1eb45a93319a7761ccaad1d7d485cce7e4a93263926a6ca783f7bc116a79a40" def install bin.install "nv" end end end test do system "#{bin}/nv" end end
require 'rails_helper' RSpec.describe Ability, type: :model do subject { Ability.new(user) } let(:user) { FactoryGirl.create(:user) } it { should be_able_to(:manage, Paper.new(user: user)) } it { should be_able_to(:read, FactoryGirl.create(:user)) } it { should be_able_to(:edit, user) } it { should be_able_to(:read, Activity.new) } context "when is an admin" do let(:user) { FactoryGirl.create(:user, is_admin: true) } it { should be_able_to(:read, Paper.new) } end end
class ProductSerializer < ActiveModel::Serializer attributes :id, :product_name, :product_image, :product_description, :created_at, :styles def styles customized_styles = [] object.styles.each do |style| custom_style = style.attributes custom_style[:inventory] = style.inventories.where("product_id":object.id) customized_styles << custom_style end customized_styles end end
class AddDraftNumberToGoals < ActiveRecord::Migration def change add_column :goals, :draft_number, :integer end end
module Api class UsersController < Api::BaseController before_action :doorkeeper_authorize! respond_to :json def index @users = User.all render json: @users end private def user_params params.require(:user).permit(:email, :password_hash, :password_salt) end def query_params params.permit(:email) end end end
class Api::OptionsController < ApplicationController def index @brands = Brand.all.pluck(:name) @categories = Category.all.pluck(:name) end end
# frozen_string_literal: true class User < ActiveRecord::Base include Exceptions include LogWrapper include Oauth # Include default devise modules. Others available are: # :confirmable, :lockable, and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, # this handles uniqueness of email automatically :timeoutable # adds session["warden.user.user.session"]["last_request_at"] which we use in sessions_controller # Makes getters and setters attr_accessor :password # Validation's for email and pin only occurs when a user record is being # created on sign up. Does not occur when updating # the record. validates :first_name, :last_name, :presence => true validates_format_of :first_name, :last_name, :with => /\A[^0-9`!@;#$%\^&*+_=\x00-\x19]+\z/ validates_format_of :alt_email,:with => Devise::email_regexp, :allow_blank => true, :allow_nil => true validates :alt_email, uniqueness: true, allow_blank: true, allow_nil: true # validate :validate_password_pattern, on: :create # PASSWORD_FORMAT = /\A(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[[:^alnum:]])/x validate :validate_email_pattern, :on => :create has_many :holds belongs_to :school # # Set default password if one is not set # before_validation(on: :create) do # self.password ||= User.default_password # self.password_confirmation ||= User.default_password # end STATUS_LABELS = {'barcode_pending' => 'barcode_pending', 'complete' => 'complete'}.freeze ## NOTE: Validation methods, including this one, are called twice when # making new user from the admin interface. While not a behavior we want, # it doesn't currently pose a problem. def validate_email_pattern if (!defined?(email) || email.blank? || !email.index('@')) errors.add(:email, ' is required and should end in @schools.nyc.gov or another participating school address') return false end email.downcase.strip allowed_email_patterns = AllowedUserEmailMasks.where(active:true).pluck(:email_pattern) index = email.index('@') if (index && (allowed_email_patterns.include? email[index..])) return true else errors.add(:email, 'should end in @schools.nyc.gov or another participating school address') return false end end def barcode_found_in_sierra # Getter for flag that reflects whether there's a user or users in Sierra # that correspond(s) to this user object in MLN db. # NOTE: The barcode_found_in_sierra is not guaranteed to accurately reflect # user sync status, until after you've called check_barcode_uniqueness_with_sierra. if @barcode_found_in_sierra.blank? return false end return @barcode_found_in_sierra end # We don't require passwords, so just create a generic one, yay! def self.default_password "mylibrarynyc" end def name(full = false) handle = self.email.sub /@.*/, '' name = self.first_name name += " #{self.last_name}" if full && !self.last_name.nil? && !self.last_name.empty? name.nil? ? handle : name end def contact_email !self.alt_email.nil? && !self.alt_email.empty? ? self.alt_email : self.email end # Enable login by either email or alt_email (DOE email and contact email, respectively) def self.find_first_by_auth_conditions(warden_conditions) conditions = warden_conditions.dup if login = conditions.delete(:email) where(conditions).where(["lower(email) = :value OR lower(alt_email) = :value", { :value => login.downcase }]).first else where(conditions).first end end def multiple_barcodes? !self.alt_barcodes.nil? && !self.alt_barcodes.empty? end def send_unsubscribe_notification_email UserMailer.unsubscribe(self).deliver end def assign_barcode LogWrapper.log('DEBUG', { 'message' => "Begin assigning barcode to #{self.email}", 'method' => "assign_barcode", 'status' => "start", 'user' => {email: self.email} }) last_user_barcode = User.where('barcode < 27777099999999').order(:barcode).last.barcode self.assign_attributes({ barcode: last_user_barcode + 1}) LogWrapper.log('DEBUG', { 'message' => "Barcode has been assigned to #{self.email}", 'method' => "assign_barcode", 'status' => "end", 'barcode' => "#{self.barcode}", 'user' => {email: self.email} }) return self.barcode end # Sends a request to the patron creator microservice. # Passes patron-specific information to the microservice s.a. name, email, and type. # The patron creator service creates a new patron record in the Sierra ILS, and comes back with # a success/failure response. # Accepts a response from the microservice, and returns. def send_request_to_patron_creator_service # Sierra supporting pin as password query = { 'names' => ["#{last_name.upcase}, #{first_name.upcase}"], 'emails' => [email], 'pin' => password, 'patronType' => patron_type, 'patronCodes' => { 'pcode1' => '-', 'pcode2' => '-', 'pcode3' => pcode3, 'pcode4' => pcode4 }, 'barcodes' => [self.barcode.present? ? self.barcode : self.assign_barcode.to_s], addresses: [ { lines: [ "#{school.address_line_1}", "#{school.address_line_2}" ], type: 'a' } ], phones: [{ number: school.phone_number, type: "t" }], varFields: [{ fieldTag: "o", content: school.name }] } response = HTTParty.post( ENV.fetch('PATRON_MICROSERVICE_URL_V02', nil), body: query.to_json, headers: { 'Authorization' => "Bearer #{Oauth.get_oauth_token}", 'Content-Type' => 'application/json' }, timeout: 10 ) case response.code when 201 LogWrapper.log('DEBUG', { 'message' => "The account with e-mail #{email} was successfully created from the micro-service!", 'status' => response.code }) when 400 LogWrapper.log('ERROR', { 'message' => "An error has occured when sending a request to the patron creator service", 'status' => response.code, 'responseData' => response.body }) raise Exceptions::InvalidResponse, response["message"]["description"] else LogWrapper.log('ERROR', { 'message' => "An error has occured when sending a request to the patron creator service", 'status' => response.code, 'responseData' => response.body }) raise Exceptions::InvalidResponse, "Invalid status code of: #{response.code}" end end # 404 - no records with the same e-mail were found # 409 - more then 1 record with the same e-mail was found # 200 - 1 record with the same e-mail was found def get_email_records(email) query = { 'email' => email } response = HTTParty.get( ENV.fetch('PATRON_MICROSERVICE_URL_V01', nil), query: query, headers: { 'Authorization' => "Bearer #{Oauth.get_oauth_token}", 'Content-Type' => 'application/json' } ) response = JSON.parse(response.body) case response['statusCode'] when 404 LogWrapper.log('DEBUG', { 'message' => "No records found with the e-mail #{email} in Sierra database", 'status' => response['statusCode'], 'user' => { email: email } }) when 409 LogWrapper.log('DEBUG', { 'message' => "The following e-mail #{email} has more then 1 record in the Sierra database with the same e-mail", 'status' => response['statusCode'], 'user' => { email: email } }) when 200 LogWrapper.log('DEBUG', { 'message' => "The following e-mail #{email} has 1 other record in the Sierra database with the same e-mail", 'status' => response['statusCode'], 'user' => { email: email } }) response = {statusCode: 200, message: 'This e-mail address already exists!'} else LogWrapper.log('ERROR', { 'message' => "#{response}", 'status' => response['statusCode'], 'user' => { email: email } }) end return response end def patron_type school.borough == 'QUEENS' ? 149 : 151 end def pcode3 return 1 if school.borough == 'BRONX' return 2 if school.borough == 'MANHATTAN' return 3 if school.borough == 'STATEN ISLAND' return 4 if school.borough == 'BROOKLYN' return 5 if school.borough == 'QUEENS' end # This returns the sierra code, not the school's zcode def pcode4 school.sierra_code end end
class AddEegDataToYtVideo < ActiveRecord::Migration def change add_column :yt_videos, :eeg_data, :text end end
class AddEfficiencyToTodoItems < ActiveRecord::Migration def change add_column :todo_items, :efficiency, :string end end
class Article < ActiveRecord::Base attr_accessible :id,:article_image, :article_image_alt,:article_content, :article_image_content_type, :article_image_file_name, :article_image_file_size, :article_image_updated_at, :article_short_description, :article_title, :article_url, :release_date # attr_accessible :description, :name, :image, :title, :url, :gallery_album_id, :delete_image, :gallery_album #attr_accessor :delete_article_image #belongs_to :gallery_album validates :article_title, :length => 1..67, presence: true validates :article_url, :uniqueness => true, presence: true validates :article_short_description, :length => 1..161, :presence => true before_validation :generate_article_url before_validation :default_release_date def default_release_date self.release_date ||= Time.now end before_validation :generate_image_alt def generate_image_alt self.article_image_alt ||= article_title end before_save :check_rename_article_image def check_rename_article_image if article_image_file_name_changed? new_name = article_image_file_name old_name = article_image_file_name_was article_image.styles.keys.each do | key | file_path = article_image.path(key) folder = File.dirname(file_path) new_path = folder + '/' + new_name old_path = folder + '/' + old_name FileUtils.mv old_path, new_path end end end def generate_article_url if !object_metadata #object_metadata = ObjectMetadata.create!(article_id: (Article.last.id + 1) ) build_object_metadata end object_metadata.url ||= article_title.parameterize object_metadata.head_title ||= article_title object_metadata.body_title ||= article_title self.article_url = object_metadata.url end has_attached_file :article_image, :styles => { :thumb => '200x155>', :article_item_page => '390x250>', :bw_thumb => '200x155>' }, :processor => 'mini_magick', :convert_options => { #:grayscale_thumb => '-threshold 50%', :bw_thumb => '-colorspace Gray' }, :url => '/assets/article_images/:id/:style/:basename.:extension', :path => ':rails_root/public/assets/article_images/:id/:style/:basename.:extension' #:hash_secret => '3858f62230ac3c915f300c664312c63f' has_one :object_metadata attr_accessible :object_metadata accepts_nested_attributes_for :object_metadata attr_accessible :object_metadata_attributes def image_width geo = Paperclip::Geometry.from_file(Paperclip.io_adapters.for(self.article_image)) #self.image_height = geo.height #self.image_width = geo.width #self.image_ratio = geo.width / geo.height return geo.width end def image_height geo = Paperclip::Geometry.from_file(Paperclip.io_adapters.for(self.article_image)) #self.image_height = geo.height #self.image_width = geo.width #self.image_ratio = geo.width / geo.height return geo.height end rails_admin do label 'Статья' label_plural 'Статьи' list do field :article_title #field :gallery_album field :article_image end edit do field :article_title field :release_date #field :article_url field :article_short_description field :article_content, :ck_editor do end field :article_image, :paperclip do label 'Image' end field :article_image_file_name field :article_image_alt #field :gallery_album field :object_metadata end end end
module DynamicAnnotation::AnnotationTypeManager def self.generate_mutation_classes_for_annotation_type(type) klass = type.camelize mutation_target = "dynamic_annotation_#{type}" Object.class_eval <<-TES DynamicAnnotation#{klass} = Dynamic unless defined?(DynamicAnnotation#{klass}) class DynamicAnnotation#{klass}Type < BaseObject include Types::Inclusions::AnnotationBehaviors graphql_name "#{mutation_target.capitalize}" def id object.relay_id('annotation') end field :lock_version, GraphQL::Types::Int, null: true field :locked, GraphQL::Types::Boolean, null: true end unless defined? DynamicAnnotation#{klass}Type module DynamicAnnotation#{klass}Mutations MUTATION_TARGET = "#{mutation_target}".freeze PARENTS = ['project_media', 'source', 'project'].freeze module SharedCreateAndUpdateFields extend ActiveSupport::Concern include Mutations::Inclusions::AnnotationBehaviors included do argument :action, GraphQL::Types::String, required: false argument :fragment, GraphQL::Types::String, required: false argument :set_attribution, GraphQL::Types::String, required: false, camelize: false argument :action_data, GraphQL::Types::String, required: false, camelize: false field :versionEdge, VersionType.edge_type, null: true field :dynamic, DynamicType, null: true field :dynamicEdge, DynamicType.edge_type, null: true end end class Create < Mutations::CreateMutation include SharedCreateAndUpdateFields argument :set_fields, GraphQL::Types::String, required: true, camelize: false end unless defined? Create class Update < Mutations::UpdateMutation include SharedCreateAndUpdateFields argument :set_fields, GraphQL::Types::String, required: false, camelize: false argument :lock_version, GraphQL::Types::Int, required: false, camelize: false argument :assigned_to_ids, GraphQL::Types::String, required: false, camelize: false argument :locked, GraphQL::Types::Boolean, required: false end unless defined? Update class Destroy < Mutations::DestroyMutation; end unless defined? Destroy end TES end end
class Result < ActiveRecord::Base include CompetitionTags belongs_to :competition belongs_to :entry has_one :competitor, through: :entry has_many :scores scope :attempted, -> { where("raw is not null") } scope :not_attempted, -> { where("raw is null") } scope :not_time_capped, -> { where("time_capped = false") } scope :time_capped, -> { where("time_capped = true") } scope :finished, -> { attempted.not_time_capped } scope :event, -> (num) { where(event_num: num) } scope :fictional, -> { tagged(fictional: true) } before_save :normalize, if: -> { normalized.blank? } def event competition.events[event_num - 1] # 0 based end def finished? raw.present? && ! time_capped? end private def normalize if raw.present? score = Score.new(event) self.normalized = score.to_normalized(raw) self.time_capped = score.time_capped?(raw) self.est_normalized = score.to_est_normalized(raw) self.est_raw = score.to_est_raw(est_normalized) # helpful to understand how estimates were generated. self.est_reps = score.reps end true end end
class Grid attr_reader :model_grid def jira unless @jira @jira = JiraCaller.new end @jira end def save @model_grid.each do |board| board.save() end end def update @grid = jira.get_boards updateModelGrid createSprints getSprintChanges processAllChanges end def create @grid = jira.get_boards createModelGrid createSprints getSprintChanges processAllChanges end def updateModelGrid @model_grid.where(jid: key).first @grid.each{ | json_board| unless @model_grid.where(jid: key).exists? @model_grid << Board.new( jId(json_board) ) end } end def createModelGrid @model_grid = Array.new unless @model_grid @grid.each { |json_board| @model_grid << Board.new( jId(json_board) ) } end def createSprints @model_grid.each { |board| sprints = jira.get_sprints(board.jid.to_s) sprints['sprints'].each{ |s| addOrCreateSprint(board, s) } } end def addOrCreateSprint board, sprint found = false board.sprints.each{|s| if s.jid == sprint['id'] s.update(sprint) found = true end } unless found board.sprints << Sprint.new( jId(sprint) ) end end def getSprintChanges @model_grid.each do |board| board.sprints.each do |sprint| unless sprint.have_all_changes change_set = jira.get_sprint_changes board.jid, sprint.jid sprint.change_set = ChangeSet.new change_set if sprint.closed sprint.have_all_changes = true end end end end end def jId o o[:jid] = o['id'] o['id'] = nil o end def processAllChanges @model_grid.each{|board| board.sprints.each{ |sprint| unless sprint.have_processed_all_changes processChanges sprint getStoryDetailsForSprint sprint sprint.have_processed_all_changes = true end } } end def processChanges(sprint) ch = sprint.change_set[:changes] ch.keys.each do |timestamp| ch[timestamp].each do |o1| curStory = getOrCreateStoryOnSprint(sprint, o1['key'], timestamp) setSizeOfStory(curStory, o1) setIsStoryDone(curStory, o1) setIfAddedOrRemoved(curStory, o1, timestamp, sprint) end end end def getOrCreateStoryOnSprint(sprint, key, timestamp) if sprint.stories.where(jid: key).exists? curStory = sprint.stories.where(jid: key).first else curStory = Story.new unless sprint.stories.where(jid: key).exists? curStory[:jid] = key curStory.init_date = Time.at Integer(timestamp) sprint.stories << curStory end curStory end def setAssignee(issue, story) assignee = issue['fields']['assignee'] if assignee story.assignee = JiraUser.new unless story.assignee populateUser story.assignee, assignee else story.assignee = nil end end def setReporter(issue, story) reporter = issue['fields']['reporter'] if reporter story.reporter = JiraUser.new unless story.reporter populateUser story.reporter, reporter else story.assignee = nil end end def populateUser user, obj user.name = obj['name'] user.email_address = obj['emailAddress'] user.display_name = obj['displayName'] end def getStoryDetailsForSprint(sprint) sprint.stories.each do |story| unless issue.assignee && issue.reporter issue = jira.get_story_detail story.jid setAssignee issue, story setReporter issue, story end end end def setSizeOfStory(curStory, o1) if o1['statC'] && o1['statC']['newValue'] curStory.size = o1['statC']['newValue'] end if o1['statC'] && ( o1['statC']['newValue'] || o1['statC']['noStatsValue'] ) unless curStory.is_initialized if o1['statC']['noStatsValue'] curStory.init_size = 0 curStory.size = 0 else curStory.init_size = o1['statC']['newValue'] || curStory.size end curStory.is_initialized = true end end end def setIsStoryDone(curStory, o1) if o1['column'] curStory.done = !o1['column']['notDone'] end end def setIfAddedOrRemoved(curStory, o1, timestamp, sprint) if o1['added'] storyAddedDate = Time.at Integer(timestamp) curStory.init_date = storyAddedDate startTime = Time.at sprint.change_set.startTime curStory.was_added = storyAddedDate > startTime curStory.was_removed = false end if o1['added'] == false curStory.was_removed = true end end end
class Evaluator::ReactGit < Evaluator::Base EXECUTOR_PATH = "evaluator_templates/react_git/executor.sh.erb" def initialize(solution) @solution = solution end def prepare # check if repository exists if !Octokit.repository?(@solution.repository) fail("No se encontró el repositorio #{@solution.repository}") return end create_file(local_path, "MirRunner.test.js", @solution.challenge.evaluation) create_executor_file FileUtils.chmod(0777, "#{local_path}/executor.sh") end def execute repo = "https://github.com/#{@solution.repository}" image = "makeitrealcamp/mir-evaluator" command = [ "docker", "run", "-d", "-v", "#{local_path}:#{container_path}", "-v", "#{base_path}/yarn-cache:/ukku/yarn-cache", image, "/bin/bash", "-c", "-l", "'#{container_path}/executor.sh #{repo}'" ].join(" ") cid = Evaluator::Docker.execute(command) ok = Evaluator::Docker.wait(cid, @solution.challenge.timeout) ok ? complete : failure rescue SimpleTimeout::Error fail_timeout end def clean FileUtils.rm_rf(local_path) end private def create_executor_file template = File.read(EXECUTOR_PATH) evaluation_file_path = "#{container_path}/MirRunner.test.js" error_file_path = "#{container_path}/error.txt" executor_content = ERB.new(template).result(binding) create_file(local_path, "executor.sh", executor_content) end def failure f = "#{local_path}/error.txt" if File.exist?(f) && !File.read(f).empty? handle_error(f) elsif File.exist?("#{local_path}/result.json") handle_test_failure("#{local_path}/result.json") else fail("La evaluación falló por un problema desconocido :S. Repórtalo a tu mentor o a info@makeitreal.camp enviando el URL con tu solución e indicando el tema y el reto donde ocurrió.") end end def handle_test_failure(result_path) result_file = File.read(result_path) result = JSON.parse(result_file) tests = result["examples"].reject { |test| test["status"] != "failed" } test = tests[0] message = "#{test['exception']['message']}" fail(message) end end
class Tesla attr_accessor :id, :controller # Allows calling methods directly from the class rather than `Tesla.new.start` -> `Tesla.start` def self.method_missing(method, *args, &block) new.send(method, *args) end def initialize(controller=nil) @controller = controller || TeslaControl.new(self) @id = @controller.vehicle_id end delegate( :vehicle_data, :cached_vehicle_data, :loc, :start_car, :off_car, :honk, :navigate, :defrost, :doors, :windows, :pop_boot, :pop_frunk, :heat_driver, :heat_passenger, to: :controller ) def set_temp(temp_F) controller.start_car controller.set_temp(temp_F) end end
module Calculations # Get hourly data points that are within a "heating season" (e.g. September to # June) and below a warm weather set point. # class AverageOutdoorTemperature < Generic::Strict attr_accessor :heating_season_end_month, :heating_season_start_month, :location, :warm_weather_shutdown_temperature def call return unless location return unless heating_season_start_month return unless heating_season_end_month regexp = /\A0?(\d+)-0?(\d+)\z/ start_pieces = heating_season_start_month.match(regexp) start_month = start_pieces[1] start_day = start_pieces[2] end_pieces = heating_season_end_month.match(regexp) end_month = end_pieces[1] end_day = end_pieces[2] result = HourlyTemperature.where( location: location ) .where( "date NOT BETWEEN (CONCAT_WS('-', EXTRACT(year from date), ?, ?)::timestamp + INTERVAL '1 day') AND (CONCAT_WS('-', EXTRACT(year from date), ?, ?)::timestamp - INTERVAL '1 day')", end_month, end_day, start_month, start_day) .where('temperature < ?', warm_weather_shutdown_temperature) .pluck('AVG(temperature)') result.first end end end
require 'minitest/autorun' describe OpenAPIRest::QueryBuilder do before do OpenAPIRest::ApiDoc.configure do |c| c.document = ::YAML::load_file('lib/generators/templates/api_docs.yml') end @api_model = OpenAPIRest::ApiModel.new(:product) end describe '' do before do params = ActionController::Parameters.new(openapi_path: { path: '/products', method: 'post' }, product: { product_id: '2222' }) @query_builder = OpenAPIRest::QueryBuilder.new(@api_model, params.merge!(operation: :create)) end it 'check default params' do assert_empty(@query_builder.query) assert_nil(@query_builder.sort) assert_equal(@query_builder.limit, 10) assert_equal(@query_builder.offset, 0) assert_empty(@query_builder.fields) assert_equal(@query_builder.single_result?, true) assert_equal(@query_builder.single?, true) assert_equal(@query_builder.resource, 'product') assert_equal(@query_builder.entity, 'products') refute_nil(@query_builder.response) end end end
class Api::SessionsController < Api::BaseController before_filter :authenticate_user!, except: [:create] before_filter :ensure_email_param_exists, only: [:create] before_filter :ensure_password_param_exists, only: [:create] respond_to :json def create resource = User.find_by_email(params[:user_login][:email].downcase) return invalid_login_attempt unless resource if resource && resource.authenticate(params[:user_login][:password]) sign_in(:user, resource) render json: { success: true, email: resource.email,username: resource.username,first_name: resource.first_name,last_name:resource.last_name }, status: :created return end invalid_login_attempt end def destroy current_user.reset_authentication_token render json: { success: true }, status: :ok end protected def ensure_user_login_param_exists return unless params[:user_login].blank? render json:{ success: false, message: "Missing #{param} parameter"}, status: :unprocessable_entity end def ensure_email_param_exists ensure_param_exists :email end def ensure_password_param_exists ensure_param_exists :password end def ensure_param_exists(param) return unless params[:user_login][param].blank? render json:{ success: false, message: "Missing #{param} parameter"}, status: :unprocessable_entity end def invalid_login_attempt render json: { success: false, message: "Error with your login or password"}, status: :unauthorized end end
require 'spec_helper' describe 'synapse' do let(:facts) {{ :osfamily => 'Debian', :operatingsystemmajrelease => '5', }} context 'supported operating systems' do ['Debian', 'RedHat'].each do |osfamily| describe "synapse class without any parameters on #{osfamily}" do let(:params) {{ }} let(:facts) {{ :osfamily => osfamily, :operatingsystemmajrelease => '5', }} it { should contain_class('synapse::params') } it { should contain_class('synapse::install') } it { should contain_class('synapse::config') } it { should contain_class('synapse::system_service') } end end end context 'when asked to install via gem' do let(:params) {{ :package_provider => 'gem', }} it { should contain_package('synapse').with( :ensure => '0.7.0', :provider => 'gem', :name => 'synapse' ) } end context 'when given a specific package name and provider' do let(:params) {{ :package_ensure => 'latest', :package_provider => 'bla', :package_name => 'special-synapse' }} it { should contain_package('synapse').with( :ensure => 'latest', :provider => 'bla', :name => 'special-synapse' ) } end context 'when not specified how to install' do let(:params) {{ }} it { should contain_package('synapse').with( :ensure => '0.7.0', :provider => nil, :name => 'rubygem-synapse' ) } end # Config stuff context 'config by default' do let(:params) {{ }} it { should contain_file('/etc/synapse/synapse.conf.json').with( :ensure => 'present', :mode => '0444' ) } it { should contain_file('/etc/synapse/synapse.conf.json').with_content(/"service_conf_dir": "\/etc\/synapse\/conf.d\/"/) } it { should contain_file('/etc/synapse/conf.d/').with( :ensure => 'directory', :purge => true ) } end context 'When alternate params are specified' do let(:params) {{ :config_file => '/opt/bla.json', :config_dir => '/tmp/synapse.d/', :purge_config => false }} it { should contain_file('/opt/bla.json').with( :ensure => 'present', :mode => '0444' ) } it { should contain_file('/opt/bla.json').with_content(/"service_conf_dir": "\/tmp\/synapse.d\/"/) } it { should contain_file('/tmp/synapse.d/').with( :ensure => 'directory', :purge => false ) } end context 'When alternate global log declarations are specified' do let(:params) {{ :haproxy_global_log => ['log foo', 'log bar'] }} it { should contain_file('/etc/synapse/synapse.conf.json').with_content(/"log foo"/).with_content(/"log bar"/) } end context 'When no global log declarations are specified' do let(:params) {{ }} it { should contain_file('/etc/synapse/synapse.conf.json').with_content(/"log 127.0.0.1 local0"/).with_content(/"log 127.0.0.1 local1 notice"/) } end context 'When alternate extra sections are specified' do let(:params) {{ :haproxy_extra_sections => {'foo' => ['bar', 'baz']} }} it { should contain_file('/etc/synapse/synapse.conf.json').with_content(/{\n\s+"foo": \[\n\s+"bar",\n\s+"baz"\n\s+\]\n\s+}/) } end # Service Stuff context 'when requested not to run' do let(:params) {{ :service_ensure => 'stopped' }} it { should contain_service('synapse').with( :ensure => 'stopped' ) } end end
require 'rails_helper' RSpec.describe ScrapersController, type: :controller do let(:special_param) { "ocean" } let(:css_class_to_count) { "row" } let(:resulting_hash) do { url: url, robots_txt_exists: true, robots_forbidden: false, bootstrap_user: true, string_to_search_for: special_param, string_in_dom: true, css_class_to_count: css_class_to_count, css_class_count: 3 } end describe 'create' do before(:each) do post :create, url: url, string_to_search_for: special_param, css_class_to_count: css_class_to_count end context 'when valid params supplied' do context 'when string is in DOM, bootstrap user, robots.txt exists but does not forbid-' do let(:url) { "http://www.hydearchitects.com/" } it 'returns in JSON an HTML body, whether special param is in HTML body, whether robots.txt exists, whether bootstrap is used' do expect(response.status).to eq(200) expect(JSON.parse(response.body)).to eq(JSON.parse(resulting_hash.to_json)) end end context 'when bootstrap is in HTML DOM, but site does not use bootstrap' do let(:url) { "http://www.agilestartup.com/making-money/go-bootstrap-yourself/" } it 'returns false for bootstrap user' do expect(JSON.parse(response.body)["bootstrap_user"]).to be false end end context 'when site forbids crawling' do let(:url) { "https://www.facebook.com/onthisday/?source=bookmark" } it 'returns true for robots forbidden' do expect(JSON.parse(response.body)["robots_forbidden"]).to be true end end context 'when robots.txt is empty/full only of comments' do let(:url) { "https://judge-my-routine.herokuapp.com" } it 'returns false for robots_txt_exists' do expect(JSON.parse(response.body)["robots_txt_exists"]).to be false end end context 'when robots.txt DNE' do let(:url) { "http://www.wordtwist.org/" } it 'returns false for robots_txt_exists, returns 200' do expect(response.status).to eq(200) expect(JSON.parse(response.body)["robots_txt_exists"]).to be false end end end context 'when invalid params are supplied - url is invalid and/or when cannot retrieve page' do let(:url) { "www.wiryhipposaretooskinny.com/"} it 'returns 400 with error message asking for formatted or proper url' do expect(response.status).to eq(400) expect(JSON.parse(response.body)["errors"]).to eq("URL is wrong or improperly formatted") end end end end
class CharactersFetcher include Container::Inject URL = "https://rickandmortyapi.com/api/character" inject :http_client inject :characters_parser, CharactersParser def fetch response = http_client.get(URL) characters_parser.parse(response.body) end end
require 'asciidoctor' require 'asciidoctor/extensions' class PageInfoPreprocessor < Asciidoctor::Extensions::Preprocessor @@page_orders =Hash.new def process document, reader lines = reader.lines # get raw lines return reader if lines.empty? # puts("file_location = #{Pathname.new Dir.pwd}") # puts("file_location = #{document}") # puts("file_location = #{document.inspect}") # puts("file_location reader= #{reader}") # puts("file_location file = #{reader.file}") # puts("file_location path = #{reader.path}") page_layout=nil page_title=nil page_order=nil lines.each do |line| if page_layout==nil and line.start_with? ':page-layout:' page_layout=line[14..-1].strip end if page_order==nil and line.start_with? ':page-order:' page_order=line[13..-1].strip end if page_title==nil and line.start_with? '= ' page_title=line[2..-1].strip end end if page_layout==nil document.set_attribute('page-layout',"doc") end if page_order!=nil and page_title!=nil @@page_orders[page_title]=page_order end document.set_attribute('imagesdir',"/foo/bar/") reader end def self.get_page_order_value(page_title) if @@page_orders[page_title]!=nil return @@page_orders[page_title] else return page_title end end end
module OrganizationsPage class Index < ApplicationPage ORGANIZATIONS = {css: "div.card"}.freeze def get_organization_count all_elements(ORGANIZATIONS).size end end end
class AddIsAdvancedToCourse < ActiveRecord::Migration def change add_column :courses, :is_advanced, :boolean, default: :false end end
require 'spec_helper' describe EsClient::ActiveRecord::Adapter do describe 'index name' do it 'determine index name from model' do expect(RspecUser.es_client.index_name).to eq 'rspec_users' end it 'allow to define custom index name' do RspecUser.es_client.index_name('custom_index_name') expect(RspecUser.es_client.index_name).to eq 'custom_index_name' RspecUser.es_client.instance_variable_set(:@index_name, nil) end end describe 'document type' do it 'determine document type from model' do expect(RspecUser.es_client.document_type).to eq 'rspec_user' end it 'allow to define custom document type' do RspecUser.es_client.document_type('custom_document_type') expect(RspecUser.es_client.document_type).to eq 'custom_document_type' RspecUser.es_client.instance_variable_set(:@document_type, nil) end end it 'save document' do expect(RspecUser.es_client.index).to receive(:save_document).with('rspec_user', 1, {id: 1, name: 'bob'}) RspecUser.es_client.save_document(RspecUser.new(id: 1, name: 'bob')) end describe 'update document' do it 'update document' do expect(RspecUser.es_client.index).to receive(:update_document).with('rspec_user', 1, {name: 'arnold'}) record = RspecUser.new(id: 1, name: 'bob') allow(record).to receive(:changes).and_return({name: %w(bob arnold)}) RspecUser.es_client.update_document(record) end end describe 'update document fields' do it 'update document fields' do expect(RspecUser.es_client.index).to receive(:update_document).with('rspec_user', 1, {name: 'arnold'}) record = RspecUser.new(id: 1, name: 'bob') RspecUser.es_client.update_fields(record, {name: 'arnold'}) end end it 'destroy document' do expect(RspecUser.es_client.index).to receive(:destroy_document).with('rspec_user', 1) RspecUser.es_client.destroy_document(1) end describe 'find' do it 'find document' do expect(RspecUser.es_client.index).to receive(:find).with('rspec_user', 1) RspecUser.es_client.find(1) end it 'find multiple documents' do expect(RspecUser.es_client.index).to receive(:search).with({query: {ids: {values: [1], type: 'rspec_user'}}, size: 1}, type: 'rspec_user') RspecUser.es_client.find([1]) end end describe 'import' do it 'import batch of records' do expect(RspecUser.es_client.index).to receive(:bulk).with(:index, 'rspec_user', [{id: 1}]) RspecUser.es_client.import([RspecUser.new(id: 1)]) end end describe 'mapping' do it 'fetch mapping' do expect(RspecUser.es_client.index).to receive(:get_mapping) RspecUser.es_client.mapping end it 'set mapping' do RspecUser.es_client.index.options[:mappings] = {} RspecUser.es_client.mapping(test: {properties: {notes: {type: 'string'}}}) expect(RspecUser.es_client.index.options[:mappings]).to include(test: {properties: {notes: {type: 'string'}}}) end it 'set append mapping' do RspecUser.es_client.index.options[:mappings] = {} RspecUser.es_client.mapping(test: {properties: {prop1: {type: 'string'}}}) RspecUser.es_client.mapping(test: {properties: {prop2: {type: 'string'}}}) expect(RspecUser.es_client.index.options[:mappings][:test][:properties]).to include(prop1: {type: 'string'}) expect(RspecUser.es_client.index.options[:mappings][:test][:properties]).to include(prop2: {type: 'string'}) end end describe 'settings' do it 'fetch settings' do expect(RspecUser.es_client.index).to receive(:get_settings) RspecUser.es_client.settings end it 'set settings' do RspecUser.es_client.index.options[:settings] = {} RspecUser.es_client.settings(refresh_interval: '3s') expect(RspecUser.es_client.index.options[:settings]).to include(refresh_interval: '3s') end end describe 'search' do it 'perform search query' do expect(RspecUser.es_client.index).to receive(:search).with({query: {query_string: {query: 'test'}}}, type: 'rspec_user') RspecUser.es_client.search(query: {query_string: {query: 'test'}}) end end end
# encoding: utf-8 Given /^that I have gone to the Google page$/ do @browser.goto ("https://www.google.by/") end When /^I add '(.*)' to the search box$/ do |item| @browser.text_field(:name,"q").set(item) end And /^click the Search Button$/ do @browser.button(:name, "btnG").click end Then /^'(.*)' should be mentioned in the results$/ do |item| # this test fails from time to time @browser.div(id: "imagebox_bigimages").wait_while_present @browser.text.should include(item) end
# Ruby Inheritance: Create an object to model something in the real world. Then, extend the object with another object that is more specific. For example, create an Animal object with attributes that all animals have and then a Bird object that extends animal and has traits specific to birds. Give examples of using each object after they have been declared including assigning attributes and using instance methods. class Animal def initialize (name) @name = name end def walk puts "...pitter patter..." end end class Dog < Animal def speak puts "Woof! Woof!" end def kisses puts "Thluurrrrp" end def info puts "This dog's name is #{@name}" end end class Snake < Animal def walk puts "I can't walk, I only slither...ssssss" end def speak puts "sssssss" end def info puts "This snake's name is #{@name}" end end
class PenguinsController < ApplicationController before_action :logged_in_admin, only: [:edit, :update] def index @penguins = Penguin.order('id') end def show @penguin = Penguin.find(params[:id]) @penguins = Penguin.order('id') @pictures = @penguin.pictures.all end def edit @penguin = Penguin.find(params[:id]) end def update @penguin = Penguin.find(params[:id]) if @penguin.update_attributes(penguin_params) flash[:success] = "Updated." redirect_to penguin_path else render 'edit' end end private def penguin_params params.require(:penguin).permit(:name, :e_name, :max_height, :overview) end end
class Merchant < ActiveRecord::Base has_many :offers, dependent: :destroy validates :advertiser_id, uniqueness: true end
require 'test_helper' class Wechaty::ResultTest < MiniTest::Test def test_success_method_with_true r = Wechaty::Result.new( Hash.from_xml( <<-XML <xml> <return_code>SUCCESS</return_code> <result_code>SUCCESS</result_code> </xml> XML )) assert_equal r.success?, true end def test_success_method_with_false r = Wechaty::Result.new( Hash.from_xml( <<-XML <xml> </xml> XML )) assert_equal r.success?, false end end
class User attr_accessor :name @@all = [] def initialize(name) @name = name @@all << self end def self.all @@all end def recipes self.recipe_cards.collect do |recipe_card| recipe_card.recipe end end def recipe_cards RecipeCard.all.select do |recipe_card| recipe_card.user == self end end def add_recipe_card(recipe, date, rating) RecipeCard.new(self, recipe, date, rating) end def declare_allergen(ingredient) Allergen.new(self, ingredient) end def allergens ingredients = Allergen.all.collect do |allergen| if allergen.user == self allergen.ingredient end end.compact ingredients.empty? ? "No Food Allergies - Lucky You" : ingredients end def top_three_recipes if self.recipes.length == 0 return "You haven't added any recipes" elsif self.recipes.length == 1 return self.recipes end sorted_recipes = self.recipe_cards.sort_by do |recipe_card| recipe_card.rating end.reverse.collect do |recipe_card| recipe_card.recipe end sorted_recipes.length == 2 ? sorted_recipes : sorted_recipes[0..2] end def most_recent_recipe self.recipes.length > 0 ? self.recipes[-1] : "You haven't added any recipes" end end
class Subject < ApplicationRecord validates :name, presence: true validates :gender, presence: true validates :birthday, presence: true validates :address, presence: true end
# Inheritance and Variable Scope # Instance Variables: class Animal def initialize(name) @name = name end end class Dog < Animal def dog_name "bark! bark! #{@name} bark! bark!" end end teddy = Dog.new("Teddy") puts teddy.dog_name #______________________ class Animal def initialize(name) @name = name end end class Dog < Animal def initialize(name); end def dog_name "bark! bark! #{@name} bark! bark!" # can @name be referenced here? end end teddy = Dog.new("Teddy") puts teddy.dog_name # ____________________________ module Swim def enable_swimming @can_swim = true end end class Dog include Swim def swim "swimming!" if @can_swim end end teddy = Dog.new teddy.swim # would need to do this teddy = Dog.new teddy.enable_swimming teddy.swim # Class Variables class Animal @@total_animals = 0 def initialize @@total_animals += 1 end end class Dog < Animal def total_animals @@total_animals end end spike = Dog.new spike.total_animals # ______________________ class Vehicle @@wheels = 4 def self.wheels @@wheels end end Vehicle.wheels # 4 class Motorcycle < Vehicle @@wheels = 2 end Motorcycle.wheels # 2 Vehicle.wheels # 2 # Constants class Dog LEGS = 4 end class Cat def legs LEGS end end kitty = Cat.new kitty.legs # error unititialized constant # ___________________________ class Dog LEGS = 4 end class Cat def legs Dog::LEGS # :: is called namespacing end end kitty = Cat.new kitty.legs # 4 # __________________________ class Vehicle WHEELS = 4 end class Car < Vehicle def self.wheels WHEELS end def wheels WHEELS end end car.wheels # 4 # ____________________ a_car = Car.new a_car.wheels # 4 module Maintenace def Change_tires "Changing #{WHEELS} tires." end end # two ways to fix the module WHEELS error # 1. module Maintenance def change_tires "Changing #{Vehicle::WHEELS} tires." end end # 2. module Maintenance def change_tires "Changing #{Car::WHEELS} tires." end end class Vehicle WHEELS = 4 end class Car < Vehicle include Maintenance end a_car = Car.new a_car.change_tires #name error unitiaialized constanct WHEELS # Summary # Instance Variables: behave the way we'd expect. The only thing to watch out for is # to make sure the instance variable is initialized before referencing it. # Class Variables: have a very insidious behavior of allowing sub-classes to # override super-class class variables. Further, the change will affect all other # sub-classes of the super_class. This is extremely unintuitive behavior, forcing # some Rubyists to eschew using class variables altogether. # Constants: have lexical scope which makes their scope resolution rules very unique # compared to other variable types. If Ruby doesn't find the constant using lexical # scope, it'll then look at the inheritance heirarchy.
# encoding: utf-8 control "V-54073" do title "The /diag subdirectory under the directory assigned to the DIAGNOSTIC_DEST parameter must be protected from unauthorized access." desc "/diag indicates the directory where trace, alert, core and incident directories and files are located. The files may contain sensitive data or information that could prove useful to potential attackers.false" impact 0.5 tag "check": "From SQL*Plus: select value from v$parameter where name='diagnostic_dest'; On UNIX Systems: ls -ld [pathname]/diag Substitute [pathname] with the directory path listed from the above SQL command, and append "/diag" to it, as shown. If permissions are granted for world access, this is a Finding. If any groups that include members other than the Oracle process and software owner accounts, DBAs, auditors, or backup accounts are listed, this is a Finding. On Windows Systems (From Windows Explorer): Browse to the \diag directory under the directory specified. Select and right-click on the directory, select Properties, select the Security tab. If permissions are granted to everyone, this is a Finding. If any account other than the Oracle process and software owner accounts, Administrators, DBAs, System group or developers authorized to write and debug applications on this database are listed, this is a Finding." tag "fix": "Alter host system permissions to the <DIAGNOSTIC_DEST>/diag directory to the Oracle process and software owner accounts, DBAs, SAs (if required) and developers or other users that may specifically require access for debugging or other purposes. Authorize and document user access requirements to the directory outside of the Oracle, DBA and SA account list." # Write Check Logic Here end
module CustomerQueries extend ActiveSupport::Concern included do establish_connection( :adapter => 'sqlserver', :host => ENV["OMNI_HOST"], :username => ENV["OMNI_UNAME"], :password => ENV["OMNI_PW"], :database => ENV["OMNI_DB"] ) end table_name = ENV["TABLE_NAME"] module ClassMethods def lookup_phone(phone_number) find_by_sql [ENV["lookup_phone_query"], phone_number] end def lookup_account_code(account_code) find_by_sql [ENV["lookup_account_code_query"], account_code] end def lookup_account_id(account_id) find_by_sql [ENV["lookup_account_id_query"], account_id] end #DAIS def dais_lookup_phone(phone_number) find_by_sql [ENV["dais_lookup_phone_query"], phone_number] end def dais_lookup_account_code(account_code) find_by_sql [ENV["dais_lookup_account_code_query"], account_code] end def dais_lookup_account_id(account_id) find_by_sql [ENV["dais_lookup_account_id_query"], account_id] end end end
require 'test_helper' class Api::V1::TodosControllerTest < ActionController::TestCase setup do stub_current_user @annotation_category = AnnotationCategory.first end test 'get index only data of area of user' do user = @controller.current_api_v1_user # useful sample data orga = create(:orga, area: user.area + ' is different', parent: nil) assert_not_equal orga.area, user.area Annotation.create!(detail: 'ganz wichtig', entry: orga, annotation_category: AnnotationCategory.first) orga.annotations.last orga.sub_orgas.create(attributes_for(:another_orga, parent_orga: orga, area: 'foo')) get :index assert_response :ok, response.body json = JSON.parse(response.body) assert_kind_of Array, json['data'] assert_equal 0, json['data'].size assert orga.update(area: user.area) get :index assert_response :ok, response.body json = JSON.parse(response.body) assert_kind_of Array, json['data'] assert_equal Orga.by_area(user.area).count, json['data'].size orga_from_db = Orga.by_area(user.area).last assert_equal orga.serialize_lazy(annotations: true, facets: false).as_json, json['data'].last end test 'get filtered for annotation category' do annotation_category2 = AnnotationCategory.last assert_not_equal @annotation_category, annotation_category2 assert orga = create(:orga, title: 'Gartenschmutz', description: 'hallihallo') assert event = create(:event, title: 'GartenFOObar') get :index, params: { filter: { title: 'Garten', description: 'hallo' } } json = JSON.parse(response.body) assert_response :ok assert_kind_of Array, json['data'] assert_equal 0, json['data'].size Annotation.create!(detail: 'ganz wichtig', entry: orga, annotation_category: @annotation_category) Annotation.create!(detail: 'ganz wichtig 2', entry: orga, annotation_category: annotation_category2) Annotation.create!(detail: 'ganz wichtig', entry: event, annotation_category: @annotation_category) get :index, params: { filter: { annotation_category_id: annotation_category2.id } } json = JSON.parse(response.body) assert_response :ok assert_kind_of Array, json['data'] assert_equal 1, json['data'].size assert_equal orga.serialize_lazy(annotations: true, facets: false).as_json, json['data'].first end test 'get todos default filter and sort' do assert orga = create(:another_orga) Annotation.create!(detail: 'ganz wichtig', entry: orga, annotation_category: @annotation_category) assert event = create(:event) Annotation.create!(detail: 'Mache ma!', entry: event, annotation_category: @annotation_category) get :index, params: { include: 'annotations', filter: { todo: '' } } json = JSON.parse(response.body) assert_response :ok assert_kind_of Array, json['data'] assert_equal 2, json['data'].size todo1 = Event.find(json['data'].first['id']) todo2 = Orga.find(json['data'].last['id']) expected = { data: [ todo1.serialize_lazy(annotations: true, facets: false).as_json, todo2.serialize_lazy(annotations: true, facets: false).as_json ] } assert_equal expected.deep_stringify_keys, json end test 'multiple sort todos' do assert orga = create(:another_orga, title: 'foo'*3) Annotation.create!(detail: 'ganz wichtig', entry: orga, annotation_category: @annotation_category) assert event = create(:event, title: 'foo'*3) Annotation.create!(detail: 'Mache ma!', entry: event, annotation_category: @annotation_category) get :index, params: { filter: { todo: '' }, sort: 'title,-state_changed_at,title' } json = JSON.parse(response.body) assert_response :ok assert_kind_of Array, json['data'] assert_equal 2, json['data'].size todo1 = Event.find(json['data'].first['id']) todo2 = Orga.find(json['data'].last['id']) expected = { data: [ todo1.serialize_lazy(annotations: true, facets: false).as_json, todo2.serialize_lazy(annotations: true, facets: false).as_json ] } assert_equal expected.deep_stringify_keys, json end end
require_relative 'key' require 'date' require 'pry' class Encryptor attr_reader :message attr_accessor :encrypted_message def initialize(message, key = Random.rand(10000..99999), date = Date.today) @message = message.chars @key = key @date = date.strftime("%d%m%y").to_i @encrypted_message = [] end def encrypt rotations = rotation_gen message.each_with_index do |char, i| letter = encrypt_letter(char, rotations[(i % 4)]) encrypted_message << letter end encrypted_message.join("") end def rotation_gen keys = KeyGen.new.key_map(@key) offsets = KeyGen.new.offsets_map(@date) rotations = [keys, offsets].transpose.map {|rotation| rotation.reduce(:+)} end def cipher(rotation) cipher = ('a'..'z').to_a + ('0'..'9').to_a + [" ", ",", "."] rotated_cipher = cipher.rotate(rotation) Hash[cipher.zip(rotated_cipher)] end def encrypt_letter(letter, rotation) cipher_lookup = cipher(rotation) cipher_lookup[letter] end end
class AddAuthorToReviews < ActiveRecord::Migration[6.0] def change add_column :reviews, :author, :text end end
class Admin::SubCategoriesController < AdminController before_action :set_category, only: [:show, :edit, :update, :destroy] load_and_authorize_resource except: [:create] has_scope :by_sub_category_name has_scope :by_sub_category_status def arts @stores = Store.all @sub_categorie = SubCategory.find(params[:id]) @sub_categories = SubCategory.all @nb_article = apply_scopes(@sub_categorie.articles).count @articles = Kaminari.paginate_array(apply_scopes(@sub_categorie.articles)).page(params[:page]) end # GET /categories # GET /categories.json def index @categories_list = Kaminari.paginate_array(apply_scopes(SubCategory.all)).page(params[:page]) @categories = Category.all respond_to do |format| format.html {render template: "admin/categories/index"} format.js end end # GET /categories/1 # GET /categories/1.json def show @sub_categories = SubCategory.all end # GET /categories/new def new @category = Category.first @sub_category = SubCategory.new end # GET /categories/1/edit def edit @category = Category.first end # POST /categories # POST /categories.json def create @sub_category = SubCategory.new(sub_category_params) if @sub_category.save redirect_to admin_sub_categories_path else render "new" end end # PATCH/PUT /categories/1 # PATCH/PUT /categories/1.json def update if @sub_category.update(sub_category_params) redirect_to admin_sub_categories_path else redirect_to edit_admin_sub_categories_path(@sub_category) end end # DELETE /categories/1 # DELETE /categories/1.json def destroy @sub_category.destroy redirect_to admin_sub_categories_path end private # Use callbacks to share common setup or constraints between actions. def set_category @sub_category = SubCategory.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def sub_category_params params.require(:sub_category).permit(:name, :avatar, :status, :category_id) end end
module Quiz class Question attr_accessor :prompt, :answer def initialize(prompt, answer) @prompt = prompt @answer = answer end end def questions q1 = "What is a syoptom of the corona virus?\n(a) Fever\n(b) Coughing\n(c) Sore throat\n(d) All of the above" q2 = "Approximately, how many confirmed cases were found in Australia?\n(a) 10,000\n(b) 200\n(c) 6,700\n(d) 8,000" q3 = "Which state has the highest number of confirmed cases?\n(a) Queensland\n(b) New South Wales\n(c) Victoria\n(d) South Australia" q4 = "If you are concerned, you should do...\n(a) Tell a friend\n(b) Wait it out, as it will pass\n(c) Go shopping, to stock up on essentials\n(d) Call the National corona virus helpline, at 1800 020 080" q5 = "Should you stay at home unless making an essential trip?\n(a) Yes\n(b) No" q6 = "Approximately, how far is social distancing\n(a) 1.5 mentres\n(b) 5 metres\n(c) 20 metres\n(d) 100 metres" q7 = "What is the least amount of time you should spend washing your hands?\n(a) 3 minutes\n(b) 20 seconds\n(c) 1 minutes\n(d) 10 minutes" q8 = "You should avoid touching what?\n(a) Eyes\n(b) Nose\n(c) Mouth\n(d) All of the above" q9 = "Should you cover your coughs and sneezes?\n(a) No, as the virus isn't airborne\n(b) Yes" questions = [ Question.new(q1, "d"), Question.new(q2, "c"), Question.new(q3, "b"), Question.new(q4, "d"), Question.new(q5, "a"), Question.new(q6, "a"), Question.new(q7, "b"), Question.new(q8, "d"), Question.new(q9, "b"), ] end def test(questions) answer = "" score = 0 for question in questions puts question.prompt answer = gets.chomp() if answer == question.answer score += 1 end end puts `clear` case score when 5...10 puts Rainbow("you got #{score} out of #{questions.length()}").green.bright puts "" puts "Congratulations, you passed" when 0...4 puts Rainbow("you got #{score} out of #{questions.length()}").red.bright puts "" puts "Please read the necessary content," puts "and retake the test." else puts "" end end end
require 'spec_helper' module MailRU class API describe DSL do context 'api' do subject do class GetRequest; def get; self; end; end class PostRequest; def post; self; end; end DSL.new(API.new, 'group') do api 'send' api 'getMethod', :get api 'postMethod', :post api 'getSecureMethod', :get, Request::Secure::Yes api 'postInsecureMethod', :post, Request::Secure::No end end it %(should have singleton_methods: 'send', 'get_method', 'post_method', 'get_secure_method', 'post_insecure_method') do subject.singleton_methods.sort.should eq( [:send, :get_method, :post_method, :get_secure_method, :post_insecure_method].sort ) end it %q(should have method 'send' which send any GET request) do subject.send.class.should eq(GetRequest) subject.send.instance_variable_get('@secure').should eq(Request::Secure::Any) end it %q(should have method 'get_method' which send any GET request) do subject.get_method.class.should eq(GetRequest) subject.get_method.instance_variable_get('@secure').should eq(Request::Secure::Any) end it %q(should have method 'post_method' which send any POST request) do subject.post_method.class.should eq(PostRequest) subject.post_method.instance_variable_get('@secure').should eq(Request::Secure::Any) end it %q(should have method 'get_secure_method' which send secure GET request) do subject.get_secure_method.class.should eq(GetRequest) subject.get_secure_method.instance_variable_get('@secure').should eq(Request::Secure::Yes) end it %q(should have method 'post_insecure_method' which send insecure POST request) do subject.post_insecure_method.class.should eq(PostRequest) subject.post_insecure_method.instance_variable_get('@secure').should eq(Request::Secure::No) end it %q(should raise an error when api's HTTP method is not set to GET or POST) do expect { DSL.new(API.new, 'group') {api 'error', :error} }.to raise_error(Error) end end context 'underscore' do subject do DSL.new(nil, nil) end it 'should return first_second_third for firstSecondThird' do subject.method(:underscore).call('firstSecondThird').should eq('first_second_third') end end end end end
require 'active_support/concern' require 'active_model/naming' require 'active_model/attribute_methods' module Circuit module Storage module MemoryModel extend ActiveSupport::Concern include ActiveModel::AttributeMethods include Compatibility::ActiveModel31 attr_reader :attributes, :errors attr_accessor :name included do extend ActiveModel::Naming class_attribute :all self.all = Array.new end module ClassMethods def setup_attributes(*attrs) attribute_method_suffix '?' attribute_method_suffix '=' define_attribute_methods attrs.collect(&:to_sym) end end def attributes=(hash) @attributes = hash.with_indifferent_access end def save! self.save ? true : raise("Invalid %s: %p"%[self.class, self.errors]) end def persisted? @persisted end def persisted!(val=true) @persisted = val end def eql?(obj) obj.instance_of?(self.class) && obj.attributes == self.attributes end protected def attribute(key) attributes[key] end def attribute=(key, val) attributes[key] = val end def attribute?(attr) !attributes[attr.to_sym].blank? end def memory_model_setup @persisted = false @attributes = HashWithIndifferentAccess.new @errors = ActiveModel::Errors.new(self) end end end end
require 'spec_helper' describe Immutable::Vector do describe '#bsearch' do let(:vector) { V[5,10,20,30] } context 'with a block which returns false for elements below desired position, and true for those at/above' do it 'returns the first element for which the predicate is true' do vector.bsearch { |x| x > 10 }.should be(20) vector.bsearch { |x| x > 1 }.should be(5) vector.bsearch { |x| x > 25 }.should be(30) end context 'if the block always returns false' do it 'returns nil' do vector.bsearch { false }.should be_nil end end context 'if the block always returns true' do it 'returns the first element' do vector.bsearch { true }.should be(5) end end end context 'with a block which returns a negative number for elements below desired position, zero for the right element, and positive for those above' do it 'returns the element for which the block returns zero' do vector.bsearch { |x| x <=> 10 }.should be(10) end context 'if the block always returns positive' do it 'returns nil' do vector.bsearch { 1 }.should be_nil end end context 'if the block always returns negative' do it 'returns nil' do vector.bsearch { -1 }.should be_nil end end context 'if the block returns sometimes positive, sometimes negative, but never zero' do it 'returns nil' do vector.bsearch { |x| x <=> 11 }.should be_nil end end context 'if not passed a block' do it 'returns an Enumerator' do enum = vector.bsearch enum.should be_a(Enumerator) enum.each { |x| x <=> 10 }.should == 10 end end end context 'on an empty vector' do it 'returns nil' do V.empty.bsearch { |x| x > 5 }.should be_nil end end end end
require_relative '../util/diagram' require_relative '../util/java' module Asciidoctor module Diagram module DitaaGenerator DITAA_JAR_PATH = File.expand_path File.join('../..', 'ditaamini0_9.jar'), File.dirname(__FILE__) Java.classpath << DITAA_JAR_PATH def self.ditaa(code) Java.load args = ['-e', 'UTF-8'] bytes = code.encode(Encoding::UTF_8).bytes.to_a bis = Java.new_object(Java.java.io.ByteArrayInputStream, '[B', Java.array_to_java_array(bytes, :byte)) bos = Java.new_object(Java.java.io.ByteArrayOutputStream) result_code = Java.org.stathissideris.ascii2image.core.CommandLineConverter.convert(Java.array_to_java_array(args, :string), bis, bos) bis.close bos.close result = Java.string_from_java_bytes(bos.toByteArray) raise "Ditaa image generation failed: #{result}" unless result_code == 0 result end end define_processors('Ditaa') do register_format(:png, :image) do |c| DitaaGenerator.ditaa(c) end end end end
class Events::StartFollowingPeople < Events::Event def to_s "#{self.subject.first_name} is now following %a=#{self.object.full_name}" end end
############################################################################### # # Back-End Web Development - Homework #1 # # Secret Number Game # Created by Mercer Hall # Instructed by Spencer Rogers # ############################################################################### # Well, this program works successfully, and it accounts for many possible user mistakes. # I realize that I have used global variables, which is not ideal. # I wanted to program for multiple contingencies, such as if the user inputed a number not between 1 and 10, # or if the user inputed a number that they had already inputed. # I also wanted to practice with methods and set up scenarios that would be applicable to future exercises, # rather than just typing out the code in sequence. # So the code here is not DRY, and it is probably unnecessarily complicated for this beginning stage. # I'll include more reflections in my development journal: mhallbewd.wordpress.com def display_title(title) puts title end def display_name(name) puts "\nGreetings #{name}." end def display_rules(rules) puts rules end def higher_lower(guess) if $secret_number < guess puts "You guessed too high. Choose a lower number." else puts "You guessed too low. Choose a higher number." end end def makeguess_one(guess_one) if $guess_one > 10 puts "That number is not between 1 and 10. Please try again." $guess_one = $stdin.gets.chomp.to_i makeguess_one($guess_one) elsif $guess_one < 1 puts "That number is not between 1 and 10. Please try again." $guess_one = $stdin.gets.chomp.to_i makeguess_one($guess_one) elsif $guess_one == $secret_number puts "Congratulations! You guessed the secret number! You win!" exit else guess = $guess_one higher_lower(guess) end end def makeguess_two(guess_two) if $guess_two > 10 puts "That number is not between 1 and 10. Please try again:" $guess_two = $stdin.gets.chomp.to_i makeguess_two($guess_two) elsif $guess_two < 1 puts "That number is not between 1 and 10. Please try again:" $guess_two = $stdin.gets.chomp.to_i makeguess_two($guess_two) elsif $guess_two == $guess_one puts "You already guessed that number. Please try again:" $guess_two = $stdin.gets.chomp.to_i makeguess_two($guess_two) elsif $guess_two == $secret_number puts "Congratulations! You guessed the secret number! You win!" exit else guess = $guess_two higher_lower(guess) end end def makeguess_three(guess_three) if $guess_three > 10 puts "That number is not between 1 and 10. Please try again:" $guess_three = $stdin.gets.chomp.to_i makeguess_three($guess_three) elsif $guess_three < 1 puts "That number is not between 1 and 10. Please try again:" $guess_three = $stdin.gets.chomp.to_i makeguess_three($guess_three) elsif $guess_three == $guess_one || $guess_three == $guess_two puts "You already guessed that number. Please try again:" $guess_three = $stdin.gets.chomp.to_i makeguess_three($guess_three) elsif $guess_three == $secret_number puts "Congratulations! You guessed the secret number! You win!" exit else puts "I'm sorry. You lost. The game is over. The secret number was #{$secret_number}." end end # Welcome the player to your game. Let them know who created the game. title = "\nWelcome to the exciting new game that is sweeping America: SECRET NUMBER! Created by a rogue international hacker, this game will test your endurance and reward your wits. Enjoy the challenge!" display_title(title) # Ask for the player's name then personally greet them by printing to the screen, "Hi player_name!" puts "Please enter your name:" name = $stdin.gets.chomp display_name(name) # Communicate the rules. # Let player know they must guess a number between 1 and 10 and that they only have 3 tries. rules = "Try to guess the secret number. \nPick any number between 1 and 10, but beware ... you only have 3 tries!" display_rules(rules) # Hard code the secret number. Make it a random number between 1 and 10. $secret_number = 6 # Ask the user for their first guess. puts "Please enter your first guess:" $guess_one = $stdin.gets.chomp.to_i # Run make_guess_one method, check if acceptable number, check if correct, give higher or lower advice. # Run make_guess_two method. makeguess_one($guess_one) puts "You have 2 guesses remaining. Please enter your second guess:" $guess_two = $stdin.gets.chomp.to_i # Run make_guess_two method, check if acceptable number, check if already guessed that number, check if correct, give higher or lower advice. # Run make_guess_three method. makeguess_two($guess_two) puts "You only have one more guess. Please enter your third guess:" $guess_three = $stdin.gets.chomp.to_i # Run make_guess_three method, check if acceptable number, check if already guessed that number, check if correct. # If not corrent, tell print that game is over and tell secert number. makeguess_three($guess_three) ###############################################################################
class CreateAuctions < ActiveRecord::Migration def change create_table :auctions do |t| t.integer :user_id t.string :title t.text :description t.integer :starting_price, :default => 0 t.integer :brand_id t.integer :clothing_condition_id t.integer :clothing_type_id t.integer :season_id t.datetime :created_at t.datetime :updated_at t.string :item_photo t.timestamps end end end
require 'test_helper' class ProjectsTest < ActionDispatch::IntegrationTest test "project index should display all projects" do get projects_path assert_template 'projects/index' projects.each do |project| assert_match project.name, response.body end end test "project index should contain link to new project" do get projects_path assert_select 'a[href=?]', new_project_path end test "shouldn't be able to create a new project with no name" do get new_project_path assert_template "projects/new" assert_no_difference 'Project.count' do post projects_path, project: { name: "" } end assert_template "projects/new" end test "should be able to create a project with a valid name" do get new_project_path assert_difference 'Project.count', 1 do post projects_path, project: { name: "My New Project Name" } end project = assigns(:project) assert_redirected_to project_path(project) end test "should be able to access new note page from project show" do project = projects(:one) get project_path(project) assert_template "projects/show" assert_select "a[href=?]", new_project_note_path(project) end test "projects show page should display all notes" do project = projects(:one) get project_path(project) project.notes.each do |note| assert_match note.title, response.body end end end
class PokemonsController < ApplicationController def capture @pokemon = Pokemon.find(params[:id]) @pokemon.update(trainer_id: current_trainer.id) @pokemon.save redirect_to '/' end def index @pokemons = Pokemon.all end def damage @pokemon = Pokemon.find(params[:id]) @pokemon.health = @pokemon.health - 10 if @pokemon.health <= 0 @pokemon.destroy else @pokemon.save end redirect_to trainer_path(@pokemon.trainer_id) end def new @pokemon = Pokemon.new end def find @pokemon = Pokemon.new end def create @pokemon = Pokemon.new(pokemon_params) @pokemon.update(level: 1, health: 100, trainer_id: current_trainer.id) if @pokemon.save redirect_to current_trainer else redirect_to new_path flash[:error] = @pokemon.errors.full_messages.to_sentence end end private def pokemon_params params.require(:pokemon).permit(:name, :ndex) end end
class Viewpoints::Acts::Moderateable::ContentField < ActiveRecord::Base belongs_to :content_document has_many :filtered_words serialize :field_value # Reload the AR objects in value if we want. We need to purge any loaded associations before Rails serializes it. def field_value=(value) if value.is_a?(Array) value.collect! do |item| if item.respond_to?(:reload) && (item.respond_to?(:new_record?) && !item.new_record?) item.reload else item end end elsif value.respond_to?(:reload) && (value.respond_to?(:new_record?) && !value.new_record?) value.reload end self.write_attribute(:field_value, value) end end
require 'user' describe User do describe '#all' do it 'returns all users, wrapped in a User instance' do user = User.create(username: 'Tester', email: 'test@example.com', password: 'password123') expect(User.all.map(&:id)).to include user.id end end subject(:user) { described_class.create(username: 'Tester', email: 'test@example.com', password: 'password123') } describe '#create' do it 'creates a new user' do expect(user.id).not_to be_nil end end it 'hashes the password using BCrypt' do expect(BCrypt::Password).to receive(:create).with('password123') User.create(username: 'Tester', email: 'test@example.com', password: 'password123') end end describe '#find' do it 'finds a user by ID' do # this rspec did not work after refactoring tests to truncate before eahc one, this will cause it to add to db user = User.create(username: 'Tester', email: 'test@example.com', password: 'password123') expect(User.find(user.id).email).to eq user.email end describe '#authenticate' do it 'returns a user given a correct username and password, if one exists' do user = User.create(username: 'Tester', email: 'test@example.com', password: 'password123') authenticated_user = User.authenticate('test@example.com', 'password123') expect(authenticated_user.id).to eq user.id end it 'returns nil given an incorrect email address' do expect(User.authenticate('nottherightemail@me.com', 'password123')).to be_nil end it 'returns nil given an incorrect password' do expect(User.authenticate('test@example.com', 'wrongpassword')).to be_nil end end end
class HelloController < ApplicationController def index render plain: "Hello! It's #{ Time.current }" end end
class CreateOpinions < ActiveRecord::Migration[6.1] def change create_table :opinions do |t| t.string :cliente t.string :descripcion t.integer :calificacion t.string :foto t.timestamps end end end
module Kuhsaft module Cms module PagesHelper def content_tab_active(page) :active unless hide_content_tab?(page) end def metadata_tab_active(page) :active if hide_content_tab?(page) end def hide_content_tab?(page) page.page_type == Kuhsaft::PageType::REDIRECT || !page.translated? || !page.persisted? || page.errors.present? end end end end
class GreenEggsAndHam def initialize @text = File.read('green_eggs_and_ham.txt') end def word_count @text.split.count end def sorted_unique_words words = @text.gsub(/[,.?!]/,"").split words.map { |word| word.downcase }.uniq.sort end def number_of_words_shorter_than(number) words = @text.gsub(/[,.?!]/,"").split short_words = words.select { |word| word.length < number } short_words.count end def longest_word words = @text.gsub(/[,.?!]/, "").split words.max { |word| word.length } end def frequency_of_unique_words words = @text.gsub(/[,.?!]/, "").split frequency = Hash.new(0) words.each { |word| frequency [word.downcase] += 1 } frequency end def stanzas stanzas = @text.split(/\n\n/) end def lines @text.gsub(/\n\n/, "\n").split("\n") end end
class SongGenre < ActiveRecord::Base attr_accessible :genre, :song, :song_id, :genre_id belongs_to :song belongs_to :genre end
class Product < ActiveRecord::Base has_and_belongs_to_many :users has_many :prices validates_uniqueness_of :name validates_presence_of :name before_save {|product| product.name = product.name.downcase} end
require 'rails' # require "active_record/railtie" require "action_view/railtie" require "action_controller/railtie" # require "action_mailer/railtie" require "active_job/railtie" # require "action_cable/engine" # require "sprockets/railtie" # require "rails/test_unit/railtie" require 'raven/integrations/rails' ActiveSupport::Deprecation.silenced = true class TestApp < Rails::Application end class HelloController < ActionController::Base def exception raise "An unhandled exception!" end def view_exception render inline: "<%= foo %>" end def world render :plain => "Hello World!" end end def make_basic_app app = Class.new(TestApp) do def self.name "RailsTestApp" end end app.config.hosts = nil app.config.secret_key_base = "test" # Usually set for us in production.rb app.config.eager_load = true app.routes.append do get "/exception", :to => "hello#exception" get "/view_exception", :to => "hello#view_exception" root :to => "hello#world" end app.initializer :configure_release do Raven.configure do |config| config.release = 'beta' end end app.initialize! Rails.application = app app end
# encoding: utf-8 class Production < ActiveRecord::Base attr_accessor :proj_name attr_accessible :name, :eng_id, :project_id, :start_date, :finish_date, :as => :role_new attr_accessible :name, :eng_id, :completed, :start_date, :finish_date, :as => :role_update #has_and_belongs_to_many :categories belongs_to :input_by, :class_name => 'User' belongs_to :eng, :class_name => 'User' belongs_to :project has_many :production_logs validates :name, :presence => true, :uniqueness => {:case_sensitive => false} validates_numericality_of :project_id, :greater_than => 0 validates_numericality_of :eng_id, :greater_than => 0 validates :start_date, :presence => true validates :finish_date, :presence => true end
require_relative 'booking' class Listing < ActiveRecord::Base belongs_to :user has_many :bookings has_many :requests, :through => :bookings validates :user_id, presence: true validates :name, presence: true validates :description, presence: true validates :ppn, presence: true validates :start_date, presence: true validates :end_date, presence: true def create_booking_dates start_year = self.start_date.to_s[0,4].to_i start_month = self.start_date.to_s[4,2].to_i start_day = self.start_date.to_s[6, 2].to_i end_year = self.end_date.to_s[0,4].to_i end_month = self.end_date.to_s[4,2].to_i end_day = self.end_date.to_s[6, 2].to_i start_date = Date.new(start_year, start_month, start_day) end_date = Date.new(end_year, end_month, end_day) input_date = start_date until input_date == end_date count = 0 Booking.create( listing_id: self.id, date: input_date ) count += 1 input_date = input_date.advance(days: count) end end end
class AddSpreePaymentMethodIdToSpreeGlobalCollectCheckout < ActiveRecord::Migration def change rename_column :spree_global_collect_checkouts, :payment_method_id, :gc_payment_method_id add_column :spree_global_collect_checkouts, :payment_method_id, :integer end end
# frozen_string_literal: true module ActiveInteractor module State # State mutation methods. Because {Mutation} is a module classes should include {Mutation} rather than inherit from # it. # # @author Aaron Allen <hello@aaronmallen.me> # @since unreleased # # @!attribute [r] errors # @return [ActiveModel::Errors] an instance of # {https://api.rubyonrails.org/classes/ActiveModel/Errors.html ActiveModel::Errors} module Mutation attr_reader :errors # Initiailize a new instance of {Manager} # # @return [Manager] a new instance of {Manager} def initialize @errors = ActiveModel::Errors.new(self) end # Add an instance of {ActiveInteractor::Base interactor} to the list of {ActiveInteractor::Base interactors} # called on the {Manager state}. This list is used when {Mutation#rollback!} is called on a {Manager state} # instance. # # @param interactor [#rollback] an {ActiveInteractor::Base interactor} instance # @return [self] the {Manager state} instance. def called!(interactor) return self unless interactor.respond_to?(:rollback) _called << interactor self end # Fail the {Manager state} instance. The instance is flagged as having failed. # # @param errors [ActiveModel::Errors, String] error messages for the failure # @see https://api.rubyonrails.org/classes/ActiveModel/Errors.html ActiveModel::Errors # @return [self] the {Manager state} instance. def fail!(errors = nil) handle_errors(errors) if errors @_failed = true self end # {#rollback! Rollback} an instance of {Manager state}. Any {ActiveInteractor::Base interactors} the instance has # been passed via the {#called!} method are asked to roll themselves back by invoking their # {Interactor::Perform#rollback #rollback} methods. The instance is also flagged as rolled back. # # @return [self] the {Manager state} instance. def rollback! return self if rolled_back? _called.reverse_each(&:rollback) @_rolled_back = true self end private def _called @_called ||= [] end def handle_errors(errors) if errors.is_a?(String) self.errors.add(:interactor, errors) else self.errors.merge!(errors) end end end end end
module Dustbag module Price extend self def parse(xml_node) xml_node && begin amount = xml_node.locate('Amount').first currency = xml_node.locate('Currency').first Money.new(amount && amount.text, currency && currency.text) end end end end
require 'optparse' require 'time' require_relative 'helpers' # https://docs.ruby-lang.org/en/2.1.0/OptionParser.html Options = Struct.new( :ignore_regex_string, :scan_date, :add_totals, :json_output, :per_thousand_lines_of_code, :input_directory ) # Parses the command line arguments class Parser def self.default_options result = Options.new result.scan_date = Time.now.iso8601(3) result.add_totals = false result.json_output = false result.per_thousand_lines_of_code = false result.input_directory = '.' result end private_class_method :default_options def self.parse(argv) # if no arguments, print help argv << '-h' if argv.empty? result = default_options options_parser = OptionParser.new do |o| o.banner = "Usage: #{EXECUTABLE_NAME} [options] [input directory]" o.on('-h', '--help', 'Prints this help') do puts options_parser exit 0 end o.on('-tTODAY', '--today=TODAY', "Today's date for testing purposes (string)") do |v| result.scan_date = v end o.on('-iIGNORE', '--ignore-regex=IGNORE', 'Case sensitive ignore files regex. Eg. "Pods|Test"') do |v| result.ignore_regex_string = v end o.on('--json', 'Output in JSON format') do |v| result.json_output = v end o.on('--totals', 'Add totals') do |v| result.add_totals = v end o.on('--per-thousand-lines', 'Output counts/1000 lines of code') do |v| result.per_thousand_lines_of_code = v end end begin options_parser.parse!(argv) rescue StandardError => exception puts exception puts options_parser exit 1 end result.input_directory = argv.pop if result.input_directory.nil? || !Dir.exist?(result.input_directory) puts 'Can\'t find directory ' Parser.parse %w[--help] exit 1 end result end end
require_relative 'spec_helper' describe Utley do describe "publish" do describe "when there is one event" do let(:events) { [Object.new]} describe "and there's one subscriber for the event" do let(:subscribers) { [Object.new] } before do Utley::Subscriber.stubs(:for).with(events.first).returns subscribers end it "should create the subscriber and pass the even to it" do subscribers.first.expects(:receive).with events.first Utley.publish events end end describe "and there are two subscribers for the event" do let(:subscribers) { [Object.new, Object.new] } before do Utley::Subscriber.stubs(:for).with(events.first).returns subscribers end it "should create the subscriber and pass the even to it" do subscribers[0].expects(:receive).with events.first subscribers[1].expects(:receive).with events.first Utley.publish events end end end describe "when there are two events" do let(:events) { [Object.new, Object.new]} describe "and there's one subscriber for both events" do let(:subscribers1) { [Object.new] } let(:subscribers2) { [Object.new] } before do Utley::Subscriber.stubs(:for).with(events[0]).returns subscribers1 Utley::Subscriber.stubs(:for).with(events[1]).returns subscribers2 end it "should pass the events to the subscribers" do subscribers1[0].expects(:receive).with events[0] subscribers2[0].expects(:receive).with events[1] Utley.publish events end end end end end
class CreateTasks < ActiveRecord::Migration[6.0] def change create_table :tasks do |t| t.string :title t.integer :priority_level t.datetime :due_date t.string :tag t.string :description t.boolean :completion_status t.timestamps end end end
# Represents the compiled course.xml class Course::Content attr_reader :course, :course_name, :version def self.memoize(*method_syms) for sym in method_syms module_eval <<-THERE alias_method :__#{sym}__, :#{sym} private :__#{sym}__ def #{sym}(*args, &block) @__#{sym}__ ||= __#{sym}__(*args, &block) end THERE end end def initialize(course, version = nil) raise "course is not yet compiled: Course(#{course.id})" if !course.compiled? @course = course @course_name = course.name @version = version end def xml_dom Nokogiri::HTML(xml) end memoize :xml_dom def xml File.read course.xml_path end memoize :xml def page_dom(name) xml_dom.css("page[name=#{name}]")[0] end #{:desc =>"desc", :title => "title"} def course_info { desc: nil, title: course_title } end memoize :course_info #[{:name => "name", :title => "title", :overview => "overview",:bbs =>"http://.." ,:discourse_topic_id => ""}, {...}] #return in order def lessons_info temp_lessons_info = [] index_dom.css("week").sort.each do |week_node| week_lessons = week_lessons_sort_by_day(week_node) week_lessons.each do |lesson_node| name = lesson_node["name"] temp_lessons_info << lesson_info(name) end end temp_lessons_info end # def position_of_lesson(name) if i = lessons_info.index { |info| info[:name] == name } return i + 1 end raise "cannot find lesson position by name: #{name}" end memoize :lessons_info def lesson_info(name) node = xml_dom.css("lesson[name=#{name}]").first info = {} info[:title] = lesson_title(node["name"]) info[:overview] = node.css("overview").children.to_xhtml.strip info[:old_name] = node["old-name"] info[:name] = node["name"] info[:project] = node["project"] return info end #[{:name => "name", :title => "title"}] #without order def extra_lessons_info lesson_names = index_dom.css("lesson").map { |node| node["name"] } extra_node = xml_dom.css("page").find_all do |page_node| lesson_names.all?{ |lesson_name| lesson_name != page_node["name"] } end extra_node.map do |node| {:name => node["name"], :title => node.css("h1")[0].text} end end memoize :extra_lessons_info #[{:title => "title", :overview => "overview"}, {...}] #return in order def weeks_info temp_weeks_info = [] index_dom.css("week").sort.each do |week_node| info = {} title = week_node.css("> h2")[0].text overview_node = week_node.css("> overview")[0] overview = overview_node ? overview_node.children.to_xhtml : "" info[:title] = title info[:overview] = overview temp_weeks_info << info end temp_weeks_info end memoize :weeks_info #{lesson_name => day, lesson_name2 => day2} def release_day_of_lesson temp_release_day_of_lesson = {} week_num = 0 index_dom.css("week").each do |week_node| week_node.css("lesson").each do |lesson_node| lesson_release_day = 7 * week_num + lesson_node["day"].to_i temp_release_day_of_lesson[lesson_node["name"]] = lesson_release_day end week_num += 1 end temp_release_day_of_lesson end memoize :release_day_of_lesson #[[lesson1_name,lesson2_name],[]] #return in order def course_weeks index_dom.css("week").sort.map do |week_node| week_lessons = week_lessons_sort_by_day(week_node) week_lessons.map do |lesson_node| lesson_node["name"] end end end memoize :course_weeks def lesson_content(lesson_name) index_dom.css("page[name=#{lesson_name}]")[0].children.to_xhtml end private def week_lessons_sort_by_day(week_node) week_node.css("lesson").sort_by do |lesson_node| lesson_node["day"].to_i end end def lesson_nodes_sort_by_day(lesson_nodes) lesson_nodes.sort_by do |lesson_node| lesson_node["day"].to_i end end def course_title xml_dom.css("course")[0]["name"] end def lesson_title(lesson_name) page_dom(lesson_name).css("h1").first.text end def index_dom @index_dom ||= xml_dom.css("index")[0] end end
class Kategory < ActiveRecord::Base belongs_to :instance, counter_cache: true has_many :operations has_many :stores, through: :operations validates_presence_of :name, :instance_id validates_uniqueness_of :name, scope: :instance_id mount_uploader :logo, LogoUploader default_scope { order('kategories.sequence ASC') } before_destroy :clean_operations def clean_operations operations.update_all kategory_id: nil end end
require 'spec_helper' describe PrivateMessage do before(:each) do Factory(:private_message) end it { should belong_to(:sender) } it { should belong_to(:recipient) } it { should belong_to(:parent) } it { should have_many(:replies) } it { should have_one(:received_message) } it { should validate_presence_of(:sender_id) } it { should validate_presence_of(:recipient_id) } it { should validate_presence_of(:content) } describe "being created" do before(:each) do @sender = Factory(:user) @recipient = Factory(:user) @message = Factory(:private_message, :sender => @sender, :recipient => @recipient) end it "creates received messages for recipient" do @recipient.received_messages.should == [@message.received_message] end it "sets conversation id for received message to self id" do @message.received_message.conversation_id.should == @message.id end context "with parent" do before(:each) do @parent = Factory(:private_message) @message = Factory(:private_message, :parent => @parent) end it "sets conversation id for received message to parent id" do @message.received_message.conversation_id.should == @parent.id end end end describe ".build_from_params" do it "creates an instance with recipient and sender initialized" do @recipient = Factory(:user) @sender = Factory(:user) @message = PrivateMessage.build_from_params({ :user_id => @recipient.username, :private_message => { :content => "content of message" } }, @sender) @message.recipient.should == @recipient @message.content.should == "content of message" @message.sender.should == @sender end end context "in conversations" do before(:each) do @conversation = Factory(:private_message) 5.times do @conversation.replies << Factory(:private_message, :recipient => @conversation.recipient) end end it "marks all messages as read" do @conversation.unread_by?(@conversation.recipient).should be_true @conversation.read_for!(@conversation.recipient) @conversation.unread_by?(@conversation.recipient).should be_false end end end
class Review < ActiveRecord::Base attr_accessible :comment, :restaurant_id, :star_rating, :user_id belongs_to :resutaurant belongs_to :user before_create :one_review_per_one_user def reviewer User.find(user_id) end def restaurant Restaurant.find(restaurant_id) end def one_review_per_one_user @restaurant = Restaurant.find(self.restaurant_id) @user = User.find(self.user_id) @user.reviews.where(:restaurant_id=>@restaurant.id).first.blank? ? @already_reviewd = false : @already_reviewd = true raise "already reviewed" if @already_reviewd end end
class AddUserIdToScenes < ActiveRecord::Migration def change add_column :scenes, :user_id, :integer, :default => 0 add_column :scenes, :ip_address, 'char(15)', :default => '' end end
namespace :antibody do desc "Create database, load the schema, and initialize with data" task :setup => :environment do Rake::Task["db:create"].invoke Rake::Task["db:schema:load"].invoke Rake::Task["antibody:update:all"].invoke end desc "recreate database, load the schema, and initialize with data" task :reset => :environment do Rake::Task["db:drop"].invoke Rake::Task["antibody:setup"].invoke end desc "load Antibody data" task :load, :file, :model, :needs => :environment do |task, args| file = args[:file] model = Object.const_get(args[:model]) File.open(file, "r") do |f| records = [] columns = [] f.each_line do |line| if f.lineno == 1 columns = line.strip.split(/\t/).map {|a| a.to_sym} else params = {} values = line.strip.split(/\t/) values.each_index do |i| key = columns[i] params[key] = values[i] end m = model.new(params) m.id = values[0] m.save! #records << model.new(params) end end #model.import records end end namespace :update do desc "update all data" task :all => :environment do [].each do |task| Rake::Task["antibody:update:#{task}"].invoke end end end end
class AddLiteracyRatePercentageAbove15ToCountries < ActiveRecord::Migration def change add_column :countries, :most_recent_literacy_rate_percentage_above_15, :decimal end end
require 'spec_helper' describe Employee do before do @employee = Employee.new(name: "Example User", email: "user@example.com", userid: "123456", password: "foobar", password_confirmation: "foobar") end subject { @employee } it { should respond_to(:name) } it { should respond_to(:email) } it { should respond_to(:userid) } it { should respond_to(:password_digest) } it { should respond_to(:password) } it { should respond_to(:password_confirmation) } it { should respond_to(:remember_token) } it { should respond_to(:authenticate) } it { should respond_to(:admin) } it { should respond_to(:events) } it { should be_valid } it { should_not be_admin } describe "with admin attribute set to 'true'" do before do @employee.save! @employee.toggle!(:admin) end it { should be_admin } end it { should be_valid } describe "return value of authenticate method" do before { @employee.save } let(:found_user) { Employee.find_by(email: @employee.email) } describe "with valid password" do it { should eq found_user.authenticate(@employee.password) } end describe "with invalid password" do let(:user_for_invalid_password) { found_user.authenticate("invalid") } it { should_not eq user_for_invalid_password } specify { expect(user_for_invalid_password).to be_false } end end describe "when name is not present" do before { @employee.name = " " } it { should_not be_valid } end describe "when email is not present" do before { @employee.email = " " } it { should_not be_valid } end describe "when userid is not present" do before { @employee.userid = " " } it { should_not be_valid } end describe "when password is not present" do before do @employee = Employee.new(name: "Example User", email: "user@example.com", password: " ", password_confirmation: " ") end it { should_not be_valid } end describe "when password doesn't match confirmation" do before { @employee.password_confirmation = "mismatch" } it { should_not be_valid } end describe "when name is too long" do before { @employee.name = "a" * 51 } it { should_not be_valid } end describe "when email format is invalid" do it "should be invalid" do addresses = %w[user@foo,com user_at_foo.org example.user@foo. foo@bar_baz.com foo@bar+baz.com] addresses.each do |invalid_address| @employee.email = invalid_address expect(@employee).not_to be_valid end end end describe "when email format is valid" do it "should be valid" do addresses = %w[user@foo.COM A_US-ER@f.b.org frst.lst@foo.jp a+b@baz.cn] addresses.each do |valid_address| @employee.email = valid_address expect(@employee).to be_valid end end end describe "when user ID address is already taken" do before do user_with_same_userid = @employee.dup user_with_same_userid.email = @employee.email.upcase user_with_same_userid.save end it { should_not be_valid } end describe "with a password that's too short" do before { @employee.password = @employee.password_confirmation = "a" * 5 } it { should be_invalid } end describe "remember token" do before { @employee.save } its(:remember_token) { should_not be_blank } end describe "event associations" do before { @employee.save } let!(:older_event) do FactoryGirl.create(:event, employee: @employee, start_date: 14.days.from_now, end_date: 30.days.from_now, created_at: 1.day.ago) end let!(:newer_event) do FactoryGirl.create(:event, employee: @employee, start_date: 3.days.from_now, end_date: 120.days.from_now, created_at: 1.hour.ago) end it "should have the right microposts in the right order" do expect(@employee.events.to_a).to eq [newer_event, older_event] end end end
class LikesController < ApplicationController before_action :authenticate_user! def like_toggle post = Post.find(params[:post_id]) like = post.likes.find_by(user: current_user) if like.nil? post.likes.create!(user: current_user) @result = 'heart' else like.destroy @result = 'heart-empty' end end end
class CreateLocations < ActiveRecord::Migration def change create_table :locations do |t| t.string :name t.string :type t.string :zip t.string :comune t.string :provincia t.string :numero_civico t.string :estensione_civico t.string :nomero_interno t.string :estensione_interno t.integer :customer_id t.timestamps end end end
module View def self.render(people_data) # system 'clear' view = "\n\nHere is the data you asked for:\n" people_data.each do |person| name = "#{person.firstname} #{person.lastname}" gender = person.gender color = person.favorite_color bday = person.birthdate view += "\n#{name} (#{gender}) was born on #{bday}, and loves #{color}." end puts view view end def self.get_input puts "Please select an option by entering the corresponding {command}:" puts "1. show all people, sorted by {gender} and last name ascending" puts "2. show all people, {birthdate} ascending" puts "3. show all people, sorted by {lastname} descending" puts "4. {exit} the program" input = gets.chomp exit if input == 'exit' return input if ['gender', 'birthdate', 'lastname'].include?(input) puts 'Please enter a valid command...' get_input end end
module Onering module CLI class Assets < Plugin def self.configure(global={}) @api = Onering::CLI.connect(global).assets @opts = ::Trollop::options do banner <<-EOS Search for, manipulate, and list values from one or more Onering assets. Usage: onering [global] assets [options] [subcommands] Subcommands: find <urlquery> get <property> [property2 ..] list <property> [property2 ..] save set <property> <value> tag <tag1>[ tag2 .. tagN] untag <tag1>[ tag2 .. tagN] Options: EOS opt :query, "The Onering urlquery to filter devices by", :short => '-f', :type => :string opt :id, "The node ID of the device to operate on", :short => '-i', :type => :string # subcommands stop_on %w{show get set list find save} end end def self.run(args) sc = args.shift case (sc.downcase.to_sym rescue nil) # ----------------------------------------------------------------------------- when :show return @api.assets.show(args[0]) # ----------------------------------------------------------------------------- when :get Onering::Logger.fatal!("Expected 1 parameter, got #{args.length}", "Onering::CLI::Assets") unless args.length == 1 if @opts[:query_given] # doing this until a bulk field query endpoint is built return @api.list('id', { :filter => @opts[:query] }).collect{|i| @api.get_field(i, args[0])} elsif @opts[:id_given] return @api.get_field(@opts[:id], args[0]) end # ----------------------------------------------------------------------------- when :set Onering::Logger.fatal!("Expected 2 parameters, got #{args.length}", "Onering::CLI::Assets") unless args.length == 2 if @opts[:query] # doing this until a bulk field set endpoint is built return @api.list('id', { :filter => @opts[:query] }).collect{|i| @api.set_field(i, args[0])} elsif @opts[:id] return @api.set_field(@opts[:id], args[0], args[1]) end # ----------------------------------------------------------------------------- when :list Onering::Logger.fatal!("Expected 1 parameter, got #{args.length}", "Onering::CLI::Assets") unless args.length >= 1 return @api.list(args, { :filter => @opts[:query] }.compact) # ----------------------------------------------------------------------------- when :find Onering::Logger.fatal!("Expected 1 parameter, got #{args.length}", "Onering::CLI::Assets") unless args.length == 1 return @api.find(args[0]) # ----------------------------------------------------------------------------- when :save rv = @api.save(args[0] || @opts[:id]) do # read from pipe if not STDIN.tty? STDIN.read() # read from specified file elsif (File.readable?(args[1]) rescue false) File.read(args[1]) else Onering::Logger.fatal!("Cannot save data, no input data specified", "Onering::CLI::Assets") end end rv.parsed_response # ----------------------------------------------------------------------------- when :tag Onering::Logger.fatal!("Expected 1 parameters, got #{args.length}", "Onering::CLI::Assets") unless args.length > 0 if @opts[:query] # doing this until a bulk field set endpoint is built @api.list('id', { :filter => @opts[:query] }).collect{|i| @api.get("devices/#{i}/tag/#{args.join('/')}") } elsif @opts[:id] @api.get("devices/#{@opts[:id]}/tag/#{args.join('/')}") end return nil when :untag Onering::Logger.fatal!("Expected 1 parameters, got #{args.length}", "Onering::CLI::Assets") unless args.length > 0 if @opts[:query] # doing this until a bulk field set endpoint is built @api.list('id', { :filter => @opts[:query] }).collect{|i| @api.get("devices/#{i}/untag/#{args.join('/')}") } elsif @opts[:id] @api.get("devices/#{@opts[:id]}/untag/#{args.join('/')}") end return nil else Onering::Logger.fatal!("Unknown subcommand #{sc.inspect}", "Onering::CLI::Assets") end end end end end
class CreateButtons < ActiveRecord::Migration def change create_table :buttons do |t| t.references :styleguide, index: true, foreign_key: true t.text :html t.string :color t.text :css t.string :name t.timestamps null: false end end end
require 'sinatra' require 'thin' require 'base64' require 'json' require 'colorize' require 'data_mapper' require 'dm-migrations' require 'dm-timestamps' class ExtrudedData include DataMapper::Resource property :id, Serial property :time, DateTime property :email, String property :search, String property :subject, String property :content, Text end DataMapper.setup(:default, "sqlite://#{File.expand_path('..', __FILE__)}/extruded_data.db") DataMapper.auto_upgrade! class Extruder < ::Thin::Backends::TcpServer def initialize(host, port, options) super(host, port) @ssl = true @ssl_options = options end end configure do set :environment, :production set :bind, '0.0.0.0' set :port, 443 set :server, 'thin' class << settings # NOTE. sometimes bundle CA certs are needed, since Thin doesn't support specifying it, you can just cat the bundle after the cert # cat example.crt godaddy-bundle.crt > new-example-with-bundle.crt def server_settings { :backend => Extruder, :private_key_file => "#{File.dirname(__FILE__)}/your_domain.key", :cert_chain_file => "#{File.dirname(__FILE__)}/your_domain.crt", :verify_peer => false } end end end get '/owa/extrude' do # TODO improve the data grid table. ideally use jquery dataGrid or bootstrap. response = "<table style='width:100%' border='1'><tr><th>Email</th><th>Search</th><th>Subject</th><th>Content</th></tr>" emails = ExtrudedData.find_all puts "Found #{emails.size} emails." emails.each do |mail| resp = <<EOF <tr> <td>#{mail.email}</td> <td>#{mail.search}</td> <td>#{mail.subject}</td> <td><iframe width="700" height="300" src="data:text/html;base64,#{Base64.encode64(mail.content)}"></iframe></td> </tr> EOF response += resp end response += "</table>" response end post '/owa/extrude' do begin data = JSON.parse(Base64.decode64(params[:data])) puts "------------> Got Extruded Packet from Target #{data['target']} <------------".colorize(:red) puts "Search Criteria: ".colorize(:green) + data['search'] puts "Subject: ".colorize(:blue) + data['subject'] content = Base64.decode64(data['body']) #puts "Content: ".colorize(:blue) + content # store the data in the database ExtrudedData.create( :email => data['target'], :search => data['search'], :subject => data['subject'], :content => content ) rescue Exception => e puts "ERROR: #{e}" end {} end
require "factory_bot_rails" require "faker" require File.expand_path("spec/utils") class SeedUsersDataJob include Sidekiq::Worker include Sidekiq::Throttled::Worker sidekiq_options queue: :low sidekiq_throttle threshold: {limit: 5, period: 1.minute} attr_reader :user USER_ACTIVITY_FACTOR = { ENV["SEED_GENERATED_ACTIVE_USER_ROLE"] => 1, ENV["SEED_GENERATED_INACTIVE_USER_ROLE"] => 0.3 } USER_ACTIVITY_FACTOR.default = 0 FACILITY_SIZE_FACTOR = { large: 10, medium: 5, small: 3, community: 1 }.with_indifferent_access FACILITY_SIZE_FACTOR.default = 0 SYNC_PAYLOAD_SIZE = 20 SEED_DATA_AGE = 24.months ONGOING_SEED_DATA_AGE = 3.months # Add traits here that pertain to creating patients. # # For every trait, these are the following attributes, # # time_fn: this should ideally be a time range, its realized value is passed to build_fn as args[:time] # size_fn: how many records should be created (ideally a range as well) # build_fn: define how to build the API attributes for this trait (typically Factory attributes) # request_key: the appropriate sync resource for the trait # api_version: the api version of the sync resource to be used # # Note: # If you do not want to create traits through APIs and simply use FactoryBot.create; # Just ignore request_key and api_version # def patient_traits @patient_traits ||= { registered_patient: { time_fn: -> { Faker::Time.between(from: SEED_DATA_AGE.ago, to: Time.now) }, size_fn: -> { rand(20..30) }, build_fn: ->(args) { build_patient_payload( FactoryBot.build(:patient, recorded_at: args[:time], registration_user: user, registration_facility: user.facility) ) }, request_key: :patients, api_version: "v3" }, diagnosis: { size_fn: -> { 1 }, build_fn: ->(args) { return if args[:patient].medical_history build_medical_history_payload( FactoryBot.build(:medical_history, [:hypertension_yes, :hypertension_no].sample, [:diabetes_yes, :diabetes_no, :diabetes_unknown].sample, patient: args[:patient], user: user) ) }, request_key: :medical_histories, api_version: "v3", patient_sample_size: 1 } } end # Add traits here that define a property on patient. # # The attributes here are a superset of the patient_traits, # # patient_sample_size: how many patients for the user to apply this trait to (factor between 0 to 1) # def per_patient_traits @per_patient_traits ||= { ongoing_bp: { time_fn: -> { Faker::Time.between(from: ONGOING_SEED_DATA_AGE.ago, to: Time.now) }, size_fn: -> { rand(1..3) }, build_fn: ->(args) { build_blood_pressure_payload( FactoryBot.build(:blood_pressure, patient: args[:patient], user: user, recorded_at: args[:time], facility: user.facility) ) }, patient_sample_size: 0.40, request_key: :blood_pressures, api_version: "v3" }, retroactive_bp: { time_fn: -> { Faker::Time.between(from: SEED_DATA_AGE.ago, to: 1.month.ago.beginning_of_month) }, size_fn: -> { rand(1..2) }, build_fn: ->(args) { build_blood_pressure_payload( FactoryBot.build(:blood_pressure, patient: args[:patient], user: user, device_created_at: args[:time], device_updated_at: args[:time], facility: user.facility) ).except(:recorded_at) }, patient_sample_size: 0.20, request_key: :blood_pressures, api_version: "v3" }, ongoing_blood_sugar: { time_fn: -> { Faker::Time.between(from: ONGOING_SEED_DATA_AGE.ago, to: Time.now) }, size_fn: -> { rand(1..3) }, build_fn: ->(args) { build_blood_sugar_payload( FactoryBot.build(:blood_sugar, :with_hba1c, patient: args[:patient], user: user, recorded_at: args[:time], facility: user.facility) ) }, patient_sample_size: 0.20, request_key: :blood_sugars, api_version: "v4" }, retroactive_blood_sugar: { time_fn: -> { Faker::Time.between(from: SEED_DATA_AGE.ago, to: 1.month.ago.beginning_of_month) }, size_fn: -> { rand(1..3) }, build_fn: ->(args) { build_blood_sugar_payload( FactoryBot.build(:blood_sugar, :with_hba1c, patient: args[:patient], user: user, device_created_at: args[:time], device_updated_at: args[:time], facility: user.facility) ) }, patient_sample_size: 0.05, request_key: :blood_sugars, api_version: "v4" }, scheduled_appointment: { size_fn: -> { 1 }, build_fn: ->(args) { return if args[:patient].latest_scheduled_appointment.present? build_appointment_payload( FactoryBot.build(:appointment, patient: args[:patient], user: user, creation_facility: user.facility, facility: user.facility) ) }, patient_sample_size: 0.50, request_key: :appointments, api_version: "v3" }, overdue_appointment: { size_fn: -> { rand(1..2) }, build_fn: ->(args) { return if args[:patient].latest_scheduled_appointment.present? build_appointment_payload( FactoryBot.build(:appointment, :overdue, patient: args[:patient], user: user, creation_facility: user.facility, facility: user.facility) ) }, patient_sample_size: 0.50, request_key: :appointments, api_version: "v3" }, completed_phone_call: { time_fn: -> { Faker::Time.between(from: SEED_DATA_AGE.ago, to: Date.today) }, size_fn: -> { rand(1..1) }, build_fn: ->(args) { FactoryBot.create(:call_log, result: "completed", caller_phone_number: user.phone_number, callee_phone_number: args[:patient].latest_phone_number, end_time: args[:time]) }, patient_sample_size: 0.20 } } end class InvalidSeedUsersDataOperation < RuntimeError; end def perform(user_id) if ENV["SIMPLE_SERVER_ENV"] == "production" raise InvalidSeedUsersDataOperation, "Can't generate seed data in #{ENV["SIMPLE_SERVER_ENV"]}!" end @user = User.find(user_id) # # register some patients # patient_trait = patient_traits[:registered_patient] registered_patients = trait_record_size(patient_trait).times.flat_map { build_trait(patient_trait) } create_trait(registered_patients, :registered_patient, patient_trait) # # add their diagnosis # diagnosis_trait = patient_traits[:diagnosis] diagnosis_data = user.registered_patients.flat_map { |patient| build_trait(diagnosis_trait, patient: patient) }.compact create_trait(diagnosis_data, :diagnosis, diagnosis_trait) # # generate various traits per patient # per_patient_traits.each do |trait_name, trait| create_trait(build_traits_per_patient(trait), trait_name, trait) end end private def create_trait(trait_data, trait_name, trait) puts "Creating #{trait_name} for #{user.full_name}..." request_key = trait[:request_key] api_version = trait[:api_version] return if request_key.blank? logger.info("Creating #{trait_name} for #{user.full_name} \ with #{trait_data.size} #{request_key} – facility: #{user.facility.name}") trait_data.each_slice(SYNC_PAYLOAD_SIZE) do |data_slice| api_post("/api/#{api_version}/#{request_key}/sync", request_key => data_slice) if data_slice.present? end end def build_traits_per_patient(trait) sample_registered_patients(trait) .flat_map do |patient| number_of_records_per_patient(trait) .times .map { build_trait(trait, patient: patient) } .compact end end def sample_registered_patients(trait) registered_patients = user.registered_patients sample_size = [trait[:patient_sample_size] * registered_patients.size, 1].max registered_patients.sample(sample_size) end def number_of_records_per_patient(trait) (trait_record_size(trait) * traits_scale_factor).to_i end def build_trait(trait, build_params = {}) build_params = build_params.merge(time: trait_time(trait)) trait[:build_fn].call(build_params) end def trait_record_size(trait) trait[:size_fn].call.to_i end def trait_time(trait) trait[:time_fn]&.call end def traits_scale_factor USER_ACTIVITY_FACTOR[user.role] * FACILITY_SIZE_FACTOR[user.registration_facility.facility_size] end def api_post(path, data) output = HTTP .auth("Bearer #{user.access_token}") .headers(api_headers) .post(api_url(path), json: data) raise HTTP::Error unless output.status.ok? end def api_headers {"Content-Type" => "application/json", "ACCEPT" => "application/json", "X-USER-ID" => user.id, "X-FACILITY-ID" => user.facility.id} end def api_url(path) URI.parse("#{ENV["SIMPLE_SERVER_HOST_PROTOCOL"]}://#{ENV["SIMPLE_SERVER_HOST"]}/#{path}") end end
# Move first constenant to the end # If vowel, leave alone. # Then add "ay" at the end. # Allow sentences with a single space in between words # Maintain the index of case. # Maintain the index of punctuation (beginning or end of word) VOWELS = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'] def to_pig_latin(sentence) words = sentence.split(/\s/) # Run each word through word_to_pig_latin pl_array = words.map do |word| word.empty? ? '' : word_to_pig_latin(word) end # Rejoin into string split by spaces pl_array.join(' ') end def is_capitalized(letter) !letter.scan(/[A-Z]/).empty? end def get_capitals_index_array(word) caps = [] word.chars.each_with_index do |letter, index| caps << index if is_capitalized(letter) end caps end def set_capitals(word, capitals_index_array) capped_word = '' # Loop through each letter word.chars.each_with_index do |char, index| # If the index of the letter is in capitals_index_array, capitalize it # Either way, concatenate to capped_word capped_word += capitals_index_array.include?(index) ? char.upcase : char end capped_word end def word_to_pig_latin(word) # Any non-letters followed by a letter left_punctuation = word.scan(/\A[^a-zA-Z]*/).first # Any non-letters following a letter right_punctuation = word.scan(/[^a-zA-Z]*\z/).first unpunctuated_word = word.gsub(left_punctuation, '') .gsub(right_punctuation, '') # Save capitals capitals_index_array = get_capitals_index_array(unpunctuated_word) # If first letter is not a vowel, shift and push the letter. pl_word = unpunctuated_word.downcase chars = pl_word.chars first_letter = chars[0] if !VOWELS.include?(first_letter) chars.shift chars.push(first_letter) pl_word = chars.join end pl_word = set_capitals(pl_word, capitals_index_array) # Add "ay" to the end, along with any previous punctuation. "#{left_punctuation}#{pl_word}ay#{right_punctuation}" end
# Paladin class verifies if files exist and writes missing files to # the paladin.log file. class Paladin #Paladin takes a default file file_spec.txt in the same directory def self.load_file @file_name = "file_spec.txt" @counter = 0 @missed = 0 @log = File.open("paladin.log", 'w') end #Write missing files to paladin.log def self.verify_files @log.write("Missing Files: \n") File.open(@file_name).each do |value| value.chomp! unless File.exist?(value) @log.write("#{value}\n") @missed+=1 end @counter+=1 end @log.write("Total Files Verified: #{@counter}\n Total Files Missing: #{@missed}\n") end end
require 'rails_helper' RSpec.describe BuyerStock, type: :model do let!(:buyer) { Buyer.create(email: 'e@email.com', first_name: 'Light', last_name: 'Yagami', username: 'Kira', password: 'password', password_confirmation: 'password') } let(:buyer_stock) { buyer.buyer_stocks.build(symbol: 'MC', quantity: 2, company_name: 'Microsoft Corp') } context 'with validations/stock should fail to save' do it 'is not valid without symbol' do buyer_stock.symbol = 'MC' expect(buyer_stock).to be_valid end it 'is not valid without a company_name' do buyer_stock.company_name = nil expect(buyer_stock).not_to be_valid end end end
require 'rails_helper' feature 'Buying' do before :each do @user = create :user @seller = create :user, :seller login @user @item = create :item, seller: @seller end describe 'No Selenium' do it 'shows the user a list of all items by default' do item = create :item visit root_path expect( page ).to have_content item.title end it 'lets buyers search for items' do item_1 = create :item, title: "foo", description: "foo 1" item_2 = create :item, title: "bar", description: "bar 2" visit root_path within('form') do fill_in "search_input", with: item_1.title end click_button "Search" #get search controller method via ajax for item_1.title expect( page ).to have_content item_1.title expect( page ).to_not have_content item_2.title end it 'lets buyers view more details about an item' do item_1 = create :item, title: "Show Test" visit root_path expect( page ).to have_content item_1.title click_link(item_1.title, match: :first) expect( page.current_path).to eq item_path(item_1) expect( page ).to have_content item_1.title end end describe 'Selenium', :js do before :each do visit items_path click_link("Add to Cart", match: :first) end it 'lets buyers add items to their cart' do expect(page).to have_css('.item') end it 'lets buyers view their cart' do item = Item.first expect(page).to have_content(item.title) expect(page).to have_content(item.description) expect(page).to have_content(item.price) end it 'lets buyers remove items from their cart' do expect(page).to have_css('.item') find('.remove-button').click expect(page).not_to have_css('.item') end it 'lets buyers checkout' do expect(page).to have_css('.item') find('.checkout').click expect(page).to have_text "Unpaid" expect(page).to have_content Item.first.title expect(page).to have_content Invoice.last.amount end describe "when using a coupon" do describe "with a valid coupon" do before :each do @coupon = create :coupon, user: @seller, status: true end it 'discounts items from a seller based on a valid coupon' do fill_in "codeInput", with: @coupon.code click_on "Apply" expect(page).to have_content @coupon.code end it 'does not discount items if the user has not items from that seller' do @wrong_seller = create :user, :seller @wrong_coupon = create :coupon, user: @wrong_seller, status: true fill_in "codeInput", with: @wrong_coupon.code click_on "Apply" expect(page).not_to have_content @wrong_coupon.code end it 'only discounts items from a seller when the cart has items from multiple sellers' it 'allows for multiple seller discounts from multiple sellers' end describe "when using an invalid coupon" do it 'rejects the coupon if the coupon code never existed' it 'rejects the coupon for a code that has been marked as inactive' end it 'allows users to remove a coupon code from checkout' end end end
describe IGMarkets::DealingPlatform::MarketMethods do let(:session) { IGMarkets::Session.new } let(:platform) do IGMarkets::DealingPlatform.new.tap do |platform| platform.instance_variable_set :@session, session end end it 'can retrieve the market hierarchy root' do result = build :market_hierarchy_result expect(session).to receive(:get).with('marketnavigation', IGMarkets::API_V1).and_return(result) expect(platform.markets.hierarchy).to eq(result) end it 'can retrieve a market hierarchy node' do result = build :market_hierarchy_result expect(session).to receive(:get).with('marketnavigation/1', IGMarkets::API_V1).and_return(result) expect(platform.markets.hierarchy(1)).to eq(result) end it 'can retrieve a market from an EPIC' do get_result = { market_details: [{ dealing_rules: build(:market_dealing_rules), instrument: build(:instrument), snapshot: build(:market_snapshot) }] } expect(session).to receive(:get).with('markets?epics=ABCDEF', IGMarkets::API_V2).and_return(get_result) expect(platform.markets['ABCDEF']).to eq(IGMarkets::Market.from(get_result[:market_details])[0]) end it 'can retrieve a market from an EPIC with DFB expiry' do get_result = { market_details: [{ dealing_rules: build(:market_dealing_rules), instrument: build(:instrument_dfb), snapshot: build(:market_snapshot) }] } expect(session).to receive(:get).with('markets?epics=ABCDEF', IGMarkets::API_V2).and_return(get_result) expect(platform.markets['ABCDEF']).to eq(IGMarkets::Market.from(get_result[:market_details])[0]) end it 'can search for markets' do markets = [build(:market_overview)] expect(session).to receive(:get).with('markets?searchTerm=USD', IGMarkets::API_V1).and_return(markets: markets) expect(platform.markets.search('USD')).to eq(markets) end it 'can retrieve a specified number of historical prices for a market' do markets_get_result = { market_details: [{ dealing_rules: build(:market_dealing_rules), instrument: build(:instrument), snapshot: build(:market_snapshot) }] } historical_price_result = build :historical_price_result expect(session).to receive(:get).with('markets?epics=ABCDEF', IGMarkets::API_V2).and_return(markets_get_result) expect(session).to receive(:get).with('prices/ABCDEF/DAY/5', IGMarkets::API_V2).and_return(historical_price_result) expect(platform.markets['ABCDEF'].recent_prices(:day, 5)).to eq(historical_price_result) end it 'can retrieve a date range of historical prices for a market' do from_date = DateTime.new 2014, 1, 2, 3, 4, 5 to_date = DateTime.new 2014, 2, 3, 4, 5, 6 markets_get_result = { market_details: [{ dealing_rules: build(:market_dealing_rules), instrument: build(:instrument), snapshot: build(:market_snapshot) }] } historical_price_result = build :historical_price_result expect(session).to receive(:get).with('markets?epics=ABCDEF', IGMarkets::API_V2).and_return(markets_get_result) expect(session).to receive(:get) .with('prices/ABCDEF/DAY/2014-01-02T03:04:05/2014-02-03T04:05:06', IGMarkets::API_V2) .and_return(historical_price_result) expect(platform.markets['ABCDEF'].prices_in_date_range(:day, from_date, to_date)).to eq(historical_price_result) end end
class RoomsController < ApplicationController protect_from_forgery :only => ["create"] def join @room = Room.find(params[:room_id]) @user = User.find(params[:users_id]) makeshadow(@room, @user) redirect_to "/rooms/home/#{@room.id}/#{@user.id}" end def delete @room = Room.find(params[:room_id]) @user = User.find(params[:user_id]) @room.users.delete(@user) redirect_to "/users/show/#{@user.id}" end def create @user = User.find(params[:users_id]) @user_id = @user.id @room = Room.new(name: params[:roomname]) @room.users << User.find(@user_id) @room.save seed(@room) redirect_to "/users/show/#{@user_id}" end def home @room = Room.find(params[:room_id]) @user = User.find(params[:user_id]) end def post @room = Room.find(params[:room_id]) @user = User.find(params[:user_id]) edit = JSON.parse(params[:edit]) patch(edit,0) patch(edit,@user.id) data = diff(@room,@user) unless data == [] # shadow(@room, @user) patch(data,@user.id) end render json: data end private def grant(user,type) last = SecureRandom.uuid if type == 0 if Vertex.last last = Vertex.last.id else last = 0 end elsif type == 1 if Face.last last = Face.last.id else last = 0 end elsif type == 2 if Mesh.last last = Mesh.last.id else last = 0 end end num = [user,type,last,SecureRandom.base64(2)].join('') end def seed(room) @scene = room.scenes.create( :aff => 0 ) @scene.save @mesh = @scene.meshes.create( :uuid => grant(0,2), ) @mesh.save @face = @scene.faces.create( :uuid => grant(0,1), ) @face.save vertex_uuid = grant(0,0) @vertex1 = @scene.vertices.create( :uuid => vertex_uuid, :component => "x", :data => 10, ) @vertex2 = @scene.vertices.create( :uuid => vertex_uuid, :component => "y", :data => 10, ) @vertex3 = @scene.vertices.create( :uuid => vertex_uuid, :component => "z", :data => 10, ) @vertex1.save @vertex2.save @vertex3.save vertex_uuid = grant(0,0) @vertex1 = @scene.vertices.create( :uuid => vertex_uuid, :component => "x", :data => 20, ) @vertex2 = @scene.vertices.create( :uuid => vertex_uuid, :component => "y", :data => 20, ) @vertex3 = @scene.vertices.create( :uuid => vertex_uuid, :component => "z", :data => 20, ) @vertex1.save @vertex2.save @vertex3.save end def diff(room,user) edit = [] servertext = room.scenes.find_by(:aff => 0) servershadow = room.scenes.find_by(:aff => user.id) @servertext_array = { :mesh => [], :meshes_id => [], :faces => [], :faces_id => [], :vertices => [], :vertices_id => [] } @servershadow_array = { :mesh => [], :meshes_id => [], :faces => [], :faces_id => [], :vertices => [], :vertices_id => [] } servertext.meshes.each do |mesh| unless @servertext_array[:meshes_id].push(mesh.uuid) @servertext_array[:meshes_id].push(mesh.uuid) end array = [] mesh.faces.each do |face| unless array.index(face.uuid) array.push(face.uuid) end end @servertext_array[:mesh].push(array) end servertext.faces.each do |face| unless @servertext_array[:faces_id].push(face.uuid) @servertext_array[:faces_id].push(face.uuid) end array = [] face.vertices.each do |vertex| unless array.index(vertex.uuid) array.push(vertex.uuid) end end @servertext_array[:faces].push(array) end servertext.vertices.each do |vertex| unless @servertext_array[:vertices_id].index(vertex.uuid) @servertext_array[:vertices_id].push(vertex.uuid) vertex_x = servertext.vertices.find_by(:uuid => vertex.uuid, :component => "x") vertex_y = servertext.vertices.find_by(:uuid => vertex.uuid, :component => "y") vertex_z = servertext.vertices.find_by(:uuid => vertex.uuid, :component => "z") @servertext_array[:vertices].push(vertex_x.data,vertex_y.data,vertex_z.data) end end servershadow.meshes.each do |mesh| unless @servershadow_array[:meshes_id].push(mesh.uuid) @servershadow_array[:meshes_id].push(mesh.uuid) end array = [] mesh.faces.each do |face| unless array.index(face.uuid) array.push(face.uuid) end end @servershadow_array[:mesh].push(array) end servershadow.faces.each do |face| unless @servershadow_array[:faces_id].push(face.uuid) @servershadow_array[:faces_id].push(face.uuid) end array = [] face.vertices.each do |vertex| unless array.index(vertex.uuid) array.push(vertex.uuid) end end @servershadow_array[:faces].push(array) end servershadow.vertices.each do |vertex| unless @servershadow_array[:vertices_id].index(vertex.uuid) @servershadow_array[:vertices_id].push(vertex.uuid) vertex_x = servershadow.vertices.find_by(:uuid => vertex.uuid, :component => "x") vertex_y = servershadow.vertices.find_by(:uuid => vertex.uuid, :component => "y") vertex_z = servershadow.vertices.find_by(:uuid => vertex.uuid, :component => "z") @servershadow_array[:vertices].push(vertex_x.data,vertex_y.data,vertex_z.data) end end p @servertext_array p @servershadow_array len_t = @servertext_array[:meshes_id].length len_s = @servershadow_array[:meshes_id].length for i in 0...len_t do pre = @servershadow_array[:meshes_id].index(@servertext_array[:meshes_id][i]) if pre if @servershadow_array[:mesh][pre] != @servertext_array[:mesh][i] for j in 0...@servertext_array[:mesh][i].length do k = @servershadow_array[:mesh][pre].index(@servertext_array[:mesh][i][j]) unless k ope = [ "mesh_update", @servertext_array[:meshes_id][i], [ @servertext_array[:mesh][i][j] ] ] edit.push(ope) end end end else ope = [ "mesh_add", @servertext_array[:meshes_id][i], 0 ] edit.push(ope) end end for i in 0...len_s do pre = @servertext_array[:meshes_id].index(@servershadow_array[:meshes_id][i]) unless pre ope = [ "mesh_remove", @servershadow_array[:meshes_id][i], 0 ] edit.push(ope) end end len_t = @servertext_array[:faces_id].length len_s = @servershadow_array[:faces_id].length for i in 0...len_t do pre = @servershadow_array[:faces_id].index(@servertext_array[:faces_id][i]) if pre if @servershadow_array[:faces][pre] != @servertext_array[:faces][i] for j in 0...@servertext_array[:faces][i].length do k = @servershadow_array[:faces][pre].index(@servertext_array[:faces][i][j]) unless k ope = [ "face_update", @servertext_array[:faces_id][i], [ @servertext_array[:faces][i][j] ] ] edit.push(ope) end end end else ope = [ "face_add", @servertext_array[:faces_id][i], 0 ] edit.push(ope) end end for i in 0...len_s do pre = @servertext_array[:faces_id].index(@servershadow_array[:faces_id][i]) unless pre ope = [ "face_remove", @servershadow_array[:faces_id][i], 0 ] edit.push(ope) end end len_t = @servertext_array[:vertices_id].length len_s = @servershadow_array[:vertices_id].length for i in 0...len_t do pre = @servershadow_array[:vertices_id].index(@servertext_array[:vertices_id][i]) if pre if @servertext_array[:vertices][i * 3] != @servershadow_array[:vertices][pre * 3] || @servertext_array[:vertices][i * 3 + 1] != @servershadow_array[:vertices][pre * 3 + 1] || @servertext_array[:vertices][i * 3 + 2] != @servershadow_array[:vertices][pre * 3 + 2] ope = [ "vertex_update", @servertext_array[:vertices_id][i], [ @servertext_array[:vertices][i * 3], @servertext_array[:vertices][i * 3 + 1], @servertext_array[:vertices][i * 3 + 2] ] ] edit.push(ope) end else ope = [ "vertex_add", @servertext_array[:vertices_id][i], [ @servertext_array[:vertices][i * 3], @servertext_array[:vertices][i * 3 + 1], @servertext_array[:vertices][i * 3 + 2] ] ] edit.push(ope) end end for i in 0...len_s do pre = @servertext_array[:vertices_id].index(@servershadow_array[:vertices_id][i]) unless pre ope = [ "vertex_remove", @servershadow_array[:vertices_id][i], 0 ] edit.push(ope) end end edit end def patch(edit,aff) # serverTextとserverShadowの値の書き換え scene = Scene.find_by(:aff => aff) for i in 0...edit.length ope = edit[i][0] id = edit[i][1] data = edit[i][2] if ope == 'mesh_add' @mesh = scene.meshes.create( :uuid => id ) @mesh.save elsif ope == 'mesh_remove' meshes = scene.meshes.where(:uuid => id) meshes.each do |mesh| mesh.destroy end elsif ope == 'mesh_update' faces = scene.faces.where(:uuid => data[0]) mesh = scene.meshes.find_by(:uuid => id) if mesh faces.each do |face| @face = scene.faces.create( :uuid => face.uuid, :mesh_id => mesh.id ) @face.save end end elsif ope == 'face_add' @face = scene.faces.create( :uuid => id ) @face.save elsif ope == 'face_remove' faces = scene.faces.where(:uuid => id) faces.each do |face| face.destroy end elsif ope == 'face_update' face = scene.faces.find_by(:uuid => id) vertices = scene.vertices.where(:uuid => data[0]) if face vertices.each do |vertex| @vertex = scene.vertices.create( :uuid => vertex.uuid, :component => vertex.component, :data => vertex.data, :face_id => face.id ) @vertex.save end end elsif ope == 'vertex_add' vertex_uuid = id @vertex1 = scene.vertices.create( :uuid => vertex_uuid, :component => "x", :data => data[0] ) @vertex2 = scene.vertices.create( :uuid => vertex_uuid, :component => "y", :data => data[1] ) @vertex3 = scene.vertices.create( :uuid => vertex_uuid, :component => "z", :data => data[2] ) @vertex1.save @vertex2.save @vertex3.save elsif ope == 'vertex_remove' vertices = scene.vertices.where(:uuid => id) vertices.each do |vertex| vertex.destroy end elsif ope == 'vertex_update' scene.vertices.each do |vertex| if vertex.uuid == id if vertex.component == "x" vertex.data = data[0] elsif vertex.component == "y" vertex.data = data[1] elsif vertex.component == "z" vertex.data = data[2] end vertex.save end end end end end def makeshadow(room,user) @scene = room.scenes.find_by(:aff => user.id) if @scene @scene.destroy end @scene = room.scenes.create( :aff => user.id ) @scene.save end def shadow(room, user) servershadow = room.scenes.find_by(:aff => user.id) servertext = room.scenes.find_by(:aff => 0) @servertext_array = { :mesh => [], :meshes_id => [], :faces => [], :faces_id => [], :vertices => [], :vertices_id => [] } servertext.meshes.each do |mesh| unless @servertext_array[:meshes_id].index(mesh.uuid) @servertext_array[:meshes_id].push(mesh.uuid) end array = [] mesh.faces.each do |face| unless array.index(face.uuid) array.push(face.uuid) end end @servertext_array[:mesh].push(array) end servertext.faces.each do |face| unless @servertext_array[:faces_id].index(face.uuid) @servertext_array[:faces_id].push(face.uuid) end array = [] face.vertices.each do |vertex| unless array.index(vertex.uuid) array.push(vertex.uuid) end end @servertext_array[:faces].push(array) end servertext.vertices.each do |vertex| unless @servertext_array[:vertices_id].index(vertex.uuid) @servertext_array[:vertices_id].push(vertex.uuid) vertex_x = servertext.vertices.find_by(:uuid => vertex.uuid, :component => "x") vertex_y = servertext.vertices.find_by(:uuid => vertex.uuid, :component => "y") vertex_z = servertext.vertices.find_by(:uuid => vertex.uuid, :component => "z") @servertext_array[:vertices].push(vertex_x.data,vertex_y.data,vertex_z.data) end end deletescene(servershadow) @scene = room.scenes.create( :aff => user.id ) @servertext_array[:meshes_id].each do |mesh| @mesh = @scene.meshes.create( :uuid => mesh ) end @servertext_array[:faces_id].each do |face| @face = @scene.faces.create( :uuid => face ) for i in 0...@servertext_array[:mesh].length do for j in 0...@servertext_array[:mesh][i].length do if face == @servertext_array[:mesh][i][j] mesh = @scene.meshes.find_by(:uuid => @servertext_array[:meshes_id][i]) if mesh @face = @scene.faces.create( :uuid => face, :mesh_id => mesh.id ) end end end end end for k in 0...@servertext_array[:vertices_id].length do @vertex_x = @scene.vertices.create( :uuid => @servertext_array[:vertices_id][k], :data => @servertext_array[:vertices][k * 3], :component => "x" ) @vertex_y = @scene.vertices.create( :uuid => @servertext_array[:vertices_id][k], :data => @servertext_array[:vertices][k * 3 + 1], :component => "y" ) @vertex_z = @scene.vertices.create( :uuid => @servertext_array[:vertices_id][k], :data => @servertext_array[:vertices][k * 3 + 2], :component => "z" ) for i in 0...@servertext_array[:faces].length do for j in 0...@servertext_array[:faces][i].length do if @servertext_array[:vertices_id][k] == @servertext_array[:faces][i][j] face = @scene.faces.find_by(:uuid => @servertext_array[:faces_id][i] ) if face @vertex_x = @scene.vertices.create( :uuid => @servertext_array[:vertices_id][k], :data => @servertext_array[:vertices][k * 3], :component => "x", :face_id => face.id ) @vertex_y = @scene.vertices.create( :uuid => @servertext_array[:vertices_id][k], :data => @servertext_array[:vertices][k * 3 + 1], :component => "y", :face_id => face.id ) @vertex_z = @scene.vertices.create( :uuid => @servertext_array[:vertices_id][k], :data => @servertext_array[:vertices][k * 3 + 2], :component => "z", :face_id => face.id ) end end end end end # # @scene = room.scenes.create( # :aff => user.id # ) # # servertext.meshes.each do |mesh| # @mesh = @scene.meshes.create( # :uuid => mesh.uuid # ) # end # # servertext.faces.each do |face| # unless face.mesh_id # @face = @scene.faces.create( # :uuid => face.uuid # ) # end # end # # servertext.vertices.each do |vertex| # unless vertex.face_id # @vertex = @scene.vertices.create( # :uuid => vertex.uuid, # :component=> vertex.component, # :data => vertex.data # ) # end # end # # for i in 0...@servertext_array[:meshes_id].length do # array = @servertext_array[:mesh][i] # array.each do |uuid| # mesh = @scene.meshes.find_by(:uuid => @servertext_array[:meshes_id][i]) # @face = @scene.faces.find_by(:uuid => uuid) # @face.mesh_id = mesh.id # @face.save # end # end # # for i in 0...@servertext_array[:faces_id].length do # array = @servertext_array[:faces][i] # array.each do |uuid| # idx = @servertext_array[:vertices_id].index(uuid) # if idx # face = @scene.faces.find_by(:uuid => @servertext_array[:faces_id][i]) # @vertex = face.vertices.create( # :uuid => uuid, # :component=> "x", # :data => @servertext_array[:vertices][idx], # :scene_id => @scene.id # ) # @vertex = face.vertices.create( # :uuid => uuid, # :component=> "y", # :data => @servertext_array[:vertices][idx], # :scene_id => @scene.id # ) # @vertex = face.vertices.create( # :uuid => uuid, # :component=> "z", # :data => @servertext_array[:vertices][idx], # :scene_id => @scene.id # ) # end # end # end end def deletescene(scene) if scene scene.meshes.each do |mesh| if mesh mesh.destroy end end scene.faces.each do |face| if face face.destroy end end scene.vertices.each do |vertex| if vertex vertex.destroy end end scene.destroy end end end
class Web::Admin::CourseKindsController < Web::Admin::ApplicationController add_breadcrumb :courses, :admin_courses_path add_breadcrumb :index, :admin_course_kinds_path def index @kinds = Course::Kind.page(params[:page]).asc_by_order_at end def new @kind = Course::Kind.new add_breadcrumb :new, new_admin_course_kind_path end def create @kind = Course::Kind.new params[:course_kind] if @kind.save flash_success redirect_to action: :index else flash_error add_breadcrumb :new, new_admin_course_kind_path render :new end end def edit @kind = Course::Kind.find params[:id] add_breadcrumb @kind.name, edit_admin_course_kind_path(@kind) end def update @kind = Course::Kind.find params[:id] if @kind.update_attributes params[:course_kind] flash_success redirect_to action: :index else flash_error add_breadcrumb @kind.name, edit_admin_course_kind_path(@kind) render :edit end end def destroy kind = Course::Kind.find params[:id] begin kind.destroy flash_success rescue ActiveRecord::DeleteRestrictionError flash_error now: false ensure redirect_to action: :index end end end
class AddIndexesToComments < ActiveRecord::Migration[5.1] def change add_index :comments, :user_id add_index :comments, :submission_id end end
require 'rails_helper' RSpec.describe RequestsController, type: :controller do describe "GET #new" do it "returns http success" do get :new expect(response).to have_http_status(:success) end end describe "POST #create" do before do request.env["HTTP_REFERER"] = "origin" def request_demo(attributes) post :create, { request: attributes } end end context "successfully request demo" do before { @request_attributes = FactoryGirl.attributes_for :request } it "and save request to database" do expect{ request_demo(@request_attributes) }.to change(Request, :count).by(1) end it "and return a success flash message" do request_demo(@request_attributes) message = "Your successfully made a request for a demo. We will be in touch with you soon" expect(flash[:success]).to eq message end it "and should redirect to root path" do request_demo(@request_attributes) expect(response).to redirect_to "origin" end end context "unsuccessful request for demo" do before do @request_invalid_attributes = FactoryGirl.attributes_for :request @request_invalid_attributes[:email] = "" end it "and should not create and save a request to database" do expect{ request_demo(@request_invalid_attributes) }.not_to change(Request, :count) end it "and render a flash message" do request_demo(@request_invalid_attributes) message = "Something went wrong. Please submit the request again." expect(flash[:alert]).to eq message end it "and redirects to root path" do request_demo(@request_invalid_attributes) expect(response).to redirect_to "origin" end end end end