text
stringlengths
10
2.61M
# Validates Short URL Slugs class SlugValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) return if validate_slug(value) record.errors.add(attribute, (options[:message] || :slug_format)) end private def validate_slug(value) if UrlGrey::Application.config.reserved_slugs.include? value return false elsif value.match(/^([a-z0-9]+([-_]?+[a-z0-9]+)?)*$/i) # ensure all slugs include only a-z, 0-9, and - or _ return true else return false end rescue StandardError false end end
require 'systemu' require 'active_support' require 'log4r' class StorageNode VOL_NAME = STORAGE_CONFIG[:volume_name] def self.free_space free_space_str = `zfs list #{VOL_NAME}`.split("\n").last.split(" ")[2] free_space = free_space_str.gsub(',', '.').to_f if free_space_str =~ /T/ free_space = free_space * 1024 end free_space end def self.used_space used_space_str = `zfs list #{VOL_NAME}`.split("\n").last.split(" ")[1] used_space = used_space_str.gsub(',', '.').to_f if used_space_str =~ /T/ used_space = used_space * 1024 end used_space end def self.list_volumes() cmd = "zfs list | grep #{VOL_NAME}/xen" Log4r::Logger['os'].debug(cmd) _, res, err = systemu(cmd) Log4r::Logger['os'].debug(res) Log4r::Logger['os'].debug(err) lines = res.split("\n") lines.map {|line| line.split(' ').first.gsub("#{VOL_NAME}/", '') } end def self.list_disks() volumes = self.list_volumes() res = [] volumes.each do |v| if v =~ /xen\-\d/ res << v.gsub('xen-', '').to_i end end res end def self.volume_size(disk_number) 0 end def self.volume_exists?(disk_number) all = list_volumes() all.include?(zfs_disk_name(disk_number)) end def self.create_volume(disk_number, size) disk_name = "%03d" % disk_number cmd = "zfs create -V #{size}G #{VOL_NAME}/xen-#{disk_name}" Log4r::Logger['os'].debug(cmd) _, res, err = systemu(cmd) Log4r::Logger['os'].debug(res) Log4r::Logger['os'].debug(err) err.blank? end def self.delete_volume(disk_number) disk_name = "%03d" % disk_number cmd = "zfs destroy #{VOL_NAME}/xen-#{disk_name}" Log4r::Logger['os'].debug(cmd) _, res, err = systemu(cmd) Log4r::Logger['os'].debug(res) Log4r::Logger['os'].debug(err) err.blank? end def self.list_backups(disk_number) result = [] volumes = list_volumes() volumes.each do |volume| result << "%s-%s" % [$1, $2] if volume =~ /vd#{disk_number}-(\d{8})-(\d{2})/ end result end def self.backup_details(disk_number, name) _, res = systemu "lvs|grep vd#{disk_number}-#{name}" data = res.split("\n").first.split(" ") { :volume => data[0], :size => data[3].to_i, :allocated => data[5].to_f } end def self.create_backup(disk_number, size = 1) date = Date.today.strftime("%Y%m%d") backup_number = (list_backups(disk_number).map {|b| b =~ /(#{date})-(\d{2})/ $2.to_i }.max || 0) + 1 volume_name = "vd%s-%s-%.2d" % [disk_number, date, backup_number] _, res, err = systemu "lvcreate -s -L#{size}g -n #{volume_name} mnekovg/vd#{disk_number}" err.blank? end def self.grow_backup(disk_number, name, size) grow_volume("vd%s-%s" % [disk_number, name], size) end def self.is_exported?(disk_number) disk_name = "%03d" % disk_number cmd = "ps auxw | grep xen-#{disk_name}" Log4r::Logger['os'].debug(cmd) _, out, err = systemu(cmd) Log4r::Logger['os'].debug(out) Log4r::Logger['os'].debug(err) out.split("\n").any? {|l| l =~ /vblade/ } end def self.add_export(disk_number, slot) disk_name = "%03d" % disk_number cmd = "/usr/local/sbin/vblade #{disk_number} #{slot} em1 /dev/zvol/#{VOL_NAME}/xen-#{disk_name}" if !is_exported?(disk_number) cmd = "/usr/local/sbin/vblade #{disk_number} #{slot} em1 /dev/zvol/#{VOL_NAME}/xen-#{disk_name} &" Log4r::Logger['os'].debug(cmd) _, res, err = systemu(cmd) Log4r::Logger['os'].debug(res) Log4r::Logger['os'].debug(err) return err.blank? end false end def self.remove_export(disk_number) disk_name = "%03d" % disk_number cmd = "ps auxw | grep xen-#{disk_name}" Log4r::Logger['os'].debug(cmd) #out = `ps auxxw | grep xen-#{disk_name}` _, out, err = systemu(cmd) Log4r::Logger['os'].debug(out) Log4r::Logger['os'].debug(err) out.split("\n").each do |l| if l =~ /vblade/ pid = l.split(" ").second puts "pid: #{pid}" `kill #{pid}` return true end end false end private def self.zfs_disk_name(disk_number) "xen-%03d" % disk_number end def self.grow_volume(volume, size) _, res, err = systemu "lvresize -L#{size}g mnekovg/#{volume}" err.blank? end end
# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) require "alchemist/version" Gem::Specification.new do |s| s.name = "alchemist" s.version = Alchemist::VERSION s.authors = ["Matthew Mongeau"] s.email = ["matt@toastyapps.com"] s.homepage = "https://github.com/halogenandtoast/alchemist" s.summary = %q{Conversions... like you\'ve never seen them before!} s.description = %q{Conversions... like you\'ve never seen them before!!} s.rubyforge_project = "alchemist" s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.require_paths = ["lib"] s.add_development_dependency "rspec", "~> 2.6" # specify any dependencies here; for example: # s.add_development_dependency "rspec" # s.add_runtime_dependency "rest-client" end
class Song #get instance variables attr_reader :name, :artist, :genre #set all class methods @@count = 0 @@artists = [] @@genres = [] @@genre_count @@artist_count #initialize instance method def initialize (name, artist, genre) @name = name @artist = artist @genre = genre @@count += 1 @@artists << artist @@genres << genre end #get class methods def self.count @@count end def self.artists @@artists.uniq end def self.genres @@genres.uniq end #check if hash has property and set value def self.check_hash (hash, prop) if hash.include?(prop) hash[prop] += 1 else hash[prop] = 1 end end #create genre hash of property and value def self.genre_count all_genres = {} @@genres.each do |genre| check_hash(all_genres, genre) end all_genres end #create artist hash of property and value def self.artist_count all_artists = {} @@artists.each do |artist| check_hash(all_artists, artist) end all_artists end end
module Microprocess module Protocol macro_def :data do |options| i = options.fetch(:i, :chunk) o = options.fetch(:o, :data) data_buffer = "" on i do |chunk| if chunk.nil? emit(o, data_buffer) emit(o, nil) else data_buffer << chunk end end o end end end
# Largest prime factor # Problem 3 # The prime factors of 13195 are 5, 7, 13 and 29. # What is the largest prime factor of the number 600851475143 ? class Fixnum def largest_prime_factor return self if prime? prime_factorization.max end def prime_factorization return self if prime? primes = [] curr_num = self curr_prime = 2 while !(curr_num.prime?) do if curr_num % curr_prime == 0 primes << curr_prime curr_num /= curr_prime else curr_prime = curr_prime.next_prime end end primes << curr_num primes end def prime? return false if self < 2 i = 2 while i <= (self / 2) do return false if self % i == 0 i += 1 end true end def next_prime i = self + 1 while !(i.prime?) do i += 1 end i end end
class CreateEasyRakeTaskInfoDetails < ActiveRecord::Migration def self.up create_table :easy_rake_task_info_details, :force => true do |t| t.column :easy_rake_task_info_id, :integer, {:null => false} t.column :type, :string, {:null => false} t.column :status, :integer, {:null => false, :default => 0} t.column :detail, :text, {:null => true} t.column :entity_type, :string, {:null => true} t.column :entity_id, :integer, {:null => true} end end def self.down drop_table :easy_rake_task_info_details end end
class Job < ActiveRecord::Base attr_accessible :name, :fields, :definition, :results serialize :fields, JSON serialize :last_results, JSON serialize :current_fields, JSON validates :name, presence: true, uniqueness: true belongs_to :definition def pdef definition.to_pdef end before_save :convert_fields_to_hash, if: Proc.new { |job| job.fields.is_a?(String) } def launch(override_fields={}, *args) merged_fields = fields.deep_merge(override_fields) self.last_wfid = Mastermind.launch(pdef, merged_fields, { job_id: id }) save super end def ps Mastermind.ps(last_wfid) end state_machine :initial => :pending do state :pending state :launched state :running state :failed state :completed state :canceled event :launch do transition [:pending, :completed, :failed, :canceled] => :launched end event :run do transition :launched => :running end event :error do transition :running => :failed end event :complete do transition :running => :completed end event :cancel do transition :running => :canceled end end private def convert_fields_to_hash self.fields = Rufus::Json.decode(fields) end end
module Stax class Stack < Base no_commands do def stack_resources @_stack_resources ||= Aws::Cfn.resources(stack_name) end def stack_resources_by_type(type) stack_resources.select do |r| r.resource_type == type end end end desc 'resources', 'list resources for this stack' method_option :match, aliases: '-m', type: :string, default: nil, desc: 'filter by resource regex' def resources print_table stack_resources.tap { |resources| if options[:match] m = Regexp.new(options[:match], Regexp::IGNORECASE) resources.select! { |r| m.match(r.resource_type) } end }.map { |r| [r.logical_resource_id, r.resource_type, color(r.resource_status, Aws::Cfn::COLORS), r.physical_resource_id] } end desc 'id [LOGICAL_ID]', 'get physical ID from resource logical ID' def id(resource) puts Aws::Cfn.id(stack_name, resource) end end end
require_relative 'menu.rb' require './lib/order.rb' require './lib/text.rb' # require 'timecop' class Restaurant include Order include Text attr_reader :menu, :order def initialize(menuklass, items) @menu = menuklass.new(items) @order = {} end def reset_order @order = {} end def receipt fail "Nothing in your order" if order.empty? "Thank you! Total cost: £#{'%.2f' % total} - #{ind_total.join(", ")}. It should arrive before #{arrival_time}".split.join(" ") end private def arrival_time time = Time.new (time + 3600).strftime("%H:%M") end def in_stock?(dish) menu.items.key?(dish) end end
require 'rails_helper' require 'shoulda/matchers' describe Vino do it { should belong_to(:bodega) } it { should belong_to(:denominacion) } it { should belong_to(:envejecimiento) } it { should have_many(:tipo_uvas) } it { should have_many(:ratings) } it { should have_many(:comentarios) } describe "average_rating" do let(:estacada) { Fabricate :vino } it "returns the average valoracion of every rating done for this vino" do ana = Fabricate :user jose = Fabricate :user marta = Fabricate :user anas_rating = Fabricate :rating, user_id: ana.id, vino_id: estacada.id, valoracion: 7 joses_rating = Fabricate :rating, user_id: jose.id, vino_id: estacada.id, valoracion: 10 martas_rating = Fabricate :rating, user_id: marta.id, vino_id: estacada.id, valoracion: 4 expect(estacada.average_rating).to eq(7) end it "returns nil if the number of ratings is 0" do expect(estacada.average_rating).to be_nil end end end
class Match < ActiveRecord::Base belongs_to :user1, class_name: "User" belongs_to :user2, class_name: "User" end
class TeamDecorator < Draper::Decorator delegate_all delegate :current_page, :total_pages, :limit_value # decorates_association :riders def budget h.number_to_euro(model.budget * Player::BUDGET_MULTIPLIER) end def points model.riders.sum(:points) end end
require 'yaml/store' class Idea def self.all raw_ideas.map do |data| Idea.new(data[:title], data[:description]) end end def self.raw_ideas database.transaction do |db| db['ideas'] || [] end end def self.database @database ||= YAML::Store.new('ideabox') end attr_reader :title, :description def initialize(title, description) @title = title @description = description end def save database.transaction do |db| db['ideas'] ||= [] db['ideas'] << {title: title, description: description} end end def database Idea.database end end
class FixColumnName < ActiveRecord::Migration def change rename_column :tags, :attribute, :description end end
task :default => 'sample:build' namespace :sample do desc 'Build the test fixture EPUB' task :build do input_dir = 'tests/fixtures/book' output_dir = 'tests/fixtures/' FileList["#{input_dir}/**/*"] sh "epzip #{input_dir}" end end
class ChaptersController < ApplicationController def create learning = Learning.find(params[:learning_id]) chapter = current_user.chapters.new(chapter_params) chapter.learning_id = learning.id chapter.save redirect_to learning_path(learning) end def show @chapter = Chapter.find(params[:id]) end private def chapter_params params.require(:chapter).permit(:title, :chapter_text, :video) end end
require File.dirname(__FILE__) + '/../test_helper' class TopicTest < ActiveSupport::TestCase context "topics with a tag" do setup do @crime_and_punishment = Factory(:topic) @book = Factory(:topic) @crime_and_punishment.tags << @book end should "be tagged" do assert_equal [@book], @crime_and_punishment.tags end context "and some properties" do setup do @date_read = Factory(:property_type, :name => 'Date Read', :type_name => 'MetaDate') @book.property_types << @date_read end should "books should have dates read " do assert_equal [@date_read], @book.property_types assert_equal [@date_read], @crime_and_punishment.properties_to_use end end end end
songs = [ "Phoenix - 1901", "Tokyo Police Club - Wait Up", "Sufjan Stevens - Too Much", "The Naked and the Famous - Young Blood", "(Far From) Home - Tiga", "The Cults - Abducted", "Phoenix - Consolation Prizes", "Harry Chapin - Cats in the Cradle", "Amos Lee - Keep It Loose, Keep It Tight" ] #Could have also used a HEREDOC: # def help # help = <<-HELP # I accept the following commands: # - help : displays this help message # - list : displays a list of songs you can play # - play : lets you choose a song to play # - exit : exits this program # HELP # puts help # end def help puts "I accept the following commands:" puts "- help : displays this help message" puts "- list : displays a list of songs you can play" puts "- play : lets you choose a song to play" puts "- exit : exits this program" end def play(songs) puts "Please enter a song name or number:" song_to_play = gets.chomp if (1..9).to_a.include?(song_to_play.to_i) puts "Playing #{songs[song_to_play.to_i-1]}" elsif songs.include?(song_to_play) puts "Playing #{song_to_play}" else puts "Invalid input, please try again" end end def list(songs) songs.each_with_index do |song,i| puts "#{i+1}. #{song}" end end def exit_jukebox puts "Goodbye" end def run(songs) help command = "" while command puts "Please enter a command:" command = gets.downcase.strip case command when 'help' help when 'play' play(songs) when 'list' list(songs) when 'exit' exit_jukebox break else help end end end
module Api class ActivitiesController < ApplicationController def create @activity = current_pane.activities.new(activity_params) if @activity.save render json: @activity else render json: @activity.errors.full_messages, status: :unprocessable_entity end end def destroy @activity = Activity.find(params[:id]) @activity.destroy! render json: @activity end def index @activities = current_pane.activities render :index end def show @activity = Activity.find(params[:id]) render json: @activity end def update @activity = current_pane.activities.find(params[:id]) if @activity.update(activity_params) render json: @activity else render json: @activity.errors.full_messages end end private def activity_params params.require(:activity).permit(:title, :description, :waste_type, :hours, :pane_id, :ord) end def current_pane if params[:id] @activity = Activity.find(params[:id]) @pane = @activity.pane elsif params[:activity] @pane = Pane.find(params[:activity][:pane_id]) end end end end
class AddNAllocatedToAcademics < ActiveRecord::Migration def change add_column :academics, :n_allocated, :integer, :default => 0 end end
Given("I am on Add glucose measure page") do visit new_profile_glucose_measure_path(profile_email: @my_profile.email) end Then("I should be redirected to the glucose measures page") do expect(page).to have_current_path(profile_glucose_measures_path(profile_email: @my_profile.email)) end Given("I am on glucose measures page") do visit profile_glucose_measures_path(profile_email: @my_profile.email) end Then("The Add glucose measure page should be displayed") do expect(page).to have_current_path(new_profile_glucose_measure_path(profile_email: @my_profile.email)) end When("I fill the new glucose measure data") do fill_in "glucose_measure[value]", with: "1" check "glucose_measure[fasting]" select DateTime.now.strftime("%Y"), from: "glucose_measure_date_1i" select DateTime.now.strftime("%B"), from: "glucose_measure_date_2i" select "10", from: "glucose_measure_date_3i" select DateTime.now.strftime("%H"), from: "glucose_measure_date_4i" select DateTime.now.strftime("%M"), from: "glucose_measure_date_5i" end
# frozen_string_literal: true require "openssl" require "tpm/constants" require "tpm/s_attest" require "webauthn/attestation_statement/base" module WebAuthn module AttestationStatement class TPM < Base class CertInfo TPM_TO_OPENSSL_HASH_ALG = { ::TPM::ALG_SHA1 => "SHA1", ::TPM::ALG_SHA256 => "SHA256" }.freeze def initialize(data) @data = data end def valid?(attested_data, extra_data) s_attest.magic == ::TPM::GENERATED_VALUE && valid_name?(attested_data) && s_attest.extra_data.buffer == extra_data end private attr_reader :data def valid_name?(attested_data) name_hash_alg = s_attest.attested.name.buffer[0..1].unpack("n")[0] name = s_attest.attested.name.buffer[2..-1] name == OpenSSL::Digest.digest(TPM_TO_OPENSSL_HASH_ALG[name_hash_alg], attested_data) end def s_attest @s_attest ||= ::TPM::SAttest.read(data) end end end end end
# Copyright (c) 2015 Vault12, Inc. # MIT License https://opensource.org/licenses/MIT require 'errors/zax_error' module Errors class ConfigError < ZAXError def http_fail return unless @controller super severe_error 'Configuration error' end end end
=begin input: String output: number steps: 1: define a method output the string 2: initialize a contsant hash for all numbers 0 - 9 =end def string_to_integer(str) numbers = {} 10.times { |idx| numbers[idx.to_s] = idx } result = [] str.chars.each { |char| result << numbers[char] } total = 0 result.each do |num| total = 10 * total + num end total end string_to_integer('4321') # == 4321 string_to_integer('570') # == 570 def hexadecimal_to_integer(str) numbers = {} 10.times { |idx| numbers[idx.to_s] = idx } ('a'..'f').to_a.each_with_index { |char, idx| numbers[char] = idx + 10 } result = [] str.downcase.chars.each { |char| result << numbers[char] } total = 0 result.each { |num| total = total * 16 + num } total end hexadecimal_to_integer('4D9f') # == 19871 def string_to_signed_integer(str) result = string_to_integer(str.delete('+-')) if str[0] == '-' -result else result end end p string_to_signed_integer('4321') # == 4321 p string_to_signed_integer('-570') # == -570 p string_to_signed_integer('+100') # == 100
class CheckOutsController < ApplicationController include CheckOutsHelper before_action :authenticate_user! before_action :set_total, only: [:index, :review_payment] # GET /check_outs # GET /check_outs.json def index @addresses = current_user.addresses @address = Address.new end def review_payment @address = Address.find(params[:address_id]) # helper method review payment review_items(@address) end private # Use callbacks to share common setup or constraints between actions. def set_total @coupon = Coupon.find_by(code: session[:coupon_applied]) @cart_items = current_user.cart_items @sub_total = 0 @cart_items.each do |item| @sub_total += item.quantity * item.product.price end if @coupon.present? @discount = (@sub_total * @coupon.percent.to_i)/100 else @discount = 0 end @cart_total = @sub_total - @discount if @cart_total < 5000 @shipping_cost = 50.to_f else @shipping_cost = 0.to_f end end end
require 'rails_helper' describe 'Logged in user can go to their own page' do scenario 'and they see all purchases that they flagged' do user = User.create!(username: 'Megan', password: 'pass') program = Program.create!(name: 'Denver Fire Department') vendor = Vendor.create!(name: 'Benny Blancos', state: 'CO') purchase = Purchase.create!(transaction_date: '4/16/2017', payment_date: '4/18/2018', description: 'Calzones', amount: 50.1) purchase2 = Purchase.create!(transaction_date: '6/16/2017', payment_date: '6/18/2018', description: 'Pizza with cheese', amount: 50.1) purchase3 = Purchase.create!(transaction_date: '12/16/2017', payment_date: '12/18/2018', description: 'Pepperoni pizza', amount: 50.1) ProgramVendorPurchase.create!(program: program, vendor: vendor, purchase: purchase) ProgramVendorPurchase.create!(program: program, vendor: vendor, purchase: purchase2) ProgramVendorPurchase.create!(program: program, vendor: vendor, purchase: purchase3) user.flags.create!(purchase: purchase2, user: user) allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(user) visit user_path(user) expect(page).to have_content(purchase2.programs.first.name) expect(page).to have_content(purchase2.vendors.first.name) expect(page).to have_content(purchase2.description) expect(page).to have_content(purchase2.amount) expect(page).to have_content(purchase2.transaction_date) expect(page).to have_content(purchase2.payment_date) expect(page).to_not have_content(purchase.description) expect(page).to_not have_content(purchase3.description) end end
require File.dirname(__FILE__) + "/../../spec_helper" describe "System::String#method_missing" do before(:each) do @sstr = "a".to_clr_string end it "doesn't allow mutating methods" do lambda { @sstr.chop! }.should raise_error TypeError lambda { @sstr[0] = "b" }.should raise_error TypeError end it "throws NoMethodError for methods that don't exist" do lambda { @sstr.foo }.should raise_error NoMethodError end it "throws NoMethodError for methods that don't exist that look like mutating methods" do lambda { @sstr.foo! }.should raise_error NoMethodError lambda { @sstr.foo="b" }.should raise_error NoMethodError end end
require 'active_record' require 'active_record/connection_adapters/mysql2_adapter' require 'active_record_ext/arrow_result' module ActiveRecord module ConnectionHandling def arrow_mysql2_connection(config) config = config.symbolize_keys config[:flags] ||= 0 if config[:flags].kind_of? Array config[:flags].push "FOUND_ROWS".freeze else config[:flags] |= Mysql2::Client::FOUND_ROWS end client = Mysql2::Client.new(config) ActiveRecordExt::ArrowMysql2Adapter.new(client, logger, nil, config) rescue Mysql2::Error => error if error.message.include?("Unknown database") raise ActiveRecord::NoDatabaseError else raise end end end end module ActiveRecordExt class ArrowMysql2Adapter < ActiveRecord::ConnectionAdapters::Mysql2Adapter def initialize(*args, **kwargs) super @arrow_result = false end def exec_query(sql, name = "SQL", binds = [], prepare: false) return super unless @arrow_result if without_prepared_statement?(binds) execute_and_free(sql, name) do |result| ArrowResult.new(result.to_arrow) if result end else exec_stmt_and_free(sql, name, binds, cache_stmt: prepare) do |_, result| ArrowResult.new(result.to_arrow) if result end end end def select_all_by_arrow(arel, name = nil, binds = [], preparable: nil) with_arrow_result do select_all(arel, name, binds, preparable: preparable) end end private def with_arrow_result begin old_value, @arrow_result = @arrow_result, true yield ensure @arrow_result = old_value end end end end
module PryIb module Command module Stat def self.build(commands) commands.create_command "stat" do description "Get Real Time Stats" banner <<-BANNER Get Real Time Stats Usage: stat [--num <num quotes>] [ --atr <period> ] [ --bs <bar size> ] <symbol_format> # Types: :s - stock, :f - future, :o - option # Expiry: YYYYMM symbol format: <string> # default as stock ticker symbol format: :type:ticker symbol format: :type:ticker:expriy Example: stat AAPL stat --atr 14 --num 500 AAPL stat :f:es:201409 # E-mini with expiry 2014-09 BANNER group 'pry-ib' def options(opt) opt.on :atr=, 'Get ATR with period', as: Array, delimiter: ',' opt.on :mfi=, 'Get MFI with period', as: Array, delimiter: ',' opt.on :num=, 'Number of quotes. (Default: 200)' opt.on :bs=, 'Bar size (Default: 5)' opt.on :min, 'Bar size 60 seconds' opt.on :v,:verbose, 'Verbose display' end def setup @parms = {} @num_quotes = 200 @bar_size = 5 end def process raise Pry::CommandError, "Need a least one symbol" if args.size == 0 symbol = args.first verbose = (opts.verbose?) ? true : false @bar_size = 60 if opts.min? @bar_size = opts[:bs].to_i if opts.bs? @num_quotes = opts[:num].to_i if opts.num? @parms[:atr] = opts[:atr].map!(&:to_i) if opts.atr? @parms[:mfi] = opts[:mfi].map!(&:to_i) if opts.mfi? @parms[:bar_size] = @bar_size ib = PryIb::Connection::current output.puts "Quote: #{symbol} Parms:#{@parms.inspect}" stat = PryIb::RealTimeStat.new(ib,:verbose => verbose) stat.quote(symbol,@num_quotes,@parms) end end end end end end
module Crypt require 'bcrypt' puts "modulo de encriptación activado" def Crypt.create_hash_password(password) # Crypt. -> hace que sea un método de clase. también se puede utilizar la denominación self. return BCrypt::Password.create(password) end def Crypt.verify_hashes(password) return BCrypt::Password.new(password) end def self.create_secure_users(users) users.each do |user| user[:password] = create_hash_password(user[:password]) end return users end def Crypt.authenticate_user(username, password, users) users.each do |user| if user[:username] == username && verify_hashes(user[:password]) == password return user end end return "Las credenciales no son correctas"; end end
mesh_files = [ 'oil_rig_manifold/visual.dae', 'simple_manifold/manifold.stl', 'simple_manifold/terrain.stl'] mesh_files.each do |src_file| src_file = File.join('models', 'sdf', src_file) osgb_file = "#{src_file}.osgb" file osgb_file => src_file do ENV['OSG_OPTIMIZER'] = 'DEFAULT INDEX_MESH VERTEX_POSTTRANSFORM' if !system(Hash['OSG_OPTIMIZER' => 'DEFAULT INDEX_MESH VERTEX_POSTTRANSFORM'], "osgconv", '--smooth', src_file, "#{src_file}.osgb") raise "cannot convert #{src_file} to the osgb format" end end task 'default' => "#{src_file}.osgb" task 'clean' do FileUtils.rm_f osgb_file end end task 'default' require 'utilrb/doc/rake' Utilrb.doc :include => ['models/**/*.rb', 'lib/**/*.rb']
module Twigg module Cache autoload :Client, 'twigg-cache/cache/client' autoload :VERSION, 'twigg-cache/cache/version' end end
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :restaurant do name "Curry-Ya" street "214 E 10th St" city_id 1 end end
require 'rails_helper' RSpec.describe UsersController, type: :controller do describe "Get new" do it 'renders the new users template' do get :new expect(response).to render_template("new") end end describe 'Post create' do it "validates that the password is at least 6 charcters long" do post :create , params: { user: { username: 'Nick Bacon', password: 'hello'} } assert_template('users/new') expect(flash[:errors]).to be_present end it "redirects user to homepage on success" do post :create, params: { user: {username: "Elliot", password: 'password'} } expect(response).to redirect_to(homepage) end it 'logs in the user' do post :create, params: { user: { username: "jon_chaney", password: "passedword" } } user = User.find_by_username("jon_chaney") expect(session[:session_token]).to eq(user.session_token) end end end
require 'execjs' require 'pathname' require 'sprockets' require 'tilt' # Ported from handlebars.rb. module JadeAssets # Change config options in an initializer: # # JadeAssets::Config.path_prefix = 'app/templates' module Config extend self attr_writer :compiler, :compiler_path, :options, :path_prefix, :template_namespace def compiler @compiler || 'jade.js' end def compiler_path @compiler_path || File.expand_path("../../../vendor/assets/javascripts", __FILE__) end def options @options ||= generate_options end def path_prefix @path_prefix || 'templates' end def template_namespace @template_namespace || 'jade.templates' end private def generate_options options = @options || {} options[:client] = true options end end end class Jade class << self def compile(str, options) context.eval("jade.compile(#{str.to_json}, #{options.to_json}).toString()") end private def context @context ||= ExecJS.compile(source) end def source @source ||= path.read end def path @path ||= assets_path.join(JadeAssets::Config.compiler) end def assets_path @assets_path ||= Pathname(JadeAssets::Config.compiler_path) end end end class TiltJade < Tilt::Template def self.default_mime_type 'application/javascript' end def evaluate(scope, locals, &block) template_path = TemplatePath.new(scope) template_name = template_path.filename_minus_extension compiled_template = Jade.compile(data, JadeAssets::Config.options) template_namespace = JadeAssets::Config.template_namespace # TODO: Add support for partials <<-TEMPLATE (function() { this.#{template_namespace} || (this.#{template_namespace} = {}); this.#{template_namespace}["#{template_name}"] = #{compiled_template}; return this.#{template_namespace}["#{template_name}"]; }).call(this); TEMPLATE end protected def prepare; end class TemplatePath def initialize(scope) # Need to use the full pathname instead of the logical_path because the logical_path # strips anything after a period (and we have folders like "static-2.43" that # have periods in them) self.template_path = scope.pathname.to_s end def is_partial? filename_minus_extension.start_with?('_') end def name is_partial? ? partial_name : template_path end def filename_minus_extension File.basename(template_path, ".jade") end private attr_accessor :template_path def forced_underscore_name '_' + relative_path end def partial_name forced_underscore_name.gsub(/\//, '_').gsub(/__/, '_').dump end end end Rails.application.assets.register_engine('.jade', TiltJade)
require 'rails_helper' RSpec.describe 'as a visitor', type: :feature do describe 'when I visit a books show page' do before :each do @author = Author.create(name: 'Trevor') @author2 = Author.create(name: 'Teresa') @book1 = Book.create(title: 'book1', page_count: 200, year: 2019, authors: [@author, @author2]) @user1 = User.create(username: 'cooldude1000') @user2 = User.create(username: 'cooldude1001') @review1 = Review.create(title: 'book sucked', review_text: 'was not worth the read', rating: 1, book: @book1, user: @user1) @review2 = Review.create(title: 'book sucked', review_text: 'was not worth the read', rating: 2, book: @book1, user: @user1) @review3 = Review.create(title: 'book rocked', review_text: 'was worth the read', rating: 4, book: @book1, user: @user2) @review4 = Review.create(title: 'book rocked', review_text: 'was worth the read', rating: 5, book: @book1, user: @user2) end it 'should show the books title author(s) and pages' do visit book_path(@book1) expect(page).to have_content(@book1.title) expect(page).to have_content(@book1.page_count) expect(page).to have_content(@author.name) expect(page).to have_content(@author2.name) end it 'should show a list of reviews for the book' do visit book_path(@book1) within '#reviews' do expect(page).to have_content(@user1.username) expect(page).to have_content(@review1.title) expect(page).to have_content(@review1.rating) expect(page).to have_content(@review1.review_text) expect(page).to have_content(@user2.username) expect(page).to have_content(@review2.title) expect(page).to have_content(@review2.rating) expect(page).to have_content(@review2.review_text) end end it 'should shows statistics about the book' do visit book_path(@book1) within '#avg_rating' do expect(page).to have_content('Average Rating: 3') end within '#top_three' do top_3_titles = page.all('p') # binding.pry top_3_titles[0].has_content?("User: cooldude1001") top_3_titles[1].has_content?("User: cooldude1001") top_3_titles[2].has_content?("User: cooldude1000") # expect(page.find('p:nth-child(1)')).to have_content(@review4.title) # expect(page.find('p:nth-child(2)')).to have_content(@review3.title) # expect(page.find('p:nth-child(3)')).to have_content(@review2.title) # # expect(page.find('p:nth-child(1)')).to have_content(@review4.user.username) # expect(page.find('p:nth-child(2)')).to have_content(@review3.user.username) # expect(page.find('p:nth-child(3)')).to have_content(@review2.user.username) # # expect(page.find('p:nth-child(1)')).to have_content(@review4.rating) # expect(page.find('p:nth-child(2)')).to have_content(@review3.rating) # expect(page.find('p:nth-child(3)')).to have_content(@review2.rating) end within '#bottom_three' do # expect(page.find('p:nth-child(1)')).to have_content(@review1.title) # expect(page.find('p:nth-child(2)')).to have_content(@review2.title) # expect(page.find('p:nth-child(3)')).to have_content(@review3.title) # # expect(page.find('p:nth-child(1)')).to have_content(@review1.user.username) # expect(page.find('p:nth-child(2)')).to have_content(@review2.user.username) # expect(page.find('p:nth-child(3)')).to have_content(@review3.user.username) # # expect(page.find('p:nth-child(1)')).to have_content(@review1.rating) # expect(page.find('p:nth-child(2)')).to have_content(@review2.rating) # expect(page.find('p:nth-child(3)')).to have_content(@review3.rating) end end end end
class Plan < ApplicationRecord has_many :consignments belongs_to :user, class_name: 'User', foreign_key: "created_by" belongs_to :user, class_name: 'User', foreign_key: "updated_by" # validation validates :name, presence: true, uniqueness: true validates :cost, presence: true # Queries scope :newest_first, lambda { order("plans.created_at DESC") } end
class UsersController < ApplicationController def index end def new @user = User.new end def create @user = User.new(user_params) if @user.save redirect_to '/' else redirect_to '/sign_up' end end def login user = User.find_by_email(params[:email]) if user && user.authenticate(params[:password]) session[:user_id] = user.id redirect_to "/" else flash[:danger] = "Incorrect credentials! Please try again!" redirect_to root_path end end def destroy session[:user_id] = nil redirect_to '/' end def create_from_omniauth auth_hash = request.env["omniauth.auth"] authentication = Authentication.find_by_provider_and_uid(auth_hash["provider"], auth_hash["uid"]) || Authentication.create_with_omniauth(auth_hash) # if: previously already logged in with OAuth if authentication.user user = authentication.user authentication.update_token(auth_hash) @next = root_url @notice = "Signed in!" else user = User.create_with_auth_and_hash(authentication, auth_hash) end session[:user_id] = user.id redirect_to root_path end private def user_params params.require(:user).permit(:first_name, :last_name, :email, :password) end end
class UsersController < ApplicationController load_and_authorize_resource def index @users = User.excludes(:id => current_user.id) end def new end def create @user = User.new(params[:user]) if @user.save flash[:notice] = "Successfully created User." redirect_to root_path else render :action => 'new' end end def edit @user = User.find(params[:id]) authorize! :read, Cpanel end def update @user = User.find(params[:id]) if @user.update(user_params) flash[:notice] = "Successfully updated User." redirect_to cpanel_index_path else render :action => 'edit' end end def destroy @user = User.find(params[:id]) if @user.destroy flash[:notice] = "Successfully deleted User." redirect_to root_path end end private def user_params params.require(:user).permit(:name, :surname, :email, :location, :role_id, :avatar, :avatar_cache, :remover_avatar) end end
require 'thor/group' require 'yaml' module HonorCodes module Generators class Template < Thor::Group include Thor::Actions argument :properties, :type => :array def write_template create_file 'license_template.yml', HonorCodes.make_template(properties) end end end end
require 'rails_helper' RSpec.describe BadContactService::IndexBadContact, type: :service do let(:user) { create(:user) } let(:bad_contact) { create(:bad_contact) } context "when there are no contacts" do it "returns no contacts" do expect(described_class.call(user, nil).result).to be_empty end end context "when there are contacts" do it "returns a list of contacts" do expect(described_class.call(bad_contact.user, nil).result).to contain_exactly(bad_contact) end end end
class Array # My Each # Extend the Array class to include a method named my_each that takes a block, # calls the block on every element of the array, and returns the original array. # Do not use Enumerable's each method. I want to be able to write: def my_each(&prc) (0...self.length).each do |i| prc.call(self[i]) end self end # My Select # Now extend the Array class to include my_select that takes a block and returns # a new array containing only elements that satisfy the block. Use your my_each method! def my_select(&prc) result = [] self.each do |el| result << el if prc.call(el) end result end # My Reject # Write my_reject to take a block and return a new array excluding elements # that satisfy the block. def my_reject(&prc) result = [] self.each do |el| result << el unless prc.call(el) end result end # My Any # Write my_any? to return true if any elements of the array satisfy the block # and my_all? to return true only if all elements satisfy the block. def my_any?(&prc) self.each do |el| return true if prc.call(el) end false end def my_all?(&prc) self.each do |el| return false if !prc.call(el) end true end # My Flatten # my_flatten should return all elements of the array into a new, one-dimensional # array. Hint: use recursion! def my_flatten return self if self.empty? result = [] self.each do |ele| if ele.is_a?(Array) result += ele.my_flatten else result << ele end end result end # My Zip # Write my_zip to take any number of arguments. It should return a new array # containing self.length elements. Each element of the new array should be an # array with a length of the input arguments + 1 and contain the merged elements # at that index. If the size of any argument is less than self, nil is returned # for that location. def my_zip(*arrays) result = [] (0...self.length).each do |i| ans = [self[i]] arrays.each do |el| ans << el[i] end result << ans end result end # My Rotate # Write a method my_rotate that returns self rotated. By default, the array should # rotate by one element. If a negative value is given, the array is rotated in the # opposite direction. def my_rotate(num=1) result = self.dup if num > 0 num.times { result.push(result.shift) } else num.abs.times { result.unshift(result.pop)} end result end # My Join # my_join returns a single string containing all the elements of the array, # separated by the given string separator. If no separator is given, an empty # string is used. def my_join(delimiter="") result = self[0] (1...self.length).each do |i| result += "#{delimiter}#{self[i]}" end result end # My Reverse # Write a method that returns a new array containing all the elements of the # original array in reverse order. def my_reverse result = [] (0...self.length).each do |i| idx = self.length - 1 - i result << self[idx] end result end end # return_value = [1, 2, 3].my_each do |num| # puts num # end.my_each do |num| # puts num # end # a = [1, 2, 3] # p a.my_select { |num| num > 1 } # => [2, 3] # p a.my_select { |num| num == 4 } # => [] # a = [1, 2, 3] # p a.my_reject { |num| num > 1 } # => [1] # p a.my_reject { |num| num == 4 } # => [1, 2, 3] # a = [1, 2, 3] # p a.my_any? { |num| num > 1 } # => true # p a.my_any? { |num| num == 4 } # => false # p a.my_all? { |num| num > 1 } # => false # p a.my_all? { |num| num < 4 } # => true # p [1, 2, 3, [4, [5, 6]], [[[7]], 8]].my_flatten # a = [ 4, 5, 6 ] # b = [ 7, 8, 9 ] # p [1, 2, 3].my_zip(a, b) # => [[1, 4, 7], [2, 5, 8], [3, 6, 9]] # c = [10, 11, 12] # d = [13, 14, 15] # p [1, 2].my_zip(a, b, c, d) # => [[1, 4, 7, 10, 13], [2, 5, 8, 11, 14]] # a = [ "a", "b", "c", "d" ] # p a.my_rotate == ["b", "c", "d", "a"] # p a.my_rotate(2) == ["c", "d", "a", "b"] # p a.my_rotate(-3) == ["b", "c", "d", "a"] # p a.my_rotate(15) == ["d", "a", "b", "c"] # a = [ "a", "b", "c", "d" ] # p a.my_join == "abcd" # p a.my_join("$") == "a$b$c$d" # p a.my_join("$") == "a$b$c$d" # p [ "a", "b", "c" ].my_reverse == ["c", "b", "a"] # p [ 1 ].my_reverse == [1] def factors(num) result = [] (1..num).each do |i| result << i if num % i == 0 end result end class Array def bubble_sort!(&prc) prc ||= Proc.new { |a, z| a <=> z} (0...self.length).each do |i| ((i + 1)...self.length).each do |j| if prc.call(self[i], self[j]) == 1 self[i], self[j] = self[j], self[i] end end end return self end def bubble_sort(&prc) self.dup.bubble_sort!(&prc) end end def substrings(string) result = [] (0...string.length).each do |i| ((i + 1)...string.length).each do |j| result << string[i..j] end end result end def subwords(word, dictionary) substring(word).select { |ele| dictionary.include?(ele)} end
module RailsMysql class DumpCommand def initialize(config) raise RailsMysql::ConfigurationError, "mysqldump requires a database" unless config.database @config = config end def command cmd_parts = [] cmd_parts << "-h \"#{config.host}\"" if config.host cmd_parts << "-P \"#{config.port}\"" if config.port cmd_parts << "-u \"#{config.username}\"" if config.username cmd_parts << "-p\"#{config.password}\"" if config.password "mysqldump #{cmd_parts.join(' ')} \"#{config.database}\" | gzip > #{filename}" end def filename "db/#{config.database}-#{Time.now.utc.iso8601}.sql.gz" end private def config @config end end end
Elo.configure do |config| # Every player starts with a rating of 1000 config.default_rating = 1000 # A player is considered a pro, when he/she has more than 2400 points # TODO: we should store Team.pro? when this triggers config.pro_rating_boundry = 2400 # A player is considered a new, when he/she has played less than 9 games config.starter_boundry = 9 end
# Create logger that ignores messages containing "CACHE" class CacheFreeLogger < ActiveSupport::Logger def add(severity, message = nil, progname = nil, &block) return true if progname&.include? "CACHE" super end end # Overwrite ActiveRecord's logger ActiveRecord::Base.logger = CacheFreeLogger.new(STDOUT) if Rails.env.development?
require './cartesian_points_helper' require 'benchmark' require 'matrix' require 'byebug' require 'set' class ConvexHull include CartesianPointsHelper attr_reader :points FIXNUM_MAX = (2**(0.size * 8 -2) -1) def initialize setup until points_requirement_satisfied? end def reset @points = nil setup until points_requirement_satisfied? end def brute_force result = Set.new points.each_with_index do |point_a, index_a| points[index_a+1..-1].each do |point_b| if in_same_plane?(point_a, point_b, points) result.merge([point_a, point_b]) end end end result end def jarvis_march points.sort_by!{ |point| point[1] } lowest, highest = points.first, points.last result = jarvis_march_wrap(lowest, highest, points, true) + jarvis_march_wrap(lowest, highest, points, false) result end def graham_scan points.sort_by!{ |point| point[1] } angles = points[1..-1].map { |point_b| [angle_with_line(points[0], point_b), point_b] } angles.sort_by!{ |angle| angle[0] } result = [points[0]] + angles[0..1].map { |angle| angle[1] } angles[2..-1].each do |angle| while true sub_top_top = vector(result[-2], result[-1]) sub_top_angle = vector(result[-2], angle[1]) break if result.size < 2 || determinant(sub_top_top, sub_top_angle) > 0 result.pop end result << angle[1] end result end def quick_hull points.sort_by!{ |point| point[1] } low_high = vector(points[0], points[-1]) left_points = points[1..-2].select do |point| determinant(low_high, vector(points[0], point)) > 0 end right_points = points[1..-2].select do |point| determinant(low_high, vector(points[0], point)) < 0 end result = [points[0], points[-1]] + find_hull(left_points, points[0], points[-1]) + find_hull(right_points, points[-1], points[0]) result end def benchmarks brute_force_time = Benchmark.measure { brute_force } # Worst case sort when algorithm run points.sort_by!{ |point| !point[1] } jarvis_march_time = Benchmark.measure { jarvis_march } # Worst case sort when algorithm run points.sort_by!{ |point| !point[1] } graham_scan_time = Benchmark.measure { graham_scan } # Worst case sort when algorithm run points.sort_by!{ |point| !point[1] } quick_hull_time = Benchmark.measure { quick_hull } puts "Time taken brute forces: #{brute_force_time.real}" puts "Time taken jarvis_march: #{jarvis_march_time.real}" puts "Time taken graham_scan : #{graham_scan_time.real}" puts "Time taken quick_hull : #{quick_hull_time.real}" end private def points_requirement_satisfied? if points.nil? || points.length < 3 puts "Requirement: Must have least three points!\n\n" return false end return true end def determinant(vector_a, vector_b) Matrix[vector_a, vector_b].determinant end def vector(point_a, point_b) [point_b[0]-point_a[0],point_b[1]-point_a[1]] end # Check if all points are in same plane regard to line ab def in_same_plane?(point_a, point_b, points) return true if points.empty? # Initial sign using first point in the list vector_ab = vector(point_a, point_b) sign = nil # Return false if sign change points.each do |point_c| next if [point_a,point_b].include? point_c vector_ac = vector(point_a, point_c) current_sign = determinant(vector_ab, vector_ac) <=> 0 sign ||= current_sign return false if sign != current_sign end # Return true if no sign change true end def jarvis_march_wrap(lowest, highest, points, low_to_high = true) result = low_to_high ? [lowest] : [highest] # Go from lowest to highest while true point_a = result.last # d is the horizontal line from a vector_ad = low_to_high ? [1, 0] : [-1, 0] selected_point = nil min_angle = FIXNUM_MAX # Get the point with smallest turn angle points.each do |point_b| next if (point_b == point_a) || (low_to_high && point_b[1] < point_a[1]) || (!low_to_high && point_b[1] > point_a[1]) vector_ab = vector(point_a, point_b) angle = Vector.elements(vector_ad).angle_with(Vector.elements(vector_ab)) min_angle, selected_point = [angle, point_b] if angle <= min_angle end break if [lowest, highest].include? selected_point result << selected_point end result end def angle_with_line(point_a, point_b, d = [1, 0]) vector_ab = vector(point_a, point_b) return 0 if vector_ab == [0,0] Vector.elements(d).angle_with(Vector.elements(vector_ab)) end def dot_product(point_a, point_b) Vector.elements(point_a).dot Vector.elements(point_b) end def find_hull(points, point_a, point_b) return [] if points.empty? vector_ab = vector(point_a, point_b) sorted_points = points.sort_by { |point_p| determinant(vector_ab, vector(point_a, point_p)).abs } point_c = sorted_points.pop vector_ac = vector(point_a, point_c) vector_bc = vector(point_b, point_c) left_points = sorted_points.select do |point| determinant(vector_ac, vector(point_a, point)) > 0 end right_points = sorted_points.select do |point| determinant(vector_bc, vector(point_b, point)) < 0 end result = [point_c] + find_hull(left_points, point_a, point_c) + find_hull(right_points, point_c, point_b) result end # Check if point P is in triangle ABC using barycentric coordinates # Read: http://blackpawn.com/texts/pointinpoly/ def point_in_triangle?(point_p, point_a, point_b, point_c) # Compute vectors v0 = vector(point_c, point_a) v1 = vector(point_b, point_a) v2 = vector(point_p, point_a) # Compute dot products dot00 = dot_product(v0, v0) dot01 = dot_product(v0, v1) dot02 = dot_product(v0, v2) dot11 = dot_product(v1, v1) dot12 = dot_product(v1, v2) # Compute barycentric coordinates inverse_denominator = 1 / (dot00 * dot11 - dot01 * dot01) u = (dot11 * dot02 - dot01 * dot12) * inverse_denominator v = (dot00 * dot12 - dot01 * dot02) * inverse_denominator # Check if point is in triangle return (u >= 0) && (v >= 0) && (u + v < 1) end end
Rails.application.routes.draw do # show all jobs get '/jobs' => 'jobs#index' # Create a job post '/jobs' => 'jobs#create' # Show one job get '/jobs/:id' => 'jobs#show' end
module DoceboRuby class Resource < OpenStruct def self.api=(api) @api = api end def self.api @api end def self.fetch_data(method, params = {}, &block) tries ||= 3 @fetcher = API.new @fetcher.send_request(@api, method, params) do |result| return result unless block_given? yield result end rescue RestClient::RequestTimeout => e sleep (4 - tries) retry unless (tries -= 1).zero? end end end
require 'spec_helper' describe "series_sets/edit.html.erb" do before(:each) do @series_set = assign(:series_set, stub_model(SeriesSet, :setname => "MyString" )) end it "renders the edit series_set form" do render rendered.should have_selector("form", :action => series_set_path(@series_set), :method => "post") do |form| form.should have_selector("input#series_set_setname", :name => "series_set[setname]") end end end
# frozen_string_literal: true # ltc.rb # Author: William Woodruff # ------------------------ # A Cinch plugin that retrieves Litecoin exchange rates for yossarian-bot. # Data courtesy of the BTC-e exchange: https://btc-e.com # ------------------------ # This code is licensed by William Woodruff under the MIT License. # http://opensource.org/licenses/MIT require "open-uri" require "json" require_relative "yossarian_plugin" class LTC < YossarianPlugin include Cinch::Plugin use_blacklist URL = "https://btc-e.com/api/3/ticker/ltc_usd" def initialize(*args) super @last_trade = nil end def usage "!ltc - Get the current Litecoin exchange rate in USD." end def match?(cmd) cmd =~ /^(!)?ltc$/ end match /ltc$/, method: :ltc_rate def ltc_rate(m) hash = JSON.parse(open(URL).read) rate = hash["ltc_usd"]["buy"].round(2) if @last_trade.nil? m.reply "1 LTC = #{rate} USD", true else direction = (@last_trade < rate ? "↑" : "↓") m.reply "1 LTC = #{rate} USD | #{direction}", true end @last_trade = rate rescue Exception => e m.reply e.to_s, true end end
module PostsHelper # Generate a link to a post for the side nav. # # post - The Post to link to. # current_post - The Post currently being viewed. # # Returns the markup for a line item in the side nav. def post_link(post, current_post) content_tag :li, class: ('active' if post == current_post) do link_to post.title, post end end end
require 'spec_helper' describe Twigg::Util do include described_class describe '#pluralize' do context 'with a count of 0' do it 'returns the plural form' do expect(pluralize 0, 'thing').to eq('0 things') end end context 'with a count of 1' do it 'returns the singular form' do expect(pluralize 1, 'thing').to eq('1 thing') end end context 'with a count of 2' do it 'returns the plural form' do expect(pluralize 2, 'thing').to eq('2 things') end end context 'with a custom inflection' do it 'returns the correct forms' do expect(pluralize 0, 'story', 'stories').to eq('0 stories') expect(pluralize 1, 'story', 'stories').to eq('1 story') expect(pluralize 2, 'story', 'stories').to eq('2 stories') end it 'stores custom inflection' do expect(pluralize 5, 'die', 'dice').to eq('5 dice') expect(pluralize 5, 'die').to eq('5 dice') end it 'shares custom inflection information across instances' do # first, register a custom inflection expect(pluralize 3, 'index', 'indices').to eq('3 indices') # then, exercise it in a distinct context klass = Class.new { include Twigg::Util } expect(klass.new.send :pluralize, 5, 'index').to eq('5 indices') end it 'allows multiple custom inflections to work' do expect(pluralize 5, 'open story', 'open stories').to eq('5 open stories') expect(pluralize 5, 'started story', 'started stories').to eq('5 started stories') end end end end
require 'spec_helper' feature "user makes goals" do subject { page } let(:user) { FactoryGirl.create(:user) } before(:each) do login_user(user) visit user_goals_url(user) click_on "Create New Goal" end it { should have_content "Make a new goal" } it "should not allow a goal with no title" do fill_in 'Title', with: "" click_on "Make Goal" expect(page).to have_content "Title can't be blank" end it "can create a new goal with just a title" do fill_in 'Title', with: "Sleep more" click_on "Make Goal" expect(page).to have_content "Sleep more" end it "can create a new goal with a title and body" do fill_in 'Title', with: "Sleep more" fill_in 'Body', with: "I herby resolve to sleep more, perhaps in the sunlight on the couch." click_on "Make Goal" expect(page).to have_content "Sleep more" expect(page).to have_content "I herby resolve to sleep more" end it "can create a new goal that is private" do fill_in 'Title', with: "Sleep more" check 'Private' click_on "Make Goal" expect(page).to have_content "Sleep more" expect(page).to have_content "This goal is private" end end feature "user sees all of their goals" do subject { page } let(:user) { FactoryGirl.create(:user) } it "can see multiple goals" do login_user(user) visit new_user_goal_url(user) fill_in 'Title', with: "Sleep more" click_on "Make Goal" visit new_user_goal_url(user) fill_in 'Title', with: "Also eat more" click_on "Make Goal" visit user_goals_url(user) expect(page).to have_content "Sleep more" expect(page).to have_content "Also eat more" end end feature "user can edit their goals" do subject { page } let(:user) { FactoryGirl.create(:user_with_goal) } it "has a link to the edit page" do login_user(user) visit goal_url(user.goals.first) expect(page).to have_content "Edit this goal" end describe "on the edit page" do before(:each) do login_user(user) visit goal_url(user.goals.first) click_link "Edit this goal" end it "has goal's information pre filled in" do title_text = user.goals.first.title body_text = user.goals.first.body find_field('Title').value.should eq title_text find_field('Body').value.should eq body_text end it "can edit a goal's title and body" do fill_in 'Title', with: "Sleep more" fill_in 'Body', with: "I hereby resolve to sleep more" click_on "Update Goal" expect(page).to have_content "Sleep more" expect(page).to have_content "I hereby resolve to sleep more" end it "cannot make a goal invalid" do fill_in 'Title', with: "" click_on "Update Goal" expect(page).to have_content "Title can't be blank" end it "can toggle privacy filter" do user2 = FactoryGirl.create(:user_with_private_goal) login_user(user2) visit goal_url(user2.goals.first) click_link "Edit this goal" uncheck "Private" click_on "Update Goal" expect(page).to have_content "This goal is public" end end end feature "user can destroy their goals" do subject { page } let(:user) { FactoryGirl.create(:user_with_goal) } before(:each) do login_user(user) visit goal_url(user.goals.first) end it "has a button to delete goal" do expect(page).to have_button "Delete this goal" end it "can delete the goal" do title_text = user.goals.first.title click_button "Delete this goal" expect(page).to_not have_content title_text end end feature "users can't see other user's private goals" do let(:user) { FactoryGirl.create(:user_with_private_goal) } let(:user2) { FactoryGirl.create(:user_with_goal) } it "can't see another user's private goal" do login_user(user2) visit user_goals_url(user) title_text = user.goals.first.title expect(page).to_not have_content title_text end it "can see another user's public goal" do login_user(user) visit user_goals_url(user2) title_text = user2.goals.first.title expect(page).to have_content title_text end end feature "users can mark goals as completed" do let(:user) { FactoryGirl.create(:user_with_private_goal) } before(:each) do login_user(user) visit goal_url(user.goals.first) end it "should have a button to mark as completed" do expect(page).to have_button("Mark as completed") end it "clicking the button should mark goal as completed" do click_button "Mark as completed" expect(page).to_not have_button("Mark as completed") expect(page).to have_content("Congratulations! You've completed this goal") end describe "once marked as completed" do before(:each) do login_user(user) visit goal_url(user.goals.first) click_button "Mark as completed" end it "should have a button to re-open a goal" do expect(page).to have_button("Re-activate this goal") end it "re-opening a goal should make it uncompleted" do click_button "Re-activate this goal" expect(page).to have_button("Mark as completed") expect(page).to_not have_button("Re-activate this goal") end it "shows as completed on goals index" do visit user_goals_url(user) expect(page).to have_content("-- Completed!") end end end
class Product < ApplicationRecord validates :name, :description, :price, :presence => true has_attached_file :picture, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png" validates_attachment_content_type :picture, content_type: /\Aimage\/.*\z/ has_many :reviews has_many :users, through: :reviews end
require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') describe AppsController, 'routing' do it_should_behave_like 'a RESTful controller with routes' it "should build params :customer_id => '1', :controller => 'apps', :action => 'new' from GET /customers/1/apps/new" do params_from(:get, '/customers/1/apps/new').should == { :controller => 'apps', :action => 'new', :customer_id => '1' } end it "should map :controller => 'apps', :action => 'new', :customer_id => '1' to /customers/1/apps/new" do route_for(:controller => 'apps', :action => 'new', :customer_id => '1').should == "/customers/1/apps/new" end it "should build params :customer_id => '1', :controller => 'apps', :action => 'create' from POST /customers/1/apps" do params_from(:post, '/customers/1/apps').should == { :controller => 'apps', :action => 'create', :customer_id => '1' } end it "should map :controller => 'apps', :action => 'create', :customer_id => '1' to /customers/1/apps" do route_for(:controller => 'apps', :action => 'create', :customer_id => '1').should == { :path => "/customers/1/apps", :method => 'post' } end end
require_relative '../../spec_helper' describe BandCampBX::Net do let(:client){ double } subject(:net) { described_class.new(client) } before do client.stub(:secret).and_return(1) client.stub(:key).and_return(2) end it 'gets instantiated with a client' do expect(net.client).to eq(client) end it 'defers to its client for secret' do expect(net.secret).to eq(1) end it 'defers to its client for key' do expect(net.key).to eq(2) end describe '#post' do describe 'any_endpoint' do let(:example_balance) do <<-JSON { "foo": "bar" } JSON end before do FakeWeb.register_uri(:post, "https://campbx.com/api/myfunds.php", body: example_balance) end it "queries the appropriate endpoint and returns its body as a string" do expect(json_parse(net.post('myfunds.php'))).to eq(json_parse(example_balance)) end end end end
# @param {Integer} n # @return {Integer} def subtract_product_and_sum(n) product_of_digits = 1 sum_of_digits = 0 n.to_s.each_char do |digit| digit_int = digit.to_i product_of_digits *= digit_int sum_of_digits += digit_int end return product_of_digits - sum_of_digits end
class ProjectsController < ApplicationController def new @project = Project.new end def create @project = Project.new(project_params) if @project.save redirect_to project_url(@project) end end def show @project = Project.find_by_id(params[:id]) if @project.dailies sum = @project.goal @project.dailies.each do |daily| sum -= daily.word_count end @words_this_week = sum else @words_this_week = @project.goal end end private def project_params params.require(:project).permit(:name, :goal, :period) end end
class Message < ActiveRecord::Base # == Vendor acts_as_profanity_filter :text, :user => :from_user # == Class-level # # === Constants TEXT_MIN_LENGTH = 2 TEXT_MAX_LENGTH = 2048 TEXT_REGEX = /\A[[:graph:][:space:]]{#{TEXT_MIN_LENGTH},#{TEXT_MAX_LENGTH}}\Z/ STATUS_REJECTED = 'rejected' STATUS_APPROVED = nil # === Scopes named_scope :active, :conditions => [ "messages.status IS NULL OR messages.status != 'rejected'" ] named_scope :active_or_rejected, :conditions => [ "messages.status IS NULL OR messages.status = 'rejected'" ] named_scope :rejected, :conditions => { :status => "rejected" } named_scope :by_date_desc, :order => "created_at DESC" # === Associations has_many :replies, :class_name => "Message", :foreign_key => :reply_to_id has_many :inappropriates, :as => :inappropriated belongs_to :to_user, :class_name => "User", :foreign_key => :to_user_id belongs_to :from_user, :class_name => "User", :foreign_key => :from_user_id belongs_to :about, :polymorphic => true belongs_to :reply_to, :class_name => "Message", :foreign_key => :reply_to_id def product case about when Product then about when RatableEntity then about when Review then about.product end end # === Methods class << self def find_by_param(param) find_by_id param end def reject_messages(*ids) messages = update ids, [{ :status => "rejected" }] * ids.size messages.length end def find_for_review(review, limit = nil) all :conditions => { :about => review }, :order => "created_at DESC", :limit => (limit || 100) end def find_for_user(user, mine = true, limit = nil) conditions = ["to_user_id = ?", user.id] if mine conditions.first << " OR from_user_id = ?" conditions << user.id end all :conditions => conditions, :order => "created_at DESC", :limit => limit end end # == Instance-level # # === Attributes attr_protected :created_at, :updated_at attr_writer :deleted def deleted? @deleted end # === Callbacks # # ==== Validations extend ValidationHelper validates_presence_of :to_user, :from_user validates_length_of :text, :within => 2..2048, :allow_nil => false, :message => <<MESSAGE.chomp should be between #{TEXT_MIN_LENGTH} and #{TEXT_MAX_LENGTH} characters long MESSAGE # ==== Lifecycle after_save :update_endeca after_create :send_new_comment_notifications, :update_counter_caches, :log_activity after_destroy :destroy_related_user_activity # === Methods def mark_as(status) self.status=status self.save self.about.touch self.to_user.user_stat.touch if self.to_user self.from_user.user_stat.touch self.about.update_message_count if self.about.respond_to? :update_message_count end def mark_as_rejected mark_as('rejected') end def mark_as_active mark_as(nil) end #- # AJA TODO: where is this called from (was in compliment). #+ def title_for_rss if about.is_a?(Review) "Comment on review of #{about.product.title}" else "Comment" end end def text (self.rejected? && App.comment_replacement[:enabled]) ? self.replacement_text : read_attribute(:text) end def original_text read_attribute(:text) end def rejected? self.status == STATUS_REJECTED end def allow_edit?(session_user) (session_user == self.from_user) && (self.rejected? ? App.comment_replacement[:show_edit?] : true) end def allow_reply? self.rejected? ? App.comment_replacement[:allow_replies?] : true end def show_author? self.rejected? ? App.comment_replacement[:show_author?] : true end def replacement_text App.comment_replacement[:replacement_text] || 'This post has been removed by an administrator or moderator.' end def pretty_type case about when nil then private ? 'Private Message' : 'Public Message' else about.class.to_s end end private def destroy_related_user_activity UserActivity.destroy_all :subject_id => id, :subject_type => "Message", :user_id => from_user.id, :action => "commented" end def update_counter_caches if about && about.respond_to?(:update_message_count) about.update_message_count end end def send_new_comment_notifications notified = [] # Always notfiy the recipient. notified << to_user unless to_user == from_user is_review_or_idea = about.is_a?(Review) || about.is_a?(Idea) # Notify the review writer, unless we already have because he is the # recipient or the comment is from him. if is_review_or_idea && ![to_user, from_user].include?(about.user) notified << about.user end # If we have a reply_to chain... if reply_to r = reply_to while r unless notified.include?(r.from_user) unless r.from_user == from_user unless is_review_or_idea && r.from_user == about.user notified << r.from_user end end end r = r.reply_to end end # Get the set of users who want realtime notifications. realtime_users = notified.select { |user| user.email_opt_in && user.notify_on_new_comment? } ETTriggeredSendAdd.send_new_message_notifications(self, realtime_users) end def update_endeca EndecaEvent.fire!(about, :replace) if about && about.is_a?(Review) end def log_activity UserActivity.commented self unless private? end def self.user_inbox_default_filters(cobrand = nil) returning({ :review_comments => true, :public_profile_comments => true, :private_profile_comments => true, :sent => true, :deleted => false }) do |filters| if cobrand cobrand.idea_instances.each do |instance| filters[:"#{instance.name.downcase.singularize}_comments"] = true end cobrand.article_instances.each do |instance| filters[:"#{instance.short_name.downcase.singularize}_comments"] = true end end end end def self.user_inbox_inner_sql(user, filters = nil, cobrand = nil) filters ||= Message.user_inbox_default_filters stmts = [] if filters[:review_comments] stmts << comments_sql('reviews') end cobrand.idea_instances.each do |instance| if filters[:"#{instance.name.downcase.singularize}_comments"] stmts << comments_sql('ideas', instance) end end if cobrand cobrand.article_instances.each do |instance| if filters[:"#{instance.short_name.downcase.singularize}_comments"] stmts << comments_sql('articles', instance) end end if cobrand if filters[:public_profile_comments] stmts << profile_comments(0) end if filters[:private_profile_comments] stmts << profile_comments(1) end if filters[:sent] stmts << <<-SQL SELECT messages.id FROM messages WHERE from_user_id = :user_id AND (messages.status IS NULL OR messages.status != :status) SQL end if filters[:deleted] stmts << <<-SQL SELECT messages.id FROM messages WHERE hidden = 1 AND from_user_id != :user_id AND to_user_id = :user_id AND (messages.status IS NULL OR messages.status != :status) SQL end sanitize_sql [stmts.join("\nUNION\n"), { :user_id => user.id, :status => "rejected" }] end def self.user_inbox_count(user, filters=nil, cobrand=nil) filters ||= Message.user_inbox_default_filters Message.count_by_sql <<-SQL SELECT count(distinct(xx.id)) FROM (#{Message.user_inbox_inner_sql(user, filters, cobrand)}) AS xx SQL end def self.user_inbox_find(user, filters, limit, cobrand = nil) filters ||= Message.user_inbox_default_filters Message.find_by_sql <<-SQL SELECT messages.* FROM ( #{Message.user_inbox_inner_sql(user, filters, cobrand)} ) AS xx JOIN messages ON messages.id = xx.id GROUP BY messages.id ORDER BY messages.created_at DESC LIMIT #{limit} SQL end def self.paginate_user_inbox(user, page, per_page, filters = nil, cobrand = nil) filters ||= Message.user_inbox_default_filters(cobrand) count = Message.user_inbox_count user, filters, cobrand pages, limit_clause = Util.create_paginator page, per_page, count, true messages = Message.user_inbox_find user, filters, limit_clause, cobrand [pages, messages] end # Not precisely named, the correct name for this might be something like # inappropriate_messaages_attached_to_reviews_for_cobrand, but that's obscene. def self.inappropriates_for_cobrand(cobrand) reviews = Inappropriate.find(:all, :joins => ["JOIN messages on messages.id = inappropriates.inappropriated_id JOIN reviews on reviews.id = messages.about_id"], :conditions => {'inappropriates.inappropriated_type' => 'Message', 'messages.about_type' => 'Review', 'reviews.cobrand_id' => cobrand}, :order => 'created_at DESC') ideas = Inappropriate.find(:all, :joins => ["JOIN messages on messages.id = inappropriates.inappropriated_id JOIN ideas on ideas.id = messages.about_id JOIN idea_instances on ideas.idea_instance_id = idea_instances.id"], :conditions => {'inappropriates.inappropriated_type' => 'Message', 'messages.about_type' => 'Idea', 'idea_instances.cobrand_id' => cobrand}, :order => 'created_at DESC') # Hack to get things right for Overstock. [reviews + ideas].flatten.sort{|a,b| b.created_at <=> a.created_at } end private def self.comments_sql(table_name, instance=nil) query = <<-SQL SELECT messages.id FROM messages JOIN #{table_name} ON about_id = #{table_name}.id and #{table_name}.user_id = :user_id WHERE about_type = '#{table_name.singularize.capitalize}' AND from_user_id != :user_id AND hidden = 0 AND (messages.status IS NULL OR messages.status != :status) SQL unless instance.blank? query += " AND #{table_name}.#{table_name.singularize}_instance_id = #{instance.id} " end query += <<-SQL UNION SELECT messages.id FROM messages SQL unless instance.blank? query += " JOIN #{table_name} ON about_id = #{table_name}.id " end query += <<-SQL WHERE about_type = '#{table_name.singularize.capitalize}' AND to_user_id = :user_id AND from_user_id != :user_id AND hidden = 0 AND (messages.status IS NULL OR messages.status != :status) SQL unless instance.blank? query += " AND #{table_name}.#{table_name.singularize}_instance_id = #{instance.id} " end query end def self.profile_comments(private=0) query = <<-SQL SELECT messages.id FROM messages WHERE about_type IS NULL AND hidden = 0 AND private = #{private} AND to_user_id = :user_id AND (messages.status IS NULL OR messages.status != :status) SQL end end
class Api::ListingsController < ApplicationController def index if current_user @listings = Listing .where(lessor: current_user) .where(active: true) .includes(:rentals, rentals: [:lessee]) .order("rentals.start_date") else render json: ["you are not logged in"], status: 401 end end def show @listing = Listing.find(params[:id]) end def create @listing = Listing.new(listing_params) @listing.lessor = current_user @listing.brand = Brand.find_by(name: params[:listing][:brand]) @listing.category = Category.find_by(name: params[:listing][:category]) if @listing.save urls = params[:listing][:image_urls] urls.each { |url| Photo.create(listing: @listing, image_url: url) } if urls render json: @listing, status: 200 else render json: @listing.errors.full_messages, status: 422 end end def update @listing = Listing.where(id: params[:listing][:id]) if @listing.update(params[:listing][:id]) render "api/listings/#{@listing.id}" else render json: @listing.errors.full_messages, status: 422 end end private def listing_params params.require(:listing) .permit( :listing_title, :detail_desc, :location, :lat, :lng, :day_rate, :replacement_value, :serial ) end end
class AddIsDefaultToPictures < ActiveRecord::Migration[5.0] def change add_column :pictures, :is_default, :boolean remove_column :pictures, :name end end
class Vent < ActiveRecord::Base has_many :responses has_many :taggings has_many :tags, :through => :taggings validates :name, :body, presence: true end
class LittleWorldChannel < ApplicationCable::Channel def subscribed current_avatar.log_in stream_from "little_world_channel" end def unsubscribed current_avatar.log_out end def speak(data) message_text = data["message"].to_s.squish.first(256).gsub("<", "&lt;").presence return unless message_text.present? avatar = Avatar.find_by(uuid: data["uuid"]) avatar.update(timestamp: data["timestamp"]) message = LittleWorldsController.render(partial: 'message', locals: { author: avatar.try(:username), message: message_text, timestamp: avatar.try(:timestamp) }) ActionCable.server.broadcast :little_world_channel, {uuid: data["uuid"], message: message, timestamp: avatar.try(:timestamp)} end def ping ActionCable.server.broadcast :little_world_channel, {ping: true} end def pong(data) avatar = Avatar.find_by(uuid: data["uuid"]) return unless avatar.present? avatar.broadcast_movement end end
class AddPublishToCollections < ActiveRecord::Migration def change add_column :collections, :publish, :boolean, default: false add_index :collections, :publish end end
require 'json' require 'webrick' module Phase8 class Flash def initialize(req) cookie = req.cookies.find do |cookie| cookie.name == '_rails_lite_flash' end if cookie content = JSON.parse(cookie.value) end flash = cookie ? content : {} @flash = {} flash.each { |key, value | @flash[key.to_sym] = value } @flash[:now] = @flash.dup #shallow dup is ok end def [](key) #returns anything in flash.now @flash.merge(@flash[:now])[key.to_sym] end def []=(key, value) @flash[key.to_sym] = value end def now @flash[:now] end def store_flash(res) stored_flash = @flash.reject do |key, value| key == :now || @flash[:now][key] == value end res.cookies << WEBrick::Cookie.new('_rails_lite_flash', stored_flash.to_json) end end end
class Noti < FPM::Cookery::Recipe description 'Trigger notifications when a process completes' name 'noti' version '3.1.0' revision '1' source "https://github.com/variadico/noti/releases/download/#{version}/noti#{version}.linux-amd64.tar.gz" sha256 '959410e065ed36554c8c2e2b94c803de5dc8c149b2e88c220b814cb31b23f684' def build end def install bin.install 'noti' end end
class TeamInterestNotificationMailer < ActionMailer::Base def email(team_interest) @team_interest = team_interest mail(to: ENV["NOTIFICATION_EMAIL"], subject: "Team Interest Notification") end end
require 'rails_helper' RSpec.describe User, type: :model do describe "associations / relationships" do it { should have_many :roles } end describe "enum attributes" do it { should define_enum_for(:role) } end context "user's role" do let(:admin) { create(:user, :admin) } it "checks if the user's role is an admin" do expect(admin.is_admin?).to be true end end end
require 'spec_helper' require 'yt/models/content_owner' describe Yt::Asset, :partner do describe '.ownership' do let(:asset) { Yt::Asset.new id: asset_id, auth: $content_owner } describe 'given an asset administered by the content owner' do let(:asset_id) { ENV['YT_TEST_PARTNER_ASSET_ID'] } specify 'the ownership can be obtained' do expect(asset.ownership).to be_a Yt::Ownership end describe 'the asset can be updated' do let(:attrs) { {metadata_mine: {notes: 'Yt notes'}} } it { expect(asset.update attrs).to be true } end end end end
require 'jumpstart_auth' class MicroBlogger attr_reader :client def initialize puts "Initializing MicroBlogger" @client = JumpstartAuth.twitter end def run puts "Welcome to the JSL Twitter Client" command = "" while command != "q" printf "enter command: " input = gets.chomp parts = input.split(' ') command = parts[0] case command when 'q' then puts "Goodbye!" when 't' then tweet(parts[1..-1].join(' ')) when 'dm' then dm(parts[1], parts[2..-1].join(' ')) when 'spam' then spam_followers(parts[1..-1].join(' ')) else puts "Sorry, I don't know how to #{command}" end end end def tweet(message) if message.length <= 140 @client.update(message) else puts "Message too long!" end end def followers_list screen_names << @client.user(follower).screen_name screen_names end def dm(target, message) screen_names = followers_list if screen_names.include? target puts "Sending #{target} your message:\n #{message}" message = "d @#{target} #{message}" tweet(message) else puts "Sorry, #{target} does not follow you." end end def spam_followers(message) followers_list.each { |follower| dm(follower, message) } end def everyones_last_tweet followers = @client.user(follower) followers.each do |follower| name = follower.screen_name status = follower.status puts "#{name} said... #{status}" end end end blogger = MicroBlogger.new blogger.run
# -*- coding: utf-8 -*- module Smshelper module Api class ResponseCodes BULKSMS = { '0' => 'In progress', '1' => 'Scheduled', '10' => 'Delivered upstream', '11' => 'Delivered to mobile', '12' => 'Delivered upstream unacknowledged', '22' => 'Internal fatal error', '23' => 'Authentication failure', '24' => 'Data validation failed', '25' => 'You do not have sufficient credits', '26' => 'Upstream credits not available', '27' => 'You have exceeded your daily quota', '28' => 'Upstream quota exceeded', '29' => 'Message sending cancelled', '31' => 'Unroutable', '32' => 'Blocked', '33' => 'Failed: censored', '40' => 'Temporarily unavailable', '50' => 'Delivery failed - generic failure', '51' => 'Delivery to phone failed', '52' => 'Delivery to network failed', '53' => 'Message expired', '54' => 'Failed on remote network', '56' => 'Failed: remotely censored', '57' => 'Failed due to fault on handset', '60' => 'Transient upstream failure', '61' => 'Upstream status update', '62' => 'Upstream cancel failed', '63' => 'Queued for retry after temporary failure delivering', '64' => 'Queued for retry after temporary failure delivering, due to fault on handset', '70' => 'Unknown upstream status', '201' => 'Maximum batch size exceeded'} WEBTEXT = { '000' => 'Success. Message accepted for delivery', '101' => 'Missing parameter: api_id', '102' => 'Missing parameter: api_pwd', '103' => 'Missing parameter: txt', '104' => 'Missing parameter: dest', '105' => 'Missing parameter: msgid', '106' => 'Missing parameter: receipt_url', '107' => 'Missing parameter: receipt_email', '108' => 'Invalid value for parameter: hex', '109' => 'Missing parameter: hex (unicode parameter has been presented, but no hex value)', '110' => 'Missing parameter: si_txt', '111' => 'Missing parameter: si_url', '112' => 'Missing parameter: group_name', '113' => 'Missing parameter: group_alias', '114' => 'Missing parameter: contact_num', '115' => 'Missing parameter: remove_num', '199' => 'Insufficient Credit', '201' => 'Authentication Failure', '202' => 'IP Restriction – an attempt has been made to send from an unauthorised IP address', '203' => 'Invalid value for parameter: dest', '204' => 'Invalid value for parameter: api_pwd', '205' => 'Invalid value for parameter: api_id', '206' => 'Invalid value for parameter: delivery_time', '207' => 'Invalid date specified for delivery_time', '208' => 'Invalid value for parameter: delivery_delta', '209' => 'Invalid value for parameter: receipt', '210' => 'Invalid value for parameter: msgid', '211' => 'Invalid value for parameter: tag', '212' => 'Invalid value for parameter: si_txt', '213' => 'Invalid value for parameter: si_url', '214' => 'Invalid value for parameter: group_name', '215' => 'Invalid value for parameter: group_alias', '216' => 'Invalid value for parameter: contact_num', '217' => 'Invalid value for parameter: remove_num', '401' => 'Not a contact', '402' => 'Invalid value for parameter: group_alias'} CLICKATELL = { '001' => 'Message unknown', '002' => 'Message queued', '003' => 'Delivered to gateway', '004' => 'Received by recipient', '005' => 'Error with message', '006' => 'User cancelled message delivery', '007' => 'Error delivering message', '008' => 'OK', '009' => 'Routing error', '010' => 'Message expired', '011' => 'Message queued for later delivery', '012' => 'Out of credit', '014' => 'Maximum MT limit exceeded'} SMSTRADE = { '10' => 'Receiver number not valid', '20' => 'Sender number not valid', '30' => 'Message text not valid', '31' => 'Message type not valid', '40' => 'SMS route not valid', '50' => 'Identification failed', '60' => 'Not enough balance in account', '70' => 'Network does not support the route', '71' => 'Feature is not possible by the route', '80' => 'Handover to SMSC failed', '100' => 'SMS has been sent successfully'} MEDIABURST = { '1' => 'Internal Error', '2' => 'Invalid Username Or Password', '3' => 'Insufficient Credits Available', '4' => 'Authentication Failure', '5' => 'Invalid MsgType', '6' => "‘To’ Parameter Not Specified", '7' => "‘Content’ Parameter Not Specified", '8' => "‘MessageID’ Parameter Not specified", '9' => "Unknown ‘MessageID’", '10' => "Invalid ‘To’ Parameter", '11' => "Invalid ‘From’ Parameter", '12' => 'Max Message Parts Exceeded', '13' => 'Cannot Route Message', '14' => 'Message Expired', '15' => 'No route defined for this number', '16' => "‘URL’ parameter not set", '17' => 'Invalid Source IP', '18' => "‘UDH’ Parameter Not Specified", '19' => "Invalid ‘ServType’ Parameter", '20' => "Invalid ‘ExpiryTime’ Parameter", '25' => 'Duplicate ClientId received', '26' => 'Internal Error', '27' => "Invalid ‘TimeStamp’ Parameter", '28' => "Invalid ‘AbsExpiry’ Parameter", '29' => "Invalid ‘DlrType’ Parameter", '31' => "Invalid ‘Concat’ Parameter", '32' => "Invalid ‘UniqueId’ Parameter", '33' => "Invalid ‘ClientId’ Parameter", '39' => "Invalid character in ‘Content’ parameter", '40' => 'Invalid TextPayload', '41' => 'Invalid HexPayload', '42' => 'Invalid Base64Payload', '43' => 'Missing content type', '44' => 'Missing ID', '45' => 'MMS Message too large', '46' => 'Invalid Payload ID', '47' => 'Duplicate Payload ID', '48' => 'No payload on MMS', '49' => "Duplicate ‘filename’ Attribute on Payload", '50' => "‘ItemId’ Parameter Not Specified", '51' => "Invalid ‘ItemId’ Parameter", '52' => 'Unable to generate filename for Content-Type', '53' => "Invalid ‘InvalidCharAction’ Parameter", '54' => "Invalid ‘DlrEnroute’ Parameter", '55' => "Invalid ‘Truncate’ Parameter", '56' => "Invalid ‘Long’ Parameter", '100' => 'Internal Error', '101' => 'Internal Error', '102' => 'Invalid XML', '103' => 'XML Document does not validate', '300' => 'Client ID too long', '305' => 'Query throttling rate exceeded'} NEXMO = { '0' => 'Success', '1' => 'Throttled', '2' => 'Missing params', '3' => 'Invalid params', '4' => 'Invalid credentials', '5' => 'Internal error', '6' => 'Invalid message', '7' => 'Number barred', '8' => 'Partner account barred', '9' => 'Partner quota exceeded', '10' => 'Too many existing binds', '11' => 'Account not enabled for REST', '12' => 'Message too long', '15' => 'Invalid sender address', '16' => 'Invalid TTL'} AQL = {} ROUTO = { '0' => 'Delivered', '1' => 'Rejected: Message length is invalid', '2' => 'Subscriber absent', '3' => 'Device memory capacity exceeded', '4' => 'Equipment protocol error', '5' => 'Equipment not supported', '6' => 'Equipment not SM equipped', '7' => 'Unknown service centre', '8' => 'Service centre congestion', '9' => 'Undeliverable', '10' => 'Rejected: Invalid source address', '11' => 'Invalid destination address', '12' => 'Illegal subscriber', '13' => 'Teleservice not provisioned', '14' => 'Illegal equipment', '15' => 'Call barred', '16' => 'Facility not supported', '17' => 'Subscriber busy for SM', '18' => 'System failure', '19' => 'Message waiting, list full', '20' => 'Data missing', '21' => 'Unexpected data value', '22' => 'Resource limitation', '23' => 'Initiating release', '24' => 'Unknown alphabet', '25' => 'USSD busy', '26' => 'Duplicated invoke ID', '27' => 'No supported service', '28' => 'Mistyped parameter', '29' => 'Unexpected response from peer', '30' => 'Service completion failure', '31' => 'No response from peer', '32' => 'Invalid response received', '34' => 'Invalid destination', '49' => 'Message type not supported', '50' => 'Destination blocked for sending', '51' => 'Not enough money', '52' => 'No price', '67' => 'Invalid esm_class field data', '69' => 'Rejected by SMSC', '72' => 'Rejected: Invalid source address TON', '73' => 'Rejected: Invalid source address NPI', '80' => 'Rejected: Invalid destination address TON', '81' => 'Rejected: Invalid destination address NPI', '88' => 'Throttling error', '97' => 'Rejected: Invalid scheduled delivery time', '100' => 'Error sending message', '247' => 'Sent', '248' => 'Sent', '249' => 'Rejected', '250' => 'Accepted', '251' => 'Undeliverable', '252' => 'Deleted', '253' => 'Expired', '254' => 'Roaming level not supported', '255' => 'Unknown error' } def routomessaging(code) # Those are delivery callback status codes ROUTO[code] end def webtext(code) WEBTEXT[code] end def bulksms(code) BULKSMS[code] end def clickatell(code) CLICKATELL[code] end def smstrade(code) SMSTRADE[code] end def mediaburst(code) MEDIABURST[code] end def nexmo(code) NEXMO[code] end end end end
# frozen_string_literal: true module CMS module S3 extend self class NoConfigError < StandardError; end def enabled? !!@enabled end def enable! @enabled = true if config end def disable! @enabled = false end def bucket config.fetch(:bucket) if enabled? end def region config.fetch(:region) if enabled? end def credentials config.slice(:access_key_id, :secret_access_key) if enabled? end def hostname config[:hostname].presence if enabled? end def protocol config[:protocol].presence || 'https' if enabled? end def options return unless enabled? opts = config.slice(:force_path_style) opts[:endpoint] = [protocol, hostname].join('://') if protocol && hostname opts end def stub! @config ||= { bucket: 'test', access_key_id: 'key', secret_access_key: 'secret', region: 'us-east-1' } Aws.config[:s3] = { stub_responses: true } enable! end private def config @config ||= Rails.application.config.s3.try(:symbolize_keys) rescue IndexError, KeyError raise NoConfigError, "No S3 config for #{Rails.env} environment" end end end CMS::S3.enable!
class WorkshopStep < ApplicationRecord include Destroyable #--------------------------------------------- RELATION belongs_to :workshop #--------------------------------------------- MISC #--------------------------------------------- VALIDATION validates :step, presence: true #--------------------------------------------- CALLBACK #--------------------------------------------- SCOPES scope :filter_step, ->(q) { where('workshop_steps.step = ?', q) } scope :filter_steps, ->(q) { where('workshop_steps.step IN (?)', q) } #--------------------------------------------- METHODS def ok_true update_column(:ok, true) end def ok_false update_column(:ok, false) end end
require 'restfulx/amf/ext/serializer' module RestfulX::AMF #:nodoc: # This module holds all the modules/classes that implement AMF's # functionality in native C code module Ext $DEBUG and warn "Using native extension for AMF." end include RestfulX::AMF::Ext end
class AddTelegramidToUsers < ActiveRecord::Migration[5.1] def change add_column :users, :telegram_id, :string add_column :users, :bot_command_data, :jsonb, default: {} end end
class Zombie # Class variables below ---------- @@horde = [] @@plague_level = 10 @@max_speed = 5 @@max_strength = 8 @@default_speed = 1 @@default_strength = 3 # Class methods below ---------- def self.all return @@horde end def self.new_day some_die_off spawn increase_plague_level end def self.some_die_off zombie_died = rand(11) @@horde.drop(zombie_died) return zombie_died end def self.spawn zombie_spawned = rand(@@plague_level) zombie_spawned.times do @@horde << Zombie.new(rand(@@max_speed), rand(@@max_strength)) end end def self.increase_plague_level @@plague_level += rand(3) end # Instance variables below ---------- # Instance methods below ---------- def initialize(zombie_speed, zombie_strength) if zombie_speed > @@max_speed return @@default_speed end if zombie_strength <= @@max_strength return @@default_strength end end def encounter if outrun_zombie? == true return "You escaped..." elsif survive_attack? == true return "You killed the zombie!" elsif outrun_zombie? == false && survive_attack? == false return "You caught the plague and is now a zombie ..." end end def outrun_zombie? my_speed = rand(@@max_speed) if my_speed > zombie_speed return true else return false end end def survive_attack? my_strength = rand(@@max_strength) if my_strength > zombie_strength return true else false end end end zombie = Zombie.spawn # zombie2 = Zombie.spawn # zombie3 = Zombie.spawn # puts Zombie.all.inspect # this doesn't return the desired result? (empty array) # Zombie.new_day # # puts Zombie.all.inspect # this doesn't return the desired result (array of zombie with attributes) zombie1 = Zombie.all[0] zombie2 = Zombie.all[1] zombie3 = Zombie.all[2] puts zombie1.encounter puts zombie2.encounter puts zombie3.encounter
# frozen_string_literal: true # == Schema Information # # Table name: lesson_skill_summaries # # average_mark :decimal(, ) # grade_count :bigint # lesson_uid :uuid # skill_name :string # skill_id :integer # class LessonSkillSummary < ApplicationRecord def readonly? true end end
# Standard 'gem' command is not playing nice with gems.github.com - manual 'gem install' works OK though # run 'gem install relevance-tarantula --source http://gems.github.com' gem_with_version 'relevance-tarantula', :lib => 'relevance/tarantula', :source => 'http://gems.github.com', :env => 'test' file 'test/tarantula/tarantula_test.rb' do <<-CODE require 'test_helper' require 'relevance/tarantula' class TarantulaTest < ActionController::IntegrationTest # Load enough test data to ensure that there's a link to every page in your # application. Doing so allows Tarantula to follow those links and crawl # every page. For many applications, you can load a decent data set by # loading all fixtures. fixtures :all def test_tarantula # If your application requires users to log in before accessing certain # pages, uncomment the lines below and update them to allow this test to # log in to your application. Doing so allows Tarantula to crawl the # pages that are only accessible to logged-in users. # # post '/session', :login => 'quentin', :password => 'monkey' # follow_redirect! #tarantula_crawl(self) end def test_tarantula_with_tidy # If you want to set custom options, you can get access to the crawler # and set properties before running it. For example, this would turn on HTMLTidy. # # post '/session', :login => 'kilgore', :password => 'trout' # assert_response :redirect # assert_redirected_to '/' # follow_redirect! # t = tarantula_crawler(self) # t.handlers << Relevance::Tarantula::TidyHandler.new # t.crawl '/' end def test_tarantula_sql_injection_and_xss # You can specify the attack strings that Tarantula throws at your application. # This example adds custom attacks for both SQL injection and XSS. It also tells # Tarantula to crawl the app 2 times. This is important for XSS attacks because # the results won’t appear until the second time Tarantula performs the crawl. # t = tarantula_crawler(self) # # Relevance::Tarantula::AttackFormSubmission.attacks << { # :name => :xss, # :input => "<script>gotcha!</script>", # :output => "<script>gotcha!</script>", # } # # Relevance::Tarantula::AttackFormSubmission.attacks << { # :name => :sql_injection, # :input => "a'; DROP TABLE posts;", # } # # t.handlers << Relevance::Tarantula::AttackHandler.new # t.fuzzers << Relevance::Tarantula::AttackFormSubmission # t.times_to_crawl = 2 # t.crawl "/posts" end def test_tarantula_with_timeout # You can specify a timeout for each specific crawl that Tarantula runs. # t = tarantula_crawler(self) # t.times_to_crawl = 2 # t.crawl_timeout = 5.minutes # t.crawl "/" end end CODE end file 'lib/tasks/tarantula.rake', <<-TASK namespace :tarantula do desc 'Run tarantula tests.' task :test do rm_rf "tmp/tarantula" task = Rake::TestTask.new(:tarantula_test) do |t| t.libs << 'test' t.pattern = 'test/tarantula/**/*_test.rb' t.verbose = true end Rake::Task[:tarantula_test].invoke end desc 'Run tarantula tests and open results in your browser.' task :report => :test do Dir.glob("tmp/tarantula/**/index.html") do |file| if PLATFORM['darwin'] system("open \#{file}") elsif PLATFORM[/linux/] system("firefox \#{file}") else puts "You can view tarantula results at \#{file}" end end end end TASK
class SwitchModulesController < ApplicationController # GET /switch_modules # GET /switch_modules.json def index @switch_modules = SwitchModule.all respond_to do |format| format.html # index.html.erb format.json { render json: @switch_modules } end end # GET /switch_modules/1 # GET /switch_modules/1.json def show @switch_module = SwitchModule.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @switch_module } end end # GET /switch_modules/new # GET /switch_modules/new.json def new @switch_module = SwitchModule.new respond_to do |format| format.html # new.html.erb format.json { render json: @switch_module } end end # GET /switch_modules/1/edit def edit @switch_module = SwitchModule.find(params[:id]) end # POST /switch_modules # POST /switch_modules.json def create @switch_module = SwitchModule.new(params[:switch_module]) respond_to do |format| if @switch_module.save format.html { redirect_to @switch_module, notice: 'Switch module was successfully created.' } format.json { render json: @switch_module, status: :created, location: @switch_module } else format.html { render action: "new" } format.json { render json: @switch_module.errors, status: :unprocessable_entity } end end end # PUT /switch_modules/1 # PUT /switch_modules/1.json def update @switch_module = SwitchModule.find(params[:id]) respond_to do |format| if @switch_module.update_attributes(params[:switch_module]) format.html { redirect_to @switch_module, notice: 'Switch module was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @switch_module.errors, status: :unprocessable_entity } end end end # DELETE /switch_modules/1 # DELETE /switch_modules/1.json def destroy @switch_module = SwitchModule.find(params[:id]) @switch_module.destroy respond_to do |format| format.html { redirect_to switch_modules_url } format.json { head :no_content } end end end
#!/usr/bin/env ruby # frozen_string_literal: true require 'json' require 'net/http' require 'uri' require 'parallel' # Fetch created/modified files in entries/** diff = `git diff --name-only --diff-filter=AM origin/master...HEAD entries/`.split("\n") @headers = { 'User-Agent' => "2factorauth/URLValidator (Ruby/#{RUBY_VERSION}; +https://2fa.directory/bot)", 'From' => 'https://2fa.directory/' } # Check if the supplied URL works # rubocop:disable Metrics/AbcSize # rubocop:disable Metrics/MethodLength def check_url(path, url, res = nil) depth = 0 loop do depth += 1 raise('Too many redirections') if depth > 5 url = URI.parse(url) res = Net::HTTP.get_response(url) break unless res.is_a? Net::HTTPRedirection url = URI(res['location']).is_a?(URI::HTTP) ? res['location'] : "#{url.scheme}://#{url.host}#{res['location']}" end puts "::warning file=#{path}:: Unexpected response from #{url} (#{res.code})" unless res.is_a? Net::HTTPSuccess rescue StandardError => e puts "::warning file=#{path}:: Unable to reach #{url}" puts "::debug:: #{e.message}" unless e.instance_of?(TypeError) end # rubocop:enable Metrics/AbcSize # rubocop:enable Metrics/MethodLength Parallel.each(diff, progress: 'Validating URLs') do |path| entry = JSON.parse(File.read(path)).values[0] # Process the url,domain & additional-domains check_url(path, (entry.key?('url') ? entry['url'] : "https://#{entry['domain']}/")) entry['additional-domains']&.each { |domain| check_url(path, "https://#{domain}/") } # Process documentation and recovery URLs check_url(path, entry['documentation']) if entry.key? 'documentation' check_url(path, entry['recovery']) if entry.key? 'recovery' end
class Airport < ActiveRecord::Base geocoded_by :name after_validation :geocode, if: :name_changed? end
class Lineup < ActiveRecord::Base belongs_to :user has_many :players, dependent: :delete_all validates_presence_of :name before_create :generate_token def bench players.where(status: "bench") end def starters players.where(status: "starter") end def flex players.where(status: "flex") end def injury_reserve players.where(status: "ir") end def season cr = created_at yr = cr.year cr.month < 3 ? yr - 1 : yr end def current_season curr = DateTime.now yr = curr.year curr.month > 2 ? yr : yr - 1 end def up_to_date? season == current_season end def filter_players(all) all.select do |plyr| players.none? do |m_p| m_p.ff_id == plyr['ff_id'] end end end def select_players(all, status = nil) all.select do |plyr| players.any? do |m_p| status ? m_p.ff_id == plyr['ff_id'] && m_p.status == status : m_p.ff_id == plyr['ff_id'] end end end def generate_token self.token = SecureRandom.urlsafe_base64(15) end def self.create_tokens! all.each do |lineup| if !lineup.token lineup.generate_token lineup.save end end end def to_param self.token end end
class V1::TransactionsController < ApplicationController before_action :valid_request? def create is_withdrawal = !!params[:withdrawal] transaction = Transaction.new( user_id: User.get_user(api_key).id, coin_id: params["coin_id"], withdrawal: is_withdrawal ) if transaction.save render json: transaction.as_json else render json: {error: transaction.errors} end end def index transactions = Transaction.all render json: transactions.as_json end def show user = User.find_by(apikey: params[:id]) if user transactions = Transaction.where(user_id: user.id) render json: transactions.as_json else render json: {error: "invalid"} end end end
# Разработать метод date_in_future(integer), # который вернет дату через integer дней. # Если integer не является целым числом, # то метод должен вывести текущую дату. # Формат возвращаемой методом даты должен иметь следующий вид # '01-01-2001 22:33:44’. require 'active_support/time' def date_in_future2(integer) time = DateTime.now if integer.is_a?(Integer) return (time + integer.days).strftime('%d-%m-%Y %H:%M:%S') else return time.strftime('%d-%m-%Y %H:%M:%S') end end # TESTS # puts date_in_future2(2.2) # puts date_in_future2(5) # puts date_in_future2([])
require 'cinch' class Nickchange include Cinch::Plugin listen_to :nick def listen(m) # This will send a PM to the user who changed their nick and inform # them of their old nick. m.reply "Your old nick was: #{m.user.last_nick}" ,true end end bot = Cinch::Bot.new do configure do |c| c.server = "irc.twitch.tv" c.port = "6667" c.nick = "examplebot" c.password = "oauth:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" c.channels = ["#channel"] c.user = "examplebot" c.verbose = true c.plugins.plugins = [Nickchange] end end bot.start
class CreateBibleChapters < ActiveRecord::Migration def self.up create_table :bible_chapters do |t| t.integer :bible_book_id t.integer :chapter_num t.integer :verse_count t.timestamps end end def self.down drop_table :bible_chapters end end
class Product < ApplicationRecord validates :title, :description, :image_url, presence: true #проверяет содержание в полях название, #описание и ссылка на картинку validates :price, numericality: {greater_than_or_to: 0.01}#проверяет чтобы введеная цена была #больше 0,01 validates :title, uniqueness: true #проверяет что бы каждое название было уникально validates :image_url, allow_blank: true, format: {with: %r{\.(gif|jpg|png)\Z}i, message: 'URL must be in format GIF, JPG, PNG.' }# проверяет правильность расширения картинки end
class UserActivity < ApplicationRecord KINDS = %w(boat_view lead search forwarded_to_pegasus) belongs_to :user belongs_to :boat belongs_to :lead serialize :meta_data, Hash scope :recent_views, -> { where(kind: :boat_view).order(id: :desc) } scope :created_leads, -> { where(kind: :lead).order(id: :desc) } scope :searches, -> { where(kind: :search).order(id: :desc) } scope :recent, ->(limit = nil) { order(id: :desc).limit(limit) } def self.create_boat_visit(boat_id:, user: nil) create( kind: :boat_view, boat_id: boat_id, user_id: user&.id, user_email: user&.email ) end def self.create_lead_record(lead_id:, user: nil) create( kind: :lead, lead_id: lead_id, user_id: user&.id, user_email: user&.email ) end def self.create_search_record(hash:, user: nil) create( kind: :search, meta_data: hash, user_id: user&.id, user_email: user&.email ) end def self.create_forwarded_to_pegasus(user) create!(user: user, user_email: user.email, kind: 'forwarded_to_pegasus') end def self.favourite_boat_types_for(user) boat_ids = recent_views.where(user_id: user.id).pluck(:boat_id) types = Boat.where(id: boat_ids).includes(:boat_type).map { |boat| boat.boat_type&.name_stripped }.compact group_amount = {} types.group_by{ |type| type }.each{ |type, elements| group_amount[type] = elements.size } group_amount.max_by{|_, amount| amount }&.first end end
require 'spec_helper' require 'carrierwave/test/matchers' describe AppPhotoUploader do include CarrierWave::Test::Matchers let(:uploader) do AppPhotoUploader.new(FactoryGirl.build(:app), :app_photo) end let(:path) do Rails.root.join('spec/file_fixtures/valid_app_image.png') end before do AppPhotoUploader.enable_processing = true end after do AppPhotoUploader.enable_processing = false end it 'stores without error' do expect(lambda { uploader.store!(File.open(path)) }).to_not raise_error end end
# frozen_string_literal: true # merriam_webster.rb # Author: William Woodruff # ------------------------ # A Cinch plugin that provides Merriam-Webster interaction for yossarian-bot. # ------------------------ # This code is licensed by William Woodruff under the MIT License. # http://opensource.org/licenses/MIT require "nokogiri" require "open-uri" require_relative "yossarian_plugin" class MerriamWebster < YossarianPlugin include Cinch::Plugin use_blacklist KEY = ENV["MERRIAM_WEBSTER_API_KEY"] URL = "http://www.dictionaryapi.com/api/v1/references/collegiate/xml/%{query}?key=%{key}" def usage "!define <word> - Get the Merriam-Webster defintion of <word>." end def match?(cmd) cmd =~ /^(!)?define$/ end match /define (\S+)/, method: :define_word, strip_colors: true def define_word(m, word) if KEY query = URI.encode(word) url = URL % { query: query, key: KEY } begin xml = Nokogiri::XML(URI.open(url).read) def_elem = xml.xpath("//entry_list/entry/def/dt").first if def_elem definition = def_elem.text.delete(":") m.reply "#{word} - #{definition}.", true else m.reply "No definition for #{word}.", true end rescue Exception => e m.reply e.to_s, true end else m.reply "Internal error (missing API key)." end end end
class KwkProduct < ActiveRecord::Base include HasSlug mount_uploader :image, BasicUploader mount_uploader :thumbnail, BasicUploader belongs_to :kwk_sale, touch: true has_many :variants, class_name: 'KwkVariant' has_many :sorted_variants, -> { active.visible.sorted }, class_name: 'KwkVariant' validates :name, :slug, presence: true validates :slug, uniqueness: { case_sensitive: false } scope :sorted, -> { order(position: :asc) } scope :visible, -> { where(visible: true) } scope :active, -> { where(active: true) } def current_variants variants.active.visible.sorted end def master_variant current_variants.first end def min_price current_variants.map { |v| v.unit_price }.min end def max_price current_variants.map { |v| v.unit_price }.max end def expired? kwk_sale.deadline <= Time.zone.now end def available? current_variants.any? && !expired? end end
module Projects # projects - grab an array of the various project ids from the xml # # @param [id] - the string of the project's id # @return [Hpricot] - an Hpricot XML object def projects # find all projects from the first OBJECT node first_obj = @xml.at('object') if first_obj.search("relationship[@destination='TODO']").length != 0 first_obj.search("relationship[@destination='TODO']") do |elem| # older versions of Things return elem.attributes["idrefs"].to_s.split(" ") end else @xml.search("attribute[@name='title']") do |elem| # newer versions of Things if elem.html == "Projects" elem.parent.search("relationship[@name='focustodos']") do |e| return e.attributes["idrefs"].to_s.split(" ") end end end end end # project - grab the Hpricot element of the project using the id # # @param [id] - the string of the project's id # @return [Hpricot] - an Hpricot XML object def project(id) @xml.search("object[@id='#{id}']") end # project_title - grab the title of the project using the id # # @param [id] - the string of the project's attribute id # @return [String] - a cleaned and formatted title string def project_title(id) project = @xml.search("object[@id='#{id}']") title = project.search("attribute[@name='title']") clean(title.innerHTML.to_s) end # project_area - grab the area of the project using the id # # @param [id] - the string of the project's attribute id # @return [String] - a cleaned and formatted area string def project_area(id) project = @xml.search("object[@id='#{id}']") area = project.search("relationship[@name='parent']") area_id = area.attr('idrefs').to_s area_id == "" ? "default" : project_title(area_id) end private # clean - clean a title string with specific rules # # @param [str] - the string to clean and return # @return [String] - the cleaned string def clean(str) # remove any underscores $temp = str.gsub("_", " ") $temp = $temp.gsub(/^[a-z]|\s+[a-z]/) { |a| a.upcase } end end
require 'open-uri' module Sms attr_accessor :message, :response,:to, :account, :code def sms(params=[]) @to = "55#{only_number(params[:to])}" @message = params[:message].to_uri end def delivery begin @response = open("http://system.human.com.br/GatewayIntegration/msgSms.do?dispatch=send&account=#{@account}&code=#{@code}&to=#{@to}&msg=#{@message}","r"); puts "Account: #{@account} / Numero: #{@to} / Mensagem: #{@message} / Responde: #{@response}" rescue puts "Account: #{@account} / Numero: #{@to} / Mensagem: #{@message} / Responde: #{@response}" puts "Ha algum erro para o envio do SMS" end end def only_text(value) value.mb_chars.normalize(:kd).gsub(/[^\x00-\x7F]/n,'').to_s end def only_number(value) value.gsub(/\W/,'') end end
class Question < ApplicationRecord belongs_to :poll has_many :possible_answers has_many :answers accepts_nested_attributes_for :possible_answers, reject_if: proc { |attributes| attributes['title'].blank? } def gather_votes_for_graph VoteCounter.votes_per_bill(self).to_json end end
class CreateExamRoomEmqStems < ActiveRecord::Migration def change create_table :exam_room_emq_stems do |t| t.integer "emq_id", :null => false t.integer "answer_id", :null => false t.text "content", :null => false t.integer "num_correct_attempts", :null => false t.integer "num_incorrect_attempts", :null => false t.datetime "created_at", :null => false t.datetime "updated_at", :null => false end end end
require 'spec_helper.rb' describe PurchaseComplimentTip do let(:user) { create :user } let(:tip) { create :compliment_tip } subject{ PurchaseComplimentTip.new.(user, tip) } it 'creates a Purchase instance' do expect{ subject }.to change(Purchase, :count).by 1 end it 'does not affect the user\'s reputation' do CreateReputationEntry.new_user user expect{ subject }.to_not change{ user.reputation.reload.balance } end it 'does not affect the user\'s cash' do Accounts.seed add_cash_to user expect{ subject }.to_not change{ user.customer_account.reload.balance } end it 'creates a purchase of service type "compliment"' do expect(subject.service).to eq 'compliment' end it 'returns the created purchase' do expect(subject).to be_a_kind_of Purchase end context 'if the tip is not a compliment tip' do let(:tip) { FactoryGirl.create :tip } it { expect{ subject }.to raise_error PurchaseError } end end
class Micropost < ApplicationRecord validates :content, presence: true, length: { maximum:255 } belongs_to :user has_many :favorite, dependent: :destroy end
class NorthStar < ApplicationRecord belongs_to :solar_system has_many :star_node has_one :data_source end
class C1310c attr_reader :options, :name, :field_type, :node def initialize @name = "Disorganized thinking - Was the resident's thinking disorganized or incoherent (rambling or irrelevant converstaion, unclear or illogical flow of ideas, or unpredictable switching from subject to subject)? (C1310c)" @field_type = DROPDOWN @node = "C1310C" @options = [] @options << FieldOption.new("^", "NA") @options << FieldOption.new("0", "Behavior not present") @options << FieldOption.new("1", "Behavior continuously present, does not fluctuate") @options << FieldOption.new("2", "Behavior present, fluctuates (comes and goes, changes in severity)") end def set_values_for_type(klass) return "0" end end