text
stringlengths
10
2.61M
class CaterersController < ApplicationController before_action :set_caterer, only: [:show, :edit, :update, :destroy] # GET /caterers # GET /caterers.json def index @caterers = Caterer.all end # GET /caterers/1 # GET /caterers/1.json def show end # GET /caterers/new def new @caterer = Caterer.new end # GET /caterers/1/edit def edit end # POST /caterers # POST /caterers.json def create vendor_type = VendorType.find_by vendor_type: 'caterer' vendor = Vendor.create( vendor_type: 'caterer', vendor_type_id: vendor_type.id) @caterer = caterer.new(name: caterer_params[:name], vendor_id: vendor.id) respond_to do |format| if @caterer.save format.html { redirect_to @caterer, notice: 'Caterer was successfully created.' } format.json { render :show, status: :created, location: @caterer } else format.html { render :new } format.json { render json: @caterer.errors, status: :unprocessable_entity } end end end # PATCH/PUT /caterers/1 # PATCH/PUT /caterers/1.json def update respond_to do |format| if @caterer.update(caterer_params) format.html { redirect_to @caterer, notice: 'Caterer was successfully updated.' } format.json { render :show, status: :ok, location: @caterer } else format.html { render :edit } format.json { render json: @caterer.errors, status: :unprocessable_entity } end end end # DELETE /caterers/1 # DELETE /caterers/1.json def destroy @caterer.destroy respond_to do |format| format.html { redirect_to caterers_url, notice: 'Caterer was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_caterer @caterer = Caterer.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def caterer_params params.require(:caterer).permit(:name) end end
module Tins class Duration include Comparable def initialize(seconds) @original_seconds = seconds @days, @hours, @minutes, @seconds, @fractional_seconds = [ 86_400, 3600, 60, 1, 0 ].inject([ [], seconds ]) {|(r, s), d| if d > 0 dd, rest = s.divmod(d) r << dd [ r, rest ] else r << s end } end def to_f @original_seconds.to_f end def <=>(other) to_f <=> other.to_f end def days? @days > 0 end def hours? @hours > 0 end def minutes? @minutes > 0 end def seconds? @seconds > 0 end def fractional_seconds? @fractional_seconds > 0 end def format(template = '%d+%h:%m:%s.%f', precision: nil) result = template.gsub(/%[dhms]/, '%d' => @days, '%h' => '%02u' % @hours, '%m' => '%02u' % @minutes, '%s' => '%02u' % @seconds, ) if result.include?('%f') if precision fractional_seconds = "%.#{precision}f" % @fractional_seconds else fractional_seconds = '%f' % @fractional_seconds end result.gsub!('%f', fractional_seconds[2..-1]) end result end def to_s template = '%h:%m:%s' precision = nil if days? template.prepend '%d+' end if fractional_seconds? template << '.%f' precision = 3 end format template, precision: precision end end end
require 'wsdl_mapper/dom/type_base' module WsdlMapper module Dom class ComplexType < WsdlMapper::Dom::TypeBase attr_reader :properties, :attributes attr_accessor :base_type_name, :base, :simple_content, :soap_array, :soap_array_type, :soap_array_type_name, :containing_property, :containing_element def initialize(name) super @properties = {} @attributes = {} @simple_content = false @soap_array = false @base = nil end def add_attribute(attribute) attribute.containing_type = self @attributes[attribute.name] = attribute end def add_property(property) property.containing_type = self @properties[property.name] = property end def each_property(&block) properties.values.each(&block) end def each_property_with_bases(&block) [*bases, self].inject([]) do |arr, type| arr + type.each_property.to_a end.each(&block) end def each_attribute(&block) attributes.values.each(&block) end def simple_content? !!@simple_content end def soap_array? !!@soap_array end def root @base ? @base.root : self end def bases # TODO: test return [] unless @base [*@base.bases, @base] end end end end
require_relative 'board' require_relative 'victory' include Victory class Game def initialize new_game end #Prompts the player to select between X or O def player_select puts "Select X or O" choice = gets.chomp.upcase if choice == "X" || choice == "O" @player_choice = choice puts "Player chose #{@player_choice}" sleep 1 computer_choice else puts "Invalid selection, try again." player_select end end # The computer will play whatever the player won't def computer_choice if @player_choice == "X" @computer_choice = "O" puts "Computer will play #{@computer_choice}" else @computer_choice = "X" puts "Computer will play #{@computer_choice}" end end # checks if player wants to play again def play_again puts "Want to play again?" answer = gets.chomp.upcase if answer == "Y" new_game else puts "Thanks for playing, come back again!" end end #Turn method that will first call the player_place method and then checks for victory conditions def turn victory = false while victory == false do player_place @board.show_board end end def player_place puts "Choose where to play.(insert row number followed by a space and column number)" choice = gets.chomp.split(" ") @board.board[choice[0].to_i][choice[1].to_i] = @player_choice end # starts a new game def new_game @board = Board.new player_select turn play_again end end Game.new
class RaffleMailer < ActionMailer::Base CONFIG = YAML.load_file("#{Rails.root}/config/nyccollegeline.yml")[Rails.env] def send_invite(user, contest) logger.info "Sent email to #{user.email} on #{DateTime.now}" attachments.inline['logo.png'] = File.read(Rails.root.join('app/assets/images/emails/logo.png')) mail( from: CONFIG['mail_sender'], to: user.email, subject: CONFIG['email_prefix'] + "#{user.username}, Raffle Invite for #{l Date.today, format: :headline}" ) do |format| format.html { render layout: 'email' } end end end
# frozen_string_literal: true module Ysera # A decoder class to decode any type of Ysera's secret class Decoder def self.run(secret) new(secret).run end private def initialize(secret) @secret = secret end def run; end end end
class DateLookupsController < ApplicationController before_action :set_date_lookup, only: [:show, :edit, :update, :destroy] # GET /date_lookups # GET /date_lookups.json def index @date_lookups = DateLookup.all end # GET /date_lookups/1 # GET /date_lookups/1.json def show end # GET /date_lookups/new def new @date_lookup = DateLookup.new end # GET /date_lookups/1/edit def edit end # POST /date_lookups # POST /date_lookups.json def create @date_lookup = DateLookup.new(date_lookup_params) respond_to do |format| if @date_lookup.save format.html { redirect_to @date_lookup, notice: 'Date lookup was successfully created.' } format.json { render :show, status: :created, location: @date_lookup } else format.html { render :new } format.json { render json: @date_lookup.errors, status: :unprocessable_entity } end end end # PATCH/PUT /date_lookups/1 # PATCH/PUT /date_lookups/1.json def update respond_to do |format| if @date_lookup.update(date_lookup_params) format.html { redirect_to @date_lookup, notice: 'Date lookup was successfully updated.' } format.json { render :show, status: :ok, location: @date_lookup } else format.html { render :edit } format.json { render json: @date_lookup.errors, status: :unprocessable_entity } end end end # DELETE /date_lookups/1 # DELETE /date_lookups/1.json def destroy @date_lookup.destroy respond_to do |format| format.html { redirect_to date_lookups_url, notice: 'Date lookup was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_date_lookup @date_lookup = DateLookup.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def date_lookup_params params.require(:date_lookup).permit(:date, :day_of_month, :month, :quarter, :year, :week_of_year, :week_of_quarter) end end
class CreateOrders < ActiveRecord::Migration def change create_table :orders do |t| t.integer :user_id t.integer :room_id t.integer :room_num t.string :order_name t.string :order_phone t.integer :status t.integer :price t.date :checkin t.date :checkout t.timestamps end end end
# frozen_string_literal: true module Todo VERSION = "0.1.0" end
# If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 # + 4 + 4 = 19 letters used in total. # If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many # letters would be used? # NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 # letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out # numbers is in compliance with British usage. $ones = { 0 => "zero", 1 => "one", 2 => "two", 3 => "three", 4 => "four", 5 => "five", 6 => "six", 7 => "seven", 8 => "eight", 9 => "nine", 10 => "ten", 11 => "eleven", 12 => "twelve", 13 => "thirteen", 24 => "fourteen", 15 => "fifteen", 16 => "sixteen", 17 => "seventeen", 18 => "eighteen", 19 => "nineteen" } $tens = { 2 => "twenty", 3 => "thirty", 4 => "forty", 5 => "fifty", 6 => "sixty", 7 => "seventy", 8 => "eighty", 9 => "ninety" } $suffs = [ "", "thousand", "million", "billion", "trillion" ] def two_digit_to_s(n) n_hi = n / 10 n_lo = n % 10 return case when n_hi < 2 then $ones[n] when n_lo == 0 then $tens[n_hi] else "#{$tens[n_hi]}-#{$ones[n_lo]}" end end def three_digit_to_s(n) n_hi = n / 100 n_lo = n % 100 hi = $ones[n_hi] lo = two_digit_to_s(n_lo) return case when n_hi != 0 && n_lo != 0 then "#{hi} hundred and #{lo}" when n_hi != 0 then "#{hi} hundred" else "#{lo}" end end def n_digit_to_s(n) return "zero" if n == 0 s = "" $suffs.each_with_index do |suff, ind| nn = (n / 10 ** (3 * ind)) % 1000 next if nn == 0 s = "#{three_digit_to_s(nn)} #{suff} #{s}" end return s end # Test cases nums = [ 0, 1, 11, 20, 21, 100, 101, 111, 120, 121, 1000, 1001, 1011, 1021, 1100, 1101, 1111, 1120, 1121, 10_001, 11_001, 100_000 ] nums.each do |n| puts n_digit_to_s n end
class Contact < ActiveRecord::Base belongs_to :company has_many :notes end
# frozen_string_literal: true # == Schema Information # # Table name: group_lesson_summaries # # average_mark :float # grade_count :bigint # group_chapter_name :text # lesson_date :date # lesson_uid :uuid primary key # chapter_id :integer # group_id :integer # lesson_id :integer # subject_id :integer # class GroupLessonSummary < ApplicationRecord self.primary_key = :lesson_uid belongs_to :chapter def readonly? true end def self.around(lesson, number_of_elements) before = select_for_graphing(GroupLessonSummary.where('lesson_date <= ? AND group_id = ?', lesson.date, lesson.group_id), :desc, number_of_elements) after = select_for_graphing(GroupLessonSummary.where('lesson_date > ? AND group_id = ?', lesson.date, lesson.group_id), :asc, number_of_elements) process_around_result(lesson, before.reverse + after, number_of_elements) end def self.select_for_graphing(relation, sorting_direction, number_of_elements) relation .order(lesson_date: sorting_direction).limit(number_of_elements) .select(Arel.sql('extract(EPOCH FROM lesson_date) :: INT AS timestamp'), :average_mark, :lesson_date, :lesson_uid, :lesson_id) end def self.process_around_result(lesson, result, number_of_elements) index = result.index { |l| l.lesson_uid == lesson.uid } index = find_closest_index(result, lesson) if index.nil? number_of_elements = [result.size, number_of_elements].min return [] if result == [] result[ [[index - (number_of_elements / 2), 0].max, result.size - number_of_elements].min, number_of_elements ] end # rubocop:disable Lint/UnreachableLoop def self.find_closest_index(lessons, lesson) previous_diff = nil lessons.each_with_index.reduce(nil) do |previous_closest_i, (l, i)| diff = (lesson.date.to_time.to_i - l.lesson_date.to_time.to_i).abs if previous_diff.nil? || diff < previous_diff previous_diff = diff return i end return previous_closest_i end end # rubocop:enable Lint/UnreachableLoop end
class RenameSubsysidInSourcings < ActiveRecord::Migration change_table :sourcings do |t| t.rename :subsys_id, :proj_module_id end end
require 'nokogiri' require 'open-uri' url = 'https://www.theskepticsguide.org/podcast/sgu' doc = Nokogiri::HTML(open(url)) sgu_mp3s = doc.xpath("//a").select {|link| link['href'] =~ /\.mp3$/ } sgu_mp3s.each do |link| xpathhref = link['href'] sgu_episode = File.basename(xpathhref) if File.exists?(sgu_episode) puts "Skipping the download of #{sgu_episode}, it already exists!" else puts "Downloading: #{sgu_episode}" open(xpathhref) do |save| File.open(sgu_episode,'w') {|out| out.print(save.read) } end end end
require 'set' require 'numo/narray' module Dezerb def using_config(name, value) old_value = Config.send(name) Config.send("#{name}=", value) begin yield ensure Config.send("#{name}=", old_value) end end def no_grad(&block) using_config('enable_backprop', false, &block) end def as_array(x) if x.instance_of? Variable or x.is_a? Numo::NArray x else Numo::NArray.cast(x) end end def as_variable(obj) if obj.is_a? Variable obj else Variable.new(obj) end end module_function :using_config, :no_grad, :as_array, :as_variable class Config @@enable_backprop = true def self.enable_backprop() @@enable_backprop end def self.enable_backprop=(val) @@enable_backprop = val end end class Variable attr_accessor :data, :name, :grad, :creator, :generation def initialize(data, name = nil) unless data.nil? unless data.is_a? Numo::NArray raise TypeError, "#{data.class} is not supported" end end @data = data @name = name @grad = nil @creator = nil @generation = 0 end def shape @data.shape end def ndim @data.ndim end def size @data.size end def length @data.length end def dtype @data.class end def inspect if @data.nil? 'variable(nil)' else p = @data.inspect.gsub(/\n/, "\n" + " " * 9) "variable(#{p})" end end def +(rval) Add.new.(self, Dezerb.as_array(rval)) end def *(rval) Mul.new.(self, Dezerb.as_array(rval)) end def -(rval) Sub.new.(self, Dezerb.as_array(rval)) end def /(rval) Div.new.(self, Dezerb.as_array(rval)) end def -@ Neg.new.(self) end def **(exp) Pow.new(exp).(self) end def coerce(other) [Variable.new(Dezerb.as_array(other)), self] end def set_creator(func) @creator = func @generation = func.generation + 1 end def cleargrad() @grad = nil end def backward(retain_grad: false, create_graph: false) if @grad.nil? @grad = Variable.new(@data.new_ones) end funcs = [] seen_set = Set.new add_func = Proc.new do |f| unless seen_set.include? f funcs << f seen_set << f funcs.sort_by! {|func| func.generation} end end add_func.(@creator) until funcs.empty? f = funcs.pop gys = f.outputs.map {|output| output.grad} Dezerb.using_config('enable_backprop', create_graph) do gxs = f.backward(*gys) unless gxs.instance_of? Array gxs = [gxs] end f.inputs.zip gxs do |x, gx| if x.grad.nil? x.grad = gx else x.grad = x.grad + gx end unless x.creator.nil? add_func.(x.creator) end end end unless retain_grad f.outputs.each {|y| y.grad = nil} end end end def reshape(*shape) if shape.length == 1 && shape[0].instance_of?(Array) shape = shape[0] end Functions.reshape self, shape end def transpose(*axes) if axes.length == 1 && axes[0].instance_of?(Array) axes = axes[0] end Functions.transpose self, axes end def T Functions.transpose self end def sum(axis: nil, keepdims: false) Functions.sum self, axis: axis, keepdims: keepdims end end class Parameter < Variable end class Function attr_accessor :inputs, :outputs, :generation def call(*inputs) inputs = inputs.map {|x| Dezerb.as_variable(x)} xs = inputs.map {|x| x.data} ys = forward(*xs) unless ys.instance_of? Array ys = [ys] end outputs = ys.map {|y| Variable.new(Dezerb.as_array(y))} if Config.enable_backprop @generation = inputs.max {|a, b| a.generation <=> b.generation}.generation outputs.each {|output| output.set_creator(self)} @inputs = inputs @outputs = outputs end outputs.length > 1 ? outputs : outputs[0] end def forward(in_data) raise NotImplementedError end def backward(gy) raise NotImplementedError end end class Add < Function def forward(x0, x1) @x0_shape, @x1_shape = x0.shape, x1.shape x0 + x1 end def backward(gy) gx0, gx1 = gy, gy if @x0_shape != @x1_shape gx0 = Functions.sum_to gx0, @x0_shape gx1 = Functions.sum_to gx1, @x1_shape end [gx0, gx1] end end def add(x0, x1) Add.new.(x0, x1) end class Mul < Function def forward(x0, x1) x0 * x1 end def backward(gy) x0, x1 = @inputs gx0, gx1 = gy * x1, gy * x0 if x0.shape != x1.shape gx0 = Functions.sum_to(gx0, x0.shape) gx1 = Functions.sum_to(gx1, x1.shape) end [gx0, gx1] end end def mul(x0, x1) Mul.new.(x0, x1) end class Neg < Function def forward(x) -x end def backward(gy) -gy end end class Sub < Function def forward(x0, x1) @x0_shape, @x1_shape = x0.shape, x1.shape x0 - x1 end def backward(gy) gx0, gx1 = gy, -gy if @x0_shape != @x1_shape gx0 = Functions.sum_to gx0, @x0_shape gx1 = Functions.sum_to gx1, @x1_shape end [gx0, gx1] end end class Div < Function def forward(x0, x1) x0 / x1 end def backward(gy) x0, x1 = @inputs gx0, gx1 = gy / x1, gy * (-x0 / x1 ** 2) if x0.shape != x1.shape gx0 = Functions.sum_to gx0, x0.shape gx1 = Functions.sum_to gx1, x1.shape end [gx0, gx1] end end class Pow < Function attr_accessor :c def initialize(c) @c = c end def forward(x) x ** @c end def backward(gy) x = @inputs[0] c = @c c * x ** (c - 1) * gy end end end
class FileIO def initialize(file_path) @file_path = file_path @line_arr = File.new(file_path).readlines @list_arr = [] @line_arr = @line_arr.map { |line| line.split("\",\"") } @line_arr.each do |line| line.pop line.shift list_title = line.shift @list_arr << convert_to_list_items(line, list_title) unless list_title == nil end end def convert_to_list_items(line_arr, list_title) val_arr = [] buffer = [] line_arr.each do |elem| if elem == "true" buffer << true elsif elem == "false" buffer << false else buffer << elem end if buffer.count == 2 val_arr << buffer buffer = [] end end return ToDoList.new(val_arr, list_title) end def return_array @list_arr end def save_file(list_obj_arr) File.open(@file_path, 'w+') do |f| f.write(get_file_string(list_obj_arr)) end end def get_file_string(list_obj_arr) save_str = "" list_obj_arr.each_with_index do |list| save_str << "\",\"" save_str << list.listname save_str << "\",\"" save_str << get_list_val_str(list) end save_str end def get_list_val_str(list_obj) result_str = "" list_obj.list.each_with_index do |pair, index| result_str << pair[0].to_s result_str << "\",\"" result_str << pair[1].to_s result_str << "\",\"" end result_str.gsub("\n", "")+"\n" end def to_boolean(str) str == 'true' end end
#!/usr/bin/env ruby class SuffixArray def initialize(the_string) @the_string = the_string @suffix_array = Array.new #build the suffixes last_index = the_string.length-1 (0..last_index).each do |i| the_suffix = the_string[i..last_index] the_position = i # << is the append (or push) operator for arrays in Ruby @suffix_array << { :suffix=>the_suffix, :position=>the_position } end #sort the suffix array @suffix_array.sort! { |a,b| a[:suffix] <=> b[:suffix] } end def find_substring(the_substring) #uses typical binary search high = @suffix_array.length - 1 low = 0 while(low <= high) mid = (high + low) / 2 this_suffix = @suffix_array[mid][:suffix] compare_len = the_substring.length-1 comparison = this_suffix[0..compare_len] if comparison > the_substring high = mid - 1 elsif comparison < the_substring low = mid + 1 else return @suffix_array[mid][:position] end end return nil end end sa = SuffixArray.new("abracadabra") puts sa.find_substring("ac")
# frozen_string_literal: true require 'bundler/setup' require 'dotenv' require 'awesome_print' require 'byebug' require 'logger' require 'pry' require 'vcr' require 'webmock/rspec' require 'help_scout-sdk' Dotenv.load('.env', '.env.test') def access_token_json file_fixture('access_token.json') end def api_path(path_part) 'https://api.helpscout.net/v2/' + path_part end def file_fixture(path) File.read("spec/fixtures/#{path}") end def model_name described_class.to_s.split('::').last.downcase end def logger @_logger ||= Logger.new($stdout, level: ENV.fetch('LOG_LEVEL', 'INFO')) end def valid_access_token file_fixture('access_token.json') end def with_config(new_configs = {}) old_values = {} new_configs.each do |getter, new_value| setter = "#{getter}=" old_values[setter] = HelpScout.configuration.public_send(getter) HelpScout.configuration.public_send(setter, new_value) end yield if block_given? old_values.each { |setter, old_value| HelpScout.configuration.public_send(setter, old_value) } end HelpScout.configure do |config| config.app_id = ENV.fetch('HELP_SCOUT_APP_ID') config.app_secret = ENV.fetch('HELP_SCOUT_APP_SECRET') config.default_mailbox = ENV.fetch('TEST_MAILBOX_ID') end HelpScout.api.access_token = ENV.fetch('HELP_SCOUT_ACCESS_TOKEN', 'bogustoken') VCR.configure do |config| config.cassette_library_dir = 'spec/cassettes' config.hook_into :webmock config.default_cassette_options = { record: :once } config.configure_rspec_metadata! config.filter_sensitive_data('<HELP_SCOUT_ACCESS_TOKEN>') { HelpScout.access_token&.value } config.filter_sensitive_data('<HELP_SCOUT_ACCESS_TOKEN>') do |interaction| begin JSON.parse(interaction.response.body)['access_token'] rescue JSON::ParserError => e logger.debug e.message end end config.filter_sensitive_data('Bearer <HELP_SCOUT_ACCESS_TOKEN>') do |interaction| interaction.request.headers['Authorization'] end config.filter_sensitive_data('<HELP_SCOUT_APP_ID>') { HelpScout.app_id } config.filter_sensitive_data('<HELP_SCOUT_APP_SECRET>') { HelpScout.app_secret } config.filter_sensitive_data('<TEST_MAILBOX_ID>') { HelpScout.default_mailbox } config.filter_sensitive_data('<TEST_CONVERSATION_ID>') { ENV['TEST_CONVERSATION_ID'] } config.filter_sensitive_data('<TEST_CUSTOMER_EMAIL>') { ENV['TEST_CUSTOMER_EMAIL'] } config.filter_sensitive_data('<TEST_CUSTOMER_ID>') { ENV['TEST_CUSTOMER_ID'] } config.filter_sensitive_data('<TEST_THREAD_ID>') { ENV['TEST_THREAD_ID'] } config.filter_sensitive_data('<TEST_USER_EMAIL>') { ENV['TEST_USER_EMAIL'] } config.filter_sensitive_data('<TEST_USER_ID>') { ENV['TEST_USER_ID'] } end RSpec.configure do |config| # rubocop:disable Metrics/BlockLength config.order = :random Kernel.srand config.seed # Default to "doc" formatting for single spec runs config.default_formatter = 'doc' if config.files_to_run.one? # Enable flags like --only-failures and --next-failure config.example_status_persistence_file_path = '.rspec_status' # Profile the 3 slowest examples config.profile_examples = 3 # Disable RSpec exposing methods globally on `Module` and `main` config.disable_monkey_patching! config.expect_with :rspec do |c| c.syntax = :expect end config.define_derived_metadata(file_path: %r{spec/unit}) do |metadata| metadata[:unit] = true end # Turn VCR off for unit specs config.around(:all, :unit) do |example| VCR.turn_off! example.run VCR.turn_on! end # Auto-tag integration specs to use VCR config.define_derived_metadata(file_path: %r{spec/integration}) do |metadata| metadata[:vcr] = true end config.before(:each) do HelpScout.reset! end config.before(:each, :unit) do stub_request(:post, 'https://api.helpscout.net/v2/oauth2/token') .to_return(body: access_token_json, headers: { 'Content-Type' => 'application/json' }) end end
class IntraDayEnergyPrice < ActiveRecord::Base belongs_to :region, class_name: "MarketRegions" end
Given /^a js literal "([^"]*)" is provided/ do |js| input_str js end Then /^i get the integer (-?\d+)$/ do |res| result.should == (res.to_i) end Then /^i get the float (.*)$/ do |res| result.should be_within(0.01).of(res.to_f) end Then /^i get the bool (true|false)$/ do |res| result.should == (res == 'true') end Given /^a js string literal (.+) is provided$/ do |str| input_str str end Then /^i get the string (.+)$/ do |res| result.should == eval("\"#{res}\"") end
#this is some code #class code: Class, Game #The class will have four methods #Guess, Check, mark, create #Guess will take a user input #Check will see if that has been guessed before, and then if its in the word #mark will add that guess to previously guessed, and if applicable add it to the word #each round it will check for completion #Create will be the init #There it will take a word from the user, and put it as the word to guess #Then, it will create a user visible list for _ class Hangman attr_accessor :user_word, :display_word, :tot_guess, :input_word, :guess_num, :word_length def initialize(word) @guess_num = 0 @input_word = word @word_length = word.length @display_word = @input_word.split("") if word.length < 4 @tot_guess = 3 elsif word.length < 7 @tot_guess = 5 else @tot_guess = 7 end @user_word = @input_word.split("") @display_word.map! {|letter| letter = "_"} end def guess(letter) spot_num = self.user_word.index(letter) if spot_num == nil return false @guess_num += 1 p @guess_num else @display_word[spot_num] = letter return true end end # def check # @blank_spaces = 0 # @display_word.each do |letter| # if letter == "_" # @blank_spaces += 1 # else # end # if @blank_spaces == 0 # @game_won = true # puts "Congratulations! You won" # break # else # @game_won = false # end # end # end def check @blank_spaces = 0 counter = 0 p self.word_length until counter == @word_length if @display_word[counter] == @user_word[counter] p "Check of #{self.display_word[counter]} is correct!" counter +=1 else @blank_spaces +=1 counter += 1 end end if @blank_spaces == 0 p "You Win" return true else p "Keep Trying!" return false end end end tester = Hangman.new("word") puts "The user word is #{tester.user_word}" puts "The current display word is #{tester.display_word}" puts "Word is #{tester.input_word}" puts tester.tot_guess tester.guess("o") puts "The user word is #{tester.user_word}" puts "The current display word is #{tester.display_word}" puts "Word is #{tester.input_word}" puts tester.tot_guess #Driver code puts "Welcome to the game, please enter what word you would like to play" input = gets.chomp game = Hangman.new(input) while game.guess_num != game.tot_guess puts "The current board is #{game.display_word}" puts "Please make a guess of a single letter" input = gets.chomp if game.guess(input) == false puts "Good try, but not good enough!" p "Your remaining guesses #{game.tot_guess - game.guess_num - 1}" else puts "Nice guess!" end if game.check == true game.guess_num = game.tot_guess else game.guess_num += 1 end end
class Item def initialize @price=30 end %^Getter %^ def price @price end %^Setter %^ def price=(price_value) @price=price_value end end item1 = Item.new puts item1.price item1.price = (10) puts item1.price item1.price = 100 puts item1.price
require 'spec_helper' describe TmuxStatus::Segments::Transfer do let(:ifconfig) do stub(downloaded: 1024*1024*23, uploaded: 1024*1024*5) end before do subject.stubs(ifconfig: ifconfig) end it { should be_a TmuxStatus::Segment } describe '#output' do context 'when interface is up' do before { ifconfig.stubs(up?: true) } it 'builds transfers string' do downloaded = ifconfig.downloaded.to_i / 1024 / 1024 uploaded = ifconfig.uploaded.to_i / 1024 / 1024 expected_output = "#{subject.modes}#{downloaded}/#{uploaded}" expect(subject.output).to eq(expected_output) end end context 'when interface is down' do before { ifconfig.stubs(up?: false) } its(:output) { should be_nil } end end end
class Todo < ApplicationRecord belongs_to :user validates :description, presence: true scope :incomplete, -> { where completed: false } end
require 'spec_helper' # Rename this file to classname_spec.rb # Check other boxen modules for examples # or read http://rspec-puppet.com/tutorial/ describe 'ohmyzsh' do let(:facts) { {:boxen_user => 'boxen_user'} } it { should contain_class('ohmyzsh') } it do should contain_exec('install oh-my-zsh').with({ :command => 'curl -L http://install.ohmyz.sh | sh', :creates => '/Users/boxen_user/.oh-my-zsh', }) end end
class PiecesController < ApplicationController before_action :check_yt, :only => :show def index @user = User.find(params[:user_id]) @yt_users = YoutubeUser.all end def show @presenter = Presenter.new(params[:user_id], params[:id], current_user) end def new @user = User.find(params[:user_id]) @piece = Piece.new end def create @piece = current_user.pieces.new(piece_params) if @piece.save flash[:success] = "'#{@piece.title}' Successfully Added" redirect_to user_pieces_path(current_user) else flash[:danger] = "Invalid Attributes" redirect_to new_user_piece_path(current_user) end end def edit @piece = Piece.find(params[:id]) @user = current_user end def update @user = current_user @piece = Piece.find(params[:id]) if @piece.update(piece_params) flash[:success] = "Updated!" redirect_to user_pieces_path(@user) else flash[:danger] = "Invalid Attributes" redirect_to edit_user_piece_path(@user, @piece) end end def destroy @user = current_user @piece = Piece.find(params[:id]) @piece.destroy flash[:success] = "Deleted!" redirect_to user_pieces_path(@user) end private def piece_params params.require(:piece).permit(:composer_last, :composer_first, :title, :yt_link) end def check_yt piece = Piece.find(params[:id]) user = YoutubeUser.find_by(user_id: params["user_id"].to_i) if piece.yt_uid != "" && piece.yt_uid != nil && user != nil piece.update_attributes(yt_uid: "", yt_link: "") if YoutubeService.on_yt?(piece.yt_uid) == false end end end
require 'albacore' MAIN_SLN = "FubuMVC.Blog.sln" tests = FileList["**/*.Tests.dll"].exclude(/obj/) task :default => [ "nuget:install", :compile, :tests] desc "Compile fubumvc.blog and run its unit test projects." msbuild :compile do |msb| msb.properties = { :configuration => :Debug } msb.targets = [ :Clean, :Build ] msb.solution = MAIN_SLN end namespace :nuget do desc "Install packages required by fubumvc.blog." task :install do sh "packages/nuget.exe install Blog/packages.config -OutputDirectory packages/" end desc "Update packages required by fubumvc.blog." task :update do |cmd| #TODO end end desc "Run tests for fubumvc.blog and all included packages." tests.uniq do |dir| dir.pathmap('%f') end .each do |assembly| xunit :tests do |xunit| xunit.command = "packages/xunit.console.exe" xunit.assembly = assembly end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) Rate.create( [ { base_currency: 'EUR', counter_currency: 'NOK', date: Date.today, rate: '9.5' }, { base_currency: 'EUR', counter_currency: 'SEK', date: Date.today, rate: '10.07' }, { base_currency: 'SEK', counter_currency: 'NOK', date: Date.today, rate: '0.94' }, { base_currency: 'NOK', counter_currency: 'SEK', date: Date.today, rate: '1.06' }, { base_currency: 'NOK', counter_currency: 'EUR', date: Date.today, rate: '0.11' }, { base_currency: 'SEK', counter_currency: 'EUR', date: Date.today, rate: '0.099' }, { base_currency: 'EUR', counter_currency: 'NOK', date: Date.yesterday, rate: '9.5' }, { base_currency: 'EUR', counter_currency: 'SEK', date: Date.yesterday, rate: '10.07' }, { base_currency: 'SEK', counter_currency: 'NOK', date: Date.yesterday, rate: '0.94' }, { base_currency: 'NOK', counter_currency: 'SEK', date: Date.yesterday, rate: '1.06' }, { base_currency: 'NOK', counter_currency: 'EUR', date: Date.yesterday, rate: '0.11' }, { base_currency: 'SEK', counter_currency: 'EUR', date: Date.yesterday, rate: '0.099' } ] )
module TaskMutations fields = { description: 'str', assigned_to_ids: 'str', json_schema: 'str', order: 'int', fieldset: 'str' } create_fields = { label: '!str', type: '!str', jsonoptions: 'str', annotated_id: 'str', annotated_type: 'str' }.merge(fields) update_fields = { label: 'str', response: 'str', accept_suggestion: 'int', reject_suggestion: 'int' }.merge(fields) Create, Update, Destroy = GraphqlCrudOperations.define_crud_operations('task', create_fields, update_fields, ['project_media', 'source', 'project', 'version']) end
require 'sqlite3' $db = SQLite3::Database.open "congress_poll_results.db" def state_to_abbr(state) state_abbr = { 'AL' => 'Alabama', 'AK' => 'Alaska', 'AS' => 'America Samoa', 'AZ' => 'Arizona', 'AR' => 'Arkansas', 'CA' => 'California', 'CO' => 'Colorado', 'CT' => 'Connecticut', 'DE' => 'Delaware', 'DC' => 'District of Columbia', 'FM' => 'Micronesia1', 'FL' => 'Florida', 'GA' => 'Georgia', 'GU' => 'Guam', 'HI' => 'Hawaii', 'ID' => 'Idaho', 'IL' => 'Illinois', 'IN' => 'Indiana', 'IA' => 'Iowa', 'KS' => 'Kansas', 'KY' => 'Kentucky', 'LA' => 'Louisiana', 'ME' => 'Maine', 'MH' => 'Islands1', 'MD' => 'Maryland', 'MA' => 'Massachusetts', 'MI' => 'Michigan', 'MN' => 'Minnesota', 'MS' => 'Mississippi', 'MO' => 'Missouri', 'MT' => 'Montana', 'NE' => 'Nebraska', 'NV' => 'Nevada', 'NH' => 'New Hampshire', 'NJ' => 'New Jersey', 'NM' => 'New Mexico', 'NY' => 'New York', 'NC' => 'North Carolina', 'ND' => 'North Dakota', 'OH' => 'Ohio', 'OK' => 'Oklahoma', 'OR' => 'Oregon', 'PW' => 'Palau', 'PA' => 'Pennsylvania', 'PR' => 'Puerto Rico', 'RI' => 'Rhode Island', 'SC' => 'South Carolina', 'SD' => 'South Dakota', 'TN' => 'Tennessee', 'TX' => 'Texas', 'UT' => 'Utah', 'VT' => 'Vermont', 'VI' => 'Virgin Island', 'VA' => 'Virginia', 'WA' => 'Washington', 'WV' => 'West Virginia', 'WI' => 'Wisconsin', 'WY' => 'Wyoming' } state_abbr.key(state) end def print_longest_serving_reps(minimum_years) raise ArgumentError.new("Argument needs to be a number") unless minimum_years.is_a? Integer # Prevents SQL injection puts "LONGEST SERVING REPRESENTATIVES" $db.execute("SELECT name, years_in_congress FROM congress_members WHERE years_in_congress > #{minimum_years}").each { |rep| puts rep.join(' - ') + ' years' } end def print_lowest_grade_level_speakers(maximum_grade) raise ArgumentError.new("Argument needs to be a number") unless maximum_grade.is_a? Integer # Prevents SQL injection puts "LOWEST GRADE LEVEL SPEAKERS (less than #{maximum_grade}th grade)" $db.execute("SELECT name, grade_current FROM congress_members WHERE grade_current < #{maximum_grade}").each { |speaker, grade| puts speaker + " - Grade: " + grade.round(1).to_s} end def print_representatives_for_states(*selected_states) # Modified this to take a list of states as arguments selected_states.each do |state| puts "REPRESENTATIVES FOR " + state.upcase puts $db.execute("SELECT name FROM congress_members WHERE location = '#{state_to_abbr(state)}'") # Translates state to its abbr so we can look for it in the database print_separator end end def print_votes_per_politician puts "VOTES PER POLITICIAN" vote_count = $db.execute("SELECT name, COUNT(politician_id) FROM congress_members INNER JOIN votes ON congress_members.id = politician_id GROUP BY name ORDER BY COUNT(politician_id) DESC") vote_count.each {|politician, votes| puts politician + ' - ' + votes.to_s + ' votes'} end def print_voters_per_politician all_politicians = $db.execute("SELECT name FROM congress_members") all_politicians.flatten!.each do |politician| puts "List of people who voted for #{politician}:" voters = $db.execute("SELECT first_name, last_name FROM congress_members INNER JOIN votes ON congress_members.id = politician_id INNER JOIN voters ON voters.id = votes.voter_id WHERE name = '#{politician}'") puts voters.map{|name, surname| name + ' ' + surname}.join(", ") end end def print_separator puts puts "------------------------------------------------------------------------------" puts end print_representatives_for_states('Arizona', 'Hijoputa') print_longest_serving_reps(35) # Print out the number of years served as well as the name of the longest running reps # output should look like: Rep. C. W. Bill Young - 41 years print_separator print_lowest_grade_level_speakers(8) print_separator print_representatives_for_states('New Jersey', 'New York', 'Maine', 'Florida', 'Alaska') # Make a method to print the following states representatives as well: # (New Jersey, New York, Maine, Florida, and Alaska) ##### BONUS ####### # Stop SQL injection attacks! Statmaster learned that interpolation of variables in SQL statements leaves some security vulnerabilities. Use the google to figure out how to protect from this type of attack. # I can raise an error if the arguments for print_longest_serving_reps and print_lowest_grade_level_speakers(8) # are not integers, I don't have that problem in print_representatives_for_states since I'm converting the # arguments passing them through the Hash # I got some info from here http://guides.rubyonrails.org/security.html#injection # (bonus) # Create a listing of all of the Politicians and the number of votes they recieved print_votes_per_politician # output should look like: Sen. John McCain - 7,323 votes # Create a listing of each Politician and the voter that voted for them # output should include the senators name, then a long list of voters separated by a comma # # * you'll need to do some join statements to complete these last queries! print_voters_per_politician # Generate an array with all the politicians names # Create the list of voters for each one # REFLECTION # This was just a matter of figuring what to SELECT and what to do with that data once retrieved # The .inspect method works wonders for this kind of work, cause it lets you see what kind of primitive # (or primitive inside of another primitive) you are dealing with. # For creating the queries I use SQLite Pro, it's a very simple GUI for SQLite that works better for me than # the terminal # I changed the print_representatives_for_states to accept any number of states as an argument, and use a hash # to 'translate' the state names to the format they are stored in the database. # The method to print voters per politicians takes more than 4 seconds to run, I'm not happy about that but # don't know how to make it go faster.
class CreateProducts < ActiveRecord::Migration def change create_table :products do |t| t.string :name t.string :quantity t.decimal :price , :precision => 8, :scale => 2 t.integer :employee_id t.integer :updater_id t.integer :location_id t.timestamps end end end
# module Hauling # def haul_weight(weight) # puts "The vehicle is hauling #{weight} pounds on its trailer." # end # end # class Vehicle # @@number_vehicles = 0 # attr_accessor :color, :year, :model # def initialize(year, model, color) # self.year = year # self.model = model # self.color = color # @current_speed = 0 # @@number_vehicles += 1 # end # def self.total_vehicles # puts "The total number of vehicles is #{@@number_vehicles}." # end # def speed_up(number) # @current_speed += number # puts "You push the gas and accelerate #{number} mph." # end # def brake(number) # @current_speed -= number # puts "You push the brake and decelerate #{number} mph." # end # def current_speed # puts "You are now going #{@current_speed} mph." # end # def shut_down # @current_speed = 0 # puts "Let's park this bad boy!" # end # def to_s # "Your vehicle is a #{color} #{year} #{model}." # end # def self.gas_mileage(miles, gallons) # puts "Your gas mileage is #{miles / gallons} mpg." # end # end # class MyTruck < Vehicle # include Hauling # TRUCK_BED_SIZE = 10 # NUMBER_OF_DOORS = 2 # def truck_bed # puts "The truck has a bed of size #{TRUCK_BED_SIZE}." # end # def to_s # "Your truck is a #{color} #{year} #{model}." # end # end # class MyCar < Vehicle # TURBO_BOOST = true # NUMBER_OF_DOORS = 2 # def has_turbo? # puts (TURBO_BOOST ? "The Car has turbo." : "The car doesn't have turbo.") # end # def spray_paint(new_color) # self.color = new_color # puts "Changing the color of the car to #{new_color}." # end # def to_s # "Your car is a #{color} #{year} #{model}." # end # end # MyCar.gas_mileage(50, 16) # lumina = MyCar.new(1997, 'chevy lumina', 'white') # lumina.has_turbo? # puts lumina.color # puts lumina ## "puts" calls "to_s" automatically # lumina.spray_paint('yellow') # puts lumina.color # puts lumina.year # lumina.speed_up(20) # lumina.current_speed # lumina.speed_up(20) # lumina.current_speed # lumina.brake(20) # lumina.current_speed # lumina.brake(20) # lumina.current_speed # lumina.shut_down # lumina.current_speed # chevy = MyTruck.new(2000, 'dodge ram', 'blue') # puts chevy # chevy.truck_bed # MyTruck.gas_mileage(351, 16) # MyTruck.total_vehicles # MyCar.total_vehicles # Vehicle.total_vehicles # chevy.haul_weight(2000) # puts MyCar.ancestors # puts MyTruck.ancestors # puts Vehicle.ancestors ## Their solution # module Towable # def can_tow?(pounds) # pounds < 2000 ? true : false # end # end # class Vehicle # SECONDS_IN_DAY = 60 * 60 * 24 # attr_accessor :color # attr_reader :model, :year # @@number_of_vehicles = 0 # def self.number_of_vehicles # puts "This program has created #{@@number_of_vehicles} vehicles" # end # def initialize(year, model, color) # @year = year # @model = model # @color = color # @current_speed = 0 # @@number_of_vehicles += 1 # end # def speed_up(number) # @current_speed += number # puts "You push the gas and accelerate #{number} mph." # end # def brake(number) # @current_speed -= number # puts "You push the brake and decelerate #{number} mph." # end # def current_speed # puts "You are now going #{@current_speed} mph." # end # def shut_down # @current_speed = 0 # puts "Let's park this bad boy!" # end # def self.gas_mileage(gallons, miles) # puts "#{miles / gallons} miles per gallon of gas" # end # def spray_paint(color) # self.color = color # puts "Your new #{color} paint job looks great!" # end # def display_age # puts "The #{self.model} is #{age_of_car} years old." # end # private # def age_of_car # # purchase_date = Time.new(year_bought, month_bought, day_bought) # purchase_year = self.year # present_year = Time.new.year # present_year - purchase_year # # number_of_days_since_purchase = (present_date - purchase_date).to_f / SECONDS_IN_DAY # # age_years, age_days = number_of_days_since_purchase.divmod(365.25) # # [age_years, age_days] # end # end # class MyTruck < Vehicle # include Towable # NUMBER_OF_DOORS = 2 # def to_s # "My truck is a #{self.color}, #{self.year}, #{self.model}!" # end # end # class MyCar < Vehicle # NUMBER_OF_DOORS = 4 # def to_s # "My car is a #{self.color}, #{self.year}, #{self.model}!" # end # end # lumina = MyCar.new(1985, 'chevy lumina', 'white') # lumina.speed_up(20) # lumina.current_speed # lumina.speed_up(20) # lumina.current_speed # lumina.brake(20) # lumina.current_speed # lumina.brake(20) # lumina.current_speed # lumina.shut_down # MyCar.gas_mileage(13, 351) # lumina.spray_paint("red") # puts lumina # lumina.display_age class Student def initialize(name, grade) @name = name @grade = grade end def name @name end def name=(n) @name = n end def grade=(g) @grade = g end def better_grade_than?(other) grade > other.grade end # protected private def grade @grade end end joe = Student.new('Joe', 55) ben = Student.new('Ben', 34) # puts "Well done" if joe.better_grade_than?(ben) puts joe.grade
require 'spec_helper' feature "User creates a game", %Q{ As an authenticated user I want to create a game So that I can begin configuring it } do # Acceptance Criteria: # * I must specify the game's name and starting character points # * If I do not specify name and points, I am presented with an error # * If I specify name and point, the game is saved context "with valid input" do it "records a game" do count = Game.count user = FactoryGirl.create(:user) login(user) visit new_game_path fill_in "Name", with: "Witchwood" fill_in "Starting", with: "25" click_on "Create Game" expect(page).to have_content("Witchwood") expect(Game.count).to eq(count + 1) expect(Game.last.user_id).to eq(user.id) end end context "with invalid input" do it "throws an error" do count = Game.count user = FactoryGirl.create(:user) login(user) visit new_game_path click_on "Create Game" expect(page).to have_content("Error") expect(Game.count).to eq(count) end end context "not logged in" do it "won't authorize you" do expect { visit new_game_path }.to raise_error(ActionController::RoutingError, "Not Found") end end end
# encoding: UTF-8 # Plugin Definition file # The purpose of this file is to declare to InSpec what plugin_types (capabilities) # are included in this plugin, and provide hooks that will load them as needed. # It is important that this file load successfully and *quickly*. # Your plugin's functionality may never be used on this InSpec run; so we keep things # fast and light by only loading heavy things when they are needed. # Presumably this is light require 'inspec-init-resource/version' module InspecPlugins module Init() # This simple class handles the plugin definition, so calling it simply Plugin is OK. # Inspec.plugin returns various Classes, intended to be superclasses for various # plugin components. Here, the one-arg form gives you the Plugin Definition superclass, # which mainly gives you access to the hook / plugin_type DSL. # The number '2' says you are asking for version 2 of the plugin API. If there are # future versions, InSpec promises plugin API v2 will work for at least two more InSpec # major versions. class CLI < ::Inspec.plugin(2, :cli_command) desc 'resource NAME', 'Generates an InSpec resource' def resource(resource_name) File. end end end end
def source 'func foo ( ) -> Int { }' end def expected_tokens [ { type: 'T_FUNCTION', value: 'func' }, { type: 'T_WHITESPACES', value: ' ' }, { type: 'T_IDENTIFIER', value: 'foo' }, { type: 'T_WHITESPACES', value: ' ' }, { type: 'T_OPEN_ROUND_BRACKET', value: '(' }, { type: 'T_WHITESPACES', value: ' ' }, { type: 'T_CLOSE_ROUND_BRACKET', value: ')' }, { type: 'T_WHITESPACES', value: ' ' }, { type: 'T_RETURN_TYPE_ARROW', value: '->' }, { type: 'T_WHITESPACES', value: ' ' }, { type: 'T_IDENTIFIER', value: 'Int' }, { type: 'T_WHITESPACES', value: ' ' }, { type: 'T_OPEN_CURLY_BRACKET', value: '{' }, { type: 'T_WHITESPACES', value: ' ' }, { type: 'T_CLOSE_CURLY_BRACKET', value: '}' } ] end def expected_ast { __type: 'program', body: [ { __type: 'function-declaration', name: { __type: 'identifier', value: 'foo' }, parameters: [], return_type: { __type: 'identifier', value: 'Int' }, body: [] } ] } end load 'spec_builder.rb'
RSpec.configure do |config| config.before(:suite) do ENV['CLUSTER_FSCK_ENV'] = 'test' #redefine constant warning when setting ClusterFsck::CLUSTER_FSCK_ENV constant here def ClusterFsck.cluster_fsck_env 'test' end ENV['CLUSTER_FSCK_BUCKET'] = 'test' ClusterFsck::CLUSTER_FSCK_BUCKET = 'test' end end
require 'active_support/core_ext/hash/conversions' class ActiveMerchant::Billing::Integrations::KkbEpay::Notification < ActiveMerchant::Billing::Integrations::Notification def initialize(post, crypt_params = {}) @crypt_params = crypt_params @crypt = ActiveMerchant::Billing::Integrations::KkbEpay::crypt crypt_params super post self end def complete? true end def item_id params['order_id'] end def transaction_id params['reference'] end def approval_code params['approval_code'] end # When was this payment received by the client. def received_at params['timestamp'] end def payer_email params['email'] end def security_key params['secure'] end # the money amount we received in X.2 decimal. def gross params['amount'] end def currency Money::Currency::find_by_iso_numeric(params['currency_code']).iso_code end def amount Money.new gross, currency end # Was this a test transaction? def test? false end def acknowledge true end private # Take the posted data and move the relevant data into a hash def parse(post) xml = post[:response] raise "Epay: Invalid signature!" unless @crypt.check_signed_xml xml hash = Hash.from_xml(xml)['document'] rc = hash['bank']['results']['payment']['response_code'] raise "Epay: ResponseCode = #{rc}. Contact to bank!" unless '00' == rc params['amount'] = hash['bank']['results']['payment']['amount'] params['email'] = hash['bank']['customer']['mail'] params['order_id'] = hash['bank']['customer']['merchant']['order']['order_id'] params['reference'] = hash['bank']['results']['payment']['reference'] params['approval_code'] = hash['bank']['results']['payment']['approval_code'] params['secure'] = hash['bank']['results']['payment']['secure'] params['timestamp'] = hash['bank']['results']['timestamp'] params['currency_code'] = hash['bank']['customer']['merchant']['order']['currency'] end end
# coding: utf-8 require File.dirname(__FILE__) + '/../spec_helper' describe Book do it "should increment tombo before saving" do user = create(:user) 3.times{ create(:book, :user_id => user.id) } book = create(:book, :user_id => user.id) book.tombo.should == '4' user = create(:user) create(:book, :user_id => user.id) book = create(:book, :user_id => user.id) book.tombo.should == '2' end it "should get concatenated titles" do create(:book, :title => 'First') create(:book, :title => 'Second') create(:book, :title => 'Second') Book.titles.should == ["First", "Second"] end # Example of the above usage it "should get concatenated editors" do create(:book, :editor => 'First') create(:book, :editor => 'Second') create(:book, :editor => 'Second') Book.editors.should == ["First", "Second"] end it "should get concatenated years" do create(:book, :year => 2000) create(:book, :year => 2001) create(:book, :year => 2001) Book.years.should == [2000, 2001] end Book.complex_fields.each do |k, v| it "should get concatenated #{v} of #{k}" do values = [create(k.singular.to_sym, v.to_sym => 'First'), create(k.singular.to_sym, v.to_sym => 'Second')] book = Factory(:book, k.to_sym => values) (book.send "#{k}_#{v}s").should == "First, Second" end end # Example of the above usage it "should get concatenated names of authors" do values = [create(:author, :name => 'First'), create(:author, :name => 'Second')] book = create(:book, :authors => values) book.authors_names.should == "First, Second" end it "should get values from google book" do isbn = '1606802127' faweb_register_book('gbook-proudhon.xml', isbn) attributes = Book.get_attributes_from_gbook(isbn) attributes['isbn'].should == isbn attributes['title'].should == "What Is Property" attributes['subtitle'].should == "An Inquiry Into The Principle Of Right And Of Government" # attributes['authors'].should == ["Pierre Joseph Proudhon", "Amédée Jérôme Langlois"] attributes['authors_attributes']['0']['name'].should == "Pierre Joseph Proudhon" attributes['editor'].should == "Forgotten Books" # attributes['year'].should == "1969" attributes['language'].should == "En" attributes['page_number'].should == "457" end it "should belong to an user" do user = create(:user) book = create(:book, :user_id => user.id) book.user.should == user end it "should give an error if no user is given" do book = build(:book, :user_id => nil) book.should_not be_valid book.should have(1).error_on(:user_id) end it "should give an error if wrong link in pdf is given" do book = build(:book, :pdflink => 'foo bar') book.should_not be_valid book.should have(1).error_on(:pdflink) end it "should give an error if wrong link in img is given" do book = build(:book, :imglink => 'foo bar') book.should_not be_valid book.should have(1).error_on(:imglink) end it "should give an error if pages is not a number" do book = build(:book, :page_number => 'foo bar') book.should_not be_valid book.should have(1).error_on(:page_number) end it "should give an error if year is not a number" do book = build(:book, :year => 'foo bar') book.should_not be_valid book.should have(1).error_on(:year) end it "should give an error if volume is not a number" do book = build(:book, :volume => 'foo bar') book.should_not be_valid book.should have(1).error_on(:volume) end it "should give an error if no title is given" do book = build(:book, :title => '') book.should_not be_valid book.should have(1).error_on(:title) end it "should return the attributes of a book if the book is found in the database" do book = create(:book, :isbn => 111) author1 = create(:author, :book_id => book.id, :name => "Foo Bar 1") author2 = create(:author, :book_id => book.id, :name => "Foo Bar 2") attributes = Book.get_attributes_from_library(111) attributes['title'].should == book.title attributes['authors_attributes']['0']['name'].should == author1.name attributes['authors_attributes']['1']['name'].should == author2.name end it "should return the attributes of book if found by google book or in the database" do isbn = '1606802127' faweb_register_book('gbook-proudhon.xml', isbn) attributes = Book.get_attributes(isbn) attributes['isbn'].should == isbn attributes['title'].should == "What Is Property" book = create(:book, :isbn => isbn, :title => "Title") attributes = Book.get_attributes(isbn) attributes['isbn'].should == isbn attributes['title'].should == book.title end end
class Request include RequestFieldValidation def self.get_all(query_params) success, messages, filters = get_request_filters(query_params) if !success return success, messages, [] end requests = self.where(filters) # updating the request status if time elapsed is 5 or more than 5 minutes after coming to ongoing status requests.each do |obj| if obj[:status] == "ongoing" time_elapsed = (Time.now - obj[:ongoing_at]).to_i/60 if time_elapsed >= 5 obj[:status] = "complete" obj[:completed_at] = obj[:ongoing_at] + 5.minutes obj.update_attributes(:status => "complete", :completed_at => (obj[:ongoing_at] + 5.minutes)) end end end requests = requests.as_json(only: [:status], methods: [:request_id, :customer_id, :driver_id, :request_time_elapsed, :pickedup_time_elapsed, :complete_time_elapsed]) return true, [], requests end def self.get_driver_requests(query_params) filters = get_driver_requests_filters(query_params) waiting_requests = Request.where(:status => "waiting") other_requests = self.where(filters.merge(:status.in => ["ongoing", "complete"])) requests = waiting_requests + other_requests requests.each do |obj| if obj[:status] == "ongoing" time_elapsed = (Time.now - obj[:ongoing_at]).to_i/60 if time_elapsed >= 5 obj[:status] = "complete" obj[:completed_at] = obj[:ongoing_at] + 5.minutes obj.update_attributes(:status => "complete", :completed_at => (obj[:ongoing_at] + 5.minutes)) end end end requests = requests.as_json(only: [:status], methods: [:request_id, :customer_id, :driver_id, :request_time_elapsed, :pickedup_time_elapsed, :complete_time_elapsed]) return true, [], requests end def self.create_request(query_params) # first will create customer # then will create request since it belongs to the specified customer return false, ["Customer id is required!"], {} unless query_params[:customer_id].present? return false, ["Customer id already registered!"], {} if Customer.where(:customer_id => query_params[:customer_id]).count > 0 @customer = Customer.create(:customer_id => query_params[:customer_id]) if @customer.present? request = Request.create(:customer => @customer) return true, [], request.as_json else return false, ["Error creating customer!"], {} end end def self.assign_request(query_params) # checking for request status before assignment # also checking for driver is busy or not since he/she can only do one ride at a time return false, ["Request no longer available!"], {} unless query_params[:request].status == "waiting" requests = Request.where(:status => "ongoing", :driver_id => query_params[:driver].id).select { |obj| ((Time.now - obj.ongoing_at).to_i/60) < 5 } return false, ["Driver is already serving a ride!"], {} if requests.count > 0 success = query_params[:request].update_attributes(:status => "ongoing", :ongoing_at => Time.now, :driver => query_params[:driver]) query_params[:request][:status] = "ongoing" query_params[:request][:ongoing_at] = Time.now query_params[:request][:driver_id] = query_params[:driver].id return success, [], query_params[:request] end ## version 2 methods def self.get_all_v2(query_params) success, messages, filters = get_request_filters(query_params) if !success return success, messages, [] end requests = self.where(filters) # updating the request status if time elapsed is 5 or more than 5 minutes after coming to ongoing status requests.each do |obj| if obj[:status] == "ongoing" time_elapsed = (Time.now - obj[:ongoing_at]).to_i/60 if time_elapsed >= 5 obj[:status] = "complete" obj[:completed_at] = obj[:ongoing_at] + 5.minutes obj.update_attributes(:status => "complete", :completed_at => (obj[:ongoing_at] + 5.minutes)) end end end requests = requests.as_json(only: [:status, :latitude, :longitude], methods: [:request_id, :customer_id, :driver_id, :request_time_elapsed, :pickedup_time_elapsed, :complete_time_elapsed]) return true, [], requests end def self.get_driver_requests_v2(query_params) filters = get_driver_requests_filters(query_params) waiting_requests = Request.where(:status => "waiting", :nearest_driver_ids => query_params[:driver].id) if filters[:status].blank? filters.merge!(:status.in => ["ongoing", "complete"]) end other_requests = self.where(filters) requests = waiting_requests + other_requests requests.each do |obj| if obj[:status] == "ongoing" time_elapsed = (Time.now - obj[:ongoing_at]).to_i/60 if time_elapsed >= 5 obj[:status] = "complete" obj[:completed_at] = obj[:ongoing_at] + 5.minutes obj.update_attributes(:status => "complete", :completed_at => (obj[:ongoing_at] + 5.minutes)) end end end requests = requests.as_json(only: [:status, :latitude, :longitude], methods: [:request_id, :customer_id, :driver_id, :request_time_elapsed, :pickedup_time_elapsed, :complete_time_elapsed]) return true, [], requests end def self.create_request_v2(query_params) # first will create customer # then will create request since it belongs to the specified customer return false, ["Customer id is required!"], {} unless query_params[:customer_id].present? return false, ["Customer id already registered!"], {} if Customer.where(:customer_id => query_params[:customer_id]).count > 0 return false, ["Rides not available. Try again later!"], {} if Request.where(:status => "waiting").count > 10 @customer = Customer.create(:customer_id => query_params[:customer_id]) if @customer.present? nearest_driver_ids = get_nearest_drivers(query_params) request = Request.create(:customer => @customer, :latitude => query_params[:latitude].to_i, :longitude => query_params[:longitude].to_i, :nearest_driver_ids => nearest_driver_ids) return true, [], request.as_json else return false, ["Error creating customer!"], {} end end def self.assign_request_v2(query_params) # checking for request status before assignment # also checking for driver is busy or not since he/she can only do one ride at a time return false, ["Request no longer available!"], {} unless query_params[:request].status == "waiting" requests = Request.where(:status => "ongoing", :driver_id => query_params[:driver].id).select { |obj| ((Time.now - obj.ongoing_at).to_i/60) < 5 } return false, ["Driver is already serving a ride!"], {} if requests.count > 0 success = query_params[:request].update_attributes(:status => "ongoing", :ongoing_at => Time.now, :driver => query_params[:driver]) query_params[:request][:status] = "ongoing" query_params[:request][:ongoing_at] = Time.now query_params[:request][:driver_id] = query_params[:driver].id if success # driver ids list to filterout to which drivers this should affect driver_ids_list = query_params[:request].nearest_driver_ids - [query_params[:driver].id] driver_ids_list = driver_ids_list.map { |id| Driver.find(id).inc_id } message_to_publish = { :request => query_params[:request].as_json, :driver_ids => driver_ids_list, :message_type => "ride_already_assigned" } Pusher.trigger('ride-request', 'ride-already-assigned', message_to_publish) end return success, [], query_params[:request] end def self.get_nearest_drivers(query_params) distance_hash_array = [] Driver.each do |driver| distance = get_distance(driver.latitude, driver.longitude, query_params[:latitude].to_i, query_params[:longitude].to_i) distance_hash_array << {:id => driver.id, :distance => distance} end distance_hash_array.sort_by { |e| e[:distance] }[0..2].map { |e| e[:id] } end def self.get_distance(driver_lat, driver_lng, request_lat, request_lng) distance = (driver_lat - request_lat)*(driver_lat - request_lat) + (driver_lng - request_lng)*(driver_lng - request_lng) distance = Math.sqrt(distance) end ## common methods def self.get_request_filters(query_params) filters = {} success = true messages = [] filters.merge!(:status => query_params[:status]) unless query_params[:status].blank? if query_params[:driver_id].present? @driver = Driver.find_by(:inc_id => query_params[:driver_id].to_i) rescue nil if @driver.nil? success, messages = false, ["Driver not found!"] else filters.merge!(:driver_id => @driver.id) end end if query_params[:customer_id].present? @customer = Customer.find_by(:inc_id => query_params[:customer_id].to_i) rescue nil if @customer.nil? success, messages = false, ["Customer not found!"] else filters.merge!(:customer_id => @customer.id) end end return success, messages, filters end def self.get_driver_requests_filters(query_params) filters = {} filters.merge!(:status => query_params[:status]) unless query_params[:status].blank? filters.merge!(:driver_id => query_params[:driver].id) filters end def get_elapsed_time(time_in_seconds) hours = time_in_seconds / (60 * 60) minutes = (time_in_seconds / 60) % 60 seconds = time_in_seconds % 60 if hours > 0 "#{ hours } hour #{ minutes } min #{ seconds } sec" elsif minutes > 0 "#{ minutes } min #{ seconds } sec" else "#{ seconds } sec" end end def publish_ride_complete_message driver_ids_list = [self.driver.inc_id] message_to_publish = { :request => self.as_json(only: [:status], methods: [:customer_id, :request_time_elapsed, :request_id, :pickedup_time_elapsed, :complete_time_elapsed]), :driver_ids => driver_ids_list, :message_type => "ride_completed" } Pusher.trigger('ride-request', 'ride-completed', message_to_publish) end def request_id self.inc_id end def customer_id self.customer.customer_id end def driver_id self.driver.inc_id rescue 'N/A' end def request_time_elapsed # get_elapsed_time((Time.now - self.created_at).to_i) (Time.now - self.created_at).to_i end def pickedup_time_elapsed # get_elapsed_time((Time.now - self.ongoing_at).to_i) rescue nil (Time.now - self.ongoing_at).to_i rescue nil end def complete_time_elapsed # get_elapsed_time((Time.now - self.completed_at).to_i) rescue nil (Time.now - self.completed_at).to_i rescue nil end end
# frozen_string_literal: true require_relative "choice_character" module TTY class Fzy class Choice include Interfaceable extend Forwardable attr_reader :search, :text, :alt def_delegators :match, :positions, :score def initialize(search, content) @search = search extract_content(content) end def match? search.empty? || !match.nil? end def render(active, longest_choice) if alt.nil? characters else [*characters, *alt_characters(active, longest_choice)] end.map.with_index do |character, index| character.to_s(inverse: active, highlight: positions.include?(index)) end.take(columns).join end def returns @returns || raw_text end def width characters.size end private def characters @characters ||= pastel.undecorate(text).flat_map do |decoration| decoration[:text].split("").map do |character| ChoiceCharacter.new(character, decoration) end end end def alt_characters(_active, longest_choice) [ *Array.new((longest_choice - width) + 2, dim_character(" ")), dim_character("("), *alt.split("").map(&method(:dim_character)), dim_character(")") ] end def dim_character(character) ChoiceCharacter.new(character, style: :dim) end def match @matches ||= {} if @matches.key?(search.query) @matches[search.query] else @matches[search.query] = ::Fzy.match(search.pretty_query, raw_text) end end def raw_text @raw_text ||= pastel.strip(text) end def pastel @pastel ||= Pastel.new end def extract_content(content) if content.is_a?(Hash) @text, @alt, @returns = content.values_at(:text, :alt, :returns) else @text = content end end end end end
class Contact < ApplicationRecord has_many :taggings, dependent: :destroy has_many :tags, through: :taggings validates :lastname, presence: true before_validation :downcase_email accepts_nested_attributes_for :tags, reject_if: :all_blank, allow_destroy: true accepts_nested_attributes_for :taggings def name "#{lastname.upcase} #{firstname.capitalize} " end def downcase_email self.email.try(:downcase!) end def next Contact.where("id > ?", id).limit(1).first end def prev Contact.where("id < ?", id).last end end
require 'rspec' require_relative '../lib/person.rb' describe Person do let(:person_name) {"Annie Edison"} let(:person_weight) {120} let(:person_gender) {'F'} let(:person_meal_time) {3} let(:person_first_drink) {2} let(:person) do Person.new(person_name, person_weight, person_gender, person_meal_time, person_first_drink) end it 'has a name' do expect(person.name).to eq(person_name) end it 'has a weight' do expect(person.weight).to eq(person_weight) end it 'has consumed a meal a certain number of hours ago' do expect(person.hours_since_meal).to eq(person_meal_time) end it 'it has consumed the first alcoholic drink a certain number of hours ago' do expect(person.hours_since_first_drink).to eq(person_first_drink) end it 'has a gender' do expect(person.gender).to eq(person_gender) end it 'can calculate a persons intoxication level based on inputted data' do #expect(person.intoxication_level).to eq() end end
class CreateRakutenCosts < ActiveRecord::Migration def change create_table :rakuten_costs do |t| t.references :user, index: true, foreign_key: true t.date :commission_pay_date t.integer :pc_commission_amount t.integer :pc_commission_book_amount t.integer :pc_commission_difference t.integer :mobile_commission_amount t.integer :mobile_commission_book_amount t.integer :mobile_commission_difference t.integer :pc_vest_point t.integer :mobile_vest_point t.integer :affiliate_reward t.integer :affiliate_system_fee t.integer :r_card_plus t.integer :system_improvement_fee t.integer :system_improvement_book_amount t.integer :system_improvement_difference t.integer :open_shop_fee t.integer :other_rakuten_fee t.integer :variable_tax t.integer :fixed_tax t.integer :tax_difference t.boolean :destroy_check, default: false, null: false t.timestamps null: false end end end
# frozen_string_literal: true require 'json' module Admin class UsersController < ApplicationController include UsersHelper include Api def new @user = User.new end def index @users = User.all end def show redirect_to edit_admin_user_path end def create @user = User.new(permit_params) if @user.save redirect_to edit_admin_user_path(@user) else render 'new' end end def edit @user = User.find(params[:id]) end def update @user = User.find(params[:id]) if @user.update(permit_params) set_user_session if @user.id == session[:current_user] redirect_to edit_admin_user_path(@user), notice: 'Your details have been successfully updated' else render 'edit' end end def logout reset_user_session if params[:user_id] == session[:current_user].to_s redirect_to admin_login_path end def login if User.authenticate(permit_params[:email], permit_params[:password]) @user = User.find_by_email(permit_params[:email]) set_user_session redirect_to admin_questions_path else redirect_to admin_login_path, notice: 'Invalid Email or password' end end def forgot_password # render 'forgot_password' end def send_reset_password_mail user_email = permit_params[:email] url = URI(Rails.application.secrets.pepipost_url) pp_api_key = Rails.application.secrets.pepipost_api_key mail_body = MAILER_TEMPLATES[:reset_password][:body].merge( personalizations: [{ recipient: user_email }], content: 'Click on the below link to reset your password ' ) config = { 'content-type' => 'application/json', 'api_key' => pp_api_key, 'body' => mail_body.to_json } # render plain: 'Reset password link has been sent to your email' response = ApiService.post(url, config) status_code = response.code.to_i if [200, 202].includes? status_code redirect_to :forgot_password, alert: 'Reset password link has been sent to your email' else flash.now[:alert] = 'FAILED' render 'forgot_password' end end private def permit_params params.require(:user) .permit(:email, :firstname, :lastname, :password, :password_confirmation, :avatar) .select { |_k, v| v.present? } end end end
class SimplifyRewards < ActiveRecord::Migration def change remove_column :rewards, :rewardable_type rename_column :rewards, :rewardable_id, :route_id end end
require_relative 'settings' Rails.application.routes.draw do namespace :api do namespace :v1 do mount_devise_token_auth_for 'User', at: 'auth', skip: [:registrations, :passwords] get :assessment_events, to: 'assessment_events#index' get :assessment_item_events, to: 'assessment_item_events#index' get :grade_events, to: 'grade_events#index' get :media_events, to: 'media_events#index' end end if Settings.active_admin_enabled? devise_for :admin_users, ActiveAdmin::Devise.config ActiveAdmin.routes(self) end # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end
class Standard::OnlineLectureList < ApplicationRecord default_scope { order(order: :asc) } belongs_to :online_lecture, inverse_of: :lists has_many :online_lecture_histories, dependent: :destroy validates :order, uniqueness: { scope: :online_lecture_id } # 최초 association 빌드시에는 적용되지 않는 단점이 있음 def order_to_s self[:order].zero? ? 'OT' : "#{self[:order]}회차" end def time_to_s self[:time].nil? ? '-' : "#{self[:time]}분" end end
# Daffy Duck: Write a method that takes in a string and replaces all the "s" characters with "th". def daffify(string) string.gsub(/[s]/, 'th') end #driver p daffify("This is ridiculous") p daffify("This is ridiculous") == "Thith ith ridiculouth" # Porky Pig: four sounds and then the word with an emphasis on the third sound for all nouns. # "boy" -> "eh beh BEH eh boy" # 1. if first two chr non vowels add --- "eh" (repeat first two letters)(REPEAT TWO lETTERS) "eh" # 2. if vowel is second letter then add --- "eh" (repeat first letter with eh) (REPEAT FIRST LETTER WITH EH) "eh" # loop through string and for each word that is in the dictionary apply appropraite pattern if not in dictionary just puts it def porkify(string, stuttered_words) string_array = string.split(" ") string_array.map! { |word| word if (stuttered_words.include? word); "eh #{word[0..1]} #{word[0..1]} eh #{word}" else word end} puts string_array.join(" ") end #driver dictionary = ["this","place", "tomorrow", "rust"] p porkify("this is a nice place", dictionary) # p porkify("this is a nice place", dictionary) == "eh th TH eh this is a nice eh pl PL eh place." # porkify("this is a nice place", dictionary) -> "eh th TH eh this is a nice eh pl PL eh place."
require 'spec_helper' describe AsanaAPI::Tag do let(:subject) { AsanaAPI::Tag.new } it 'returns 200 for index', vcr: true do expect(subject.index.code).to eq(200) end it 'returns 200 for show', vcr: true do subject.index expect(subject.show(id: subject.parsed.first['id']).code). to eq(200) end end
class CreateEasyUserReadEntities < ActiveRecord::Migration def self.up create_table :easy_user_read_entities do |t| t.column :user_id, :integer, {:null => false} t.column :entity_type, :string, {:limit => 255, :null => false} t.column :entity_id, :integer, {:null => false} t.column :read_on, :datetime, {:null => false} end add_index :easy_user_read_entities, [:user_id, :entity_type, :entity_id], :unique => true, :name => 'idx_easy_read_user_entities_1' end def self.down drop_table :easy_user_read_entities end end
require 'forge.rb' require 'forge/can_be_foreign.rb' require 'forge/can_have_comments.rb' require 'forge/can_use_asset.rb' # This configuration block is for config that should bes pecified # by the site developer. There is a Settings module built into Forge # where you can expose other settings to your client. Forge.configure do |config| # Enable a mobile layout for this website config.mobile_layout = false # Set up languages for front-end internationalization # Currently Forge is anglo-centric so you don't need to # specify English. # # config.languages = { # "French" => :fr, # "German" => :de # # etc. # } # Print out support instructions for your client # in the bottom right-hand corner of Forge # config.support_instructions_in_layout = File.read("support.html") # Print out any additional SEO information you'd like # to display on the SEO tabs of supported modules # config.seo_callout = File.read("seo.html") # If you need to add further config options you can add them # in lib/forge.rb as attr_accessors to Forge::Configuration end
module Api::V1 class LeaveSerializer < ActiveModel::Serializer attributes :id, :date belongs_to :member, serializer: Api::V1::MemberWithoutPointsSerializer belongs_to :last_updated_by, serializer: Api::V1::MemberWithoutPointsSerializer end end
class Product < ActiveRecord::Base # Find all products priced more than 100 and less than 300. Order them by name and limit the results to 10 products. def self.find_price where("price > 100 AND price < 300") end # Find all the users whose neither first_name nor last_name is "john" end
class Report def initialize @title = 'Monthly Report' @content = [ 'Things are going', 'really, really well.'] end def output_report(formatter) if formatter == :plain puts("*** #{@title} ***") elsif formatter == :html puts('<html>') puts(' <head>') puts("<title> #{@title} </title>") puts(' </head>') puts(' </body>') else raise "Unknown format: #{format}" end @content.each do |line| if formatter == :plain puts(line) else puts(" <p>#{line}</p>") end end if formatter == :html puts(' </body>') puts('</html>') end end end r = Report.new r.output_report(:html) # <html> # <head> # <title> Monthly Report </title> # </head> # </body> # <p>Things are going</p> # <p>really, really well.</p> # </body> # </html> r.output_report(:plain) # *** Monthly Report *** # Things are going # really, really well.
module Report module RepairDataPageWritable include DataPageWritable private def date_key :repair_date end def technician_key :repaired_by end end end
require_relative '../../lib/skymorph/parsers/observation_table_parser' describe SkyMorph::ObservationTableParser do subject { SkyMorph::ObservationTableParser } describe '::parse' do let(:result) { subject.parse(Fixtures.observation_table_j99ts7a) } let(:ceres_result) { subject.parse(Fixtures.observation_table_ceres) } it 'returns a hash' do expect(result).to be_kind_of(Array) expect(ceres_result).to be_kind_of(Array) end it 'returns the correct number of rows' do expect(result.count).to eq(65) expect(ceres_result.count).to eq(70) end it 'fetches the key' do expect(result.first[:key]).to eq('|001204124410|51882.530787037|129.062741402712|4.64001695570385|128.337645|4.0726|20.70|-4.28|-11.08|n.a.|n.a.|n.a.|71.9154214757038|547.287989060186|y|') expect(ceres_result.first[:key]).to eq('|960612124155|50246.529224537|244.586842294571|-18.7630733314539|244.964565|-18.55884|7.30|-32.09|-4.65|0.05|0.04|-19.63|2942.15100272039|2568.62273640486|y|') end it 'fetches the observation_id' do expect(result.first[:observation_id]).to eq('001204124410') expect(ceres_result.first[:observation_id]).to eq('960612124155') end it 'fetches the triplet' do expect(result.first[:triplet]).to be(true) expect(ceres_result.first[:triplet]).to be(true) end it 'fetches the time' do expect(result.first[:time]).to eq(DateTime.new(2000, 12, 04, 12, 44, 20)) expect(ceres_result.first[:time]).to eq(DateTime.new(1996, 06, 12, 12, 42, 05)) end it 'fetches the predicted_position' do expect(result.first[:predicted_position]).to eq( right_ascension: SkyMorph::RightAscension.new(8, 36, 15.06), declination: SkyMorph::Declination.new(4, 38, 24.1) ) expect(ceres_result.first[:predicted_position]).to eq( right_ascension: SkyMorph::RightAscension.new(16, 18, 20.84), declination: SkyMorph::Declination.new(-18, 45, 47.1) ) end it 'fetches to observation_center' do expect(result.first[:observation_center]).to eq( right_ascension: SkyMorph::RightAscension.new(8, 33, 21.03), declination: SkyMorph::Declination.new(4, 4, 21.4) ) expect(ceres_result.first[:observation_center]).to eq( right_ascension: SkyMorph::RightAscension.new(16, 19, 51.50), declination: SkyMorph::Declination.new(-18, 33, 31.8) ) end it 'fetches the magnitude' do expect(result.first[:magnitude]).to eq(20.70) expect(ceres_result.first[:magnitude]).to eq(7.30) end it 'fetches velocity' do expect(result.first[:velocity]).to eq( west_east_degrees_per_hour: -4.28, south_north_degrees_per_hour: -11.08 ) expect(ceres_result.first[:velocity]).to eq( west_east_degrees_per_hour: -32.09, south_north_degrees_per_hour: -4.65 ) end it 'fetches offset' do expect(result.first[:offset]).to eq(55.14) expect(ceres_result.first[:offset]).to eq(24.72) end it 'fetches positional_error' do expect(result.first[:positional_error]).to eq( major: nil, minor: nil, position_angle: nil ) expect(ceres_result.first[:positional_error]).to eq( major: 0.05, minor: 0.04, position_angle: -19.63 ) end it 'fetches pixel_location' do expect(result.first[:pixel_location]).to eq( x: 71.92, y: 547.29 ) expect(ceres_result.first[:pixel_location]).to eq( x: 2942.15, y: 2568.62 ) end end end
Meucandidato::Application.configure do # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Do not eager load code on boot. config.eager_load = false # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = true config_dir = File.join Rails.root, 'config' MAIL = YAML.load_file(File.join(config_dir, 'mail.yml'))[Rails.env] config.action_mailer.raise_delivery_errors = true config.action_mailer.delivery_method = :smtp config.action_mailer.smtp_settings = { address: MAIL['address'], port: MAIL['port'], domain: MAIL['domain'], authentication: MAIL['authentication'], enable_starttls_auto: MAIL['enable_starttls_auto'], user_name: MAIL["user_name"], password: MAIL["password"] } config.action_mailer.default_url_options = { :host => "http://localhost:3000" } end
require 'spec_helper' describe Enriched::UrlReplacer do describe '#call' do let(:input) { '' } let(:opts) { {} } let(:result) { Enriched::UrlReplacer.new(input, opts).call } it 'processes multiple urls' do input.replace 'Ein http://te.xt mit mehreren https://urls.drin' expect(Enriched::URL).to receive(:new).twice.and_call_original expect(result).to eq input end it 'ignores unknown urls' do input.replace 'Normal url http://foo.bar' expect(result).to eq input end it 'ignores urls that are part of a tag already' do input.replace '<foo src="https://www.youtube.com/embed/zJORwxt9O6o" />' expect(result).to eq input end end end
# frozen_string_literal: true class Suggestion < ApplicationRecord include PermissionsConcern validates :email, :phone, :question, presence: true validates :email, format: { with: EMAIL_REGEXP } validates :phone, format: { with: /\A(\d{7}|\d{10})\z/ } validates :question, length: { in: 15..140, too_short: I18n.t('activerecord.errors.too_short'), too_long: I18n.t('activerecord.errors.too_long') } end
require 'rspec/core/rake_task' require 'data_mapper' require 'faker' desc "run specs" #run rake spec to run the tests RSpec::Core::RakeTask.new task :environment do DataMapper.setup(:default, ENV['DATABASE_URL'] || "sqlite3://#{Dir.pwd}/dev.db") require_relative 'models/texture' require_relative 'models/building' require_relative 'models/buildingtextures' end namespace :db do desc "This task will only add tables and columns (It will not alter or drop tables or columns)." task(update: :environment) do DataMapper.auto_upgrade! end desc "This task will remove all the data from the database and recreate the database strcuture from the class file definitions." task(drop_and_rebuild: :environment) do DataMapper.auto_migrate! end desc "Adds one record to each of the buildings, textures, and buildings_textures table." task(seed: :update) do 7.times do building = Building.create( address_line_one: Faker::Address.street_address(include_secondary = false), address_line_two: [Faker::Address.secondary_address,""].sample, city: Faker::Address.city, state: Faker::Address.state, country: Faker::Address.country, zipcode: Faker::Address.zip ) (1+rand(5)).times do file_name = (Faker::Lorem.words(num=2)).join("_") building.textures.create(file: "#{file_name}.jpg") end end DataMapper.finalize end end
# credits to https://gist.github.com/keithtom/8763169 # disables CSS3 and jQuery animations in test mode for speed, # consistency, and avoiding timing issues. DISABLE_ANIMATIONS_HTML = <<~HTML.freeze <script type="text/javascript"> (typeof jQuery !== 'undefined') && (jQuery.fx.off = true); </script> <style> * { -o-transition: none !important; -moz-transition: none !important; -ms-transition: none !important; -webkit-transition: none !important; transition: none !important; -webkit-animation: none !important; -moz-animation: none !important; -o-animation: none !important; -ms-animation: none !important; animation: none !important; } </style> HTML module Rack class NoAnimations def initialize(app, _options = {}) @app = app end def call(env) @status, @headers, @body = @app.call(env) return [@status, @headers, @body] unless html? response = Rack::Response.new([], @status, @headers) @body.each { |fragment| response.write inject(fragment) } @body.close if @body.respond_to?(:close) response.finish end private def html? @headers["Content-Type"] =~ /html/ end # add html to the end of the head tag. def inject(fragment) fragment.gsub(%r{</head>}, DISABLE_ANIMATIONS_HTML + "</head>") end end end
class ActorMacro < Actor validates :operational_field, presence: true after_save :rebuild_operational_field, if: 'operational_field_changed?' def operational_field_txt field = OperationalField.find_by_id(operational_field) if operational_field.present? field.name if field.present? end def empty_relations? parents.empty? end private def rebuild_operational_field operational_fields.delete_all query = "INSERT INTO actors_categories(actor_id, category_id) VALUES(#{id}, #{operational_field})" ActiveRecord::Base.connection.insert(query) end end
require 'rails_helper' RSpec.feature "Showing an article" do before do @article = Article.create(title: "The article was created", body: "blablabla") end scenario "A users shows an article" do visit "/" click_link @article.title expect(page).to have_content(@article.title) expect(page).to have_content(@article.body) expect(current_path).to eq(article_path(@article)) end end
module Shipwire class Products::Kit < Products protected def product_classification { classification: "kit" } end end end
class Category < ApplicationRecord validates :name, uniqueness: true before_save :default_value has_one :image, as: :imagable, dependent: :destroy accepts_nested_attributes_for :image, allow_destroy: true has_one :metum, as: :metable, dependent: :destroy accepts_nested_attributes_for :metum, allow_destroy: true has_and_belongs_to_many :articles private def default_value self.permalink.parameterize = name if self.permalink.blank? end end
class EmployeePresenter < StatsPresenter def initialize(model) @model = model end def show methods = %i[department store work_shift role] only = %i[id name surname_1 first_day phone address commune avatar email] json = @model.as_json(methods: methods, only: only) methods.each { |method| json[method.to_s] = json[method.to_s].name } json[:working_today] = @model.working_today? json[:should_work_today] = @model.should_work_today? json[:achievements] = @model.achievements_labor_month_until_today.sum(:total_day) json end end
# frozen_string_literal: true class ContributionsController < ApplicationController before_action :set_contribution, only: %i[show edit update destroy] # GET /contributions def index @pagy, @contributions = pagy(Contribution.all) end # GET /contributions/1 def show; end # GET /contributions/new def new @contribution = Contribution.new @contribution.house_id = params[:house_id] end # GET /contributions/1/edit def edit; end # POST /contributions def create @contribution = Contribution.new(contribution_params) if @contribution.save redirect_to @contribution, notice: 'Contribution was successfully created.' else render :new end end # PATCH/PUT /contributions/1 def update if @contribution.update(contribution_params) redirect_to @contribution, notice: 'Contribution was successfully updated.' else render :edit end end # DELETE /contributions/1 def destroy @contribution.destroy redirect_to contributions_url, notice: 'Contribution was successfully destroyed.' end private def set_contribution @contribution = Contribution.find(params[:id]) end def contribution_params params.require(:contribution).permit(:house_id, :date_paid, :amount) end end
require 'zip/zipfilesystem' require 'fileutils' class ProgramsExportWorker < BackgrounDRb::MetaWorker set_worker_name :programs_export_worker def create(args = nil) # this method is called, when worker is loaded for the first time end def export_program_users(program_id) @program = Sampling::Program.find_by_param(program_id) base_file_name = "sampling_participants-#{UUIDTools::UUID.timestamp_create.to_s}" zip_file_name = "#{base_file_name}.zip" FileUtils.mkdir_p(dir = Rails.root.join('tmp', 'reports')) full_zip_file_path = File.join(dir, zip_file_name) Zip::ZipFile.open(full_zip_file_path, Zip::ZipFile::CREATE) do |zipfile| zipfile.file.open("#{base_file_name}.csv", 'w') do |f| f.puts @program.export_participants_to_csv end end persistent_job.finish! if persistent_job @program.filename = zip_file_name @program.save end end
# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{active-behavior} s.version = "0.2.1" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Lance Pollard"] s.date = %q{2011-07-06} s.description = %q{Put each association into it's own behavior module. This makes testing and organizing your Rails app a lot easier when it gets big.} s.email = %q{lancejpollard@gmail.com} s.files = ["Rakefile", "lib/active-behavior", "lib/active-behavior/loader.rb", "lib/active-behavior/railtie.rb", "lib/active-behavior/record_helper.rb", "lib/active-behavior.rb"] s.homepage = %q{http://github.com/viatropos/active-behavior} s.require_paths = ["lib"] s.rubyforge_project = %q{active-behavior} s.rubygems_version = %q{1.7.2} s.summary = %q{Build your models one module at a time.} if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then else end else end end
require "docking_station" describe DockingStation do describe "docking station" do it "responds to release_bike" do expect(subject).to respond_to :release_bike end it { is_expected.to respond_to(:dock).with(1).argument} #should be done for every method that has arguments it {is_expected.to respond_to(:bikes)} #it responds to attr_reader (a method to initialize bike) end describe "#dock" do it "docks a bike" do bike = Bike.new expect(subject.dock(bike).last).to eq bike #checks if the docked kike is the same as the new instance of bike end it "it raises an error if the dock is full" do subject.capacity.times {subject.dock(Bike.new)} expect{subject.dock(Bike.new)}.to raise_error "The dock is full!" end end describe "#release_bike" do it "releases a bike if there is one available" do bike = Bike.new subject.dock(bike) expect(subject.release_bike).to eq bike end it "raises an error if the dock is empty/no bikes available" do expect{subject.release_bike}.to raise_error "There are no available bikes!" end it "releases working bikes" do subject.dock(Bike.new) expect(subject.release_bike).to be_working end end describe "#capacity" do it "has a default capacity" do expect(subject.capacity).to eq DockingStation::DEFAULT_CAPACITY end end end
class CityTrip < ApplicationRecord belongs_to :trip belongs_to :city validates :trip_id, :city_id, presence: true def self.my_trips(user_id) self.all.select { |ct| ct.trip.user_id == user_id } end def trip_name self.trip.name end def city_name self.city.name end end
require 'spec_helper' describe "Dashboard" do let(:dashboard) { Dashboard.new } context "#total_pending_orders" do context "when there are pending orders" do let!(:status) { Fabricate(:status, :name => StoreEngine::Status::PENDING) } let!(:order) { Fabricate(:order, :status => status) } let!(:order1) { Fabricate(:order, :status => status) } it "returns 2" do dashboard.total_pending_orders.should == 2 end end context "when there are no pending orders" do it "returns 0" do dashboard.total_pending_orders.should == 0 end end end context "#total_cancelled_orders" do context "when there are orders" do let!(:status) { Fabricate(:status, :name => StoreEngine::Status::CANCELLED) } let!(:order) { Fabricate(:order, :status => status) } let!(:order1) { Fabricate(:order, :status => status) } it "returns 2" do dashboard.total_cancelled_orders.should == 2 end end context "when there are no orders" do it "returns 0" do dashboard.total_cancelled_orders.should == 0 end end end context "#total_paid_orders" do context "when there are orders" do let!(:status) { Fabricate(:status, :name => StoreEngine::Status::PAID) } let!(:order) { Fabricate(:order, :status => status) } let!(:order1) { Fabricate(:order, :status => status) } it "returns 2" do dashboard.total_paid_orders.should == 2 end end context "when there are no orders" do it "returns 0" do dashboard.total_paid_orders.should == 0 end end end context "#total_shipped_orders" do context "when there are orders" do let!(:status) { Fabricate(:status, :name => StoreEngine::Status::SHIPPED) } let!(:order) { Fabricate(:order, :status => status) } let!(:order1) { Fabricate(:order, :status => status) } it "returns 2" do dashboard.total_shipped_orders.should == 2 end end context "when there are no orders" do it "returns 0" do dashboard.total_shipped_orders.should == 0 end end end context "#total_returned_orders" do context "when there are orders" do let!(:status) { Fabricate(:status, :name => StoreEngine::Status::RETURNED) } let!(:order) { Fabricate(:order, :status => status) } let!(:order1) { Fabricate(:order, :status => status) } it "returns 2" do dashboard.total_returned_orders.should == 2 end end context "when there are no orders" do it "returns 0" do dashboard.total_returned_orders.should == 0 end end end end
class RecordLabel < ActiveRecord::Base has_and_belongs_to_many :artists has_one :address end
class AdjustOrderItemFields < ActiveRecord::Migration def change rename_column :order_items, :price, :unit_price rename_column :shipment_items, :price, :unit_price end end
module ResourceRenderer module ViewHelper class RenderCollection attr_accessor :helper, :collection, :renderer, :renderer_class def initialize(collection, resource_class, helper, options = {}) options.reverse_merge!({ :as => :text }) renderer_name = options.delete(:as) self.renderer_class = get_renderer_class(renderer_name) self.collection = collection self.helper = helper self.renderer = renderer_class.new(collection, resource_class, helper, options) self end def render_collection(&block) renderer.render(&block) end private def get_renderer_class(renderer_name) renderer_class_name = "#{renderer_name.to_s.camelize}CollectionRenderer" renderer = Object.const_get(renderer_class_name) raise DisplayBlockNotDefinedException, "#{renderer.to_s} not defined" unless renderer.is_a?(Class) renderer end end class RenderResource attr_accessor :helper, :resource, :renderer, :renderer_class def initialize(resource, helper, options = {}) options.reverse_merge!({ :as => :text }) renderer_name = options.delete(:as) self.renderer_class = get_renderer_class(renderer_name) self.resource = resource self.helper = helper self.renderer = renderer_class.new(resource, helper) self end def render(&block) renderer.render(&block) end private def get_renderer_class(renderer_name) renderer_class_name = "#{renderer_name.to_s.camelize}ResourceRenderer" renderer = Object.const_get(renderer_class_name) raise DisplayBlockNotDefinedException, "#{renderer.to_s} not defined" unless renderer.is_a?(Class) renderer end end def render_resource(resource, options = {}, &block) RenderResource.new(resource, self, options).render(&block) end def render_collection(collection, resource_class, options = {}, &block) RenderCollection.new(collection, resource_class, self, options).render_collection(&block) end end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) require 'csv' require 'faker' # Create Enclosures quarantines = 1..6 quarantines.each do |q| Enclosure.create(:name => "Quarantine #{q}") end kennels = 1..14 kennels.each do |q| Enclosure.create(:name => "Kennel #{q}") end cats = 1..10 cats.each do |q| Enclosure.create(:name => "Cat Room #{q}") end CSV.foreach(Rails.root.join('lib/Austin_Animal_Center_Outcomes.csv'), headers: true) do |row| name = row[0] birthday = row[1].insert(-3, '20') birthday = Date.strptime(birthday, '%m/%d/%Y') if (name.blank? || name.nil? || name.include?("0") || name.include?("1") || name.include?("2") || name.include?("3") || name.include?("4") || name.include?("5") || name.include?("6") || name.include?("7") || name.include?("8") || name.include?("9")) if (row[4].downcase == 'cat') name = Faker::Creature::Cat.name elsif (row[4].downcase == 'dog') name = Faker::Creature::Dog.name elsif (row[5].downcase.include? "female") name = Faker::Name.female_first_name else name = Faker::Name.male_first_name end end intake_date = Faker::Date.between(from: birthday, to: 10.days.ago) outcome_date = Faker::Date.between(from: intake_date, to: 1.day.ago) Animal.create( :name => name, :birthday => birthday, :outcometype => row[2], :outcomesubtype => row[3], :animaltype => row[4], :sex => row[5], :breed => row[6], :color => row[7], :intake_date => intake_date, :outcome_date => outcome_date ) end
require 'test_helper' require 'unit/rpx/test_helper' class RPX::UserTest < ActiveSupport::TestCase include RPX::TestHelper test "should instantiate" do assert_instance_of RPX::User, user_from(:facebook) assert_instance_of RPX::User, user_from(:twitter) end test "should have a profile" do assert_instance_of RPX::Profile, user_from(:facebook).profile end test "should have an identifier" do assert_instance_of RPX::Mapping, user_from(:facebook).identifier end test "should have access credentials" do assert_instance_of RPX::AccessCredentials, user_from(:facebook).access_credentials end end
require "pry" class Author attr_accessor :name, :title, :author attr_reader :posts # @@post_count = 0 @@authors = [] def self.all @@authors end def self.total_authors @@authors.size end def self.post_count self.all.collect {|a|a.posts}.flatten.count end def initialize(name) @@authors << self @name = name @posts = [] end def add_post(post) @posts << post post.author = self end def add_post_by_title(post_title) #binding.pry post = Post.new(post_title) post.author = self post.author_name = self end def posts Post.all.select {|a| a.author == self } end def post_count @@post_count = post_count end end
# Master Event Table Structure require 'dm-core' class Event include DataMapper::Resource property :eid, Serial property :event_name, String, :required => true property :event_day, Integer, :required => true property :event_day_name, String, :required => true property :event_range, Integer, :required => true property :event_time, String, :required => true property :type, Integer, :required => true property :location, Integer, :required => true property :need, Integer, :required => true property :have, Integer property :notes, Text end
require 'open-uri' class Feed < ActiveRecord::Base has_many :entries, :dependent => :destroy has_many :user_feeds has_many :users, through: :user_feeds, source: :user has_many :favorites, as: :favorable def self.find_or_create_by_url(url) feed = Feed.find_by_url(url) return feed if feed begin feed_data = SimpleRSS.parse(open(url)) feed = Feed.create!(title: feed_data.title, url: url) feed_data.entries.each do |entry_data| Entry.create_from_json!(entry_data, feed) end rescue SimpleRSSError return nil end feed end def reload # reloads entries self.touch #this causes the updated_at column to be updated begin feed_data = SimpleRSS.parse(open(url)) existing_entry_guids = Entry.pluck(:guid).sort feed_data.entries.each do |entry_data| unless existing_entry_guids.include?(entry_data.guid) Entry.create_from_json!(entry_data, self) end end self rescue SimpleRSSError return false end end def latest_entries if self.updated_at < 30.seconds.ago self.reload end self.entries end def fav_entries(user) entry_favs = Favorite.all.where(user_id: user.id, favorable_type: "Entry") feed_entry_favs = entry_favs.select do |fav| self.entries.pluck(:id).include?(fav.favorable_id) end feed_entry_favs end end
# @param {Integer[][]} accounts # @return {Integer} def maximum_wealth(accounts) max_wealth = 0 for account in accounts cur_wealth = account.sum max_wealth = cur_wealth if cur_wealth > max_wealth end max_wealth end acc = [[2,8,7],[7,1,3],[1,9,5]] p maximum_wealth acc
#!/usr/bin/env ruby require_relative 'pub/compile' require_relative 'pub/init' module DBP module BookCompiler module Pub class << self NAME = Pathname($0).basename COMMANDS = [Compile.new(NAME), Init.new(NAME)] def run command_name = (ARGV.shift || '') COMMANDS.find(-> { abort help }) { |c| c.name == command_name }.run end def help (['Usage:'] + COMMANDS.map { |command| " #{command.banner}" }).join($/) end end end end end
require 'spec_helper' RSpec.describe SolidusBraintree::TransactionsController, type: :controller do routes { SolidusBraintree::Engine.routes } let!(:country) { create :country } let(:line_item) { create :line_item, price: 50 } let(:order) do Spree::Order.create!( line_items: [line_item], email: 'test@example.com', bill_address: create(:address, country: country), ship_address: create(:address, country: country), user: create(:user) ) end let(:payment_method) { create_gateway } before do allow(controller).to receive(:spree_current_user) { order.user } allow(controller).to receive(:current_order) { order } create :shipping_method, cost: 5 create :state, abbr: "WA", country: country end cassette_options = { cassette_name: "transactions_controller/create", match_requests_on: [:braintree_uri] } describe "POST create", vcr: cassette_options do subject(:post_create) { post :create, params: params } let!(:country) { create :country, iso: 'US' } let(:params) do { transaction: { nonce: "fake-valid-nonce", payment_type: SolidusBraintree::Source::PAYPAL, phone: "1112223333", email: "batman@example.com", address_attributes: { name: "Wade Wilson", address_line_1: "123 Fake Street", city: "Seattle", zip: "98101", state_code: "WA", country_code: "US" } }, payment_method_id: payment_method.id } end before do create :state, abbr: "WA", country: country end context "when import has invalid address" do before { params[:transaction][:address_attributes][:city] = nil } it "raises a validation error" do expect { post_create }.to raise_error( SolidusBraintree::TransactionsController::InvalidImportError, "Import invalid: " \ "Address is invalid, " \ "Address City can't be blank" ) end end context "when the transaction is valid", vcr: { cassette_name: 'transaction/import/valid', match_requests_on: [:braintree_uri] } do it "imports the payment" do expect { post_create }.to change { order.payments.count }.by(1) expect(order.payments.first.amount).to eq 55 end context "when no end state is provided" do it "advances the order to confirm" do post_create expect(order).to be_confirm end end context "when end state provided is delivery" do let(:params) { super().merge(state: 'delivery') } it "advances the order to delivery" do post_create expect(order).to be_delivery end end context "with provided address" do it "creates a new address" do # Creating the order also creates 3 addresses, we want to make sure # the transaction import only creates 1 new one order expect { post_create }.to change(Spree::Address, :count).by(1) expect(Spree::Address.last.address1).to eq "123 Fake Street" end end context "without country ISO" do before do params[:transaction][:address_attributes][:country_code] = "" params[:transaction][:address_attributes][:country_name] = "United States" end it "creates a new address, looking up the ISO by country name" do order expect { post_create }.to change(Spree::Address, :count).by(1) expect(Spree::Address.last.country.iso).to eq "US" end end context "without transaction address" do before { params[:transaction].delete(:address_attributes) } it "does not create a new address" do order expect { post_create }.not_to(change(Spree::Address, :count)) end end context "when format is HTML" do context "when import! leaves the order in confirm" do it "redirects the user to the confirm page" do expect(post_create).to redirect_to spree.checkout_state_path("confirm") end end context "when import! completes the order" do before { allow(order).to receive(:complete?).and_return(true) } it "displays the order to the user" do expect(post_create).to redirect_to spree.order_path(order) end end end context "when format is JSON" do before { params[:format] = :json } it "has a successful response" do post_create expect(response).to be_successful end end end context "when the transaction is invalid" do before { params[:transaction][:email] = nil } context "when format is HTML" do it "raises an error including the validation messages" do expect { post_create }.to raise_error( SolidusBraintree::TransactionsController::InvalidImportError, "Import invalid: Email can't be blank" ) end end context "when format is JSON" do before { params[:format] = :json } it "has a failed status" do post_create expect(response).to have_http_status :unprocessable_entity end it "returns the errors as JSON" do post_create expect(JSON.parse(response.body)["errors"]["email"]).to eq ["can't be blank"] end end end end end
# frozen_string_literal: true require 'time' module ExpertsHelper def set_address(address) address.split(' ').join('+') end def selector_element(arr) arr.each_with_index.map { |x, i| [x.name, i + 1] } end def set_time (0..23).map { |x| %W[#{x}:00 #{x}:00] } end end
class User attr_reader :login, :c def initialize xml @xml = xml parse end def parse @login = @xml.xpath("login").text @c = @xml.xpath("c").text end end
class RemoveImageColumnFromDesigns < ActiveRecord::Migration def change remove_column :designs, :image_url end end
class User < ApplicationRecord has_secure_password validates :email, presence: true, uniqueness: true has_many :prescriptions has_many :medications, :through => :prescriptions end
class User < ActiveRecord::Base has_many :careers, through: :career_skill has_many :skills, through: :career, as: :assigned_skills has_secure_password end
# Methods defined in the helpers block are available in templates module SeoHelper def page_title current_page.data.title || data.site.title end def page_description current_page.data.description || data.site.description end def current_page_url "#{data.site.url}#{current_page.url}" end def page_url page "#{data.site.url}#{page.url}" end def page_twitter_card_type current_page.data.twitter_card_type || 'summary' end def page_image current_page.data.image_path || data.site.logo_image_path end # Social share URLs def twitter_url "https://twitter.com/share?text=“#{page_title}”" + "&url=#{current_page_url}" + "&via=#{data.site.twitter_handle}" end def facebook_url "https://www.facebook.com/dialog/feed?app_id=#{data.site.facebook_app_id}" + "&caption=#{page_title}" + "&picture=#{page_image}" + "&name=“#{page_title}”" + "&description=#{page_description}" + "&display=popup" + "&link=#{current_page_url}" + "&redirect_uri=#{current_page_url}" end end
# frozen_string_literal: true RSpec.describe Chef, type: :model do describe 'associations' do it { should have_many(:recipes) } end describe 'presence validations' do it { should validate_presence_of(:name) } it { should validate_presence_of(:contentful_id) } end describe 'uniqueness validations' do subject { FactoryBot.create(:chef) } it { should validate_uniqueness_of(:contentful_id) } end end
module SQLite3 module API extend FFI::Library lib_paths = Array(ENV["SQLITE3_LIB"] || Dir["/{opt,usr}/{,local/}lib{,64}/libsqlite3.{dylib,so*}"]) fallback_names = ["libsqlite3", "sqlite3"] ffi_lib(lib_paths + fallback_names) attach_function :sqlite3_bind_blob, [:pointer, :int, :pointer, :int, :pointer], :int attach_function :sqlite3_bind_double, [:pointer, :int, :double], :int attach_function :sqlite3_bind_int, [:pointer, :int, :int], :int attach_function :sqlite3_bind_int64, [:pointer, :int, :int64], :int attach_function :sqlite3_bind_null, [:pointer, :int], :int attach_function :sqlite3_bind_parameter_index, [:pointer, :string], :int attach_function :sqlite3_bind_text, [:pointer, :int, :string, :int, :pointer], :int attach_function :sqlite3_bind_text16, [:pointer, :int, :pointer, :int, :pointer], :int attach_function :sqlite3_busy_timeout, [:pointer, :int], :int attach_function :sqlite3_changes, [:pointer], :int attach_function :sqlite3_close, [:pointer], :int attach_function :sqlite3_column_blob, [:pointer, :int], :pointer attach_function :sqlite3_column_bytes, [:pointer, :int], :int attach_function :sqlite3_column_bytes16, [:pointer, :int], :int attach_function :sqlite3_column_count, [:pointer], :int attach_function :sqlite3_column_decltype, [:pointer, :int], :string attach_function :sqlite3_column_double, [:pointer, :int], :double attach_function :sqlite3_column_int64, [:pointer, :int], :int64 attach_function :sqlite3_column_name, [:pointer, :int], :string attach_function :sqlite3_column_text, [:pointer, :int], :string attach_function :sqlite3_column_text16, [:pointer, :int], :pointer attach_function :sqlite3_column_type, [:pointer, :int], :int attach_function :sqlite3_data_count, [:pointer], :int attach_function :sqlite3_errcode, [:pointer], :int attach_function :sqlite3_errmsg, [:pointer], :string attach_function :sqlite3_errmsg16, [:pointer], :pointer attach_function :sqlite3_finalize, [:pointer], :int attach_function :sqlite3_last_insert_rowid, [:pointer], :int64 attach_function :sqlite3_libversion, [], :string attach_function :sqlite3_open, [:string, :pointer], :int attach_function :sqlite3_open16, [:pointer, :pointer], :int attach_function :sqlite3_prepare, [:pointer, :string, :int, :pointer, :pointer], :int attach_function :sqlite3_reset, [:pointer], :int attach_function :sqlite3_step, [:pointer], :int begin attach_function :sqlite3_enable_load_extension, [:pointer, :int], :int attach_function :sqlite3_load_extension, [:pointer, :string, :string, :string], :int EXTENSION_SUPPORT = true rescue FFI::NotFoundError EXTENSION_SUPPORT = false end end end
class StringCalculator def add number_str num_arr = number_str.gsub("\n", ",").split(",") num_arr.reduce(0) {|sum, num| sum + (num.to_i || 0)} end end RSpec.describe 'String Calculator' do before :each do @calculator = StringCalculator.new end it 'returns 0 for empty string' do input = "" expect(@calculator.add(input)).to eq(0) end it 'returns 2 for that number' do input = "2" expect(@calculator.add(input)).to eq(2) end it 'returns 10 for the sum of 1,2,2,1,3,1' do input = "1,2,2,1,3,1" expect(@calculator.add(input)).to eq(10) end it 'returns 10 for the sum of 1\n2\n2\n1\n3\n1' do input = "1\n2\n2\n1\n3\n1" expect(@calculator.add(input)).to eq(10) end end
class AddUserToPhones < ActiveRecord::Migration[5.1] def change add_reference :phones, :user, index: true, null: false, foreign_key: {on_delete: :restrict, on_update: :restrict} end end
# == Schema Information # # Table name: action_events # # id :integer not null, primary key # event_name :text # notes :text # streak_length :integer # timestamp :datetime # created_at :datetime not null # updated_at :datetime not null # user_id :integer # class ActionEvent < ApplicationRecord belongs_to :user validates :event_name, presence: true before_save { self.timestamp ||= Time.current } search_terms( :notes, name: :event_name, ) def timestamp=(str_stamp) return if str_stamp.blank? super(str_stamp.in_time_zone("Mountain Time (US & Canada)")) end def self.serialize all.as_json(only: [:event_name, :notes, :timestamp]) end def serialize as_json(only: [:event_name, :notes, :timestamp]) end end
class TaskWithTaskListController < ApplicationController def create task_list = TaskList.find_by!(find_task_list) task = Task.find_by(find_task_params) || Task.create!(create_params) # binding.pry task_in_list = TaskInList.create!(task: task, task_list: task_list) render_created(TaskInListSerializer.new(task_in_list)) end private def find_task_params params.require(:name) params.permit(:name).merge(user_id: current_user.id) end def find_task_list { id: params[:task_list_id], user_id: current_user.id } end def create_params params.require(%i[name]) params.permit(%i[name description]) .merge(user_id: current_user.id) end end
class Game < ActiveRecord::Base belongs_to :sport belongs_to :winner, :class_name => "Player" belongs_to :loser, :class_name => "Player" has_many :ranks, :dependent => :destroy validates_presence_of :sport, message: "When you play nothing, there is no winner or loser" validates_presence_of :winner, message: "Even life has a winner" validates_presence_of :loser, message: "Without losers, there can be no winners" before_destroy :players_last_game def self.order_played order('created_at asc') end def self.most_recent order('created_at desc') end def to_s "#{winner.name} beat #{loser.name} at #{sport.name}" end def self.games_played(player) self.for_player(player).length end def self.for_player(player) where("winner_id = :player OR loser_id = :player", {:player => player}) end def update_player_rank eloWinner = Elo::Player.new(:rating => self.winner.rank_for_sport(sport), :games_played => winner.games_played) eloLoser = Elo::Player.new(:rating => self.loser.rank_for_sport(sport), :games_played => loser.games_played) game = eloWinner.wins_from(eloLoser) winner.update_rank(sport, eloWinner.rating, self) loser.update_rank(sport, eloLoser.rating, self) end def update_player_boss winner.update_boss loser.update_boss end def players_last_game winner.games.first == self && loser.games.first == self end after_save :update_player_rank after_save :update_player_boss after_create :update_twitter def update_twitter Twitter.update(to_twitter) rescue Twitter::Error::Forbidden end def to_twitter "#{winner.to_twitter} beat #{loser.to_twitter} at #{sport.to_twitter}" end def self.by_player_week_day if ActiveRecord::Base.connection.adapter_name == "SQLite" dow = "strftime('%w', created_at)" else dow = "extract(dow from created_at)" end select("player_id, count(player_id) as cnt, #{dow}").from("(select distinct winner_id as player_id, id, created_at from games union select distinct loser_id as player_id, id, created_at from games) agg").group("player_id, #{dow} ").order("#{dow}") #select("winner_id, loser_id, strftime('%w', created_at) as day, count(*) as cnt").group("winner_id, loser_id, strftime('%w', created_at)") end end
require "rails_helper" RSpec.feature "Downloads" do before do allow(DownloadFileJob).to receive(:perform_later) end scenario "Creating a download" do visit "/" fill_in "File Number", with: "1234" click_button "Download" @download = Download.last expect(@download).to_not be_nil expect(page).to have_content 'Downloading File #1234' expect(page).to have_content "We are gathering the list of files in the eFolder now" expect(page).to have_content "Progress: 20%" expect(page).to have_current_path(download_path(@download)) expect(DownloadFileJob).to have_received(:perform_later) end scenario "Download with no documents" do @download = Download.create(status: :no_documents) visit download_url(@download) expect(page).to have_css ".usa-alert-error", text: "no documents" click_on "Try Again" expect(page).to have_current_path(root_path) end scenario "Unfinished download with documents" do @download = Download.create(status: :pending_documents) @download.documents.create(filename: "yawn.pdf", download_status: :pending) @download.documents.create(filename: "poo.pdf", download_status: :failed) @download.documents.create(filename: "smiley.pdf", download_status: :success) visit download_url(@download) expect(page).to have_css ".document-success", text: "smiley.pdf" expect(page).to have_css ".document-pending", text: "yawn.pdf" expect(page).to have_css ".document-failed", text: "poo.pdf" end scenario "Completed with at least one failed document download" do @download = Download.create(file_number: "12", status: :complete) @download.documents.create(filename: "roll.pdf", download_status: :failed) @download.documents.create(filename: "tide.pdf", download_status: :success) visit download_url(@download) expect(page).to have_content "Some documents failed to download" click_on "Try Again" expect(page).to have_current_path(root_path) end scenario "Completed download" do # clean files FileUtils.rm_rf(Rails.application.config.download_filepath) @download = Download.create(file_number: "12", status: :complete) @download.documents.create(filename: "roll.pdf") @download.documents.create(filename: "tide.pdf") class FakeVBMSService def self.fetch_document_file(_document) "this is some document, woah!" end end download_documents = DownloadDocuments.new(download: @download, vbms_service: FakeVBMSService) download_documents.perform visit download_url(@download) expect(page).to have_css ".document-success", text: "roll.pdf" expect(page).to have_css ".document-success", text: "tide.pdf" click_on "Download .zip" expect(page.response_headers["Content-Type"]).to eq("application/zip") end end
module Kuhsaft class AccordionItemBrick < ColumnBrick validates :caption, presence: true def user_can_delete? true end def to_style_class [super, 'accordion-group'].join(' ') end def user_can_save? true end def collect_fulltext [super, caption].join(' ') end end end
RSpec.shared_context 'collection resource' do let(:resource) do Yaks::CollectionResource.new( links: links, members: members, rels: ['http://api.example.com/rels/plants'] ) end let(:links) { [] } let(:members) { [] } end RSpec.shared_context 'yaks context' do let(:policy) { Yaks::DefaultPolicy.new } let(:rack_env) { {} } let(:mapper_stack) { [] } let(:yaks_context) { {policy: policy, env: rack_env, mapper_stack: mapper_stack} } end RSpec.shared_context 'plant collection resource' do include_context 'collection resource' let(:links) { [ plants_self_link, plants_profile_link ] } let(:members) { [ plain_grass, oak, passiflora ] } [ [ :plant, :profile, 'http://api.example.com/doc/plant' ], [ :plants, :profile, 'http://api.example.com/doc/plant_collection' ], [ :plants, :self, 'http://api.example.com/plants' ], [ :plain_grass, :self, 'http://api.example.com/plants/7/plain_grass' ], [ :oak, :self, 'http://api.example.com/plants/15/oak' ], [ :passiflora, :self, 'http://api.example.com/plants/33/passiflora' ] ].each do |name, type, uri| let(:"#{name}_#{type}_link") { Yaks::Resource::Link.new(rel: type, uri: uri) } end let(:plain_grass) do Yaks::Resource.new( attributes: {name: "Plain grass", type: "grass"}, links: [plain_grass_self_link, plant_profile_link] ) end let(:oak) do Yaks::Resource.new( attributes: {name: "Oak", type: "tree"}, links: [oak_self_link, plant_profile_link] ) end let(:passiflora) do Yaks::Resource.new( attributes: {name: "Passiflora", type: "flower"}, links: [passiflora_self_link, plant_profile_link] ) end end
class OldTextFile < ActiveRecord::Base attr_accessor :remove_image1, :remove_image2, :remove_file1 has_friendly_id :page_title, :use_slug => true acts_as_taggable acts_as_commentable # Associations belongs_to :category belongs_to :subcategory Paperclip.interpolates :normalized_image1_file_name do |attachment, style| attachment.instance.normalized_image1_file_name end Paperclip.interpolates :normalized_image2_file_name do |attachment, style| attachment.instance.normalized_image2_file_name end Paperclip.interpolates :normalized_file1_file_name do |attachment, style| attachment.instance.normalized_file1_file_name end # Paperclip has_attached_file :image1, :styles => {:preview => '50x50!', :small => '100x108!', :medium => '120x120!', :med_large => '145x105!', :large => '308x200!'}, :url => "/system/:class/:attachment/:id/:style/:normalized_image1_file_name", :default_url => "/missing/:class/:attachment/:style/missing.png", :path => ":rails_root/public/system/:class/:attachment/:id/:style/:normalized_image1_file_name" has_attached_file :image2, :styles => {:preview => '50x50!', :small => '100x108!', :medium => '120x120!', :med_large => '145x105!', :large => '308x200!'}, :url => "/system/:class/:attachment/:id/:style/:normalized_image2_file_name", :default_url => "/missing/:class/:attachment/:style/missing.png", :path => ":rails_root/public/system/:class/:attachment/:id/:style/:normalized_image2_file_name" has_attached_file :file1, :url => "/system/:class/:attachment/:id/:normalized_file1_file_name" , :path => ":rails_root/public/system/:class/:attachment/:id/:style/:normalized_file1_file_name" # Validations #validates_attachment_content_type :image1, :content_type => ['image/jpeg', 'image/png', 'image/pjpeg', 'image/x-png'] # Instance Methods def remove_image1=(value) self.image1 = nil if value == '1' end def remove_image2=(value) self.image2 = nil if value == '1' end def remove_file1=(value) self.file1 = nil if value == '1' end def normalized_image1_file_name return transliterate(self.image1_file_name) end def normalized_image2_file_name return transliterate(self.image2_file_name) end def normalized_file1_file_name return transliterate(self.file1_file_name) end def transliterate(str) # Based on permalink_fu by Rick Olsen # Escape str by transliterating to UTF-8 with Iconv s = Iconv.iconv('ascii//ignore//translit', 'utf-8', str).to_s # Downcase string s.downcase! # Remove apostrophes so isn't changes to isnt s.gsub!(/'/, '') # Replace any non-letter or non-number character with a space s.gsub!(/[^A-Za-z0-9_\.]+/, ' ') s.strip! # Replace groups of spaces with single hyphen s.gsub!(/\ +/, '-') return s end end