text stringlengths 10 2.61M |
|---|
require 'rails_helper'
describe SampleGroupCloneService do
let(:audit) { create(:audit) }
let(:common_area_type) { create(:audit_strc_type, name: 'Common Area') }
let(:sample_group) do
create(:sample_group,
name: 'My sample group',
parent_structure: audit.audit_structure,
audit_strc_type: common_area_type)
end
it 'sets and gets params' do
service = described_class.new(params: :foo)
expect(service.params).to eq :foo
end
it 'sets and gets sample_group' do
service = described_class.new(sample_group: :foo)
expect(service.sample_group).to eq :foo
end
it 'clones the sample group' do
service = described_class.new(
params: { name: 'My cloned sample group' },
sample_group: sample_group
)
service.execute!
expect(audit.audit_structure.sample_groups.map(&:name)).to eq [
'My sample group',
'My cloned sample group'
]
end
it 'clones all sampled structures' do
hallway = create(:audit_structure,
name: 'My hallway',
sample_group: sample_group,
audit_strc_type: common_area_type)
service = described_class.new(
params: { name: 'My cloned sample group' },
sample_group: sample_group
)
service.execute!
expect(service.cloned_sample_group.substructures.map(&:name)).to eq ['My hallway']
end
end
|
require 'rails_helper'
RSpec.describe User, type: :model do
before do
@user = FactoryGirl.build(:user)
end
it "should be valid" do
expect(@user).to respond_to(:email)
expect(@user).to respond_to(:password)
expect(@user).to respond_to(:password_confirmation)
expect(@user).to be_valid
expect(@user).to respond_to(:auth_token)
# expect(@user).to have_many(:products)
# TODO: Add shoulda matchers
end
it "should not be valid when email is not present" do
@user.email = ""
expect(@user).to_not be_valid
end
describe "#generate_authentication_token!" do
it "generates a unique token" do
allow(Devise).to receive(:friendly_token) { "auniquetoken123" }
@user.generate_authentication_token!
expect(@user.auth_token).to eq("auniquetoken123")
end
it "generates another token when one already has been taken" do
existing_user = FactoryGirl.create(:user, auth_token: "auniquetoken123")
@user.generate_authentication_token!
expect(@user.auth_token).not_to eq(existing_user.auth_token)
end
end
describe "products association" do
before do
@user.save
3.times { FactoryGirl.create(:product, user: @user) }
end
it "destroys the associated products on self destruct" do
products = @user.products
@user.destroy
products.each do |product|
expect(Product.find(product)).to raise_error(ActiveRecord::RecordNotFound)
end
end
end
end
|
class AddCommandsTable < ActiveRecord::Migration
def self.up
create_table :commands, :force => true do |t|
t.column :device_id, :integer
t.column :imei, :string, :limit => 30
t.column :command, :string, :limit => 100
t.column :response, :string, :limit => 100
t.column :status, :string, :limit => 100, :default => 'Processing'
t.column :start_date_time, :datetime
t.column :end_date_time, :datetime
t.column :transaction_id, :string, :limit => 25
end
end
def self.down
drop_table :commands
end
end
|
class Api::V1::TranslationsController < ApplicationController
def index
render json: Translation.order(created_at: :desc)
end
def create
@translation = Translation.create(translation_params)
render json: @translation
end
def update
@translation = Translation.find(params[:id])
@translation.update(translation_params)
render json: @translation
end
def destroy
render json: Translation.destroy(params[:id])
end
private
# Never trust parameters from the scary internet, only allow the white list through.
def translation_params
params.require(:translation).permit(:id, :title, :result)
end
end
|
require 'rails_helper'
feature 'Sign Up' do
scenario 'User can sign up and then sign out' do
visit root_path
click_on 'Sign Up'
expect(page).to have_content('Sign Up for gCamp!')
fill_in 'First Name', with: 'Thomas'
fill_in 'Last Name', with: 'Iliffe'
fill_in 'Email', with: 'tom@example.com'
fill_in 'Password', with: 'password'
fill_in 'Password Confirmation', with: 'password'
click_on 'Sign up'
expect(page).to have_content('Create Project')
expect(page).to have_content('Thomas Iliffe')
expect(page).to have_content('Sign Out')
expect(page).to have_no_content('Sign In')
click_on 'Sign Out'
expect(page).to have_content('Sign Up')
expect(page).to have_content('Sign In')
expect(page).to have_no_content('Thomas Iliffe')
end
scenario 'User cannot sign up without email/password' do
visit root_path
click_on 'Sign Up'
fill_in 'First Name', with: 'Thomas'
fill_in 'Last Name', with: 'Iliffe'
fill_in 'Password', with: 'password'
fill_in 'Password Confirmation', with: 'password'
click_on 'Sign up'
expect(page).to have_content("Email can't be blank")
expect(page).to have_no_content('Sign Out')
end
end
|
module Opity
module Resource
class << self
def new(data)
type = data[:type] || data['type']
begin
name = "Opity::Resource::#{type.capitalize}"
klass = name.constantize
klass.new(data)
rescue => e
puts e.message
puts e.backtrace.first(5).join("\n")
raise "could not find class #{name}: #{e.message}"
end
end
end
class Base < Model
attribute :name
attribute :type
attribute :environment
def options
opts = @data.dup
opts.delete(:name)
opts.delete(:type)
opts.delete(:cloud)
opts
end
def list
[self]
end
def name
"#{@data[:name]}-#{self.environment}-#{self.application}"
end
def options_string
o = options
return '' unless o.count > 0
o = o.delete_if {|k, v| v.nil?}
o.map do |k, v|
val = v.is_a?(Array) ? v.join(',') : v
"#{k}=#{val}"
end.join('; ')
end
end
end
end |
class CreateTheaters < ActiveRecord::Migration[6.0]
def change
create_table :theaters do |t|
t.references :user, null: false, foreign_key: true
t.string :name, null: false, default: ""
t.integer :prefecture_id, null: false
t.text :city, null: false
t.integer :company_id, null: false
t.integer :parking_id, null: false
t.integer :smorkingroom_id, null: false
t.text :access, null: false
t.integer :babyroom_id, null: false
t.text :remark
t.timestamps
end
end
end
|
class Captain::SignupsController < ApplicationController
# grab all players in database (populated from seed data)
def new
@player_options = Player.all.order('first_name ASC').map{ |p| ["#{p.first_name} #{p.last_name}", p.id] }
@practice_options = Practice.where(cancelled: false).order('date ASC').map{ |p| [p.date.strftime("%A %B %d"), p.id] }
end
private
helper_method :current_practice, :selected_player
def current_practice
@current_practice = Practice.find(params[:practice_id])
end
def selected_player
@selected_player = Player.find(params[:player_id])
end
end
|
class Drone < Formula
version "1.2.0"
desc "Command line client for the Drone continuous integration server."
homepage "https://github.com/recollir/homebrew-foucli"
url "https://github.com/recollir/homebrew-foucli/releases/download/drone-#{version}/drone-darwin-amd64.tar.gz"
sha256 "3df7b6abfce4488cb0df5fafbc62d77ab9c803a64082b3b9a12caa7ae91eaa20"
def install
bin.install "drone"
end
# Homebrew requires tests.
test do
assert_match "#{version}", shell_output("#{bin}/drone -v", 2)
end
end
|
class Admin::SectionsController < Admin::AdminController
def index
@sections = Section.all
respond_with @sections
end
def show
@section = Section.find(params[:id])
respond_with = @section
end
def new
@section = Section.new
respond_with @section
end
def edit
@section = Section.find(params[:id])
end
def create
@section = Section.new(params[:section])
flash[:notice] = "Section was successfully created." if @section.save
respond_with @section, :location => admin_sections_path
end
def update
@section = Section.find(params[:id])
flash[:notice] = "Section was successfully updated." if @section.update_attributes(params[:section])
respond_with @section, :location => admin_sections_path
end
def destroy
@section = Section.find(params[:id])
@section.destroy
respond_with @section, :location => admin_sections_path
end
end
|
class AddTradeDirectionToTrades < ActiveRecord::Migration[5.1]
def change
add_column :trades,:trade_direction,:bool
end
end
|
class UpdateEnvironmentsAndServersTable < ActiveRecord::Migration
def up
rename_column :environments, :environment, :name
rename_column :servers, :environment, :environment_id
change_column :servers, :environment_id, :integer
end
def down
rename_column :environments, :name, :environment
rename_column :servers, :environment_id, :environment
change_column :servers, :environment, :string
end
end
|
class Project < ActiveRecord::Base
has_many :issues
has_many :allocatedProfiles, :class_name => 'ProjectsProfiles', :dependent => :destroy
has_many :profiles, :through => :allocatedProfiles
belongs_to :client
has_many :logs, :as => :content
default_scope { order('name DESC') }
before_create :defaults
has_attached_file :image, :styles => { :thumb => "500x500#" }, :default_url => "/assets/projects/:style/missing.jpg"
validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/
attr_accessor :image_url, :totalProjectHours, :totalProjectHoursCompleted, :sprints
def defaults
self.hoursPerDay = 8 if self.hoursPerDay.blank?
self.daysPerSprint = 7 if self.daysPerSprint.blank?
self.isArchived = false
return true
end
def attributes
super.merge({'image_url' => image_url, 'totalProjectHours' => totalProjectHours, 'totalProjectHoursCompleted' => totalProjectHoursCompleted, 'sprints' => sprints, 'currentSprint' => currentSprint, 'sprint' => sprint})
end
def image_url
return self.image.url(:thumb)
end
def projectCode
return (self.client.name[0,3] + self.name[0,3]).upcase
end
def totalProjectHours
hours = 0
self.issues.each do |issue|
hours += issue.productionEstimate || 0
hours += issue.testingEstimate || 0
end
return hours
end
def totalProjectHoursCompleted
hours = 0
self.issues.each do |issue|
if(issue.status == 'closed' || issue.status == 'ready-for-production')
hours += issue.productionEstimate || 0
hours += issue.testingEstimate || 0
end
end
return hours
end
def currentSprintDayNumber
if self.projectStartDate.present?
days = (((Time.now - Time.at(self.projectStartDate)).to_i / (24 * 60 * 60)) + 1) - ((self.sprint-1) * self.daysPerSprint)
return (days > self.daysPerSprint-1) ? self.daysPerSprint-1 : days
else
return nil
end
end
def sprints
sprintArray = []
# return sprintArray if self.projectStartDate.blank?
[-1, 0, 1, 2, 3, 4, 5].each do |i|
isBacklog = (i == -1 || i == 0)
currentSprintStartDate = (self.projectStartDate.present?) ? self.projectStartDate + ((i-1) * self.daysPerSprint).days : nil
totalHours = 0
totalCompletedHours = 0
self.issues.each do |issue|
if(issue.sprint == i)
totalHours += issue.productionEstimate || 0
totalHours += issue.testingEstimate || 0
end
if(issue.sprint == i && issue.isCompleted)
totalCompletedHours += issue.productionEstimate || 0
totalCompletedHours += issue.testingEstimate || 0
end
end
days = []
if !isBacklog
workday = 0
completedHoursCumulative = totalHours
(0 .. (self.daysPerSprint-1)).each do |j|
targetBurndownHours = totalHours
if self.projectStartDate.present? && !((self.projectStartDate + j.days).strftime('%a') == 'Sat' || (self.projectStartDate + j.days).strftime('%a') == 'Sun')
workday += 1
targetBurndownHours = [totalHours - (self.hoursPerDay * workday), 0].max
else
targetBurndownHours = (days.last.present? && days.last[:targetBurndownHours].present?) ? days.last[:targetBurndownHours] : totalHours
end
completedHours = (self.projectStartDate.present?) ? self.totalHoursCompletedForSprintDay((currentSprintStartDate + j.days).strftime('%Y-%m-%d'), i) : 0;
completedHoursCumulative -= completedHours
days << {
:day => j + 1,
:date => (self.projectStartDate.present?) ? currentSprintStartDate + j.days : nil,
:isToday => (self.projectStartDate.present?) ? ((currentSprintStartDate + j.days).strftime('%Y-%m-%d') == Date.today.to_s) : false,
:workDay => self.projectStartDate.present? && (!((currentSprintStartDate + j.days).strftime('%a') == 'Sat' || (currentSprintStartDate + j.days).strftime('%a') == 'Sun')) ? workday : nil,
:isWorkDay => self.projectStartDate.present? && (!((currentSprintStartDate + j.days).strftime('%a') == 'Sat' || (currentSprintStartDate + j.days).strftime('%a') == 'Sun')),
:targetBurndownHours => targetBurndownHours,
:totalHoursLeft => completedHoursCumulative,
:hoursCompletedToday => completedHours
}
end
end
sprintArray << {
:sprint => i,
:currentDay => (i == self.sprint && !isBacklog) ? self.currentSprintDayNumber : nil,
:startDate => (self.projectStartDate.present? && !isBacklog) ? self.projectStartDate + ((i-1)*self.daysPerSprint).days : nil,
:totalHours => totalHours,
:totalCompletedHours => totalCompletedHours,
:days => days
}
end
return sprintArray
end
def sprint
return (self.projectStartDate.nil?) ? -1 : ((((Time.now - Time.at(self.projectStartDate)).to_i / (24 * 60 * 60)) + 1) / self.daysPerSprint).floor + 1
end
def currentSprint
if self.projectStartDate.present?
return self.sprints[self.sprint + 1]
else
return []
end
end
def totalHoursCompletedForSprintDay(comparatorDate, sprint)
hours = 0
date = Date.parse(comparatorDate)
self.issues.each do |issue|
if issue.isCompleted && issue.sprint == sprint && date.strftime("%Y %m %d") == issue.completedDateTime.strftime("%Y %m %d")
hours += issue.productionEstimate || 0
hours += issue.testingEstimate || 0
end
end
return hours
end
end
|
require 'rails_helper'
RSpec.describe ProcessingMailbox, type: :mailbox do
context 'with no associated profile' do
subject do
receive_inbound_email_from_mail(
from: 'from-address@example.com',
to: 'any-old-address@example.com',
subject: 'Subject Line',
body: "I'm a sample body"
)
end
it 'should not create a message object' do
expect { subject }.to change(Message, :count).by(0)
end
it 'should bounce the message' do
expect(subject.status).to eq('bounced')
end
end
context 'with an associated profile' do
subject do
profile = FactoryBot.create(:profile)
receive_inbound_email_from_mail(
from: 'from-address@example.com',
to: profile.email_address,
subject: 'Subject Line',
body: "I'm a sample body"
)
end
it 'should create a message object' do
expect { subject }.to change(Message, :count).by(1)
end
it 'should mark the message delivered' do
expect(subject.status).to eq('delivered')
end
end
end
|
# ruby -r "./regression_tests/scrape_apk.rb" -e "ScrapeApk.new.execute()"
require 'rubygems'
require 'fileutils'
require 'nokogiri'
require 'CSV'
require 'zip'
require 'diffy'
require './regression_tests/download_app.rb'
class ScrapeApk
def initialize
@apk_path = ("/Users/ericmckinney/desktop/android-regression/*new")
end
def execute
move_csvs
check_for_android_zips
locate_apk
scrape
add_to_new_csv
end
def move_csvs
Dir.chdir("/Users/ericmckinney/Desktop/scheme_discovery/regression_tests/csv_compare")
FileUtils.rm_rf("./old")
FileUtils.mv("./new","./old")
Dir.mkdir("/Users/ericmckinney/Desktop/scheme_discovery/regression_tests/csv_compare/new")
end
def check_for_android_zips
Dir.foreach(@apk_path) do |folder|
if folder.include? '.zip'
extract_zip(folder, @apk_path)
end
end
end
def extract_zip(file, destination)
begin
FileUtils.mkdir_p(destination)
file = "#{destination}/#{file}"
Zip::File.open(file) do |zip_file|
zip_file.each do |f|
fpath = File.join(destination, f.name)
FileUtils.mkdir_p(File.dirname(fpath))
zip_file.extract(f, fpath) unless File.exist?(fpath)
zip_file.delete
end
rescue => e
"Error: #{e}"
end
end
end
def locate_apk
Dir.chdir(@apk_path)
Dir.foreach(@apk_path) do |folder|
next if folder == '.' or folder == '..' or folder.include? '.DS_Store' or folder.include? '.apk'
end
end
def scrape
begin
Dir.chdir(@apk_path)
Dir.foreach(@apk_path) do |folder|
next unless folder.include? '.apk'
@apk_name = folder
Dir.chdir(@apk_path)
system "apktool d #{@apk_path}/#{@apk_name}"
scrape_manifest
add_to_new_csv
rescue => e
puts "Error: #{e}"
end
end
end
def scrape_manifest
manifest_file_name = "#{@apk_path}/#{@apk_name}".gsub(".apk","")
Dir.chdir(manifest_file_name)
doc = Nokogiri.parse(File.read("AndroidManifest.xml"))
filterData = "intent-filter.data."
@csv_array = []
package_name = doc.search("manifest").each do |i|
i.each do |att_name, att_value|
if att_name.include? "package"
att_value = "package = '#{att_value}'"
@csv_array << att_value
puts "#" * 100
puts att_value
end
end
end
android_keywords = doc.search("data").each do |i|
i.each do |att_name, att_value|
links = "#{att_name} = '#{att_value}'"
puts "#"*100
@csv_array << links
puts links
end
end
end
def add_to_new_csv
Dir.chdir("/Users/ericmckinney/Desktop/scheme_discovery/regression_tests/csv_compare/new")
@full_path = "#{@apk_name}.csv"
File.open("#{@apk_name}.csv", "w") do |f|
@csv_array.each do |row|
f.puts row
end
end
end
def csv_name
return @full_path
end
# TODO: Delete apps in both `ios-apps` and `android-apps` directories.
def run_ios_script
IosSchemeDiscovery.new(@full_path).execute
end
end
# Run get_versions.rb
# 1. Loop through update_diffs and grab anything with a '+'
# 1. Delete *old directory, rename *new directory to *old directory, create *new directory
# 2. Download the app using the download_app class
# 3. Rename the apk to be the package - example: `com.linkein.android.apk`
# 4. Move the app to the *new directory
# 5. Extract if it's a zip
# 6. Scrape
# 7. Check if CSV is in csv_compare/new, if it is check to see if it is in csv_compare/old, if it is delete from old and move new to old, if it's not move new to old
# 8. Create CSV and place in /new
# 9. if old/new are identicle, compare with diffy
#
|
# Are You There?
# Using the following code, print true if colors includes the color 'yellow' and print false if it doesn't.
# Then, print true if colors includes the color 'purple' and print false if it doesn't.
# colors = 'blue pink yellow orange'
colors = 'blue pink yellow orange'
# colors.split(' ').each { |color| puts color.include?('yellow') }
puts colors.split(' ').include?('yellow')
puts colors.include?('purple')
# launch school solution
# colors = 'blue pink yellow orange'
# puts colors.include?('yellow')
# puts colors.include?('purple')
# if colors.include?('yellow')
# puts 'true'
# elsif colors.include?('purple')
# puts 'false'
# end
# case colors
# when 'yellow' then puts "true"
# when 'purple' then puts 'false'
# end
# Expected output:
# true
# false |
require "test/unit"
def smallest_spread_day(days)
min_day = days.min { |a, b| (a["MxT"] - a["MnT"]) <=> (b["MxT"] - b["MnT"]) }
min_day["Dy"]
end
def load_weather(path)
padded_lines = File.open(path).map { |line| '%-90.90s' % line }
days = padded_lines.map do |line|
{
"Dy" => line.slice(2,2).to_i,
"MxT" => line.slice(6,4).gsub(/\D/, '').to_f,
"MnT" => line.slice(12,4).gsub(/\D/, '').to_f
}
end
days.select { |d| d["Dy"] > 0 }
end
class TestWeather < Test::Unit::TestCase
def test_smallest_spread
test_days = [
{ "Dy" => 1, "MxT" => 60.0, "MnT" => 55.0 },
{ "Dy" => 2, "MxT" => 56.0, "MnT" => 55.0 },
{ "Dy" => 3, "MxT" => 65.0, "MnT" => 55.0 } ]
assert_equal(2, smallest_spread_day(test_days))
end
def test_load_Weather
days = load_weather('weather.dat')
assert_equal({ "Dy" => 1, "MxT" => 88.0, "MnT" => 59.0 }, days[0] )
end
def test_find_smallest_spread
days = load_weather('weather.dat')
assert_equal(14, smallest_spread_day(days))
end
end
|
#TODO:- Use filenames instead of ids as keys.
# - Change this to just handle routes and pass the coding on to external objects.
# - code reloading
require 'sinatra/base'
require 'sinatra/contrib'
require 'sequel'
require 'rack-flash'
require_relative './admin'
require_relative './report'
require_relative './helpers'
module Crossbeams
module DataminerPortal
class ConfigMerger
# Write a new config file by applying the client-specific settings over the defaults.
def self.merge_config_files(base_file, over_file, new_config_file_name)
f = File.open(new_config_file_name, 'w')
YAML.dump(YAML.load_file(base_file).merge(YAML.load_file(over_file)), f)
f.close
hold = File.readlines(new_config_file_name)[1..-1].join
File.open(new_config_file_name,"w") {|fw| fw.write(hold) }
end
end
class WebPortal < Sinatra::Base
register Sinatra::Contrib
register Crossbeams::DataminerPortal::Admin
register Crossbeams::DataminerPortal::Report
helpers Sinatra::DataminerPortalHelpers
configure do
enable :logging
# mkdir log if it does not exist...
Dir.mkdir('log') unless Dir.exist?('log')
file = File.new("log/dm_#{settings.environment}.log", 'a+')
file.sync = true
use Rack::CommonLogger, file
enable :sessions
use Rack::Flash, :sweep => true
set :environment, :production
set :root, File.dirname(__FILE__)
# :method_override - use for PATCH etc forms? http://www.rubydoc.info/github/rack/rack/Rack/MethodOverride
set :app_file, __FILE__
# :raise_errors - should be set so that Rack::ShowExceptions or the server can be used to handle the error...
enable :show_exceptions # because we are forcing the environment to production...
set :appname, 'tst'
set :url_prefix, ENV['DM_PREFIX'] ? "#{ENV['DM_PREFIX']}/" : ''
set :protection, except: :frame_options # so it can be loaded in another app's iframe...
set :base_file, "#{FileUtils.pwd}/config/dm_defaults.yml"
set :over_file, "#{FileUtils.pwd}/config/dm_#{ENV['DM_CLIENT'] || 'defaults'}.yml"
set :new_config_file_name, "#{FileUtils.pwd}/config/dm_config_file.yml" # This could be a StringIO...
end
if settings.base_file == settings.over_file
FileUtils.cp(settings.base_file, settings.new_config_file_name)
else
ConfigMerger.merge_config_files(settings.base_file, settings.over_file, settings.new_config_file_name)
end
config_file settings.new_config_file_name
# TODO: Need to see how this should be done when running under passenger/thin/puma...
Crossbeams::DataminerPortal::DB = Sequel.postgres(settings.database['name'], :user => settings.database['user'], :password => settings.database['password'], :host => settings.database['host'] || 'localhost')
# helpers do
# end
get '/' do
erb "<a href='/#{settings.url_prefix}index'>DATAMINER REPORT INDEX</a> | <a href='/#{settings.url_prefix}admin'>Admin index</a>"
end
get '/index' do
# TODO: sort report list, group, add tags etc...
rpt_list = DmReportLister.new(settings.dm_reports_location).get_report_list(persist: true)
erb(<<-EOS)
<h1>Dataminer Reports</h1>
<ol><li>#{rpt_list.map {|r| "<a href='/#{settings.url_prefix}report/#{r[:id]}'>#{r[:caption]}</a>" }.join('</li><li>')}</li></ol>
<p><a href='/#{settings.url_prefix}admin'>Admin index</a></p>
EOS
end
end
end
end
# Could we have two dm's connected to different databases?
# ...and store each set of yml files in different dirs.
# --- how to use the same gem twice on diferent routes?????
#
|
"current" {
"dt": 1595243443,
"sunrise": 1595243663,
"sunset": 1595296278,
"temp": 293.28,
"feels_like": 293.82,
"pressure": 1016,
"humidity": 100,
"dew_point": 293.28,
"uvi": 10.64,
"clouds": 90,
"visibility": 10000,
"wind_speed": 4.6,
"wind_deg": 310,
"weather": [
{
"id": 501,
"main": "Rain",
"description": "moderate rain",
"icon": "10n"
},
{
"id": 201,
"main": "Thunderstorm",
"description": "thunderstorm with rain",
"icon": "11n"
}
],
"rain": {
"1h": 2.93
}
}
# Icon URL http://openweathermap.org/img/wn/10d@2x.png Just have to interoplate in the icon id
|
class Grid
attr_accessor :status_line
AXE_LETTERS = %w( A B C D E F G H I J )
AXE_DIGGITS = %w( 1 2 3 4 5 6 7 8 9 10 )
HIT_CHAR = 'X'
NO_SHOT_CHAR = '.'
MISS_CHAR = '-'
def initialize
@matrix = []
@fleet = []
end
def build(matrix, fleet = nil)
@matrix = matrix
@fleet = fleet
self
end
def show
print_header
setup_with_fleet if @fleet
@matrix.each_with_index do |grow, index|
Grid.row("#{ AXE_LETTERS[index] } #{ grow.join(' ') }")
end
end
def self.row(txt)
return nil if ENV['RACK_ENV'] == 'test'
puts txt if txt
end
private
def setup_with_fleet
if @fleet
for ship in @fleet
for coordinates in ship.location
@matrix[coordinates[0]][coordinates[1]] = HIT_CHAR
end
end
end
@matrix
end
def print_header
return nil if ENV['RACK_ENV'] == 'test'
puts "=" * AXE_DIGGITS.size*3
puts status_line
puts " #{AXE_DIGGITS.join(' ')}"
end
end
|
require "rails_helper"
RSpec.describe CreateAdjustment do
let(:activity) { double("activity", id: "xyz321") }
let(:report) { double("report", state: "active", id: "abc123") }
let(:user) { double("user") }
let(:adjustment) do
double(
"adjustment",
errors: [],
build_comment: double,
build_detail: double,
parent_activity: activity
)
end
let(:creator) { described_class.new(activity: activity) }
let(:history_recorder) do
instance_double(HistoryRecorder, call: double)
end
describe "#call" do
before do
allow(Report).to receive(:find).and_return(report)
allow(Report).to receive(:for_activity).and_return([report])
allow(Adjustment).to receive(:new).and_return(adjustment)
allow(adjustment).to receive(:save).and_return(adjustment)
allow(HistoryRecorder).to receive(:new).and_return(history_recorder)
end
let(:valid_attributes) do
{report: report,
value: BigDecimal("100.01"),
comment: "A typo in the original value",
user: user,
adjustment_type: "Actual",
financial_quarter: 2,
financial_year: 2020}
end
it "uses Report#for_activity to verify that the given report is associated " \
"with the given Activity" do
creator.call(attributes: valid_attributes)
expect(Report).to have_received(:for_activity).with(activity)
end
it "initialises an Adjustment with the given attrs" do
creator.call(attributes: valid_attributes)
expect(Adjustment).to have_received(:new).with(
parent_activity: activity,
report: report,
value: BigDecimal("100.01"),
financial_quarter: 2,
financial_year: 2020
)
end
it "builds a comment" do
creator.call(attributes: valid_attributes)
expect(adjustment).to have_received(:build_comment)
.with(
body: "A typo in the original value",
commentable: adjustment,
report: report
)
end
it "builds a detail with the user and the adjustment type" do
creator.call(attributes: valid_attributes)
expect(adjustment).to have_received(:build_detail)
.with(
user: user,
adjustment_type: "Actual"
)
end
it "attempts to persist the new Adjustment" do
creator.call(attributes: valid_attributes)
expect(adjustment).to have_received(:save)
end
context "when creation is successful" do
it "returns a Result object with a *true* flag" do
expect(creator.call(attributes: valid_attributes)).to eq(
Result.new(true, adjustment)
)
end
it "asks the HistoryRecorder to handle the changes" do
changes_to_tracked_attributes = {
value: [nil, valid_attributes.fetch(:value)],
financial_quarter: [nil, valid_attributes.fetch(:financial_quarter)],
financial_year: [nil, valid_attributes.fetch(:financial_year)],
comment: [nil, valid_attributes.fetch(:comment)],
adjustment_type: [nil, valid_attributes.fetch(:adjustment_type)]
}
creator.call(attributes: valid_attributes)
expect(HistoryRecorder).to have_received(:new).with(user: user)
expect(history_recorder).to have_received(:call).with(
changes: changes_to_tracked_attributes,
reference: "Adjustment to Actual",
activity: adjustment.parent_activity,
trackable: adjustment,
report: report
)
end
end
context "when creation is unsuccessful" do
before { allow(adjustment).to receive(:errors).and_return(["validation error"]) }
it "returns a Result object with a *false* flag" do
expect(creator.call(attributes: valid_attributes)).to eq(
Result.new(false, adjustment)
)
end
it "does NOT ask the HistoryRecorder to handle the changes" do
creator.call(attributes: valid_attributes)
expect(HistoryRecorder).not_to have_received(:new)
end
end
context "when an error is raised by the Adjustment model" do
before do
allow(Adjustment).to receive(:new).and_raise(
Exception, "Unexpected error"
)
end
it "allows the error to bubble up to the caller" do
expect { creator.call(attributes: valid_attributes) }
.to raise_error(Exception, "Unexpected error")
end
end
context "when the given report is not in an *editable* state" do
before do
allow(report).to receive(:state).and_return("approved")
end
it "raises an error with a message identifying the problem report" do
expect { creator.call(attributes: {report: report}) }
.to raise_error(
CreateAdjustment::AdjustmentError,
"Report #abc123 is not in an editable state"
)
end
it "does not try to create an Adjustment" do
begin
creator.call(attributes: {report: report})
rescue CreateAdjustment::AdjustmentError
# we're interested in what does or doesn't happen after the error is raised
end
expect(Adjustment).not_to have_received(:new)
end
end
context "when the given report is in any *editable* state" do
Report::EDITABLE_STATES.each do |editable_state|
before do
allow(report).to receive(:state).and_return(editable_state)
end
it "does not raise an error when report is in *#{editable_state}* state" do
expect { creator.call(attributes: valid_attributes) }.not_to raise_error
end
end
end
context "when the given report is not associated with the activity" do
before { allow(Report).to receive(:for_activity).and_return([]) }
it "raises an error with a message identifying the problem report" do
expect { creator.call(attributes: {report: report}) }
.to raise_error(
CreateAdjustment::AdjustmentError,
"Report #abc123 is not associated with Activity #xyz321"
)
end
it "does not try to create an Adjustment" do
begin
creator.call(attributes: {report: report})
rescue CreateAdjustment::AdjustmentError
# we're interested in what does or doesn't happen after the error is raised
end
expect(Adjustment).not_to have_received(:new)
end
end
end
end
|
class State < ApplicationRecord
belongs_to :country
has_many :cities, dependent: :destroy
has_many :users, dependent: :nullify
validates :name, presence: true, uniqueness: { case_sensitive: false }
end
|
class CreateEloRatings < ActiveRecord::Migration
def change
create_table :elo_ratings do |t|
t.belongs_to :player, index: true
t.integer :rating
t.timestamps null: false
end
add_foreign_key :elo_ratings, :players
end
end
|
class BackboneUiGenerator < Rails::Generators::Base
def do
base = File.expand_path("#{File.dirname(__FILE__)}/../..")
source = "#{base}/public/assets/backbone_ui"
destination = "#{Rails.root}/public/assets"
source_ui_layout = "#{base}/app/views/layouts/ui.html.erb"
destination_ui_layout = "#{Rails.root}/app/views/layouts/"
source_ui_controller = "#{base}/app/controllers/ui_controller.rb"
destination_controllers_dir = "#{Rails.root}/app/controllers"
source_stylesheets = "#{base}/app/assets/stylesheets"
destination_stylesheets = "#{Rails.root}/public/assets"
raise ArgumentError, "backbone_ui already present at: #{destination}/backbone_ui" if File.directory? "#{destination}/backbone_ui"
raise ArgumentError, "You already have a layout at: #{destination_ui_layout}/ui.html.erb" if File.exists? "#{destination_ui_layout}/ui.html.erb"
raise ArgumentError, "You already have a controller at: #{destination_controllers_dir}/ui_controller.rb" if File.exists? "#{destination_controllers_dir}/ui_controller.rb"
raise ArgumentError, "You already have a file named #{Rails.root}/app/views/ui/index.html.erb" if File.exists? "#{Rails.root}/app/views/ui/index.html.erb"
FileUtils.mkdir_p "#{Rails.root}/app/views/ui"
FileUtils.touch "#{Rails.root}/app/views/ui/index.html.erb"
FileUtils.mkdir_p destination unless File.directory? destination
FileUtils.cp_r source, destination
FileUtils.cp source_ui_layout, destination_ui_layout
FileUtils.cp source_ui_controller, "#{destination_controllers_dir}/ui_controller.rb"
FileUtils.cp_r source_stylesheets, destination_stylesheets
end
end
|
module Optimizely
class Error < StandardError; end
class InvalidAudienceError < Error
# Raised when an invalid audience is provided
def initialize(msg = 'Provided audience is not in datafile.')
super
end
end
class InvalidAttributeError < Error
# Raised when an invalid attribute is provided
def initialize(msg = 'Provided attribute is not in datafile.')
super
end
end
class InvalidAttributeFormatError < Error
# Raised when attributes are provided in an invalid format (e.g. not a Hash)
def initialize(msg = 'Attributes provided are in an invalid format.')
super
end
end
class InvalidDatafileError < Error
# Raised when an invalid datafile is provided
def initialize(msg = 'Provided datafile is in an invalid format.')
super
end
end
class InvalidErrorHandlerError < Error
# Raised when an invalid error handler is provided
def initialize(msg = 'Provided error_handler is in an invalid format.')
super
end
end
class InvalidEventDispatcherError < Error
# Raised when an invalid event dispatcher is provided
def initialize(msg = 'Provided event_dispatcher is in an invalid format.')
super
end
end
class InvalidExperimentError < Error
# Raised when an invalid experiment key is provided
def initialize(msg = 'Provided experiment is not in datafile.')
super
end
end
class InvalidGoalError < Error
# Raised when an invalid event key is provided
def initialize(msg = 'Provided event is not in datafile.')
super
end
end
class InvalidLoggerError < Error
# Raised when an invalid logger is provided
def initialize(msg = 'Provided logger is in an invalid format.')
super
end
end
class InvalidVariationError < Error
# Raised when an invalid variation key or ID is provided
def initialize(msg = 'Provided variation is not in datafile.')
super
end
end
end
|
require File.join(Dir.pwd, 'spec', 'spec_helper')
describe 'Experian::DataDictionary y000' do
context 'valid lookup' do
it { expect( Experian::DataDictionary.lookup('y000',' ') ).to eq('Non-match') }
it { expect( Experian::DataDictionary.lookup('y000','S') ).to eq('Census State') }
it { expect( Experian::DataDictionary.lookup('y000','C') ).to eq('Census County') }
it { expect( Experian::DataDictionary.lookup('y000','T') ).to eq('Census Tract') }
it { expect( Experian::DataDictionary.lookup('y000','B') ).to eq('Census Block Group') }
end
context 'invalid lookup' do
it { expect( Experian::DataDictionary.lookup('y000','F') ).to be_nil }
it { expect( Experian::DataDictionary.lookup('y000','PE') ).to be_nil }
it { expect( Experian::DataDictionary.lookup('y000','GG') ).to be_nil }
it { expect( Experian::DataDictionary.lookup('y000','DOG') ).to be_nil }
end
end |
# Program of Getter, Setter & Initialize method in RUBY CLASS
class Rectangle
#constructor
def initialize(l,b)
@length = l
@breadth = b
end
#Setter
def setLength=(value)
@length = value
end
def setBreadth=(value)
@breadth = value
end
#Getter
def getLength
return @length
end
def getBreadth
return @breadth
end
#Area of rectangle
def calculateArea
return @length * @breadth
end
end
#Creating an object
rect = Rectangle.new(30,50)
#using setters
rect.setLength=130
rect.setBreadth=200
x = rect.getLength
y = rect.getBreadth
area = rect.calculateArea
puts "The length of rectange is: #{x}"
puts "The breadth of rectange is: #{y}"
puts "The Area is: #{area}" |
# Copyright (c) 2019 Danil Pismenny <danil@brandymint.ru>
# frozen_string_literal: true
# New state for processor
class StrategyState
include RedisModel
include StrategyActivation
attribute :created_orders, Array[PersistedOrder]
attribute :maker_pid, Integer
attribute :best_ask_price, BigDecimal
attribute :best_bid_price, BigDecimal
attribute :last_error_message, String
attribute :acted_at, Time
attribute :last_errors, Array[String]
end
|
#
# Cookbook:: jnj_chef_stack
# Spec:: default
#
# Copyright:: 2017, The Authors, All Rights Reserved.
require 'spec_helper'
describe 'jnj_chef_stack::frontend' do
context 'When all attributes are default, on an unspecified platform' do
let(:chef_run) do
ChefSpec::ServerRunner.new(platform: 'centos', version: '7.0') do |node, server|
server.create_environment('_default', default_attributes: {})
# Assign the environment to the node
node.chef_environment = '_default'
server.create_data_bag('chef_stack',
'infra_secrets' => parse_data_bag('chef_stack/infra_secrets.json'))
end.converge(described_recipe)
end
before do
allow_any_instance_of(Chef::Recipe).to receive(:read_env_secret).with('backend_secrets')\
.and_return(parse_data_bag('chef_stack/infra_secrets.json')['_default']['backend_secrets'])
allow_any_instance_of(Chef::Recipe).to receive(:read_env_secret).with('frontend_secrets')\
.and_return(parse_data_bag('chef_stack/infra_secrets.json')['_default']['frontend_secrets'])
allow_any_instance_of(Chef::Recipe).to receive(:read_env_secret).with('certificates')\
.and_return(parse_data_bag('chef_stack/infra_secrets.json')['_default']['certificates'])
allow_any_instance_of(Chef::Recipe).to receive(:search_for_nodes).and_return([{ 'fqdn' => 'hostname' }])
end
it 'converges successfully' do
expect { chef_run }.to_not raise_error
end
end
end
|
require 'tzinfo/timezone_definition'
module TZInfo
module Definitions
module Asia
module Taipei
include TimezoneDefinition
timezone 'Asia/Taipei' do |tz|
tz.offset :o0, 29160, 0, :LMT
tz.offset :o1, 28800, 0, :CST
tz.offset :o2, 28800, 3600, :CDT
tz.transition 1895, 12, :o1, 193084733, 80
tz.transition 1945, 4, :o2, 14589457, 6
tz.transition 1945, 9, :o1, 19453833, 8
tz.transition 1946, 4, :o2, 14591647, 6
tz.transition 1946, 9, :o1, 19456753, 8
tz.transition 1947, 4, :o2, 14593837, 6
tz.transition 1947, 9, :o1, 19459673, 8
tz.transition 1948, 4, :o2, 14596033, 6
tz.transition 1948, 9, :o1, 19462601, 8
tz.transition 1949, 4, :o2, 14598223, 6
tz.transition 1949, 9, :o1, 19465521, 8
tz.transition 1950, 4, :o2, 14600413, 6
tz.transition 1950, 9, :o1, 19468441, 8
tz.transition 1951, 4, :o2, 14602603, 6
tz.transition 1951, 9, :o1, 19471361, 8
tz.transition 1952, 2, :o2, 14604433, 6
tz.transition 1952, 10, :o1, 19474537, 8
tz.transition 1953, 3, :o2, 14606809, 6
tz.transition 1953, 10, :o1, 19477457, 8
tz.transition 1954, 3, :o2, 14608999, 6
tz.transition 1954, 10, :o1, 19480377, 8
tz.transition 1955, 3, :o2, 14611189, 6
tz.transition 1955, 9, :o1, 19483049, 8
tz.transition 1956, 3, :o2, 14613385, 6
tz.transition 1956, 9, :o1, 19485977, 8
tz.transition 1957, 3, :o2, 14615575, 6
tz.transition 1957, 9, :o1, 19488897, 8
tz.transition 1958, 3, :o2, 14617765, 6
tz.transition 1958, 9, :o1, 19491817, 8
tz.transition 1959, 3, :o2, 14619955, 6
tz.transition 1959, 9, :o1, 19494737, 8
tz.transition 1960, 5, :o2, 14622517, 6
tz.transition 1960, 9, :o1, 19497665, 8
tz.transition 1961, 5, :o2, 14624707, 6
tz.transition 1961, 9, :o1, 19500585, 8
tz.transition 1974, 3, :o2, 133977600
tz.transition 1974, 9, :o1, 149785200
tz.transition 1975, 3, :o2, 165513600
tz.transition 1975, 9, :o1, 181321200
tz.transition 1979, 6, :o2, 299520000
tz.transition 1979, 9, :o1, 307465200
end
end
end
end
end
|
module Emarsys
module Broadcast
class ImportStatus
attr_accessor :column_count,
:created,
:error,
:file_size,
:imported_count,
:invalid_count,
:status,
:updated
def initialize(status)
@status = status
yield self
self
end
def to_s
if error.present?
"#{status} with #{error}"
else
"#{status} with #{column_count} columns, #{imported_count} imported emails of which #{invalid_count} were invalid"
end
end
end
end
end
|
module Unsplash # :nodoc:
# Unsplash Search operations
class Search < Client
class << self
# Helper class to facilitate search on multiple classes
# @param url [String] Url to be searched into
# @param klass [Class] Class to instantiate the contents with
# @param params [Hash] Params for the search
def search(url, klass, params)
list = JSON.parse(connection.get(url, params).body)
list["results"].map do |content|
klass.new content.to_hash
end
end
end
end
end
|
class Address < ActiveRecord::Base
belongs_to :user
belongs_to :state_province
validates :address1, :city, :state_province, :first_name, :last_name, :user_id, :postal_code, presence: true
end
|
class User < ActiveRecord::Base
has_secure_password
has_many :articles
has_many :comments
validates :username, uniqueness: true, length: { in: 4..12 }, on: :create
validates :first_name, :last_name, presence: true
validates :email, presence: true, uniqueness: true, on: :create
validates :password, confirmation: true, length: { in: 6..20 }, on: :create
validates :password_confirmation, presence: true, on: :create
mount_uploader :picture, PictureUploader
extend FriendlyId
friendly_id :username, use: :slugged
def admin?
self.admin == true
end
end |
require("minitest/autorun")
require("minitest/rg")
require_relative("../Drink")
require_relative("../Customer")
require_relative("../Pub")
class TestCustomer < MiniTest::Test
def setup
@customer1 = Customer.new("Neil", 30, 45, 0)
@customer2 = Customer.new("Kim", 50, 41, 0)
@drink1 = Drink.new("beer", 3, 1)
@drink2 = Drink.new("beer", 3, 1)
@drink3 = Drink.new("beer", 3, 1)
@drink4 = Drink.new("wine", 4, 2)
@drink5 = Drink.new("wine", 4, 2)
@drink6 = Drink.new("wine", 4, 2)
@drink7 = Drink.new("Gin", 5, 3)
@drink8 = Drink.new("Gin", 5, 3)
@drink9 = Drink.new("Gin", 5, 3)
@pub = Pub.new("Clansman", 500,[@drink1, @drink2, @drink3, @drink4, @drink5, @drink6, @drink7, @drink8, @drink9])
end
def test_customer_name
assert_equal("Neil", @customer1.name)
end
def test_customer_wallet
assert_equal(50, @customer2.wallet)
end
def test_customer_age
assert_equal(45, @customer1.age)
end
def test_wallet_decrease
@customer2.buy_drink(@drink4)
assert_equal(46, @customer2.wallet)
end
def test_drunkenness
assert_equal(0, @customer1.drunkenness)
end
def test_drunk_level
@customer1.drunk_level(@drink4, @customer1)
assert_equal(2, @customer1.drunkenness)
end
end
|
require File.expand_path("../lib/sequel/version", __FILE__)
SEQUEL_GEMSPEC = Gem::Specification.new do |s|
s.name = 'sequel'
s.version = Sequel.version
s.platform = Gem::Platform::RUBY
s.extra_rdoc_files = ["README.rdoc", "CHANGELOG", "MIT-LICENSE"] + Dir["doc/*.rdoc"] + Dir['doc/release_notes/5.*.txt']
s.rdoc_options += ["--quiet", "--line-numbers", "--inline-source", '--title', 'Sequel: The Database Toolkit for Ruby', '--main', 'README.rdoc']
s.summary = "The Database Toolkit for Ruby"
s.description = s.summary
s.author = "Jeremy Evans"
s.email = "code@jeremyevans.net"
s.homepage = "https://sequel.jeremyevans.net"
s.license = 'MIT'
s.metadata = {
'bug_tracker_uri' => 'https://github.com/jeremyevans/sequel/issues',
'changelog_uri' => 'https://sequel.jeremyevans.net/rdoc/files/CHANGELOG.html',
'documentation_uri' => 'https://sequel.jeremyevans.net/documentation.html',
'mailing_list_uri' => 'https://github.com/jeremyevans/sequel/discussions',
'source_code_uri' => 'https://github.com/jeremyevans/sequel',
}
s.required_ruby_version = ">= 1.9.2"
s.files = %w(MIT-LICENSE CHANGELOG README.rdoc bin/sequel) + Dir["doc/*.rdoc"] + Dir["doc/release_notes/5.*.txt"] + Dir["lib/**/*.rb"]
s.require_path = "lib"
s.bindir = 'bin'
s.executables << 'sequel'
s.add_dependency "bigdecimal"
s.add_development_dependency "minitest", '>=5.7.0'
s.add_development_dependency "minitest-hooks"
s.add_development_dependency "minitest-global_expectations"
s.add_development_dependency "tzinfo"
s.add_development_dependency "activemodel"
s.add_development_dependency "nokogiri"
end
|
class DoctorSerializer < ActiveModel::Serializer
attributes :id, :name, :image, :bio, :wikilink, :regenindex
has_many :comments
end
|
module Renoval
module Validators
# Base class for all the validators
class Improvement < Base
private
def validator_type
'Improvements'
end
end
end
end
|
Pod::Spec.new do |s|
s.name = "AFNetworking"
s.summary = "Beautiful networking library for Objective-C and Swift"
s.version = "1.3.4"
s.license = 'MIT'
s.homepage = "https://github.com/AFNetworking/AFNetworking"
s.author = { 'Mattt Thompson' => 'm@mattt.me' }
s.source = { :http => "http://repository.neonstingray.com/content/repositories/thirdparty/com/afnetworking/ios/afnetworking/1.3.4/afnetworking-1.3.4.zip" }
s.platform = :ios
s.frameworks = 'MobileCoreServices', 'CoreGraphics', 'Security', 'SystemConfiguration'
s.source_files = 'AFNetworking/*.{h,m}'
s.requires_arc = true
s.ios.deployment_target = '6.0'
end
|
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_filter :get_picture
def get_picture
if current_user
@pic = current_user.facebook.get_picture("me")
end
end
end
|
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_action :set_locale
def user_init?
@user = User.find_by(id: session[:user_id])
if @user.nil?
redirect_to '/users/login'
return false
end
return true
end
def set_locale
I18n.locale = :ru
end
end
|
class PartsController < ApplicationController
def list
@parts = Part.order("parts.")
end
end
|
class Integer
@@ONE = {
0 => "zero",
1 => "one",
2 => "two",
3 => "three",
4 => "four",
5 => "five",
6 => "six",
7 => "seven",
8 => "eight",
9 => "nine",
}
@@TEEN = {
10 => "ten",
11 => "eleven",
12 => "twelve",
13 => "thirteen",
14 => "fourteen",
15 => "fifteen",
16 => "sixteen",
17 => "seventeen",
18 => "eighteen",
19 => "nineteen"
}
@@TEN = {
10 =>"ten",
20 => "twenty",
30 => "thirty",
40 => "forty",
50 => "fifty",
60 => "sixty",
70 => "seventy",
80 => "eighty",
90 => "ninety"
}
@@HUNDRED = {
100 =>"hundred",
1_000 => "thousand",
1_000_000 => "million",
1_000_000_000 => "billion",
1_000_000_000_000 => "trillion"
}
def in_words
if (self < 10)
@@ONE[self]
elsif (self < 20)
@@TEEN[self]
elsif (self < 100)
if(self % 10 != 0)
@@TEN[(self / 10) * 10] + " "+ (self % 10).in_words
else @@TEN[self]
end
else
found = find_hundred
founded = (self / found).in_words + " " + @@HUNDRED[found]
if (self % found != 0)
founded + " " + (self % found).in_words
else founded
end
end
end
def find_hundred
@@HUNDRED.keys.sort.take_while { |found|found <= self }.last
end
end
|
class BwcAnnualManualClassChangesController < ApplicationController
before_action :set_manual_class, only: [:update, :edit, :destroy]
def index
@manual_classes = BwcAnnualManualClassChange.all
end
def new
@manual_class = BwcAnnualManualClassChange.new
end
def create
@manual_class = BwcAnnualManualClassChange.new(permitted_params)
if @manual_class.save
flash[:success] = 'Created Successfully!'
redirect_to action: :index
else
flash[:error] = 'Something Went Wrong!'
render :new
end
end
def edit
end
def update
if @manual_class.update_attributes(permitted_params)
flash[:success] = 'Updated Successfully!'
redirect_to action: :index
else
flash[:error] = 'Something Went Wrong!'
render :edit
end
end
def destroy
if @manual_class.destroy
flash[:success] = 'Deleted Successfully!'
redirect_to action: :index
else
flash[:error] = 'Something Went Wrong!'
end
end
private
def permitted_params
params.require(:manual_class).permit(:manual_class_from, :manual_class_to, :policy_year)
end
def set_manual_class
@manual_class = BwcAnnualManualClassChange.find(params[:id])
end
end |
require 'benchmark'
# This solution employs iterative dynamic programming, a bottom-up approach.
#
# More specifically, this solution iterates from the bottom row upwards; reducing the triangle's
# dimensionality until we're (effectively) left with an array with size = 1.
#
# Given this example:
# 1
# 2 3
# 21 2 1
# We can see that the naive, top-down greedy search for the largest sum gives us the answer 6.
# Starting from the top, [1 => 3 > 1 so let's go there (3+1) => 4 => 2 > 1 so let's go there (4+2) => 6!]
# But we can easily see that the correct maximal sum for the triangle is 24 (1+2+21), taking the leftmost path.
#
# This is why dynamic programming was my chosen solution.
time = Benchmark.measure do
temp_int_ar = Array.new # The array we use for 'memoization.'
cur_int_ar = Array.new # The current array we're iterating in.
File.readlines("string_18.dat").reverse_each.with_index do |line, index| # Start at the last line.
if index == 0 # When at the last line only
temp_int_ar = line.chomp.split.map(&:to_i)
next
else
cur_int_ar = line.chomp.split.map(&:to_i)
cur_int_ar.each_with_index do |val, index|
# Check which adjacent number in the memoized array gives the larger sum when added to the current iterated element in the current iterated line.
temp_int_ar[index] > temp_int_ar[index + 1] ? temp_int_ar[index] = cur_int_ar[index] + temp_int_ar[index] : temp_int_ar[index] = cur_int_ar[index] + temp_int_ar[index + 1]
end
end
end
puts "The largest sum in the routes of the triangle given by string_18.dat is #{temp_int_ar.first}"
end
puts "Time elapsed (in seconds): #{time}" |
class Style < ActiveRecord::Base
include RatingAverage
extend TopItem
has_many :beers
has_many :ratings, :through => :beers
def to_s
name
end
def self.top(n)
self.top_item(Style, n)
end
end
|
class Test
extend Rum::Docker::AttrCallable
attr_method_accessor :fizz
end
RSpec.describe Rum::Docker::AttrCallable do
subject { Test.new }
describe "::attr_method_accessor" do
it "sets an attr by calling it as a method" do
expect { subject.fizz :buzz }.to \
change { subject.instance_variables }.from([]).to([:@fizz])
end
it "gets an attr by calling it as a method" do
subject.fizz :buzz
expect(subject.fizz).to eq :buzz
end
end
end
RSpec.describe Rum::Docker::Options do
let(:options) { {:flag => [:value, {:key => :value}]} }
subject { Rum::Docker::Options.new options }
describe "#each" do
it "converts to an Array of words" do
expect(subject.to_a).to eq(%w[--flag value --flag key=value])
end
end
describe "#method_missing" do
it "forwards methods to set options" do
subject.fizz true
subject.fizz false
expect(subject[:fizz]).to eq [true, false]
end
end
describe "#to_h" do
it "can be expressed as a Hash" do
expect(subject.to_h).to eq options
end
end
describe "#to_s" do
it "converts to a string" do
expect(subject.to_s).to eq "--flag value --flag key=value"
end
end
end
RSpec.describe Rum::Docker::Build do
describe "#each" do
it "converts to an Array of Docker build command words" do
expect(subject.to_a).to eq %w[docker build .]
end
end
describe "#method_missing" do
it "forwards missing methods to the Options instance variable" do
expect { subject.label :FIZZ }.to \
change { subject.label }.from([]).to([:FIZZ])
end
end
describe "#to_s" do
it "converts to a Docker build command string" do
subject.build_arg :FIZZ => "buzz"
subject.build_arg :BUZZ
expect(subject.to_s).to eq "docker build --build-arg FIZZ=buzz --build-arg BUZZ ."
end
end
describe "#with_defaults" do
subject { Rum::Docker::Build.new.tag(:fizz).target(:buzz).with_defaults(tag: "foo", target: "bar", :jazz => :fuzz) }
it "applies defaults if not provided in initialization" do
expect(subject.options.to_h).to include tag: [:fizz], target: [:buzz], jazz: [:fuzz]
end
end
describe "#clear_options" do
it "clears the command @options" do
expect(subject.clear_options.options.to_h.empty?).to be true
end
end
end
RSpec.describe Rum::Docker::Run do
subject { Rum::Docker::Run.new image: "fizz" }
describe "#each" do
it "converts to an Array of Docker run command words" do
expect(subject.to_a).to eq %w[docker run fizz]
end
end
describe "#to_s" do
let(:subject_with_opts) { subject.rm(false).cmd(%w[echo hello, world]) }
it "converts to a Docker run command string" do
expect(subject_with_opts.to_s).to eq "docker run --rm=false fizz echo hello, world"
end
end
describe "#with_defaults" do
let(:subject_with_defaults) { subject.rm(false).with_defaults(rm: true) }
it "applies defaults if not provided in initialization" do
expect(subject_with_defaults.options.to_h).to include rm: [false]
end
end
describe "#clear_options" do
it "clears the command @options" do
expect(subject.clear_options.options.to_h.empty?).to be true
end
end
end
RSpec.describe Rum::Docker::Image do
let(:image) { "image" }
let(:image_tag) { "image:tag" }
let(:username_image) { "username/image" }
let(:username_image_tag) { "username/image:tag" }
let(:registry_5000_username_image) { "registry:5000/username/image" }
let(:registry_5000_username_image_tag) { "registry:5000/username/image:tag" }
subject { Rum::Docker::Image.new name: "fizz", registry: "registry", username: "user" }
describe "::parse" do
subject { Rum::Docker::Image }
it "parses 'image'" do
expect(subject.parse(image).to_s).to eq "#{image}:latest"
end
it "parses 'username/image'" do
expect(subject.parse(username_image).to_s).to eq "#{username_image}:latest"
end
it "parses 'image:tag'" do
expect(subject.parse(image_tag).to_s).to eq image_tag
end
it "parses 'username/image:tag'" do
expect(subject.parse(username_image_tag).to_s).to eq username_image_tag
end
it "parses 'registry:5000/username/image'" do
expect(subject.parse(registry_5000_username_image).to_s).to eq "#{registry_5000_username_image}:latest"
end
it "parses 'registry:5000/username/image:tag'" do
expect(subject.parse(registry_5000_username_image_tag).to_s).to eq registry_5000_username_image_tag
end
end
describe "#each" do
it "converts to a compacted Array of [registry, username, name, tag]" do
expect(subject.to_a).to eq %w[registry user fizz latest]
end
end
describe "#family" do
it "gets the image name without the tag" do
expect(subject.family).to eq "registry/user/fizz"
end
end
describe "#inspect" do
it "should show the shortened version of the instance (without tag)" do
subject.tag :latest
expect(subject.inspect).to eq "#<Rum::Docker::Image[registry/user/fizz]>"
end
it "should show the shortened version of the instance (with tag)" do
subject.tag :edge
expect(subject.inspect).to eq "#<Rum::Docker::Image[registry/user/fizz:edge]>"
end
end
describe "#to_s" do
it "converts to a fully-qualified Docker tag" do
expect(subject.to_s).to eq "registry/user/fizz:latest"
end
end
end
|
#represents a companu that is a supplier
class Supplier < Company
has_many :sales_team_contracts
has_many :sales_teams, :through=>:sales_team_contracts
has_many :serving_us_states,:foreign_key=>"company_id"
has_many :us_states, :through=>:serving_us_states
validates :tax_number, :presence=>true
after_create :generate_warehouse
def can_sell_wholesale
self.sell_wholesale
end
#called after creating company. If it is a supplier then we generate their first warehouse with an address equivalent to their company address. This is because most suppliers have the same address for their office and warehouse. Makes it easier on the person adding the company to the DB.
def generate_warehouse
return true if type!="Supplier"
Warehouse.create(:company_id=>self.id,
:name=>self.name,
:managed=>false,
:address=>self.address,
:address2=>self.address2,
:city=>self.city,
:us_state=>self.state,
:zipcode=>self.zipcode)
end
def samples_with_owned_products
SampleOrder.includes(:order_items=>:product).where("products.company_id=?",self.id)
end
def orders_with_owned_products
#Order.all(:joins=>{:order_items=>{:product=>:company}}, :conditions=>{:companies=>{:id=>self.id}})
Order.find_by_sql("select Orders.* from orders where spo_order_id in (select spo_order_id from order_items oi join products p on oi.product_id=p.id left join companies c on p.company_id=c.id where c.id=#{self.id}) order by orders.created_at DESC")
end
end
|
require_relative "static_array"
class DynamicArray
attr_reader :length
def initialize
@capacity = 8
@store = StaticArray.new(@capacity)
@length = 0
@start_idx = 0
end
# O(1)
def [](index)
raise "index out of bounds" if index.abs >= @length.abs
@store[
(@start_idx + index) % @capacity
]
end
# O(1)
def []=(index, value)
check_index(index)
@store[
(@start_idx + index) % @capacity
] = value
end
# O(1)
def pop
raise "index out of bounds" if @length < 1
popped = self[@length - 1]
@length -= 1
popped
end
# O(1) ammortized; O(n) worst case. Variable because of the possible
# resize.
def push(val)
resize_if_needed!
self[@length] = val
@length += 1
self
end
# O(1) due to ring-buffer style wrap
def shift
raise "index out of bounds" if @length < 1
shifted = self[0]
@start_idx += 1
@length -= 1
shifted
end
# O(1) ammortized due to ring-buffer style wrap
def unshift(val)
resize_if_needed!
@start_idx = (@start_idx - 1) % @capacity
self[0] = val
@length += 1
self
end
def to_s
output = '['
i = 0
while i < @length do
output += "#{i}"
output += ", " if i < @length - 1
i += 1
end
output += "]"
end
protected
attr_accessor :capacity, :store
attr_writer :length
def check_index(index)
raise "index out of bounds" if index.abs >= @capacity.abs
end
def resize_if_needed!
resize! if @length + 1 > @capacity
end
# O(n) where n is the length of store
def resize!
@capacity = @capacity * 2
new_arr = StaticArray.new(@capacity)
(@length).times { |i| new_arr[i] = self[i] }
@store = new_arr
end
end
|
class AddEventToAttendments < ActiveRecord::Migration[5.1]
def change
add_reference :attendments, :event, foreign_key: true
end
end
|
require File.expand_path(File.dirname(__FILE__) + "/../util_helper")
class QaAnswer
include UtilHelper
def initialize(text, photos)
if text == nil
@text = "Answer_" + random_number
else
@text = text
end
@photos = photos
end
def text
@text
end
def photos
@photos
end
end
|
# http://www.mudynamics.com
# http://labs.mudynamics.com
# http://www.pcapr.net
require 'ipaddr'
module Mu
class Pcap
class IPv6 < IP
FORMAT = 'NnCCa16a16'
attr_accessor :next_header, :hop_limit
def initialize
super
@next_header = 0
@hop_limit = 64
end
def v6?
return true
end
alias :proto :next_header
alias :ttl :hop_limit
def flow_id
if not @payload or @payload.is_a? String
return [:ipv6, @next_header, @src, @dst]
else
return [:ipv6, @src, @dst, @payload.flow_id]
end
end
def self.from_bytes bytes
Pcap.assert bytes.length >= 40, 'Truncated IPv6 header: ' +
"expected at least 40 bytes, got #{bytes.length} bytes"
vcl, length, next_header, hop_limit, src, dst =
bytes[0, 40].unpack FORMAT
version = vcl >> 28 & 0x0f
traffic_class = vcl >> 20 & 0xff
flow_label = vcl & 0xfffff
Pcap.assert version == 6, "Wrong IPv6 version: got (#{version})"
Pcap.assert bytes.length >= (40 + length), 'Truncated IPv6 header: ' +
"expected #{length + 40} bytes, got #{bytes.length} bytes"
ipv6 = IPv6.new
ipv6.next_header = next_header
ipv6.hop_limit = hop_limit
ipv6.src = IPAddr.new_ntoh(src).to_s
ipv6.dst = IPAddr.new_ntoh(dst).to_s
ipv6.payload_raw = bytes[40..-1]
ipv6.next_header, ipv6.payload =
payload_from_bytes ipv6, ipv6.next_header, bytes[40...40+length]
return ipv6
end
# Parse bytes and returns next_header and payload. Skips extension
# headers.
def self.payload_from_bytes ipv6, next_header, bytes
begin
case next_header
when IPPROTO_TCP
payload = TCP.from_bytes bytes
when IPPROTO_UDP
payload = UDP.from_bytes bytes
when IPPROTO_SCTP
payload = SCTP.from_bytes bytes
when IPPROTO_HOPOPTS
next_header, payload = eight_byte_header_from_bytes(ipv6,
bytes, 'hop-by-hop options')
when IPPROTO_ROUTING
next_header, payload = eight_byte_header_from_bytes(ipv6,
bytes, 'routing')
when IPPROTO_DSTOPTS
next_header, payload = eight_byte_header_from_bytes(ipv6,
bytes, 'destination options')
when IPPROTO_FRAGMENT
Pcap.assert bytes.length >= 8,
"Truncated IPv6 fragment header"
Pcap.assert false, 'IPv6 fragments are not supported'
when IPPROTO_AH
next_header, payload = ah_header_from_bytes(ipv6,
bytes, 'authentication header')
when IPPROTO_NONE
payload = ''
else
payload = bytes
end
rescue ParseError => e
Pcap.warning e
payload = bytes
end
return [next_header, payload]
end
# Parse extension header that's a multiple of 8 bytes
def self.eight_byte_header_from_bytes ipv6, bytes, name
Pcap.assert bytes.length >= 8, "Truncated IPv6 #{name} header"
length = (bytes[1].ord + 1) * 8
Pcap.assert bytes.length >= length, "Truncated IPv6 #{name} header"
return payload_from_bytes(ipv6, bytes[0].ord, bytes[length..-1])
end
# Parse authentication header (whose length field is interpeted differently)
def self.ah_header_from_bytes ipv6, bytes, name
Pcap.assert bytes.length >= 8, "Truncated IPv6 #{name} header"
length = (bytes[1].ord + 2) * 4
Pcap.assert bytes.length >= length, "Truncated IPv6 #{name} header"
return payload_from_bytes(ipv6, bytes[0].ord, bytes[length..-1])
end
def write io
if @payload.is_a? String
payload = @payload
else
string_io = StringIO.new
@payload.write string_io, self
payload = string_io.string
end
src = IPAddr.new(@src, Socket::AF_INET6).hton
dst = IPAddr.new(@dst, Socket::AF_INET6).hton
header = [0x60000000, payload.length, @next_header, @hop_limit,
src, dst].pack FORMAT
io.write header
io.write payload
end
def pseudo_header payload_length
return IPAddr.new(@src, Socket::AF_INET6).hton +
IPAddr.new(@dst, Socket::AF_INET6).hton +
[payload_length, '', @next_header].pack('Na3C')
end
def == other
return super &&
self.next_header == other.next_header &&
self.hop_limit == other.hop_limit
end
end
end
end
|
class ShortUrlsController < ApplicationController
# Since we're working on an API, we don't have authenticity tokens
skip_before_action :verify_authenticity_token
def index
short_urls = ShortUrl.select(:click_count, :short_code, :full_url, :title).
order(click_count: :desc).
limit(100)
render json: { urls: short_urls.as_json(except: :id) }
end
def create
short_url = ShortUrl.find_or_initialize_by(full_url: short_url_params[:full_url])
short_url.short_code = short_url.short_code
short_url.save!
render json: { short_code: short_url.short_code }
rescue ActiveRecord::RecordInvalid => e
render json: { errors: short_url.errors.full_messages }, status: :bad_request
end
def show
short_url = ShortUrl.where(short_code: short_url_params[:id]).last
if short_url.nil?
return render json: { message: 'Not a valid short code' }, status: :not_found
end
short_url.update! click_count: (short_url.click_count + 1)
respond_to do |format|
format.html { redirect_to short_url.full_url }
format.json { render json: { redirect: short_url.full_url, click_count: short_url.click_count } }
end
end
private
def short_url_params
params.permit(:id, :full_url)
end
end
|
class Cms::Tag < ActiveRecord::Base
resourcify
validates :name, presence: true
validates :lang, presence: true
validates :name, uniqueness: {scope: :lang}
has_and_belongs_to_many :articles
end
|
class CreateIndexPostSonComment < ActiveRecord::Migration[5.1]
def change
create_table :index_post_son_comments do |t|
t.string :content
t.integer :thumbs_count
t.references :user, index: false
t.timestamps
end
add_index :index_post_son_comments, :user_id, name: :index_post_son_comments_on_user_id
end
end
|
require 'spec_helper'
module Refinery
describe Images do
describe "#configure" do
it "should set configurable option" do
subject.configure do |config|
config.max_image_size = 8201984
end
subject.max_image_size.should == 8201984
end
end
describe ".reset!" do
it "should set max_image_size back to the default value" do
subject.max_image_size.should == subject::DEFAULT_MAX_IMAGE_SIZE
subject.max_image_size += 1
subject.max_image_size.should_not == subject::DEFAULT_MAX_IMAGE_SIZE
subject.reset!
subject.max_image_size.should == subject::DEFAULT_MAX_IMAGE_SIZE
end
it "should set pages_per_dialog back to the default value" do
subject.pages_per_dialog.should == subject::DEFAULT_PAGES_PER_DIALOG
subject.pages_per_dialog += 1
subject.pages_per_dialog.should_not == subject::DEFAULT_PAGES_PER_DIALOG
subject.reset!
subject.pages_per_dialog.should == subject::DEFAULT_PAGES_PER_DIALOG
end
it "should set pages_per_dialog_that_have_size_options back to the default value" do
subject.pages_per_dialog_that_have_size_options.should == subject::DEFAULT_PAGES_PER_DIALOG_THAT_HAVE_SIZE_OPTIONS
subject.pages_per_dialog_that_have_size_options += 1
subject.pages_per_dialog_that_have_size_options.should_not == subject::DEFAULT_PAGES_PER_DIALOG_THAT_HAVE_SIZE_OPTIONS
subject.reset!
subject.pages_per_dialog_that_have_size_options.should == subject::DEFAULT_PAGES_PER_DIALOG_THAT_HAVE_SIZE_OPTIONS
end
it "should set pages_per_admin_index back to the default value" do
subject.pages_per_admin_index.should == subject::DEFAULT_PAGES_PER_ADMIN_INDEX
subject.pages_per_admin_index += 1
subject.pages_per_admin_index.should_not == subject::DEFAULT_PAGES_PER_ADMIN_INDEX
subject.reset!
subject.pages_per_admin_index.should == subject::DEFAULT_PAGES_PER_ADMIN_INDEX
end
end
end
end
|
class ProviderDetail < ApplicationRecord
belongs_to :provider
belongs_to :category
has_many :comments, dependent: :destroy
has_one_attached :image, dependent: :destroy
has_many :favourite_posts, dependent: :destroy
has_many :users, through: :favourite_posts
# VALIDATION :
validates :city, :state, presence: true
validates :description, length: {minimum: 60}
validates :zipcode, numericality: true
validates_uniqueness_of :category_id, scope: [:provider_id]
scope :searching, ->(s) { ProviderDetail.joins(:category).where('provider_details.city LIKE ? OR provider_details.state LIKE ? OR provider_details.zipcode LIKE ? OR categories.name LIKE ? AND provider_details.email_confirmed = ? ', "%#{s}%", "%#{s}%", "%#{s}%", "%#{s}%", false) }
# after_create_commit {
# ProviderDetailBroadcastJob.perform_later(self)
# }
# after_update_commit {
# if self.email_confirmed
# ProviderDetailBroadcastJob.perform_later(self)
# end
# }
def self.set_confirmation_token(provider_detail)
if provider_detail.confirm_token.blank?
provider_detail.confirm_token = SecureRandom.urlsafe_base64.to_s
provider_detail.save
end
end
def self.validate_email(provider_detail)
provider_detail.update(email_confirmed: true, confirm_token: nil)
end
end
|
require_relative 'spec_helper'
require_relative '../lib/Bluray'
describe Bluray do
before(:context) do
@br1 = Bluray.new("Fifth Element", 6, 126, "Luc Besson", "Gaumont")
end
describe "Initialization" do
it "is a kind of the Item class" do
expect(@br1).to be_a_kind_of(Item)
end
it "is an instance of the Bluray class" do
expect(@br1).to be_an_instance_of(Bluray)
end
it "is assigned a name" do
expect(@br1.name).to eq("Fifth Element")
end
it "is assigned a price" do
expect(@br1.price).to eq(6)
end
end
describe "Accessors" do
it "should be able to get quantity" do
expect(@br1.quantity).to eq(0)
end
it "should be able to get and set name" do
@br1.name="New Name"
expect(@br1.name).to eq("New Name")
end
it "should be able to get and set price" do
@br1.price=44.99
expect(@br1.price).to eq(44.99)
end
it "should be able to get and set description" do
expect(@br1.description).to eq("")
@br1.description="test"
expect(@br1.description).to eq("test")
end
end
describe "Methods" do
it "should be able to stock" do
result = @br1.stock 5
expect(result).to eq(true)
expect(@br1.quantity).to eq(5)
end
it "should not be able to sell more items than we have" do
result = @br1.sell 6
expect(result).to eq(false)
expect(@br1.quantity).to eq(5)
end
it "should be able to sell items and update quantity" do
result = @br1.sell 3
expect(result).to eq(true)
expect(@br1.quantity).to eq(2)
end
end
describe "Part 2 Methods" do
it "should be able to return" do
result = @br1.return 2
expect(result).to eq(true)
expect(@br1.quantity).to eq(4)
end
it "should have a default weight of 0" do
expect(@br1.weight).to eq(0)
end
it "should be able to set a new weight" do
@br1.weight = 1
expect(@br1.weight).to eq(1)
end
it "should be able to report a ship_price" do
expect(@br1.ship_price).to eq(1.2)
end
end
end
|
class AddInheritanceToOrgasAndEvents < ActiveRecord::Migration[5.0]
def change
add_column :orgas, :inheritance, :string
add_column :events, :inheritance, :string
end
end
|
class Twing
class Receivers
attr_reader :receivers, :instances
def initialize
@receivers, @instances = [], []
end
def add(receiver)
@receivers << receiver
end
def init(app)
@instances = @receivers.map do |receiver|
receiver.new(app)
end
end
def run(&block)
@instances.each(&block)
end
end
end
|
class TodoList < ActiveRecord::Base
has_many :todo_items, :dependent => :destroy
validates :name, :presence => true, :uniqueness => true
def hello
"Hello from TodoList"
end
end
|
Pod::Spec.new do |s|
s.name = "YWCustomAlertPopUp"
s.version = "1.0"
s.summary = "YWCustomAlertPopUp Customizable Alertcontroller"
s.description = "Simple Customizable AlertController for you to try in Objective-C 2017"
s.requires_arc = true
s.homepage = "https://github.com/nsnull0/YWCustomAlertPopUp"
s.license = { :type => "MIT", :file => "LICENSE" }
s.author = { "yoseph_wijaya" => "info@yoseph.ws" }
s.platform = :ios
s.ios.deployment_target = "9.0"
s.source = { :git => "https://github.com/nsnull0/YWCustomAlertPopUp.git", :tag => "#{s.version}" }
s.source_files = "YWCustomAlertPopUp/Classes/*.{h,m}"
s.resources = "YWCustomAlertPopUp/Resources/*.{png,jpeg,jpg,storyboard,xib,xcassets}"
s.framework = "UIKit"
end
|
class Song
attr_accessor :name, :artist_name
@@all = []
def self.all
@@all
end
def save
self.class.all << self
end
def self.create
song = self.new
song.name = name
@@all << song
song
end
def self.new_by_name(name)
song = self.new
song.name = name
song
end
def self.create_by_name(name)
song = self.create
song.name = name
song
end
def self.find_by_name(name)
@@all.detect {|song| song.name == name}
end
def self.find_or_create_by_name(name)
if self.find_by_name(name)
self.find_by_name(name)
else
self.create_by_name(name)
end
end
def self.alphabetical
self.all.sort_by! {|song| song.name}
end
def self.new_from_filename(song_format)
row = song_format
data = row.split(" - ")
artist_name = data[0]
song_name = data[1].gsub(".mp3", "")
song = self.new
song.name = song_name
song.artist_name = artist_name
song
end
def self.create_from_filename(song_format)
song = self.new_from_filename(song_format)
song.save
song
end
def self.destroy_all
@@all.clear
end
end
|
class UsersController < ApplicationController
before_action :authenticate_user!, except: [:show, :index]
before_action :ensure_correct_user, only: [:edit, :update]
before_action :admin_user, only: [:destroy]
def show
@user = User.find(params[:id])
@user_comments = @user.store_comments.page(params[:page]).per(5)
# ユーザーのトップ3ランキング
@my_ranking = Store.my_ranking(@user).first(3)
end
def edit
@user = User.find(params[:id])
end
def update
@user = User.find(params[:id])
if @user.update(user_params)
redirect_to @user, notice: "会員情報を更新しました"
else
render "edit"
end
end
def destroy
@user = User.find(params[:id])
@user.destroy
redirect_to root_path
end
private
def user_params
params.require(:user).permit(:name, :introduction, :profile_image)
end
def ensure_correct_user
@user = User.find(params[:id])
unless @user == current_user
redirect_to user_path(current_user)
end
end
def admin_user
redirect_to(root_path) unless current_user.admin?
end
end
|
# -*- mode: ruby; coding: utf-8 -*-
require 'open-uri'
require 'kconv'
$KCODE = 'utf8'
module Psycho
module Util
class PostingModel
attr_accessor :serial, :number, :hundle, :email, :posted, :id, :contents, :parents, :children, :nest
def initialize(params={})
@serial = params[:serial]
@number = params[:number]
@hundle = params[:hundle]
@email = params[:email]
@posted = params[:posted]
@id = params[:id]
@contents = params[:contents]
@parents = params[:parents]
@children = params[:children] ? params[:children] : Array.new
@nest = params[:nest] ? params[:nest] : 0
end
# for template
def to_liquid
{
'number' => @number,
'hundle' => @hundle,
'email' => @email,
'posted' => @posted,
'id' => @id,
'contents' => @contents,
'nest' => @nest
}
end
end
class ThreadModel
attr_accessor :id, :subject, :owner
def initialize(params={})
@id = params[:id]
@subject = params[:subject]
@owner = params[:owner]
end
# for template
def to_liquid
{
'id' => @id,
'subject' => @subject,
'owner' => @owner
}
end
end
module_function
def getChild(articles, article, nest=0)
article.nest = nest
children = [article]
article.children.sort.each do |child_number|
children.concat(getChild(articles, articles[child_number-1], nest+1))
end
children
end
def PostingSummary(dat, effective_posts=1000)
thread = nil
articles = []
open(dat) do |file|
number = 1
while line = file.gets
#break if number >= 1001
break if number > effective_posts
arr = line.toutf8.strip.split('<>')
hundle = arr[0].strip
if number == 1
r = dat.match(/^https?:\/\/.+?\/dat\/(\d+)\.dat/)
thread = ThreadModel.new(:subject => arr[4].strip, :owner => hundle, :id => r[0] ? r[1] : 0)
end
posted_and_id = arr[2].strip.split
parents = []
arr[3].strip.scan(/>>\s*([\d]+)/) do |parent_number_arr|
if number > parent_number_arr[0].to_i
parents << parent_number_arr[0].to_i
tmp = articles.select do |p|
p.number == parent_number_arr[0].to_i
end
tmp.each do |c|
c.children << number
end
end
end
contents = arr[3].strip.gsub(/sssp:\/\//, 'http://').gsub(/<\/?b>/, '').gsub(/(?:<a\s+href=\"\.\.[^>]+>)(?:>>)\s*(\d+)(?:<\/a>)/, '<a href="#\\1">>>\\1</a>')
links = contents.scan(/h?ttps?:\/\/[-_.!~*\'()a-zA-Z0-9;\/?:\@&=+\$,%#]+/)
contents.gsub!(/(h?ttps?:\/\/[-_.!~*\'()a-zA-Z0-9;\/?:\@&=+\$,%#]+)/, '__REGEX_MEDIA_LINK__')
links.each do |link|
href = (/^ttp/).match(link) ? 'h'+link : link
if (/\.(jpe?g|png|gif)$/).match(link)
# 画像
contents.sub!(/__REGEX_MEDIA_LINK__/, '<a href="'+href+'" rel="lightbox" title="'+number.to_s+'" target="_tab"><img class="threadimage" src="'+href+'"></a>')
contents_type = 2
elsif (/h?ttp:\/\/www.youtube.com\/watch/).match(link)
# 動画
href.gsub!(/&.+$/, '')
iframe_src = href.sub(/\/watch(_popup)?\?v=/, '/embed/')
contents.sub!(/__REGEX_MEDIA_LINK__/,
'<iframe class="youtube" title="YouTube video player" width="499" height="311" src="'+iframe_src+'" frameborder="0" allowfullscreen></iframe>')
contents_type = 3
else
contents.sub!(/__REGEX_MEDIA_LINK__/, '<a href="'+href+'" target="_tab">'+link+'</a>')
contents_type = 1 unless number == 1
end
end
posting = PostingModel.new({
:number => number,
:hundle => hundle,
:email => arr[1].strip,
:posted => "#{posted_and_id[0]} #{posted_and_id[1]}",
:id => posted_and_id[2] ? posted_and_id[2].strip : nil,
:contents => contents,
:parents => parents
})
articles << posting
number += 1
end
end
blog_summary = []
articles.each do |article|
if article.parents.size > 0
next
elsif article.children.size > 0
blog_summary.concat(getChild(articles, article))
elsif thread.owner == article.hundle
blog_summary << article
end
end
{:thread => thread, :postings => blog_summary}
end # PostingSummary
end
end
if __FILE__ == $0
dat = "http://uni.2ch.net/newsplus/dat/1349525321.dat"
res = Psycho::Util::PostingSummary(dat)
res[:postings].each do |posting|
puts "[#{posting.number}] #{posting.contents}"
end
end
|
require_relative 'figure'
class Chassis
attr_accessor :p,:q,:r,:s, :p1,:q1,:r1,:s1, :p2,:q2,:r2,:s2, :p3,:q3,:r3,:s3, :p4,:q4,:r4,:s4,
:p5,:q5,:r5,:s5, :p6,:q6,:r6,:s6, :p7,:q7,:r7,:s7, :p8,:q8,:r8,:s8, :p9,:q9,:r9,:s9,
:p10,:q10,:r10,:s10, :p11,:q11,:r11,:s11, :p12,:q12,:r12,:s12, :p13,:q13,:r13,:s13,
:p14,:q14,:r14,:s14, :p15,:q15,:r15,:s15, :p16,:q16,:r16,:s16, :p17,:q17,:r17,:s17,
:p18,:q18,:r18,:s18, :p19,:q19,:r19,:s19, :p20,:q20,:r20,:s20, :p21,:q21,:r21,:s21
def initialize(p,q,r,s, p1,q1,r1,s1, p2,q2,r2,s2, p3,q3,r3,s3, p4,q4,r4,s4,
p5,q5,r5,s5, p6,q6,r6,s6, p7,q7,r7,s7, p8,q8,r8,s8, p9,q9,r9,s9,
p10,q10,r10,s10, p11,q11,r11,s11, p12,q12,r12,s12, p13,q13,r13,s13,
p14,q14,r14,s14, p15,q15,r15,s15, p16,q16,r16,s16, p17,q17,r17,s17,
p18,q18,r18,s18, p19,q19,r19,s19, p20,q20,r20,s20, p21,q21,r21,s21)
@p = p
@q = q
@r = r
@s = s
@p1 = p1
@q1 = q1
@r1 = r1
@s1 = s1
@p2 = p2
@q2 = q2
@r2 = r2
@s2 = s2
@p3 = p3
@q3 = q3
@r3 = r3
@s3 = s3
@p4 = p4
@q4 = q4
@r4 = r4
@s4 = s4
@p5 = p5
@q5 = q5
@r5 = r5
@s5 = s5
@p6 = p6
@q6 = q6
@r6 = r6
@s6 = s6
@p7 = p7
@q7 = q7
@r7 = r7
@s7 = s7
@p8 = p8
@q8 = q8
@r8 = r8
@s8 = s8
@p9 = p9
@q9 = q9
@r9 = r9
@s9 = s9
@p10 = p10
@q10 = q10
@r10 = r10
@s10 = s10
@p11 = p11
@q11 = q11
@r11 = r11
@s11 = s11
@p12 = p12
@q12 = q12
@r12 = r12
@s12 = s12
@p13 = p13
@q13 = q13
@r13 = r13
@s13 = s13
@p14 = p14
@q14 = q14
@r14 = r14
@s14 = s14
@p15 = p15
@q15 = q15
@r15 = r15
@s15 = s15
@p16 = p16
@q16 = q16
@r16 = r16
@s16 = s16
@p17 = p17
@q17 = q17
@r17 = r17
@s17 = s17
@p18 = p18
@q18 = q18
@r18 = r18
@s18 = s18
@p19 = p19
@q19 = q19
@r19 = r19
@s19 = s19
@p20 = p20
@q20 = q20
@r20 = r20
@s20 = s20
@p21 = p21
@q21 = q21
@r21 = r21
@s21 = s21
end
def chassis
specular = [0.7, 0.7, 0.7, 1.0]
ambient = [1,1,1,1]
diffuse = [0.7,0.7,0.7,1]
full_shininess = [100.0]
glMaterialfv(GL_FRONT,GL_AMBIENT,ambient)
glMaterialfv(GL_FRONT,GL_SPECULAR,specular)
glMaterialfv(GL_FRONT,GL_DIFFUSE,diffuse)
glMaterialfv(GL_FRONT,GL_SHININESS, full_shininess)
glColor3f(0,0.2,0.9)
f = Figure.new
f.rect(@p,@q,@r,@s)
f.rect(@p2,@q2,@r2,@s2)
f.rect(@p3,@q3,@r3,@s3)
f.rect(@p4,@q4,@r4,@s4)
f.rect(@p5,@q5,@r5,@s5)
f.rect(@q5,@q4,@r4,@r5)
f.rect(@p6,@q6,@r6,@s6)
f.rect(@p7,@q7,@r7,@s7)
f.rect(@p8,@q8,@r8,@s8)
f.rect(@p9,@q9,@r9,@s9)
glColor3f(1,0.6,0)
f.rect(@p1,@q1,@r1,@s1)
f.rect(@q5,@q4,@p3,@q3)
f.tri(@p4,@q4,@p3)
f.tri(@p5,@q5,@q3)
f.rect(@p10,@q10,@r10,@s10)
f.rect(@p11,@q11,@r11,@s11)
f.rect(@r16,@r18,@q18,@q16)
f.rect(@q17,@q19,@r19,@r17)
f.rect(@p21,@q21,@r21,@s21)
glColor3f(0,0.2,0.9)
f.rect(@p12,@q12,@r12,@s12)
f.rect(@p13,@q13,@r13,@s13)
f.rect(@p14,@q14,@r14,@s14)
f.rect(@p15,@q15,@r15,@s15)
f.rect(@p16,@q16,@r16,@s16)
f.rect(@p17,@q17,@r17,@s17)
f.rect(@p18,@q18,@r18,@s18)
f.rect(@p19,@q19,@r19,@s19)
f.rect(@r18,@q19,@p19,@s18)
f.rect(@p20,@q20,@r20,@s20)
end
end |
module SiegeSiege
class URL
attr_reader :url, :http_method, :parameter
def initialize(url, http_method = nil, parameter = nil)
splat = url.split(' ')
if splat.size > 1
@url = splat[0]
@http_method = splat[1].downcase.to_sym
@parameter = splat[2]
else
@url = url
end
@http_method ||= http_method || :get
@parameter ||= parameter || {}
end
def parameter_string
case parameter
when Hash
parameter.to_param
else
parameter
end
end
def post?
http_method.to_s.downcase == 'post'
end
def to_siege_url
if post?
[url, 'POST', parameter_string]
else
url
end
end
class RequireURL < StandardError
end
end
end
|
Factory.define :category do |c|
c.sequence(:name) { |n| "Category #{n}" }
end
Factory.define :post_without_categories, :class => Post do |p|
p.sequence(:title) { |n| "Title#{n}" }
p.body "Body"
p.association :author, :factory => :user
p.published true
end
Factory.define :post, :parent => :post_without_categories do |p|
p.categories {|c| [c.association(:category), c.association(:category)] }
end
|
class StaticPagesController < ApplicationController
include MicropostsHelper
#
# @param [Array] feed 全ユーザーの投稿記事
# @param [Array] following_users_feed current_userがフォローしているユーザーの投稿記事
# @param [Array] current_user_post current_userの投稿
# @param [Array] post_json_data current_user_postをJSONに変換した配列
#
def home
@feed = Micropost.all.page(params[:page])
return unless user_signed_in?
@following_users_feed = current_user.following_users_feed.page(params[:page])
@current_user_post = Micropost.where(user_id: current_user.id,exif_is_valid: true).or \
(Micropost.where(user_id: current_user.id).where.not(address: nil).where.not(latitude: nil))
@post_json_data = @current_user_post.to_json(only: %i[id title picture latitude longitude])
# jsリクエストなら通過
return unless request.xhr?
case params[:type]
when 'new_post_list', 'friendly_post_list'
render "shared/#{params[:type]}"
end
end
def contact
end
end
|
require 'yaml'
MESSAGES = YAML.load_file('yrps.yaml')
RPS = %w(r p s l sp)
VICTORY_CONDITIONS = { 'r' => %w(s l),
'p' => %w(r sp),
's' => %w(p l),
'l' => %w(sp p),
'sp' => %w(s r) }
# Just two helpers
def refresh_display
(system('clear') || system('cls'))
end
def message(key)
MESSAGES[key]
end
# constructs a variable message to display the results of the game.
def print_round_result(choices, result, player_score, computer_score)
puts 'You chose ' + message(choices[0]) +
'The computer chose ' + message(choices[1]) + message(result) +
" The scores are :: You: #{player_score}. Computer: #{computer_score}."
end
# Returns an array containing the player and computer choices
def make_choices
puts message('player_options')
choice = gets.chomp.downcase
return [choice, RPS.sample] if RPS.include?(choice)
puts message('bad_player_options')
make_choices
end
# returns true if the player wants to play again, else false
def another_game?
loop do
puts message('go_again')
answer = gets.chomp.downcase
next puts message('bad_input_go_again') unless answer.start_with?('y', 'n')
break answer.start_with?('y') ? true : false
end
end
# The next two method combine to determine the result of the match
def player_win?(player, computer)
VICTORY_CONDITIONS[player].include?(computer)
end
def game_result(choices)
player = choices[0]
computer = choices[1]
case
when player == computer then 'draw'
when player_win?(player, computer) then 'win'
else 'lose'
end
end
def update_scores(scores, result)
case result
when 'win' then [scores[0] + 1, scores[1]]
when 'lose' then [scores[0], scores[1] + 1]
else scores
end
end
# Plays a single round of rps
def play_round(scores)
choices = make_choices
result = game_result(choices)
scores = update_scores(scores, result)
print_round_result(choices, result, scores[0], scores[1])
scores
end
# string used when a match (5 games) has been won.
def victor_string(scores)
message(scores[0] == 5 ? 'match_won' : 'match_lost')
end
def play_match(scores)
loop do
puts message('new_game')
scores = play_round(scores)
break puts victor_string(scores) if scores.include?(5)
puts message('next_round')
refresh_display if gets
end
end
def play_game
refresh_display
puts message('welcome')
loop do
play_match([0, 0])
puts message('exit') unless another_game?
refresh_display
end
end
play_game
|
class RemoveStylesFromUsers < ActiveRecord::Migration
def change
remove_column :users, :fave_styles
end
end
|
class PagesController < ApplicationController
def lp
@meta_title = 'ブンゴウメール | 1日3分のメールでムリせず毎月1冊本が読める、忙しいあなたのための読書サポートサービス'
@meta_description = '青空文庫の作品を小分けにして、毎朝メールで配信。気づいたら毎月1冊本が読めてしまう、忙しいあなたのための読書サポートサービスです。'
end
def show
@meta_title = page_titles[params[:page].to_sym]
raise ActionController::RoutingError, request.url unless @meta_title
@meta_description = @meta_title
render params[:page]
end
def dogramagra
@meta_title = "ドグラ・マグラ365日配信チャレンジ"
@meta_description = "夢野久作『ドグラ・マグラ』を、365日かけて毎日メールで少しずつ配信します。"
@meta_image = "https://bungomail.com/assets/images/campaigns/dogramagra.png"
end
private
def page_titles
{
terms: '利用規約',
privacy: 'プライバシーポリシー',
tokushoho: '特定商取引法に基づく表記',
unsubscribe: '退会',
custom_delivery: 'カスタム配信',
}
end
end
|
class Photoalbum
include Mongoid::Document
field :name, type: String
has_many :fans
accepts_nested_attributes_for :fans
validates_associated :fans
has_many :photos
accepts_nested_attributes_for :photos
validates_associated :photos
end
|
require 'backstage_pass'
describe BackStagePass do
it "Backstage passes increases in quality by 1 when sell_in is greater than 10" do
item = BackStagePass.new("Backstage passes to a TAFKAL80ETC concert", 11, 10)
expect {item.update_quality()}.to change {item.quality}.by(1)
end
it "Backstage passes increases in quality by 2 when sell_in is 10 or less" do
item = BackStagePass.new("Backstage passes to a TAFKAL80ETC concert", 9, 10)
expect {item.update_quality()}.to change {item.quality}.by(2)
end
it "Backstage passes increases in quality by 3 when sell_in is 5 or less" do
item = BackStagePass.new("Backstage passes to a TAFKAL80ETC concert", 4, 10)
expect {item.update_quality()}.to change {item.quality}.by(3)
end
it "Backstage passes quality drops to 0 when sell_in is 0" do
item = BackStagePass.new("Backstage passes to a TAFKAL80ETC concert", 0, 10)
item.update_quality
expect(item.quality).to eq 0
end
end
|
class CreateEventStudentRelationships < ActiveRecord::Migration
def change
create_table :event_student_relationships do |t|
t.integer :event_id
t.integer :user_id
t.timestamps
end
add_index :event_student_relationships, :event_id
add_index :event_student_relationships, :user_id
add_index :event_student_relationships, [:event_id, :user_id], unique: true
end
end
|
Rails.application.routes.draw do
get 'appointments/index'
get 'appointments/new'
get 'appointments/create'
get 'appointments/edit'
get 'appointments/delete'
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
resources :therapists
resources :clients
resources :appointments
end
|
require 'net/http'
require 'json'
require 'dotenv'
require_relative './query_impala.rb'
Dotenv.load
class Requester
attr_reader :id
def initialize(id)
@id = id
end
def get_subid
uri = URI('http://sponsorpaynetwork.api.hasoffers.com/Apiv3/json')
params = {"NetworkId" => ENV['network_id'],
"NetworkToken" => ENV['network_token'],
"Target" => "Report",
"Method" => "getConversions",
"fields[0]" => "Stat.affiliate_info1",
"filters[Stat.ad_id][conditional]" => "EQUAL_TO",
"filters[Stat.ad_id][values][0]" => id}
uri.query = URI.encode_www_form(params)
res = Net::HTTP.get_response(uri)
if res.is_a?(Net::HTTPSuccess)
res = JSON.parse(res.body)
res = res["response"]["data"]["data"]
else res = ""
end
res
end
def get_hoid
now = Date.today
startdate = (now - 40).to_s
uri = URI('http://sponsorpaynetwork.api.hasoffers.com/Apiv3/json')
params = {"NetworkId" => ENV['network_id'],
"NetworkToken" => ENV['network_token'],
"Target" => "Report",
"Method" => "getConversions",
"fields[0]" => "Stat.ad_id",
"filters[Stat.affiliate_info1][conditional]" => "EQUAL_TO",
"filters[Stat.affiliate_info1][values][0]" => id,
"data_start" => startdate,
"hour_offset" => 9}
uri.query = URI.encode_www_form(params)
res = Net::HTTP.get_response(uri)
if res.is_a?(Net::HTTPSuccess)
res = JSON.parse(res.body)
res = res["response"]["data"]["data"]
else res = ""
end
res
end
end
class Offer
attr_reader :res
def initialize(res)
@res = res
end
def get_format
if res == "" || res.nil? || res == []
result = "No result"
elsif res[0]["Stat"]["affiliate_info1"].size < 28
result = "No result"
else
result = res[0]["Stat"]["affiliate_info1"].insert(8, '-').insert(13, '-').insert(18, '-').insert(23, '-')
end
result
end
end
class Result
attr_reader :hoids, :result
def initialize(hoids)
@hoids = hoids
@result = result
end
def ams_result
result = Requester.new(hoids).get_subid
Offer.new(result).get_format
end
def sql_result
result = String.new
hoids.split(/\r?\n|\r/).each do |line|
res = Requester.new(line).get_subid
res = Offer.new(res).get_format
result << "'"+res+"'"+"</br>"","
end
result
end
def hoid_result
result = String.new
hoids.split(/\r?\n|\r/).each do |line|
if line.include? "-"
line.gsub!(/-/, "")
end
res = Requester.new(line).get_hoid
result << "</br>" + res[0]["Stat"]["ad_id"]
end
result
end
def query_result
subid = String.new
hoids.split(/\r?\n|\r/).each do |line|
res = Requester.new(line).get_subid
res = Offer.new(res).get_format
subid << "'"+res+"'"+","
end
if subid == "'No subid',"
result = "No result"
else
l = subid.size
l = l -2
subids = subid[0..l]
now = Date.today
startdate = (now - 30).to_s
enddate = now.to_s
puts subids
query = "select toc.landing_page_id as lpid, a.id as appid, a.name as appname,
count(*) as number_of_conversions
from cms.applications_parquet as a
join ids.track_offer_clicks_history_parquet toc on a.id = toc.application_id
where toc.subid in (#{subids})
and toc.created_at >= '2015-08-01' group by 1,2,3"
puts query
result = Query.new(query,startdate,enddate)
result = result.run_query
end
result = result.map{ |l| l.to_s+'</br>'}
result.*""
end
end
|
require 'test_helper'
class LanguageUsersControllerTest < ActionDispatch::IntegrationTest
setup do
@language_user = language_users(:one)
end
test "should get index" do
get language_users_url
assert_response :success
end
test "should get new" do
get new_language_user_url
assert_response :success
end
test "should create language_user" do
assert_difference('LanguageUser.count') do
post language_users_url, params: { language_user: { language_id: @language_user.language_id, level: @language_user.level, user_id: @language_user.user_id } }
end
assert_redirected_to language_user_url(LanguageUser.last)
end
test "should show language_user" do
get language_user_url(@language_user)
assert_response :success
end
test "should get edit" do
get edit_language_user_url(@language_user)
assert_response :success
end
test "should update language_user" do
patch language_user_url(@language_user), params: { language_user: { language_id: @language_user.language_id, level: @language_user.level, user_id: @language_user.user_id } }
assert_redirected_to language_user_url(@language_user)
end
test "should destroy language_user" do
assert_difference('LanguageUser.count', -1) do
delete language_user_url(@language_user)
end
assert_redirected_to language_users_url
end
end
|
#https://semaphoreci.com/community/tutorials/how-to-deploy-node-js-applications-with-capistrano
#http://vladigleba.com/blog/2014/04/10/deploying-rails-apps-part-6-writing-capistrano-tasks/
require 'json'
namespace :pm2 do
def app_status
within current_path do
ps = JSON.parse(capture :pm2, :jlist, "/home/deploy/apps/anker_store_tablet/current/build/server.js") rescue []
if ps.empty?
return nil
else
# status: online, errored, stopped
return ps[0]["pm2_env"]["status"]
end
end
end
def restart_app
within current_path do
execute :pm2, :delete, "/home/deploy/apps/anker_store_tablet/current/build/server.js"
execute :pm2, :start, "/home/deploy/apps/anker_store_tablet/current/build/server.js"
end
end
def start_app
within current_path do
execute :pm2, :start, "/home/deploy/apps/anker_store_tablet/current/build/server.js"
# execute :pm2, :stop, fetch(:app_command)
end
end
desc 'Restart app gracefully'
task :restart do
on roles(:all) do
info 'App is online'
puts "--------------------------------------------------------------"
execute "pwd"
#execute "cd /home/deploy/apps/anker_store_tablet/current; (test -s build-#{fetch(:branch)} && mv build-#{fetch(:branch)} build)"
case app_status
when nil
info 'App is not registerd'
start_app
when 'stopped'
info 'App is stopped'
restart_app
when 'errored'
info 'App has errored'
restart_app
when 'online'
info 'App is online'
restart_app
end
end
end
end
|
module SQB
module Joins
# Add a join
#
# @param table_name [String, Symbol]
# @param foreign_key [String, Symbol]
# @option options [Hash] :where
# @option options [Array] :select
# @return [Query]
def join(table_name, foreign_key, options = {})
@joins ||= []
@joins_name_mapping ||= {}
if options[:name]
join_name = options[:name]
else
@joins_name_mapping[table_name] ||= 0
join_name= "#{table_name}_#{@joins_name_mapping[table_name]}"
@joins_name_mapping[table_name] += 1
end
@joins << [].tap do |query|
query << "INNER JOIN"
query << escape_and_join(@options[:database_name], table_name)
query << "AS"
query << escape(join_name)
query << "ON"
query << escape_and_join(@table_name, 'id')
query << "="
query << escape_and_join(join_name, foreign_key)
end.join(' ')
if options[:where]
join_where = options[:where].each_with_object({}) do |(column, value), hash|
hash[{join_name => column}] = value
end
where(join_where)
end
if columns = options[:columns]
for field in columns
column({join_name => field}, :as => "#{join_name}_#{field}")
end
end
if g = options[:group_by]
group_by(join_name => g.is_a?(Symbol) ? g : :id)
end
self
end
end
end
|
module SlackRubyBot
module Commands
class Default < Base
command 'about'
match(/^(?<bot>[[:alnum:][:punct:]@<>]*)$/u)
def self.call(client, data, _match)
client.say(
channel: data.channel,
text: "Available commands: hi, about, help, hello, 'weather CITY'",
gif: 'nigga'
)
end
end
end
end
|
module Square
# CashDrawersApi
class CashDrawersApi < BaseApi
# Provides the details for all of the cash drawer shifts for a location
# in a date range.
# @param [String] location_id Required parameter: The ID of the location to
# query for a list of cash drawer shifts.
# @param [SortOrder] sort_order Optional parameter: The order in which cash
# drawer shifts are listed in the response, based on their opened_at field.
# Default value: ASC
# @param [String] begin_time Optional parameter: The inclusive start time of
# the query on opened_at, in ISO 8601 format.
# @param [String] end_time Optional parameter: The exclusive end date of the
# query on opened_at, in ISO 8601 format.
# @param [Integer] limit Optional parameter: Number of cash drawer shift
# events in a page of results (200 by default, 1000 max).
# @param [String] cursor Optional parameter: Opaque cursor for fetching the
# next page of results.
# @return [ListCashDrawerShiftsResponse Hash] response from the API call
def list_cash_drawer_shifts(location_id:,
sort_order: nil,
begin_time: nil,
end_time: nil,
limit: nil,
cursor: nil)
new_api_call_builder
.request(new_request_builder(HttpMethodEnum::GET,
'/v2/cash-drawers/shifts',
'default')
.query_param(new_parameter(location_id, key: 'location_id'))
.query_param(new_parameter(sort_order, key: 'sort_order'))
.query_param(new_parameter(begin_time, key: 'begin_time'))
.query_param(new_parameter(end_time, key: 'end_time'))
.query_param(new_parameter(limit, key: 'limit'))
.query_param(new_parameter(cursor, key: 'cursor'))
.header_param(new_parameter('application/json', key: 'accept'))
.auth(Single.new('global')))
.response(new_response_handler
.deserializer(APIHelper.method(:json_deserialize))
.is_api_response(true)
.convertor(ApiResponse.method(:create)))
.execute
end
# Provides the summary details for a single cash drawer shift. See
# [ListCashDrawerShiftEvents]($e/CashDrawers/ListCashDrawerShiftEvents) for
# a list of cash drawer shift events.
# @param [String] location_id Required parameter: The ID of the location to
# retrieve cash drawer shifts from.
# @param [String] shift_id Required parameter: The shift ID.
# @return [RetrieveCashDrawerShiftResponse Hash] response from the API call
def retrieve_cash_drawer_shift(location_id:,
shift_id:)
new_api_call_builder
.request(new_request_builder(HttpMethodEnum::GET,
'/v2/cash-drawers/shifts/{shift_id}',
'default')
.query_param(new_parameter(location_id, key: 'location_id'))
.template_param(new_parameter(shift_id, key: 'shift_id')
.should_encode(true))
.header_param(new_parameter('application/json', key: 'accept'))
.auth(Single.new('global')))
.response(new_response_handler
.deserializer(APIHelper.method(:json_deserialize))
.is_api_response(true)
.convertor(ApiResponse.method(:create)))
.execute
end
# Provides a paginated list of events for a single cash drawer shift.
# @param [String] location_id Required parameter: The ID of the location to
# list cash drawer shifts for.
# @param [String] shift_id Required parameter: The shift ID.
# @param [Integer] limit Optional parameter: Number of resources to be
# returned in a page of results (200 by default, 1000 max).
# @param [String] cursor Optional parameter: Opaque cursor for fetching the
# next page of results.
# @return [ListCashDrawerShiftEventsResponse Hash] response from the API call
def list_cash_drawer_shift_events(location_id:,
shift_id:,
limit: nil,
cursor: nil)
new_api_call_builder
.request(new_request_builder(HttpMethodEnum::GET,
'/v2/cash-drawers/shifts/{shift_id}/events',
'default')
.query_param(new_parameter(location_id, key: 'location_id'))
.template_param(new_parameter(shift_id, key: 'shift_id')
.should_encode(true))
.query_param(new_parameter(limit, key: 'limit'))
.query_param(new_parameter(cursor, key: 'cursor'))
.header_param(new_parameter('application/json', key: 'accept'))
.auth(Single.new('global')))
.response(new_response_handler
.deserializer(APIHelper.method(:json_deserialize))
.is_api_response(true)
.convertor(ApiResponse.method(:create)))
.execute
end
end
end
|
module ActiveRecord
class Relation
include QueryMethods, FinderMethods, CalculationMethods
delegate :to_sql, :to => :relation
delegate :length, :collect, :map, :each, :all?, :to => :to_a
attr_reader :relation, :klass, :preload_associations, :eager_load_associations
attr_writer :readonly, :preload_associations, :eager_load_associations, :table
def initialize(klass, relation)
@klass, @relation = klass, relation
@preload_associations = []
@eager_load_associations = []
@loaded, @readonly = false
end
def merge(r)
raise ArgumentError, "Cannot merge a #{r.klass.name} relation with #{@klass.name} relation" if r.klass != @klass
joins(r.relation.joins(r.relation)).
group(r.send(:group_clauses).join(', ')).
order(r.send(:order_clauses).join(', ')).
where(r.send(:where_clause)).
limit(r.taken).
offset(r.skipped).
select(r.send(:select_clauses).join(', ')).
eager_load(r.eager_load_associations).
preload(r.preload_associations).
from(r.send(:sources).present? ? r.send(:from_clauses) : nil)
end
alias :& :merge
def respond_to?(method, include_private = false)
return true if @relation.respond_to?(method, include_private) || Array.method_defined?(method)
if match = DynamicFinderMatch.match(method)
return true if @klass.send(:all_attributes_exists?, match.attribute_names)
elsif match = DynamicScopeMatch.match(method)
return true if @klass.send(:all_attributes_exists?, match.attribute_names)
else
super
end
end
def to_a
return @records if loaded?
@records = if @eager_load_associations.any?
begin
@klass.send(:find_with_associations, {
:select => @relation.send(:select_clauses).join(', '),
:joins => @relation.joins(relation),
:group => @relation.send(:group_clauses).join(', '),
:order => @relation.send(:order_clauses).join(', '),
:conditions => where_clause,
:limit => @relation.taken,
:offset => @relation.skipped,
:from => (@relation.send(:from_clauses) if @relation.send(:sources).present?)
},
ActiveRecord::Associations::ClassMethods::JoinDependency.new(@klass, @eager_load_associations, nil))
rescue ThrowResult
[]
end
else
@klass.find_by_sql(@relation.to_sql)
end
@preload_associations.each {|associations| @klass.send(:preload_associations, @records, associations) }
@records.each { |record| record.readonly! } if @readonly
@loaded = true
@records
end
alias all to_a
def size
loaded? ? @records.length : count
end
def empty?
loaded? ? @records.empty? : count.zero?
end
def any?
if block_given?
to_a.any? { |*block_args| yield(*block_args) }
else
!empty?
end
end
def many?
if block_given?
to_a.many? { |*block_args| yield(*block_args) }
else
@relation.send(:taken).present? ? to_a.many? : size > 1
end
end
def destroy_all
to_a.each {|object| object.destroy}
reset
end
def delete_all
@relation.delete.tap { reset }
end
def delete(id_or_array)
where(@klass.primary_key => id_or_array).delete_all
end
def loaded?
@loaded
end
def reload
@loaded = false
reset
end
def reset
@first = @last = nil
@records = []
self
end
def spawn(relation = @relation)
relation = self.class.new(@klass, relation)
relation.readonly = @readonly
relation.preload_associations = @preload_associations
relation.eager_load_associations = @eager_load_associations
relation.table = table
relation
end
def table
@table ||= Arel::Table.new(@klass.table_name, Arel::Sql::Engine.new(@klass))
end
def primary_key
@primary_key ||= table[@klass.primary_key]
end
protected
def method_missing(method, *args, &block)
if @relation.respond_to?(method)
@relation.send(method, *args, &block)
elsif Array.method_defined?(method)
to_a.send(method, *args, &block)
elsif match = DynamicFinderMatch.match(method)
attributes = match.attribute_names
super unless @klass.send(:all_attributes_exists?, attributes)
if match.finder?
find_by_attributes(match, attributes, *args)
elsif match.instantiator?
find_or_instantiator_by_attributes(match, attributes, *args, &block)
end
else
super
end
end
def where_clause(join_string = " AND ")
@relation.send(:where_clauses).join(join_string)
end
end
end
|
json.pictures @pictures, partial: 'pictures/picture', as: :picture
json.meta do
json.total_pages @pictures.total_pages
end
|
require_relative '../test_helper'
class MockApplePiesControllerTest < ActionController::TestCase
PIES_COUNT = 3
def setup
@grandma = FactoryGirl.create(:grandma, pies_count: PIES_COUNT)
@controller.current_grandma = @grandma
end
test "GET index" do
get :index
assert_response :success
assert_not_nil assigns(:mock_apple_pies)
assert_equal PIES_COUNT, assigns(:mock_apple_pies).size
assert_template :index
end
test "GET index JSON" do
get :index, format: 'json'
assert_response :success
response_data = nil
assert_nothing_thrown { response_data = JSON.parse(@response.body) }
assert_kind_of Hash, response_data
assert_kind_of Array, response_data['mock_apple_pies']
assert_equal PIES_COUNT, response_data['mock_apple_pies'].size
response_data['mock_apple_pies'].each do |pie_data|
assert_equal @grandma.id, pie_data['grandma_id']
assert_not_nil pie_data['ingredients']
end
end
test "GET show" do
pie = @grandma.mock_apple_pies.first
get :show, id: pie.to_param
assert_response :success
assert_not_nil assigns(:mock_apple_pie)
assert_kind_of MockApplePie, assigns(:mock_apple_pie)
assert_template :show
end
test "GET show (not found)" do
get :show, id: '555'
assert_response :not_found
end
test "GET show JSON" do
pie = @grandma.mock_apple_pies.first
get :show, id: pie.to_param, format: 'json'
assert_response :success
response_data = nil
assert_nothing_thrown { response_data = JSON.parse(@response.body) }
assert_kind_of Hash, response_data
assert_kind_of Hash, response_data['mock_apple_pie']
assert_equal @grandma.id, response_data['mock_apple_pie']['grandma_id']
assert_not_nil response_data['mock_apple_pie']['ingredients']
end
test "GET new" do
get :new
assert_response :success
assert_not_nil assigns(:mock_apple_pie)
assert_kind_of MockApplePie, assigns(:mock_apple_pie)
assert_template :new
end
test "GET new JSON" do
get :new, format: 'json'
assert_response :success
response_data = nil
assert_nothing_thrown { response_data = JSON.parse(@response.body) }
assert_kind_of Hash, response_data
assert_kind_of Hash, response_data['mock_apple_pie']
assert response_data['mock_apple_pie'].has_key? 'grandma_id'
assert response_data['mock_apple_pie'].has_key? 'ingredients'
end
test "POST create" do
new_attrs = { mock_apple_pie: { ingredients: 'love', grandma_id: @grandma.id }}
post :create, new_attrs
pie = MockApplePie.all.last
assert_response :redirect
assert_redirected_to controller: 'mock_apple_pies', action: 'show', id: pie.to_param
end
test "POST create (validation error)" do
new_attrs = { mock_apple_pie: { ingredients: '', grandma_id: @grandma.id }}
post :create, new_attrs
assert_response :unprocessable_entity
end
test "POST create JSON" do
new_attrs = { mock_apple_pie: { ingredients: 'love', grandma_id: @grandma.id }}
post :create, new_attrs.merge( format: 'json' )
assert_response :created
response_data = nil
assert_nothing_thrown { response_data = JSON.parse(@response.body) }
assert_kind_of Hash, response_data
assert_kind_of Hash, response_data['mock_apple_pie']
assert_equal new_attrs[:mock_apple_pie][:grandma_id], response_data['mock_apple_pie']['grandma_id']
assert_equal new_attrs[:mock_apple_pie][:ingredients], response_data['mock_apple_pie']['ingredients']
end
test "POST create JSON (validation error)" do
new_attrs = { mock_apple_pie: { ingredients: '', grandma_id: @grandma.id }}
post :create, new_attrs.merge( format: 'json' )
assert_response :unprocessable_entity
response_data = nil
assert_nothing_thrown { response_data = JSON.parse(@response.body) }
assert_kind_of Hash, response_data
assert_kind_of Hash, response_data['mock_apple_pie']
assert_equal new_attrs[:mock_apple_pie][:grandma_id], response_data['mock_apple_pie']['grandma_id']
assert_equal new_attrs[:mock_apple_pie][:ingredients], response_data['mock_apple_pie']['ingredients']
assert_equal ["can't be blank"], response_data['mock_apple_pie']['errors']['ingredients']
end
test "GET edit" do
pie = @grandma.mock_apple_pies.first
get :edit, id: pie.to_param
assert_response :success
assert_not_nil assigns(:mock_apple_pie)
assert_kind_of MockApplePie, assigns(:mock_apple_pie)
assert_template :edit
end
test "GET edit (not found)" do
get :edit, id: '555'
assert_response :not_found
end
test "GET edit JSON" do
pie = @grandma.mock_apple_pies.first
get :edit, id: pie.to_param, format: 'json'
assert_response :success
response_data = nil
assert_nothing_thrown { response_data = JSON.parse(@response.body) }
assert_kind_of Hash, response_data
assert_kind_of Hash, response_data['mock_apple_pie']
assert_equal @grandma.id, response_data['mock_apple_pie']['grandma_id']
assert_equal pie.ingredients, response_data['mock_apple_pie']['ingredients']
end
test "PUT update" do
pie = @grandma.mock_apple_pies.first
update_attrs = { mock_apple_pie: { ingredients: 'lots of love', grandma_id: pie.grandma.id }}
put :update, update_attrs.merge( id: pie.to_param )
assert_response :redirect
assert_redirected_to controller: 'mock_apple_pies', action: 'show', id: pie.to_param
end
test "PUT update (not found)" do
pie = @grandma.mock_apple_pies.first
update_attrs = { mock_apple_pie: { ingredients: 'lots of love', grandma_id: pie.grandma.id }}
put :update, update_attrs.merge( id: '555' )
assert_response :not_found
end
test "PUT update (validation error)" do
pie = @grandma.mock_apple_pies.first
update_attrs = { mock_apple_pie: { ingredients: '', grandma_id: pie.grandma.id }}
put :update, update_attrs.merge( id: pie.to_param )
assert_response :unprocessable_entity
end
test "PUT update JSON" do
pie = @grandma.mock_apple_pies.first
update_attrs = { mock_apple_pie: { ingredients: 'lots of love', grandma_id: pie.grandma.id }}
put :update, update_attrs.merge( id: pie.to_param, format: 'json' )
assert_response :success
response_data = nil
assert_nothing_thrown { response_data = JSON.parse(@response.body) }
assert_kind_of Hash, response_data
assert_kind_of Hash, response_data['mock_apple_pie']
assert_equal update_attrs[:mock_apple_pie][:grandma_id], response_data['mock_apple_pie']['grandma_id']
assert_equal update_attrs[:mock_apple_pie][:ingredients], response_data['mock_apple_pie']['ingredients']
end
test "PUT update JSON (validation error)" do
pie = @grandma.mock_apple_pies.first
update_attrs = { mock_apple_pie: { ingredients: '', grandma_id: pie.grandma.id }}
put :update, update_attrs.merge( id: pie.to_param, format: 'json' )
assert_response :unprocessable_entity
response_data = nil
assert_nothing_thrown { response_data = JSON.parse(@response.body) }
assert_kind_of Hash, response_data
assert_kind_of Hash, response_data['mock_apple_pie']
assert_equal update_attrs[:mock_apple_pie][:grandma_id], response_data['mock_apple_pie']['grandma_id']
assert_equal update_attrs[:mock_apple_pie][:ingredients], response_data['mock_apple_pie']['ingredients']
assert_equal ["can't be blank"], response_data['mock_apple_pie']['errors']['ingredients']
end
test "DELETE destroy" do
pie = @grandma.mock_apple_pies.first
delete :destroy, id: pie.to_param
assert_response :redirect
assert_redirected_to controller: 'mock_apple_pies', action: 'index'
end
test "DELETE destroy (not_found)" do
delete :destroy, id: '555'
assert_response :not_found
end
test "DELETE destroy JSON" do
pie = @grandma.mock_apple_pies.first
delete :destroy, id: pie.to_param, format: 'json'
assert_response :no_content
assert_empty @response.body
end
test "DELETE destroy JSON (validation error)" do
pie = @grandma.mock_apple_pies.first
pie.update_attribute(:ingredients, 'sugar, real apples, flour, butter, and egg.')
delete :destroy, id: pie.to_param, format: 'json'
assert_response :unprocessable_entity
response_data = nil
assert_nothing_thrown { response_data = JSON.parse(@response.body) }
assert_equal ["can't be deleted because it contains real apple"], response_data['mock_apple_pie']['errors']['base']
end
end
|
require 'spec_helper'
describe "series_sets/show.html.erb" do
before(:each) do
@series_set = assign(:series_set, Factory(:series_set))
end
it "renders attributes in <p>" do
render
rendered.should have_content("Setname".to_s)
end
end
|
module GalgoParser
class Consumer
def initialize(config)
@config = config
end
def invoke_jar
command = "java -jar #{@config["jar_path"]} #{@config["output_path"]}"
puts ".. JAR command: #{command}"
exe_return = system(command)
raise StandardError.new(exe_return) unless exe_return
end
def parse_xml
data = File.read(@config["output_path"])
keys = {
date: ".//ns3:NAVDtTm/ns3:DtTm",
value: ".//ns3:NAV/ns3:Unit",
fund_sti: ".//ns3:FinInstrmDtls/ns3:Id/ns3:OthrPrtryId/ns3:Id",
aum: ".//ns3:TtlNAV"
}
xml = Nokogiri::XML(data)
values = xml.xpath("//ns3:PricValtnDtls")
shares = []
values.each do |line|
shares << {sti: line.xpath(keys[:fund_sti]).text,
date: Date.parse(line.xpath(keys[:date]).text),
value: line.xpath(keys[:value]).text.to_f,
aum: line.xpath(keys[:aum]).text.to_f}
end
shares
end
end
end
|
class CreateLeafMeasures < ActiveRecord::Migration[5.2]
def change
create_table :leaf_measures do |t|
t.references :leaf_measure_type, foreign_key: true
t.references :leaf_failure, foreign_key: true
t.timestamps
end
end
end
|
module PropertyPickerHelper
def property_types
return ['Apartment', 'House', 'Condo', 'Townhome']
end
def furnished_available
return ['Furnished', 'Unfurnished', 'Select Units']
end
def pets_allowed
return ['Allowed', 'Small Animals Only', 'Not Permitted']
end
def smoking_allowed
return ['No', 'Yes']
end
def lease_term
return ['0.5+ Years', '1+ Year']
end
def utilities_included
return ['Included', 'Not Included']
end
def landlords_agents(landlord_id)
array = []
Landlord.find_by(id: landlord_id).agents.each do |i|
array<< "#{i.first_name.capitalize} #{i.last_name.capitalize}"
end
return array
end
def display_landlord_agents_first
return "#{Property.find(params[:property_id]).agents.first.try(:first_name).try(:capitalize)} #{Property.find(params[:property_id]).agents.first.try(:last_name).try(:capitalize)}"
end
def display_landlord_agents_second
return "#{Property.find(params[:property_id]).agents.second.try(:first_name).try(:capitalize)} #{Property.find(params[:property_id]).agents.second.try(:last_name).try(:capitalize)}"
end
def display_landlord_agents_third
return "#{Property.find(params[:property_id]).agents.third.try(:first_name).try(:capitalize)} #{Property.find(params[:property_id]).agents.third.try(:last_name).try(:capitalize)}"
end
def display_landlord_agents_fourth
return "#{Property.find(params[:property_id]).agents.fourth.try(:first_name).try(:capitalize)} #{Property.find(params[:property_id]).agents.fourth.try(:last_name).try(:capitalize)}"
end
def bed_builder(property)
beds_array = [property.bachelor, property.one_bedroom, property.two_bedroom, property.three_bedroom, property.four_bedroom]
return beds_array.compact.join(", ")
end
end
|
class Valvat
class Lookup
class Response
def initialize(raw)
@raw = raw
end
def [](key)
to_hash[key]
end
def to_hash
@hash ||= self.class.cleanup(@raw.to_hash)
end
private
def self.cleanup(hash)
(hash[:check_vat_approx_response] || hash[:check_vat_response] || {}).inject({}) do |hash, (key, value)|
hash[cleanup_key(key)] = cleanup_value(value) unless key == :"@xmlns"
hash
end
end
TRADER_PREFIX = /\Atrader_/
def self.cleanup_key(key)
key.to_s.sub(TRADER_PREFIX, "").to_sym
end
def self.cleanup_value(value)
value == "---" ? nil : value
end
end
end
end |
#add role attribute to capybara selectors
Capybara.add_selector(:role) do
xpath { |role| XPath.descendant[XPath.attr(:role) == role.to_s] }
end
|
require 'spec_helper'
describe Puppet::Type.type(:selmodule) do
context 'when validating attributes' do
[:name, :selmoduledir, :selmodulepath].each do |param|
it "has a #{param} parameter" do
expect(Puppet::Type.type(:selmodule).attrtype(param)).to eq(:param)
end
end
[:ensure, :syncversion].each do |param|
it "has a #{param} property" do
expect(Puppet::Type.type(:selmodule).attrtype(param)).to eq(:property)
end
end
end
context 'when checking policy modules' do
let(:provider_class) { Puppet::Type::Selmodule.provider(Puppet::Type::Selmodule.providers[0]) }
let(:selmodule) do
Puppet::Type::Selmodule.new(
name: 'foo',
selmoduledir: '/some/path',
selmodulepath: '/some/path/foo.pp',
syncversion: true,
)
end
before :each do
allow(Puppet::Type::Selmodule).to receive(:defaultprovider).and_return provider_class
end
it 'is able to access :name' do
expect(selmodule[:name]).to eq('foo')
end
it 'is able to access :selmoduledir' do
expect(selmodule[:selmoduledir]).to eq('/some/path')
end
it 'is able to access :selmodulepath' do
expect(selmodule[:selmodulepath]).to eq('/some/path/foo.pp')
end
it 'is able to access :syncversion' do
expect(selmodule[:syncversion]).to eq(:true)
end
it 'sets the syncversion value to false' do
selmodule[:syncversion] = :false
expect(selmodule[:syncversion]).to eq(:false)
end
end
end
|
# frozen_string_literal: true
# The UnderlyingInstrumentParser is responsible for the <Undly> mapping. This tag is one of many tags inside
# a FIXML message. To see a complete FIXML message there are many examples inside of spec/datafiles.
#
# Relevant FIXML Slice:
#
# <Undly Exch="NYMEX" MMY="201501" SecTyp="FUT" Src="H" ID="NG"/>
#
module CmeFixListener
# <Undly> Mappings from abbreviations to full names (with types)
class UnderlyingInstrumentParser
extend ParsingMethods
MAPPINGS = [
["underlyingProductCode", "ID"],
["underlyingProductCodeSource", "Src"],
["underlyingSecurityType", "SecTyp"],
["underlyingMaturity", "MMY"],
["underlyingProductExchange", "Exch"]
].freeze
end
end
|
class Api::V1::MyPostsController < Api::ApiController
doorkeeper_for :all
def index
page = (params[:page] || 1).to_i
expires_in 5.seconds
if page > 1 || stale?(last_modified: current_user.posts.maximum(:updated_at))
@posts = current_user.posts.alive.order("updated_at DESC").page(page)
end
end
def show
@post = current_user.posts.find_by_id(params[:id])
if @post.nil?
render_error(
:resource_not_found,
"Not Found",
"Requested post does not exist or you don't have permission to see it."
)
return
end
expires_in 5.seconds
fresh_when @post
end
def create
@post = current_user.posts.create(params[:post])
unless @post.valid?
render_error(:invalid_parameter, "Parameter Error", @post.errors.messages)
return
end
render :action => :show
end
def update
@post = current_user.posts.find_by_id(params[:id])
@post.update_attributes(params[:post])
unless @post.valid?
render_error(:invalid_parameter, "Parameter Error", @post.errors.messages)
return
end
render :action => :show
end
def destroy
@post = current_user.posts.find_by_id(params[:id])
@post.update_attribute(:deleted_at, Time.now)
render :action => :show
end
end
|
source 'https://rubygems.org'
source 'https://rails-assets.org'
ruby '2.3.4'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '5.1.1'
# Use postgresql as the database for Active Record
gem 'pg', '~>0.21.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '~> 3.2.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2.2'
gem 'uglifier', '~> 3.2.0'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0.6'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
# Use jquery as the JavaScript library
gem 'jquery-rails', '~> 4.3.1'
# # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
# gem 'jbuilder', '~> 2.0'
# # bundle exec rake doc:rails generates the API under doc/api.
# gem 'sdoc', '~> 0.4.0', group: :doc
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'
# Use Unicorn as the app server
# gem 'unicorn'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
gem 'haml', '~> 5.0.1'
gem 'sass', '~> 3.4.24'
# Markdown parser
gem 'redcarpet', '~> 3.4.0'
gem 'rails_12factor', '~> 0.0.3'
gem 'nokogiri'
gem 'rest-client', '~> 2.0.2'
gem 'reverse_markdown'
# gem 'rails-assets-bootstrap-material-design'
# gem 'rails-assets-bootstrap', '~> 3.3.1'
gem 'bootstrap-sass', '3.3.7'
gem 'bootstrap-material-design'
gem 'bootstrap-typeahead-rails'
gem 'font-awesome-sass'
gem 'meta-tags'
gem 'intercom-rails'
gem 'swiftype'
gem 'delayed_job', '~> 4.1.3'
gem 'delayed_job_active_record', '~> 4.1.2'
group :development, :test do
gem 'pry'
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug'
# Access an IRB console on exception pages or by using <%= console %> in views
gem 'web-console', '~> 3.5.1'
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
gem "rspec-rails", '~> 3.6.0'
gem 'spring-commands-rspec'
gem 'capybara', '~> 2.6.2'
gem 'launchy', '~> 2.1' # save_and_open_page
end
# Manage rails environment variable
gem 'figaro'
# Support Elasticsearch
gem 'elasticsearch-model'
gem 'elasticsearch-rails'
gem 'bonsai-elasticsearch-rails'
# Intelligent search
gem 'searchkick'
# Pagenate
gem "will_paginate"
gem 'kaminari'
# File upload
gem 'carrierwave'
# particles.js for background effect
# gem 'high_voltage', '~> 3.0.0'
source 'https://rails-assets.org' do
gem 'rails-assets-particles.js'
end
|
require 'date'
require 'yaml'
require 'octokit'
require 'fileutils'
require 'choice'
require 'highline/import'
require 'git'
Octokit.configure do |c|
c.login = ENV['GITHUB_USER']
c.password = ENV['GITHUB_PASS']
end
module Elyan
VERSION=0.1
def open_config_file(file)
YAML.load(IO.read(file))
end
def pr_list_for_repo(repo)
prs=Octokit.pull_requests(repo, :state => 'open')
prs.each { |pr| pr[:comments]=get_pr_comments(repo, pr[:number]) }
prs
end
def get_pr_comments(repo, pr_number)
o=Octokit::Client.new
o.issue_comments(repo, pr_number)
end
def contains_plus_one?(comment_body)
comment_body =~ /\+1/
end
def non_author_comments(pr)
pr[:comments].collect { |c| c unless pr[:user][:login] == c[:user][:login] }.compact
end
def reviews(pr)
non_author_comments(pr).collect { |comment| comment if contains_plus_one?(comment[:body]) }.compact
end
def collect_merge_candidates(repo)
mylogger = Logger['mylog']
mylogger.debug "REPO: #{repo} Getting PR List"
pr_list = pr_list_for_repo(repo)
mylogger.debug "REPO: #{repo} #{pr_list.length} Open Pull Requests"
merge_candidates=[]
pr_list.each do |pr|
pr[:non_author_comments] = non_author_comments(pr)
pr[:reviews] = reviews(pr)
reviewers = pr[:reviews].collect { |r| r[:user][:login] }
mylogger.debug "PR ##{pr[:number].to_s} total comments: [#{pr[:comments].length}]"
mylogger.debug "PR ##{pr[:number]} non_author_comments: [#{pr[:non_author_comments].length}]"
mylogger.debug "PR ##{pr[:number]} code reviews: [#{pr[:reviews].length}] #{reviewers.join(",")}"
if pr[:reviews].length >= Config[:minimum_reviewers]
mylogger.debug "PR ##{pr[:number]} MERGE Candidate"
merge_candidates.push(pr)
else
mylogger.debug "PR ##{pr[:number]} SKIP"
end
end
merge_candidates
end
class GitWorker
TMP_DIR='/var/tmp/build'
def self.run_build_step(name, command)
# todo refactor for build status hash
mylogger = Logger['mylog']
output = `#{command}`
# set build status
unless $? == 0
mylogger.debug "[ #{name} ] [ERROR] \"#{command}\" Failed #{output}"
return false
else
mylogger.debug "[ #{name} ] [OK] \"#{command}\""
return true
end
end
def self.get_build_status(pr)
mylogger = Logger['mylog']
repo =pr.base.repo.full_name
build_status = {}
build_status[:pr]={:title => pr[:title], :id => pr[:id]}
build_status[:started_at]=DateTime.now
mylogger.debug "PR ##{pr[:number]} BEGIN"
build_dir = File.join(TMP_DIR, "#{repo.gsub(/\//, '_')}_#{pr[:number].to_s}")
build_status[:build_dir]=build_dir
mylogger.debug "Cleaning build dir #{build_dir}"
FileUtils.rm_rf(build_dir)
mylogger.debug "Cloning (\"git@github.com:#{repo}\", build_dir)"
g = Git.clone("git@github.com:#{repo}", build_dir)
begin
g.checkout('master')
g.branch("integration_branch_#{pr.head.ref}").checkout
mylogger.debug "Trying merge"
g.merge("#{pr.head.sha}")
rescue StandardError => e
mylogger.error "Merge Failed, Stopping"
mylogger.debug "PR ##{pr[:number]} END"
build_status[:result]=:error
build_status[:message]="Merge test failed"
build_status[:output]=e.inspect
return build_status
end
Dir.chdir(build_dir)
unless run_build_step("BUILD", "make build")
log_message = "make build failed"
mylogger.debug "PR ##{pr[:number]} BEGIN"
mylogger.debug log_message
build_status[:result]=:error
build_status[:message]=log_message
return build_status
end
unless run_build_step("TEST", "make test")
log_message = "make test failed"
mylogger.debug "PR ##{pr[:number]} BEGIN"
mylogger.debug log_message
build_status[:result]=:error
build_status[:message]=log_message
return build_status
end
build_status[:result]=:ok
mylogger.debug "[MERGE,BUILD,TEST] Successful."
unless Choice[:non_interactive] == true
unless ask("[INTERACTIVE MODE] : MERGING Pull Request #{repo} PR ##{pr[:number]} \"#{pr[:title]}\" OK? (y/n)") == "y"
say "OK, Safely exiting without merging"
return build_status
end
end
mylogger.debug "MERGING Pull Request (#{repo}, #{pr[:number]}, commit_message = 'Robot Merge OK'"
begin
Octokit.merge_pull_request(repo, pr[:number], commit_message = 'Elyan GitRobot Merge', options = {})
mylogger.debug "PR ##{pr[:number]} Merge OK"
rescue StandardError => e
log_message = "PR ##{pr[:number]} Merge FAILED #{e.inspect}"
mylogger.debug log_message
build_status[:message] = log_message
build_status[:output]=e.inspect
return build_status
end
mylogger.debug "PR ##{pr[:number]} END"
build_status[:ended_at]=DateTime.now
build_status
end
def self.start
mylogger = Logger['mylog']
ratelimit = Octokit.ratelimit
ratelimit_remaining = Octokit.ratelimit.remaining
mylogger.debug "STATS: Rate Limit Remaining: #{ratelimit_remaining} / #{ratelimit}"
mylogger.debug "CONFIG: Loading"
mylogger.debug "CONFIG: #{Config.to_json}"
mylogger.debug "CONFIG: #{Config[:repos].length} repos loaded"
mylogger.debug "Setting tmp_dir at #{TMP_DIR}"
FileUtils.mkdir_p(TMP_DIR)
data = {}
mylogger.debug "Collecting Merge Candidates"
Config[:repos].each do |repo|
data[repo]=[]
merge_candidate_pr_list = collect_merge_candidates(repo)
merge_candidate_pr_list.each do |pr|
data[repo].push(get_build_status(pr))
end
end
print "build report\n"
print data.to_yaml
print "\n"
end
end
end
|
Rails.application.routes.draw do
devise_for :users
root to: "rooms#index"
resources :users, only: [:edit, :update,]#ユーザー編集に必要なルーティング
resources :rooms, only: [:new, :create, :destroy] do #新規チャットルームの作成で動くアクション
resources :messages, only: [:index, :create]#メッセージ送信機能に必要なルーティングを記述
#ネストをすることにより、roomsが親で、messagesが子という親子関係
#チャットルームに属しているメッセージという意味
#メッセージに結びつくルームのidの情報を含んだパスを、受け取れるようにな
end
end
|
class EntrySerializer
include Super::Serializer
root :data
attribute :id
attribute :timestamp, with: ->(timestamp) { timestamp&.iso8601 }
attribute :message, with: MessageSerializer
postprocess do |result, options|
result.tap do |r|
r[:meta] = { page: options[:page] } if options && options[:page]
end
end
end
|
require_relative 'docking_station'
require_relative 'garage'
class Van
attr_accessor :load
attr_reader :garage
def initialize
@load = []
@garage = Garage.new
end
def get_load(bikes)
@load = bikes
end
def load_garage
@garage.store(@load)
@load = []
end
end |
Rails.application.routes.draw do
root to: 'short_urls#new'
resources :short_urls, only: [:create, :show, :index]
get '/:short_url', to: 'short_urls#redirect_original', as: :redirect_with_short
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.